text:
package com.antbrains.wordseg.luceneanalyzer;

/**
 * Represents char[], as a slice (offset + length) into an existing char[].
 *
 * @lucene.internal
 */
public final class CharsRef implements Comparable<CharsRef>, CharSequence {
  private static final char[] EMPTY_ARRAY = new char[0];
  public char[] chars;
  public int offset;
  public int length;

  /**
   * Creates a new {@link CharsRef} initialized an empty array zero-length
   */
  public CharsRef() {
    this(EMPTY_ARRAY, 0, 0);
  }

  /**
   * Creates a new {@link CharsRef} initialized with an array of the given capacity
   */
  public CharsRef(int capacity) {
    chars = new char[capacity];
  }

  /**
   * Creates a new {@link CharsRef} initialized with the given array, offset and length
   */
  public CharsRef(char[] chars, int offset, int length) {
    assert chars != null;
    assert chars.length >= offset + length;
    this.chars = chars;
    this.offset = offset;
    this.length = length;
  }

  /**
   * Creates a new {@link CharsRef} initialized with the given Strings character array
   */
  public CharsRef(String string) {
    this.chars = string.toCharArray();
    this.offset = 0;
    this.length = chars.length;
  }

  /**
   * Creates a new {@link CharsRef} and copies the contents of the source into the new instance.
   *
   * @see #copy(CharsRef)
   */
  public CharsRef(CharsRef other) {
    copy(other);
  }

  @Override
  public Object clone() {
    return new CharsRef(this);
  }

  @Override
  public int hashCode() {
    final int prime = 31;
    int result = 0;
    final int end = offset + length;
    for (int i = offset; i < end; i++) {
      result = prime * result + chars[i];
    }
    return result;
  }

  @Override
  public boolean equals(Object other) {
    if (this == other) {
      return true;
    }

    if (other instanceof CharsRef) {
      return charsEquals((CharsRef) other);
    }

    if (other instanceof CharSequence) {
      final CharSequence seq = (CharSequence) other;
      if (length == seq.length()) {
        int n = length;
        int i = offset;
        int j = 0;
        while (n-- != 0) {
          if (chars[i++] != seq.charAt(j++))
            return false;
        }
        return true;
      }
    }
    return false;
  }

  public boolean charsEquals(CharsRef other) {
    if (length == other.length) {
      int otherUpto = other.offset;
      final char[] otherChars = other.chars;
      final int end = offset + length;
      for (int upto = offset; upto < end; upto++, otherUpto++) {
        if (chars[upto] != otherChars[otherUpto]) {
          return false;
        }
      }
      return true;
    } else {
      return false;
    }
  }

  /** Signed int order comparison */
  public int compareTo(CharsRef other) {
    if (this == other)
      return 0;

    final char[] aChars = this.chars;
    int aUpto = this.offset;
    final char[] bChars = other.chars;
    int bUpto = other.offset;

    final int aStop = aUpto + Math.min(this.length, other.length);

    while (aUpto < aStop) {
      int aInt = aChars[aUpto++];
      int bInt = bChars[bUpto++];
      if (aInt > bInt) {
        return 1;
      } else if (aInt < bInt) {
        return -1;
      }
    }

    // One is a prefix of the other, or, they are equal:
    return this.length - other.length;
  }

  /**
   * Copies the given {@link CharsRef} referenced content into this instance starting at offset 0.
   *
   * @param other
   *          the {@link CharsRef} to copy
   */
  public void copy(CharsRef other) {
    chars = ArrayUtil.grow(chars, other.length);
    System.arraycopy(other.chars, other.offset, chars, 0, other.length);
    length = other.length;
    offset = 0;
  }

  public void grow(int newLength) {
    if (chars.length < newLength) {
      chars = ArrayUtil.grow(chars, newLength);
    }
  }

  /**
   * Copies the given array into this CharsRef starting at offset 0
   */
  public void copy(char[] otherChars, int otherOffset, int otherLength) {
    this.offset = 0;
    append(otherChars, otherOffset, otherLength);
  }

  /**
   * Appends the given array to this CharsRef starting at the current offset
   */
  public void append(char[] otherChars, int otherOffset, int otherLength) {
    grow(this.offset + otherLength);
    System.arraycopy(otherChars, otherOffset, this.chars, this.offset, otherLength);
    this.length = otherLength;
  }

  @Override
  public String toString() {
    return new String(chars, offset, length);
  }

  public int length() {
    return length;
  }

  public char charAt(int index) {
    return chars[offset + index];
  }

  public CharSequence subSequence(int start, int end) {
    return new CharsRef(chars, offset + start, offset + end - 1);
  }
}


text:
import { A } from '@ember/array';
import { computed } from '@ember/object';
import { alias } from '@ember/object/computed';
import Component from '@ember/component';

export default Component.extend({
  tagName: 'div',
  classNames: 'ui field',
  classNameBindings: ['hasError:error', 'fieldClass', 'for', 'required'],

  object: alias('parentView.for'),

  fieldClass: computed('group', {
    get() {
      var isGroup = this.get('group'),
        fieldClass = isGroup ? 'fields' : 'field';

      return fieldClass;
    }
  }),

  hasError: computed('object.errors.[]', {
    get() {
      var _ref = this.get('object.errors');

      return _ref != null ? _ref.has(this.get('for')) : void 0;
    }
  }),

  errors: computed('object.errors.[]', {
    get() {
      if (!this.get('object.errors')) {
        return A();
      }
      return this.get('object.errors')
        .errorsFor(this.get('for'))
        .mapBy('message')[0];
    }
  })
});

redpajama_set_name: RedPajamaGithub


text:
package auth

import (
	"errors"
	"net/http"

	"github.com/goharbor/harbor/src/common/http/modifier"
	"github.com/goharbor/harbor/src/common/secret"
)

// Authorizer is a kind of Modifier used to authorize the requests
type Authorizer modifier.Modifier

// SecretAuthorizer authorizes the requests with the specified secret
type SecretAuthorizer struct {
	secret string
}

// NewSecretAuthorizer returns an instance of SecretAuthorizer
func NewSecretAuthorizer(secret string) *SecretAuthorizer {
	return &SecretAuthorizer{
		secret: secret,
	}
}

// Modify the request by adding secret authentication information
func (s *SecretAuthorizer) Modify(req *http.Request) error {
	if req == nil {
		return errors.New("the request is null")
	}

	return secret.AddToRequest(req, s.secret)
}


text:
// Copyright (c) 2014 The Chromium Embedded Framework Authors. All rights
// reserved. Use of this source code is governed by a BSD-style license that
// can be found in the LICENSE file.

package org.cef.handler;

import org.cef.browser.CefBrowser;
import org.cef.callback.CefContextMenuParams;
import org.cef.callback.CefMenuModel;

/**
 * An abstract adapter class for receiving context menu events.
 * The methods in this class are empty.
 * This class exists as convenience for creating handler objects.
 */
public abstract class CefContextMenuHandlerAdapter implements CefContextMenuHandler {
  @Override
  public void onBeforeContextMenu(CefBrowser browser,
                                  CefContextMenuParams params,
                                  CefMenuModel model) {
  }

  @Override
  public boolean onContextMenuCommand(CefBrowser browser,
                                      CefContextMenuParams params,
                                      int commandId,
                                      int eventFlags) {
    return false;
  }

  @Override
  public void onContextMenuDismissed(CefBrowser browser) {
  }
}


text:
import requests
import json
import sys
sys.path.append('../conn/')
import conn

service = 'vlan'
url = conn.url + 'network/' + service + '/'
auth = conn.auth
headers = conn.headers
payload = {
          "vlan_vint": "vlan0",
          "vlan_pint": "em0",
          "vlan_tag": 0
}

def vlan_get():
  r = requests.get(url, auth = auth)
  result = json.loads(r.text)
  i = 0
  for i in range(0,len(result)):
    print '\n'
    for items in result[i]:
      print items+':', result[i][items]

def vlan_post():
  r = requests.post(url, auth = auth, data = json.dumps(payload), headers = headers)
  result = json.loads(r.text)
  for items in result:
    print items+':', result[items]

def vlan_put():
  id = raw_input('Input id:')+'/'
  r = requests.put(url+id, auth = auth, data = json.dumps(payload), headers = headers)
  result = json.loads(r.text)
  for items in result:
    print items+':', result[items]

def vlan_delete():
  id = raw_input('Input id:')+'/'
  r = requests.delete(url+id, auth = auth)
  print r.status_code

while(1):
  method = raw_input('Input method:')
  if method == 'get':
    vlan_get()
  elif method == 'post':
    vlan_post()
  elif method == 'put':
    vlan_put()
  elif method == 'delete':
    vlan_delete()


text:
package org.apache.struts2;

import java.util.ArrayList;
import java.util.List;

import junit.framework.Assert;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.Result;
import com.opensymphony.xwork2.util.ValueStack;
import com.opensymphony.xwork2.util.logging.Logger;
import com.opensymphony.xwork2.util.logging.LoggerFactory;

/**
 * TestResult
 *
 */
public class TestResult implements Result {

    private static final long serialVersionUID = -4429258122011663164L;

    private static final Logger LOG = LoggerFactory.getLogger(TestResult.class);

    private List expectedValues = new ArrayList();
    private List propertyNames = new ArrayList();

    public void setExpectedValue(int index, String value) {
        expectedValues.set(index, value);
    }

    public void setExpectedValue(String value) {
        expectedValues.add(value);
    }

    public List getExpectedValues() {
        return expectedValues;
    }

    public void setPropertyName(int index, String propertyName) {
        propertyNames.set(index, propertyName);
    }

    public void setPropertyName(String propertyName) {
        propertyNames.add(propertyName);
    }

    public List getPropertyNames() {
        return propertyNames;
    }

    public void execute(ActionInvocation invocation) throws Exception {
        LOG.info("executing TestResult.");

        if ((expectedValues != null) && (expectedValues.size() > 0) && (propertyNames != null) && (propertyNames.size() > 0))
        {
            ValueStack stack = ActionContext.getContext().getValueStack();

            for (int i = 0; i < propertyNames.size(); i++) {
                String propertyName = (String) propertyNames.get(i);
                String expectedValue = null;

                if (i < expectedValues.size()) {
                    expectedValue = (String) expectedValues.get(i);
                }

                String value = (String) stack.findValue(propertyName, String.class);
                Assert.assertEquals(expectedValue, value);
            }
        } else {
            LOG.error("One of expectedValues = " + expectedValues + " and propertyNames = " + propertyNames + " was null or empty.");
            Assert.fail();
        }
    }
}


text:
/*
PdfCatalog.c

Author: Nebojsa Vislavski
Date: 4.7.2008.

Used for writting catalog dictionary in pdf

*/

#include "PdfCatalog.h"
#include "DictionaryObject.h"
#include "NameObject.h"
#include "IndirectReference.h"
#include "PdfOutlines.h"
#include "PdfPages.h"
#include "PdfBaseObject.h"
#include "MemoryManager.h"
#include <stdlib.h>

DLLEXPORT_TEST_FUNCTION struct PdfCatalog* PdfCatalog_Create(struct PdfDocument *document)
{
	struct PdfCatalog *x;
	x = (struct PdfCatalog*)MemoryManager_Alloc(sizeof(struct PdfCatalog));
	PdfCatalog_Init(x, document);
	return x;
}

DLLEXPORT_TEST_FUNCTION void PdfCatalog_Init(struct PdfCatalog *self, struct PdfDocument *document)
{
	PdfBaseObject_Init((struct PdfBaseObject*)self, document);

	self->outlines = PdfOutlines_Create(document);
	self->pages = PdfPages_Create(document);
}

/*
  writes something like this + other catalog properties
  1 0 obj
  <<
  /Type /Catalog
  /Outlines 2 0 R
  /Pages 3 0 R
  >>
  endobj
*/
DLLEXPORT_TEST_FUNCTION void PdfCatalog_Write(struct PdfCatalog *self)
{
	struct DictionaryObject *dict;
	struct NameObject *name;
	struct IndirectReference *ref;

	// write Pages
	PdfPages_Write(self->pages);
	// Write outlines
	PdfOutlines_Write(self->outlines);

	PdfDocument_BeginNewObject((struct PdfBaseObject*)self);
	{
		dict = DictionaryObject_Begin(self->base.document->streamWriter);
		{
			DictionaryObject_WriteKey(dict, "Type");
			name = NameObject_Create(self->base.document->streamWriter, "Catalog");
			NameObject_Write(name);
			NameObject_Destroy(name);

			DictionaryObject_WriteKey(dict, "Outlines");
			ref = IndirectReference_Create(self->base.document->streamWriter, self->outlines->base.objectId, self->outlines->base.generationNumber);
			IndirectReference_Write(ref);
			IndirectReference_Destroy(ref);

			DictionaryObject_WriteKey(dict, "Pages");
			ref = IndirectReference_Create(self->base.document->streamWriter, self->pages->base.objectId, self->pages->base.generationNumber);
			IndirectReference_Write(ref);
			IndirectReference_Destroy(ref);
		}
		DictionaryObject_End(dict);
	}
	PdfDocument_EndObject((struct PdfBaseObject*)self);
}

DLLEXPORT_TEST_FUNCTION void PdfCatalog_Destroy(struct PdfCatalog *self)
{
	PdfPages_Destroy(self->pages);
	PdfOutlines_Destroy(self->outlines);
	MemoryManager_Free(self);
}


text:
package cwl

// Steps represents "steps" field in CWL.
type Steps []Step

// New constructs "Steps" from interface.
func (_ Steps) New(i interface{}) Steps {
	dest := Steps{}
	switch x := i.(type) {
	case []interface{}:
		for _, v := range x {
			s := Step{}.New(v)
			dest = append(dest, s)
		}
	case map[string]interface{}:
		for key, v := range x {
			s := Step{}.New(v)
			s.ID = key
			dest = append(dest, s)
		}
	}
	return dest
}

// Step represents WorkflowStep.
// @see http://www.commonwl.org/v1.0/Workflow.html#WorkflowStep
type Step struct {
	ID            string
	In            StepInputs
	Out           []StepOutput
	Run           Run
	Requirements  []Requirement
	Scatter       []string
	ScatterMethod string
}

// Run `run` accept string | CommandLineTool | ExpressionTool | Workflow
type Run struct {
	Value    string
	Workflow *Root
}

// New constructs "Step" from interface.
func (_ Step) New(i interface{}) Step {
	dest := Step{}
	switch x := i.(type) {
	case map[string]interface{}:
		for key, v := range x {
			switch key {
			case "id":
				dest.ID = v.(string)
			case "run":
				switch x2 := v.(type) {
				case string:
					dest.Run.Value = x2
				case map[string]interface{}:
					dest.Run.Workflow = dest.Run.Workflow.AsStep(v)
				}
			case "in":
				dest.In = StepInput{}.NewList(v)
			case "out":
				dest.Out = StepOutput{}.NewList(v)
			case "requirements":
				dest.Requirements = Requirements{}.New(v)
			case "scatter":
				dest.Scatter = StringArrayable(v)
			case "scatterMethod":
				dest.ScatterMethod = v.(string)
			}
		}
	}
	return dest
}

// Len for sorting
func (steps Steps) Len() int {
	return len(steps)
}

// Less for sorting
func (steps Steps) Less(i, j int) bool {
	return steps[i].ID < steps[j].ID
}

// Swap for sorting
func (steps Steps) Swap(i, j int) {
	steps[i], steps[j] = steps[j], steps[i]
}


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
          package="com.esri.arcgisandroid.sample.spatialoperations">

    <uses-permission android:name="android.permission.INTERNET" />

    <uses-feature
        android:glEsVersion="0x00020000"
        android:required="true" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme">
        <activity
            android:name="com.esri.arcgisandroid.sample.spatialoperations.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>

                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>
    </application>

</manifest>


text:
from __future__ import unicode_literals

from django.db import models, migrations

class Migration(migrations.Migration):

    dependencies = [
        ('browser', '0016_auto_20150402_2302'),
    ]

    operations = [
        migrations.AlterField(
            model_name='rlibrary',
            name='borrower_name',
            field=models.CharField(max_length=60, verbose_name=b'name', blank=True),
            preserve_default=True,
        ),
        migrations.AlterField(
            model_name='rlibrary',
            name='checkout_date',
            field=models.DateTimeField(null=True, verbose_name=b'reserved until/check out appointment', blank=True),
            preserve_default=True,
        ),
        migrations.AlterField(
            model_name='rlibrary',
            name='return_date',
            field=models.DateTimeField(null=True, verbose_name=b'return appointment', blank=True),
            preserve_default=True,
        ),
    ]


text:
<?xml version="1.0" encoding="UTF-8"?><module codename="org.netbeans.core.multitabs">
    <module_version install_time="1396872790732" last="true" origin="installer" specification_version="1.3.3.1">
        <file crc="3018881510" name="config/Modules/org-netbeans-core-multitabs.xml"/>
        <file crc="950518791" name="modules/org-netbeans-core-multitabs.jar"/>
    </module_version>
</module>


text:
package org.springframework.cloud.gcp.data.datastore.core.convert;

import java.beans.beancontext.BeanContextSupport;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Objects;
import java.util.Set;

import org.springframework.util.CollectionUtils;

/**
 * A test entity focused on collections.
 *
 * @author Dmitry Solomakha
 */
public class TestDatastoreItemCollections {
	private List<Integer> intList;

	private ComparableBeanContextSupport beanContext;

	private String[] stringArray;

	private boolean[] boolArray;

	private byte[][] bytes;

	private List<byte[]> listByteArray;

	public TestDatastoreItemCollections(List<Integer> intList, ComparableBeanContextSupport beanContext, String[] stringArray,
			boolean[] boolArray, byte[][] bytes, List<byte[]> listByteArray) {
		this.intList = intList;
		this.beanContext = beanContext;
		this.stringArray = stringArray;
		this.boolArray = boolArray;
		this.bytes = bytes;
		this.listByteArray = listByteArray;
	}

	public List<Integer> getIntList() {
		return this.intList;
	}

	public BeanContextSupport getBeanContext() {
		return this.beanContext;
	}

	public String[] getStringArray() {
		return this.stringArray;
	}

	public boolean[] getBoolArray() {
		return this.boolArray;
	}

	public byte[][] getBytes() {
		return this.bytes;
	}

	public List<byte[]> getListByteArray() {
		return this.listByteArray;
	}

	@Override
	public boolean equals(Object o) {
		if (this == o) {
			return true;
		}
		if (o == null || getClass() != o.getClass()) {
			return false;
		}
		TestDatastoreItemCollections that = (TestDatastoreItemCollections) o;
		return Objects.equals(getIntList(), that.getIntList()) &&
				Objects.equals(getBeanContext(), that.getBeanContext()) &&
				Arrays.equals(getStringArray(), that.getStringArray()) &&
				Arrays.equals(getBoolArray(), that.getBoolArray()) &&
				equal(getBytes(), that.getBytes()) &&
				equal(getListByteArray(), that.getListByteArray());
	}

	@Override
	public int hashCode() {
		int result = Objects.hash(getIntList(), getBeanContext(), getListByteArray());
		result = 31 * result + Arrays.hashCode(getStringArray());
		result = 31 * result + Arrays.hashCode(getBoolArray());
		result = 31 * result + Arrays.hashCode(getBytes());
		return result;
	}

	private List<List<Byte>> arraysToLists(Object[] arrays) {
		List<List<Byte>> result = new ArrayList<>();
		for (Object e : arrays) {
			result.add(CollectionUtils.arrayToList(e));
		}
		return result;
	}

	private boolean equal(Object a, Object b) {
		if (a == null && b == null) {
			return true;
		}
		if (a == null || b == null) {
			return false;
		}

		Object valA = a;
		Object valB = b;
		if (a instanceof List) {
			valA = ((List<byte[]>) a).toArray();
			valB = ((List<byte[]>) b).toArray();
		}
		return arraysToLists((Object[]) valA).equals(arraysToLists((Object[]) valB));
	}

	/**
	 * BeanContextSupport does not provide an equals() implementation.
	 * This subclass overrides {@code equals/hashCode} and keeps a simple list of values
	 * to enable test verification.
	 */
	static class ComparableBeanContextSupport extends BeanContextSupport {
		private Set<Object> values = new HashSet<>();

		@Override
		public boolean add(Object o) {
			this.values.add(o);
			return super.add(o);
		}

		@Override
		public boolean equals(Object o) {
			if (o == null || !(o instanceof ComparableBeanContextSupport)) {
				return false;
			}
			ComparableBeanContextSupport cbcs = (ComparableBeanContextSupport) o;
			return cbcs.values.equals(this.values);
		}

		@Override
		public int hashCode() {
			// Abides by hashCode contract, while being perfectly useless.
			return 1;
		}
	}
}


text:
<?php

namespace Timber\Integrations;

class WPML {

	public function __construct() {
		add_filter('timber/URLHelper/file_system_to_url', array($this, 'file_system_to_url'), 10, 1);
		add_filter('timber/URLHelper/get_content_subdir/home_url', array($this, 'file_system_to_url'), 10, 1);
		add_filter('timber/URLHelper/url_to_file_system/path', array($this, 'file_system_to_url'), 10, 1);

	}

	public function file_system_to_url($url) {
		if ( defined('ICL_LANGUAGE_CODE') ) {
			$url = preg_replace('/\/' . ICL_LANGUAGE_CODE . '/', '', $url);
		}
		return $url;
	}

}


text:
package com.interview.linklist;

/**
 * http://www.geeksforgeeks.org/find-a-triplet-from-three-linked-lists-with-sum-equal-to-a-given-number/
 * Test case
 * empty list
 * list with 0 1 or more nodes
 * negative sum
 * 0 sum
 * positive sum
 */
public class TripletToSumInLinkList {

    public void printTriplet(Node head1, Node head2, Node head3,int sum){
        if(head1 == null || head2 == null || head3 == null){
            return;
        }

        MergeSortLinkList msll = new MergeSortLinkList();
        head2 = msll.sort(head2, true);
        head3 = msll.sort(head3, false);

        while(head1 != null){
            int newSum = sum - head1.data;
            Node tempHead2 = head2;
            Node tempHead3 = head3;
            while(tempHead2 != null && tempHead3 != null){
                if(tempHead2.data + tempHead3.data == newSum){
                    System.out.println(head1.data + " " + tempHead2.data + " " + tempHead3.data);
                    break;
                }
                else if(tempHead2.data + tempHead3.data < newSum){
                    tempHead2 = tempHead2.next;
                }else{
                    tempHead3 = tempHead3.next;
                }
            }
            head1 = head1.next;
        }
    }

    public static void main(String args[]){
        LinkList ll = new LinkList();
        Node head = null;
        head = ll.addNode(1, head);
        head = ll.addNode(8, head);
        head = ll.addNode(-3, head);
        head = ll.addNode(14, head);

        Node head1 = null;
        head1 = ll.addNode(-1, head1);
        head1 = ll.addNode(22, head1);
        head1 = ll.addNode(31, head1);
        head1 = ll.addNode(11, head1);

        Node head2 = null;
        head2 = ll.addNode(5, head2);
        head2 = ll.addNode(7, head2);
        head2 = ll.addNode(3, head2);
        head2 = ll.addNode(1, head2);

        TripletToSumInLinkList tts  = new TripletToSumInLinkList();
        tts.printTriplet(head, head1, head2, 20);
    }
}


text:
@echo off
net user NLogTestUser /delete
net user NLogTestUser BC@57acasd123 /add
exit /b 0


text:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Net;
using System.IO;
using System.Text;
using System.Web.Script.Serialization;
using System.Threading;

namespace BoxTestCSharp
{

    public class Program
    {
        static void Main(string[] args)
        {
            bool bstop = false;
            string boxip = "10.186.81.186";

            Thread t = new Thread(() =>
            {

                while ((!bstop))
                {
                    dynamic result_post = HandleBoxCmd("get_state", false, boxip, 1);

                    JavaScriptSerializer jss = new JavaScriptSerializer();
                    BoxStateObject BoxStateObject = jss.Deserialize<BoxStateObject>(result_post);
                    Console.WriteLine(BoxStateObject.state);

                    dynamic BoxState = jss.Deserialize<object>(result_post);
                    Console.WriteLine(BoxState["state"]);

                    Console.WriteLine(result_post);

                    Thread.Sleep(1000);
                }

            });
            t.Start();

            while (true)
            {
                string result_post = "";
                dynamic input = Console.ReadLine();
                if (input.Equals("!"))
                {
                    bstop = true;
                    t.Join();
                    return;
                }

                if (input.Equals("st"))
                {
                    result_post = HandleBoxCmd("get_state", false, boxip, 1);
                }

                if (input.Equals("in"))
                {
                    result_post = HandleBoxCmd("initialize", false, boxip, 1);
                }

                if (input.Equals("o"))
                {
                    result_post = HandleBoxCmd("open", false, boxip, 1);
                }

                if (input.Equals("cn"))
                {
                    result_post = HandleBoxCmd("close", false, boxip, 1);
                }

                if (input.Equals("cp"))
                {
                    result_post = HandleBoxCmd("close", true, boxip, 1);
                }

                if (input.Equals("en"))
                {
                    result_post = HandleBoxCmd("engage", false, boxip, 1);
                }

                if (input.Equals("res"))
                {
                    result_post = HandleBoxCmd("reset", false, boxip, 1);
                }

                if (input.Equals("dis"))
                {
                    result_post = HandleBoxSetting("disabled", true, boxip, 1);
                }

                if (input.Equals("ena"))
                {
                    result_post = HandleBoxSetting("disabled", false, boxip, 1);
                }

                if (input.Equals("cali"))
                {
                    result_post = HandleBoxSetting("calibrated", true, boxip, 1);
                }

                if (input.Equals("uncali"))
                {
                    result_post = HandleBoxSetting("calibrated", false, boxip, 1);
                }

                if (input.Equals("calreq"))
                {
                    result_post = HandleBoxSetting("calibration_requested", true, boxip, 1);
                }

                if (input.Equals("uncalreq"))
                {
                    result_post = HandleBoxSetting("calibration_requested", false, boxip, 1);
                }

                if (input.Equals("re"))
                {
                    result_post = HandleBoxCmd("get_state", false, boxip, 1);
                    dynamic jss = new JavaScriptSerializer();
                    dynamic BoxState = jss.Deserialize<object>(result_post);
                    result_post = HandleBoxCmd("release", true, BoxState["products"][0]["jlid"], boxip, 1);
                }

                Console.WriteLine(result_post);

            }

        }

        public static string HandleBoxCmd(string cmd, bool withproduct, string jlid, string boxip, int slidenumber)
        {
            BoxCommand commandToBeSent = default(BoxCommand);
            Random rnd = new Random();

            String thejlid = null;
            if ((!withproduct))
            {
                thejlid = "";
            }
            else
            {
                if ((jlid.Equals("")))
                {
                    thejlid = rnd.Next(1000, 100000).ToString();
                }
                else
                {
                    thejlid = jlid;
                }
            }

            ProductInBoxInfo theproduct = new ProductInBoxInfo
            {
                jlid = thejlid,
                test_result = "not_tested"
            };
            commandToBeSent = new BoxCommand
            {
                cmd = cmd,
                products = new ProductInBoxInfo[] { theproduct }
            };
            String response = PostCmd(string.Format("http://{0}/slide{1}/command", boxip, slidenumber.ToString()), commandToBeSent);
            return response;

        }

        public static string HandleBoxCmd(string cmd, bool withproduct, string boxip, int slidenumber)
        {
            return HandleBoxCmd(cmd, withproduct, "", boxip, slidenumber);
        }

        public static string HandleBoxSetting(string SettingName, bool value, string boxip, int slidenumber)
        {

            object commandToBeSent = new
            {
                cmd = "change_setting",
                name = SettingName,
                value = value
            };

            String response = PostCmd(string.Format("http://{0}/slide{1}/command", boxip, slidenumber.ToString()), commandToBeSent);
            return response;

        }

        public static string PostCmd(string postDestination, object objectToSend)
        {
            //Send the message
            var subrequest = (HttpWebRequest)WebRequest.Create(postDestination);
            subrequest.Method = "POST";
            subrequest.Timeout = 4000;

            try
            {
                using (var requestStream = subrequest.GetRequestStream())
                {
                    using (var requestStreamWriter = new System.IO.StreamWriter(requestStream))
                    {
                        JavaScriptSerializer ser = new JavaScriptSerializer();
                        requestStreamWriter.Write(ser.Serialize(objectToSend));
                    }
                }
                using (var response = (HttpWebResponse)subrequest.GetResponse())
                {
                    // todo: consider a more lenient check here?
                    if (response.StatusCode != HttpStatusCode.OK)
                    {
                        Thread.Sleep(1000);
                    }
                    else
                    {
                        Console.WriteLine("command sent ok");
                        string theresponse = "";
                        using (var reader = new StreamReader(response.GetResponseStream()))
                        {
                            theresponse = reader.ReadToEnd().ToString();
                        }
                        return theresponse;

                    }
                }
            }
            catch (System.Net.WebException ex1)
            {

            }
            catch (Exception ex)
            {

            }
            return null;
        }

        public struct BoxStateObject
        {
            public string state;
            public ProductInBoxInfo[] products;
            public string error_message;
            public string error_description;
            public uint message_timestamp;
            public bool disabled;
            public bool calibrated;
            public bool calibration_requested;
        }

        public struct ProductInBoxInfo
        {
            public string jlid;
            public string test_result;
        }

        public struct BoxCommand
        {
            public string cmd;
            public ProductInBoxInfo[] products;
            public string scanner_secret;
        }
    }
}


text:
package modularmachines.client.gui.modules;

import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.entity.player.InventoryPlayer;

import modularmachines.api.IGuiProvider;
import modularmachines.api.modules.IModule;
import modularmachines.client.gui.GuiBase;

public class GuiChestModule extends GuiBase {

	private final IModule module;

	public GuiChestModule(IModule module, InventoryPlayer inventory) {
		super(module.getComponent(IGuiProvider.class), inventory);
		this.module = module;
	}

	@Override
	protected void drawGuiContainerBackgroundLayer(float partialTicks, int mouseX, int mouseY) {
		GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F);
		this.mc.getTextureManager().bindTexture(guiTexture);
		this.drawTexturedModalRect(guiLeft, guiTop, 0, 0, this.xSize, 3 * 18 + 17);
		this.drawTexturedModalRect(guiLeft, guiTop + 3 * 18 + 17, 0, 126, this.xSize, 96);
	}

	@Override
	protected void drawGuiContainerForegroundLayer(int param1, int param2) {
		this.fontRenderer.drawString(module.getData().getDisplayName(), 8, 6, 4210752);
		this.fontRenderer.drawString(player.inventory.getDisplayName().getUnformattedText(), 8, this.ySize - 92, 4210752);
	}

	@Override
	protected String getTextureModID() {
		return "minecraft";
	}

	@Override
	protected String getGuiTexture() {
		return "container/generic_54";
	}
}


text:
var path = require('path');

console.log(__dirname);
console.log(__filename);

console.log(path.parse(__filename));

var objPath = path.parse(__filename);
console.log(objPath.ext);
console.log(path.sep);


text:
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var sassMiddleware = require('node-sass-middleware');

var indexRouter = require('./routes/index');
var adminRouter = require('./routes/admin');
var contentRouter = require('./routes/content');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'hbs');
app.set('view options', { layout: false });

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());

app.use(sassMiddleware({
  src: path.join(__dirname, 'public'),
  dest: path.join(__dirname, 'public'),
  indentedSyntax: true, // true = .sass and false = .scss
  sourceMap: true
}));

app.use(express.static(path.join(__dirname, 'public'), { immutable: true, maxAge: 3600000 }));

app.use('/', indexRouter);
app.use('/admin', adminRouter);
app.use('/content', contentRouter);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;


text:
#安装cocoapods
```sudo gem install cocoapods
pod setup
如果失败,运行下面命令
sudo gem update --system
gem sources -l
gem sources --remove https://rubygems.org/
gem sources -a http://ruby.taobao.org/
https://rubygems.org/   https://ruby.taobao.org/
sudo gem install cocoapods
sudo gem update cocoapods
如果没有权限
sudo gem install -n /usr/local/bin sass
sudo gem install -n /usr/local/bin cocoapods
```
# MyCocoaPods
这是我所有自己上传和使用的cocoapods集合

help http://www.cocoachina.com/ios/20160415/15939.html

error http://www.jianshu.com/p/e5209ac6ce6b

# podspec

```
Pod::Spec.new do |s|
s.name         = "GRBNavigationKit"
s.version      = "0.0.5"
s.summary      = "Yes ,this is my Summary is A short description of KNavigate."
s.frameworks = 'UIKit','Foundation'
s.requires_arc = true
s.platform = :ios
s.ios.deployment_target = '8.0'
s.description  = "this is the description you know ? yes ,so ,what do you want to do?Yes you are right"
s.homepage     = "https://github.com/yangyueguang/MyCocoaPods"
# s.screenshots  = "www.example.com/screenshots_1.gif", "www.example.com/screenshots_2.gif"
s.license      = "MIT"
# s.license      = { :type => "MIT", :file => "FILE_LICENSE" }
s.author             = { "yangyueguang" => "邮箱" }
# Or just: s.author    = ""
# s.authors            = { "" => "" }
# s.social_media_url   = "http://twitter.com/"
# s.platform     = :ios
# s.platform     = :ios, "5.0"
#  When using multiple platforms
# s.ios.deployment_target = "5.0"
# s.osx.deployment_target = "10.7"
# s.watchos.deployment_target = "2.0"
# s.tvos.deployment_target = "9.0"
s.source       = { :git => "https://github.com/yangyueguang/MyCocoaPods.git", :tag => "#{s.version}" }
s.source_files  = "GRBNavigationKit"
#, "GestureNavi/*.{h,m}"
# s.public_header_files = "Classes/**/*.h"
# s.resource  = "icon.png"
# s.resources = "Resources/*.png"
# s.preserve_paths = "FilesToSave", "MoreFilesToSave"
# s.framework  = "SomeFramework"
# s.frameworks = "SomeFramework", "AnotherFramework"
# s.library   = "iconv"
# s.libraries = "iconv", "xml2"
# s.requires_arc = true
# s.xcconfig = { "HEADER_SEARCH_PATHS" => "$(SDKROOT)/usr/include/libxml2" }
# s.dependency "JSONKit", "~> 1.4"
    s.subspec 'JSONKit' do |js|
    js.source_files = 'GRBNavigationKit/JSONKit'
    js.requires_arc = false
    end
    s.subspec 'VRPlayer' do |ss|
    ss.source_files = 'GRBNavigationKit/VRPlayer'
    # ss.public_header_files = 'VRPlayer/*.h'
    ss.ios.frameworks = 'MobileCoreServices'
    end
end
```

#创建github项目=》创建本地podspec文件=》github上release版本=》注册CocoaPods账号=》上传代码到cocoapods=》更新框架版本

```
git clone https://github/xx.git
git add .
git commit -m "建立代码仓库"
git push
git tag 0.0.1
git push --tag //到github上更新release #给源代码打版本标签,与podspec文件中version一致即可
pod spec create name //touch name.podspec
vim name.podspec
echo "3.0" > .swift-version 如果swift版本不对的话s.dependency "SDWebImage", "~> 3.7.1"
pod lib lint name.podspec --allow-warnings
#如果饮用了包涵静态库的.a文件,则需要加上 --use-libraries
#如果遇到simclt问题则使用sudo xcode-select -switch /Applications/Xcode.app/Contents/Developer
pod lib lint --verbose
pod trunk register 邮箱 'yangyueguang' -description='薛超'
pod trunk me
pod spec lint --allow-warnings
pod trunk COMMAND
pod trunk push name.podspec  --allow-warnings
pod repo update
pod search name
```
# 更新内容
```
pod 'XExtension'
pod 'XCarryOn'
pod 'XWechartSDK'
```
# RepositoryBranch
## 这是只克隆一个仓库中的某个文件夹或某个分支到本地进行修改并上传的说明。
```
Desktop super$ mkdir devops
Desktop super$ cd devops/
Desktop super$ git init    #初始化空库 <br>
Desktop super$ git remote add -f origin https://github.com/yangyueguang/RepositoryBranch.git   #拉取remote的all objects信息
```
>\*Updating origin

remote: Counting objects: 70, done.

remote: Compressing objects: 100% (66/66), done.

remote: Total 70 (delta 15), reused 0 (delta 0)

Unpacking objects: 100% (70/70), done.

From https://github.com/yangyueguang/RepositoryBranch

\* [new branch]      master     -> origin/master

```
Desktop super$ git config core.sparsecheckout true   #开启sparse clone
Desktop super$ echo "devops/" >> .git/info/sparse-checkout   #设置需要pull的目录,*表示所有,!表示匹配相反的
Desktop super$ echo "another/sub/tree" >> .git/info/sparse-checkout
Desktop super$ more .git/info/sparse-checkout
Desktop super$ git pull origin master  #更新
```
>From https://github.com/yangyueguang/RepositoryBranch

\* branch            master     -> FETCH_HEAD
```
Desktop super$ git add .
Desktop super$ git commit -m "change"
Desktop super$ git push
```
```

# Swift 版本声明
post_install do |installer|
  installer.pods_project.targets.each do |target|
    if ['LightRoute', 'Kakapo'].include? target.name
      target.build_configurations.each do |config|
        config.build_settings['SWIFT_VERSION'] = '4.0'
        config.build_settings['ONLY_ACTIVE_ARCH'] = 'NO'
      end
      else
      target.build_configurations.each do |config|
        config.build_settings['SWIFT_VERSION'] = '5.0'
        config.build_settings['ONLY_ACTIVE_ARCH'] = 'NO'
      end
    end
  end
end

```


text:
class Node(object):
    def __init__(self, data, p, o=0):
        self._priority = p
        self._order = o
        self._data = data

class P_Queue(object):
    def __init__(self):
        self._list = []
        self._counter = 0
        self._size = 0

    def insert(self, data=None, p=0):
        new_node = Node(data, p, self._counter)
        self._counter += 1
        self._list.append(new_node)
        child = parent = self._size
        self._size += 1
        while parent > 0:
            parent = (child-1)//2
            if self._compare(child, parent):
                break
            self._swap(child, parent)
            child = parent

    def pop(self):
        if not self._size:
            raise IndexError("This is an empty Queue, yo.")

        val = self._list[0]
        self._list[0] = self._list[-1]
        self._list.pop()
        self._size -= 1
        parent, left, right = 0, 1, 2

        while right < self._size:
            if (self._compare(left, parent) and
                self._compare(right, parent)):
                break

            if self._compare(right, left):
                self._swap(parent, left)
                parent = left

            else:
                self._swap(parent, right)
                parent = right

            left = parent*2 + 1
            right = left + 1

        if left < self._size:
            if self._compare(parent, left):
                self._swap(parent, left)

        return val

    def peek(self):
        return self._list[0]

    def _swap(self, x, y):
        self._list[x], self._list[y] = self._list[y], self._list[x]

    def _compare(self, x, y):
        if self._list[x]._priority > self._list[y]._priority:
            return True
        elif self._list[x]._priority == self._list[y]._priority:
            return True if self._list[x]._order < self._list[y]._order else False
        else:
            return False


text:
void task_drive_controller(void *p)
{
	Motor m(GPIO_NUM_26, 1800, 3400);
	ServoSteering s(GPIO_NUM_1, 2000, 4100); //TODO

	CarState *state;
	state = CarState::getInstance();

	for (;;)
	{
		if (state->startmodule_state == eStartModuleState::RUNNING) //Startmodule
		{
			//TODO: Analyze the sensordata

			//TODO: Tell motor and steering what to do
			m.SetSpeed(50);
			//s.SetAngle(0);
		}

		vTaskDelay(1000/portTICK_PERIOD_MS);  //Yield CPU time
	}

	vTaskDelete(NULL);
}


text:
<?php

namespace AppBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity(repositoryClass="AppBundle\Repository\EmailTemplateRepository")
 * @ORM\Table(name="email_templates",
 *     indexes={
 *          @ORM\Index(name="createdAt", columns={"created_at"})
 *     }
 * )
 * Class EmailTemplate
 * @package AppBundle\Entity
 */
class EmailTemplate
{
    /**
     * @ORM\Id
     * @ORM\GeneratedValue
     * @ORM\Column(type="integer")
     * @var
     */
    private $id;

    /**
     * @ORM\Column(type="string")
     * @var
     */
    private $name;

    /**
     * @ORM\Column(type="string", unique=true)
     * @var
     */
    private $slug;

    /**
     * @ORM\Column(type="string")
     * @var
     */
    private $subject;

    /**
     * @ORM\Column(type="text")
     * @var
     */
    private $content;

    /**
     * @ORM\Column(type="datetime")
     * @var
     */
    private $createdAt;

    public function __construct()
    {
        $this->createdAt = new \DateTime();
    }

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

    /**
     * @param mixed $id
     */
    public function setId($id)
    {
        $this->id = $id;
    }

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

    /**
     * @param mixed $name
     */
    public function setName($name)
    {
        $this->name = $name;
    }

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

    /**
     * @param mixed $slug
     */
    public function setSlug($slug)
    {
        $this->slug = $slug;
    }

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

    /**
     * @param mixed $subject
     */
    public function setSubject($subject)
    {
        $this->subject = $subject;
    }

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

    /**
     * @param mixed $content
     */
    public function setContent($content)
    {
        $this->content = $content;
    }

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

    /**
     * @param mixed $createdAt
     */
    public function setCreatedAt($createdAt)
    {
        $this->createdAt = $createdAt;
    }
}


text:
require 'rubygems'
require 'httparty'
require 'digest/md5'
require 'cgi'
require "curb"
require 'xmlsimple'

$:.unshift(File.dirname(__FILE__))
require 'sevenload/base'
require 'sevenload/auth'
require 'sevenload/upload'
require 'sevenload/item'

module Sevenload

end


text:
// Copyright 2009 the Sputnik authors.  All rights reserved.
/**
 * The length property of parseFloat has the attribute ReadOnly
 *
 * @path ch15/15.1/15.1.2/15.1.2.3/S15.1.2.3_A7.3.js
 * @description Checking if varying the length property fails
 * @noStrict
 */

//CHECK#1
var x = parseFloat.length;
parseFloat.length = Infinity;
if (parseFloat.length !== x) {
  $ERROR('#1: x = parseFloat.length; parseFloat.length = Infinity; parseFloat.length === x. Actual: ' + (parseFloat.length));
}


text:
/*
Script: MultipleOpenAccordion.js

Creates a Mootools Fx.Accordion that allows the user to open more than one element.

License:
	http://www.clientcide.com/wiki/cnet-libraries#license
*/
var MultipleOpenAccordion = new Class({
	Implements: [Options, Events, Chain],
	options: {
		togglers: [],
		elements: [],
		openAll: false,
		firstElementsOpen: [0],
		fixedHeight: false,
		fixedWidth: false,
		height: true,
		opacity: true,
		width: false
//	onActive: $empty,
//	onBackground: $empty
	},
	togglers: [],
	elements: [],
	initialize: function(options){
		var args = Array.link(arguments, {options: Object.type, elements: Array.type});
		this.setOptions(args.options);
		elements = $$(this.options.elements);
		$$(this.options.togglers).each(function(toggler, idx){
			this.addSection(toggler, elements[idx], idx);
		}, this);
		if (this.togglers.length) {
			if (this.options.openAll) this.showAll();
			else this.toggleSections(this.options.firstElementsOpen, false, true);
		}
		this.openSections = this.showSections.bind(this);
		this.closeSections = this.hideSections.bind(this);
	},
	addSection: function(toggler, element){
		toggler = document.id(toggler);
		element = document.id(element);
		var test = this.togglers.contains(toggler);
		var len = this.togglers.length;
		this.togglers.include(toggler);
		this.elements.include(element);
		var idx = this.togglers.indexOf(toggler);
		toggler.addEvent('click', this.toggleSection.bind(this, idx));
		var mode;
		if (this.options.height && this.options.width) mode = "both";
		else mode = (this.options.height)?"vertical":"horizontal";
		element.store('reveal', new Fx.Reveal(element, {
			transitionOpacity: this.options.opacity,
			mode: mode,
			heightOverride: this.options.fixedHeight,
			widthOverride: this.options.fixedWidth
		}));
		return this;
	},
	onComplete: function(idx, callChain){
		this.fireEvent(this.elements[idx].isDisplayed()?'onActive':'onBackground', [this.togglers[idx], this.elements[idx]]);
		this.callChain();
		return this;
	},
	showSection: function(idx, useFx){
		this.toggleSection(idx, useFx, true);
	},
	hideSection: function(idx, useFx){
		this.toggleSection(idx, useFx, false);
	},
	toggleSection: function(idx, useFx, show, callChain){
		var method = show?'reveal':$defined(show)?'dissolve':'toggle';
		callChain = $pick(callChain, true);
		var el = this.elements[idx];
		if ($pick(useFx, true)) {
			el.retrieve('reveal')[method]().chain(
				this.onComplete.bind(this, [idx, callChain])
			);
		} else {
				if (method == "toggle") el.togglek();
				else el[method == "reveal"?'show':'hide']();
				this.onComplete(idx, callChain);
		}
		return this;
	},
	toggleAll: function(useFx, show){
		var method = show?'reveal':$chk(show)?'disolve':'toggle';
		var last = this.elements.getLast();
		this.elements.each(function(el, idx){
			this.toggleSection(idx, useFx, show, el == last);
		}, this);
		return this;
	},
	toggleSections: function(sections, useFx, show) {
		last = sections.getLast();
		this.elements.each(function(el,idx){
			this.toggleSection(idx, useFx, sections.contains(idx)?show:!show, idx == last);
		}, this);
		return this;
	},
	showSections: function(sections, useFx){
		sections.each(function(i){
			this.showSection(i, useFx);
		}, this);
	},
	hideSections: function(sections, useFx){
		sections.each(function(i){
			this.hideSection(i, useFx);
		}, this);
	},
	showAll: function(useFx){
		return this.toggleAll(useFx, true);
	},
	hideAll: function(useFx){
		return this.toggleAll(useFx, false);
	}
});


text:
layout: post
title: "Add natural language understanding to your bot - Part 2"
subtitle: "This blog post is about adding natural language understanding to your bot. Language Understanding (LUIS) is a cloud-based API service that helps you to recognize the intent of user input and better direct the conversation flow. In the previous post I configured LUIS and in this post I will explain how we can use the LUIS service in a Bot Application."
date: 2020-11-05 00:00:00
categories: [Azure,BotFramework,LUIS]
tags: [Azure,BotFramework,LUIS]
author: "Anuraj"
---
This blog post is about adding natural language understanding to your bot. Language Understanding (LUIS) is a cloud-based API service that helps you to recognize the intent of user input and better direct the conversation flow. In the previous post I configured LUIS and in this post I will explain how we can use the LUIS service in a Bot Application.

I am using Visual Studio 2019, and I have created an Bot from the EchoBot template. Next we need to integrate LUIS app to the Bot. To do that first we need to add the reference of `Microsoft.Bot.Builder.Ai.LUIS` package. Once it is added, we need to implement `IRecognizer` interface, which helps you to interact with the LUIS application.

Here is the code for IRecognizer implementation.

{% highlight CSharp %}
public class NotesRecognizer : IRecognizer
{
    private readonly LuisRecognizer _recognizer;

    public NotesRecognizer(IConfiguration configuration)
    {
        var luisIsConfigured = !string.IsNullOrEmpty(configuration["LuisAppId"]) &&
            !string.IsNullOrEmpty(configuration["LuisAPIKey"]) &&
            !string.IsNullOrEmpty(configuration["LuisAPIHostName"]);
        if (luisIsConfigured)
        {
            var luisApplication = new LuisApplication(
                configuration["LuisAppId"],
                configuration["LuisAPIKey"],
                "https://" + configuration["LuisAPIHostName"]);
            var recognizerOptions = new LuisRecognizerOptionsV3(luisApplication)
            {
                PredictionOptions = new LuisV3.LuisPredictionOptions
                {
                    IncludeInstanceData = true,
                }
            };

            _recognizer = new LuisRecognizer(recognizerOptions);
        }
    }
    public virtual bool IsConfigured => _recognizer != null;

    public virtual async Task<RecognizerResult> RecognizeAsync(ITurnContext turnContext,
        CancellationToken cancellationToken)
        => await _recognizer.RecognizeAsync(turnContext, cancellationToken);

    public virtual async Task<T> RecognizeAsync<T>(ITurnContext turnContext, CancellationToken cancellationToken)
        where T : IRecognizerConvert, new()
        => await _recognizer.RecognizeAsync<T>(turnContext, cancellationToken);
}
{% endhighlight %}

Next you need to inject this to the controllers and bots using the ASP.NET Core dependency injection service. To do this I am modifying the `Startup.cs` class and adding following code.

{% highlight CSharp %}
public void ConfigureServices(IServiceCollection services)
{
    services.AddControllers().AddNewtonsoftJson();

    // Create the Bot Framework Adapter with error handling enabled.
    services.AddSingleton<IBotFrameworkHttpAdapter, AdapterWithErrorHandler>();
    services.AddTransient(typeof(NotesRecognizer));
    // Create the bot as a transient. In this case the ASP Controller is expecting an IBot.
    services.AddTransient<IBot, EchoBot>();
}
{% endhighlight %}

If you notice the NotesRecognizer implementation, there is `RecognizeAsync` generic implementation which accepts type of `IRecognizerConvert` - this implementation will help us to get the intents and entities from the user input. There is a tool called `LUISGen` - LUISGen is a tool for generating a strongly typed C# class or typescript interface to make consuming LUIS output easier. So first we need to install the LUISGen - it is a dotnet tool - `dotnet tool install -g LUISGen`. Once the tool is installed, open the LUIS Portal, select the app from the dashboard and choose `Export` menu, and choose `Export as JSON`

![Export JSON from LUIS]({{ site.url }}{{ site.baseurl }}/assets/images/2020/11/luis_data_export_as_json.png)

It will open the JSON data in a new tab. Save it to your local folder - I created a folder called `CognitiveModels` in the Bot project and I saved it there. Next open powershell or command line window. And run the following command - `luisgen .\notes.json -cs NotesBot.NotesRecognizerConvert` - this command will converts the JSON to C# class.

Next you need to add the following entries in the appsettings.json file - `LuisAppId`, `LuisAPIKey` and `LuisAPIHostName`. You can get these values from LUIS portal.

Finally we need to modify the code in the Bot Application. I added a Constructor so that I can access the `NotesRecognizer` service. And in the `OnMessageActivityAsync` method, I am checking whether it is configured or not. And if configured, get the result from the `NotesRecognizer`. And from the result I am selecting the top intent and executing it. Here is my implementation.

{% highlight CSharp %}
protected override async Task OnMessageActivityAsync(ITurnContext<IMessageActivity> turnContext,
    CancellationToken cancellationToken)
{
    if (!_notesRecognizer.IsConfigured)
    {
        await turnContext.SendActivityAsync(
            MessageFactory.Text("NOTE: LUIS is not configured. To enable all capabilities, add 'LuisAppId', " +
            "'LuisAPIKey' and 'LuisAPIHostName' to the appsettings.json file.", inputHint: InputHints.IgnoringInput), cancellationToken);
    }
    var luisResult = await _notesRecognizer.RecognizeAsync<NotesRecognizerConvert>(turnContext, cancellationToken);
    switch (luisResult.TopIntent().intent)
    {
        case NotesRecognizerConvert.Intent.Note_AddToNote:
            break;
        case NotesRecognizerConvert.Intent.Note_ChangeTitle:
            break;
        case NotesRecognizerConvert.Intent.Note_Clear:
            break;
        case NotesRecognizerConvert.Intent.Note_Close:
            break;
        case NotesRecognizerConvert.Intent.Note_Create:
            break;
        case NotesRecognizerConvert.Intent.Note_Delete:
            break;
        case NotesRecognizerConvert.Intent.Note_Open:
            break;
        case NotesRecognizerConvert.Intent.Note_ReadAloud:
            break;
        case NotesRecognizerConvert.Intent.Note_RemoveSentence:
            break;
        case NotesRecognizerConvert.Intent.None:
        default:
            break;
    }
}
{% endhighlight %}

To get the entities you can access the `luisResult.Entities` object. From which you can access properties like `Note_Text` and `Note_Title` etc.

In this post we explored how to integrate LUIS application to Bot application. Also we explored how to generate C# or Typescript code using `LUISGen` tool.

Happy Programming :)


text:
package glib.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class SystemUtils {
	public static String executeCommand(final String command) {

        StringBuilder output = new StringBuilder();

        Process p;
        try {
            p = Runtime.getRuntime().exec(command);
            p.waitFor();
            InputStreamReader i = new InputStreamReader(p.getInputStream());
            BufferedReader reader =
                new BufferedReader(i);

            String line;
            while ((line = reader.readLine())!= null) {
                    output.append(line).append("\n");
                    System.out.println(line);
            }

            i.close();
            reader.close();
        } catch (IOException e) {
                e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return output.toString();
    }

	public static boolean isMac(){
        return System.getProperty("os.name").toLowerCase().contains("mac");
    }

    public static boolean isWindows(){
        return System.getProperty("os.name").toLowerCase().contains("win");
    }

    public static int numberCPU(){
        return Runtime.getRuntime().availableProcessors();
    }
}


text:
package de.tudarmstadt.ukp.jwktl.parser.ru.wikokit.base.wikt.multi.ru;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import de.tudarmstadt.ukp.jwktl.parser.ru.wikokit.base.wikipedia.language.LanguageType;
import de.tudarmstadt.ukp.jwktl.parser.ru.wikokit.base.wikipedia.text.WikiParser;
import de.tudarmstadt.ukp.jwktl.parser.ru.wikokit.base.wikipedia.util.StringUtilRegular;
import de.tudarmstadt.ukp.jwktl.parser.ru.wikokit.base.wikt.constant.POS;
import de.tudarmstadt.ukp.jwktl.parser.ru.wikokit.base.wikt.util.LangText;
import de.tudarmstadt.ukp.jwktl.parser.ru.wikokit.base.wikt.util.POSText;
//import wikt.constant.POSType;
//import wikt.multi.ru.POSTypeRu;

/** Splits text to fragments related to different parts of speech (POS).
 * POS is basically a level 2 header in Russian Wiktionary, e.g. for "roast":
 * ==roast I==
 * ...
 * ==roast II==
 *
 * (and a level 3 in English Wiktionary: ===Verb===)
 *
 * see http://ru.wiktionary.org/wiki/%D0%92%D0%B8%D0%BA%D0%B8%D1%81%D0%BB%D0%BE%D0%B2%D0%B0%D1%80%D1%8C:%D0%A7%D0%B0%D1%81%D1%82%D0%B8_%D1%80%D0%B5%D1%87%D0%B8
 *      http://ru.wiktionary.org/wiki/Викисловарь:Части речи
 *
 * see http://ru.wiktionary.org/wiki/Викисловарь:Правила оформления статей
 */
public class WPOSRu {

    private final static POSText[] NULL_POS_TEXT_ARRAY = new POSText[0];

    /** start of the POS block,
     * current: ==word I==
     * old: == Существительное I ==
     * it can absent...
     */
    private final static Pattern ptrn_2nd_level = Pattern.compile(  // Vim: ^==\s*\([^=]\+\)\s*==\s*\Z
            //"(?m)^\\s*==");
            "(?m)^==\\s*([^=]+?)\\s*==\\s*");
            // "\\A==\\s*([^=]+)\\s*==\\s*\\Z");

    /** start of the POS block,
     * {{заголовок|be|add=I}}
     * it can absent...
     */
    private final static Pattern ptrn_title_add_template = Pattern.compile(
       // Vim: ^{{заголовок|\([^|]\+\)|add=[^}]\+}}\Z
            // ^{{заголовок|\([^|]\+\)|add=[^}]\+}}\Z

            //"(?m)^\\s*==");
            //"(?m)^==\\s*([^=]+?)\\s*==\\s*");

            //"(?m)^\\Q{{заголовок|\\E([^|]+?)\\Q|add=\\E([^}]+?)\\}\\}\\s*\\Z"); // -
            //"(?m)^\\Q{{заголовок|\\E([^|]+?)\\Q|add=\\E([^}]{2,9})\\s*\\Z"); // -
              "(?m)^\\Q{{заголовок|\\E([^|]+?)\\Q|add=\\E([^}]{1,4})\\s*"); // ?  1-4 = len(I,..,VIII,..)
            //"(?m)^\\Q{{заголовок|\\E([^|]+?)\\Q|add=\\E([^}]{2,9})"); // +
            // "\\A==\\s*([^=]+)\\s*==\\s*\\Z");

// "\\{\\{-([-_a-zA-Z]{2,9})-(?:\\}\\}|\\|.*?\\}\\})|\\Q{{заголовок|\\E([-_a-zA-Z]{2,9})(?:\\}\\}|\\|add=\\}\\})"

    /** start of the POS block,
     * {{заголовок|add=I}}
     * it can absent...
     */
    private final static Pattern ptrn_title_add_template_without_lang = Pattern.compile(
            "(?m)^\\Q{{заголовок|add=\\E([^}]{1,4})\\s*"); // ?  1-4 = len(I,..,VIII,..)

    /** Gets first two letter after ==Морфологические и синтаксические свойства==
     * e.g. "{{" or "Су"ществительное, or "Гл"агол...
     */
    private final static Pattern ptrn_morpho_then_2letters = Pattern.compile(
            "===\\s*Морфологические и синтаксические свойства\\s*===\\s*\\n\\s*(..)");
            //"===\\s*Морфологические и синтаксические свойства\\s*==="); +
            //"\\A===\\s*Морфологические и синтаксические свойства\\s*===\\s*\\n\\s*(..)");

    /** Gets true, if str is known header, e.g. "References",
     * but it's not a part of speech name, e.g. "Verb".
     */
    public static boolean isSecondLevelHeaderWordNotPOS (String str)
    {
        if(str.equalsIgnoreCase("Ссылки"))
            return true;

        return false;
    }

    /** page_title - word which are described in this article 'text'
     * @param lt .text will be parsed and splitted,
     *           .lang is not using now, may be in future...
     *
     * 1) Split the following text to "lead I" and "leat II"
     * 2) Extracts part of speech "гл" from "lead II"
     *

     * == lead I ==
     * English text1
     * == lead II==
     * ===Морфологические и синтаксические свойства==="
     * {{гл en reg|lead}}";

     *
     * todo isPOSHeader() (remove acce'nt -> accent) or guessPOS
     */
    public static POSText[] splitToPOSSections (
            String      page_title,
            LangText    lt)
    {
        String  pos_title = "";
        if(null == lt.text || 0 == lt.text.length()) {
            return NULL_POS_TEXT_ARRAY;
        }

        Matcher m = ptrn_2nd_level.matcher(lt.text.toString());
        boolean b_next = m.find();

        if(b_next && m.groupCount() > 0 && isSecondLevelHeaderWordNotPOS(m.group(1)))
            b_next = false; // it's usual header, e.g. "Links", not a == Verb I ==

        if(!b_next) {   // check: "{{заголовок|sq|add=I}}")
            POSText[] pp = splitToPOSWithTitleAddParameter(page_title, lt);
            if(pp.length > 0)
                return pp;

                        // there is only one ==Second level header== in this language in this word
            POSText[] pos_section_alone = new POSText[1];
            pos_section_alone[0] = guessPOS(lt.text);
            return pos_section_alone;
        }
                                                                // there are more than one POS in this language in this word
        List<POSText> pos_sections = new ArrayList<POSText>();  // result will be stored to
        StringBuffer current_pos_section = new StringBuffer();

        int start, end; // "<start> == Verb I == ... <end> == Verb II ==" position of POS block in the lt.text

        start = 0;
        pos_title = WikiParser.removeAcuteAccent(new StringBuffer(m.group(1)), LanguageType.ru).toString();
        b_next = m.find();
        if(b_next)
            end = m.start();
        else {
            end = 0;    // there is only one POS block, e.g. ==Verb I==, it is a little strange ...
            System.out.println("Warning: there is only one POS block, e.g. ==Verb I== for the word '" + page_title + "' with language code '" + lt.getLanguage().toString() + "' in WPOSRu.splitToPOSSections()");
        }

        while(b_next) {
            current_pos_section.append(lt.text.substring(start, end));

            POS p = guessPOSWith2ndLevelHeader(page_title, pos_title, current_pos_section);
            if(null != p) { // OK. It's POS header, though it's possible that p=unknown :(
                POSText pt = new POSText(p, current_pos_section.toString());
                current_pos_section.setLength(0);
                pos_sections.add(pt);

            } else {
                // null, if this is another 2nd level header, e.g. Bibliography or References
                current_pos_section.append(""); // +??? this Bibliography text
                // todo ...
            }

            // variant I:  \1==page_title+"I", "II", ... "VIII"
            // variant II: \1==Verb|Noun|... (In Russian)
            pos_title = WikiParser.removeAcuteAccent(new StringBuffer(m.group(1)), LanguageType.ru).toString();

            b_next = m.find();
            if(b_next) {
                start = end;
                end = m.start();
            }
        }

        current_pos_section.append(lt.text.substring(end)); // last POS section

        POS p = guessPOSWith2ndLevelHeader(page_title, pos_title, current_pos_section);
        if(null != p) { // OK. It's last POS header, though it's possible that p=unknown :(
            POSText pt = new POSText(p, current_pos_section.toString());
            current_pos_section.setLength(0);
            pos_sections.add(pt);
        }

        return pos_sections.toArray(NULL_POS_TEXT_ARRAY);
    }

    /** Checks whether the language code XX is equals to lt.lang.
     *
     * @param page_title word which are described in this article 'text'
     * @param lt .text will be parsed and splitted,
     *           .lang is not using now, may be in future...
     * @param add_lang_code language code XX in {{заголовок|XX|add=..}}
     */
    private static boolean isValidLanguageCode (
            String      page_title,
            LangText    lt,
            String      add_lang_code)
    {
        // template {{заголовок|add=II}} can be without language code
        if(add_lang_code.startsWith("add="))
            return true;

        if(null == add_lang_code
                || add_lang_code.length() < 2
                || !LanguageType.has(add_lang_code)) {
                // i.e. skip the whole block POS if the first lang code is unknown

            if (null == add_lang_code)
                System.out.println("Error: null language code in {{заголовок|lang_code|add=..}} for the word '" + page_title + "' in WPOSRu.splitToPOSWithTitleAddParameter()");
            else
                System.out.println("Error: unknown language code '" + add_lang_code + "' in {{заголовок|lang_code|add=..}} for the word '" + page_title + "' in WPOSRu.splitToPOSWithTitleAddParameter()");
            return false;
        }

        LanguageType add_lang_type = LanguageType.get(add_lang_code);

        if(add_lang_type != lt.getLanguage()) {
            System.out.println("Error: language code '" + add_lang_code + "' != '"+ lt.getLanguage().toString() +"' (in {{заголовок|YY|add=..}} and {{-XX-}}) for the word '" + page_title + "' in WPOSRu.splitToPOSWithTitleAddParameter()");
            return false;
        }

        return true;
    }

    /** Splits to blocks of text which describe different part of speech.
     *
     * page_title - word which are described in this article 'text'
     * @param lt .text will be parsed and splitted,
     *           .lang is not using now, may be in future...
     *
     * 1) Splits the following text to "заголовок|...|add=I" and "заголовок|...|add=II"
     * 2) Extracts part of speech (e.g. "сущ" i.e. "noun")
     *

     * {{заголовок|be|add=I}}
     * === Морфологические и синтаксические свойства ===
     * {{сущ be m|слоги={{по-слогам|шах}}|}}
     *
     * {{заголовок|be|add=II}}
     * === Морфологические и синтаксические свойства ===
     * {{сущ be m|слоги={{по-слогам|}}|}}

     */
    private static POSText[] splitToPOSWithTitleAddParameter (
            String      page_title,
            LangText    lt)
    {
        Matcher m;
        String lt_text = lt.text.toString();
        boolean lang_code_presented;

        if(lt_text.contains("{{заголовок|add=")) {
            m = ptrn_title_add_template_without_lang.matcher( lt_text );
            lang_code_presented = false;
        } else {
            m = ptrn_title_add_template.matcher( lt_text );
            lang_code_presented = true;
        }

        boolean b_next = m.find();

        if(!b_next) // there is no POS delimiter "{{заголовок|...|add=I}}"
            return NULL_POS_TEXT_ARRAY;

        List<POSText> pos_sections = new ArrayList<POSText>();  // result will be stored to
        StringBuffer current_pos_section = new StringBuffer();

        int start, end; // "<start> {{заголовок|...|add=I}} ...
                        //    <end> {{заголовок|...|add=II}}" position of POS block in the lt.text

        if(lang_code_presented && !isValidLanguageCode(page_title, lt, m.group(1)))
            return NULL_POS_TEXT_ARRAY;

        start = 0;
        b_next = m.find();
        if(b_next)
            end = m.start();
        else {
            end = 0;    // there is only one POS block, it is a little strange ...
            System.out.println("Warning: there is only one POS block, e.g. {{заголовок|...|add=I}} for the word '" + page_title + "' with language code  '" + lt.getLanguage().toString() + "' in WPOSRu.splitToPOSSections()");
        }

        while(b_next) {
            current_pos_section.append(lt.text.substring(start, end));

            POSText pt = guessPOS (current_pos_section);

            if(null != pt.getPOSType()) { // OK. It's POS header, though it's possible that p=unknown :(
                pos_sections.add(pt);
                current_pos_section.setLength(0);

            } else {
                // null, if this is another 2nd level header, e.g. Bibliography or References
                current_pos_section.append(""); // +??? this Bibliography text
                // todo ...
            }

            // variant I:  \1==page_title+"I", "II", ... "VIII"
            // variant II: \1==Verb|Noun|... (In Russian)
            //pos_title = WikiParser.removeAcuteAccent(new StringBuffer(m.group(1)), LanguageType.ru).toString();

            b_next = m.find();
            if(b_next) {
                start = end;
                end = m.start();
            }
        }

        current_pos_section.append(lt.text.substring(end)); // last POS section

        POSText pt = guessPOS (current_pos_section);
        if(null != pt.getPOSType()) { // OK. It's last POS header, though it's possible that p=unknown :(
            current_pos_section.setLength(0);
            pos_sections.add(pt);
        }

        return pos_sections.toArray(NULL_POS_TEXT_ARRAY);
    }

    /** The POS should be extracted from the texts, e.g.

     * noun:
     * ===Морфологические и синтаксические свойства===
     * {{сущ en|слоги=lead|lead|leads}}
     *
     * verb:
     * ===Морфологические и синтаксические свойства===
     * {{гл ru 4b-ся
     * {{гл ru 8b/b^
     * {{гл ru 5c'^-т
     *
     * adjective:
     * ===Морфологические и синтаксические свойства===
     * {{прил ru 1*a
     *
     * adverb:
     * ===Морфологические и синтаксические свойства===
     *
     * {{adv ru|слоги={{по-слогам|ра|но|ва́|то}}|или=предикатив|или-кат=предикативы|}}
     *
     * {{adv-ru|
     * Наречие, неизменяемое.
     *
     * Old formatting
     *
     *  ===Морфологические и синтаксические свойства===
     *  {{СущМужНеодуш1c(1)
     *  {{СущЖенНеодуш8a
     *  Существительное, ...
     *
     * {{прил ia}}
     *
     * {{парадигма-рус  // old formatting (>500, < 1000 pages)
     * |шаблон=Гл11b/c
     * {{Гл1a

     */
    public static POSText guessPOS (StringBuffer text)
    {
        POS p_type = POS.unknown;

        if(null == text || 0 == text.length()) {
            return new POSText(p_type, "");
        }

        Matcher m = ptrn_morpho_then_2letters.matcher(text.toString());
        boolean b = m.find();
        if(b) {
            String two_letters = m.group(1);

            if(two_letters.equalsIgnoreCase("{{")) {
                // if \1=="{{" then get first letters till space
                // substring started after the symbol "{{"
                //String pos_name = StringUtilRegular.getLettersTillSpace(text.substring(m.end())).toLowerCase();
                String pos_name = StringUtilRegular.getLettersTillSpaceHyphenOrPipe(text.substring(m.end())).toLowerCase();
                if(POSTemplateRu.has(pos_name)) {
                    p_type = checkIfSuchPOSExist(pos_name);
                } /*else {
                    // old template of POS with hyphen, e.g. "{{adv-ru|}} instead of {{adv ru|}}, or Мс-п6b
                    pos_name = StringUtilRegular.getLettersTillHyphen(text.substring(m.end())).toLowerCase();
                    if(POSTypeRu.has(pos_name)) {
                        p_type = POSTypeRu.get(pos_name);
                    }
                }
            } else {
                // else get two_letters + the first Word
                // todo
                // ....*/
            }
        } else {
            if(isPhrasePOS(text))
                p_type = POS.phrase;
        }

        return new POSText(p_type, new StringBuffer(text));
    }

    /** Checks whether the text describes a phrase. It is true if the text
     * contains something like:
     *

     * === Тип и синтаксические свойства сочетания ===
     * {{phrase|
     * |тип=фразема
     * }}
     *

     * @param text
     * @return
     */
    private static boolean isPhrasePOS (StringBuffer text)
    {
        return text.toString().contains("{{phrase");
    }

    public static POS checkIfSuchPOSExist(String pos_name) {
    	for (int idx = 0; idx < pos_name.length(); idx++)
    		if (" |}-".indexOf(pos_name.charAt(idx)) >= 0) {
    			pos_name = pos_name.substring(0, idx);
    			break;
    		}
    	if (POSTemplateRu.has(pos_name))
    		return POSTemplateRu.get(pos_name);
    	// POS may exist in the pos_name as a substring. isPOSin() - checks wheather POS is in the pos_name
    	else
    		return POSTemplateRu.isPOSIn(pos_name.toLowerCase());

    }

    /** The POS should be extracted from the text.
     * @return POS, e.g. POS.verb for "== Verb =="
     * @return POS.unknown if text contains "== Word I ==" or "== Word II =="
     * (without additional POS data, e.g. "verb").
     * @return else null
     *
     * Example of text.

     * noun:
     * == bar II ==
     * ===Морфологические и синтаксические свойства===
     * {{сущ en|nom-sg=bar|слоги=bar}}
     *
     * adjective:
     * == round I ==
     * ===Морфологические и синтаксические свойства===
     * {{прил en|round|слоги=round}}
     *
     * adverb (old style for "fast"):
     * ==Наречие==
     * {{нар en|fast}}
     *
     * adverb (very old style for DE "fast")
     * fast
     * Наречие
     * ==Произношение==
     * {{transcription|fɑst}}
     * ==Значение==
     * [[почти]]
     *

     *
     * @param page_title    word, name of the article, e.g. "lead"
     * @param pos_title     extracted 2nd level title, e.g. "lead I", "lead II", or "Adverb" (old style)
     */
    public static POS guessPOSWith2ndLevelHeader (String page_title,String pos_title, StringBuffer text)
    {
        POSText pt = guessPOS (text);

        if(POS.unknown != pt.getPOSType() || null == text || 0 == text.length()) {
            return pt.getPOSType();
        }

        // compare pos_title with POSType
        pos_title = pos_title.toLowerCase();
        if( POSTemplateRu.has(pos_title)) {
            return POSTemplateRu.get(pos_title);
        }

        // get first word without number, e.g. ==Verb I== -> "Verb"
        String pos_name = StringUtilRegular.getLettersTillSpace(pos_title);
        if( POSTemplateRu.has(pos_name)) {
            return POSTemplateRu.get(pos_name);
        }

        if(page_title.equalsIgnoreCase(pos_name)) { // It's POS because, e.g. "round I" == "round" + "I", but it's unknown POS
            return POS.unknown;
        }

        // takes one by one second-level-headers (first word, e.g. Noun for "Noun I", compare with POS
        /*Matcher m = ptrn_2nd_level.matcher(text.toString());

        while(m.find()) {
           String s = m.group(1);   // header 2nd level
            if( POSTypeRu.has(s)) {
                return POSTypeRu.get(s);
            }
        }*/

        return null;
    }

}


text:
CXX = C:\Strawberry\64\c\bin\g++.exe
CXXFLAGS ?= -g -Wall -W -ansi # -pedantic
LDFLAGS ?=
PATH = C:\tools\unxutils\wbin
SED = C:\tools\unxutils\wbin\sed.exe
MV = C:\tools\unxutils\wbin\mv.exe
RM = C:\tools\unxutils\wbin\rm.exe

.SUFFIXES: .o .cpp

lib = libUnitTest++.a
test = TestUnitTest++

src = src/AssertException.cpp \
	src/Test.cpp \
	src/Checks.cpp \
	src/TestRunner.cpp \
	src/TestResults.cpp \
	src/TestReporter.cpp \
	src/TestReporterStdout.cpp \
	src/ReportAssert.cpp \
	src/TestList.cpp \
	src/TimeConstraint.cpp \
	src/TestDetails.cpp \
	src/MemoryOutStream.cpp \
	src/DeferredTestReporter.cpp \
	src/DeferredTestResult.cpp \
	src/XmlTestReporter.cpp \
	src/CurrentTest.cpp

ifeq ($(MSYSTEM), MINGW32)
  src += src/Win32/TimeHelpers.cpp
else
  src += src/Posix/SignalTranslator.cpp \
	src/Posix/TimeHelpers.cpp
endif

test_src = src/tests/Main.cpp \
	src/tests/TestAssertHandler.cpp \
	src/tests/TestChecks.cpp \
	src/tests/TestUnitTest++.cpp \
	src/tests/TestTest.cpp \
	src/tests/TestTestResults.cpp \
	src/tests/TestTestRunner.cpp \
	src/tests/TestCheckMacros.cpp \
	src/tests/TestTestList.cpp \
	src/tests/TestTestMacros.cpp \
	src/tests/TestTimeConstraint.cpp \
	src/tests/TestTimeConstraintMacro.cpp \
	src/tests/TestMemoryOutStream.cpp \
	src/tests/TestDeferredTestReporter.cpp \
	src/tests/TestXmlTestReporter.cpp \
	src/tests/TestCurrentTest.cpp

objects = $(patsubst %.cpp, %.o, $(src))
test_objects = $(patsubst %.cpp, %.o, $(test_src))
dependencies = $(subst .o,.d,$(objects))
test_dependencies = $(subst .o,.d,$(test_objects))

define make-depend
  $(CXX) $(CXXFLAGS) -M $1 | \
  $(SED) -e 's,\($(notdir $2)\) *:,$(dir $2)\1: ,' > $3.tmp
  $(SED) -e 's/#.*//' \
      -e 's/^[^:]*: *//' \
      -e 's/ *\\$$//' \
      -e '/^$$/ d' \
      -e 's/$$/ :/' $3.tmp >> $3.tmp
  $(MV) $3.tmp $3
endef

all: $(test)

$(lib): $(objects)
	@echo Creating $(lib) library...
	@ar cr $(lib) $(objects)

$(test): $(lib) $(test_objects)
	@echo Linking $(test)...
	@$(CXX) $(LDFLAGS) -o $(test) $(test_objects) $(lib)
	@echo Running unit tests...
	@./$(test)

clean:
	-@$(RM) $(objects) $(test_objects) $(dependencies) $(test_dependencies) $(test) $(lib) 2> /dev/null

%.o : %.cpp
	@echo $<
	@$(call make-depend,$<,$@,$(subst .o,.d,$@))
	@$(CXX) $(CXXFLAGS) -c $< -o $(patsubst %.cpp, %.o, $<)

ifneq "$(MAKECMDGOALS)" "clean"
-include $(dependencies)
-include $(test_dependencies)
endif


text:
namespace chrome {

namespace {

#if defined(OS_WIN)
// This is the minimum version of google update that is required for deferred
// crash uploads to work.
const char kMinUpdateVersion[] = "1.3.21.115";
#endif

}  // namespace

ChromeBreakpadClient::ChromeBreakpadClient() {}

ChromeBreakpadClient::~ChromeBreakpadClient() {}

#if defined(OS_WIN)
bool ChromeBreakpadClient::GetAlternativeCrashDumpLocation(
    base::FilePath* crash_dir) {
  // By setting the BREAKPAD_DUMP_LOCATION environment variable, an alternate
  // location to write breakpad crash dumps can be set.
  scoped_ptr<base::Environment> env(base::Environment::Create());
  std::string alternate_crash_dump_location;
  if (env->GetVar("BREAKPAD_DUMP_LOCATION", &alternate_crash_dump_location)) {
    *crash_dir = base::FilePath::FromUTF8Unsafe(alternate_crash_dump_location);
    return true;
  }

  return false;
}

void ChromeBreakpadClient::GetProductNameAndVersion(
    const base::FilePath& exe_path,
    base::string16* product_name,
    base::string16* version,
    base::string16* special_build,
    base::string16* channel_name) {
  DCHECK(product_name);
  DCHECK(version);
  DCHECK(special_build);
  DCHECK(channel_name);

  scoped_ptr<FileVersionInfo> version_info(
      FileVersionInfo::CreateFileVersionInfo(exe_path));

  if (version_info.get()) {
    // Get the information from the file.
    *version = version_info->product_version();
    if (!version_info->is_official_build())
      version->append(base::ASCIIToUTF16("-devel"));

    const CommandLine& command = *CommandLine::ForCurrentProcess();
    if (command.HasSwitch(switches::kChromeFrame)) {
      *product_name = base::ASCIIToUTF16("ChromeFrame");
    } else {
      *product_name = version_info->product_short_name();
    }

    *special_build = version_info->special_build();
  } else {
    // No version info found. Make up the values.
    *product_name = base::ASCIIToUTF16("Chrome");
    *version = base::ASCIIToUTF16("0.0.0.0-devel");
  }

  std::wstring channel_string;
  GoogleUpdateSettings::GetChromeChannelAndModifiers(
      !GetIsPerUserInstall(exe_path), &channel_string);
  *channel_name = base::WideToUTF16(channel_string);
}

bool ChromeBreakpadClient::ShouldShowRestartDialog(base::string16* title,
                                                   base::string16* message,
                                                   bool* is_rtl_locale) {
  scoped_ptr<base::Environment> env(base::Environment::Create());
  if (!env->HasVar(env_vars::kShowRestart) ||
      !env->HasVar(env_vars::kRestartInfo)) {
    return false;
  }

  std::string restart_info;
  env->GetVar(env_vars::kRestartInfo, &restart_info);

  // The CHROME_RESTART var contains the dialog strings separated by '|'.
  // See ChromeBrowserMainPartsWin::PrepareRestartOnCrashEnviroment()
  // for details.
  std::vector<std::string> dlg_strings;
  base::SplitString(restart_info, '|', &dlg_strings);

  if (dlg_strings.size() < 3)
    return false;

  *title = base::ASCIIToUTF16(dlg_strings[0]);
  *message = base::ASCIIToUTF16(dlg_strings[1]);
  *is_rtl_locale = dlg_strings[2] == env_vars::kRtlLocale;
  return true;
}

bool ChromeBreakpadClient::AboutToRestart() {
  scoped_ptr<base::Environment> env(base::Environment::Create());
  if (!env->HasVar(env_vars::kRestartInfo))
    return false;

  env->SetVar(env_vars::kShowRestart, "1");
  return true;
}

base::string16 ChromeBreakpadClient::GetCrashGUID() {
  std::wstring guid;
  GoogleUpdateSettings::GetMetricsId(&guid);
  return base::WideToUTF16(guid);
}

bool ChromeBreakpadClient::GetDeferredUploadsSupported(
    bool is_per_user_install) {
  Version update_version = GoogleUpdateSettings::GetGoogleUpdateVersion(
      !is_per_user_install);
  if (!update_version.IsValid() ||
      update_version.IsOlderThan(std::string(kMinUpdateVersion)))
    return false;

  return true;
}

bool ChromeBreakpadClient::GetIsPerUserInstall(const base::FilePath& exe_path) {
  return InstallUtil::IsPerUserInstall(exe_path.value().c_str());
}

bool ChromeBreakpadClient::GetShouldDumpLargerDumps(bool is_per_user_install) {
  base::string16 channel_name(base::WideToUTF16(
      GoogleUpdateSettings::GetChromeChannel(!is_per_user_install)));

  // Capture more detail in crash dumps for beta and dev channel builds.
  if (channel_name == base::ASCIIToUTF16("dev") ||
      channel_name == base::ASCIIToUTF16("beta") ||
      channel_name == GoogleChromeSxSDistribution::ChannelName())
    return true;
  return false;
}

int ChromeBreakpadClient::GetResultCodeRespawnFailed() {
  return chrome::RESULT_CODE_RESPAWN_FAILED;
}
#endif

#if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_IOS)
void ChromeBreakpadClient::GetProductNameAndVersion(std::string* product_name,
                                                    std::string* version) {
  DCHECK(product_name);
  DCHECK(version);
#if defined(OS_ANDROID)
  *product_name = "Chrome_Android";
#elif defined(OS_CHROMEOS)
  *product_name = "Chrome_ChromeOS";
#else  // OS_LINUX
#if !defined(ADDRESS_SANITIZER)
  *product_name = "Chrome_Linux";
#else
  *product_name = "Chrome_Linux_ASan";
#endif
#endif

  *version = PRODUCT_VERSION;
}

base::FilePath ChromeBreakpadClient::GetReporterLogFilename() {
  return base::FilePath(CrashUploadList::kReporterLogFilename);
}
#endif

bool ChromeBreakpadClient::GetCrashDumpLocation(base::FilePath* crash_dir) {
  // By setting the BREAKPAD_DUMP_LOCATION environment variable, an alternate
  // location to write breakpad crash dumps can be set.
  scoped_ptr<base::Environment> env(base::Environment::Create());
  std::string alternate_crash_dump_location;
  if (env->GetVar("BREAKPAD_DUMP_LOCATION", &alternate_crash_dump_location)) {
    base::FilePath crash_dumps_dir_path =
        base::FilePath::FromUTF8Unsafe(alternate_crash_dump_location);
    PathService::Override(chrome::DIR_CRASH_DUMPS, crash_dumps_dir_path);
  }

  return PathService::Get(chrome::DIR_CRASH_DUMPS, crash_dir);
}

#if defined(OS_POSIX)
void ChromeBreakpadClient::SetDumpWithoutCrashingFunction(void (*function)()) {
  logging::SetDumpWithoutCrashingFunction(function);
}
#endif

size_t ChromeBreakpadClient::RegisterCrashKeys() {
  return crash_keys::RegisterChromeCrashKeys();
}

bool ChromeBreakpadClient::IsRunningUnattended() {
  scoped_ptr<base::Environment> env(base::Environment::Create());
  return env->HasVar(env_vars::kHeadless);
}

#if defined(OS_WIN) || defined(OS_MACOSX)
bool ChromeBreakpadClient::GetCollectStatsConsent() {
  return GoogleUpdateSettings::GetCollectStatsConsent();
}
#endif

#if defined(OS_ANDROID)
int ChromeBreakpadClient::GetAndroidMinidumpDescriptor() {
  return kAndroidMinidumpDescriptor;
}
#endif

}  // namespace chrome


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="initial-scale=1,user-scalable=no,maximum-scale=1,width=device-width">
    <meta name="mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="theme-color" content="#000000">
    <meta name="description" content="bikeablebrews web map of good beer locations off the Mt. Vernon Trail">
    <meta name="author" content="David Todd">
    <title>BikeableBrews</title>

    <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Lato%7COswald:400">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/leaflet/0.7.7/leaflet.css">
    <link rel="stylesheet" href="https://api.tiles.mapbox.com/mapbox.js/plugins/leaflet-markercluster/v0.4.0/MarkerCluster.css">
    <link rel="stylesheet" href="https://api.tiles.mapbox.com/mapbox.js/plugins/leaflet-markercluster/v0.4.0/MarkerCluster.Default.css">
    <link rel="stylesheet" href="https://api.tiles.mapbox.com/mapbox.js/plugins/leaflet-locatecontrol/v0.43.0/L.Control.Locate.css">
    <link rel="stylesheet" href="assets/leaflet-groupedlayercontrol/leaflet.groupedlayercontrol.css">
    <link rel="stylesheet" href="assets/css/app.css">

    <link rel="apple-touch-icon" sizes="76x76" href="assets/img/favicon-76.png">
    <link rel="apple-touch-icon" sizes="120x120" href="assets/img/favicon-120.png">
    <link rel="apple-touch-icon" sizes="152x152" href="assets/img/favicon-152.png">
    <link rel="icon" sizes="196x196" href="assets/img/favicon-196.png">
    <link rel="icon" type="image/x-icon" href="assets/img/favicon.ico">

            BikeableBrews

          <form class="navbar-form navbar-right" role="search">

                <input id="searchbox" type="text" placeholder="Search" class="form-control">

          </form>

  About

                Tools

  Zoom To Full Extent

  Show Legend

  Places

Places
              <button type="button" class="btn btn-xs btn-default pull-right" id="sidebar-hide-btn"></button>

                  <input type="text" class="form-control search" placeholder="Filter" />

                  <button type="button" class="btn btn-primary pull-right sort" data-sort="feature-name" id="sort-btn">  Sort</button>

                    Icon

                    Name

                    Chevron

            <button class="close" type="button" data-dismiss="modal" aria-hidden="true">×</button>

  Welcome to BikeableBrews.com!

 About the project

 Contact us

 Disclaimer

                 Metadata

Trail

 Places

Bikeablebrews.com is a guide for Custis, Fairfax County Parkway, Mount Vernon, and Washington & Old Dominion (W&OD) trail users searching for craft brew refreshment along their walk, run, or ride. Bikeablebrews has identified 92 craft brew establishments, including 23 breweries, brewpubs, and brewery-affiliated venues located close to the trails. All establishments featured here have a substantial craft beer menu and serve beer on the premises. Most have several taps.

Current trail maps include Custis, Fairfax County Parkway, Mt. Vernon, and the W&OD.

The data provided on this site is for informational and planning purposes only.

Absolutely no accuracy or completeness guarantee is implied or intended. All information on this map is subject to such variations and corrections as might result from a complete title search and/or accurate field survey.

For all map inquiries, contact DT.

For general inquiries, contact thirstyman@bikeablebrews.com

Additional places can be proposed on the Github repository issue here.

Mt. Vernon Trail data was hand traced by DT using satellite imagery.

Place data researched and provided by Bob McArthur.  Last updated 07-31-2017.

            <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

            <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

Map Legend

A brewery will have this icon:

Other locations will have this icon:

Clusters of Places at various densities look like this:

6

13

187

            <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

            <button class="close" type="button" data-dismiss="modal" aria-hidden="true">×</button>

            <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

            <button class="close" type="button" data-dismiss="modal" aria-hidden="true">×</button>

              Developed by DT


text:
@implementation GPPaymentRequest

@end


text:
package hex.genmodel;

import java.io.*;
import java.net.URL;
import java.util.HashMap;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

/**
 * Factory class for vending MojoReaderBackend object that can be used to load MOJOs from different data sources.
 *
 *
This class provides convenience methods for loading MOJOs from files, URLs (this includes classpath resources)
 * and also from a generic InputStream source.

 *
 *
User needs to make a choice of a Caching Strategy for MOJO sources that are not file based.
 * Available caching strategies:

 *

 *
MEMORY: (decompressed) content of the MOJO will be cached in memory, this should be suitable for most cases
 *  (for very large models please make sure that your application has enough memory to hold the unpacked MOJO)

 *
DISK: MOJO is cached in a temporary file on disk, recommended for very large models

 *

 *
 *
Example of using MojoReaderBackendFactory to read a MOJO from a classpath resource:

 *
 *

 * {@code
 *   public class ExampleApp {
 *     public static void main(String[] args) throws Exception {
 *       URL mojoURL = ExampleApp.class.getResource("/com/company/mojo.zip");
 *       MojoReaderBackend reader = MojoReaderBackendFactory.createReaderBackend(mojoURL, CachingStrategy.MEMORY);
 *       MojoModel model = ModelMojoReader.readFrom(reader);
 *       EasyPredictModelWrapper modelWrapper = new EasyPredictModelWrapper(model);
 *       RowData testRow = new RowData();
 *         for (int i = 0; i < args.length; i++)
 *           testRow.put("C"+i, Double.valueOf(args[i]));
 *       RegressionModelPrediction prediction = (RegressionModelPrediction) modelWrapper.predict(testRow);
 *       System.out.println("Prediction: " + prediction.value);
 *     }
 *   }
 * }
 *

 */
public class MojoReaderBackendFactory {

  public enum CachingStrategy { MEMORY, DISK }

  public static MojoReaderBackend createReaderBackend(String filename) throws IOException {
    return createReaderBackend(new File(filename));
  }

  public static MojoReaderBackend createReaderBackend(File file) throws IOException {
    if (file.isFile())
      return new ZipfileMojoReaderBackend(file.getPath());
    else if (file.isDirectory())
      return new FolderMojoReaderBackend(file.getPath());
    else
      throw new IOException("Invalid file specification: " + file);
  }

  public static MojoReaderBackend createReaderBackend(URL url, CachingStrategy cachingStrategy) throws IOException {
    try (InputStream is = url.openStream()) {
      return createReaderBackend(is, cachingStrategy);
    }
  }

  public static MojoReaderBackend createReaderBackend(InputStream inputStream, CachingStrategy cachingStrategy) throws IOException {
    switch (cachingStrategy) {
      case MEMORY:
        return createInMemoryReaderBackend(inputStream);
      case DISK:
        return createTempFileReaderBackend(inputStream);
    }
    throw new IllegalStateException("Unexpected caching strategy: " + cachingStrategy);
  }

  private static MojoReaderBackend createInMemoryReaderBackend(InputStream inputStream) throws IOException {
    HashMap<String, byte[]> content = new HashMap<>();
    ZipInputStream zis = new ZipInputStream(inputStream);
    try {
      ZipEntry entry;
      while ((entry = zis.getNextEntry()) != null) {
        if (entry.getSize() > Integer.MAX_VALUE)
          throw new IOException("File too large: " + entry.getName());
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        copyStream(zis, os);
        content.put(entry.getName(), os.toByteArray());
      }
      zis.close();
    } finally {
      closeQuietly(zis);
    }
    return new InMemoryMojoReaderBackend(content);
  }

  private static MojoReaderBackend createTempFileReaderBackend(InputStream inputStream) throws IOException {
    File tmpFile = File.createTempFile("h2o-mojo", ".zip");
    tmpFile.deleteOnExit(); // register delete on exit hook (in case tmp reader doesn't do the job)
    FileOutputStream fos = new FileOutputStream(tmpFile);
    try {
      copyStream(inputStream, fos);
      fos.close();
    } catch (IOException e) {
      closeQuietly(fos); // Windows won't let us delete an open file
      if (! tmpFile.delete())
        e = new IOException(e.getMessage() + " [Note: temp file " + tmpFile + " not deleted]", e);
      throw e;
    } finally {
      closeQuietly(fos);
    }
    return new TmpMojoReaderBackend(tmpFile);
  }

  private static void closeQuietly(Closeable c) {
    if (c != null)
      try {
        c.close();
      } catch (IOException e) {
        // intentionally ignore exception
      }
  }

  private static void copyStream(InputStream source, OutputStream target) throws IOException {
    byte[] buffer = new byte[8 * 1024];
    while (true) {
      int len = source.read(buffer);
      if (len == -1)
        break;
      target.write(buffer, 0, len);
    }
  }

}


text:
<?php

namespace Omnipay\Payone\Message;

/**
 * Shop Authorize Response for the Client API
 */

use Omnipay\Common\Message\RedirectResponseInterface;

class ShopClientCompleteAuthorizeResponse extends AbstractResponse implements RedirectResponseInterface
{
    public function getData()
    {
        return $this->data;
    }

    public function getTransactionReference()
    {
        return $this->getDataItem('txid');
    }

    /**
     * The raw status code.
     * Values: APPROVED / REDIRECT / ERROR / PENDING
     */
    public function getStatus()
    {
        return $this->getDataItem('status');
    }

    /**
     * The numeric error code, set only when the status is ERROR
     */
    public function getCode()
    {
        return $this->getDataItem('errorcode');
    }

    public function getDebtorId()
    {
        return $this->getDataItem('userid');
    }

    public function getMessage()
    {
        return $this->getDataItem('errormessage');
    }

    public function getCustomerMessage()
    {
        return $this->getDataItem('customermessage');
    }

    public function getAvs()
    {
        return $this->getDataItem('protect_result_avs');
    }

    /**
     * Set if status is REDIRECT
     */
    public function getRedirectUrl()
    {
        return $this->getDataItem('redirecturl');
    }

    /**
     * 3D Secure is always POST to an end bank, but GET for PAYONE since the
     * 3D Secure forms get wrapped by PAYONE.
     * Note: the application will only need to perform the redirect if an AJAX
     * return has been requested.
     */
    public function getRedirectMethod()
    {
        return 'GET';
    }

    /**
     * There is no redirect data - it is all in the URL.
     */
    public function getRedirectData()
    {
        return [];
    }

    public function isRedirect()
    {
        return $this->getStatus() === static::STATUS_REDIRECT;
    }

    public function isSuccessful()
    {
        return $this->getStatus() === static::STATUS_APPROVED
            || $this->getStatus() === static::STATUS_PENDING;
    }
}


text:
package com.hourglassapps.persist;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;

import com.hourglassapps.util.Converter;
import com.hourglassapps.util.Log;

public class Trail<C> {
	private final static String TAG=Trail.class.getName();

	private final List<C> mTrail=new ArrayList<>();
	private final Path mPartialDir;

	public Trail(Path pPartialDir) {
		mPartialDir=pPartialDir;
	}

	public void add(C pSource) {
		mTrail.add(pSource);
	}

	public void clear() {
		mTrail.clear();
	}

	public void save(Path pDest) throws IOException {
		Log.i(TAG, Log.esc("trail file: "+mPartialDir.resolve(AbstractFilesJournal.META_PREFIX+pDest.getFileName().toString()).toString()));
		try(PrintWriter out=
				new PrintWriter(new BufferedWriter(
						new FileWriter(mPartialDir.resolve(AbstractFilesJournal.META_PREFIX+pDest.getFileName().toString()).toString())))) {
			for(C source: mTrail) {
				out.println(source);
			}
		}
	}

	public Trail(Path pTrailPath, Converter<String,C> pParser) throws IOException {
		this(pTrailPath.getParent());
		List<String> urls=new ArrayList<>();
		try (BufferedReader reader=new BufferedReader(new FileReader(pTrailPath.toFile()))) {
			String line=reader.readLine();
			while(line!=null) {
				add(pParser.convert(line));
				line=reader.readLine();
			}
		}
	}

	public C url(Path pPath) {
		String filename=pPath.getFileName().toString();
		int extIdx=filename.lastIndexOf('.');
		String numberPart;
		if(extIdx==-1) {
			numberPart=filename;
		} else {
			numberPart=filename.substring(0, extIdx);
		}
		int urlIdx=Integer.parseInt(numberPart);
		assert(urlIdx>0);
		return mTrail.get(urlIdx-1);
	}
}