text:
import { Span } from '@opentelemetry/api';
import { registerInstrumentations } from '@opentelemetry/instrumentation';
import { SemanticAttributes } from '@opentelemetry/semantic-conventions';
import { ReadableSpan, SpanProcessor } from '@opentelemetry/sdk-trace-base';
import { WebTracerProvider } from '@opentelemetry/sdk-trace-web';
import { XMLHttpRequestInstrumentation } from '../src';
import assert = require('assert');

class TestSpanProcessor implements SpanProcessor {
  spans: ReadableSpan[] = [];

  forceFlush(): Promise<void> {
    return Promise.resolve();
  }
  onStart(span: Span): void {}
  shutdown(): Promise<void> {
    return Promise.resolve();
  }

  onEnd(span: ReadableSpan): void {
    this.spans.push(span);
  }
}

describe('unmocked xhr', () => {
  let testSpans: TestSpanProcessor;
  let provider: WebTracerProvider;
  beforeEach(() => {
    provider = new WebTracerProvider();
    registerInstrumentations({
      instrumentations: [new XMLHttpRequestInstrumentation()],
      tracerProvider: provider,
    });
    testSpans = new TestSpanProcessor();
    provider.addSpanProcessor(testSpans);
  });
  afterEach(() => {
    // nop
  });

  it('should find resource with a relative url', done => {
    const xhr = new XMLHttpRequest();
    let path = location.pathname;
    path = path.substring(path.lastIndexOf('/') + 1);
    xhr.open('GET', path);
    xhr.addEventListener('loadend', () => {
      setTimeout(() => {
        assert.strictEqual(testSpans.spans.length, 1);
        const span = testSpans.spans[0];
        // content length comes from the PerformanceTiming resource; this ensures that our
        // matching logic found the right one
        assert.ok(
          (span.attributes[
            SemanticAttributes.HTTP_RESPONSE_CONTENT_LENGTH
          ] as any) > 0
        );
        done();
      }, 500);
    });
    xhr.send();
  });
});


text:
scikit-protopy
==============

Prototype Selection and Generation Toolbox based on scikit-learn.

This project was started in 2014 by Dayvid Victor as a result of
his masters and on-going PhD at Federal University of Pernambuco.

The aim of this project is to provide Prototype Selection (PS) and
Prototype Generation (PG) techniques to be applied where instance
reduction is needed (noisy sensitive domains, imbalanced datasets,
high density clusters ...).

Right now, this project is referenced in the scikit-learn official
wiki (https://github.com/scikit-learn/scikit-learn/wiki/Third-party-projects-and-code-snippets).
Hopefully, the PS/PG techniques might be included in the scikit-learn
project anytime soon.

Dependencies
============

This is designed to work with:
- Python 2.6+
- scikit-learn == 0.16.0
- Numpy >= 1.3
- SciPy >= 0.7
- Matplotlib >= 0.99.1. (for examples, only)

Install
=======

To install, use::

    sudo python setup.py install

To install via easy\_install, use::

    sudo easy_install .

Important References
====================

For all algorithms a reference is provided. But if you are new to
PS/PG, we recommend the following papers:

- **Prototype Selection**: Garcia, Salvador, et al. "Prototype selection for nearest neighbor classification: Taxonomy and empirical study." Pattern Analysis and Machine Intelligence, IEEE Transactions on 34.3 (2012): 417-435.

- **Prototype Generation**: Triguero, Isaac, et al. "A taxonomy and experimental study on prototype generation for nearest neighbor classification." Systems, Man, and Cybernetics, Part C: Applications and Reviews, IEEE Transactions on 42.1 (2012): 86-100.

redpajama_set_name: RedPajamaGithub


text:
title: Book List
layout: single
tags:
  - book
  - list
  - queue
sitemap: true
comments: false
modified: {}
author_profile: true
published: true
---

Here I'll post a list of books that I mark as important to me.
Any read material that atracts me: Articles/Books of tech, science, astronomy, biology, math, arts, social, history, philosofy...

I'll do my best to categorize that in the best way....but sometimes...you know....will only make sense in my head. Sorry! ;)

## IT, Computer Science, Programming

### Big data, data science, data analysis

* Roger D. Peng. [R Programming for Data Science](https://leanpub.com/rprogramming).    ([+info and my notes](myNotes/R-programming-data-science))

## Math, Physics, Statistic

* James, Witten, Hastie, and Tibshirani. [An Introduction To Statistical Learning](http://www-bcf.usc.edu/%7Egareth/ISL/).


text:
/****** Object:  StoredProcedure [dbo].[app_ProgramGameLevel_Update]    Script Date: 01/05/2015 14:43:25 ******/
--Create the Update Proc
CREATE PROCEDURE [dbo].[app_ProgramGameLevel_Update] (
	@PGLID INT,
	@PGID INT,
	@LevelNumber INT,
	@LocationX INT,
	@LocationY INT,
	@PointNumber INT,
	@Minigame1ID INT,
	@Minigame2ID INT,
	@AwardBadgeID INT,
	@LastModDate DATETIME,
	@LastModUser VARCHAR(50),
	@AddedDate DATETIME,
	@AddedUser VARCHAR(50),
	@LocationXBonus INT,
	@LocationYBonus INT,
	@Minigame1IDBonus INT,
	@Minigame2IDBonus INT,
	@AwardBadgeIDBonus INT
	)
AS
UPDATE ProgramGameLevel
SET PGID = @PGID,
	LevelNumber = @LevelNumber,
	LocationX = @LocationX,
	LocationY = @LocationY,
	PointNumber = @PointNumber,
	Minigame1ID = @Minigame1ID,
	Minigame2ID = @Minigame2ID,
	AwardBadgeID = @AwardBadgeID,
	LastModDate = @LastModDate,
	LastModUser = @LastModUser,
	AddedDate = @AddedDate,
	AddedUser = @AddedUser,
	LocationXBonus = @LocationXBonus,
	LocationYBonus = @LocationYBonus,
	Minigame1IDBonus = @Minigame1IDBonus,
	Minigame2IDBonus = @Minigame2IDBonus,
	AwardBadgeIDBonus = @AwardBadgeIDBonus
WHERE PGLID = @PGLID


text:
package errors

// Walk performs a depth-first traversal of the supplied error, unfolding it and
// invoke the supplied callback for each layered error recursively. If the
// callback returns true, Walk will continue its traversal.
//
//	- If walk encounters a MultiError, the callback is called once for the
//	  outer MultiError, then once for each inner error.
//	- If walk encounters a Wrapped error, the callback is called for the outer
//	  and inner error.
//	- If an inner error is, itself, a container, Walk will recurse into it.
//
// If err is nil, the callback will not be invoked.
func Walk(err error, fn func(error) bool) {
	_ = walkVisit(err, fn, false)
}

// WalkLeaves is like Walk, but only calls fn on leaf nodes.
func WalkLeaves(err error, fn func(error) bool) {
	_ = walkVisit(err, fn, true)
}

func walkVisit(err error, fn func(error) bool, leavesOnly bool) bool {
	if err == nil {
		return true
	}

	// Call fn if we are not in leavesOnly mode.
	if !(leavesOnly || fn(err)) {
		return false
	}

	switch t := err.(type) {
	case MultiError:
		for _, e := range t {
			if !walkVisit(e, fn, leavesOnly) {
				return false
			}
		}

	case Wrapped:
		return walkVisit(t.Unwrap(), fn, leavesOnly)

	default:
		if leavesOnly {
			return fn(err)
		}
	}

	return true
}

// Any performs a Walk traversal of an error, returning true (and
// short-circuiting) if the supplied filter function returns true for any
// visited error.
//
// If err is nil, Any will return false.
func Any(err error, fn func(error) bool) (any bool) {
	Walk(err, func(err error) bool {
		any = fn(err)
		return !any
	})
	return
}

// Contains performs a Walk traversal of |outer|, returning true if any visited
// error is equal to |inner|.
func Contains(outer error, inner error) bool {
	return Any(outer, func(item error) bool {
		if item == inner {
			return true
		}
		if is, ok := item.(interface{ Is(error) bool }); ok {
			return is.Is(inner)
		}
		return false
	})
}


text:
'''
Philips HUE lamps module for proxy.
'''

from __future__ import absolute_import
import sys

__virtualname__ = 'hue'
__proxyenabled__ = ['philips_hue']

def _proxy():
    '''
    Get proxy.
    '''
    return __opts__['proxymodule']

def __virtual__():
    '''
    Start the Philips HUE only for proxies.
    '''

    def _mkf(cmd_name, doc):
        def _cmd(*args, **kw):
            return _proxy()[_proxy().loaded_base_name + "." + cmd_name](*args, **kw)
        return _cmd

    import salt.proxy.philips_hue as hue
    for method in dir(hue):
        if method.startswith('call_'):
            setattr(sys.modules[__name__], method[5:], _mkf(method, getattr(hue, method).__doc__))
    del hue

    return _proxy() and __virtualname__ or False


text:
import constants from './constants';
import update from 'immutability-helper';

type ActionType = constants.UPDATE | constants.RESET;

type ReducerState = {
  lastFormName: string;
  lastActionType: string;
  data: Object
}

const defaultState = (): ReducerState => ({
  lastFormName: '',
  lastActionType: '',
  data: {}
});

const getDelta = (type: ActionType, name: string, data: Object): Object => ({
  lastFormName: {
    $set: name
  },
  lastActionType: {
    $set: type
  },
  data: {
    [name]: {
      $set: data
    }
  }
});

const doUpdateAction = (state: ReducerState, action: Object): ReducerState => {
  const payload: Object = action.payload;

  const delta = getDelta(constants.UPDATE, payload.name, {
    formData: payload.formData,
    formMeta: payload.formMeta
  });

  return update(state, delta);
}

const doResetAction = (state: ReducerState, action: Object): ReducerState => {
  const payload: Object = action.payload;
  const delta = getDelta(constants.RESET, payload.name, {});
  return update(state, delta);
}

function reducer(state: ReducerState = defaultState(), action: Object = {}): ReducerState {
  if (action.type === constants.UPDATE) {
    return doUpdateAction(state, action);
  }

  if (action.type === constants.RESET) {
    return doResetAction(state, action);
  }

	return state;
}

export {defaultState};
export default reducer;


text:
The median is the middle value in an ordered integer list. If the size of the list is even, there is no middle value and the median is the mean of the two middle values.

- For example, for arr = [2,3,4], the median is 3.
- For example, for arr = [2,3], the median is (2 + 3) / 2 = 2.5.

Implement the MedianFinder class:

- `MedianFinder()` initializes the MedianFinder object.
- `void addNum(int num)` adds the integer num from the data stream to the data structure.
- `double findMedian()` returns the median of all elements so far. Answers within 10^-5 of the actual answer will be accepted.

### Example 1:

```
Input
["MedianFinder", "addNum", "addNum", "findMedian", "addNum", "findMedian"]
[[], [1], [2], [], [3], []]
Output
[null, null, null, 1.5, null, 2.0]

Explanation
MedianFinder medianFinder = new MedianFinder();
medianFinder.addNum(1);    // arr = [1]
medianFinder.addNum(2);    // arr = [1, 2]
medianFinder.findMedian(); // return 1.5 (i.e., (1 + 2) / 2)
medianFinder.addNum(3);    // arr[1, 2, 3]
medianFinder.findMedian(); // return 2.0
```

### Constraints:

- -10^5 <= num <= 10^5
- There will be at least one element in the data structure before calling findMedian.
- At most 5 \* 10^4 calls will be made to addNum and findMedian.

### Follow up:

- If all integer numbers from the stream are in the range [0, 100], how would you optimize your solution?
- If 99% of all integer numbers from the stream are in the range [0, 100], how would you optimize your solution?

#Two Pointers #Design #Sorting #Heap #Data Stream


text:
package opus.gwt.management.console.client.dashboard;

import com.google.gwt.core.client.JsArrayString;

public class DeployedURLS extends JsArrayString{
	protected DeployedURLS(){}
}


text: echo build complited


text:
from __future__ import absolute_import
import datetime
import logging
import os
import random
import tempfile

import py_utils
from py_utils import cloud_storage  # pylint: disable=import-error
from telemetry.util import image_util
from telemetry.internal.util import file_handle

def TryCaptureScreenShot(platform, tab=None, timeout=None):
  """ If the platform or tab supports screenshot, attempt to take a screenshot
  of the current browser.

  Args:
    platform: current platform
    tab: browser tab if available
    timeout: An float denoting the number of seconds to wait for a successful
        screenshot. If set to None, only attempts once.

  Returns:
    file handle of the tempoerary file path for the screenshot if
    present, None otherwise.
  """
  try:
    if platform.CanTakeScreenshot():
      tf = tempfile.NamedTemporaryFile(delete=False, suffix='.png')
      tf.close()
      try:
        py_utils.WaitFor(lambda: platform.TakeScreenshot(tf.name), timeout or 0)
      except py_utils.TimeoutException:
        logging.warning('Did not succeed in screenshot capture')
      return file_handle.FromTempFile(tf)
    if tab and tab.IsAlive() and tab.screenshot_supported:
      tf = tempfile.NamedTemporaryFile(delete=False, suffix='.png')
      tf.close()
      image = tab.Screenshot()
      image_util.WritePngFile(image, tf.name)
      return file_handle.FromTempFile(tf)
    logging.warning(
        'Either tab has crashed or browser does not support taking tab '
        'screenshot. Skip taking screenshot on failure.')
    return None
  except Exception as e: # pylint: disable=broad-except
    logging.warning('Exception when trying to capture screenshot: %s', repr(e))
    return None

def TryCaptureScreenShotAndUploadToCloudStorage(platform, tab=None):
  """ If the platform or tab supports screenshot, attempt to take a screenshot
  of the current browser.  If present it uploads this local path to cloud
  storage and returns the URL of the cloud storage path.

  Args:
    platform: current platform
    tab: browser tab if available

  Returns:
    url of the cloud storage path if screenshot is present, None otherwise
  """
  fh = TryCaptureScreenShot(platform, tab)
  if fh is not None:
    return _UploadScreenShotToCloudStorage(fh)

  return None

def _GenerateRemotePath(fh):
  return ('browser-screenshot_%s-%s%-d%s' %
          (fh.id, datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S'),
           random.randint(1, 100000), fh.extension))

def _UploadScreenShotToCloudStorage(fh):
  """ Upload the given screenshot image to cloud storage and return the
    cloud storage url if successful.
  """
  try:
    return cloud_storage.Insert(cloud_storage.TELEMETRY_OUTPUT,
                                _GenerateRemotePath(fh), fh.GetAbsPath())
  except cloud_storage.CloudStorageError as err:
    logging.error('Cloud storage error while trying to upload screenshot: %s',
                  repr(err))
    return '<Missing link>'
  finally:  # Must clean up screenshot file if exists.
    os.remove(fh.GetAbsPath())


text:
package org.apache.axis2.rmi.databind.dto;

public class Activate {

    private CancelWorkflowRequest CancelWorkflowRequest;

    public CancelWorkflowRequest getCancelWorkflowRequest() {
        return CancelWorkflowRequest;
    }

    public void setCancelWorkflowRequest(CancelWorkflowRequest cancelWorkflowRequest) {
        CancelWorkflowRequest = cancelWorkflowRequest;
    }
}


text:
package elastic

import (
	"bytes"
	"encoding/json"
	"errors"
	"fmt"
	"io/ioutil"
	"net/http"
	"time"

	"github.com/khezen/bulklog/pkg/auth"
	"github.com/khezen/bulklog/pkg/collection"
)

var (
	// ErrNotAcknowledged - creation request has been sent but not acknowledged by elasticsearh
	ErrNotAcknowledged = errors.New("ErrNotAcknowledged - creation request has been sent but not acknowledged by elasticsearh")
)

// Elastic is a client for Elasticsearch API
type Elastic struct {
	signer                         auth.Signer
	bulkEndpoint, templateEndpoint string
	httpcli                        http.Client
}

// New returns a elasticsearch as a output
func New(cfg Config) *Elastic {
	if cfg.Scheme == "" {
		cfg.Scheme = "http"
	}
	bulkEndpoint := fmt.Sprintf("%s://%s/_bulk", cfg.Scheme, cfg.Endpoint)
	createTemplateEndpoint := fmt.Sprintf("%s://%s/_template", cfg.Scheme, cfg.Endpoint)
	var signer auth.Signer
	switch {
	case cfg.AWSAuth != nil:
		signer = auth.NewAWSSigner(*cfg.AWSAuth, "es")
	case cfg.BasicAuth != nil:
		signer = auth.NewBasicSigner(*cfg.BasicAuth)
	}
	return &Elastic{
		signer,
		bulkEndpoint,
		createTemplateEndpoint,
		http.Client{
			Transport: &http.Transport{
				MaxIdleConns:       10,
				IdleConnTimeout:    30 * time.Second,
				DisableCompression: true,
			},
		},
	}
}

// Digest send bulk request to Elasticsearch
func (c *Elastic) Digest(documents []collection.Document) error {
	buf := bytes.NewBuffer([]byte{})
	for _, doc := range documents {
		docBytes, err := Digest(doc)
		if err != nil {
			return fmt.Errorf("Digest.%s", err)
		}
		buf.Write(docBytes)
	}
	req, err := http.NewRequest("POST", c.bulkEndpoint, buf)
	if err != nil {
		return fmt.Errorf("http.NewRequest.%s", err)
	}
	req.Header.Add("Content-Type", "application/json")
	err = c.sign(req, buf.Bytes())
	if err != nil {
		return fmt.Errorf("Sign.%s", err)
	}
	res, err := c.httpcli.Do(req)
	if err != nil {
		return fmt.Errorf("httpClient.Do.%s", err)
	}
	if res.StatusCode > 300 {
		resBody, err := ioutil.ReadAll(res.Body)
		if err != nil {
			return fmt.Errorf("ioutil.ReadAll.%s", err)
		}
		return fmt.Errorf("elasticsearch: %s : %b", res.Status, resBody)
	}
	return nil
}

// Ensure creates a template in Elasticsearch
func (c *Elastic) Ensure(collection *collection.Collection) error {
	endpoint := fmt.Sprintf("%s/%s", c.templateEndpoint, collection.Name)
	elasticIndex := RenderElasticIndex(collection)
	elasticIndexBytes, err := json.Marshal(elasticIndex)
	if err != nil {
		return fmt.Errorf("json.Marshal.%s", err)
	}
	buf := bytes.NewBuffer(elasticIndexBytes)
	req, err := http.NewRequest("POST", endpoint, buf)
	if err != nil {
		return fmt.Errorf("http.NewRequest.%s", err)
	}
	req.Header.Add("Content-Type", "application/json")
	err = c.sign(req, elasticIndexBytes)
	if err != nil {
		return fmt.Errorf("Sign.%s", err)
	}
	res, err := c.httpcli.Do(req)
	if err != nil {
		return fmt.Errorf("httpClient.Do.%s", err)
	}
	defer res.Body.Close()
	if res.StatusCode != http.StatusOK {
		return ErrNotAcknowledged
	}
	return nil
}

func (c *Elastic) sign(req *http.Request, body []byte) (err error) {
	if c.signer != nil {
		err = c.signer.Sign(req, body)
	}
	return err
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>simple-io: Error with dependencies 🚒</title>
    <link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" />
    <link href="../../../../../bootstrap.min.css" rel="stylesheet">
    <link href="../../../../../bootstrap-custom.css" rel="stylesheet">
    <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">

             Coq bench

clean / released

8.12.2 / simple-io - 1.0.0

            « Up

              simple-io

                1.0.0
                Error with dependencies 🚒

📅  (2022-09-24 11:57:39 UTC)

Context

# Packages matching: installed
# Name              # Installed # Synopsis
base-bigarray       base
base-threads        base
base-unix           base
conf-findutils      1           Virtual package relying on findutils
coq                 8.12.2      Formal proof management system
num                 1.4         The legacy Num library for arbitrary-precision integer and rational arithmetic
ocaml               4.06.1      The OCaml compiler (virtual package)
ocaml-base-compiler 4.06.1      Official 4.06.1 release
ocaml-config        1           OCaml Switch Configuration
ocamlfind           1.9.5       A library manager for OCaml
# opam file:
opam-version: "2.0"
maintainer: "Li-yao Xia <lysxia@gmail.com>"
authors: "Li-yao Xia"
homepage: "https://github.com/Lysxia/coq-simple-io"
bug-reports: "https://github.com/Lysxia/coq-simple-io/issues"
license: "MIT"
dev-repo: "git+https://github.com/Lysxia/coq-simple-io.git"
build: [
  [make "build"]
  [make "test"] {with-test}
]
install: [make "install"]
remove: [make "uninstall"]
depends: [
  "ocaml"
  "coq"
  "coq-ext-lib" {>= "0.10.0"}
  "ocamlbuild" {with-test & >= "0.9.0"}
]
tags: [
  "date:2019-02-02"
  "logpath:SimpleIO"
  "keyword:extraction"
  "keyword:effects"
]
synopsis: "IO monad for Coq"
description: """
This library provides tools to implement IO programs directly in Coq, in a
similar style to Haskell. Facilities for formal verification are not included.
IO is defined as a parameter with a purely functional interface in Coq,
to be extracted to OCaml. Some wrappers for the basic types and functions in
the OCaml Pervasives module are provided. Users are free to define their own
APIs on top of this IO type."""
url {
  src: "https://github.com/Lysxia/coq-simple-io/archive/1.0.0.tar.gz"
  checksum:
    "sha256=a15bf89a0282cdccd909219e328bf278f704627cb9c93d3bd8fe22197319091b"
}

Lint

Command

true

Return code

0

Dry install 🏜

Dry install with the current Coq version:

Command

opam install -y --show-action coq-simple-io.1.0.0 coq.8.12.2

Return code

0

Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:

Command

true

Return code

0

Install dependencies

Command

opam list; echo; ulimit -Sv 4000000; timeout 4h opam install -y --deps-only coq-simple-io.1.0.0 coq.8.12.2

Return code

7936

Duration

11 s

Output

# Packages matching: installed
# Name              # Installed # Synopsis
base-bigarray       base
base-threads        base
base-unix           base
conf-findutils      1           Virtual package relying on findutils
coq                 8.12.2      Formal proof management system
num                 1.4         The legacy Num library for arbitrary-precision integer and rational arithmetic
ocaml               4.06.1      The OCaml compiler (virtual package)
ocaml-base-compiler 4.06.1      Official 4.06.1 release
ocaml-config        1           OCaml Switch Configuration
ocamlfind           1.9.5       A library manager for OCaml
The following actions will be performed:
  - install coq-ext-lib 0.11.7
<><> Gathering sources ><><><><><><><><><><><><><><><><><><><><><><><><><><><><>
[coq-ext-lib.0.11.7] downloaded from https://github.com/coq-community/coq-ext-lib/archive/v0.11.7.tar.gz
<><> Processing actions <><><><><><><><><><><><><><><><><><><><><><><><><><><><>
[ERROR] The compilation of coq-ext-lib failed at "/home/bench/.opam/opam-init/hooks/sandbox.sh build make -j4 theories".
#=== ERROR while compiling coq-ext-lib.0.11.7 =================================#
# context              2.0.5 | linux/x86_64 | ocaml-base-compiler.4.06.1 | file:///home/bench/run/opam-coq-archive/released
# path                 ~/.opam/ocaml-base-compiler.4.06.1/.opam-switch/build/coq-ext-lib.0.11.7
# command              ~/.opam/opam-init/hooks/sandbox.sh build make -j4 theories
# exit-code            2
# env-file             ~/.opam/log/coq-ext-lib-19279-0a5907.env
# output-file          ~/.opam/log/coq-ext-lib-19279-0a5907.out
### output ###
# [...]
# COQDEP VFILES
# /bin/sh: 1: coqdep: not found
# COQC theories/ExtLib.v
# COQC theories/Tactics.v
# /bin/sh: 1: coqc: not found
# /bin/sh: 1: coqc: not found
# make[2]: *** [Makefile.coq:716: theories/ExtLib.vo] Error 127
# make[2]: *** Waiting for unfinished jobs....
# make[2]: *** [Makefile.coq:716: theories/Tactics.vo] Error 127
# make[1]: *** [Makefile.coq:339: all] Error 2
# make[1]: Leaving directory '/home/bench/.opam/ocaml-base-compiler.4.06.1/.opam-switch/build/coq-ext-lib.0.11.7'
# make: *** [Makefile:7: theories] Error 2
<><> Error report <><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><>
+- The following actions failed
| - build coq-ext-lib 0.11.7
+-
- No changes have been performed
# Run eval $(opam env) to update the current shell environment

Install 🚀

Command

true

Return code

0

Duration

0 s

Installation size

No files were installed.

Uninstall 🧹

Command

true

Return code

0

Missing removes

                none

Wrong removes

                none

          Sources are on GitHub © Guillaume Claret 🐣


text:
Если у Вас не установлен [Composer](http://getcomposer.org/), вы должны установить его следуя инструкция
на официальном сайтеа [getcomposer.org](http://getcomposer.org/doc/00-intro.md#installation-nix).

Новый проект Вы можете создаь выполнив команду:
```
php composer.phar create-project --prefer-dist --stability=dev rmrevin/yii2-application my-new-application
```

## Подготовка окружения

Для обработки bower пакетов, в системе требуется глобально установить пакет `fxp/composer-asset-plugin`. Делается это командой
```
php composer.phar global require "fxp/composer-asset-plugin:1.0.0"
```
Для полуавтоматического деплоя используется phing. Установить phing не составляет труда. Для этого необходимо выполнить команду
```bash
pear channel-discover pear.phing.info
pear install --alldeps phing/phing
```

## Деплой

Document root -
* Web - `~/frontend-app/web`

1. Клонировать проект через git
2. Скопировать файл `.environment.example.php` в `.environment.php`, заполнить необходимые данные. MYSQL - основаня база, MYSQL_TEST - копия базы для автоматических тестов.
3. Установить зависимости через композер `./composer.phar install` (если нет композера, установить через `./getcomposer`)
4. С помощью команды `./init` выбрать нужное окружение
5. Развернуть миграции `./frontend migrate`
6. Установить frontend зависимости через npm `npm install`
7. Скомпилировать less в css `phing less`
8. Создать пользователя-администратора `./frontend user/add`, программа спросит придумать имя, email и пароль

Система готова к эксплуатации.

## Обновление

1. Обновить кодовую базу через git
2. Обновить композер `./composer.phar selfupdate`
3. Обновить зависимости через композер `./composer.phar update`
4. Развернуть новые миграции `./frontend migrate`
5. Оновить frontend зависимости через npm `npm update`
6. Скомпилировать less в css `phing less`

Система готова к эксплуатации.

## Полуавтоматический деплой и обновление

Сначала потребуется скачать обновление из гита командой `git pull`, затем выполнить одну из команд:
* `phing build/production` - собрать проект для продакшена.
* `phing build/demo` - собрать проект для demo площадки.
* `phing build/dev` - собрать проект для dev площадки.

Дополнительно доступны следующие команды (они выполняются в рамках `build/*` команд, и добавлены только для справки):
* `phing clear` - удалить все временные файлы и логи во всех приложениях.
* `phing clear/frontend` - удалить все временные файлы и логи в приложении frontend.
* `phing migrate` - выполнить все новые миграции для всех приложений
* `phing migrate/frontend` - выполнить все новые миграции для приложения frontend

## Основные моменты

За основу каркаса взят yii2-advance-application. Он позволяет создавать комплекс из разных приложений с разными подходами (обычное web приложение, cli приложение, rest приложение).
На данный момент, в проекте созданны следующие приложения:
* frontend-app - основное web приложение.

Так же присутствуют несколько вспомогательных разделов:
* common - общие для всех приложений ресурсы (конфиги, расширяющие компоненты фреймворка, хелперы)
* frontend-modules - здесь хранятся модули для web приложения. Это как раз таки те модули, которые вызываются из веба. В идеале, здесь должны быть только расширяющие компонениы, контроллеры, модели форм и представления.

## Для запуска тестов

Для того, чтобы запустить codeception тесты, необходимо скопировать конфигурации для тестов и настроить их для своей плащадки.

Автоматически, это поможет сделать `phing`. Запускаете из корня проекта команду `phing build/codecept`, и конфиги автоматически скопируются.

Для ручного копирования необходимо в директориях `erp-app/tests` и `hub-app/tests` скопировать файлы `acceptance.suite.yml.dist` в `acceptance.suite.yml`,
`functional.suite.yml.dist` в `functional.suite.yml` и `unit.suite.yml.dist` в `unit.suite.yml`.

После того, как файлы были скопированы, необходимо их настроить. В `acceptance.suite.yml` необходимо изменить параметры `PhpBrowser/url` и `REST/url` под настройки Вашей площадки.

Остальные файлы могут быть оставлены без изменений.

После создания конфигов, нужно "собрать" "актёров" для тестирования. Для этого из корня проекта выполните команды
```bash
./codecept build -c web-app/tests/codeception.yml
```
Теперь можно приступать непосредственно к запуску тестов.

Для этого из корня провека выполните команду
```bash
# запустить выполнение всех тестов во всех приложениях
./codecept run

# запустить выполнение только тестов для erp приложения
./codecept run -c web-app/tests/codeception.yml

# запустить выполнение только unit тестов для hub приложения
./codecept run -c web-app/tests/codeception.yml unit

# запустить выполнение определённого unit теста для hub приложения
./codecept run -c web-app/tests/codeception.yml unit commands/UserCommandTest.php
```

Для генерации карты покрытия кода к вызову комманды добавьте параметр --coverage-html.
Для отображения более подробной иформации по ходу выполнения теста к вызову комманды добавьте параметр --debug.
```bash
./codecept run --coverage-html
./codecept run -c web-app/tests/codeception.yml --coverage-html --debug
```


text:
import scala.collection.mutable.Map
import scala.collection.Set

import org.apache.spark._
import org.apache.spark.graphx._
// To make some of the examples work we will also need RDD
import org.apache.spark.rdd.RDD

object Question5 {
  def parseContent(content: String): Set[String] = {
    var m = scala.collection.mutable.Map[String, Int]()
    for (line <- content.split('\n')) {
      val two = line.split('\t')
      if (two.length > 1) {
	m(two(1)) = two(0).toInt
      } else {
	println("problematic:" + line + two)
      }
    }
    m.keySet
  }

  def parseFile(nameContent: (String, String)): (VertexId, Set[String]) = {
    //val id = java.util.UUID.randomUUID().getMostSignificantBits()
    val id = nameContent._1.split('/').last.toInt
    println(s"read file $id : " + nameContent._1)
    (id, parseContent(nameContent._2))
  }

  def hasCommon(vertexPair: ((VertexId, Set[String]), (VertexId, Set[String]))): Boolean = {
    if (vertexPair._1._1 != vertexPair._2._1) {
      val common = vertexPair._1._2.intersect(vertexPair._2._2)
      if (common.isEmpty) {
	false
      } else {
	true
      }
    } else {
      false
    }
  }

  def generateEdgeFromVertexPair(vertexPair: ((VertexId, Set[String]), (VertexId, Set[String]))): Edge[Set[String]] = {
    val common = vertexPair._1._2.intersect(vertexPair._2._2)
    val e = new Edge[Set[String]](vertexPair._1._1, vertexPair._2._1, common)
    e
  }

  def createGraph(conf: SparkConf, folderPath: String): Graph[Set[String], Set[String]] = {
    val sc = new SparkContext(conf)

    val nameContents = sc.wholeTextFiles(folderPath)
    val myVertex: RDD[(VertexId, Set[String])] = nameContents.map[(VertexId, Set[String])](parseFile)
    val myEdges: RDD[Edge[Set[String]]] = myVertex.cartesian(myVertex).filter(hasCommon).map(generateEdgeFromVertexPair)

    val graph: Graph[Set[String], Set[String]] = Graph[Set[String], Set[String]](myVertex, myEdges)
    graph
  }

  def getVertexIDs(graph: Graph[Set[String], Set[String]]): Array[VertexId] = {
      val vertexIDs = graph.vertices.map[VertexId](x => x._1).collect()
    vertexIDs
  }

  def searchLargestSubgraph(graph: Graph[Set[String], Set[String]]): Graph[Set[String], Set[String]] = {
    if (graph == null || graph.numVertices == 0) {
      return null
    }
    val indegree = graph.inDegrees
    if (indegree == null || indegree.isEmpty()) {
      return null
    }
    println(graph.numVertices + "\tChecking:\t" + graph.toString() + "indegree:" + indegree.count())
    val num = graph.numVertices.toInt
    // if exists one vertice's degree is less than all vertice
    if (indegree.filter(x => x._2 < num - 1).count() > 0) {
      val vertexIDs = getVertexIDs(graph)
      var validGraphs: Array[Graph[Set[String], Set[String]]] = new Array(num)
      for ( id <- vertexIDs ) {
	val smallerGraph = graph.subgraph(vpred = (vid, attr) => vid != id)
	val tmpGraph = searchLargestSubgraph(smallerGraph)
	if (tmpGraph != null && tmpGraph.vertices.count() > 0) {
	  validGraphs +:= tmpGraph
	}
      }
      if (validGraphs != null && validGraphs.length > 0) {
	validGraphs.filter(x => x != null).maxBy[Long](x => x.vertices.count())
      } else {
	null
      }
    } else {
      println("found complete subgraph! $graph")
      graph
    }
  }

  def main(args: Array[String]) {
    if (args.length < 1) {
      println("please input tweets folder" + args.mkString(" "))
      println(args(0))
    } else {
      val sparkConf = new SparkConf().setAppName("Q5LargestSubgraph")
      val graph = createGraph(sparkConf, args(0))
      graph.cache()

      val subGraph = searchLargestSubgraph(graph)

      println("LargestSubgraph size: " + subGraph.vertices.count())
      subGraph.vertices.foreach(x => println("subgraph has vertex:" + x._1))
    }
  }
}


text:
// Copyright 1998-2015 Epic Games, Inc. All Rights Reserved.

#pragma once

struct FEngineServiceAuthDeny;
struct FEngineServiceAuthGrant;
struct FEngineServiceExecuteCommand;
struct FEngineServicePing;
struct FEngineServiceTerminate;
struct FMessageAddress;
class FMessageEndpoint;
class IMessageContext;

/**
 * Implements an application session service.
 */
class FEngineService
{
public:

	/** Default constructor. */
	ENGINE_API FEngineService();

protected:

	/**
	 * Sends a notification to the specified recipient.
	 *
	 * @param NotificationText The notification text.
	 * @param Recipient The recipient's message address.
	 */
	void SendNotification( const TCHAR* NotificationText, const FMessageAddress& Recipient );

	/**
	 * Publishes a ping response.
	 *
	 * @param Context The message context of the received Ping message.
	 */
	void SendPong( const TSharedRef<IMessageContext, ESPMode::ThreadSafe>& Context );

private:

	/** Handles FEngineServiceAuthGrant messages. */
	void HandleAuthGrantMessage( const FEngineServiceAuthGrant& Message, const TSharedRef<IMessageContext, ESPMode::ThreadSafe>& Context );

	/** Handles FEngineServiceAuthGrant messages. */
	void HandleAuthDenyMessage( const FEngineServiceAuthDeny& Message, const TSharedRef<IMessageContext, ESPMode::ThreadSafe>& Context );

	/** Handles FEngineServiceExecuteCommand messages. */
	void HandleExecuteCommandMessage( const FEngineServiceExecuteCommand& Message, const TSharedRef<IMessageContext, ESPMode::ThreadSafe>& Context );

	/** Handles FEngineServicePing messages. */
	void HandlePingMessage( const FEngineServicePing& Message, const TSharedRef<IMessageContext, ESPMode::ThreadSafe>& Context );

	/** Handles FEngineServiceTerminate messages. */
	void HandleTerminateMessage( const FEngineServiceTerminate& Message, const TSharedRef<IMessageContext, ESPMode::ThreadSafe>& Context );

private:

	/** Holds the list of users that are allowed to interact with this session. */
	TArray<FString> AuthorizedUsers;

	/** Holds the message endpoint. */
	TSharedPtr<FMessageEndpoint, ESPMode::ThreadSafe> MessageEndpoint;
};


text:
using WorkshopXMLAndJSON.Contracts;

namespace WorkshopXMLAndJSON.Models
{
    public class Manufacturer : IManufacturer
    {
        public string Name { get; set; }
    }
}


text:
class Curry::AuthorizedCommitAuthorComment
  #
  # Creates a new +Curry::AuthorizedCommitAuthorComment+
  #
  # @param octokit [Octokit::Client]
  # @param pull_request [Curry::PullRequest]
  # @param unauthorized_commit_authors [Array<Curry::CommitAuthor>]
  #
  def initialize(octokit, pull_request, unauthorized_commit_authors)
    @octokit = octokit
    @pull_request = pull_request
    @unauthorized_commit_authors = unauthorized_commit_authors
  end

  #
  # Adds a comment to the given +pull_request+ and adds a record of the comment
  # internally
  #
  def call
    @octokit.add_comment(
      @pull_request.repository.full_name,
      @pull_request.number,
      comment_body
    ).tap do |comment|
      @pull_request.comments.create!(github_id: comment.id)
    end
  end

  private

  #
  # The comment text
  #
  # @return [String]
  #
  def comment_body
    %(
      Hi. Your friendly Curry bot here. Just letting you know that all commit
      authors have become authorized to contribute. I have added the
      "#{ENV['CURRY_SUCCESS_LABEL']}" label to this issue so it can easily be
      found in the future.
    ).squish
  end
end


text:
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**balance** | **Integer** | Wallet's balance in ISK hundredths. | [optional]
**wallet_id** | **Integer** | wallet_id integer | [optional]


text:
module Google
  module Cloud
    module NetworkManagement
      module V1
        # A Connectivity Test for a network reachability analysis.
        # @!attribute [rw] name
        #   @return [::String]
        #     Required. Unique name of the resource using the form:
        #         `projects/{project_id}/locations/global/connectivityTests/{test_id}`
        # @!attribute [rw] description
        #   @return [::String]
        #     The user-supplied description of the Connectivity Test.
        #     Maximum of 512 characters.
        # @!attribute [rw] source
        #   @return [::Google::Cloud::NetworkManagement::V1::Endpoint]
        #     Required. Source specification of the Connectivity Test.
        #
        #     You can use a combination of source IP address, virtual machine
        #     (VM) instance, or Compute Engine network to uniquely identify
        #     the source location.
        #
        #     Examples:
        #     If the source IP address is an internal IP address within a Google Cloud
        #     Virtual Private Cloud (VPC) network, then you must also specify the VPC
        #     network. Otherwise, specify the VM instance, which already contains its
        #     internal IP address and VPC network information.
        #
        #     If the source of the test is within an on-premises network, then you must
        #     provide the destination VPC network.
        #
        #     If the source endpoint is a Compute Engine VM instance with multiple
        #     network interfaces, the instance itself is not sufficient to identify the
        #     endpoint. So, you must also specify the source IP address or VPC network.
        #
        #     A reachability analysis proceeds even if the source location is
        #     ambiguous. However, the test result may include endpoints that you don't
        #     intend to test.
        # @!attribute [rw] destination
        #   @return [::Google::Cloud::NetworkManagement::V1::Endpoint]
        #     Required. Destination specification of the Connectivity Test.
        #
        #     You can use a combination of destination IP address, Compute Engine
        #     VM instance, or VPC network to uniquely identify the destination
        #     location.
        #
        #     Even if the destination IP address is not unique, the source IP
        #     location is unique. Usually, the analysis can infer the destination
        #     endpoint from route information.
        #
        #     If the destination you specify is a VM instance and the instance has
        #     multiple network interfaces, then you must also specify either
        #     a destination IP address  or VPC network to identify the destination
        #     interface.
        #
        #     A reachability analysis proceeds even if the destination location is
        #     ambiguous. However, the result can include endpoints that you don't
        #     intend to test.
        # @!attribute [rw] protocol
        #   @return [::String]
        #     IP Protocol of the test. When not provided, "TCP" is assumed.
        # @!attribute [rw] related_projects
        #   @return [::Array<::String>]
        #     Other projects that may be relevant for reachability analysis.
        #     This is applicable to scenarios where a test can cross project boundaries.
        # @!attribute [r] display_name
        #   @return [::String]
        #     Output only. The display name of a Connectivity Test.
        # @!attribute [rw] labels
        #   @return [::Google::Protobuf::Map{::String => ::String}]
        #     Resource labels to represent user-provided metadata.
        # @!attribute [r] create_time
        #   @return [::Google::Protobuf::Timestamp]
        #     Output only. The time the test was created.
        # @!attribute [r] update_time
        #   @return [::Google::Protobuf::Timestamp]
        #     Output only. The time the test's configuration was updated.
        # @!attribute [r] reachability_details
        #   @return [::Google::Cloud::NetworkManagement::V1::ReachabilityDetails]
        #     Output only. The reachability details of this test from the latest run.
        #     The details are updated when creating a new test, updating an
        #     existing test, or triggering a one-time rerun of an existing test.
        class ConnectivityTest
          include ::Google::Protobuf::MessageExts
          extend ::Google::Protobuf::MessageExts::ClassMethods

          # @!attribute [rw] key
          #   @return [::String]
          # @!attribute [rw] value
          #   @return [::String]
          class LabelsEntry
            include ::Google::Protobuf::MessageExts
            extend ::Google::Protobuf::MessageExts::ClassMethods
          end
        end

        # Source or destination of the Connectivity Test.
        # @!attribute [rw] ip_address
        #   @return [::String]
        #     The IP address of the endpoint, which can be an external or internal IP.
        #     An IPv6 address is only allowed when the test's destination is a
        #     [global load balancer VIP](/load-balancing/docs/load-balancing-overview).
        # @!attribute [rw] port
        #   @return [::Integer]
        #     The IP protocol port of the endpoint.
        #     Only applicable when protocol is TCP or UDP.
        # @!attribute [rw] instance
        #   @return [::String]
        #     A Compute Engine instance URI.
        # @!attribute [rw] gke_master_cluster
        #   @return [::String]
        #     A cluster URI for [Google Kubernetes Engine
        #     master](https://cloud.google.com/kubernetes-engine/docs/concepts/cluster-architecture).
        # @!attribute [rw] cloud_sql_instance
        #   @return [::String]
        #     A [Cloud SQL](https://cloud.google.com/sql) instance URI.
        # @!attribute [rw] network
        #   @return [::String]
        #     A Compute Engine network URI.
        # @!attribute [rw] network_type
        #   @return [::Google::Cloud::NetworkManagement::V1::Endpoint::NetworkType]
        #     Type of the network where the endpoint is located.
        #     Applicable only to source endpoint, as destination network type can be
        #     inferred from the source.
        # @!attribute [rw] project_id
        #   @return [::String]
        #     Project ID where the endpoint is located.
        #     The Project ID can be derived from the URI if you provide a VM instance or
        #     network URI.
        #     The following are two cases where you must provide the project ID:
        #     1. Only the IP address is specified, and the IP address is within a GCP
        #     project.
        #     2. When you are using Shared VPC and the IP address that you provide is
        #     from the service project. In this case, the network that the IP address
        #     resides in is defined in the host project.
        class Endpoint
          include ::Google::Protobuf::MessageExts
          extend ::Google::Protobuf::MessageExts::ClassMethods

          # The type definition of an endpoint's network. Use one of the
          # following choices:
          module NetworkType
            # Default type if unspecified.
            NETWORK_TYPE_UNSPECIFIED = 0

            # A network hosted within Google Cloud Platform.
            # To receive more detailed output, specify the URI for the source or
            # destination network.
            GCP_NETWORK = 1

            # A network hosted outside of Google Cloud Platform.
            # This can be an on-premises network, or a network hosted by another cloud
            # provider.
            NON_GCP_NETWORK = 2
          end
        end

        # Results of the configuration analysis from the last run of the test.
        # @!attribute [rw] result
        #   @return [::Google::Cloud::NetworkManagement::V1::ReachabilityDetails::Result]
        #     The overall result of the test's configuration analysis.
        # @!attribute [rw] verify_time
        #   @return [::Google::Protobuf::Timestamp]
        #     The time of the configuration analysis.
        # @!attribute [rw] error
        #   @return [::Google::Rpc::Status]
        #     The details of a failure or a cancellation of reachability analysis.
        # @!attribute [rw] traces
        #   @return [::Array<::Google::Cloud::NetworkManagement::V1::Trace>]
        #     Result may contain a list of traces if a test has multiple possible
        #     paths in the network, such as when destination endpoint is a load balancer
        #     with multiple backends.
        class ReachabilityDetails
          include ::Google::Protobuf::MessageExts
          extend ::Google::Protobuf::MessageExts::ClassMethods

          # The overall result of the test's configuration analysis.
          module Result
            # No result was specified.
            RESULT_UNSPECIFIED = 0

            # Possible scenarios are:
            #
            # * The configuration analysis determined that a packet originating from
            #   the source is expected to reach the destination.
            # * The analysis didn't complete because the user lacks permission for
            #   some of the resources in the trace. However, at the time the user's
            #   permission became insufficient, the trace had been successful so far.
            REACHABLE = 1

            # A packet originating from the source is expected to be dropped before
            # reaching the destination.
            UNREACHABLE = 2

            # The source and destination endpoints do not uniquely identify
            # the test location in the network, and the reachability result contains
            # multiple traces. For some traces, a packet could be delivered, and for
            # others, it would not be.
            AMBIGUOUS = 4

            # The configuration analysis did not complete. Possible reasons are:
            #
            # * A permissions error occurred--for example, the user might not have
            #   read permission for all of the resources named in the test.
            # * An internal error occurred.
            # * The analyzer received an invalid or unsupported argument or was unable
            #   to identify a known endpoint.
            UNDETERMINED = 5
          end
        end
      end
    end
  end
end


text:
<?php
/*
Plugin Name: WP-reCAPTCHA-bp
Description: Integrates reCAPTCHA anti-spam solutions with wordpress sites using BuddyPress
Version: 4.1
Email: rodrigo@phplist.com
*/

// this is the 'driver' file that instantiates the objects and registers every hook

define('ALLOW_INCLUDE', true);

require_once('recaptcha.php');

$recaptcha = new ReCAPTCHAPlugin('recaptcha_options');

?>


text:
<?php

/**
 * @namespace
 */
namespace Zend\View\Helper;

use Zend\Mvc\Router\RouteStack,
    Zend\Mvc\Router\RouteMatch,
    Zend\View\Exception;

/**
 * Helper for making easy links and getting urls that depend on the routes and router.
 *
 * @uses       \Zend\View\Helper\AbstractHelper
 * @package    Zend_View
 * @subpackage Helper
 * @copyright  Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Url extends AbstractHelper
{
    /**
     * RouteStack instance.
     *
     * @var RouteStack
     */
    protected $router;

    /**
     * Route match returned by the router.
     *
     * @var RouteMatch.
     */
    protected $routeMatch;

    /**
     * Set the router to use for assembling.
     *
     * @param RouteStack $router
     * @return Url
     */
    public function setRouter(RouteStack $router)
    {
        $this->router = $router;
        return $this;
    }

    /**
     * Set route match returned by the router.
     *
     * @param  RouteMatch $routeMatch
     * @return self
     */
    public function setRouteMatch(RouteMatch $routeMatch)
    {
        $this->routeMatch = $routeMatch;
        return $this;
    }

    /**
     * Generates an url given the name of a route.
     *
     * @see    Zend\Mvc\Router\Route::assemble()
     * @param  string  $name               Name of the route
     * @param  array   $params             Parameters for the link
     * @param  array   $options            Options for the route
     * @param  boolean $reuseMatchedParams Whether to reuse matched parameters
     * @return string Url                  For the link href attribute
     * @throws Exception\RuntimeException  If no RouteStack was provided
     * @throws Exception\RuntimeException  If no RouteMatch was provided
     * @throws Exception\RuntimeException  If RouteMatch didn't contain a matched route name
     */
    public function __invoke($name = null, array $params = array(), array $options = array(), $reuseMatchedParams = false)
    {
        if (null === $this->router) {
            throw new Exception\RuntimeException('No RouteStack instance provided');
        }

        if ($name === null) {
            if ($this->routeMatch === null) {
                throw new Exception\RuntimeException('No RouteMatch instance provided');
            }

            $name = $this->routeMatch->getMatchedRouteName();

            if ($name === null) {
                throw new Exception\RuntimeException('RouteMatch does not contain a matched route name');
            }
        }

        if ($reuseMatchedParams && $this->routeMatch !== null) {
            $params = array_merge($this->routeMatch->getParams(), $params);
        }

        $options['name'] = $name;

        return $this->router->assemble($params, $options);
    }
}


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

    <meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />
    <link rel="stylesheet" type="text/css" href="./swish.css" media="screen" title="swish css" />
    <link rel="shortcut icon" href="/favicon.ico" type="image/x-icon" />

        <link rel="Last" href="./filter.html" />

        <link rel="Prev" href="./swish.cgi.html" />

        <link rel="Up" href="./index.html" />

        <link rel="Next" href="./spider.html" />

        <link rel="Start" href="./index.html" />

        <link rel="First" href="./readme.html" />

    <title>Swish-e :: search.cgi -- Example Perl program for searching with Swish-e and SWISH::API</title>

Skip to main content.

        Related Sites:
            swish-e wiki |
            libxml2 |
            zlib |
            xpdf |
            Subversion

Swish-e

Simple Web Indexing System for Humans - Enhanced

          Tools:

              download latest version

                home |
                support |
                download

                <form method="get"
                    action="http://swish-e.org/search/index.html"
                    enctype="application/x-www-form-urlencoded"
                    class="srchform">

                    Search for
                    <input maxlength="200" value="" id="searchfield" size="30" name="query" type="text" alt="Search input field" />
                    <input value="search swish-e.org" name="submit" type="submit" class='button' />
                </form>

search.cgi -- Example Perl program for searching with Swish-e and SWISH::API

Swish-e version 2.4.7

Table of Contents

                DESCRIPTION

                REQUIREMENTS

                OVERVIEW

                INSTALLATION EXAMPLE

                Using with SpeedyCGI

                Using with MOD_PERL

                SUPPORT

                AUTHOR

                LICENSE

                SEE ALSO

DESCRIPTION

This is a very simple program that shows how to use the SWISH::API module
in a CGI script or mod_perl handler using Template-Toolkit to generate
output.  This program is intended for programmers that want to create a custom
search script.

Unlike swish.cgi this script does not have many features, and provides no
external configuration (with the execption of a few config options under
mod_perl).  So don't ask why it doesn't do something.  The point is that this
script is used as a starting point that YOU customize.

REQUIREMENTS

You must have swish-e and the SWISH::API module installed.  See the README
and INSTALL documents in the swish-e distribution.  As of this writing SWISH::API
is part of the swish-e distribution, but in the future may be provided as a separate
package (provided on the CPAN).  In either case SWISH::API is a separate installation
procedure from installing swish-e.  The Storable module is also required if using mod_perl.

This program does require that some modules are installed from CPAN.
You will need Template-Toolkit and HTML::FillInForm (which depends on HTML::Parser).
How those are installed depends on your computer's packaging system.

You will need a web server, obviously.  The discussion below assumes Apache is used.
If you are using MS IIS take note that IIS works differently in a number of ways.

OVERVIEW

The search.cgi script and related templates are installed when swish-e is installed.
search.cgi is installed in $prefix/lib/swish-e/ and templates are installed
in $prefix/share/swish-e/templates/.  $prefix is /usr/local by default
but can be changed when running the swish-e configure script.  Upon
installation search.cgi is updated with correct paths to your perl binary and

When running as a CGI script search.cgi is copied or symlinked to the location
of your CGI scripts (or any directory that allows CGI scripts).  By default,
the search.cgi script looks for the index index.swish-e in the current
directory (that's what the web server considers the current directory).  On Apache
running mod-cgi that's the same place as the script.  On IIS it's not.  If your
index is elsewhere you will need to modify the script.

The script works by parsing the query, calling SWISH::API to run the actual search, then
calls Template-Toolkit to generate the ouput.

The script calls the search.tt template.  This template generates the query
form and the search results.  The search.tt template uses a
Template-Toolkit "WRAPPER" function to wrap the search form and results in your
site's design.   This design is in the page_layout template.   The idea is
if you use Template-Toolkit to manage your entire site then your entire site
would be formatted by the same page_layout template.  The page_layout template
calls two other templates common_header and common_footer to generate a common
header and footer for the site.  Those are just demonstrating Template-Toolkit's
features.

The page_layout page only defines the basic structure of the site.  The true
design of the site is managed by style sheets.  style.css defines the basic
layout and markup.css sets fonts and colors.

Note: these style sheets are included directly in the output of the CGI script.
In production the style sheets would be stored as separate style
sheet files and imported by the browser instead of directly included in the
search results page.

See the section MOD_PERL below for more on templates.

Highlighting of search terms is provided by the SWISH::PhraseHighlight module.
That is a very slow module, so you may wish to disable it if you expect a lot
of traffic.

INSTALLATION EXAMPLE

Enough talking, sometimes it's nice to see a complete example.  Below swish-e
is installed in the default location (/usr/local).  The "$" is a normal user
prompt, where "#" is a root prompt.  Use ./configure --prefix to install in another
location (e.g. if you do not have root access).

Download and install swish-e

    $ wget -q http://swish-e.org/Download/latest.tar.gz
    $ tar zxf latest.tar.gz
    $ cd swish-e-2.x.x
    $ (./configure && make) >/dev/null
    $ make check
    $ su
    # make install
    # exit

Install SWISH::API

    $ cd perl
    $ perl Makefile.PL && make && make test
    $ su
    # make install
    $ exit

Install requried Perl modules.  You can install via RPMs, Debs or directly from the CPAN
or by using the CPAN shell.

    # su
    # perl -MCPAN -e 'install Template'
    # perl -MCPAN -e 'install HTML::FillInForm'
    # exit

Now setup the script in someplace that allows CGI scripts.

    $ cd $HOME/apache
    $ ln -s /usr/local/lib/swish-e/search.cgi .
    $ cat .htaccess
    deny from all
    <files search.cgi>
        allow from all
        SetHandler cgi-script
        Options +ExecCGI
    </files>

Create an index

    $ cat swish.config
    IndexOnly .htm .html
    DefaultContents HTML*
    StoreDescription HTML* <body>
    metanames swishtitle swishdocpath

    $ swish-e -c swish.config -i /usr/share/doc/apache-doc/manual

Test the index and the CGI script:

    $ swish-e -w apache -m1 | grep hits
    # Number of hits: 152

    $ lynx -dump http://localhost/apache/search.cgi?query=apache | grep hits
        Showing page 1 (1 - 10 of 152 hits) [3]Next
              'hits' => 152,

Now, the above isn't very helpful because the Apache documentation indexed is not
in the web space.  You would likely index content available on your web site.

Using with SpeedyCGI

Perl CGI script must be compiled for each request.  SpeedyCGI is a tool to speed up
scripts by running them persistently.  To run search.cgi with SpeedyCGI install
the program (you can Google, right?) and then change the first line of search.cgi
to run the speedy program.

For example:

    #!/usr/bin/speedy -w

Using with MOD_PERL

This script can be run directly as a mod_perl handler, and the same code can be used
to run multiple sites by using separate Location directives and passing in a "site id."
The script caches in memory different configurations based on this site id.

Below is a complete httpd.conf file.  It requires an Apache httpd that has
mod_perl compiled in statically.  It runs mod_perl on a high port (port 5000)
listening to all interfaces.

For testing I put this config file in a directory along with search.cgi, but
that's just done to make the example simple (i.e. so I don't have to show any
absolute paths).  Normally the httpd.conf and the swish.cgi "module" would be
in separate locations.

    # httpd.conf -- test file for search.cgi as mod_perl handler

    <ifModule mod_so.c>
        LoadModule mime_module /usr/lib/apache/1.3/mod_mime.so
    </IfModule>

    ErrorLog swish_error_log
    PidFile swish_httpd.pid

    Listen *:5000

    <perl>
        push @PerlSetVar, [
            index  => Apache->server_root_relative( 'index.swish-e'),
        ];
        $DocumentRoot =  Apache->server_root_relative;
        require "search.cgi";
    </perl>

    NameVirtualHost *:5000
    <VirtualHost *:5000>

        ServerName localhost

        <Location /search>
            SetHandler  perl-script
            PerlHandler SwishAPISearch
        </Location>

        <Location /othersite>
            SetHandler perl-script
            PerlHandler SwishAPISearch
            # Define this site
            PerlSetVar  site_id othersite
            PerlSetVar  title "Some other Site"
        </Location>

    </VirtualHost>

The server is started using this command:

    $ /usr/sbin/apache-perl -d $(pwd) -f $(pwd)/httpd.conf

which says to use the current directory as the ServerRoot.
(See comments below.)  Stop the server like:

    $ kill `cat swish_httpd.pid`

Then access either:

    http://localhost:5000/search
    http://localhost:5000/othersite

A few Notes:

I like test configurations to not care where things are located.  Thus, the
above httpd.conf does a few tricks in the "Perl Section" shown.

First, mod_perl, unlike CGI, doesn't set the working directory.  So, the index file
name must be absolute.  This is accomplished by a PerlSetVar entry building
the index file name from the ServerRoot.

Second, the DocumentRoot is set to the same as the ServerRoot.  The DocumentRoot
needs to be set so search.cgi can figure out the path to the script (for
creating next and previous links).

Third, the script is loaded by a require statement.  This works only because
the current directory "." is in Perl's @INC path at Apache start up time and
search.cgi is also in the current directory.  Normally, set PERL5LIB
on server startup or use a "use lib" line in your startup.pl file to point to
the location of search.cgi.

The "PerlSetVar" lines pass config information into the script.  Note that they can
be set globally or specific to a given Location.

The following config options are currently available:

site_id

The site_id options allow caching of configurations on a per-site basis.
It's overkill in this example, but normally you might have expensive configuration
processes that you might want to do only once.  But, since there is caching by this id
it's a good id to set a site_id if using more than one Location directive.

index

This specifies the index file to use.  The index file needs to be absolute
as discussed above.  Example:

    PerlSetVar index /usr/share/swish/site.index

title

This options sets the title that's passed into the template.

template

Sets the file name of the template use to generate the form.  This might be useful
if you want an "advanced" form, for example.

template_path

This can be used to update the path where templates are searched.  Useful if you wish
to override templates.

page_size

This allow changing the default number of results shown per page.

SUPPORT

Not much support is provided.  But what support is provided is ONLY provided via
the Swish-e discussion list.

    http://swish-e.org/

AUTHOR

Bill Moseley

LICENSE

Copyright 2003, 2004 Bill Moseley.  All rights reserved.

This program is free software; you can redistribute it and/or modify it
under the same terms as Perl itself.

SEE ALSO

SWISH::API,  Template, HTML::FillInForm

    Doc Overview

    README

    Install

    Changes

    Configuration

    Running

    Searching

    FAQ

    Known issues

    The Future

    C API

    Perl API

    Swish.cgi

    Search.cgi »

    Spider.pl

    Filters

    Swish-e is distributed with no warranty under the terms of the

    Swish-e License.

    Questions may be posted to the
    Swish-e Discussion list.

    URI » http://swish-e.org/
    •

    Updated »Sun, 05 Apr 2009 01:58:33 UTC


text:
#include <aws/external/gtest.h>

#include <aws/core/utils/Document.h>
#include <aws/core/utils/memory/stl/AWSStringStream.h>

using namespace Aws::Utils;

TEST(DocumentTest, TestParseString)
{
    const Aws::String docString = R"("testString")";
    Document doc(docString);
    if (doc.WasParseSuccessful())
    {
        ASSERT_TRUE(doc.GetErrorMessage().empty());
        auto view = doc.View();
        ASSERT_TRUE(view.IsString());
        ASSERT_STREQ("testString", view.AsString().c_str());
    }
    else
    {
        GTEST_NONFATAL_FAILURE_(doc.GetErrorMessage().c_str());
    }
}

TEST(DocumentTest, TestParseStringValue)
{
    const Aws::String docString = R"({"testStringKey":"testStringValue"})";
    Document doc(docString);
    if (doc.WasParseSuccessful())
    {
        ASSERT_TRUE(doc.GetErrorMessage().empty());
        auto view = doc.View();
        ASSERT_TRUE(view.IsObject());
        ASSERT_STREQ("testStringValue", view.GetString("testStringKey").c_str());
    }
    else
    {
        GTEST_NONFATAL_FAILURE_(doc.GetErrorMessage().c_str());
    }
}

TEST(DocumentTest, TestParseBool)
{
    const Aws::String docString = R"(false)";
    Document doc(docString);
    if (doc.WasParseSuccessful())
    {
        ASSERT_TRUE(doc.GetErrorMessage().empty());
        auto view = doc.View();
        ASSERT_TRUE(view.IsBool());
        ASSERT_FALSE(view.AsBool());
    }
    else
    {
        GTEST_NONFATAL_FAILURE_(doc.GetErrorMessage().c_str());
    }
}

TEST(DocumentTest, TestParseBoolValue)
{
    const Aws::String docString = R"({"testBoolKey":false})";
    Document doc(docString);
    if (doc.WasParseSuccessful())
    {
        ASSERT_TRUE(doc.GetErrorMessage().empty());
        auto view = doc.View();
        ASSERT_TRUE(view.IsObject());
        ASSERT_FALSE(view.GetBool("testBoolKey"));
    }
    else
    {
        GTEST_NONFATAL_FAILURE_(doc.GetErrorMessage().c_str());
    }
}

TEST(DocumentTest, TestParseInteger)
{
    Aws::String docString = R"(10)";
    Document doc(docString);
    if (doc.WasParseSuccessful())
    {
        ASSERT_TRUE(doc.GetErrorMessage().empty());
        auto view = doc.View();
        ASSERT_TRUE(view.IsIntegerType());
        ASSERT_FALSE(view.IsFloatingPointType());
        ASSERT_EQ(10, view.AsInteger());
    }
    else
    {
        GTEST_NONFATAL_FAILURE_(doc.GetErrorMessage().c_str());
    }

    docString = R"(2.99792458e8)";
    doc = Document(docString);
    if (doc.WasParseSuccessful())
    {
        ASSERT_TRUE(doc.GetErrorMessage().empty());
        auto view = doc.View();
        ASSERT_TRUE(view.IsIntegerType());
        ASSERT_FALSE(view.IsFloatingPointType());
        ASSERT_EQ(299792458, view.AsInteger());
    }
    else
    {
        GTEST_NONFATAL_FAILURE_(doc.GetErrorMessage().c_str());
    }
}

TEST(DocumentTest, TestParseIntegerValue)
{
    const Aws::String docString = R"({"testIntKey":10})";
    Document doc(docString);
    if (doc.WasParseSuccessful())
    {
        ASSERT_TRUE(doc.GetErrorMessage().empty());
        auto view = doc.View();
        ASSERT_TRUE(view.IsObject());
        ASSERT_EQ(10, view.GetInteger("testIntKey"));
    }
    else
    {
        GTEST_NONFATAL_FAILURE_(doc.GetErrorMessage().c_str());
    }
}

TEST(DocumentTest, TestParseInt64)
{
    const Aws::String docString = R"(8765432109876543210)";
    Document doc(docString);
    if (doc.WasParseSuccessful())
    {
        ASSERT_TRUE(doc.GetErrorMessage().empty());
        auto view = doc.View();
        ASSERT_TRUE(view.IsIntegerType());
        ASSERT_FALSE(view.IsFloatingPointType());
        ASSERT_EQ(8765432109876543210, view.AsInt64());
    }
    else
    {
        GTEST_NONFATAL_FAILURE_(doc.GetErrorMessage().c_str());
    }
}

TEST(DocumentTest, TestParseInt64Value)
{
    const Aws::String docString = R"({"testInt64Key":8765432109876543210})";
    Document doc(docString);
    if (doc.WasParseSuccessful())
    {
        ASSERT_TRUE(doc.GetErrorMessage().empty());
        auto view = doc.View();
        ASSERT_TRUE(view.IsObject());
        ASSERT_EQ(8765432109876543210, view.GetInt64("testInt64Key"));
    }
    else
    {
        GTEST_NONFATAL_FAILURE_(doc.GetErrorMessage().c_str());
    }
}

TEST(DocumentTest, TestParseDouble)
{
    const Aws::String docString = R"(6.626e-34)";
    Document doc(docString);
    if (doc.WasParseSuccessful())
    {
        ASSERT_TRUE(doc.GetErrorMessage().empty());
        auto view = doc.View();
        ASSERT_TRUE(view.IsFloatingPointType());
        ASSERT_FALSE(view.IsIntegerType());
        ASSERT_EQ(6.626e-34, view.AsDouble());
    }
    else
    {
        GTEST_NONFATAL_FAILURE_(doc.GetErrorMessage().c_str());
    }
}

TEST(DocumentTest, TestParseDoubleValue)
{
    const Aws::String docString = R"({"testDoubleKey":-6.626e-34})";
    Document doc(docString);
    if (doc.WasParseSuccessful())
    {
        ASSERT_TRUE(doc.GetErrorMessage().empty());
        auto view = doc.View();
        ASSERT_TRUE(view.IsObject());
        ASSERT_EQ(-6.626e-34, view.GetDouble("testDoubleKey"));
    }
    else
    {
        GTEST_NONFATAL_FAILURE_(doc.GetErrorMessage().c_str());
    }
}

TEST(DocumentTest, TestParseArray)
{
    const Aws::String docString = R"(["stringArrayEntry1", "stringArrayEntry2"])";
    Document doc(docString);
    if (doc.WasParseSuccessful())
    {
        ASSERT_TRUE(doc.GetErrorMessage().empty());
        auto view = doc.View();
        ASSERT_TRUE(view.IsListType());
        ASSERT_STREQ("stringArrayEntry1", view.AsArray()[0].AsString().c_str());
        ASSERT_STREQ("stringArrayEntry2", view.AsArray()[1].AsString().c_str());
    }
    else
    {
        GTEST_NONFATAL_FAILURE_(doc.GetErrorMessage().c_str());
    }
}

TEST(DocumentTest, TestParseArrayValue)
{
    const Aws::String docString = R"({"array": ["stringArrayEntry1", "stringArrayEntry2"]})";
    Document doc(docString);
    if (doc.WasParseSuccessful())
    {
        ASSERT_TRUE(doc.GetErrorMessage().empty());
        auto view = doc.View();
        ASSERT_TRUE(view.IsObject());
        ASSERT_STREQ("stringArrayEntry1", view.GetArray("array")[0].AsString().c_str());
        ASSERT_STREQ("stringArrayEntry2", view.GetArray("array")[1].AsString().c_str());
    }
    else
    {
        GTEST_NONFATAL_FAILURE_(doc.GetErrorMessage().c_str());
    }
}

TEST(DocumentTest, TestParseObjectValue)
{
    const Aws::String docString = R"({"object": {"testObjectStringKey":"testObjectStringValue"}})";
    Document doc(docString);
    if (doc.WasParseSuccessful())
    {
        ASSERT_TRUE(doc.GetErrorMessage().empty());
        auto view = doc.View();
        ASSERT_TRUE(view.IsObject());
        ASSERT_TRUE(view.GetObject("object").IsObject());
        ASSERT_STREQ("testObjectStringValue", view.GetObject("object").GetString("testObjectStringKey").c_str());
        ASSERT_STREQ("testObjectStringValue", view.GetObject("object").AsObject().GetString("testObjectStringKey").c_str());
    }
    else
    {
        GTEST_NONFATAL_FAILURE_(doc.GetErrorMessage().c_str());
    }
}

const std::string docString = R"({
    "testStringKey":"testStringValue",
    "testBoolKey":false,
    "testIntKey":10,
    "testInt64Key":8765432109876543210,
    "testDoubleKey":6.626e-34,
    "array": ["stringArrayEntry1", "stringArrayEntry2"],
    "object": {"testObjectStringKey":"testObjectStringValue"}
})";

TEST(DocumentTest, TestParseJsonString)
{
    Document doc(Aws::String(docString.c_str()));
    if (doc.WasParseSuccessful())
    {
        auto view = doc.View();
        ASSERT_TRUE(doc.GetErrorMessage().empty());
        ASSERT_STREQ("testStringValue", view.GetString("testStringKey").c_str());
        ASSERT_FALSE(view.GetBool("testBoolKey"));
        ASSERT_EQ(10, view.GetInteger("testIntKey"));
        ASSERT_EQ(8765432109876543210, view.GetInt64("testInt64Key"));
        ASSERT_EQ(6.626e-34, view.GetDouble("testDoubleKey"));
        ASSERT_STREQ("stringArrayEntry1", view.GetArray("array")[0].AsString().c_str());
        ASSERT_STREQ("stringArrayEntry2", view.GetArray("array")[1].AsString().c_str());
        ASSERT_TRUE(view.GetObject("object").AsString().empty());
        ASSERT_STREQ("testObjectStringValue", view.GetObject("object").GetString("testObjectStringKey").c_str());
    }
    else
    {
        GTEST_NONFATAL_FAILURE_(doc.GetErrorMessage().c_str());
    }
}

TEST(DocumentTest, TestParseJsonStream)
{
    Aws::StringStream inputAsStream(Aws::String(docString.c_str()));
    Document doc(inputAsStream);

    if (doc.WasParseSuccessful())
    {
        auto view = doc.View();
        ASSERT_TRUE(doc.GetErrorMessage().empty());
        ASSERT_STREQ("testStringValue", view.GetString("testStringKey").c_str());
        ASSERT_FALSE(view.GetBool("testBoolKey"));
        ASSERT_EQ(10, view.GetInteger("testIntKey"));
        ASSERT_EQ(8765432109876543210, view.GetInt64("testInt64Key"));
        ASSERT_EQ(6.626e-34, view.GetDouble("testDoubleKey"));
        ASSERT_STREQ("stringArrayEntry1", view.GetArray("array")[0].AsString().c_str());
        ASSERT_STREQ("stringArrayEntry2", view.GetArray("array")[1].AsString().c_str());
        ASSERT_TRUE(view.GetObject("object").AsString().empty());
        ASSERT_STREQ("testObjectStringValue", view.GetObject("object").GetString("testObjectStringKey").c_str());
    }
    else
    {
        GTEST_NONFATAL_FAILURE_(doc.GetErrorMessage().c_str());
    }
}

TEST(DocumentTest, TestParseStringFailed)
{
    Document doc(Aws::String("blah blah blah"));
    ASSERT_FALSE(doc.WasParseSuccessful());
    ASSERT_FALSE(doc.GetErrorMessage().empty());
}

TEST(DocumentTest, TestParseStreamFailed)
{
    Aws::StringStream ss;
    ss << "{\"bla\" : blah blah";
    Document doc(ss);
    ASSERT_FALSE(doc.WasParseSuccessful());
    ASSERT_STREQ("Failed to parse JSON. Invalid input at: blah blah", doc.GetErrorMessage().c_str());
}

TEST(DocumentTest, TestCreateStringValue)
{
    Document doc;
    doc.WithString("testStringKey", "testStringValue");
    ASSERT_TRUE(doc.View().IsObject());
    ASSERT_STREQ("testStringValue", doc.View().GetString("testStringKey").c_str());

    doc.AsString("anotherTestString");
    ASSERT_TRUE(doc.View().IsString());
    ASSERT_STREQ("anotherTestString", doc.View().AsString().c_str());
}

TEST(DocumentTest, TestCreateBoolValue)
{
    Document doc;
    doc.WithBool("testBoolKey", false);
    ASSERT_TRUE(doc.View().IsObject());
    ASSERT_FALSE(doc.View().GetBool("testBoolKey"));

    doc.AsBool(true);
    ASSERT_TRUE(doc.View().IsBool());
    ASSERT_TRUE(doc.View().AsBool());
}

TEST(DocumentTest, TestCreateIntegerValue)
{
    Document doc;
    doc.WithInteger("testIntKey", 10);
    ASSERT_TRUE(doc.View().IsObject());
    ASSERT_EQ(10, doc.View().GetInteger("testIntKey"));

    doc.AsInteger(15);
    ASSERT_TRUE(doc.View().IsIntegerType());
    ASSERT_FALSE(doc.View().IsFloatingPointType());
    ASSERT_EQ(15, doc.View().AsInteger());
}

TEST(DocumentTest, TestCreateInt64Value)
{
    Document doc;
    doc.WithInt64("testInt64Key", INT64_MIN);
    ASSERT_TRUE(doc.View().IsObject());
    ASSERT_EQ(INT64_MIN, doc.View().GetInt64("testInt64Key"));
    doc.WithInt64("testInt64Key", INT64_MIN + 1);
    ASSERT_EQ(INT64_MIN + 1, doc.View().GetInt64("testInt64Key"));
    doc.WithInt64("testInt64Key", INT64_MAX);
    ASSERT_EQ(INT64_MAX, doc.View().GetInt64("testInt64Key"));
    doc.WithInt64("testInt64Key", INT64_MAX - 1);
    ASSERT_EQ(INT64_MAX - 1, doc.View().GetInt64("testInt64Key"));

    doc.AsInt64(INT64_MIN);
    ASSERT_EQ(INT64_MIN, doc.View().AsInt64());
    ASSERT_TRUE(doc.View().IsIntegerType());
    ASSERT_FALSE(doc.View().IsFloatingPointType());
    doc.AsInt64(INT64_MIN + 1);
    ASSERT_EQ(INT64_MIN + 1, doc.View().AsInt64());
    ASSERT_TRUE(doc.View().IsIntegerType());
    ASSERT_FALSE(doc.View().IsFloatingPointType());
    doc.AsInt64(INT64_MAX);
    ASSERT_EQ(INT64_MAX, doc.View().AsInt64());
    ASSERT_TRUE(doc.View().IsIntegerType());
    ASSERT_FALSE(doc.View().IsFloatingPointType());
    doc.AsInt64(INT64_MAX - 1);
    ASSERT_EQ(INT64_MAX - 1, doc.View().AsInt64());
    ASSERT_TRUE(doc.View().IsIntegerType());
    ASSERT_FALSE(doc.View().IsFloatingPointType());
}

TEST(DocumentTest, TestCreateDoubleValue)
{
    Document doc;
    doc.WithDouble("testDoubleKey", 6.626e-34);
    ASSERT_TRUE(doc.View().IsObject());
    ASSERT_EQ(6.626e-34, doc.View().GetDouble("testDoubleKey"));

    doc.AsDouble(2.71828182845);
    ASSERT_TRUE(doc.View().IsFloatingPointType());
    ASSERT_FALSE(doc.View().IsIntegerType());
    ASSERT_EQ(2.71828182845, doc.View().AsDouble());
}

TEST(DocumentTest, TestCreateArrayValue)
{
    Document doc;
    Array<Document> arrayDoc(2);
    Document doc1;
    Document doc2;
    arrayDoc[0] = doc1.AsString("testArrayValue1");
    arrayDoc[1] = doc1.AsString("testArrayValue2");

    doc.WithArray("testArrayKey", arrayDoc);
    ASSERT_TRUE(doc.View().IsObject());
    Array<DocumentView> viewArray = doc.View().GetArray("testArrayKey");
    ASSERT_EQ(2uL, viewArray.GetLength());
    ASSERT_EQ("testArrayValue1", viewArray[0].AsString());
    ASSERT_EQ("testArrayValue2", viewArray[1].AsString());

    arrayDoc[0] = doc1.AsString("testArrayValue3");
    arrayDoc[1] = doc2.AsString("testArrayValue4");

    doc.AsArray(arrayDoc);
    ASSERT_TRUE(doc.View().IsListType());
    viewArray = doc.View().AsArray();
    ASSERT_EQ(2uL, viewArray.GetLength());
    ASSERT_EQ("testArrayValue3", viewArray[0].AsString());
    ASSERT_EQ("testArrayValue4", viewArray[1].AsString());
}

TEST(DocumentTest, TestCreateObjectValue)
{
    Document doc;
    Array<Document> arrayDoc(2);
    Document doc1;
    Document doc2;
    arrayDoc[0] = doc1.AsString("testArrayValue1");
    arrayDoc[1] = doc2.AsString("testArrayValue2");
    doc.WithArray("testArrayKey", arrayDoc);
    doc.WithString("testStringKey", "testStringValue");
    doc.WithBool("testBoolKey", false);
    doc.WithInteger("testIntegerKey", 10);
    doc.WithInt64("testInt64Key", -8765432109876543210);
    doc.WithDouble("testDoubleKey", -6.626e-34);

    Document object;
    object.WithObject("testObjectKey", doc);
    auto objectView = object.View();
    ASSERT_TRUE(objectView.IsObject());
    ASSERT_STREQ("testStringValue", objectView.GetObject("testObjectKey").GetString("testStringKey").c_str());
    ASSERT_FALSE(objectView.GetObject("testObjectKey").GetBool("testBoolKey"));
    ASSERT_EQ(10, objectView.GetObject("testObjectKey").GetInteger("testIntegerKey"));
    ASSERT_EQ(-8765432109876543210, objectView.GetObject("testObjectKey").GetInt64("testInt64Key"));
    ASSERT_EQ(-6.626e-34, objectView.GetObject("testObjectKey").GetDouble("testDoubleKey"));
    ASSERT_EQ(2uL, objectView.GetObject("testObjectKey").GetArray("testArrayKey").GetLength());
    ASSERT_EQ("testArrayValue1", objectView.GetObject("testObjectKey").GetArray("testArrayKey")[0].AsString());
    ASSERT_EQ("testArrayValue2", objectView.GetObject("testObjectKey").GetArray("testArrayKey")[1].AsString());

    object.AsObject(doc);
    objectView = object.View();
    ASSERT_TRUE(objectView.IsObject());
    ASSERT_STREQ("testStringValue", objectView.AsObject().GetString("testStringKey").c_str());
    ASSERT_FALSE(objectView.AsObject().GetBool("testBoolKey"));
    ASSERT_EQ(10, objectView.AsObject().GetInteger("testIntegerKey"));
    ASSERT_EQ(-8765432109876543210, objectView.AsObject().GetInt64("testInt64Key"));
    ASSERT_EQ(-6.626e-34, objectView.AsObject().GetDouble("testDoubleKey"));
    ASSERT_EQ(2uL, objectView.AsObject().GetArray("testArrayKey").GetLength());
    ASSERT_EQ("testArrayValue1", objectView.AsObject().GetArray("testArrayKey")[0].AsString());
    ASSERT_EQ("testArrayValue2", objectView.AsObject().GetArray("testArrayKey")[1].AsString());
}

TEST(DocumentTest, TestDocCompactSerializeObject)
{
    Document doc(Aws::String(docString.c_str()));
    Aws::String outputString = doc.View().WriteCompact();
    Document reparsedDoc(outputString);
    if (reparsedDoc.WasParseSuccessful())
    {
        auto view = doc.View();
        ASSERT_TRUE(doc.GetErrorMessage().empty());
        ASSERT_STREQ("testStringValue", view.GetString("testStringKey").c_str());
        ASSERT_FALSE(view.GetBool("testBoolKey"));
        ASSERT_EQ(10, view.GetInteger("testIntKey"));
        ASSERT_EQ(8765432109876543210, view.GetInt64("testInt64Key"));
        ASSERT_EQ(6.626e-34, view.GetDouble("testDoubleKey"));
        ASSERT_STREQ("stringArrayEntry1", view.GetArray("array")[0].AsString().c_str());
        ASSERT_STREQ("stringArrayEntry2", view.GetArray("array")[1].AsString().c_str());
        ASSERT_STREQ("testObjectStringValue", view.GetObject("object").GetString("testObjectStringKey").c_str());
    }
    else
    {
        GTEST_NONFATAL_FAILURE_(reparsedDoc.GetErrorMessage().c_str());
    }
}

TEST(DocumentTest, TestJsonStyledSerializeObject)
{
    Document doc(Aws::String(docString.c_str()));
    Aws::String outputString = doc.View().WriteReadable();
    Document reparsedDoc(outputString);
    if (reparsedDoc.WasParseSuccessful())
    {
        auto view = doc.View();
        ASSERT_TRUE(doc.GetErrorMessage().empty());
        ASSERT_STREQ("testStringValue", view.GetString("testStringKey").c_str());
        ASSERT_FALSE(view.GetBool("testBoolKey"));
        ASSERT_EQ(10, view.GetInteger("testIntKey"));
        ASSERT_EQ(8765432109876543210, view.GetInt64("testInt64Key"));
        ASSERT_EQ(6.626e-34, view.GetDouble("testDoubleKey"));
        ASSERT_STREQ("stringArrayEntry1", view.GetArray("array")[0].AsString().c_str());
        ASSERT_STREQ("stringArrayEntry2", view.GetArray("array")[1].AsString().c_str());
        ASSERT_STREQ("testObjectStringValue", view.GetObject("object").GetString("testObjectStringKey").c_str());
    }
    else
    {
        GTEST_NONFATAL_FAILURE_(reparsedDoc.GetErrorMessage().c_str());
    }
}

TEST(DocumentTest, TestNullSanity)
{
    Document doc;
    DocumentView view = doc.View();
    ASSERT_STREQ("null", view.WriteReadable().c_str());
    ASSERT_STREQ("null", view.WriteCompact().c_str());
    auto map = view.GetAllObjects();
    ASSERT_TRUE(map.empty());
    ASSERT_FALSE(view.ValueExists("null"));
}

TEST(DocumentTest, TestKeyValueExists)
{
    auto input = R"({"AWS" : {
        "key" : "value",
        "nullKey" : null
    }})";
    Document doc(input);
    auto view = doc.View().GetObject("AWS");

    ASSERT_TRUE(view.ValueExists("key"));
    ASSERT_FALSE(view.ValueExists("nullKey"));
    ASSERT_FALSE(view.ValueExists("notExistsKey"));

    ASSERT_TRUE(view.KeyExists("key"));
    ASSERT_TRUE(view.KeyExists("nullKey"));
    ASSERT_FALSE(view.KeyExists("notExistsKey"));
}

TEST(DocumentTest, TestCopy)
{
    Document doc;
    ASSERT_TRUE(doc.WasParseSuccessful());
    Document copiedDoc(doc);
    ASSERT_TRUE(copiedDoc.WasParseSuccessful());
    Document copiedDoc2;
    copiedDoc2 = doc;
    ASSERT_TRUE(copiedDoc2.WasParseSuccessful());
    Document bad(Aws::String("not valid json"));
    ASSERT_FALSE(bad.WasParseSuccessful());
    copiedDoc = bad;
    ASSERT_FALSE(copiedDoc.WasParseSuccessful());
}

TEST(DocumentTest, TestMove)
{
    Document doc;
    ASSERT_TRUE(doc.WasParseSuccessful());
    Document movedDoc(doc);
    ASSERT_TRUE(movedDoc.WasParseSuccessful());
    Document movedDoc2;
    movedDoc2 = doc;
    ASSERT_TRUE(movedDoc2.WasParseSuccessful());
    Document bad(Aws::String("not valid json"));
    ASSERT_FALSE(bad.WasParseSuccessful());
    movedDoc = bad;
    ASSERT_FALSE(movedDoc.WasParseSuccessful());
}

TEST(DocumentTest, TestBuilderPatternReplacesKeys)
{
    auto input = R"({"AWS" : {
        "stringKey" : "StringValue",
        "intKey" : 42
    }})";

    Document doc(input);
    auto modified = doc.View().GetObject("AWS")
        .Materialize()
        .WithString("stringKey", "anotherStringValue")
        .WithInteger("intKey", 43);
    const auto output = doc.WithObject("AWS", modified).View().WriteCompact();
    const auto expected = R"({"AWS":{"stringKey":"anotherStringValue","intKey":43}})";
    ASSERT_STREQ(expected, output.c_str());
}

TEST(DocumentTest, TestGetAllObjects)
{
    auto input = R"({"AWS" : {
        "stringKey" : "StringValue",
        "intKey" : 42
    }})";

    Document doc(input);
    auto docView = doc.View();
    ASSERT_EQ(1u, docView.GetAllObjects().size());
    auto all = docView.GetObject("AWS").GetAllObjects();
    ASSERT_EQ(2u, all.size());
    ASSERT_STREQ("StringValue", all["stringKey"].AsString().c_str());
    ASSERT_EQ(42, all["intKey"].AsInteger());
}

TEST(DocumentTest, TestEquality)
{
    auto input = R"({"AWS" : {
        "stringKey" : "StringValue",
        "intKey" : 42
    }})";

    Document parsed(input);
    Document keys;
    keys.WithString("stringKey", "StringValue").WithInteger("intKey", 42);

    Document built;
    built.WithObject("AWS", keys);
    ASSERT_EQ(parsed, built);
    built.WithString("AWS", "Amazon Web Services");
    ASSERT_NE(parsed, built);
}

#if ENABLE_FUNCTIONAL_TESTING
#include <aws/core/http/HttpClientFactory.h>
#include <aws/core/http/standard/StandardHttpResponse.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <aws/core/client/DefaultRetryStrategy.h>
#include <aws/testing/mocks/aws/client/MockAWSClient.h>
#include <aws/document-test/DocumentTestClient.h>
#include <aws/document-test/model/DocumentTypeOperationRequest.h>

using namespace Aws::Http;
using namespace Aws::Http::Standard;
using namespace Aws::Utils::Json;
using namespace Aws::DocumentTest;
using namespace Aws::DocumentTest::Model;

static const char ALLOCATION_TAG[] = "DocumentTest";

TEST(DocumentTest, TestRequestResponseBody)
{
    std::shared_ptr<MockHttpClient> mockHttpClient = Aws::MakeShared<MockHttpClient>(ALLOCATION_TAG);
    std::shared_ptr<MockHttpClientFactory> mockHttpClientFactory = Aws::MakeShared<MockHttpClientFactory>(ALLOCATION_TAG);
    mockHttpClientFactory->SetClient(mockHttpClient);
    SetHttpClientFactory(mockHttpClientFactory);

    auto httpRequest = CreateHttpRequest(URI("http://www.uri.com/path/to/res"),
            HttpMethod::HTTP_GET, Aws::Utils::Stream::DefaultResponseStreamFactoryMethod);
    httpRequest->SetResolvedRemoteHost("127.0.0.1");
    auto httpResponse = Aws::MakeShared<StandardHttpResponse>(ALLOCATION_TAG, httpRequest);
    httpResponse->SetResponseCode(Aws::Http::HttpResponseCode::OK);
    httpResponse->GetResponseBody() << R"({
        "StringTypeMember": "ResponseStringMember",
        "DocumentTypeMember": {
            "AWS": {
                "boolKey": false,
                "doubleKey": 6.626e-34
            }
        }
    })";
    mockHttpClient->AddResponseToReturn(httpResponse);

    Aws::Client::ClientConfiguration config;
    config.retryStrategy = Aws::MakeShared<Aws::Client::DefaultRetryStrategy>(ALLOCATION_TAG, 0 /* don't retry */, 25);
    DocumentTestClient client(config);
    DocumentTypeOperationRequest request;
    request.SetStringTypeMember("RequestStringMember");
    Document doc(R"({"AWS" : {
        "stringKey" : "StringValue",
        "intKey" : 42
    }})");
    request.SetDocumentTypeMember(doc);

    auto outcome = client.DocumentTypeOperation(request);
    ASSERT_TRUE(outcome.IsSuccess());

    JsonValue expectedRequestBody;
    expectedRequestBody.WithString("StringTypeMember", "RequestStringMember");
    expectedRequestBody.WithObject("DocumentTypeMember", JsonValue(doc.View()));
    Aws::StringStream ss;
    ss << request.GetBody()->rdbuf();
    JsonValue actualRequestBody(ss.str());
    ASSERT_EQ(expectedRequestBody, actualRequestBody);

    ASSERT_STREQ("ResponseStringMember", outcome.GetResult().GetStringTypeMember().c_str());
    DocumentView view = outcome.GetResult().GetDocumentTypeMember();
    ASSERT_TRUE(view.KeyExists("AWS"));
    ASSERT_FALSE(view.GetObject("AWS").GetBool("boolKey"));
    ASSERT_EQ(6.626e-34, view.GetObject("AWS").GetDouble("doubleKey"));

    // Test null sanity
    auto httpRequestWithNullDoc = CreateHttpRequest(URI("http://www.uri.com/path/to/res"),
            HttpMethod::HTTP_GET, Aws::Utils::Stream::DefaultResponseStreamFactoryMethod);
    httpRequestWithNullDoc->SetResolvedRemoteHost("127.0.0.1");
    auto httpResponseWithNullDoc = Aws::MakeShared<StandardHttpResponse>(ALLOCATION_TAG, httpRequestWithNullDoc);
    httpResponseWithNullDoc->SetResponseCode(Aws::Http::HttpResponseCode::OK);
    httpResponseWithNullDoc->GetResponseBody() << R"({
        "StringTypeMember": "ResponseStringMember",
        "DocumentTypeMember": null
    })";
    mockHttpClient->AddResponseToReturn(httpResponseWithNullDoc);

    Document nullDoc("null");
    request.SetDocumentTypeMember(nullDoc);

    outcome = client.DocumentTypeOperation(request);
    ASSERT_TRUE(outcome.IsSuccess());

    JsonValue expectedRequestBodyWithNullDoc;
    expectedRequestBodyWithNullDoc.WithString("StringTypeMember", "RequestStringMember");
    ss.str("");
    ss << request.GetBody()->rdbuf();
    JsonValue actualRequestBodyWithNullDoc(ss.str());
    ASSERT_EQ(expectedRequestBodyWithNullDoc, actualRequestBodyWithNullDoc);

    ASSERT_STREQ("ResponseStringMember", outcome.GetResult().GetStringTypeMember().c_str());
    ASSERT_STREQ("null", outcome.GetResult().GetDocumentTypeMember().WriteCompact().c_str());

    CleanupHttp();
    InitHttp();
}
#endif // ENABLE_FUNCTIONAL_TESTING


text:
name 'build_cookbook'
maintainer 'Jp Robinson'
maintainer_email 'you@example.com'
license 'all_rights'
version '0.1.0'
chef_version '>= 12.1' if respond_to?(:chef_version)
depends 'delivery-sugar'
depends 'delivery-truck'


text:
const SocketClusterAdapter = require('./adapters/socket-cluster');

class Provider {

    /**
     *
     * @param name
     * @param options
     */
    constructor(name, options) {

        /**
         *
         * @type {{socket-cluster: SocketClusterAdapter}}
         */
        const list = {
            'socket-cluster': SocketClusterAdapter
        };

        return new list[name](options);
    }
}

module.exports = Provider;


text:
package org.ovirt.engine.core.aaa.filters;

import java.io.IOException;
import java.lang.reflect.Field;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.UUID;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.ovirt.engine.api.extensions.Base;
import org.ovirt.engine.api.extensions.ExtKey;
import org.ovirt.engine.api.extensions.ExtMap;
import org.ovirt.engine.api.extensions.ExtUUID;
import org.ovirt.engine.api.extensions.aaa.Acct;
import org.ovirt.engine.api.extensions.aaa.Authn;
import org.ovirt.engine.core.aaa.AcctUtils;
import org.ovirt.engine.core.aaa.AuthType;
import org.ovirt.engine.core.aaa.AuthenticationProfile;
import org.ovirt.engine.core.aaa.AuthenticationProfileRepository;

public class BasicAuthenticationFilter implements Filter {

    private static enum UserNameFormat {
        UPN,
        RESTAPI_SPECIFIC
    };

    private static class UserProfile {

        private String userName;
        private AuthenticationProfile profile;

        public UserProfile(String user, AuthenticationProfile profile) {
            this.userName = user;
            this.profile = profile;
        }
    }

    private static final Map<Integer, String> authResultMap;
    static {
        try {
            authResultMap = new HashMap<Integer, String>();
            for (Field field : Authn.AuthResult.class.getFields()) {
                authResultMap.put((Integer)field.get(null), field.getName());
            }
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }

    private static final Logger log = LoggerFactory.getLogger(BasicAuthenticationFilter.class);
    private UserNameFormat userNameFormat = UserNameFormat.UPN;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        try {
            userNameFormat = UserNameFormat.valueOf(filterConfig.getInitParameter("user-name-format"));
        } catch (Exception ex) {
            log.error("The value {} is not a valid UserNameFormat. setting UPN as default", filterConfig.getInitParameter("user-name-format"));
        }

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException,
            ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        log.info("enter into the basic authentication");
        if (!FiltersHelper.isAuthenticated(req)) {
        	if (req.getRequestURI().contains("/license")) {
        		handleCredentials(req, "", "", true);
        	} else {
	            String headerValue = req.getHeader(FiltersHelper.Constants.HEADER_AUTHORIZATION);
	            if (headerValue != null && headerValue.startsWith("Basic ")) {
	                String[] creds = new String(
	                        Base64.decodeBase64(headerValue.substring("Basic".length())),
	                        Charset.forName("UTF-8")
	                    ).split(":", 2);
	                if (creds != null && creds.length == 2) {
	                    handleCredentials(req, creds[0], creds[1], false);
	                } else {
	                    log.error("Error in parsing basic authorization information");
	                }
	            }
        	}
        }
        chain.doFilter(request, response);
    }

    private UserProfile translateUser(String translateFrom) {
        UserProfile result = translateUserProfileUpn(translateFrom);
        if (userNameFormat == UserNameFormat.RESTAPI_SPECIFIC && result == null) {
            result = translateUserRestApiSpecific(translateFrom);
        }
        if (result == null) {
            result = new UserProfile(translateFrom, null);
        }
        return result;
    }

    private UserProfile translateUserProfileUpn(String translateFrom) {
        UserProfile result = null;
        int separator = translateFrom.lastIndexOf("@");
        if (separator != -1) {
            String profileName = translateFrom.substring(separator + 1);
            AuthenticationProfile profile = AuthenticationProfileRepository.getInstance().getProfile(profileName);
            result = profile != null ? new UserProfile(translateFrom.substring(0, separator), profile) : null;
        }
        return result;
    }

    private UserProfile translateUserRestApiSpecific(String translateFrom) {
        UserProfile result = null;
        int separator = translateFrom.indexOf("\\");
        if (separator != -1) {

            String profileName = translateFrom.substring(0, separator);
            AuthenticationProfile profile = AuthenticationProfileRepository.getInstance().getProfile(profileName);
            result = profile != null ? new UserProfile(translateFrom.substring(separator + 1), profile) : null;
        }
        return result;
    }

    private void handleCredentials(HttpServletRequest request, String user, String password, boolean isLicense) {
        UserProfile userProfile = null;
        if (isLicense) {
        	userProfile = translateUser("admin@internal");
        	password = "admin";
        } else {
        	userProfile = translateUser(user);
        }
        if (userProfile == null || userProfile.profile == null) {
            log.error("Cannot obtain profile for user {}", user);
        } else {
        	ExtMap outputMap = null;
        	if (!isLicense) {
	            outputMap = userProfile.profile.getAuthn().invoke(new ExtMap().mput(
	                    Base.InvokeKeys.COMMAND,
	                    Authn.InvokeCommands.AUTHENTICATE_CREDENTIALS
	                    ).mput(
	                            Authn.InvokeKeys.USER,
	                            userProfile.userName
	                    ).mput(
	                           Authn.InvokeKeys.CREDENTIALS,
	                           password
	                    )
	            );
        	} else {
        		outputMap = new ExtMap();

        		ExtKey k1 = new ExtKey(Integer.class, new ExtUUID("EXTENSION_INVOKE_RESULT", UUID.fromString("0909d91d-8bde-40fb-b6c0-099c772ddd4e")), 0);
        		outputMap.put(k1, 0);

        		ExtKey k2 = new ExtKey(String.class, new ExtUUID("AAA_AUTHN_PRINCIPAL", UUID.fromString("bc637d1d-f93f-45e1-bd04-646c6dc38279")), 0);
        		outputMap.put(k2, "admin");

        		ExtKey k3 = new ExtKey(Integer.class, new ExtUUID("AAA_AUTHN_RESULT", UUID.fromString("af9771dc-a0bb-417d-a700-277616aedd85")), 0);
        		outputMap.put(k3, 0);

        		ExtKey k4 = new ExtKey(ExtMap.class, new ExtUUID("AAA_AUTHN_AUTH_RECORD", UUID.fromString("e9462168-b53b-44ac-9af5-f25e1697173e")), 0);

        		ExtMap k4m = new ExtMap();
        		ExtKey k4mk = new ExtKey(String.class, new ExtUUID("AAA_AUTHN_AUTH_RECORD_PRINCIPAL", UUID.fromString("c3498f07-11fe-464c-958c-8bd7490b119a")), 0);
        		k4m.put(k4mk, "admin");
        		outputMap.put(k4, k4m);
        	}

            if (isLicense || (outputMap.<Integer> get(Base.InvokeKeys.RESULT) == Base.InvokeResult.SUCCESS &&
                    outputMap.<Integer> get(Authn.InvokeKeys.RESULT) == Authn.AuthResult.SUCCESS)) {
                request.setAttribute(FiltersHelper.Constants.REQUEST_AUTH_RECORD_KEY,
                    outputMap.<ExtMap> get(Authn.InvokeKeys.AUTH_RECORD));
                request.setAttribute(FiltersHelper.Constants.REQUEST_AUTH_TYPE_KEY, AuthType.CREDENTIALS);
                request.setAttribute(FiltersHelper.Constants.REQUEST_PROFILE_KEY, userProfile.profile.getName());
                request.setAttribute(FiltersHelper.Constants.REQUEST_PASSWORD_KEY, password);
            } else {
                int authResultCode = outputMap.<Integer> get(Authn.InvokeKeys.RESULT, Authn.AuthResult.GENERAL_ERROR);
                String authnResult = authResultMap.get(authResultCode);
                if (authnResult == null) {
                    authnResult = Integer.toString(authResultCode);
                }
                AcctUtils.reportRecords(
                        Acct.ReportReason.PRINCIPAL_LOGIN_FAILED,
                        userProfile.profile.getAuthzName(),
                        userProfile.userName,
                        null,
                        null,
                        "Basic authentication failed for User %1$s (%2$s).",
                        userProfile.userName,
                        authnResult
                        );
                log.error("User {} authentication failed. profile is {}. Invocation Result code is {}. Authn result code is {}",
                        userProfile.userName,
                        userProfile.profile.getName(),
                        outputMap.<Integer> get(Base.InvokeKeys.RESULT),
                        authnResult
                        );
            }
        }
    }

    @Override
    public void destroy() {
    }

}


text:
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >

<suite name="DBCJ-TEST" verbose="1" >

    <test name="DBCJ">
        <parameter name="url" value="adbcj:mysql://localhost/adbcjtck"/>
        <parameter name="user" value="adbcjtck"/>
        <parameter name="password" value="adbcjtck"/>
        <packages>
            <package name="org.adbcj.dbcj"/>
        </packages>
        <classes>
            <class name="org.adbcj.dbcj.ConnectionTest"/>
            <class name="org.adbcj.dbcj.UtilTest"/>
        </classes>
    </test>
</suite>


text:
import MySQLdb
import logging

from cdsagent.common import base
from cdsagent import cfg

__author__ = 'Hardy.zheng'

conf = cfg.CONF
LOG = logging.getLogger(__name__)

class MysqlBase(base.Connection):
    def __init__(self, dbname):
        try:
            self.conn = MySQLdb.connect(host=conf.mysql.host,
                                        user=conf.mysql.user,
                                        passwd=conf.mysql.passwd,
                                        db=dbname,
                                        port=int(conf.mysql.port))
        except MySQLdb.Error, e:
            self.conn = None
            LOG.error(str(e))

    def clear(self):
        self.conn.close()


text:
footer

<?php
if (!isset ($export)):
	require '../lib/developer-bar.php';
endif;
?>