text:
<?php

namespace Application\Form;

use Application\Persistence\ObjectManagerAwareTrait;
use DoctrineModule\Persistence\ObjectManagerAwareInterface;
use Zend\Form\Form;
use Zend\InputFilter\InputFilterProviderInterface;
use Zend\ServiceManager\ServiceLocatorAwareTrait;

class User extends Form implements InputFilterProviderInterface, ObjectManagerAwareInterface
{

    use ObjectManagerAwareTrait;
    use ServiceLocatorAwareTrait;

    public function init()
    {
        $this->setAttribute('novalidate', 'novalidate');
        $this->setAttribute('autocomplete', 'off');
        $this->setAttribute('role', 'form');

        $this->add(array(
            'type' => 'text',
            'name' => 'firstName',
            'attributes' => ['class' => 'form-control'],
            'options' => array(
                'label' => '__user_first_name',
            ),
        ));

        $this->add(array(
            'type' => 'text',
            'name' => 'lastName',
            'attributes' => ['class' => 'form-control'],
            'options' => array(
                'label' => '__user_last_name',
            ),
        ));

        $this->add(array(
            'type' => 'number',
            'name' => 'age',
            'attributes' => ['class' => 'form-control'],
            'options' => array(
                'label' => '__user_age',
            ),
        ));

        $this->add(array(
            'type' => 'number',
            'name' => 'size',
            'attributes' => ['class' => 'form-control'],
            'options' => array(
                'label' => '__user_size',
            ),
        ));

        $this->add(array(
            'name' => 'skiLevel',
            'type' => 'objectselect',
            'attributes' => array(
                'class' => 'select2 full-width',
            ),
            'options' => array(
                'label' => '__user_ski_level',
                'label_attributes' => array(
                    'class' => 'control-label'
                ),
                'object_manager' => $this->getObjectManager(),
                'target_class' => 'Application\Entity\User',
                'property' => 'name'
            )
        ));

        $this->add(array(
            'type' => 'select',
            'name' => 'sex',
            'attributes' => ['class' => 'select2 full-width'],
            'options' => array(
                'label' => '__user_sex',
                'empty_option' => '__label_select_sex',
                'value_options' => array(
                    \Application\Entity\User::SEX_F => \Application\Entity\User::SEX_F,
                    \Application\Entity\User::SEX_M => \Application\Entity\User::SEX_M,
                ),
            )
        ));

        $this->add(array(
            'type' => 'select',
            'name' => 'ageMax',
            'attributes' => ['class' => 'select2 full-width', 'id' => 'ageMax'],
            'options' => array(
                'label' => '__label_choice_max_age',
                'empty_option' => '__label_select_age',
                'value_options' => array(
                    '25' => '25',
                    '50' => '50',
                ),
            )
        ));

        $this->add(array(
            'type' => 'submit',
            'name' => 'submit',
            'attributes' => ['class' => 'btn btn-success']
        ));
    }

    /**
     * Should return an array specification compatible with
     * {@link Zend\InputFilter\Factory::createInputFilter()}.
     *
     * @return array
     */
    public function getInputFilterSpecification()
    {
        return array(
            'firstName' => array(
                'required' => true
            ),
            'lastName' => array(
                'required' => true
            ),
            'age' => array(
                'required' => true
            ),
            'size' => array(
                'required' => true
            ),
            'skiLevel' => array(
                'required' => true
            ),
            'sex' => array(
                'required' => true
            ),
            'ageMax' => array(
                'required' => false
            ),
        );
    }

}


text:
package com.intellij.codeInsight.folding.impl;

import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.*;
import com.intellij.psi.javadoc.PsiDocComment;
import org.jetbrains.annotations.Nullable;

import java.util.NoSuchElementException;
import java.util.StringTokenizer;

@SuppressWarnings({"HardCodedStringLiteral"})
public class JavaElementSignatureProvider extends ElementSignatureProvider {
  private static final Logger LOG = Logger.getInstance("#com.intellij.codeInsight.folding.impl.JavaElementSignatureProvider");

  @Nullable
  public String getSignature(final PsiElement element) {
    if (element instanceof PsiImportList) {
      PsiFile file = element.getContainingFile();
      if (file instanceof PsiJavaFile && element.equals(((PsiJavaFile)file).getImportList())) {
        return "imports";
      }
      else {
        return null;
      }
    }
    if (element instanceof PsiMethod) {
      PsiMethod method = (PsiMethod)element;
      PsiElement parent = method.getParent();

      StringBuilder buffer = new StringBuilder();
      buffer.append("method#");
      String name = method.getName();
      buffer.append(name);
      buffer.append("#");
      buffer.append(getChildIndex(method, parent, name, PsiMethod.class));

      if (parent instanceof PsiClass) {
        String parentSignature = getSignature(parent);
        if (parentSignature == null) return null;
        buffer.append(";");
        buffer.append(parentSignature);
      }

      return buffer.toString();
    }
    if (element instanceof PsiClass) {
      PsiClass aClass = (PsiClass)element;
      PsiElement parent = aClass.getParent();

      StringBuilder buffer = new StringBuilder();
      buffer.append("class#");
      if (parent instanceof PsiClass || parent instanceof PsiFile) {
        String name = aClass.getName();
        buffer.append(name);
        buffer.append("#");
        buffer.append(getChildIndex(aClass, parent, name, PsiClass.class));

        if (parent instanceof PsiClass) {
          String parentSignature = getSignature(parent);
          if (parentSignature == null) return null;
          buffer.append(";");
          buffer.append(parentSignature);
        }
      }
      else {
        buffer.append(aClass.getTextRange().getStartOffset());
        buffer.append(":");
        buffer.append(aClass.getTextRange().getEndOffset());
      }

      return buffer.toString();
    }
    if (element instanceof PsiClassInitializer) {
      PsiClassInitializer initializer = (PsiClassInitializer)element;
      PsiElement parent = initializer.getParent();

      StringBuilder buffer = new StringBuilder();
      buffer.append("initializer#");

      int index = 0;
      PsiElement[] children = parent.getChildren();
      for (PsiElement child : children) {
        if (child instanceof PsiClassInitializer) {
          if (child.equals(initializer)) break;
          index++;
        }
      }
      buffer.append("#");
      buffer.append(index);

      if (parent instanceof PsiClass) {
        String parentSignature = getSignature(parent);
        if (parentSignature == null) return null;
        buffer.append(";");
        buffer.append(parentSignature);
      }

      return buffer.toString();
    }
    if (element instanceof PsiField) { // needed for doc-comments only
      PsiField field = (PsiField)element;
      PsiElement parent = field.getParent();

      StringBuilder buffer = new StringBuilder();
      buffer.append("field#");
      String name = field.getName();
      buffer.append(name);

      buffer.append("#");
      buffer.append(getChildIndex(field, parent, name, PsiField.class));

      if (parent instanceof PsiClass) {
        String parentSignature = getSignature(parent);
        if (parentSignature == null) return null;
        buffer.append(";");
        buffer.append(parentSignature);
      }

      return buffer.toString();
    }
    if (element instanceof PsiDocComment) {
      StringBuilder buffer = new StringBuilder();
      buffer.append("docComment;");

      PsiElement parent = element.getParent();
      if (!(parent instanceof PsiClass) && !(parent instanceof PsiMethod) && !(parent instanceof PsiField)) {
        return null;
      }
      String parentSignature = getSignature(parent);
      if (parentSignature == null) return null;
      buffer.append(parentSignature);

      return buffer.toString();
    }
    return null;
  }

  protected PsiElement restoreBySignatureTokens(PsiFile file, PsiElement parent, String type, StringTokenizer tokenizer) {
    if (type.equals("imports")) {
      if (!(file instanceof PsiJavaFile)) return null;
      return ((PsiJavaFile)file).getImportList();
    }
    else if (type.equals("method")) {
      String name = tokenizer.nextToken();
      try {
        int index = Integer.parseInt(tokenizer.nextToken());
        return restoreElementInternal(parent, name, index, PsiMethod.class);
      }
      catch (NumberFormatException e) {
        LOG.error(e);
        return null;
      }
    }
    else if (type.equals("class")) {
      String name = tokenizer.nextToken();

      PsiNameHelper nameHelper = JavaPsiFacade.getInstance(file.getProject()).getNameHelper();
      if (nameHelper.isIdentifier(name)) {
        int index = 0;
        try {
          index = Integer.parseInt(tokenizer.nextToken());
        }
        catch (NoSuchElementException e) { //To read previous XML versions correctly
        }

        return restoreElementInternal(parent, name, index, PsiClass.class);
      }
      StringTokenizer tok1 = new StringTokenizer(name, ":");
      int start = Integer.parseInt(tok1.nextToken());
      int end = Integer.parseInt(tok1.nextToken());
      PsiElement element = file.findElementAt(start);
      if (element != null) {
        TextRange range = element.getTextRange();
        while (range != null && range.getEndOffset() < end) {
          element = element.getParent();
          range = element.getTextRange();
        }

        if (range != null && range.getEndOffset() == end && element instanceof PsiClass) {
          return element;
        }
      }

      return null;
    }
    else if (type.equals("initializer")) {
      try {
        int index = Integer.parseInt(tokenizer.nextToken());

        PsiElement[] children = parent.getChildren();
        for (PsiElement child : children) {
          if (child instanceof PsiClassInitializer) {
            if (index == 0) {
              return child;
            }
            index--;
          }
        }

        return null;
      }
      catch (NumberFormatException e) {
        LOG.error(e);
        return null;
      }
    }
    else if (type.equals("field")) {
      String name = tokenizer.nextToken();

      try {
        int index = 0;
        try {
          index = Integer.parseInt(tokenizer.nextToken());
        }
        catch (NoSuchElementException e) { //To read previous XML versions correctly
        }

        return restoreElementInternal(parent, name, index, PsiField.class);
      }
      catch (NumberFormatException e) {
        LOG.error(e);
        return null;
      }

    }
    else if (type.equals("docComment")) {
      if (parent instanceof PsiClass) {
        return ((PsiClass)parent).getDocComment();
      }
      else if (parent instanceof PsiMethod) {
        return ((PsiMethod)parent).getDocComment();
      }
      else if (parent instanceof PsiField) {
        return ((PsiField)parent).getDocComment();
      }
      else {
        return null;
      }
    }
    else {
      return null;
    }
  }
}

redpajama_set_name: RedPajamaGithub


text:
while [[ $# -gt 0 ]]
do
key="$1"

case $key in
    -n | --nodes)
    NUM_NODES="$2"
    shift # past argument
    shift # past value
    ;;
    -g | --gpus)
    NUM_GPUS="$2"
    shift # pass argument
    shift # pass value
    ;;
    -c | --cpus)
    NUM_CPUS="$2"
    shift # pass argument
    shift # pass value
    ;;
    -p | --program)
    EXTENSION="$2"
    shift # pass argument
    shift # pass value
    ;;
    *)
    shift # pass argument
    ;;
esac
done

if [ -z "$NUM_NODES" ]; then echo "Warning: --nodes is missing"; exit; fi
if [ -z "$NUM_GPUS" ]; then echo "Warning: --gpus is missing"; exit; fi
if [ -z "$NUM_CPUS" ]; then echo "Warning: --cpus is missing"; exit; fi
if [ -z "$EXTENSION" ]; then echo "Warning: --file is missing"; exit; fi

if [ "$EXTENSION" == "mapping" ]; then
  echo "Running PageRank demo with mapping optimization..."
elif [ "$EXTENSION" == "baseline" ]; then
  echo "Running PageRank baseline demo..."
elif [ "$EXTENSION" == "optimized" ]; then
  echo "Running PageRank demo with optimized CUDA kernel..."
else
  echo "Warning: --program must be one of baseline, mapping, optimized"
  exit
fi

if [ $NUM_GPUS -eq 0 ]; then
    NUM_PARTS=$((NUM_CPUS * NUM_NODES))
else
    NUM_PARTS=$((NUM_GPUS * NUM_NODES))
fi

if [ $NUM_GPUS -lt 8 ]; then
    NUM_CPUS_TO_ALLOC=8
else
    NUM_CPUS_TO_ALLOC=$((NUM_CPUS))
fi

echo "Total partitions = ${NUM_PARTS}"

cat > submit_pr.sh <<EOL
#!/bin/bash
#
#SBATCH --job-name=pagerank
#SBATCH --export=TERRA_PATH,INCLUDE_PATH,PATH,LD_LIBRARY_PATH,CUDA_HOME,LG_RT_DIR,C_PATH
#SBATCH --time=10:00
#SBATCH --mem-per-cpu=6000MB
#SBATCH -p aaiken
EOL

echo "#SBATCH --output=res_%j_${EXTENSION}_nodes${NUM_NODES}_gpus${NUM_GPUS}_cpus${NUM_CPUS}.txt" >> submit_pr.sh
echo "#SBATCH --nodes=${NUM_NODES}" >> submit_pr.sh
echo "#SBATCH --gres gpu:4" >> submit_pr.sh
echo "#SBATCH --cpus-per-task=16" >> submit_pr.sh
echo "" >> submit_pr.sh

if [ $NUM_GPUS -gt 0 ]; then
    echo "LAUNCHER='srun -n ${NUM_NODES}' ~/legion/language/regent.py ~/legion/language/examples/pagerank/pagerank_${EXTENSION}.rg -graph ~/legion/language/examples/pagerank/twitter.gr -ni 10 -nw ${NUM_PARTS} -ll:gpu ${NUM_GPUS} -ll:fsize 15000 -ll:zsize 20000 -ll:cpu ${NUM_CPUS} -lg:prof ${NUM_NODES} -lg:prof_logfile prof%.gz" >> submit_pr.sh
else
    echo "LAUNCHER='srun -n ${NUM_NODES}' ~/legion/language/regent.py ~/legion/language/examples/pagerank/pagerank_${EXTENSION}.rg -graph ~/legion/language/examples/pagerank/twitter.gr -ni 10 -nw ${NUM_PARTS} -ll:csize 20000 -ll:cpu ${NUM_CPUS} -lg:prof ${NUM_NODES} -lg:prof_logfile prof%.gz" >> submit_pr.sh
fi

sbatch submit_pr.sh
squeue | grep pagerank


text:
require 'rubygems'

require 'erb'
require 'activesupport'
require 'find'
require 'zip/zip'
require 'fileutils'

class NUnitRunner
	include FileTest

	def initialize(paths)
		@sourceDir = paths.fetch(:source, 'source')
		@resultsDir = paths.fetch(:results, 'results')
		@compilePlatform = paths.fetch(:platform, 'x86')
		@compileTarget = paths.fetch(:compilemode, 'debug')

		if ENV["teamcity.dotnet.nunitlauncher"] # check if we are running in TeamCity
			# We are not using the TeamCity nunit launcher. We use NUnit with the TeamCity NUnit Addin which needs tO be copied to our NUnit addins folder
			# http://blogs.jetbrains.com/teamcity/2008/07/28/unfolding-teamcity-addin-for-nunit-secrets/
			# The teamcity.dotnet.nunitaddin environment variable is not available until TeamCity 4.0, so we hardcode it for now
			@teamCityAddinPath = ENV["teamcity.dotnet.nunitaddin"] ? ENV["teamcity.dotnet.nunitaddin"] : 'c:/TeamCity/buildAgent/plugins/dotnetPlugin/bin/JetBrains.TeamCity.NUnitAddin-NUnit'
			cp @teamCityAddinPath + '-2.4.7.dll', 'tools/nunit/addins'
		end

		@nunitExe = File.join('tools', 'nunit', "nunit-console#{(@compilePlatform.nil? ? '' : "-#{@compilePlatform}")}.exe").gsub('/','\\') + ' /nothread'
	end

	def executeTests(assemblies)
		Dir.mkdir @resultsDir unless exists?(@resultsDir)

		assemblies.each do |assem|
			file = File.expand_path("#{@sourceDir}/#{assem}/bin/#{(@compilePlatform.nil? ? '' : "#{@compilePlatform}/")}#{@compileTarget}/#{assem}.dll")
			sh "#{@nunitExe} \"#{file}\""
		end
	end
end

class MSBuildRunner
	def self.compile(attributes)
		version = attributes.fetch(:clrversion, 'v3.5')
		compileTarget = attributes.fetch(:compilemode, 'debug')
	    solutionFile = attributes[:solutionfile]

		frameworkDir = File.join(ENV['windir'].dup, 'Microsoft.NET', 'Framework', version)
		msbuildFile = File.join(frameworkDir, 'msbuild.exe')

		sh "#{msbuildFile} #{solutionFile} /maxcpucount /v:m /property:BuildInParallel=false /property:Configuration=#{compileTarget} /t:Rebuild"
	end
end

class AspNetCompilerRunner
	def self.compile(attributes)

		webPhysDir = attributes.fetch(:webPhysDir, '')
		webVirDir = attributes.fetch(:webVirDir, '')

		frameworkDir = File.join(ENV['windir'].dup, 'Microsoft.NET', 'Framework', 'v2.0.50727')
		aspNetCompiler = File.join(frameworkDir, 'aspnet_compiler.exe')

		sh "#{aspNetCompiler} -p #{webPhysDir} -v #{webVirDir}"
	end
end

class AsmInfoBuilder
	attr_reader :buildnumber, :parameterless_attributes

	def initialize(version, properties)
		@properties = properties
		@buildnumber = version
		@properties['Version'] = @properties['InformationalVersion'] = buildnumber;
		@parameterless_attributes = [:allow_partially_trusted_callers]
	end

	def write(file)
		template = %q{using System.Reflection;
using System.Security;

<% @properties.each do |k, v| %>
<% if @parameterless_attributes.include? k %>
[assembly: <%= k.to_s.camelize %>]
<% else %>
[assembly: Assembly<%= k.to_s.camelize %>("<%= v %>")]
<% end %>
<% end %>
		}.gsub(/^    /, '')

	  erb = ERB.new(template, 0, "%<>")

	  File.open(file, 'w') do |file|
		  file.puts erb.result(binding)
	  end
	end
end

class InstallUtilRunner
	def installServices(services, parameters)
		services.each do |service|
			params = ""
			parameters.each_pair {|key, value| params = params + "/" + key + "=" + value + " "}
			sh "tools/installutil /i #{params} #{service}"
		end
	end

	def uninstallServices(services)
		services.each do |service|
			begin
				sh "tools/installutil /u #{service}"
			rescue Exception => e
				puts 'IGNORING ERROR: ' + e
			end
		end
	end

end

def create_zip(filename, root, excludes=/^$/)
  File.delete(filename) if File.exists? filename
  Zip::ZipFile.open(filename, Zip::ZipFile::CREATE) do |zip|
    Find.find(root) do |path|
	  next if path =~ excludes

	  zip_path = path.gsub(root, '')
	  zip.add(zip_path, path)
	end
  end
end

def docu(dll_name)
	FileUtils.rm_r('output') if File.exists? 'output'

	docu_exe = "tools/docu/docu.exe"

	`#{docu_exe} #{dll_name}`
end


text:
[@concord-consortium/lara-interactive-api](../README.md) › [Globals](../globals.md) › [IRuntimeOpenResponseMetadata](iruntimeopenresponsemetadata.md)

# Interface: IRuntimeOpenResponseMetadata

## Hierarchy

* [IRuntimeMetadataBase](iruntimemetadatabase.md)

  ↳ **IRuntimeOpenResponseMetadata**

## Index

### Properties

* [answerText](iruntimeopenresponsemetadata.md#optional-answertext)
* [answerType](iruntimeopenresponsemetadata.md#answertype)
* [submitted](iruntimeopenresponsemetadata.md#optional-submitted)

## Properties

### `Optional` answerText

• **answerText**? : *undefined | string*

*Inherited from [IRuntimeMetadataBase](iruntimemetadatabase.md).[answerText](iruntimemetadatabase.md#optional-answertext)*

answerText can be used by all the interactive types to display answer summary without having to load iframe
with report view.

___

###  answerType

• **answerType**: *"open_response_answer"*

*Overrides [IRuntimeMetadataBase](iruntimemetadatabase.md).[answerType](iruntimemetadatabase.md#answertype)*

answerType is different so Report and Portal can recognize this type of question.
Use answerText (defined in IRuntimeMetadataBase) to provide open response answer.

___

### `Optional` submitted

• **submitted**? : *undefined | false | true*

*Inherited from [IRuntimeMetadataBase](iruntimemetadatabase.md).[submitted](iruntimemetadatabase.md#optional-submitted)*


text:
ActiveRecord::Schema.define(version: 20140218204714) do

  # These are extensions that must be enabled in order to support this database
  enable_extension "plpgsql"

  create_table "comments", force: true do |t|
    t.integer  "event_id"
    t.text     "body"
    t.datetime "created_at"
    t.datetime "updated_at"
    t.integer  "user_id"
  end

  add_index "comments", ["event_id"], name: "index_comments_on_event_id", using: :btree

  create_table "events", force: true do |t|
    t.string   "title"
    t.string   "room_name"
    t.text     "body"
    t.boolean  "open",       default: false
    t.datetime "start"
    t.datetime "created_at"
    t.datetime "updated_at"
    t.integer  "user_id"
  end

  create_table "users", force: true do |t|
    t.string   "provider"
    t.string   "uid"
    t.string   "name"
    t.string   "email"
    t.string   "image"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

end


text:
gogh
====
/*2012.9.3*/
Open source code sharing platform,please respect autor's copyright.


text:
set -euo pipefail

gcsweb_base_url="https://gcsweb.ci.kubevirt.io/gcs/kubevirt-prow"

function test_kubevirt_release() {
    release="$(get_release_tag_for_xy "$1")"
    export DOCKER_TAG="$release"
    deploy_release "$release"

    wait_on_kubevirt_ready
    run_tests
}

function get_release_tag_for_xy() {
    release_xy="$1"

    curl --fail -s https://api.github.com/repos/kubevirt/kubevirt/releases |
        jq -r '(.[].tag_name | select( test("-(rc|alpha|beta)") | not ) )' |
        sort -rV | grep "v$release_xy" | head -1
}

function deploy_release() {
    local release="$1"

    tagged_release_url="https://github.com/kubevirt/kubevirt/releases/download/${release}"

    curl -Lo "$BIN_DIR/tests.test" "${tagged_release_url}/tests.test"
    chmod +x "$BIN_DIR/tests.test"

    curl -L "${tagged_release_url}/kubevirt-operator.yaml" | oc create -f -
    curl -L "${tagged_release_url}/kubevirt-cr.yaml" | oc create -f -

    testing_infra_url="$gcsweb_base_url/devel/release/kubevirt/kubevirt/${release}/manifests/testing/"
    for testinfra_file in $(curl -L "${testing_infra_url}" | grep -oE 'https://[^"]*\.yaml'); do
        curl -L ${testinfra_file} | oc create -f -
    done
}

function test_kubevirt_nightly() {
    export DOCKER_PREFIX='quay.io/kubevirt'
    local release_url
    release_date=$(get_latest_release_date_for_kubevirt_nightly)
    release_url="$(get_release_url_for_kubevirt_nightly "$release_date")"
    DOCKER_TAG="$(get_release_tag_for_kubevirt_nightly "$release_url" "$release_date")"
    export DOCKER_TAG

    deploy_kubevirt_nightly "$release_url"
    wait_on_kubevirt_ready
    run_tests
}

function deploy_kubevirt_nightly() {
    release_url="$1"

    echo "Downloading kubevirt tests binary from nightly build $release_url"
    curl -Lo "$BIN_DIR/tests.test" "${release_url}/testing/tests.test"
    chmod +x "$BIN_DIR/tests.test"

    echo "Deploying kubevirt from nightly build $release_url"
    oc create -f "${release_url}/kubevirt-operator.yaml"
    oc create -f "${release_url}/kubevirt-cr.yaml"

    echo "Deploying test infrastructure from $release_url"
    for testinfra_file in $(curl -L "${release_url}/testing/" | grep -oE 'https://[^"]*\.yaml'); do
        oc create -f "${testinfra_file}"
    done
}

function get_release_tag_for_kubevirt_nightly() {
    release_url="$1"
    release_date="$2"
    commit=$(curl -L "${release_url}/commit")
    echo "${release_date}_$(echo "${commit}" | cut -c 1-9)"
}

function get_release_url_for_kubevirt_nightly() {
    release_base_url="$gcsweb_base_url/devel/nightly/release/kubevirt/kubevirt"
    release_date="$1"
    echo "${release_base_url}/${release_date}"
}

function get_latest_release_date_for_kubevirt_nightly() {
    release_base_url="$gcsweb_base_url/devel/nightly/release/kubevirt/kubevirt"
    release_date=$(curl -L "${release_base_url}/latest")
    echo "${release_date}"
}

function wait_on_kubevirt_ready() {
    oc wait -n kubevirt kv kubevirt --for condition=Available --timeout 15m
}

function get_path_or_empty_string_for_cmd() {
    cmd="$1"
    set +e
    which "$cmd"
    set -e
}

function run_tests() {
    mkdir -p "$ARTIFACT_DIR"
    # required to be set for test binary
    export ARTIFACTS=${ARTIFACT_DIR}

    OC_PATH=$(get_path_or_empty_string_for_cmd oc)
    KUBECTL_PATH=$(get_path_or_empty_string_for_cmd kubectl)

    tests.test -v=5 -kubeconfig=${KUBECONFIG} -container-tag=${DOCKER_TAG} -container-tag-alt= -container-prefix=${DOCKER_PREFIX} -image-prefix-alt=-kv -oc-path=${OC_PATH} -kubectl-path=${KUBECTL_PATH} -gocli-path=$(pwd)/cluster-up/cli.sh -test.timeout 420m -ginkgo.noColor -ginkgo.succinct -ginkgo.slow-spec-threshold=60s ${KUBEVIRT_TESTS_FOCUS} -junit-output=${ARTIFACT_DIR}/junit.functest.xml -installed-namespace=kubevirt -previous-release-tag= -previous-release-registry=quay.io/kubevirt -deploy-testing-infra=false
}

export PATH="$BIN_DIR:$PATH"
eval "$@"


text:
1. How to create a basic Granitic application
 2. Some of Granitic's fundamental principles
 3. How to create a simple web service

## Prerequisites

 1. Follow the Granitic [installation instructions](../installation.md)
 2. Read the [before you start](000-before-you-start.md) tutorial
 3. Have access to a text editor or IDE for writing Go and JSON files and a terminal emulator or command prompt
 (referred to as a terminal from now on)

#### Note for Windows users

Refer to the Windows notes in the [before you start](000-before-you-start.md) tutorial

## Introduction

This tutorial will show you how to create a simple Granitic application that exposes a JSON web service over HTTP. It will
also introduce you to some of Granitic's fundamentals.

## Creating a Grantic project

A Granitic project is made up of three sets of assets:

 1. Go source files
 2. JSON application configuration files
 3. JSON component definition files

Each of these types of asset will be explained over the course of this tutorial. Granitic includes a command line tool
to create a skeleton project that can be compiled and started.

Run the following in a terminal:

cd ~
grnc-project recordstore

This will create the following files under your home directory:

recordstore
  .gitignore
  main.go
  go mod
  comp-def/
    common.json
  config/
    base.json

## Starting and stopping your application

This minimal configuration is actually a working Granitic application that can be started and stopped - it just doesn't
do anything interesting.

Start the application by returning to your terminal and running

cd recordstore
go mod download
grnc-bind
go build
./recordstore

You should see output similar to:

01/Mar/2019:14:59:52 Z INFO  [grncInit] Starting components
01/Mar/2019:14:59:52 Z INFO  [grncInit] Ready (startup time 1.68654ms)

This means your application has started and is waiting. You can stop it with `CTRL+C` and will see output similar to

01/Mar/2019:15:00:36 Z INFO  [grncInit] Shutting down (system signal)

## Facilities

A `facility` is Granitic's name for a high-level feature that your application can enable or disable. By default,
most of the features are disabled. You can see which features are available to your applications and whether or not they're enabled
by inspecting the file `facility/config/active.json` in your Granitic installation folder:

```json
{
  "Facilities": {
    "HTTPServer": false,
    "JSONWs": false,
    "XMLWs": false,
    "FrameworkLogging": true,
    "ApplicationLogging": true,
    "QueryManager": false,
    "RdbmsAccess": false,
    "ServiceErrorManager": false,
    "RuntimeCtl": false,
    "TaskScheduler": false
  }
}
```

In order to build a JSON web service that will listen for an handler HTTP requests, you will need to enable two facilities:
`HTTPServer` and `JSONWs` (JSON Web Services).

We do this by overriding the default setting for each facility. To do this, open the JSON `config/base.json`
that was generated for you and change it so it looks like:

```json
{
  "Facilities": {
    "HTTPServer": true,
    "JSONWs": true
  }
}
```
(from now on this file will be referred to as your base config file)

If you return to your terminal and run:

grnc-bind && go build && ./recordstore

You'll see an additional line of logging on startup similar to:

01/Mar/2019:15:12:29 Z INFO  [grncHTTPServer] Listening on 8080

Which shows that an HTTP server is listening for web service requests on the default port of 8080. Stop the running
service with `CTRL+C`

## Adding an endpoint

An `endpoint` is Granitic's preferred name for code that handles a web service request to a particular URI pattern for a
particular HTTP method (GET, POST etc). Most of the mechanics of routing a request to your code and converting between
JSON and your custom Go code is handled by Granitic, you will be concerned mainly with defining your _endpoint logic_.

Endpoint logic is code in a Go struct that has a member function that Granitic can call to pass control of a request
once the framework has completed its automatic steps.

Create the file `artist/get.go` in your `recordstore` project and set the contents to:

```go
package artist

import (
  "github.com/graniticio/granitic/v2/ws"
  "context"
)

type GetLogic struct {}

func (gl *GetLogic) Process(ctx context.Context, req *ws.Request, res *ws.Response) {

  res.Body = Info{
    Name: "Hello, World!",
  }

}

type Info struct {
  Name string
}
```

This code defines an object implementing the `ws.WsRequestProcessor` interface and another object that will
be used to store the results of the web service call, in this case a recording artist with the unlikely name "Hello, World!"

## Turning your code into a component

At the core of Granitic is an Inversion of Control (IoC) container, sometimes also called a Dependency Injection framework.
Granitic looks after the lifecycle (creating and destroying) of the Go objects you define, but needs to be told which
objects should be included in your application and how they should be configured.

These definitions are stored in JSON _component definition files_ which, by default, are stored in your project in a folder called `comp-def`.
You can have as many files as you like in this folder, and it is recommend you group related components in to separate
named files.

Open the file `comp-def/common.json` and set the content to:

```json
{
  "packages": [
    "github.com/graniticio/granitic/v2/ws/handler",
    "recordstore/artist"
  ],

  "components": {
    "artistHandler": {
      "type": "handler.WsHandler",
      "HTTPMethod": "GET",
      "Logic": {
        "type": "artist.GetLogic"
      },
      "PathPattern": "^/artist"
    }
  }
}
```

A component definition file has two sections. The `packages` section declares the Go packages containing the
code that you intend to use as components. The `components` section declares uniquely named components that
you want to be managed by Granitic.

The sole component in this file, `artistHandler`, is an instance of `handler.WsHandler`, a built-in Granitic
type. A `ws.WsHandler` coordinates the bulk of the request processing lifecycle as well as managing error-handling
for a web service request.

One of the fields on this component, `Logic`, expects another component to be injected into to it. In this case
we're defining the component that the needs to be injected inline as a _nested component_. Note that the nested component
doesn't need a name, just a type - this case the  `artist.GetLogic` struct we defined above.

The minimal configuration in this example specifies the HTTP method that the handler will respond to (GET)
and a regex for matching against incoming request paths.

## Binding

Granitic is written in Go because of Go's positioning between C's performance and memory consumption and the
relative ease-of-use of JVM and CLR languages (Java, C# etc). One of the compromises we accept in using Go is that it
is a statically-linked language with no facility for creating objects from a text name at runtime - if you want to use
a type in your application, it must be referenced at compile time.

In order to reconcile the configuration-based approach favoured by Granitic with this limitation, a tool is used to
generate Go source code from component definition files.

Return to your terminal and run

grnc-bind

You will notice that a Go source file `bindings/bindings.go` has been created. You will not
(and in fact should not) edit this file directly, but feel free to examine it to see what is happening.

*You will need to re-run `grnc-bind` whenever you change your component definition file*

## Building and testing your application

Every Go application requires an entry point `main` method. For a Go application that was created using the
`grnc-project` tool, the `main` method is in the `main.go` file at the root of the
project. For this tutorial, this file will look like:

```go
package main

import "github.com/graniticio/granitic/v2"
import "recordstore/bindings"

func main() {
  granitic.StartGranitic(bindings.Components())
}

```

This simply takes the objects generated by `grnc-bind` and passes them to Granitic. For the vast majority of
Granitic applications you will not need to modify or even look at this file.

Return to your terminal and run:

go build && ./recordstore

Now open a browser and visit:

[http://localhost:8080/artist](http://localhost:8080/artist) or [http://[::1]:8080/artist](http://[::1]:8080/artist)

and you should see the response:

```json
{
  "Name": "Hello, World!"
}
```

## Recap

 * Granitic applications contain Go source files, configuration files and component definition files
 * The `grnc-project` tool can create an empty, working Granitic application
 * Components are a named instance of a Go object, managed by Granitic's IoC container
 * The `grnc-bind` tool converts your component definition files into Go source - run the tool whenever
  you change your component definitions.

## Next

The next tutorial covers [configuration](002-configuration.md) in more depth


text:
namespace demoloop {

void initVertices(Vertex *vertices, int width, int height) {
  for (int i = 0; i < 4; i++)
    vertices[i].r = vertices[i].g = vertices[i].b = vertices[i].a = 255;

  // Vertices are ordered for use with triangle strips:
  // 0----2
  // |  / |
  // | /  |
  // 1----3
  vertices[0].x = 0.0f;
  vertices[0].y = 0.0f;
  vertices[1].x = 0.0f;
  vertices[1].y = (float) height;
  vertices[2].x = (float) width;
  vertices[2].y = 0.0f;
  vertices[3].x = (float) width;
  vertices[3].y = (float) height;

  vertices[0].s = 0.0f;
  vertices[0].t = 0.0f;
  vertices[1].s = 0.0f;
  vertices[1].t = 1.0f;
  vertices[2].s = 1.0f;
  vertices[2].t = 0.0f;
  vertices[3].s = 1.0f;
  vertices[3].t = 1.0f;
}

Image::Image(std::vector<uint8_t> &&pixels, int width, int height) : width(width), height(height) {
  glGenTextures(1, &texture);
  glBindTexture(GL_TEXTURE_2D,texture);
  glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, static_cast<void *>(pixels.data()));
  glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR);
  glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);
  glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_WRAP_S,GL_CLAMP_TO_EDGE);
  glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_WRAP_T,GL_CLAMP_TO_EDGE);

  initVertices(vertices, width, height);
}

Image::Image(const std::string &path) {
  SDL_Surface *surf = IMG_Load((getResourcePath() + path).c_str());
  if (surf == nullptr) {
    logSDLError("IMG_Load");
  }

  auto fmt = surf->format->BytesPerPixel == 4 ? GL_RGBA : GL_RGB;
  width = surf->w;
  height = surf->h;

  glGenTextures(1, &texture);
  glBindTexture(GL_TEXTURE_2D,texture);
  glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, surf->w,surf->h, 0, fmt, GL_UNSIGNED_BYTE,surf->pixels);
  glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR);
  glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);
  glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_WRAP_S,GL_CLAMP_TO_EDGE);
  glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_WRAP_T,GL_CLAMP_TO_EDGE);
  SDL_FreeSurface(surf);

  initVertices(vertices, width, height);
}

Image::~Image() {
  gl.deleteTexture(texture);
}

const void *Image::getHandle() const {
  return &texture;
}

void Image::setFilter(const Texture::Filter &f) {
  if (!validateFilter(f, false))
    throw std::runtime_error("Invalid texture filter.");

  filter = f;
  gl.bindTexture(texture);
  gl.setTextureFilter(filter);
}

bool Image::setWrap(const Texture::Wrap &w) {
  bool success = true;
  wrap = w;

  // if ((GLAD_ES_VERSION_2_0 && !(GLAD_ES_VERSION_3_0 || GLAD_OES_texture_npot))
  //   && (width != next_p2(width) || height != next_p2(height)))
  if (width != next_p2(width) || height != next_p2(height))
  {
    if (wrap.s != WRAP_CLAMP || wrap.t != WRAP_CLAMP)
      success = false;

    // If we only have limited NPOT support then the wrap mode must be CLAMP.
    wrap.s = wrap.t = WRAP_CLAMP;
  }

  // if (!gl.isClampZeroTextureWrapSupported())
  // {
    if (wrap.s == WRAP_CLAMP_ZERO)
      wrap.s = WRAP_CLAMP;
    if (wrap.t == WRAP_CLAMP_ZERO)
      wrap.t = WRAP_CLAMP;
  // }

  gl.bindTexture(texture);
  gl.setTextureWrap(wrap);

  return success;
}

void Image::drawv(const glm::mat4 &modelTransform, const Vertex *v) {
  gl.bindTexture(texture);

  gl.bufferVertices(v, 4, GL_DYNAMIC_DRAW);

  gl.useVertexAttribArrays(ATTRIBFLAG_POS | ATTRIBFLAG_TEXCOORD);
  glVertexAttribPointer(ATTRIB_POS, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (GLvoid*) offsetof(Vertex, x));
  glVertexAttribPointer(ATTRIB_TEXCOORD, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex), (GLvoid*) offsetof(Vertex, s));

  gl.prepareDraw(modelTransform);
  gl.drawArrays(GL_TRIANGLE_STRIP, 0, 4);
}

void Image::draw(glm::mat4 curModel) {
  drawv(curModel, vertices);
}

void Image::drawq(Quad *quad, glm::mat4 curModel) {
  drawv(curModel, quad->getVertices());
}

}


text:
describe 'http' do
  it 'redirects to ssl' do
    response = get '/'
    ensure_redirect response, %r{^https://#{MACHINE_NAME}/}
  end
end


text:
module Adder {
    export function add(a: number, b: number): number {
        return a + b;
    }
}


text:
    <form>
        <input type="text" size="50" id="testinput" />
        <input type="text" size="50" />
    </form>

This tests that DOMKeyboardEvents are created correctly in the JavaScript API.


text:
/* ----------------------------------------------------------------------------
 * This file was automatically generated by SWIG (http://www.swig.org).
 * Version 3.0.5
 *
 * Do not make changes to this file unless you know what you are doing--modify
 * the SWIG interface file instead.
 * ----------------------------------------------------------------------------- */

package rhcad.touchvg.core;

public class RECT_2D {
  private long swigCPtr;
  protected boolean swigCMemOwn;

  protected RECT_2D(long cPtr, boolean cMemoryOwn) {
    swigCMemOwn = cMemoryOwn;
    swigCPtr = cPtr;
  }

  protected static long getCPtr(RECT_2D obj) {
    return (obj == null) ? 0 : obj.swigCPtr;
  }

  protected void finalize() {
    delete();
  }

  public synchronized void delete() {
    if (swigCPtr != 0) {
      if (swigCMemOwn) {
        swigCMemOwn = false;
        touchvgJNI.delete_RECT_2D(swigCPtr);
      }
      swigCPtr = 0;
    }
  }

  public void setLeft(float value) {
    touchvgJNI.RECT_2D_left_set(swigCPtr, this, value);
  }

  public float getLeft() {
    return touchvgJNI.RECT_2D_left_get(swigCPtr, this);
  }

  public void setTop(float value) {
    touchvgJNI.RECT_2D_top_set(swigCPtr, this, value);
  }

  public float getTop() {
    return touchvgJNI.RECT_2D_top_get(swigCPtr, this);
  }

  public void setRight(float value) {
    touchvgJNI.RECT_2D_right_set(swigCPtr, this, value);
  }

  public float getRight() {
    return touchvgJNI.RECT_2D_right_get(swigCPtr, this);
  }

  public void setBottom(float value) {
    touchvgJNI.RECT_2D_bottom_set(swigCPtr, this, value);
  }

  public float getBottom() {
    return touchvgJNI.RECT_2D_bottom_get(swigCPtr, this);
  }

  public RECT_2D() {
    this(touchvgJNI.new_RECT_2D(), true);
  }

  public float width() {
    return touchvgJNI.RECT_2D_width(swigCPtr, this);
  }

  public float height() {
    return touchvgJNI.RECT_2D_height(swigCPtr, this);
  }

}


text:
import ConfigParser
import json
import logging
import os
import subprocess
import re
import time
import unittest

from selenium import webdriver
from selenium.webdriver import ActionChains
from selenium.webdriver.support.ui import Select
from selenium.common.exceptions import UnexpectedAlertPresentException

from autothreadharness import settings
from autothreadharness.exceptions import FailError, FatalError, GoldenDeviceNotEnoughError
from autothreadharness.harness_controller import HarnessController
from autothreadharness.helpers import HistoryHelper
from autothreadharness.open_thread_controller import OpenThreadController
from autothreadharness.pdu_controller_factory import PduControllerFactory
from autothreadharness.rf_shield_controller import get_rf_shield_controller

logger = logging.getLogger(__name__)

THREAD_CHANNEL_MAX = 26
"""Maximum channel number of thread protocol"""

THREAD_CHANNEL_MIN = 11
"""Minimum channel number of thread protocol"""

DEFAULT_TIMEOUT = 2700
"""Timeout for each test case in seconds"""

def wait_until(what, times=-1):
    """Wait until `what` return True

    Args:
        what (Callable[bool]): Call `wait()` again and again until it returns True
        times (int): Maximum times of trials before giving up

    Returns:
        True if success, False if times threshold reached

    """
    while times:
        logger.info('Waiting times left %d', times)
        try:
            if what() is True:
                return True
        except:
            logger.exception('Wait failed')
        else:
            logger.warning('Trial[%d] failed', times)
        times -= 1
        time.sleep(1)

    return False

class HarnessCase(unittest.TestCase):
    """This is the case class of all automation test cases.

    All test case classes MUST define properties `role`, `case` and `golden_devices_required`
    """

    channel = settings.THREAD_CHANNEL
    """int: Thread channel.

    Thread channel ranges from 11 to 26.
    """

    ROLE_LEADER         = 1
    ROLE_ROUTER         = 2
    ROLE_SED            = 4
    ROLE_BORDER         = 8
    ROLE_REED           = 16
    ROLE_ED             = 32
    ROLE_COMMISSIONER   = 64
    ROLE_JOINER         = 128
    ROLE_FED            = 512
    ROLE_MED            = 1024

    role = None
    """int: role id.

    1
        Leader
    2
        Router
    4
        Sleepy end device
    16
        Router eligible end device
    32
        End device
    64
        Commissioner
    128
        Joiner
    512
        Full end device
    1024
        Minimal end device
    """

    case = None
    """str: Case id, e.g. '6 5 1'.
    """

    golden_devices_required = 0
    """int: Golden devices needed to finish the test
    """

    child_timeout = settings.THREAD_CHILD_TIMEOUT
    """int: Child timeout in seconds
    """

    sed_polling_interval = settings.THREAD_SED_POLLING_INTERVAL
    """int: SED polling interval in seconds
    """

    auto_dut = settings.AUTO_DUT
    """bool: whether use harness auto dut feature"""

    timeout = hasattr(settings, 'TIMEOUT') and settings.TIMEOUT or DEFAULT_TIMEOUT
    """number: timeout in seconds to stop running this test case"""

    started = 0
    """number: test case started timestamp"""

    def __init__(self, *args, **kwargs):
        self.dut = None
        self._browser = None
        self._hc = None
        self.result_dir = '%s\\%s' % (settings.OUTPUT_PATH, self.__class__.__name__)
        self.history = HistoryHelper()
        self.add_all_devices = False

        super(HarnessCase, self).__init__(*args, **kwargs)

    def _init_devices(self):
        """Reboot all usb devices.

        Note:
            If PDU_CONTROLLER_TYPE is not valid, usb devices is not rebooted.
        """
        if not settings.PDU_CONTROLLER_TYPE:
            if settings.AUTO_DUT:
                return

            for device in settings.GOLDEN_DEVICES:
                port, _ = device
                try:
                    with OpenThreadController(port) as otc:
                        logger.info('Resetting %s', port)
                        otc.reset()
                except:
                    logger.exception('Failed to reset device %s', port)
                    self.history.mark_bad_golden_device(device)

            return

        tries = 3
        pdu_factory = PduControllerFactory()

        while True:
            try:
                pdu = pdu_factory.create_pdu_controller(settings.PDU_CONTROLLER_TYPE)
                pdu.open(**settings.PDU_CONTROLLER_OPEN_PARAMS)
            except EOFError:
                logger.warning('Failed to connect to telnet')
                tries = tries - 1
                if tries:
                    time.sleep(10)
                    continue
                else:
                    logger.error('Fatal error: cannot connect to apc')
                    raise
            else:
                pdu.reboot(**settings.PDU_CONTROLLER_REBOOT_PARAMS)
                pdu.close()
                break

        time.sleep(len(settings.GOLDEN_DEVICES))

    def _init_harness(self):
        """Restart harness backend service.

        Please start the harness controller before running the cases, otherwise, nothing happens
        """
        self._hc = HarnessController(self.result_dir)
        self._hc.stop()
        time.sleep(1)
        self._hc.start()
        time.sleep(2)

        harness_config = ConfigParser.ConfigParser()
        harness_config.read('%s\\Config\\Configuration.ini' % settings.HARNESS_HOME)
        if harness_config.has_option('THREAD_HARNESS_CONFIG', 'BrowserAutoNavigate') and \
                harness_config.getboolean('THREAD_HARNESS_CONFIG', 'BrowserAutoNavigate'):
            os.system('taskkill /t /f /im chrome.exe')

    def _destroy_harness(self):
        """Stop harness backend service

        Stop harness service.
        """
        self._hc.stop()
        time.sleep(2)

    def _init_dut(self):
        """Initialize the DUT.

        DUT will be restarted. and openthread will started.
        """
        if self.auto_dut:
            self.dut = None
            return

        dut_port = settings.DUT_DEVICE[0]
        dut = OpenThreadController(dut_port)
        self.dut = dut

    def _destroy_dut(self):
        self.dut = None

    def _init_browser(self):
        """Open harness web page.

        Open a quiet chrome which:
        1. disables extensions,
        2. ignore certificate errors and
        3. always allow notifications.
        """
        chrome_options = webdriver.ChromeOptions()
        chrome_options.add_argument('--disable-extensions')
        chrome_options.add_argument('--ignore-certificate-errors')
        chrome_options.add_experimental_option('prefs', {
            'profile.managed_default_content_settings.notifications': 1
        })

        browser = webdriver.Chrome(chrome_options=chrome_options)
        browser.set_page_load_timeout(10)
        browser.implicitly_wait(1)
        browser.maximize_window()
        browser.get(settings.HARNESS_URL)
        self._browser = browser
        if not wait_until(lambda: 'Thread' in browser.title, 30):
            self.assertIn('Thread', browser.title)

    def _destroy_browser(self):
        """Close the browser.
        """
        self._browser.close()
        self._browser = None

    def _init_rf_shield(self):
        if getattr(settings, 'SHIELD_CONTROLLER_TYPE', None) and getattr(settings, 'SHIELD_CONTROLLER_PARAMS', None):
            self.rf_shield = get_rf_shield_controller(
                shield_type=settings.SHIELD_CONTROLLER_TYPE,
                params=settings.SHIELD_CONTROLLER_PARAMS
            )
        else:
            self.rf_shield = None

    def _destroy_rf_shield(self):
        self.rf_shield = None

    def setUp(self):
        """Prepare to run test case.

        Start harness service, init golden devices, reset DUT and open browser.
        """
        if self.__class__ is HarnessCase:
            return

        logger.info('Setting up')
        # clear files
        logger.info('Deleting all .pdf')
        os.system('del /q "%HOMEDRIVE%%HOMEPATH%\\Downloads\\NewPdf_*.pdf"')
        logger.info('Deleting all .xlsx')
        os.system('del /q "%HOMEDRIVE%%HOMEPATH%\\Downloads\\ExcelReport*.xlsx"')
        logger.info('Deleting all .pcapng')
        os.system('del /q "%s\\Captures\\*.pcapng"' % settings.HARNESS_HOME)

        # using temp files to fix excel downloading fail
        logger.info('Empty files in temps')
        os.system('del /q "%s\\Thread_Harness\\temp\\*.*"' % settings.HARNESS_HOME)

        # create directory
        os.system('mkdir %s' % self.result_dir)
        self._init_harness()
        self._init_devices()
        self._init_dut()
        self._init_rf_shield()

    def tearDown(self):
        """Clean up after each case.

        Stop harness service, close browser and close DUT.
        """
        if self.__class__ is HarnessCase:
            return

        logger.info('Tearing down')
        self._destroy_harness()
        self._destroy_browser()
        self._destroy_dut()
        self._destroy_rf_shield()

    def _setup_page(self):
        """Do sniffer settings and general settings
        """
        if not self.started:
            self.started = time.time()

        if time.time() - self.started > 30:
            self._browser.refresh()
            return

        # Detect Sniffer
        try:
            dialog = self._browser.find_element_by_id('capture-Setup-modal')
        except:
            logger.exception('Failed to get dialog.')
        else:
            if dialog and dialog.get_attribute('aria-hidden') == 'false':
                times = 60
                while times:
                    status = dialog.find_element_by_class_name('status-notify').text
                    if 'Searching' in status:
                        logger.info('Still detecting..')
                    elif 'Not' in status:
                        logger.warning('Sniffer device not verified!')
                        button = dialog.find_element_by_id('snifferAutoDetectBtn')
                        button.click()
                    elif 'Verified' in status:
                        logger.info('Verified!')
                        button = dialog.find_element_by_id('saveCaptureSettings')
                        button.click()
                        break
                    else:
                        logger.warning('Unexpected sniffer verification status')

                    times = times - 1
                    time.sleep(1)

                if not times:
                    raise Exception('Unable to detect sniffer device')

        time.sleep(1)

        try:
            skip_button = self._browser.find_element_by_id('SkipPrepareDevice')
            if skip_button.is_enabled():
                skip_button.click()
                time.sleep(1)
        except:
            logger.info('Still detecting sniffers')

        try:
            next_button = self._browser.find_element_by_id('nextButton')
        except:
            logger.exception('Failed to finish setup')
            return

        if not next_button.is_enabled():
            logger.info('Harness is still not ready')
            return

        # General Setup
        try:
            if self.child_timeout or self.sed_polling_interval:
                button = self._browser.find_element_by_id('general-Setup')
                button.click()
                time.sleep(2)

                dialog = self._browser.find_element_by_id('general-Setup-modal')
                if dialog.get_attribute('aria-hidden') != 'false':
                    raise Exception('Missing General Setup dialog')

                field = dialog.find_element_by_id('inp_general_child_update_wait_time')
                field.clear()
                if self.child_timeout:
                    field.send_keys(str(self.child_timeout))

                field = dialog.find_element_by_id('inp_general_sed_polling_rate')
                field.clear()
                if self.sed_polling_interval:
                    field.send_keys(str(self.sed_polling_interval))

                button = dialog.find_element_by_id('saveGeneralSettings')
                button.click()
                time.sleep(1)

        except:
            logger.exception('Failed to do general setup')
            return

        # Finish this page
        next_button.click()
        time.sleep(1)

    def _connect_devices(self):
        connect_all = self._browser.find_element_by_link_text('Connect All')
        connect_all.click()

    def _add_device(self, port, device_type_id):
        browser = self._browser
        test_bed = browser.find_element_by_id('test-bed')
        device = browser.find_element_by_id(device_type_id)
        # drag
        action_chains = ActionChains(browser)
        action_chains.click_and_hold(device)
        action_chains.move_to_element(test_bed).perform()
        time.sleep(1)

        # drop
        drop_hw = browser.find_element_by_class_name('drop-hw')
        action_chains = ActionChains(browser)
        action_chains.move_to_element(drop_hw)
        action_chains.release(drop_hw).perform()

        time.sleep(0.5)
        selected_hw = browser.find_element_by_class_name('selected-hw')
        form_inputs = selected_hw.find_elements_by_tag_name('input')
        form_port = form_inputs[0]
        form_port.clear()
        form_port.send_keys(port)

    def _test_bed(self):
        """Set up the test bed.

        Connect number of golden devices required by each case.
        """
        browser = self._browser
        test_bed = browser.find_element_by_id('test-bed')
        time.sleep(3)
        selected_hw_set = test_bed.find_elements_by_class_name('selected-hw')
        selected_hw_num = len(selected_hw_set)

        while selected_hw_num:
            remove_button = selected_hw_set[selected_hw_num - 1].find_element_by_class_name(
                'removeSelectedDevice')
            remove_button.click()
            selected_hw_num = selected_hw_num - 1

        devices = [device for device in settings.GOLDEN_DEVICES
                   if not self.history.is_bad_golden_device(device[0]) and \
                   not (settings.DUT_DEVICE and device[0] == settings.DUT_DEVICE[0])]

        logger.info('Available golden devices: %s', json.dumps(devices, indent=2))
        golden_devices_required = self.golden_devices_required

        if self.auto_dut and not settings.DUT_DEVICE:
            golden_devices_required += 1

        if len(devices) < golden_devices_required:
            raise GoldenDeviceNotEnoughError()

        # add golden devices
        number_of_devices_to_add = len(devices) if self.add_all_devices else golden_devices_required
        for i in range(number_of_devices_to_add):
            self._add_device(*devices.pop())

        # add DUT
        if settings.DUT_DEVICE:
            self._add_device(*settings.DUT_DEVICE)

        # enable AUTO DUT
        if self.auto_dut:
            checkbox_auto_dut = browser.find_element_by_id('EnableAutoDutSelection')
            if not checkbox_auto_dut.is_selected():
                checkbox_auto_dut.click()
                time.sleep(1)

            if settings.DUT_DEVICE:
                radio_auto_dut = browser.find_element_by_class_name('AutoDUT_RadBtns')
                if not radio_auto_dut.is_selected():
                    radio_auto_dut.click()

        while True:
            try:
                self._connect_devices()
                button_next = browser.find_element_by_id('nextBtn')
                if not wait_until(lambda: 'disabled' not in button_next.get_attribute('class'),
                                  times=(30 + 4 * number_of_devices_to_add)):
                    bad_ones = []
                    selected_hw_set = test_bed.find_elements_by_class_name('selected-hw')
                    for selected_hw in selected_hw_set:
                        form_inputs = selected_hw.find_elements_by_tag_name('input')
                        form_port = form_inputs[0]
                        if form_port.is_enabled():
                            bad_ones.append(selected_hw)

                    for selected_hw in bad_ones:
                        form_inputs = selected_hw.find_elements_by_tag_name('input')
                        form_port = form_inputs[0]
                        port = form_port.get_attribute('value').encode('utf8')
                        if settings.DUT_DEVICE and port == settings.DUT_DEVICE[0]:
                            if settings.PDU_CONTROLLER_TYPE is None:
                                # connection error cannot recover without power cycling
                                raise FatalError('Failed to connect to DUT')
                            else:
                                raise FailError('Failed to connect to DUT')

                        if settings.PDU_CONTROLLER_TYPE is None:
                            # port cannot recover without power cycling
                            self.history.mark_bad_golden_device(port)

                        # remove the bad one
                        selected_hw.find_element_by_class_name('removeSelectedDevice').click()
                        time.sleep(0.1)

                        if len(devices):
                            self._add_device(*devices.pop())
                        else:
                            devices = None

                    if devices is None:
                        logger.warning('Golden devices not enough')
                        raise GoldenDeviceNotEnoughError()
                    else:
                        logger.info('Try again with new golden devices')
                        continue

                if self.auto_dut and not settings.DUT_DEVICE:
                    radio_auto_dut = browser.find_element_by_class_name('AutoDUT_RadBtns')
                    if not radio_auto_dut.is_selected():
                        radio_auto_dut.click()

                    time.sleep(5)

                button_next.click()
                if not wait_until(lambda: self._browser.current_url.endswith('TestExecution.html'), 20):
                    raise Exception('Failed to load TestExecution page')
            except FailError:
                raise
            except:
                logger.exception('Unexpected error')
            else:
                break

    def _select_case(self, role, case):
        """Select the test case.
        """
        # select the case
        elem = Select(self._browser.find_element_by_id('select-dut'))
        elem.select_by_value(str(role))
        time.sleep(1)

        checkbox = None
        wait_until(lambda: self._browser.find_elements_by_css_selector('.tree-node .tree-title') and True)
        elems = self._browser.find_elements_by_css_selector('.tree-node .tree-title')
        finder = re.compile(r'.*\b' + case + r'\b')
        finder_dotted = re.compile(r'.*\b' + case.replace(' ', r'\.') + r'\b')
        for elem in elems:
            action_chains = ActionChains(self._browser)
            action_chains.move_to_element(elem)
            action_chains.perform()
            logger.debug(elem.text)
            if finder.match(elem.text) or finder_dotted.match(elem.text):
                parent = elem.find_element_by_xpath('..')
                checkbox = parent.find_element_by_class_name('tree-checkbox')
                break

        if not checkbox:
            time.sleep(5)
            raise Exception('Failed to find the case')

        self._browser.execute_script("$('.overview').css('left', '0')")
        checkbox.click()
        time.sleep(1)

        elem = self._browser.find_element_by_id('runTest')
        elem.click()
        if not wait_until(lambda: self._browser.find_element_by_id('stopTest') and True, 10):
            raise Exception('Failed to start test case')

    def _collect_result(self):
        """Collect test result.

        Generate PDF, excel and pcap file
        """
        # generate pdf
        self._browser.find_element_by_class_name('save-pdf').click()
        time.sleep(1)
        try:
            dialog = self._browser.find_element_by_id('Testinfo')
        except:
            logger.exception('Failed to get test info dialog.')
        else:
            if dialog.get_attribute('aria-hidden') != 'false':
                raise Exception('Test information dialog not ready')

            version = self.auto_dut and settings.DUT_VERSION or self.dut.version
            dialog.find_element_by_id('inp_dut_manufacturer').send_keys(settings.DUT_MANUFACTURER)
            dialog.find_element_by_id('inp_dut_firmware_version').send_keys(version)
            dialog.find_element_by_id('inp_tester_name').send_keys(settings.TESTER_NAME)
            dialog.find_element_by_id('inp_remarks').send_keys(settings.TESTER_REMARKS)
            dialog.find_element_by_id('generatePdf').click()

        time.sleep(1)
        main_window = self._browser.current_window_handle

        # generate excel
        self._browser.find_element_by_class_name('save-excel').click()
        time.sleep(1)
        for window_handle in self._browser.window_handles:
            if window_handle != main_window:
                self._browser.switch_to.window(window_handle)
                self._browser.close()
        self._browser.switch_to.window(main_window)

        # save pcap
        self._browser.find_element_by_class_name('save-wireshark').click()
        time.sleep(1)
        for window_handle in self._browser.window_handles:
            if window_handle != main_window:
                self._browser.switch_to.window(window_handle)
                self._browser.close()
        self._browser.switch_to.window(main_window)

        os.system('copy "%%HOMEPATH%%\\Downloads\\NewPdf_*.pdf" %s\\'
                  % self.result_dir)
        os.system('copy "%%HOMEPATH%%\\Downloads\\ExcelReport_*.xlsx" %s\\'
                  % self.result_dir)
        os.system('copy "%s\\Captures\\*.pcapng" %s\\'
                  % (settings.HARNESS_HOME, self.result_dir))
        os.system('copy "%s\\Thread_Harness\\temp\\*.*" "%s"'
                  % (settings.HARNESS_HOME, self.result_dir))

    def _wait_dialog(self):
        """Wait for dialogs and handle them until done.
        """
        logger.debug('waiting for dialog')
        done = False
        error = False

        while not done and self.timeout:
            try:
                dialog = self._browser.find_element_by_id('RemoteConfirm')
            except:
                logger.exception('Failed to get dialog.')
            else:
                if dialog and dialog.get_attribute('aria-hidden') == 'false':
                    title = dialog.find_element_by_class_name('modal-title').text
                    time.sleep(1)
                    logger.info('Handling dialog[%s]', title)

                    try:
                        done = self._handle_dialog(dialog, title)
                    except:
                        logger.exception('Error handling dialog: %s', title)
                        error = True

                    if done is None:
                        raise FailError('Unexpected dialog occurred')

                    dialog.find_element_by_id('ConfirmOk').click()

            time.sleep(1)

            try:
                stop_button = self._browser.find_element_by_id('stopTest')
                if done:
                    stop_button.click()
                    # wait for stop procedure end
                    time.sleep(10)
            except:
                logger.exception('Test stopped')
                time.sleep(5)
                done = True

            self.timeout -= 1

            # check if already ended capture
            if self.timeout % 10 == 0:
                lines = self._hc.tail()
                if 'SUCCESS: The process "dumpcap.exe" with PID ' in lines:
                    logger.info('Tshark should be ended now, lets wait at most 30 seconds.')
                    if not wait_until(lambda: 'tshark.exe' not in subprocess.check_output('tasklist'), 30):
                        res = subprocess.check_output('taskkill /t /f /im tshark.exe',
                                                      stderr=subprocess.STDOUT, shell=True)
                        logger.info(res)

        # Wait until case really stopped
        wait_until(lambda: self._browser.find_element_by_id('runTest') and True, 30)

        if error:
            raise FailError('Fail for previous exceptions')

    def _handle_dialog(self, dialog, title):
        """Handle a dialog.

        Returns:
            bool True if no more dialogs expected,
                 False if more dialogs needed, and
                 None if not handled
        """
        done = self.on_dialog(dialog, title)
        if isinstance(done, bool):
            return done

        if title.startswith('Start DUT'):
            body = dialog.find_element_by_id('cnfrmMsg').text
            if 'Sleepy End Device' in body:
                self.dut.mode = 's'
                self.dut.child_timeout = self.child_timeout
            elif 'End Device' in body:
                self.dut.mode = 'rsn'
                self.dut.child_timeout = self.child_timeout
            else:
                self.dut.mode = 'rsdn'

            if 'at channel' in body:
                self.channel = int(body.split(':')[1])

            self.dut.channel = self.channel
            self.dut.panid = settings.THREAD_PANID
            self.dut.networkname = settings.THREAD_NETWORKNAME
            self.dut.extpanid = settings.THREAD_EXTPANID
            self.dut.start()

        elif (title.startswith('MAC Address Required')
              or title.startswith('DUT Random Extended MAC Address Required')):
            mac = self.dut.mac
            inp = dialog.find_element_by_id('cnfrmInpText')
            inp.clear()
            inp.send_keys('0x%s' % mac)

        elif title.startswith('LL64 Address'):
            ll64 = None
            for addr in self.dut.addrs:
                addr = addr.lower()
                if addr.startswith('fe80') and not re.match('.+ff:fe00:[0-9a-f]{0,4}$', addr):
                    ll64 = addr
                    break

            if not ll64:
                raise FailError('No link local address found')

            logger.info('Link local address is %s', ll64)
            inp = dialog.find_element_by_id('cnfrmInpText')
            inp.clear()
            inp.send_keys(ll64)

        elif title.startswith('Enter Channel'):
            self.dut.channel = self.channel
            inp = dialog.find_element_by_id('cnfrmInpText')
            inp.clear()
            inp.send_keys(str(self.dut.channel))

        elif title.startswith('User Action Needed'):
            body = dialog.find_element_by_id('cnfrmMsg').text
            if body.startswith('Power Down the DUT'):
                self.dut.stop()
            return True

        elif title.startswith('Short Address'):
            short_addr = '0x%s' % self.dut.short_addr
            inp = dialog.find_element_by_id('cnfrmInpText')
            inp.clear()
            inp.send_keys(short_addr)

        elif title.startswith('ML64 Address'):
            ml64 = None
            for addr in self.dut.addrs:
                if addr.startswith('fd') and not re.match('.+ff:fe00:[0-9a-f]{0,4}$', addr):
                    ml64 = addr
                    break

            if not ml64:
                raise Exception('No mesh local address found')

            logger.info('Mesh local address is %s', ml64)
            inp = dialog.find_element_by_id('cnfrmInpText')
            inp.clear()
            inp.send_keys(ml64)

        elif title.startswith('Shield Devices') or title.startswith('Sheild DUT'):
            if self.rf_shield:
                logger.info('Shielding devices')
                with self.rf_shield:
                    self.rf_shield.shield()
            elif self.dut and settings.SHIELD_SIMULATION:
                self.dut.channel = (self.channel == THREAD_CHANNEL_MAX
                                    and THREAD_CHANNEL_MIN) or (self.channel + 1)
            else:
                raw_input('Shield DUT and press enter to continue..')

        elif title.startswith('Unshield Devices') or title.startswith('Bring DUT Back to network'):
            if self.rf_shield:
                logger.info('Unshielding devices')
                with self.rf_shield:
                    self.rf_shield.unshield()
            elif self.dut and settings.SHIELD_SIMULATION:
                self.dut.channel = self.channel
            else:
                raw_input('Bring DUT and press enter to continue..')

        elif title.startswith('Configure Prefix on DUT'):
            body = dialog.find_element_by_id('cnfrmMsg').text
            body = body.split(': ')[1]
            params = reduce(lambda params, param: params.update(((param[0].strip(' '), param[1]),)) or params,
                            [it.split('=') for it in body.split(', ')], {})
            prefix = params['P_Prefix'].strip('\0\r\n\t ')
            flags = []
            if params.get('P_slaac_preferred', 0) == '1':
                flags.append('p')
            flags.append('ao')
            if params.get('P_stable', 0) == '1':
                flags.append('s')
            if params.get('P_default', 0) == '1':
                flags.append('r')
            prf = 'high'
            self.dut.add_prefix(prefix, ''.join(flags), prf)

        return False

    def test(self):
        """This method will only start test case in child class"""
        if self.__class__ is HarnessCase:
            logger.warning('Skip this harness itself')
            return

        logger.info('Testing role[%d] case[%s]', self.role, self.case)
        try:
            self._init_browser()
            # prepare test case
            while True:
                url = self._browser.current_url
                if url.endswith('SetupPage.html'):
                    self._setup_page()
                elif url.endswith('TestBed.html'):
                    self._test_bed()
                elif url.endswith('TestExecution.html'):
                    logger.info('Ready to handle dialogs')
                    break
                time.sleep(2)
        except UnexpectedAlertPresentException:
            logger.exception('Failed to connect to harness server')
            raise SystemExit()
        except FatalError:
            logger.exception('Test stopped for fatal error')
            raise SystemExit()
        except FailError:
            logger.exception('Test failed')
            raise
        except:
            logger.exception('Something wrong')

        self._select_case(self.role, self.case)

        self._wait_dialog()

        try:
            self._collect_result()
        except:
            logger.exception('Failed to collect results')
            raise

        # get case result
        status = self._browser.find_element_by_class_name('title-test').text
        logger.info(status)
        success = 'Pass' in status
        self.assertTrue(success)


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;

namespace NTachyon.Api
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            //var builder = new ConfigurationBuilder()
            //    .SetBasePath(env.ContentRootPath)
            //    .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
            //    .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
            //    .AddEnvironmentVariables();
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();
            services.AddCrontab();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseMvc();
        }
    }
}


text:
package io.aos.endpoint.socket.nio;
import java.net.*;
import java.io.*;
import java.nio.ByteBuffer;
import java.nio.channels.*;

public class NioHelloServer {

  public final static int PORT = 2345;

  public static void main(String... args) throws IOException {

    ServerSocketChannel serverChannel = ServerSocketChannel.open();
    SocketAddress port = new InetSocketAddress(PORT);
    serverChannel.socket().bind(port);

    while (true) {
      try {
        SocketChannel clientChannel = serverChannel.accept();

        String response = "Hello "
         + clientChannel.socket().getInetAddress() + " on port "
         + clientChannel.socket().getPort() + "\r\n";
        response += "This is " + serverChannel.socket() + " on port "
         + serverChannel.socket().getLocalPort() + "\r\n";

        byte[] data = response.getBytes("UTF-8");
        ByteBuffer buffer = ByteBuffer.wrap(data);
        while (buffer.hasRemaining()) clientChannel.write(buffer);
        clientChannel.close();
      }
      catch (IOException ex) {
        // This is an error on one connection. Maybe the client crashed.
        // Maybe it broke the connection prematurely. Whatever happened,
        // it's not worth shutting down the server for.
      }
    }  // end while
  }
} // end NewIOHelloServer


text:
package com.amazonaws.services.rds.model.transform;

import java.util.ArrayList;

import javax.xml.stream.events.XMLEvent;
import javax.annotation.Generated;

import com.amazonaws.services.rds.model.*;
import com.amazonaws.transform.Unmarshaller;

import com.amazonaws.transform.StaxUnmarshallerContext;
import com.amazonaws.transform.SimpleTypeStaxUnmarshallers.*;

/**
 * OptionConfiguration StAX Unmarshaller
 */

@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class OptionConfigurationStaxUnmarshaller implements Unmarshaller<OptionConfiguration, StaxUnmarshallerContext> {

    public OptionConfiguration unmarshall(StaxUnmarshallerContext context) throws Exception {
        OptionConfiguration optionConfiguration = new OptionConfiguration();
        int originalDepth = context.getCurrentDepth();
        int targetDepth = originalDepth + 1;

        if (context.isStartOfDocument())
            targetDepth += 1;

        while (true) {
            XMLEvent xmlEvent = context.nextEvent();
            if (xmlEvent.isEndDocument())
                return optionConfiguration;

            if (xmlEvent.isAttribute() || xmlEvent.isStartElement()) {

                if (context.testExpression("OptionName", targetDepth)) {
                    optionConfiguration.setOptionName(StringStaxUnmarshaller.getInstance().unmarshall(context));
                    continue;
                }

                if (context.testExpression("Port", targetDepth)) {
                    optionConfiguration.setPort(IntegerStaxUnmarshaller.getInstance().unmarshall(context));
                    continue;
                }

                if (context.testExpression("OptionVersion", targetDepth)) {
                    optionConfiguration.setOptionVersion(StringStaxUnmarshaller.getInstance().unmarshall(context));
                    continue;
                }

                if (context.testExpression("DBSecurityGroupMemberships", targetDepth)) {
                    optionConfiguration.withDBSecurityGroupMemberships(new ArrayList<String>());
                    continue;
                }

                if (context.testExpression("DBSecurityGroupMemberships/DBSecurityGroupName", targetDepth)) {
                    optionConfiguration.withDBSecurityGroupMemberships(StringStaxUnmarshaller.getInstance().unmarshall(context));
                    continue;
                }

                if (context.testExpression("VpcSecurityGroupMemberships", targetDepth)) {
                    optionConfiguration.withVpcSecurityGroupMemberships(new ArrayList<String>());
                    continue;
                }

                if (context.testExpression("VpcSecurityGroupMemberships/VpcSecurityGroupId", targetDepth)) {
                    optionConfiguration.withVpcSecurityGroupMemberships(StringStaxUnmarshaller.getInstance().unmarshall(context));
                    continue;
                }

                if (context.testExpression("OptionSettings", targetDepth)) {
                    optionConfiguration.withOptionSettings(new ArrayList<OptionSetting>());
                    continue;
                }

                if (context.testExpression("OptionSettings/OptionSetting", targetDepth)) {
                    optionConfiguration.withOptionSettings(OptionSettingStaxUnmarshaller.getInstance().unmarshall(context));
                    continue;
                }

            } else if (xmlEvent.isEndElement()) {
                if (context.getCurrentDepth() < originalDepth) {
                    return optionConfiguration;
                }
            }
        }
    }

    private static OptionConfigurationStaxUnmarshaller instance;

    public static OptionConfigurationStaxUnmarshaller getInstance() {
        if (instance == null)
            instance = new OptionConfigurationStaxUnmarshaller();
        return instance;
    }
}


text:
using System.Collections.Specialized;
using System.ComponentModel;
using DNTProfiler.ByCommand.Core;
using DNTProfiler.Common.JsonToolkit;
using DNTProfiler.Common.Models;
using DNTProfiler.Common.Mvvm;
using DNTProfiler.Infrastructure.ViewModels;
using DNTProfiler.PluginsBase;

namespace DNTProfiler.ByCommand.ViewModels
{
    public class MainViewModel : MainViewModelBase
    {
        private readonly CallbacksManager _callbacksManager;

        public MainViewModel(ProfilerPluginBase pluginContext)
            : base(pluginContext)
        {
            if (Designer.IsInDesignModeStatic)
                return;

            setActions();
            setGuiModel();
            _callbacksManager = new CallbacksManager(PluginContext, GuiModelData);
            setEvenets();
        }

        private void Commands_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
        {
            switch (e.Action)
            {
                case NotifyCollectionChangedAction.Add:
                    foreach (Command item in e.NewItems)
                    {
                        _callbacksManager.ManageCommands(item);
                    }
                    break;
            }
        }

        private void GuiModelData_PropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            switch (e.PropertyName)
            {
                case "SelectedApplicationIdentity":
                    _callbacksManager.ShowSelectedApplicationIdentityLocalCommands();
                    break;
                case "SelectedExecutedCommand":
                    _callbacksManager.ShowSelectedCommandRelatedStackTraces();
                    break;
            }
        }

        private void setActions()
        {
            PluginContext.Reset = () =>
            {
                ResetAll();
            };

            PluginContext.GetResults = () =>
            {
                return GuiModelData.RelatedCommands.ToFormattedJson();
            };
        }

        private void setEvenets()
        {
            PluginContext.ProfilerData.Commands.CollectionChanged += Commands_CollectionChanged;
        }

        private void setGuiModel()
        {
            GuiModelData.PropertyChanged += GuiModelData_PropertyChanged;
        }
    }
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <TITLE>Generic Image Library: iterator_add_deref Struct Template Reference</TITLE>
    <META HTTP-EQUIV="content-type" CONTENT="text/html;charset=ISO-8859-1"/>
    <LINK TYPE="text/css" REL="stylesheet" HREF="adobe_source.css"/>

Modules
                  | Alphabetical List
                  | Class List
                  | Directories
                  | File List
                  | GIL Home Page

boost::gil::iterator_add_deref

iterator_add_deref Struct Template Reference

[dereference_iterator_adaptor]

#include <pixel_iterator_adaptor.hpp>

List of all members.

Detailed Description

template<typename Iterator, typename Deref>

 struct boost::gil::iterator_add_deref< Iterator, Deref >

Returns the type (and creates an instance) of an iterator that invokes the given dereference adaptor upon dereferencing.

Public Types

typedef

dereference_iterator_adaptor

< Iterator, Deref > 	type

Static Public Member Functions

static type 	make (const Iterator &it, const Deref &d)

The documentation for this struct was generated from the following file:

pixel_iterator_adaptor.hpp

<address style="text-align: right;">Generated on Sat May 2 13:50:18 2009 for Generic Image Library by

 1.5.6 </address>


text:
<?php

class Revision47_InsertSmaertphoneNavigationAndGadgets extends Doctrine_Migration_Base
{
  public function up()
  {
  }
}


text:
import warnings

from django import template
from django.template import VariableDoesNotExist
from django.conf import settings

from customtags.exceptions import TemplateSyntaxWarning

class StaticValue(object):
    """
    A 'constant' internal template variable which basically allows 'resolving'
    returning it's initial value
    """
    def __init__(self, value):
        if isinstance(value, basestring):
            self.value = value.strip('"\'')
        else:
            self.value = value

    def __repr__(self): # pragma: no cover
        return '<StaticValue: %s>' % repr(self.value)

    def resolve(self, context):
        try:
            return self.value
        except VariableDoesNotExist:
            return None

class NullValue(object):
    def __repr__(self):
        return 'NullValue()'

    def resolve(self, context):
        return None

class StringValue(object):
    errors = {}
    value_on_error = ""

    def __init__(self, var):
        self.var = var

    def __repr__(self):
        return "<%s(%s)>" % (self.__class__.__name__, self.var.__repr__())

    def resolve(self, context):
        try:
            resolved = self.var.resolve(context)
            return self.clean(resolved)
        except VariableDoesNotExist:
            return None

    def clean(self, value):
        """
        In the case that the specified string is a static (i.e. explicitly specified)
        value, then do not change it to None.  In any other case, we have to transform
        the empty string to None because the django template engine transforms None
        to the empty string inside resolve().
        """
        if value == "" and not isinstance(self.var, StaticValue):
            return None
        return value

    def error(self, value, category):
        message = self.errors.get(category, "") % {'value': repr(value)}
        if settings.DEBUG:
            raise template.TemplateSyntaxError(message)
        else:
            warnings.warn(message, TemplateSyntaxWarning)
            return self.value_on_error

class IntegerValue(StringValue):
    errors = {
        "clean": "%(value)s could not be converted to Integer",
    }

    def clean(self, value):
        if value == "":
            return None
        try:
            return int(value)
        except ValueError:
            return self.error(value, "clean")

class ListValue(list, StringValue):
    """
    A list of template variables for easy resolving
    """
    def __init__(self, value=None):
        list.__init__(self)
        if value is not None:
            self.append(value)

    def resolve(self, context):
        try:
            resolved = [item.resolve(context) for item in self]
            return self.clean(resolved)
        except VariableDoesNotExist:
            return None

class DictValue(dict, StringValue):
    """
    A dict of template variables for easy resolving
    """
    def __init__(self, key=None, value=None):
        dict.__init__(self)
        if key is not None and value is not None:
            self[key] = value

    def resolve(self, context):
        try:
            resolved = [(key, self[key].resolve(context)) for key in self]
            return self.clean(dict(resolved))
        except VariableDoesNotExist:
            return None


text:
<!DOCTYPE frameset SYSTEM "frameset.dtd">
<frameset>
    <predicate lemma="quantize">

        <roleset framnet="" id="quantize.01" name="quantize" vncls="34.2">
            <roles>
                <role descr="quantizer(s), agent" f="" n="0">
                    <vnrole vncls="34.2" vntheta="agent"/>
                </role>
                <role descr="thing quantized, theme" f="" n="1">
                    <vnrole vncls="34.2" vntheta="theme"/>
                </role>
                <role descr="value/amount of quantization" f="" n="2"/>

                <note/>
                <role descr="quantized into what, destination" f="" n="3"/>
            </roles>
            <example name="regular usage" src="web usage" type="">
                <text>They quantized the host image and obtained the residual.</text>

                <note/>
                <arg f="" n="0">They</arg>
                <rel f="">quantized</rel>
                <arg f="" n="1">the host image</arg>
            </example>

            <note>hand-checked by Kevin</note>
        </roleset>

        <note>Automatically created based on framefiles: gauge (34.2)</note>
    </predicate>

    <note/>
</frameset>


text:
<template name="AddUpdateMinutes">

  {{#if is_visible}}

    {{#if is_add}}

Entering a new set of minutes

    {{else}}

Updating an existing set of minutes

    {{/if}}

    <form class="ui fluid form">

          {{# if is_add }}
          <input type="text" id="minutes_date" name="minutes_date" value={{todays_date}}>
          {{else}}
          <input type="text" id="minutes_date" name="minutes_date" value="{{existing_content 'date'}}">
          {{/if}}

      {{#if missing_content "date"}}

        Enter a date

      {{/if}}

        <select id="minutes_type" class="ui dropdown scrolling minutes_type_select">
          <option value="">Select a minutes type</option>
          {{#each list_of_minutes_types}}
          {{#if is_add}}
          <option value="{{this}}" class=""> {{this}}</option>
          {{else}}
          {{#if is_selected_type }}
          <option value="{{this}}" selected class="">{{this}} </option>
          {{else}}
          <option value="{{this}}" class="">{{this}} </option>
          {{/if}}
          {{/if}}
          {{/each}}
        </select>
        {{#if missing_content "type"}}

          Select a minutes type

        {{/if}}

    </form>

    <form class="ui fluid form">

        <textarea rows=3 placeholder="Enter a list of participants" id="minutes_participants">{{#if is_update}}{{existing_content "participants"}}{{/if}}</textarea>

        {{#if missing_content "participants"}}

          Enter a list of participants

        {{/if}}

    </form>

    <form class="ui fluid form">

        <textarea placeholder="Enter minutes description..." id="minutes_minutes" rows=15>{{#if is_update}}{{existing_content "minutes"}}{{/if}}</textarea>
        {{#if missing_content "minutes"}}

          Enter minutes

        {{/if}}

    </form>

    {{#if are_there_errors}}

      Correct the above errors

    {{/if}}

    {{#if is_add}}
    <button class="ui button green" id="submit">Save</button>
    {{else}}
    <button class="ui button green" id="submit">Save</button>
    {{/if}}

    <button class="ui button red" id="cancel">Cancel</button>

  {{/if}}

</template>


text:
import pymunk
import math

from .base_shape import BaseShape

class RotarySpring(BaseShape):
    def __init__(self, space, shape1, shape2, angle, stiffness, damping):
        # Associate the joint with the location of one of the bodies so
        # it is removed when that body is out of the simulation
        self.body = shape1.body
        self.shape = pymunk.DampedRotarySpring(shape1.body, shape2.body, math.radians(-angle), stiffness, damping)
        super().__init__()

        space.add(self.shape)

    def has_own_body(self):
        return False

    def _draw(self, screen):
        pass

    def _pin_points(self):
        raise Exception('Do not use draw_on for rotary springs')

    def __repr__(self):
        return 'rotary_spring: p(' + str(self.body.position.x) + ',' + str(self.body.position.y) + '), rest angle: ' + \
               str(-math.degrees(self.shape.rest_angle))


text:
<?php namespace Kreitje\L4SchemadMigrations;

use Illuminate\Support\ServiceProvider;
use Illuminate\Database\MigrationServiceProvider;

class L4SchemadMigrationsServiceProvider extends MigrationServiceProvider {

	/**
	 * Indicates if loading of the provider is deferred.
	 *
	 * @var bool
	 */
	protected $defer = false;

	/**
	 * Register the service provider.
	 *
	 * @return void
	 */
	public function register()
	{
		$this->registerRepository();
		$this->registerSchemaMigrator();
		$this->registerCommands();
	}

	public function registerSchemaMigrator() {
		$this->app->bindShared('migrator', function($app)
		{
			$repository = $app['migration.repository'];

			return new Migrator($repository, $app['db'], $app['files']);
		});
	}

	/**
	 * Get the services provided by the provider.
	 *
	 * @return array
	 */
	public function provides()
	{
		return array();
	}

}


text:
.tempo-recurrenteventset {
    display: table;
}

.tempo-recurrenteventset-operator {
    display: table-cell;
    vertical-align: middle;
    width: 30px;
    background-color: #C8D8E9;
    padding: 10px 5px;
}

.tempo-controls {
    display: table;
    width: 100%;
    border-bottom: solid #D2D2D2 1px;
    clear: both;
    margin-bottom: 5px;
    padding-bottom: 5px;
}
.tempo-controls:before { content: '\A'; }
.tempo-controls:after { content: '\A'; }

.tempo-recurrenteventset-controls {
    display: inline-block;
}

.tempo-recurrentevent-from, .tempo-recurrentevent-to {
    width: 30px;
    display: inline;
}

.tempo-recurrenteventset-remove, .tempo-recurrentevent-remove {
    font-size: 14px;
    margin-right: 5px;
}

.tempo-recurrenteventset-add, .tempo-recurrenteventset-addset {
    display: table-cell;
    font-size: 10px;
    padding: 10px;
}

.tempo-recurrenteventset-operands {
    padding-left: 10px;
    display: table;
    /*float: left;*/
}


text:
package com.maalaang.waltz.Adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.maalaang.waltz.R;
import com.maalaang.waltz.model.DrawerListData;

import java.util.ArrayList;

/**
 * Created by User on 2015-02-03.
 */

public class DrawerListAdapter extends ArrayAdapter<DrawerListData> {

    private LayoutInflater inflater = null;
    private ArrayList<DrawerListData> drawerList = null;
    private ViewHolder viewHolder = null;
    private Context mContext = null;

    public DrawerListAdapter(Context c, int textViewResourceId, ArrayList<DrawerListData> arrays) {
        super(c, textViewResourceId, arrays);
        this.mContext = c;
        this.inflater = LayoutInflater.from(c);
        this.drawerList = arrays;
    }

    @Override
    public int getCount() {
        return drawerList.size();
    }

    @Override
    public View getView(int position, View convertview, ViewGroup parent) {

        View v = convertview;

        if(v == null){
            viewHolder = new ViewHolder();
            v = inflater.inflate(R.layout.drawer_item, null);
            viewHolder.tv_title = (TextView)v.findViewById(R.id.drawer_tv_list);
            viewHolder.iv_image = (ImageView)v.findViewById(R.id.drawer_iv_list);

            v.setTag(viewHolder);

        }else {
            viewHolder = (ViewHolder)v.getTag();
        }
        viewHolder.tv_title.setText(getItem(position).getTitle());
        viewHolder.iv_image.setTag(position);
        return v;
    }

    @Override
    public DrawerListData getItem(int position) {
        return drawerList.get(position);
    }

    class ViewHolder{
        public TextView tv_title = null;
        public ImageView iv_image = null;
    }

    @Override
    protected void finalize() throws Throwable {
        free();
        super.finalize();
    }

    private void free(){
        inflater = null;
        drawerList = null;
        viewHolder = null;
        mContext = null;
    }
}