text:
/*
package com.dreampany.network.manager;

import android.content.Context;

import androidx.annotation.Nullable;

import com.dreampany.network.api.BluetoothApi;
import com.dreampany.network.api.InternetApi;
import com.dreampany.network.api.MobileApi;
import com.dreampany.network.api.WifiApApi;
import com.dreampany.network.api.WifiApi;
import com.dreampany.network.data.model.Network;
import com.dreampany.network.misc.RxMapper;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.inject.Inject;
import javax.inject.Singleton;

*/
/**
 * Created by Hawladar Roman on 8/18/2018.
 * Dreampany Ltd
 * dreampanymail@gmail.com
 *//*

@Singleton
public final class NetworkManager {

    public interface Callback {
        void onResult(Network... networks);
    }

    private final Context context;
    private final RxMapper rx;
*/
/*    private final WifiApi wifi;
    private final WifiApApi ap;
    private final MobileApi mobile;
    private final BluetoothApi bt;
    private final InternetApi internetApi;*//*

    private volatile boolean internet;
    private final Set<Callback> callbacks;
    private final Map<Callback, Boolean> checkInternets;

    private boolean resultFired;

    @Inject
    NetworkManager(Context context,
                   RxMapper rx,
                   WifiApi wifi,
                   WifiApApi ap,
                   MobileApi mobile,
                   BluetoothApi bt,
                   InternetApi internetApi) {
        this.context = context.getApplicationContext();
        this.rx = rx;
        this.wifi = wifi;
        this.ap = ap;
        this.mobile = mobile;
        this.bt = bt;
        this.internetApi = internetApi;
        callbacks = Sets.newConcurrentHashSet();
        checkInternets = Maps.newConcurrentMap();

        resultFired = false;
    }

    void onResult(boolean internet) {
        resultFired = true;
        this.internet = internet;
        postActiveNetworks();
    }

    public void observe(Callback callback, boolean checkInternet) {
        callbacks.add(callback);
        checkInternets.put(callback, checkInternet);
        startInternetIfPossible();
    }

    public void deObserve(Callback callback, boolean stopInternetCheck) {
        callbacks.remove(callback);
        if (stopInternetCheck) {
            checkInternets.remove(callback);
        }
        stopInternetIfPossible();
    }

    public boolean isObserving() {
        return resultFired && !callbacks.isEmpty();
    }

    public List<Network> getNetworks() {
        List<Network> networks = new ArrayList<>();
        networks.add(wifi.getNetwork(internet));
        networks.add(ap.getNetwork(internet));
        networks.add(bt.getNetwork(internet));
        return networks;
    }

    public List<Network> getActiveNetworks() {
        List<Network> networks = new ArrayList<>();
        if (wifi.isEnabled()) {
            networks.add(wifi.getNetwork(internet));
        }
        if (ap.isEnabled()) {
            networks.add(ap.getNetwork(internet));
        }
        if (mobile.isEnabled()) {
            networks.add(mobile.getNetwork(internet));
        }
*/
/*        if (bt.isEnabled()) {
            networks.add(bt.getNetwork(internet));
        }*//*

        return networks;
    }

    public boolean hasInternet() {
        return internet;
    }

    private void startInternetIfPossible() {
        for (Map.Entry<Callback, Boolean> entry : checkInternets.entrySet()) {
            if (entry.getValue()) {
                internetApi.start(this::onResult);
                break;
            }
        }
    }

    private void stopInternetIfPossible() {
        boolean checkInternet = false;
        for (Map.Entry<Callback, Boolean> entry : checkInternets.entrySet()) {
            if (entry.getValue()) {
                checkInternet = true;
                break;
            }
        }
        if (!checkInternet) {
            internetApi.stop(this::onResult);
        }
    }

    private void postActiveNetworks() {
        List<Network> result = getActiveNetworks();
        Network[] networks = result.toArray(new Network[0]);
        for (Callback callback : callbacks) {
            callback.onResult(networks);
        }
    }
}
*/


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */
/*
 * This code was generated by https://github.com/googleapis/google-api-java-client-services/
 * Modify at your own risk.
 */

package com.google.api.services.chromepolicy.v1.model;

/**
 * Request message for modifying multiple policy values for a specific target.
 *
 *
 This is the Java data model class that specifies how to parse/serialize into the JSON that is
 * transmitted over HTTP when working with the Chrome Policy API. For a detailed explanation see:
 * https://developers.google.com/api-client-library/java/google-http-java-client/json
 *

 *
 * @author Google, Inc.
 */
@SuppressWarnings("javadoc")
public final class GoogleChromePolicyVersionsV1BatchModifyOrgUnitPoliciesRequest extends com.google.api.client.json.GenericJson {

  /**
   * List of policies to modify as defined by the `requests`. All requests in the list must follow
   * these restrictions: 1. All schemas in the list must have the same root namespace. 2. All
   * `policyTargetKey.targetResource` values must point to an org unit resource. 3. All
   * `policyTargetKey` values must have the same key names in the ` additionalTargetKeys`. This also
   * means if one of the targets has an empty `additionalTargetKeys` map, all of the targets must
   * have an empty `additionalTargetKeys` map. 4. No two modification requests can reference the
   * same `policySchema` + ` policyTargetKey` pair.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.util.List<GoogleChromePolicyVersionsV1ModifyOrgUnitPolicyRequest> requests;

  /**
   * List of policies to modify as defined by the `requests`. All requests in the list must follow
   * these restrictions: 1. All schemas in the list must have the same root namespace. 2. All
   * `policyTargetKey.targetResource` values must point to an org unit resource. 3. All
   * `policyTargetKey` values must have the same key names in the ` additionalTargetKeys`. This also
   * means if one of the targets has an empty `additionalTargetKeys` map, all of the targets must
   * have an empty `additionalTargetKeys` map. 4. No two modification requests can reference the
   * same `policySchema` + ` policyTargetKey` pair.
   * @return value or {@code null} for none
   */
  public java.util.List<GoogleChromePolicyVersionsV1ModifyOrgUnitPolicyRequest> getRequests() {
    return requests;
  }

  /**
   * List of policies to modify as defined by the `requests`. All requests in the list must follow
   * these restrictions: 1. All schemas in the list must have the same root namespace. 2. All
   * `policyTargetKey.targetResource` values must point to an org unit resource. 3. All
   * `policyTargetKey` values must have the same key names in the ` additionalTargetKeys`. This also
   * means if one of the targets has an empty `additionalTargetKeys` map, all of the targets must
   * have an empty `additionalTargetKeys` map. 4. No two modification requests can reference the
   * same `policySchema` + ` policyTargetKey` pair.
   * @param requests requests or {@code null} for none
   */
  public GoogleChromePolicyVersionsV1BatchModifyOrgUnitPoliciesRequest setRequests(java.util.List<GoogleChromePolicyVersionsV1ModifyOrgUnitPolicyRequest> requests) {
    this.requests = requests;
    return this;
  }

  @Override
  public GoogleChromePolicyVersionsV1BatchModifyOrgUnitPoliciesRequest set(String fieldName, Object value) {
    return (GoogleChromePolicyVersionsV1BatchModifyOrgUnitPoliciesRequest) super.set(fieldName, value);
  }

  @Override
  public GoogleChromePolicyVersionsV1BatchModifyOrgUnitPoliciesRequest clone() {
    return (GoogleChromePolicyVersionsV1BatchModifyOrgUnitPoliciesRequest) super.clone();
  }

}

redpajama_set_name: RedPajamaGithub


text:
FROM atoto/docker-nginx-php-stack

COPY composer.json composer.lock /var/www/html/
COPY app/AppCache.php app/AppKernel.php /var/www/html/app/

RUN composer install --no-dev --no-scripts --optimize-autoloader --ignore-platform-reqs

ADD . /var/www/html

USER root

RUN rm -fr var/* && \
	mkdir -p var var/logs var/temp var/cache && \
	chown -R www-data:www-data /var/www/* && \
	chmod -R 777 var/*

USER www-data


text:
<link rel="import" href="../../bower_components/polymer/polymer.html">

<link rel="import" href="../../bower_components/paper-styles/typography.html">
<link rel="import" href="../../bower_components/iron-pages/iron-pages.html">

<link rel="import" href="../../bower_components/app-route/app-location.html">
<link rel="import" href="../../bower_components/app-route/app-route.html">

<link rel="import" href="../../bower_components/app-layout/app-header/app-header.html">
<link rel="import" href="../../bower_components/app-layout/app-toolbar/app-toolbar.html">
<link rel="import" href="../../bower_components/app-layout/app-layout.html">
<link rel="import" href="../../bower_components/app-layout/app-scroll-effects/effects/waterfall.html">

<link rel="import" href="../../bower_components/iron-flex-layout/iron-flex-layout-classes.html">

<link rel="import" href="../../bower_components/paper-input/paper-input.html">

<link rel="import" href="../product-catalogue-view/product-catalogue-view.html">
<link rel="import" href="../product-shopping-cart/product-shopping-cart.html">

<link rel="import" href="../../styles/app-theme.html" />
<dom-module id="product-catalogue-app">
  <template>

    <app-location route="{{route}}" use-hash-as-path></app-location>

    <app-route route="{{route}}"
               pattern="/catalogue"
               active="{{catalogueActive}}"></app-route>

    <app-route route="{{route}}"
               pattern="/catalogue"
               active="{{shoppingCartActive}}"></app-route>

    <app-header-layout>
      <app-header effects="waterfall" condenses reveals>
        <app-toolbar>
          <paper-icon-button icon="menu"></paper-icon-button>

          <paper-icon-button icon="search"></paper-icon-button>
        </app-toolbar>
      <app-toolbar></app-toolbar>
      <app-toolbar>

Product Catalogue

      </app-toolbar>
    </app-header>

      <product-catalogue-view name="catalogue"  on-add-product="addProductToBasket" on-remove-product="removeProductFromBasket" active="{{catalogueActive}}"></product-catalogue-view>

      <product-shopping-cart name="shoppingCart" products="{{itemsInBasket}}" on-post-tv-package="postTVPackage" active="{{catalogueActive}}"></product-shopping-cart>

    <paper-input label="Testing ClientID:" placeholder="{{clientID}}" value="{{clientID}}" type="number"></paper-input>

  </app-header-layout>

  <iron-ajax
     id="postTVPackageIronAjax"
     url$="[[_postTVPackageURL()]]"
     handle-as="json"
     method="POST">
  </iron-ajax>

  </template>

</dom-module>


text:
<?php

namespace Spatie\MediaLibrary\Test\HasMediaTrait;

use Spatie\MediaLibrary\Test\TestCase;

class GetMediaTest extends TestCase
{
    /**
     * @test
     */
    public function it_can_handle_an_empty_collection()
    {
        $emptyCollection = $this->testModel->getMedia('images');
        $this->assertInstanceOf(\Illuminate\Support\Collection::class, $emptyCollection);
        $this->assertCount(0, $emptyCollection);
    }

    /**
     * @test
     */
    public function it_can_get_the_default_collection()
    {
        $this->testModel->addMedia($this->getTestFilesDirectory('test.jpg'));

        $this->assertCount(1, $this->testModel->getMedia());
    }

    /**
     * @test
     */
    public function it_returns_a_media_collection_as_a_laravel_collection()
    {
        $this->testModel->addMedia($this->getTestFilesDirectory('test.jpg'));

        $this->assertInstanceOf(\Illuminate\Support\Collection::class, $this->testModel->getMedia());
    }

    /**
     * @test
     */
    public function it_returns_collections_filled_with_media_objects()
    {
        $this->testModel->addMedia($this->getTestFilesDirectory('test.jpg'));

        $this->assertInstanceOf(\Spatie\MediaLibrary\Media::class, $this->testModel->getMedia()->first());
    }

    /**
     * @test
     */
    public function it_can_get_multiple_media_from_the_default_collection()
    {
        $this->testModel->addMedia($this->getTestFilesDirectory('test.jpg'), 'default', false);
        $this->testModel->addMedia($this->getTestFilesDirectory('test.jpg'), 'default', false);

        $this->assertCount(2, $this->testModel->getMedia());
    }

    /**
     * @test
     */
    public function it_can_get_files_from_a_named_collection()
    {
        $this->testModel->addMedia($this->getTestFilesDirectory('test.jpg'), 'default', false);
        $this->testModel->addMedia($this->getTestFilesDirectory('test.jpg'), 'images', false);

        $this->assertCount(1, $this->testModel->getMedia('images'));
        $this->assertEquals('images', $this->testModel->getMedia('images')[0]->collection_name);
    }

    /**
     * @test
     */
    public function it_can_get_files_from_a_collection_using_a_filter()
    {
        $this->testModel->addMedia($this->getTestFilesDirectory('test.jpg'), 'default', false, false);
        $this->testModel->addMedia($this->getTestFilesDirectory('test.jpg'), 'images', false, true);
        $this->testModel->addMedia($this->getTestFilesDirectory('test.jpg'), 'images', false, true);

        $this->assertCount(2, $this->testModel->getMedia('images', ['temp' => 1]));
    }

    /**
     * @test
     */
    public function it_can_get_the_first_media_from_a_collection()
    {
        $media = $this->testModel->addMedia($this->getTestFilesDirectory('test.jpg'), 'images', false);
        $media->name = 'first';
        $media->save();

        $media = $this->testModel->addMedia($this->getTestFilesDirectory('test.jpg'), 'images', false, true);
        $media->name = 'second';
        $media->save();

        $this->assertEquals('first', $this->testModel->getFirstMedia('images')->name);
    }

    /**
     * @test
     */
    public function it_can_get_the_first_media_from_a_collection_using_a_filter()
    {
        $media = $this->testModel->addMedia($this->getTestFilesDirectory('test.jpg'), 'images', false);
        $media->name = 'first';
        $media->save();

        $media = $this->testModel->addMedia($this->getTestFilesDirectory('test.jpg'), 'images', false, true);
        $media->name = 'second';
        $media->save();

        $this->assertEquals('second', $this->testModel->getFirstMedia('images', ['temp' => 1])->name);
    }

    public function it_returns_false_when_getting_first_media_for_an_empty_collection()
    {
        $this->assertFalse($this->testModel->getFirstMedia());
    }
}


text:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using System.Xml.Linq;
using Excel = Microsoft.Office.Interop.Excel;

namespace ExcelQueryServiceAddIn
{
    public partial class DataElementCreationForm : Form
    {
        private static XNamespace rs = "http://cagrid.org/schema/result-set";
        private Excel.Worksheet cdeList = null;
        private Excel.Application application = Globals.ThisAddIn.Application;
        private static readonly string dummyPass = "dummy_password";

        public DataElementCreationForm()
        {
            InitializeComponent();
            dataElementCreationControl.parent = this;
            ExcelSubmissionCompleteControl scControl = new ExcelSubmissionCompleteControl();
            scControl.OnUse += new EventHandler(scControl_OnUse);
            dataElementCreationControl.scControl = scControl;
            //dataElementCreationControl.OnUseResult += new EventHandler(dataElementCreationControl_OnUseResult);
        }

        void scControl_OnUse(object sender, EventArgs e)
        {
            if (dataElementCreationControl.LastResult == null)
            {
                MessageBox.Show("Error inserting data element");
                return;
            }
            XElement selectedNode = XElement.Parse(dataElementCreationControl.LastResult);
            handleCDE(selectedNode);
        }
        /*
        void dataElementCreationControl_OnUseResult(object sender, EventArgs e)
        {
            if (dataElementCreationControl.LastResult == null)
            {
                MessageBox.Show("Error inserting data element");
                return;
            }
            XElement selectedNode = XElement.Parse(dataElementCreationControl.LastResult);
            handleCDE(selectedNode);
        }
        */
        protected void handleCDE(XElement selectedNode)
        {
            string id = selectedNode.Element("names").Element("id").Value;
            string preferredName = selectedNode.Element("names").Element("preferred").Value;
            string preferredNameTag = preferredName.Replace(" ", "_");
            string definition = selectedNode.Element("definition").Value;
            if (definition == null || definition.Length == 0)
            {
                definition = "(No definition supplied)";
            }
            else
            {
                //Handle special caDSR format
                definition = definition.Trim().Replace(">", ">").Replace("<", "<").Replace("<![CDATA[", "").Replace("]]>", "");
                if (definition.Contains("<def-source>"))
                {
                    XElement e = XElement.Parse("<def>" + definition + "</def>");
                    definition = e.Element("def-definition").Value + "\n(Source: " + e.Element("def-source").Value + ")";
                }
            }

            Excel.Workbook workbook = (Excel.Workbook)application.ActiveWorkbook;
            Excel.Range selected = (Excel.Range)application.Selection;

            Excel.XmlMap xmlMap = null;

            string attr = "";
            string attrWithDef = "";

            if (selectedNode.Element("values").Element("enumerated") != null)
            {

                var validValues = from vv in selectedNode.Element("values").Element("enumerated").Elements("valid-value")
                                  select new
                                  {
                                      Code = vv.Element("code").Value,
                                      Meaning = vv.Element("meaning").Value
                                  };

                XNamespace xs = "http://www.w3.org/2001/XMLSchema";
                XDocument x =
                    new XDocument(
                        new XDeclaration("1.0", "utf-8", "yes"),
                        new XElement(xs + "schema",
                            new XAttribute(XNamespace.Xmlns + "xs", "http://www.w3.org/2001/XMLSchema"),
                            new XAttribute("xmlns", "http://cagrid.org/schema/result-set"),
                            new XAttribute("targetNamespace", "http://cagrid.org/schema/result-set"),
                            new XElement(xs + "element",
                                new XAttribute("name", preferredNameTag + "List"),
                                new XAttribute("type", preferredNameTag + "List")
                                ),
                            new XElement(xs + "complexType",
                                new XAttribute("name", preferredNameTag + "List"),
                                new XElement(xs + "sequence",
                                    new XElement(xs + "element",
                                        new XAttribute("ref", preferredNameTag),
                                        new XAttribute("minOccurs", "0"),
                                        new XAttribute("maxOccurs", "unbounded")
                                        )
                                    )
                                ),
                            new XElement(xs + "element",
                                new XAttribute("name", preferredNameTag),
                                new XAttribute("type", preferredNameTag)
                            ),
                            new XElement(xs + "simpleType",
                                new XAttribute("name", preferredNameTag),
                                new XElement(xs + "restriction",
                                    new XAttribute("base", "xs:string")
                                    )
                                )
                            )
                        );

                XElement restrictionNode = x.Element(xs + "schema").Element(xs + "simpleType").Element(xs + "restriction");

                foreach (var vv in validValues)
                {
                    XElement enumNode = new XElement(xs + "enumeration",
                        new XAttribute("value", vv.Code),
                        new XElement(xs + "annotation", vv.Meaning)
                        );
                    restrictionNode.Add(enumNode);

                    attr += vv.Code + ",";
                    attrWithDef += vv.Code + " : (" + vv.Meaning.Replace(",", ",").Replace("<", "<").Replace(">", ">") + "),";

                }

                if (attr != null && attr.Contains(","))
                {
                    attr.Remove(attr.LastIndexOf(','));
                    attr.Trim();
                }
                try
                {
                    xmlMap = workbook.XmlMaps.Add(x.ToString(), (selected.Count > 1) ? preferredNameTag + "List" : preferredNameTag);
                    xmlMap.ShowImportExportValidationErrors = true;
                    xmlMap.AdjustColumnWidth = true;
                    selected.XPath.SetValue(xmlMap, (selected.Count > 1) ? "/rs:" + preferredNameTag + "List/rs:" + preferredNameTag : "/rs:" + preferredNameTag, "xmlns:rs=\"" + rs.NamespaceName + "\"", selected.Count > 1);
                }
                catch (ArgumentException ex)
                {
                    MessageBox.Show(ex.Message, "Range Selection Error");
                    xmlMap.Delete();
                    return;
                }

                selected.Validation.Delete();

                //xs:enumeration
                selected.Validation.Add(Excel.XlDVType.xlValidateList, Excel.XlDVAlertStyle.xlValidAlertStop, Excel.XlFormatConditionOperator.xlBetween, attr, attr);
                selected.Validation.InputTitle = "Select a value from the list";
                selected.Validation.InputMessage = attrWithDef.Replace(",", "\n");
                selected.Validation.ErrorMessage = "Please select a value from the enumeration list.";
            }
            else if (selectedNode.Element( "values").Element( "non-enumerated") != null)
            {
                attr = selectedNode.Element( "values").Element( "non-enumerated").Element( "data-type").Value;
                attrWithDef = "data-type: " + selectedNode.Element("values").Element("non-enumerated").Element("data-type").Value + "\nUnits: " + selectedNode.Element("values").Element("non-enumerated").Element("units").Value;

                XNamespace xs = "http://www.w3.org/2001/XMLSchema";
                XDocument x =
                    new XDocument(
                        new XDeclaration("1.0", "utf-8", "yes"),
                        new XElement(xs + "schema",
                            new XAttribute(XNamespace.Xmlns + "xs", "http://www.w3.org/2001/XMLSchema"),
                            new XAttribute("xmlns", "http://cagrid.org/schema/result-set"),
                            new XAttribute("targetNamespace", "http://cagrid.org/schema/result-set"),
                            new XElement(xs + "element",
                                new XAttribute("name", preferredNameTag + "List"),
                                new XAttribute("type", preferredNameTag + "List")
                                ),
                            new XElement(xs + "complexType",
                                new XAttribute("name", preferredNameTag + "List"),
                                new XElement(xs + "sequence",
                                    new XElement(xs + "element",
                                        new XAttribute("ref", preferredNameTag),
                                        new XAttribute("minOccurs", "0"),
                                        new XAttribute("maxOccurs", "unbounded")
                                        )
                                    )
                                ),
                            new XElement(xs + "element",
                                new XAttribute("name", preferredNameTag),
                                new XAttribute("type", preferredNameTag)
                            ),
                            new XElement(xs + "simpleType",
                                new XAttribute("name", preferredNameTag),
                                new XElement(xs + "annotation", definition),
                                new XElement(xs + "restriction",
                                    new XAttribute("base", attr)
                                    )
                                )
                            )
                        );
                try
                {
                    xmlMap = workbook.XmlMaps.Add(x.ToString(), (selected.Count > 1) ? preferredNameTag + "List" : preferredNameTag);
                    xmlMap.ShowImportExportValidationErrors = true;
                    xmlMap.AdjustColumnWidth = true;
                    selected.XPath.SetValue(xmlMap, (selected.Count > 1) ? "/rs:" + preferredNameTag + "List/rs:" + preferredNameTag : "/rs:" + preferredNameTag, "xmlns:rs=\"" + rs.NamespaceName + "\"", selected.Count > 1);
                }
                catch (ArgumentException ex)
                {
                    MessageBox.Show(ex.Message, "Range Selection Error");
                    xmlMap.Delete();
                    return;
                }

                selected.Validation.Delete();
                if (attr == "xs:nonNegativeInteger" || attr == "xs:positiveInteger")
                {
                    //xs:nonNegativeInteger
                    selected.Validation.Add(Excel.XlDVType.xlValidateWholeNumber, Excel.XlDVAlertStyle.xlValidAlertStop, Excel.XlFormatConditionOperator.xlGreaterEqual, 0, 0);
                    selected.Validation.InputTitle = "Enter a positive integer";
                    selected.Validation.InputMessage = " ";
                    selected.Validation.ErrorMessage = "Please enter a positive number";
                }
                else if (attr == "xs:nonPositiveInteger")
                {
                    //xs:integer
                    selected.Validation.Add(Excel.XlDVType.xlValidateWholeNumber, Excel.XlDVAlertStyle.xlValidAlertStop, Excel.XlFormatConditionOperator.xlLessEqual, 0, 0);
                    selected.Validation.InputTitle = "Enter a negative integer";
                    selected.Validation.InputMessage = " ";
                    selected.Validation.ErrorMessage = "Please enter a negative number";
                }
                else if (attr == "xs:positiveInteger")
                {
                    //xs:integer
                    selected.Validation.Add(Excel.XlDVType.xlValidateWholeNumber, Excel.XlDVAlertStyle.xlValidAlertStop, Excel.XlFormatConditionOperator.xlGreater, 0, 0);
                    selected.Validation.InputTitle = "Enter an integer number greater than 0(zero)";
                    selected.Validation.InputMessage = " ";
                    selected.Validation.ErrorMessage = "Please enter an integer number 0(zero)";
                }
                else if (attr == "xs:integer")
                {
                    //xs:integer
                    selected.Validation.Add(Excel.XlDVType.xlValidateWholeNumber, Excel.XlDVAlertStyle.xlValidAlertStop, Excel.XlFormatConditionOperator.xlBetween, Int32.MinValue, Int32.MaxValue);
                    selected.Validation.InputTitle = "Enter an integer number";
                    selected.Validation.InputMessage = " ";
                    selected.Validation.ErrorMessage = "Please enter an integer number";
                }
                else if (attr == "xs:int")
                {
                    //xs:int
                    selected.Validation.Add(Excel.XlDVType.xlValidateWholeNumber, Excel.XlDVAlertStyle.xlValidAlertStop, Excel.XlFormatConditionOperator.xlBetween, Int32.MinValue, Int32.MaxValue);
                    selected.Validation.InputTitle = "Enter an integer number";
                    selected.Validation.InputMessage = " ";
                    selected.Validation.ErrorMessage = "Please enter an integer number";
                }
                else if (attr == "xs:long")
                {
                    //xs:long
                    selected.Validation.Add(Excel.XlDVType.xlValidateWholeNumber, Excel.XlDVAlertStyle.xlValidAlertStop, Excel.XlFormatConditionOperator.xlBetween, Int64.MinValue, Int64.MaxValue);
                    selected.Validation.InputTitle = "Enter an integer number";
                    selected.Validation.InputMessage = " ";
                    selected.Validation.ErrorMessage = "Please enter an integer number";
                }
                else if (attr == "xs:date")
                {
                    //xs:date
                    selected.Validation.Add(Excel.XlDVType.xlValidateDate, Excel.XlDVAlertStyle.xlValidAlertStop, Excel.XlFormatConditionOperator.xlGreaterEqual, "=DATE(1900,1,1)", "=DATE(1900,1,1)");
                    selected.Validation.InputTitle = "Enter a date";
                    selected.Validation.InputMessage = "Date format: =DATE(year,month,day)";
                    selected.Validation.ErrorMessage = "Please enter correct date format: =DATE(year,month,day)";
                }
                else if (attr == "xs:boolean")
                {
                    //xs:boolean
                    selected.Validation.Add(Excel.XlDVType.xlValidateList, Excel.XlDVAlertStyle.xlValidAlertStop, Excel.XlFormatConditionOperator.xlBetween, "true,false", "true,false");
                    selected.Validation.InputTitle = "Select True or False";
                    selected.Validation.InputMessage = " ";
                    selected.Validation.ErrorMessage = "Please select a boolean value from the list";
                }
                else if (attr == "xs:double")
                {
                    //xs:double
                    selected.Validation.Add(Excel.XlDVType.xlValidateDecimal, Excel.XlDVAlertStyle.xlValidAlertStop, Excel.XlFormatConditionOperator.xlBetween, Decimal.MinValue, Decimal.MaxValue);
                    selected.Validation.InputTitle = "Enter a decimal number";
                    selected.Validation.InputMessage = " ";
                    selected.Validation.ErrorMessage = "Please select a decimal number";
                }
                else if (attr == "xs:float")
                {
                    //xs:float
                    selected.Validation.Add(Excel.XlDVType.xlValidateDecimal, Excel.XlDVAlertStyle.xlValidAlertStop, Excel.XlFormatConditionOperator.xlBetween, Single.MinValue, Single.MaxValue);
                    selected.Validation.InputTitle = "Enter a decimal number";
                    selected.Validation.InputMessage = " ";
                    selected.Validation.ErrorMessage = "Please select a decimal number";
                }
                else if (attr == "xs:unsignedInt")
                {
                    //xs:boolean
                    selected.Validation.Add(Excel.XlDVType.xlValidateWholeNumber, Excel.XlDVAlertStyle.xlValidAlertStop, Excel.XlFormatConditionOperator.xlBetween, UInt32.MinValue, UInt32.MaxValue);
                    selected.Validation.InputTitle = "Enter an unsigned integer number";
                    selected.Validation.InputMessage = " ";
                    selected.Validation.ErrorMessage = "Please select an unsigned integer number";
                }
                else if (attr == "xs:unsignedLong")
                {
                    //xs:boolean
                    selected.Validation.Add(Excel.XlDVType.xlValidateWholeNumber, Excel.XlDVAlertStyle.xlValidAlertStop, Excel.XlFormatConditionOperator.xlBetween, UInt64.MinValue, UInt64.MaxValue);
                    selected.Validation.InputTitle = "Enter an unsigned integer number";
                    selected.Validation.InputMessage = " ";
                    selected.Validation.ErrorMessage = "Please select an unsigned integer number";
                }
                else if (attr == "xs:unsignedShort")
                {
                    //xs:boolean
                    selected.Validation.Add(Excel.XlDVType.xlValidateWholeNumber, Excel.XlDVAlertStyle.xlValidAlertStop, Excel.XlFormatConditionOperator.xlBetween, UInt16.MinValue, UInt16.MaxValue);
                    selected.Validation.InputTitle = "Enter an unsigned integer number";
                    selected.Validation.InputMessage = " ";
                    selected.Validation.ErrorMessage = "Please select an unsigned integer number";
                }
                /*
                else if (attr == "xs:duration")
                {
                    //xs:duration
                    selected.Validation.Add(Excel.XlDVType.xlValidateDecimal, Excel.XlDVAlertStyle.xlValidAlertStop, Excel.XlFormatConditionOperator.xlBetween, Decimal.MinValue, Decimal.MaxValue);
                    selected.Validation.InputTitle = "Enter a decimal number";
                    selected.Validation.InputMessage = " ";
                    selected.Validation.ErrorMessage = "Please select a decimal number";
                }
                else if (attr == "xs:dateTime")
                {
                    //xs:dateTime
                    selected.Validation.Add(Excel.XlDVType.xlValidateDecimal, Excel.XlDVAlertStyle.xlValidAlertStop, Excel.XlFormatConditionOperator.xlBetween, Decimal.MinValue, Decimal.MaxValue);
                    selected.Validation.InputTitle = "Enter a decimal number";
                    selected.Validation.InputMessage = " ";
                    selected.Validation.ErrorMessage = "Please select a decimal number";
                }
                else if (attr == "xs:time")
                {
                    //xs:time
                    selected.Validation.Add(Excel.XlDVType.xlValidateDecimal, Excel.XlDVAlertStyle.xlValidAlertStop, Excel.XlFormatConditionOperator.xlBetween, Decimal.MinValue, Decimal.MaxValue);
                    selected.Validation.InputTitle = "Enter a decimal number";
                    selected.Validation.InputMessage = " ";
                    selected.Validation.ErrorMessage = "Please select a decimal number";
                }
                else if (attr == "xs:gYearMonth")
                {
                    //xs:gYearMonth
                    selected.Validation.Add(Excel.XlDVType.xlValidateDecimal, Excel.XlDVAlertStyle.xlValidAlertStop, Excel.XlFormatConditionOperator.xlBetween, Decimal.MinValue, Decimal.MaxValue);
                    selected.Validation.InputTitle = "Enter a decimal number";
                    selected.Validation.InputMessage = " ";
                    selected.Validation.ErrorMessage = "Please select a decimal number";
                }
                else if (attr == "xs:gYear")
                {
                    //xs:gYear
                    selected.Validation.Add(Excel.XlDVType.xlValidateDecimal, Excel.XlDVAlertStyle.xlValidAlertStop, Excel.XlFormatConditionOperator.xlBetween, Decimal.MinValue, Decimal.MaxValue);
                    selected.Validation.InputTitle = "Enter a decimal number";
                    selected.Validation.InputMessage = " ";
                    selected.Validation.ErrorMessage = "Please select a decimal number";
                }
                else if (attr == "xs:gMonthDay")
                {
                    //xs:gMonthDay
                    selected.Validation.Add(Excel.XlDVType.xlValidateDecimal, Excel.XlDVAlertStyle.xlValidAlertStop, Excel.XlFormatConditionOperator.xlBetween, Decimal.MinValue, Decimal.MaxValue);
                    selected.Validation.InputTitle = "Enter a decimal number";
                    selected.Validation.InputMessage = " ";
                    selected.Validation.ErrorMessage = "Please select a decimal number";
                }
                else if (attr == "xs:gDay")
                {
                    //xs:gDay
                    selected.Validation.Add(Excel.XlDVType.xlValidateDecimal, Excel.XlDVAlertStyle.xlValidAlertStop, Excel.XlFormatConditionOperator.xlBetween, Decimal.MinValue, Decimal.MaxValue);
                    selected.Validation.InputTitle = "Enter a decimal number";
                    selected.Validation.InputMessage = " ";
                    selected.Validation.ErrorMessage = "Please select a decimal number";
                }
                else if (attr == "xs:gMonth")
                {
                    //xs:gMonth
                    selected.Validation.Add(Excel.XlDVType.xlValidateDecimal, Excel.XlDVAlertStyle.xlValidAlertStop, Excel.XlFormatConditionOperator.xlBetween, Decimal.MinValue, Decimal.MaxValue);
                    selected.Validation.InputTitle = "Enter a decimal number";
                    selected.Validation.InputMessage = " ";
                    selected.Validation.ErrorMessage = "Please select a decimal number";
                }
                else if (attr == "xs:anyURI")
                {
                    //xs:anyURI
                    selected.Validation.Add(Excel.XlDVType.xlValidateDecimal, Excel.XlDVAlertStyle.xlValidAlertStop, Excel.XlFormatConditionOperator.xlBetween, Decimal.MinValue, Decimal.MaxValue);
                    selected.Validation.InputTitle = "Enter a decimal number";
                    selected.Validation.InputMessage = " ";
                    selected.Validation.ErrorMessage = "Please select a decimal number";
                }
                */
            }

            selected.Name = xmlMap.Name;

            //Create CDE list is not exist
            if (!isCDEListExists())
            {
                createCDEList();
            }

            //Add new CDE entry to cde_list
            cdeList.Unprotect(dummyPass);
            Excel.Range c = (Excel.Range)cdeList.Cells[2, 1];

            for (int i = 3; c.Value2 != null; i++)
            {
                c = (Excel.Range)cdeList.Cells[i, 1];
            }

            string instanceNum = xmlMap.Name.Substring(xmlMap.Name.LastIndexOf("_Map") + 4);
            c.Hyperlinks.Add(c, "", xmlMap.Name, Type.Missing, id + ((selected.Count > 1) ? "(List)" : "(Single)") + ((instanceNum != null && instanceNum.Length > 0) ? "(" + instanceNum + ")" : "") + "\n\nRange: " + getSelectedRangeAddress(selected));
            c.Next.Value2 = preferredName;
            c.Next.Next.Value2 = definition.Trim().Replace(">", ">").Replace("<", "<").Replace("&", "&");
            c.Next.Next.Next.Value2 = attrWithDef.Trim().Replace(",", "\n\n").Replace(",", ", ").Replace(">", ">").Replace("<", "<").Replace("&", "&");
            cdeList.Protect(dummyPass, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);

            // Create/Format Header
            if (selected.Count > 1)
            {
                Excel.Range firstCell = (Excel.Range)selected.Cells[1, 1];
                firstCell.Validation.Delete();
                firstCell.Value2 = ((string)firstCell.Value2).Substring(((string)firstCell.Value2).IndexOf(":") + 1).Replace("_", " ");
                firstCell.Hyperlinks.Add(firstCell, "", getSelectedRangeAddress(c), Type.Missing, firstCell.Value2);
                firstCell.Font.ColorIndex = 2;
                firstCell.Font.Underline = false;
            }
            else if (selected.Count == 1)
            {
                selected.Interior.ThemeColor = Excel.XlThemeColor.xlThemeColorAccent1;
                selected.Interior.TintAndShade = 0.6;

                if (selected.Column != 1)
                {
                    try
                    {
                        Excel.Range leftCell = selected.get_Offset(0, -1);
                        if (leftCell != null && (leftCell.Value2 == null || ((string)leftCell.Value2).Length == 0))
                        {
                            leftCell.Value2 = preferredName;
                            leftCell.Hyperlinks.Add(leftCell, "", getSelectedRangeAddress(c), Type.Missing, leftCell.Value2);
                            leftCell.Font.Bold = true;
                            leftCell.Font.Underline = false;
                            leftCell.Font.ColorIndex = 1;
                            return;
                        }

                        Excel.Range upCell = selected.get_Offset(-1, 0);
                        if (upCell != null && (upCell.Value2 == null || ((string)upCell.Value2).Length == 0))
                        {
                            upCell.Value2 = preferredName;
                            upCell.Hyperlinks.Add(upCell, "", getSelectedRangeAddress(c), Type.Missing, upCell.Value2);
                            upCell.Font.Bold = true;
                            upCell.Font.Underline = false;
                            upCell.Font.ColorIndex = 1;
                            return;
                        }
                    }
                    catch (Exception)
                    {
                        //Unable to get valid cell
                        MessageBox.Show("Unable to find suitable location to insert header/label", "Header/Label not created");
                    }
                }
                else
                {
                    try
                    {
                        Excel.Range upCell = selected.get_Offset(-1, 0);
                        if (upCell != null && (upCell.Value2 == null || ((string)upCell.Value2).Length == 0))
                        {
                            upCell.Value2 = preferredName;
                            upCell.Hyperlinks.Add(upCell, "", getSelectedRangeAddress(c), Type.Missing, upCell.Value2);
                            upCell.Font.Bold = true;
                            upCell.Font.Underline = false;
                            upCell.Font.ColorIndex = 1;
                            return;
                        }
                    }
                    catch (Exception)
                    {
                        MessageBox.Show("Unable to find suitable location to insert header/label", "Header/Label not created");
                    }
                }
            }
        }

        protected string getSelectedRangeAddress(Excel.Range r)
        {
            return ((Excel.Worksheet)r.Parent).Name + "!" + r.get_Address(Type.Missing, Type.Missing, Excel.XlReferenceStyle.xlA1, Type.Missing, Type.Missing);
        }

        private bool isCDEListExists()
        {
            try
            {
                cdeList = (Excel.Worksheet)application.Worksheets.get_Item("cde_list");
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }

        private void createCDEList()
        {
            Excel.Worksheet origin = (Excel.Worksheet)application.ActiveSheet;
            cdeList = (Excel.Worksheet)application.ActiveWorkbook.Worksheets.Add(Type.Missing, application.ActiveSheet, Type.Missing, Type.Missing);
            cdeList.Name = "cde_list";

            Excel.Range column = ((Excel.Range)cdeList.Cells[1, 1]);

            //ID
            column.Value2 = "ID";
            column.Font.Bold = true;
            column.Font.Background = Excel.XlBackground.xlBackgroundOpaque;
            column.EntireColumn.ColumnWidth = 25;
            column.EntireColumn.WrapText = true;
            column.EntireColumn.VerticalAlignment = Excel.XlVAlign.xlVAlignTop;

            //Name
            column.Next.Value2 = "Name";
            column.Next.Font.Bold = true;
            column.Next.Font.Background = Excel.XlBackground.xlBackgroundOpaque;
            column.Next.EntireColumn.ColumnWidth = 30;
            column.Next.EntireColumn.WrapText = true;
            column.Next.EntireColumn.VerticalAlignment = Excel.XlVAlign.xlVAlignTop;

            //Definition
            column.Next.Next.Value2 = "Definition";
            column.Next.Next.Font.Bold = true;
            column.Next.Next.Font.Background = Excel.XlBackground.xlBackgroundOpaque;
            column.Next.Next.EntireColumn.ColumnWidth = 60;
            column.Next.Next.EntireColumn.VerticalAlignment = Excel.XlVAlign.xlVAlignTop;
            column.Next.Next.EntireColumn.WrapText = true;
            column.Next.Next.EntireColumn.HorizontalAlignment = Excel.XlHAlign.xlHAlignJustify;

            //Properties/Values
            column.Next.Next.Next.Value2 = "Properties/Values";
            column.Next.Next.Next.Font.Bold = true;
            column.Next.Next.Next.Font.Background = Excel.XlBackground.xlBackgroundOpaque;
            column.Next.Next.Next.EntireColumn.ColumnWidth = 50;
            column.Next.Next.Next.EntireColumn.VerticalAlignment = Excel.XlVAlign.xlVAlignTop;
            column.Next.Next.Next.EntireColumn.WrapText = true;
            column.Next.Next.Next.EntireColumn.HorizontalAlignment = Excel.XlHAlign.xlHAlignJustify;

            cdeList.Protect(dummyPass, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);

            //((Excel.Worksheet)application.Worksheets.get_Item(origin.Name)).Activate();
            (origin as Microsoft.Office.Interop.Excel._Worksheet).Activate();
        }
/*
        private void insertCDE(Excel.Application application)
        {
            Excel.Worksheet cdeList = null;

            //Applying validation rules based on selected CDE
            XmlDocument xDoc = new XmlDocument();
            xDoc.LoadXml(dataElementCreationControl.LastResult);
            XmlNode srcNode = xDoc.DocumentElement.SelectSingleNode("/data-element");
            XmlNode names = srcNode.SelectSingleNode("names");
            XmlNode attributes = srcNode.SelectSingleNode("values");
            XmlNodeList validValues = attributes.SelectNodes("enumerated/valid-value");
            string attr = "";

            application.ActiveCell.Validation.Delete();
            string id = names.SelectSingleNode("id").InnerXml;
            string preferred = names.SelectSingleNode("preferred").InnerXml;
            string definition = srcNode.SelectSingleNode("definition").InnerXml;

            Excel.Range selected = (Excel.Range)application.Selection;
            if (validValues != null && validValues.Count != 0)
            {
                foreach (XmlNode n in validValues)
                {
                    attr += n.SelectSingleNode("code").InnerXml + " : (" + n.SelectSingleNode("meaning").InnerXml.Replace(",", ",") + "),";
                }
                attr.Remove(attr.LastIndexOf(','));
                attr.Trim();

                //xs:enumeration
                selected.Validation.Add(Excel.XlDVType.xlValidateList, Excel.XlDVAlertStyle.xlValidAlertStop, Excel.XlFormatConditionOperator.xlBetween, attr, attr);
                //application.ActiveCell.Validation.InputTitle = name.InnerXml;
                //application.ActiveCell.Validation.ErrorTitle = name.InnerXml;
                selected.Validation.InputMessage = "Select a value from the list.";
                selected.Validation.ErrorMessage = "You must select a value from the enumeration list.";
            }
            else
            {
                attr = attributes.SelectSingleNode("non-enumerated/data-type").InnerXml;
                if (attr == "xs:nonNegativeInteger")
                {
                    //xs:nonNegativeInteger
                    selected.Validation.Add(Excel.XlDVType.xlValidateWholeNumber, Excel.XlDVAlertStyle.xlValidAlertStop, Excel.XlFormatConditionOperator.xlGreaterEqual, 0, 0);
                    //application.ActiveCell.Validation.InputTitle = name.InnerXml;
                    //application.ActiveCell.Validation.ErrorTitle = name.InnerXml;
                    selected.Validation.InputMessage = "Enter a positive integer";
                    selected.Validation.ErrorMessage = "You must enter a positive number";
                }
                else if (attr == "xs:integer")
                {
                    //xs:integer
                    selected.Validation.Add(Excel.XlDVType.xlValidateWholeNumber, Excel.XlDVAlertStyle.xlValidAlertStop, Excel.XlFormatConditionOperator.xlBetween, Int32.MinValue, Int32.MaxValue);
                    //application.ActiveCell.Validation.InputTitle = name.InnerXml;
                    //application.ActiveCell.Validation.ErrorTitle = name.InnerXml;
                    selected.Validation.InputMessage = "Enter an integer";
                    selected.Validation.ErrorMessage = "You must enter an integer number";
                }
                else if (attr == "xs:date")
                {
                    //xs:date
                    selected.Validation.Add(Excel.XlDVType.xlValidateDate, Excel.XlDVAlertStyle.xlValidAlertStop, Excel.XlFormatConditionOperator.xlGreaterEqual, "=DATE(1900,1,1)", "=DATE(1900,1,1)");
                    //application.ActiveCell.Validation.InputTitle = name.InnerXml;
                    //application.ActiveCell.Validation.ErrorTitle = name.InnerXml;
                    selected.Validation.InputMessage = "Enter a date";
                    selected.Validation.ErrorMessage = "You must enter correct date format";
                }
                else if (attr == "xs:boolean")
                {
                    //xs:boolean
                    selected.Validation.Add(Excel.XlDVType.xlValidateList, Excel.XlDVAlertStyle.xlValidAlertStop, Excel.XlFormatConditionOperator.xlBetween, "true,false", "true,false");
                    //application.ActiveCell.Validation.InputTitle = name.InnerXml;
                    //application.ActiveCell.Validation.ErrorTitle = name.InnerXml;
                    selected.Validation.InputMessage = "Select true or false";
                    selected.Validation.ErrorMessage = "You must select a boolean value";
                }
            }
            if (selected.Count > 1 && selected.Areas.Count == 1)
            {
                Excel.Range firstCell = ((Excel.Range)selected.Cells[1, 1]);
                firstCell.Value2 = preferred;
                firstCell.Font.Bold = true;
                selected.ColumnWidth = firstCell.Value2.ToString().Length;
                firstCell.Validation.Delete();
            }

            //Create CDE list
            try
            {
                cdeList = (Excel.Worksheet)application.Worksheets.get_Item("cde_list");
            }
            catch (Exception)
            {
                Excel.Worksheet origin = (Excel.Worksheet)application.ActiveSheet;
                cdeList = (Excel.Worksheet)application.ActiveWorkbook.Worksheets.Add(Type.Missing, application.ActiveSheet, Type.Missing, Type.Missing);
                cdeList.Name = "cde_list";

                Excel.Range column = ((Excel.Range)cdeList.Cells[1, 1]);

                //ID
                column.Value2 = "ID";
                column.Font.Bold = true;
                column.Font.Background = Excel.XlBackground.xlBackgroundOpaque;
                column.EntireColumn.ColumnWidth = 25;
                column.EntireColumn.WrapText = true;
                column.EntireColumn.VerticalAlignment = Excel.XlVAlign.xlVAlignTop;

                //Name
                column.Next.Value2 = "Name";
                column.Next.Font.Bold = true;
                column.Next.Font.Background = Excel.XlBackground.xlBackgroundOpaque;
                column.Next.EntireColumn.ColumnWidth = 30;
                column.Next.EntireColumn.WrapText = true;
                column.Next.EntireColumn.VerticalAlignment = Excel.XlVAlign.xlVAlignTop;

                //Definition
                column.Next.Next.Value2 = "Definition";
                column.Next.Next.Font.Bold = true;
                column.Next.Next.Font.Background = Excel.XlBackground.xlBackgroundOpaque;
                column.Next.Next.EntireColumn.ColumnWidth = 60;
                column.Next.Next.EntireColumn.VerticalAlignment = Excel.XlVAlign.xlVAlignTop;
                column.Next.Next.EntireColumn.WrapText = true;
                column.Next.Next.EntireColumn.HorizontalAlignment = Excel.XlHAlign.xlHAlignJustify;

                //Properties/Values
                column.Next.Next.Next.Value2 = "Properties/Values";
                column.Next.Next.Next.Font.Bold = true;
                column.Next.Next.Next.Font.Background = Excel.XlBackground.xlBackgroundOpaque;
                column.Next.Next.Next.EntireColumn.ColumnWidth = 50;
                column.Next.Next.Next.EntireColumn.VerticalAlignment = Excel.XlVAlign.xlVAlignTop;
                column.Next.Next.Next.EntireColumn.WrapText = true;
                column.Next.Next.Next.EntireColumn.HorizontalAlignment = Excel.XlHAlign.xlHAlignJustify;

                //((Excel.Worksheet)application.Worksheets.get_Item(origin.Name)).Activate();
                (origin as Microsoft.Office.Interop.Excel._Worksheet).Activate();
            }
            cdeList.Unprotect("dummy_password");
            Excel.Range c = (Excel.Range)cdeList.Cells[2, 1];

            for (int i = 3; c.Value2 != null; i++)
            {
                c = (Excel.Range)cdeList.Cells[i, 1];
            }

            c.Value2 = id;
            c.Next.Value2 = preferred;
            c.Next.Next.Value2 = definition.Trim().Replace(">", ">").Replace("<", "<").Replace("&", "&");
            c.Next.Next.Next.Value2 = attr.Trim().Replace(",", "\n\n").Replace(",", ", ").Replace(">", ">").Replace("<", "<").Replace("&", "&");
            cdeList.Protect("dummy_password", Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
        }
 */
    }
}


text:
package statecouchdb

import (
	"os"
	"testing"

	"github.com/hyperledger/fabric/core/ledger/kvledger/txmgmt/statedb"
	"github.com/hyperledger/fabric/core/ledger/kvledger/txmgmt/statedb/commontests"
	"github.com/hyperledger/fabric/core/ledger/kvledger/txmgmt/version"
	"github.com/hyperledger/fabric/core/ledger/ledgerconfig"
	"github.com/hyperledger/fabric/core/ledger/testutil"
	"github.com/spf13/viper"
)

func TestMain(m *testing.M) {

	//call a helper method to load the core.yaml, will be used to detect if CouchDB is enabled
	testutil.SetupCoreYAMLConfig("./../../../../../../peer")

	viper.Set("ledger.state.couchDBConfig.couchDBAddress", "127.0.0.1:5984")
	viper.Set("peer.fileSystemPath", "/tmp/fabric/ledgertests/kvledger/txmgmt/statedb/statecouchdb")

	os.Exit(m.Run())
}

func TestBasicRW(t *testing.T) {
	if ledgerconfig.IsCouchDBEnabled() == true {

		env := NewTestVDBEnv(t)
		env.Cleanup("TestDB")
		defer env.Cleanup("TestDB")
		commontests.TestBasicRW(t, env.DBProvider)

	}
}

func TestMultiDBBasicRW(t *testing.T) {
	if ledgerconfig.IsCouchDBEnabled() == true {

		env := NewTestVDBEnv(t)
		env.Cleanup("TestDB1")
		env.Cleanup("TestDB2")
		defer env.Cleanup("TestDB1")
		defer env.Cleanup("TestDB2")
		commontests.TestMultiDBBasicRW(t, env.DBProvider)

	}
}

/* TODO add delete support in couchdb and then convert key value of nil to a couch delete. This will resolve TestDeletes
func TestDeletes(t *testing.T) {
	env := NewTestVDBEnv(t)
	env.Cleanup("TestDB")
	defer env.Cleanup("TestDB")
	commontests.TestDeletes(t, env.DBProvider)
}
*/

func TestIterator(t *testing.T) {
	if ledgerconfig.IsCouchDBEnabled() == true {

		env := NewTestVDBEnv(t)
		env.Cleanup("TestDB")
		defer env.Cleanup("TestDB")
		commontests.TestIterator(t, env.DBProvider)

	}
}

func TestEncodeDecodeValueAndVersion(t *testing.T) {
	testValueAndVersionEncoding(t, []byte("value1"), version.NewHeight(1, 2))
	testValueAndVersionEncoding(t, []byte{}, version.NewHeight(50, 50))
}

func testValueAndVersionEncoding(t *testing.T, value []byte, version *version.Height) {
	encodedValue := statedb.EncodeValue(value, version)
	val, ver := statedb.DecodeValue(encodedValue)
	testutil.AssertEquals(t, val, value)
	testutil.AssertEquals(t, ver, version)
}

func TestCompositeKey(t *testing.T) {
	if ledgerconfig.IsCouchDBEnabled() == true {

		testCompositeKey(t, "ns", "key")
		testCompositeKey(t, "ns", "")

	}
}

func testCompositeKey(t *testing.T, ns string, key string) {
	compositeKey := constructCompositeKey(ns, key)
	t.Logf("compositeKey=%#v", compositeKey)
	ns1, key1 := splitCompositeKey(compositeKey)
	testutil.AssertEquals(t, ns1, ns)
	testutil.AssertEquals(t, key1, key)
}

// The following tests are unique to couchdb, they are not used in leveldb
//  query test
func TestQuery(t *testing.T) {
	if ledgerconfig.IsCouchDBEnabled() == true {

		env := NewTestVDBEnv(t)
		env.Cleanup("TestDB")
		defer env.Cleanup("TestDB")
		commontests.TestQuery(t, env.DBProvider)

	}
}


text:
package com.github.dm.jrt.operator;

import com.github.dm.jrt.core.channel.Channel;
import com.github.dm.jrt.core.invocation.Invocation;
import com.github.dm.jrt.core.invocation.InvocationFactory;
import com.github.dm.jrt.core.invocation.TemplateInvocation;

import org.jetbrains.annotations.NotNull;

import static com.github.dm.jrt.operator.math.Numbers.addOptimistic;

/**
 * Invocation computing the average of the input numbers in double precision.
 * <p>
 * Created by davide-maestroni on 05/02/2016.
 */
class AverageDoubleInvocation extends TemplateInvocation<Number, Double> {

  private static final InvocationFactory<Number, Double> sFactory =
      new InvocationFactory<Number, Double>(null) {

        @NotNull
        @Override
        public Invocation<Number, Double> newInvocation() {
          return new AverageDoubleInvocation();
        }
      };

  private int mCount;

  private Number mSum;

  /**
   * Constructor.
   */
  private AverageDoubleInvocation() {
  }

  /**
   * Returns a factory of invocations computing the average of the input numbers in double
   * precision.
   *
   * @return the factory instance.
   */
  @NotNull
  static InvocationFactory<Number, Double> factoryOf() {
    return sFactory;
  }

  @Override
  public void onComplete(@NotNull final Channel<Double, ?> result) {
    if (mCount == 0) {
      result.pass(0d);

    } else {
      result.pass(mSum.doubleValue() / mCount);
    }
  }

  @Override
  public void onInput(final Number input, @NotNull final Channel<Double, ?> result) {
    mSum = addOptimistic(mSum, input).doubleValue();
    ++mCount;
  }

  @Override
  public void onRestart() {
    mSum = (byte) 0;
    mCount = 0;
  }
}


text:
from twisted.internet import reactor, defer
from pysnmp.entity import engine, config
from pysnmp.entity.rfc3413.twisted import cmdgen
from pysnmp.proto import rfc1905
from pysnmp.carrier.twisted.dgram import udp

# Create SNMP engine instance
snmpEngine = engine.SnmpEngine()

#
# SNMPv3/USM setup
#

# user: usr-md5-des, auth: MD5, priv DES
config.addV3User(
    snmpEngine, 'usr-md5-des',
        config.usmHMACMD5AuthProtocol, 'authkey1',
        config.usmDESPrivProtocol, 'privkey1'
)
config.addTargetParams(snmpEngine, 'my-creds', 'usr-md5-des', 'authPriv')

#
# Setup transport endpoint and bind it with security settings yielding
# a target name
#

# UDP/IPv4
config.addTransport(
    snmpEngine,
    udp.domainName,
    udp.UdpTwistedTransport().openClientMode()
)
config.addTargetAddr(
    snmpEngine, 'my-router',
    udp.domainName, ('195.218.195.228', 161),
    'my-creds'
)

# Error/response receiver
def cbFun(response):
    snmpEngine, errorIndication, errorStatus, errorIndex, varBindTable = response
    if errorIndication:
        print(errorIndication)
    elif errorStatus:
        print('%s at %s' % (
                errorStatus.prettyPrint(),
                errorIndex and varBinds[int(errorIndex)-1][0] or '?'
            )
        )
    else:
        for varBindRow in varBindTable:
            for oid, val in varBindRow:
                print('%s = %s' % (oid.prettyPrint(), val.prettyPrint()))

        # Stop reactor when we are done walking (optional)
        for oid, val in varBindRow:
            if not val.isSameTypeWith(rfc1905.endOfMibView):
                break
        else:
            reactor.stop()
            return

        # Re-create deferred for next GETBULK iteration
        df = defer.Deferred()
        df.addCallback(cbFun)
        return df  # This also indicates that we wish to continue walking

    # Stop reactor on SNMP error (optional)
    reactor.stop()

# Prepare request to be sent yielding Twisted deferred object
df = cmdgen.BulkCommandGenerator().sendVarBinds(
    snmpEngine,
    'my-router',
    None, '',  # contextEngineId, contextName
    0, 25,   # non-repeaters, max-repetitions
    [ ((1,3,6,1,2,1,1), None), ((1,3,6,1,4,1,1), None) ]
)

# Register error/response receiver function at deferred
df.addCallback(cbFun)

# Run Twisted main loop
reactor.run()


text:
"""Application controller for ParsInsert

designed for ParsInsert v1.03 """

__author__ = "Jesse Stombaugh"
__copyright__ = "Copyright 2007-2012, The Cogent Project"
__credits__ = ["Jesse Stombaugh"]
__license__ = "GPL"
__version__ = "1.5.3"
__maintainer__ = "Jesse Stombaugh"
__email__ = "jesse.stombaugh@colorado.edu"
__status__ = "Production"

from cogent.app.parameters import ValuedParameter, FlagParameter, \
       MixedParameter
from cogent.app.util import CommandLineApplication, FilePath, system, \
       CommandLineAppResult, ResultPath, remove, ApplicationError
from cogent.core.tree import PhyloNode
from cogent.parse.tree import DndParser
from cogent.core.moltype import DNA, RNA, PROTEIN
from cogent.core.alignment import SequenceCollection,Alignment
from os.path import splitext, join,abspath
from cogent.parse.phylip import get_align_for_phylip
from StringIO import StringIO

class ParsInsert(CommandLineApplication):
    """ParsInsert application Controller"""

    _command = 'ParsInsert'
    _input_handler = '_input_as_multiline_string'
    _parameters = {
                    # read mask from this file
                    '-m':ValuedParameter('-',Name='m',Delimiter=' '),

                    # read core tree sequences from this file
                    '-s':ValuedParameter('-',Name='s',Delimiter=' '),

                    # read core tree from this file
                    '-t':ValuedParameter('-',Name='t',Delimiter=' '),

                    # read core tree taxomony from this file
                    '-x':ValuedParameter('-',Name='x',Delimiter=' '),

                    # output taxonomy for each insert sequence to this file
                    '-o':ValuedParameter('-',Name='o',Delimiter=' '),

                    # create log file
                    '-l':ValuedParameter('-',Name='l',Delimiter=' '),

                    # number of best matches to display
                    '-n':ValuedParameter('-',Name='n',Delimiter=' '),

                    #percent threshold cutoff
                    '-c':ValuedParameter('-',Name='c',Delimiter=' '),
                   }

    def _handle_app_result_build_failure(self,out,err,exit_status,result_paths):
        """ Catch the error when files are not produced """
        raise ApplicationError, \
         'ParsInsert failed to produce an output file due to the following error: \n\n%s ' \
         % err.read()

    def _get_result_paths(self,data):
        """ Get the resulting tree"""
        result = {}
        result['Tree'] = ResultPath(Path=splitext(self._input_filename)[0] + \
                                                  '.tree')
        return result

def insert_sequences_into_tree(aln, moltype, params={}):
    """Returns a tree from placement of sequences
    """
    # convert aln to phy since seq_names need fixed to run through parsinsert
    new_aln=get_align_for_phylip(StringIO(aln))

    # convert aln to fasta in case it is not already a fasta file
    aln2 = Alignment(new_aln)
    seqs = aln2.toFasta()

    parsinsert_app = ParsInsert(params=params)
    result = parsinsert_app(seqs)

    # parse tree
    tree = DndParser(result['Tree'].read(), constructor=PhyloNode)

    # cleanup files
    result.cleanUp()

    return tree


text:
package server

import (
	"encoding/json"
	"github.com/LapisBlue/lapitar/face"
	"github.com/LapisBlue/lapitar/render"
	"github.com/LapisBlue/lapitar/util"
	"github.com/disintegration/imaging"
	"io"
)

const (
	indent = "    "
)

type config struct {
	Address  string          `json:"address"`
	Proxy    bool            `json:"proxy"`
	Defaults *renderDefaults `json:"defaults"`
}

type renderDefaults struct {
	Head     *renderConfig `json:"head"`
	Portrait *renderConfig `json:"portrait"`
	Body     *renderConfig `json:"body"`
	Face     *faceConfig   `json:"face"`
}

type faceConfig struct {
	Size  *limitedInt `json:"size"`
	Scale *scaling    `json:"scale"`
}

type renderConfig struct {
	*faceConfig
	Overlay       bool    `json:"overlay"`
	Angle         float32 `json:"angle"`
	Tilt          float32 `json:"tilt"`
	Zoom          float32 `json:"zoom"`
	SuperSampling int     `json:"supersampling"`
	Shadow        bool    `json:"shadow"`
	Lighting      bool    `json:"lighting"`
}

type limitedInt struct {
	Def int `json:"default"`
	Max int `json:"max"`
}

func defaultConfig() *config {
	return &config{
		":8088",
		false,
		&renderDefaults{
			newRenderConfig(-35, 20, -4.5),
			newRenderConfig(25, 10, -4.5),
			newRenderConfig(25, 10, -6),
			&faceConfig{
				&limitedInt{128, 512},
				&scaling{face.DefaultScale},
			},
		},
	}
}

func newRenderConfig(angle, tilt, zoom float32) *renderConfig {
	return &renderConfig{
		&faceConfig{
			&limitedInt{128, 512},
			&scaling{render.DefaultScale},
		},
		true,
		angle,
		tilt,
		zoom,
		4,
		true,
		true,
	}
}

func parseConfig(reader io.Reader) (conf *config, err error) {
	conf = defaultConfig()
	err = json.NewDecoder(reader).Decode(conf)
	return
}

func writeConfig(writer io.Writer, conf *config) (err error) {
	// We can't use an encoder here because it cannot print with indentation
	buf, err := json.MarshalIndent(conf, "", indent)
	if err != nil {
		return
	}
	_, err = writer.Write(buf)
	if err != nil {
		return
	}
	_, err = io.WriteString(writer, "\n")
	return
}

type scaling struct {
	*imaging.ResampleFilter
}

func (scale *scaling) Get() *imaging.ResampleFilter {
	return scale.ResampleFilter
}

func (scale *scaling) MarshalText() ([]byte, error) {
	return []byte(util.ScaleName(scale.ResampleFilter)), nil
}

func (scale *scaling) UnmarshalText(text []byte) (err error) {
	scale.ResampleFilter, err = util.ParseScale(string(text))
	return
}


text:
#include "config.h"
#include "CachedResourceRequest.h"

#include "CachedResourceLoader.h"
#include "CrossOriginAccessControl.h"
#include "Document.h"
#include "Element.h"
#include <wtf/NeverDestroyed.h>

namespace WebCore {

CachedResourceRequest::CachedResourceRequest(const ResourceRequest& resourceRequest, const String& charset, Optional<ResourceLoadPriority> priority)
    : m_resourceRequest(resourceRequest)
    , m_charset(charset)
    , m_options(CachedResourceLoader::defaultCachedResourceOptions())
    , m_priority(priority)
    , m_forPreload(false)
    , m_defer(NoDefer)
{
}

CachedResourceRequest::CachedResourceRequest(const ResourceRequest& resourceRequest, const ResourceLoaderOptions& options)
    : m_resourceRequest(resourceRequest)
    , m_options(options)
    , m_forPreload(false)
    , m_defer(NoDefer)
{
}

CachedResourceRequest::CachedResourceRequest(const ResourceRequest& resourceRequest, Optional<ResourceLoadPriority> priority)
    : m_resourceRequest(resourceRequest)
    , m_options(CachedResourceLoader::defaultCachedResourceOptions())
    , m_priority(priority)
    , m_forPreload(false)
    , m_defer(NoDefer)
{
}

CachedResourceRequest::~CachedResourceRequest()
{
}

void CachedResourceRequest::setInitiator(PassRefPtr<Element> element)
{
    ASSERT(!m_initiatorElement && m_initiatorName.isEmpty());
    m_initiatorElement = element;
}

void CachedResourceRequest::setInitiator(const AtomicString& name)
{
    ASSERT(!m_initiatorElement && m_initiatorName.isEmpty());
    m_initiatorName = name;
}

void CachedResourceRequest::setInitiator(DocumentLoader& documentLoader)
{
    m_initiatingDocumentLoader = &documentLoader;
}

const AtomicString& CachedResourceRequest::initiatorName() const
{
    if (m_initiatorElement)
        return m_initiatorElement->localName();
    if (!m_initiatorName.isEmpty())
        return m_initiatorName;

    static NeverDestroyed<AtomicString> defaultName("resource", AtomicString::ConstructFromLiteral);
    return defaultName;
}

void CachedResourceRequest::setAsPotentiallyCrossOrigin(const String& mode, Document& document)
{
    ASSERT(m_options.mode == FetchOptions::Mode::NoCors);
    if (mode.isNull())
        return;
    m_options.mode = FetchOptions::Mode::Cors;
    m_options.credentials = equalLettersIgnoringASCIICase(mode, "use-credentials") ? FetchOptions::Credentials::Include : FetchOptions::Credentials::SameOrigin;
    m_options.setAllowCredentials(equalLettersIgnoringASCIICase(mode, "use-credentials") ? AllowStoredCredentials : DoNotAllowStoredCredentials);

    ASSERT(document.securityOrigin());
    updateRequestForAccessControl(m_resourceRequest, *document.securityOrigin(), m_options.allowCredentials());
}

} // namespace WebCore


text:
Gobblin comes with two tools for better understanding the state of
Gobblin and the jobs executed. These interfaces are early in their
development, will likely change, and have many new features planned. The
two interfaces provided are a command line interface and a GUI,
accessible via a web server. The current state of the interfaces relies
on the [Job Execution History
Store](https://gobblin.readthedocs.io/en/latest/user-guide/Job-Execution-History-Store/),
which must be enabled and running for the interfaces to work.

## CLI
Gobblin offers a command line interface out of the box. To run it, build
and run Gobblin, then run `<code_dir>/bin/gobblin-admin.sh`. You'll
likely want to alias that command, along with any additional Java
options that you need to pass in.
### Commands
#### Jobs
Use `gobblin-admin.sh jobs --help` for more additional help and for a
list of all options provided.

Some common commands include:

|Command
|Result    |
|-----------------------------------------------------------------|----------|
|`gobblin-admin.sh jobs --list`                                   |Lists
distinct job names|
|`gobblin-admin.sh jobs --list --name JobName`                    |Lists
the most recent executions of the given job name|
|`gobblin-admin.sh jobs --details --id job_id`                    |Lists
detailed information about the job execution with the given id|
|`gobblin-admin.sh jobs --properties --<id|name> <job_id|JobName>`|Lists
properties of the job|

#### Tasks
The CLI does not yet support the `tasks` command.

## GUI
The GUI is a lightweight Backbone.js frontend to the Job Execution
History Store.

To enable it, you can set `admin.server.enabled` to true in your configuration file.
The admin web server will be available on port 8000 by default, but this can be changed with
the `admin.server.port` configuration key.


text:
#include "dhcp_client.hpp"

using namespace hls;

void open_dhcp_port(stream<ap_uint<16> >&	openPort,
					stream<bool>&			confirmPortStatus,
					stream<ap_uint<1> >		&portOpen)
{
#pragma HLS PIPELINE II=1
#pragma HLS INLINE off

	static bool odp_listenDone 			= false;
	static bool odp_waitListenStatus 	= false;
	static ap_uint<32> openPortWaitTime = TIME_5S;

	if (openPortWaitTime == 0) {
		if (!odp_listenDone && !odp_waitListenStatus && !openPort.full()) {
			openPort.write(68);
			odp_waitListenStatus = true;
		}
		else if (!confirmPortStatus.empty() && odp_waitListenStatus){
			confirmPortStatus.read(odp_listenDone);
			portOpen.write(1);
		}
	}
	else
		openPortWaitTime--;
}

void receive_message(	stream<udpMetadata>&	dataInMeta,
						stream<axiWord>&		dataIn,
						stream<dhcpReplyMeta>&	metaOut,
						ap_uint<48>				myMacAddress) {
#pragma HLS PIPELINE II=1
#pragma HLS INLINE off

	static bool rm_isReply 			= false;
	static bool rm_correctMac 		= true;
	static bool rm_isDHCP 			= false;
	static ap_uint<6> rm_wordCount 	= 0;
	static dhcpReplyMeta meta;

	axiWord currWord;

	if (!dataIn.empty()) {
		dataIn.read(currWord);
		//std::cout << std::hex << currWord.data << " " << currWord.last << std::endl;
		switch (rm_wordCount) {
		case 0: // Type, HWTYPE, HWLEN, HOPS, ID
			rm_isReply = currWord.data(7, 0) == 0x2;
			meta.identifier = currWord.data(63, 32);
			rm_correctMac = true;
			break;
		case 1: //SECS, FLAGS, ClientIp
			// Do nothing
			//currWord.data[32] == flag
			break;
		case 2: //YourIP, NextServer IP
			meta.assignedIpAddress = currWord.data(31, 0);
			meta.serverAddress = currWord.data(63, 32); //TODO maybe not necessary
			break;
		case 3: //Relay Agent, Client MAC part1
			rm_correctMac = (rm_correctMac && (myMacAddress(31, 0) == currWord.data(63, 32)));
			break;
		case 4:
			// Client Mac Part 2
			rm_correctMac = (rm_correctMac && (myMacAddress(47, 32) == currWord.data(15, 0)));
			break;
		/*case 5: //client mac padding
		case 7:
			//legacy BOOTP
			break;*/
		case 29:
			// Assumption, no Option Overload and DHCP Message Type is first option
			//MAGIC COOKIE
			rm_isDHCP = (MAGIC_COOKIE == currWord.data(63, 32));
			break;
		case 30:
			//Option 53
			if (currWord.data(15, 0) == 0x0135)
				meta.type = currWord.data(23, 16);
			break;
		default:
			// 5-7 legacy BOOTP stuff
			break;
		} //switch
		rm_wordCount++;
		if (currWord.last) {
			rm_wordCount = 0;
			//s Write out metadata
			if (rm_isReply && rm_correctMac && rm_isDHCP)
				metaOut.write(meta);
		}
	} //if

	if (!dataInMeta.empty())
		dataInMeta.read();
}

void send_message(	stream<dhcpRequestMeta>&	metaIn,
					stream<udpMetadata>&		dataOutMeta,
					stream<ap_uint<16> >&		dataOutLength,
					stream<axiWord>&			dataOut,
					ap_uint<48> 				myMacAddress)
{
#pragma HLS PIPELINE II=1
#pragma HLS INLINE off

	static ap_uint<6> sm_wordCount = 0;
	static dhcpRequestMeta meta;
	axiWord sendWord = {0, 0xFF, 0};

	switch (sm_wordCount)
	{
	case 0:
		if (!metaIn.empty())
		{
			metaIn.read(meta);
			sendWord.data(7, 0) = 0x01; //O
			sendWord.data(15, 8) = 0x01; //HTYPE
			sendWord.data(23, 16) = 0x06; //HLEN
			sendWord.data(31, 24) = 0x00; //HOPS
			// identifier
			sendWord.data(63, 32) = meta.identifier;
			dataOut.write(sendWord);
			dataOutMeta.write(udpMetadata(sockaddr_in(0x00000000, 68), sockaddr_in(0xffffffff, 67)));
			dataOutLength.write(300); // 37*8 + 4
			sm_wordCount++;
		}
		break;
	case 1: //secs, flags, CIADDR
		sendWord.data(22, 0) = 0;
		sendWord.data[23] = 0x1; // Broadcast flag
		sendWord.data(63, 24) = 0;
		dataOut.write(sendWord);
		sm_wordCount++;
		break;
	//case 2: //YIADDR, SIADDR
	//case 5: //CHADDR padding + servername
	default: //BOOTP legacy
	//case 5:
	//case 6:
		dataOut.write(sendWord);
		sm_wordCount++;
		break;
	case 3:
		// GIADDR, CHADDR
		sendWord.data(31, 0) = 0;
		sendWord.data(63, 32) = myMacAddress(31, 0);
		dataOut.write(sendWord);
		sm_wordCount++;
		break;
	case 4:
		sendWord.data(15, 0) = myMacAddress(47, 32);
		sendWord.data(63, 16) = 0;
		dataOut.write(sendWord);
		sm_wordCount++;
		break;
	case 29:
		sendWord.data(31, 0) = 0;
		// Magic cookie
		sendWord.data(63, 32) = MAGIC_COOKIE;
		dataOut.write(sendWord);
		sm_wordCount++;
		break;
	case 30:
		// DHCP option 53
		sendWord.data(15, 0) = 0x0135;
		sendWord.data(23, 16) = meta.type;
		if (meta.type == DISCOVER)
		{
			// We are done
			sendWord.data(31, 24) = 0xff;
			sendWord.data(63, 32) = 0;
		}
		else
		{
			// Add DHCP Option 50, len 4, ip add
			sendWord.data(31, 24) = 0x32; //50
			sendWord.data(39, 32) = 0x04;
			sendWord.data(63, 40) = meta.requestedIpAddress(23, 0);
		}
		sm_wordCount++;
		dataOut.write(sendWord);
		break;
	case 31:
		// DHCP Option 50, len 4, ip add
		if (meta.type == REQUEST)
			sendWord.data(7, 0) = meta.requestedIpAddress(31, 24);
		else
			sendWord.data = 0;
		sm_wordCount++;
		dataOut.write(sendWord);
		break;
	case 37:
		// Last padding word, after 64bytes
		sendWord.keep = 0x0f;
		sendWord.last = 1;
		dataOut.write(sendWord);
		sm_wordCount = 0;
		break;
	}//switch
}

void dhcp_fsm(	stream<dhcpReplyMeta>& 		replyMetaIn,
				stream<dhcpRequestMeta>&	requestMetaOut,
				stream<ap_uint<1> >			&portOpen,
				ap_uint<32>&				ipAddressOut,
				ap_uint<1>&					dhcpEnable,
				ap_uint<32>&				inputIpAddress) {
#pragma HLS PIPELINE II=1
#pragma HLS INLINE off

	enum dhcpStateType {PORT_WAIT, INIT, SELECTING, REQUESTING, BOUND};
	static dhcpStateType state = PORT_WAIT;
	static ap_uint<32> randomValue = 0x34aad34b;
	static ap_uint<32> myIdentity = 0;
	static ap_uint<32> myIpAddress = 0;
	static ap_uint<32> IpAddressBuffer = 0;
	static ap_uint<32> time = 100;

	dhcpReplyMeta reply;
	ipAddressOut = myIpAddress;

	switch (state) {
	case PORT_WAIT:
		myIpAddress = inputIpAddress;
		if (!portOpen.empty()) {
			portOpen.read();
			state = INIT;
		}
		break;
	case INIT:
		myIpAddress = inputIpAddress;
		if (dhcpEnable == 1) {
			if (time == 0) {
				myIdentity = randomValue;
				requestMetaOut.write(dhcpRequestMeta(randomValue, DISCOVER));
				randomValue = (randomValue * 8) xor randomValue; // Update randomValue
				time = TIME_5S;
				state = SELECTING;
			}
			else
				time--;
		}
		break;
	case SELECTING:
		if (!replyMetaIn.empty()) {
			replyMetaIn.read(reply);
			if (reply.identifier == myIdentity) {
				if (reply.type == OFFER) {
					IpAddressBuffer = reply.assignedIpAddress;
					requestMetaOut.write(dhcpRequestMeta(myIdentity, REQUEST, reply.assignedIpAddress));
					time = TIME_5S;
					state = REQUESTING;
				}
				else
					state = INIT;
			}
		}
		else { //else we are waiting
			if (time == 0)
				state = INIT;
			else // Decrease time-out value
				time--;
		}
		break;
	case REQUESTING:
		if (!replyMetaIn.empty()) {
			replyMetaIn.read(reply);
			if (reply.identifier == myIdentity) {
				if (reply.type == ACK) {  //TODO check if IP address correct
					myIpAddress = IpAddressBuffer;
					state = BOUND;
				}
				else
					state = INIT;
			}
			//else omit
		}
		else {
			if (time == 0)
				state = INIT;
			else // Decrease time-out value
				time--;
		}
		break;
	case BOUND:
		ipAddressOut = myIpAddress;
		if (!replyMetaIn.empty())
			replyMetaIn.read();
		if (dhcpEnable == 0)
			state = INIT;
		break;
	}
	randomValue++; //Make sure it doesn't get zero
}

void dhcp_client(	stream<ap_uint<16> >&	openPort,
					stream<bool>&			confirmPortStatus,
					//stream<ap_uint<16> >&	realeasePort,
					stream<udpMetadata>&	dataInMeta,
					stream<axiWord>&		dataIn,
					stream<udpMetadata>&	dataOutMeta,
					stream<ap_uint<16> >&	dataOutLength,
					stream<axiWord>&		dataOut,
					ap_uint<1>&				dhcpEnable,
					ap_uint<32>&			inputIpAddress,
					ap_uint<32>&			dhcpIpAddressOut,
					ap_uint<48>&			myMacAddress) {
#pragma HLS DATAFLOW
#pragma HLS INTERFACE ap_ctrl_none port=return

	#pragma HLS resource core=AXI4Stream variable=openPort 		metadata="-bus_bundle m_axis_open_port"
#pragma HLS resource core=AXI4Stream variable=confirmPortStatus metadata="-bus_bundle s_axis_open_port_status"
#pragma HLS resource core=AXI4Stream variable=dataInMeta 		metadata="-bus_bundle s_axis_rx_metadata"
#pragma HLS resource core=AXI4Stream variable=dataIn 			metadata="-bus_bundle s_axis_rx_data"
#pragma HLS DATA_PACK variable=dataInMeta

#pragma HLS resource core=AXI4Stream variable=dataOutMeta 		metadata="-bus_bundle m_axis_tx_metadata"
#pragma HLS resource core=AXI4Stream variable=dataOutLength 	metadata="-bus_bundle m_axis_tx_length"
#pragma HLS resource core=AXI4Stream variable=dataOut 			metadata="-bus_bundle m_axis_tx_data"
#pragma HLS DATA_PACK variable=dataOutMeta

#pragma HLS INTERFACE ap_none register	port=dhcpEnable
#pragma HLS INTERFACE ap_none register	port=dhcpIpAddressOut
#pragma HLS INTERFACE ap_stable			port=myMacAddress
#pragma HLS INTERFACE ap_none register	port=inputIpAddress

	static stream<dhcpReplyMeta>		dhcp_replyMetaFifo("dhcp_replyMetaFifo");
	static stream<dhcpRequestMeta>		dhcp_requestMetaFifo("dhcp_requestMetaFifo");
#pragma HLS stream variable=dhcp_replyMetaFifo depth=4
#pragma HLS stream variable=dhcp_requestMetaFifo depth=4
#pragma HLS DATA_PACK variable=dhcp_replyMetaFifo
#pragma HLS DATA_PACK variable=dhcp_requestMetaFifo
	static stream<ap_uint<1> >		portOpen("portOpen");

	open_dhcp_port(openPort, confirmPortStatus, portOpen);

	receive_message(dataInMeta, dataIn, dhcp_replyMetaFifo, myMacAddress);

	dhcp_fsm(dhcp_replyMetaFifo, dhcp_requestMetaFifo, portOpen, dhcpIpAddressOut, dhcpEnable, inputIpAddress);

	send_message(	dhcp_requestMetaFifo,
					dataOutMeta,
					dataOutLength,
					dataOut, myMacAddress);
}


text:
package com.fuhj.log;

import java.lang.reflect.Method;

import org.springframework.aop.AfterReturningAdvice;
import org.springframework.aop.MethodBeforeAdvice;

public class ServiceLogAdvice implements MethodBeforeAdvice, AfterReturningAdvice {

	@Override
	public void before(Method method, Object[] args, Object target) throws Throwable {
		AppLogger.sysDebug("------------------------------------------------------------");
		StringBuffer buf1 = new StringBuffer();
		buf1.append("METHODBEFORE").append(" ");
		buf1.append(target.getClass().getName()).append(" ");
		buf1.append(method.getName()).append(" ");
		AppLogger.sysDebug(buf1.toString());
		StringBuffer buf2 = new StringBuffer("args: ");
		for (int i = 0; i < args.length; i++) {
			buf2.append("arg").append(i).append(" = ").append(args[i]).append(" ");
		}
		AppLogger.sysDebug(buf2.toString());
	}

	@Override
	public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable {
		StringBuffer buf1 = new StringBuffer();
		buf1.append("AFTERRETURNING").append(" ");
		buf1.append(target.getClass().getName()).append(" ");
		buf1.append(method.getName()).append(" ");
		AppLogger.sysDebug(buf1.toString());
		StringBuffer buf2 = new StringBuffer("returnValue: ");
		buf2.append(returnValue);
		AppLogger.sysDebug(buf2.toString());
		AppLogger.sysDebug("------------------------------------------------------------");
	}
}


text:
namespace webcrypto {

class AlgorithmImplementation;
class Status;

// Retrieves the AlgorithmImplementation applicable for |id|.
//
// If there is no available implementation, then an error is returned, and
// *impl is set to NULL.
//
// Otherwise Success is returned and *impl is set to a non-NULL value. The
// AlgorithmImplementation pointer will remain valid until the program's
// termination.
Status GetAlgorithmImplementation(blink::WebCryptoAlgorithmId id,
                                  const AlgorithmImplementation** impl);

}  // namespace webcrypto

#endif  // COMPONENTS_WEBCRYPTO_ALGORITHM_REGISTRY_H_


text:
<?php
defined('C5_EXECUTE') or die('Access Denied.');

?>

    <a href="<?= $view->action('update') ?>" class="btn btn-default"><?= t('Install/Update Languages') ?>

<?php

if (empty($interfacelocales)) {
    ?>
    <fieldset>
	   <?= t("You don't have any interface languages installed. You must run concrete5 in English.") ?>
    </fieldset>
    <?php
} else {
    ?>
    <form method="post" action="<?= $view->action('save_interface_language') ?>">
        <fieldset>

                <?= $form->label('LANGUAGE_CHOOSE_ON_LOGIN', t('Login')) ?>

                    <?= $form->checkbox('LANGUAGE_CHOOSE_ON_LOGIN', 1, $LANGUAGE_CHOOSE_ON_LOGIN) ?><?= t('Offer choice of language on login.') ?>

                <?= $form->label('SITE_LOCALE', t('Default Language')) ?>

                    <?= $form->select('SITE_LOCALE', $interfacelocales, $SITE_LOCALE) ?>

            <?php $token->output('save_interface_language') ?>
        </fieldset>

                <?= Core::make('helper/concrete/ui')->submit(t('Save'), 'save', 'right', 'btn-primary') ?>

    </form>
    <?php
}

if (isset($mlLink)) {
    ?>

        <?= t(
            'You can configure the site languages in the %s dashboard page.',
            sprintf('%s', h($mlLink[1]), h($mlLink[0]))
        ) ?>

    <?php
}


text:
using System;
using System.Reflection;
using System.Runtime.InteropServices;

[assembly: AssemblyTitle("PokerLeagueManager.Infrastructure.Tests")]
[assembly: AssemblyProduct("PokerLeagueManager.Infrastructure.Tests")]
[assembly: CLSCompliant(true)]
[assembly: Guid("c306ed78-2fd5-47de-81c4-1825d35cd0a5")]


text:
<!DOCTYPE html>

        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <title>@yield('title')</title>

        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">

                    <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
                        Toggle navigation

                    </button>
                    Centaur

Dashboard

                        @if (Sentinel::check() && Sentinel::inRole('administrator'))

Users

Roles

                        @endif

                        @if (Sentinel::check())

{{ Sentinel::getUser()->email }}

Log Out

                        @else

Login

Register

                        @endif

            @include('Centaur::notifications')
            @yield('content')


text:
<?php

namespace Hifone\Http\Controllers\Auth;

use AltThree\Validator\ValidationException;
use Hifone\Commands\Identity\AddIdentityCommand;
use Hifone\Events\User\UserWasAddedEvent;
use Hifone\Events\User\UserWasLoggedinEvent;
use Hifone\Hashing\PasswordHasher;
use Hifone\Http\Controllers\Controller;
use Hifone\Models\Identity;
use Hifone\Models\Provider;
use Hifone\Models\User;
use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;
use Illuminate\Foundation\Auth\ThrottlesLogins;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\View;
use Illuminate\Support\Str;
use Input;
use Laravel\Socialite\Two\InvalidStateException;

class AuthController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Registration & Login Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles the registration of new users, as well as the
    | authentication of existing users. By default, this controller uses
    | a simple trait to add these behaviors. Why don't you explore it?
    |
    */

    use AuthenticatesAndRegistersUsers, ThrottlesLogins;
    //注册后返回主页
    protected $redirectPath = '/';

    protected $hasher;

    public function __construct(PasswordHasher $hasher)
    {
        $this->hasher = $hasher;
        $this->middleware('guest', ['except' => ['logout', 'getLogout']]);
    }

    public function getLogin()
    {
        $providers = Provider::orderBy('created_at', 'desc')->get();

        return $this->view('auth.login')
            ->withCaptcha(route('captcha', ['random' => time()]))
            ->withConnectData(Session::get('connect_data'))
            ->withProviders($providers)
            ->withPageTitle(trans('dashboard.login.login'));
    }

    public function landing()
    {
        return $this->view('auth.landing')
            ->withConnectData(Session::get('connect_data'))
            ->withPageTitle('');
    }

    /**
     * Logs the user in.
     *
     * @return \Illuminate\Http\RedirectResponse
     */
    public function postLogin()
    {
        $loginData = Input::only(['login', 'password', 'verifycode']);
        if (!Config::get('setting.site_captcha_login_disabled')) {
            $verifycode = array_pull($loginData, 'verifycode');
            if ($verifycode != Session::get('phrase')) {
                // instructions if user phrase is good
                return Redirect::to('auth/login')
                ->withInput(Input::except('password'))
                ->withError(trans('hifone.captcha.failure'));
            }
        }
        // Login with username or email.
        $loginKey = Str::contains($loginData['login'], '@') ? 'email' : 'username';
        $loginData[$loginKey] = array_pull($loginData, 'login');
        // Validate login credentials.
        if (Auth::validate($loginData)) {

            // We probably want to add support for "Remember me" here.
            Auth::attempt($loginData, false);

            if (Session::has('connect_data')) {
                $connect_data = Session::get('connect_data');
                dispatch(new AddIdentityCommand(Auth::user()->id, $connect_data));
            }

            event(new UserWasLoggedinEvent(Auth::user()));

            return Redirect::intended('/')
                ->withSuccess(sprintf('%s %s', trans('hifone.awesome'), trans('hifone.login.success')));
        }

        return redirect('/auth/login')
            ->withInput(Input::except('password'))
            ->withError(trans('hifone.login.invalid'));
    }

    public function getRegister()
    {
        $connect_data = Session::get('connect_data');

        return $this->view('auth.register')
            ->withCaptcha(route('captcha', ['random' => time()]))
            ->withConnectData($connect_data)
            ->withPageTitle(trans('dashboard.login.login'));
    }

    public function postRegister()
    {
        // Auto register
        $connect_data = Session::get('connect_data');
        $from = '';
        if ($connect_data && isset($connect_data['extern_uid'])) {
            $registerData = [
                'username' => $connect_data['nickname'].'_'.$connect_data['provider_id'],
                'nickname' => $connect_data['nickname'],
                'password' => $this->hashPassword(str_random(8), ''),
                'email'    => $connect_data['extern_uid'].'@'.$connect_data['provider_id'],
                'salt'     => '',
            ];
            $from = 'provider';
        } else {
            $registerData = Input::only(['username', 'email', 'password', 'password_confirmation', 'verifycode']);

            if ($registerData['verifycode'] != Session::get('phrase') && Config::get('setting.site_captcha_reg_disabled')) {
                return Redirect::to('auth/register')
                    ->withTitle(sprintf('%s %s', trans('hifone.whoops'), trans('dashboard.users.add.failure')))
                    ->withInput(Input::all())
                    ->withErrors([trans('hifone.captcha.failure')]);
            }
        }
        try {
            $user = $this->create($registerData);
        } catch (ValidationException $e) {
            return Redirect::to('auth/register')
                ->withTitle(sprintf('%s %s', trans('hifone.whoops'), trans('dashboard.users.add.failure')))
                ->withInput(Input::all())
                ->withErrors($e->getMessageBag());
        }

        if ($from == 'provider') {
            dispatch(new AddIdentityCommand($user->id, $connect_data));
        }

        event(new UserWasAddedEvent($user));

        Auth::guard($this->getGuard())->login($user);

        return redirect($this->redirectPath());
    }

    /**
     * Create a new user instance after a valid registration.
     *
     * @param array $data
     *
     * @return User
     */
    protected function create(array $data)
    {
        $salt = $this->generateSalt();

        $password = $this->hashPassword($data['password'], $salt);

        $user = User::create([
            'username'     => $data['username'],
            'email'        => $data['email'],
            'salt'         => $salt,
            'password'     => $password,
        ]);

        return $user;
    }

    /**
     * hash user's raw password.
     *
     * @param string $password plain text form of user's password
     * @param string $salt     salt
     *
     * @return string hashed password
     */
    private function hashPassword($password, $salt)
    {
        return $this->hasher->make($password, ['salt' => $salt]);
    }

    /**
     * generate salt for hashing password.
     *
     * @return string
     */
    private function generateSalt()
    {
        return str_random(16);
    }

    public function provider($slug)
    {
        return \Socialite::with($slug)->redirect();
    }

    public function callback($slug)
    {
        if (Input::has('code')) {
            $provider = Provider::where('slug', '=', $slug)->firstOrFail();
            try {
                $extern_user = \Socialite::with($slug)->user();
            } catch (InvalidStateException $e) {
                return Redirect::to('/auth/landing')
                    ->withErrors(['授权失效']);
            }

            //检查是否已经连接过
            $identity = Identity::where('provider_id', '=', $provider->id)->where('extern_uid', '=', $extern_user->id)->first();

            if (is_null($identity)) {
                Session::put('connect_data', ['provider_id' => $provider->id, 'extern_uid' => $extern_user->id, 'nickname' => $extern_user->nickname]);

                return Redirect::to('/auth/landing');
            }
            //已经连接过,找出user_id, 直接登录
            $user = User::find($identity->user_id);

            if (!Auth::check()) {
                Auth::login($user, true);
            }

            return Redirect::to('/')
            ->withSuccess(sprintf('%s %s', trans('hifone.awesome'), trans('hifone.login.success')));
        }
    }

    public function userBanned()
    {
        if (Auth::check() && !Auth::user()->is_banned) {
            return redirect(route('home'));
        }
        //force logout
        Auth::logout();

        return Redirect::to('/');
    }

    // 用户屏蔽
    public function userIsBanned($user)
    {
        return Redirect::route('user-banned');
    }
}