text:
namespace quark {

using namespace couchit;

 bool app_version_changed = false;

void initOrdersDB(CouchDB &db) {

	db.putDesignDocument(designdoc_index,designdoc_index_length);
	Document ver;
	ver= db.get("version", CouchDB::flgCreateNew);
	if (ver["version"].getString() != QUARK_VERSION) {
		ver.set("version", QUARK_VERSION);
		db.put(ver);
		app_version_changed = true;
	}
}

void initTradesDB(couchit::CouchDB& db) {
	db.putDesignDocument(designdoc_trades,designdoc_trades_length);
}

void initPositionsDB(couchit::CouchDB& db) {
	db.putDesignDocument(designdoc_positions,designdoc_positions_length);
}

}

redpajama_set_name: RedPajamaGithub


text:
package ru.imho.ddsmt.ds

import ru.imho.ddsmt.Base._

/**
 * Created by skotlov on 11/13/14.
 */
class GenericDsConfig(id: String) extends DataSetConfig {

  override def createDataSetInstance(): DataSet = new GenericDs(id, this)

  override def createDataSetInstance(param: Param, paramName: String): DataSet =
    new GenericDs(param.applyToString(id, paramName), this)

  override def checkStrategy: Option[CheckStrategies.Value] = None
}


text:
#include <sstream>
#include <iostream>
#include "vulkan/vulkan.h"
#include "vkbpGlobal.h"
#include "vkbpHelpers.h"

namespace vkbp {

    #define EMIT_CASE_ERROR_ENUM(e) case VK_ ##e: return #e
    std::string resolveErrorToString(VkResult err) {
        switch (err) {
            EMIT_CASE_ERROR_ENUM(NOT_READY);
            EMIT_CASE_ERROR_ENUM(TIMEOUT);
            EMIT_CASE_ERROR_ENUM(EVENT_SET);
            EMIT_CASE_ERROR_ENUM(EVENT_RESET);
            EMIT_CASE_ERROR_ENUM(INCOMPLETE);
            EMIT_CASE_ERROR_ENUM(ERROR_OUT_OF_HOST_MEMORY);
            EMIT_CASE_ERROR_ENUM(ERROR_OUT_OF_DEVICE_MEMORY);
            EMIT_CASE_ERROR_ENUM(ERROR_INITIALIZATION_FAILED);
            EMIT_CASE_ERROR_ENUM(ERROR_DEVICE_LOST);
            EMIT_CASE_ERROR_ENUM(ERROR_MEMORY_MAP_FAILED);
            EMIT_CASE_ERROR_ENUM(ERROR_LAYER_NOT_PRESENT);
            EMIT_CASE_ERROR_ENUM(ERROR_EXTENSION_NOT_PRESENT);
            EMIT_CASE_ERROR_ENUM(ERROR_INCOMPATIBLE_DRIVER);
            EMIT_CASE_ERROR_ENUM(ERROR_FEATURE_NOT_PRESENT);
            EMIT_CASE_ERROR_ENUM(ERROR_TOO_MANY_OBJECTS);
            EMIT_CASE_ERROR_ENUM(ERROR_FORMAT_NOT_SUPPORTED);
            EMIT_CASE_ERROR_ENUM(ERROR_SURFACE_LOST_KHR);
            EMIT_CASE_ERROR_ENUM(ERROR_NATIVE_WINDOW_IN_USE_KHR);
            EMIT_CASE_ERROR_ENUM(SUBOPTIMAL_KHR);
            EMIT_CASE_ERROR_ENUM(ERROR_OUT_OF_DATE_KHR);
            EMIT_CASE_ERROR_ENUM(ERROR_INCOMPATIBLE_DISPLAY_KHR);
            EMIT_CASE_ERROR_ENUM(ERROR_VALIDATION_FAILED_EXT);
            EMIT_CASE_ERROR_ENUM(ERROR_INVALID_SHADER_NV);
            case VK_RESULT_MAX_ENUM:
                return "Error";
                break;
            default:
                return "Unknown Error";
        }
    }
    #undef EMIT_CASE_ERROR_ENUM

    #define EMIT_CASE_PHYSICAL_DEVICE_TYPE_ENUM(r) case VK_PHYSICAL_DEVICE_TYPE_ ##r: return #r
    std::string resolvePhysicalDeviceTypeToString(VkPhysicalDeviceType type) {
        switch(type) {
            EMIT_CASE_PHYSICAL_DEVICE_TYPE_ENUM(OTHER);
            EMIT_CASE_PHYSICAL_DEVICE_TYPE_ENUM(INTEGRATED_GPU);
            EMIT_CASE_PHYSICAL_DEVICE_TYPE_ENUM(DISCRETE_GPU);
            EMIT_CASE_PHYSICAL_DEVICE_TYPE_ENUM(VIRTUAL_GPU);
            EMIT_CASE_PHYSICAL_DEVICE_TYPE_ENUM(CPU);
            default:
                return "Unknown Type";
        }
    }
    #undef EMIT_CASE_PHYSICAL_DEVICE_TYPE_ENUM

    VkbpResult::VkbpResult(const char* message /*= ""*/)
            : lineNumber(-1), errCode(VK_SUCCESS), fileName(""), funcName(""), message(message) { }

    VkbpResult::VkbpResult(const char* fileName, const char* funcName, int lineNumber, VkResult errCode,
                           const char* message /*= ""*/)
            : lineNumber(lineNumber), errCode(errCode), fileName(fileName), funcName(funcName), message(message) { }

    std::string VkbpResult::toString() {
        return resolveErrorToString(errCode) + " found in file \'" + fileName + "\'" +
                (funcName.length() ? " in function " : "" ) + funcName +
                " at line " + std::to_string(lineNumber) +
                (message.length() ? " with message: " : "") + message;
    }

}


text:
'use strict';

var rimraf = require('rimraf');
var path = require("path");

module.exports = function(grunt) {

  function createunit(filepath, options) {
    if (!grunt.file.exists(filepath)) {
      return false;
    }

    var opt = {
        grunt: grunt.config(),
        testfile: path.join('..',filepath),
        name: path.basename( filepath, options.test_sufix )
    }

    opt.filename = path.join( options.destination, opt.name + options.run_sufix );

    grunt.log.write('Createunit ' + opt.filename + '...');

    var tpl = grunt.file.read( options.template );
    tpl = grunt.template.process( tpl, { data: opt } );

    grunt.file.write( opt.filename, tpl );
    grunt.log.ok();
  }

  grunt.registerMultiTask('createunit', 'Create nodeunit and qunit files.', function() {
    // Merge task-specific and/or target-specific options with these defaults.
    var options = this.options({
      test_sufix: '_test.js',
      run_sufix: '_run.js'
    });

    // Create specified unit files.
    this.filesSrc.forEach(function(filepath) {
      createunit(filepath, options);
    });
  });

};


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

package cgotest

/*
#include <stdint.h>

typedef struct {
	char x;
	long y;
} __attribute__((__packed__)) misaligned;

int
offset7560(void)
{
	return (uintptr_t)&((misaligned*)0)->y;
}
*/
import "C"

import (
	"reflect"
	"testing"
)

func test7560(t *testing.T) {
	// some mingw don't implement __packed__ correctly.
	if C.offset7560() != 1 {
		t.Skip("C compiler did not pack struct")
	}

	// C.misaligned should have x but then a padding field to get to the end of the struct.
	// There should not be a field named 'y'.
	var v C.misaligned
	rt := reflect.TypeOf(&v).Elem()
	if rt.NumField() != 2 || rt.Field(0).Name != "x" || rt.Field(1).Name != "_" {
		t.Errorf("unexpected fields in C.misaligned:\n")
		for i := 0; i < rt.NumField(); i++ {
			t.Logf("%+v\n", rt.Field(i))
		}
	}
}


text:
import {ArrayEntry, MapEntry, ObjectEntry, SetEntry} from './entry';

type ArrayEntries<BaseType extends readonly unknown[]> = Array<ArrayEntry<BaseType>>;
type MapEntries<BaseType> = Array<MapEntry<BaseType>>;
type ObjectEntries<BaseType> = Array<ObjectEntry<BaseType>>;
type SetEntries<BaseType extends Set<unknown>> = Array<SetEntry<BaseType>>;

/**
Many collections have an `entries` method which returns an array of a given object's own enumerable string-keyed property [key, value] pairs. The `Entries` type will return the type of that collection's entries.

For example the {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries|`Object`}, {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/entries|`Map`}, {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/entries|`Array`}, and {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set/entries|`Set`} collections all have this method. Note that `WeakMap` and `WeakSet` do not have this method since their entries are not enumerable.

@see `Entry` if you want to just access the type of a single entry.

@example
```
import {Entries} from 'type-fest';

interface Example {
	someKey: number;
}

const manipulatesEntries = (examples: Entries<Example>) => examples.map(example => [
	// Does some arbitrary processing on the key (with type information available)
	example[0].toUpperCase(),

	// Does some arbitrary processing on the value (with type information available)
	example[1].toFixed()
]);

const example: Example = {someKey: 1};
const entries = Object.entries(example) as Entries<Example>;
const output = manipulatesEntries(entries);

// Objects
const objectExample = {a: 1};
const objectEntries: Entries<typeof objectExample> = [['a', 1]];

// Arrays
const arrayExample = ['a', 1];
const arrayEntries: Entries<typeof arrayExample> = [[0, 'a'], [1, 1]];

// Maps
const mapExample = new Map([['a', 1]]);
const mapEntries: Entries<typeof map> = [['a', 1]];

// Sets
const setExample = new Set(['a', 1]);
const setEntries: Entries<typeof setExample> = [['a', 'a'], [1, 1]];
```
*/
export type Entries<BaseType> =
	BaseType extends Map<unknown, unknown> ? MapEntries<BaseType>
		: BaseType extends Set<unknown> ? SetEntries<BaseType>
		: BaseType extends unknown[] ? ArrayEntries<BaseType>
		: BaseType extends object ? ObjectEntries<BaseType>
		: never;


text:
require 'test_helper'

class SearchQueryTest < Minitest::Test
  let(:connection_options) { { :token => 'dummy' } }
  let(:connection) { Papertrail::Connection.new(connection_options) }
  let(:api_url) { Papertrail::SearchQuery.api_url }
  let(:default_initial_params) { { :limit => Papertrail::SearchQuery.initial_search_limit } }
  let(:get_response) { OpenStruct.new(:body => { 'max_id' => 122, 'events' => [] }) }

  describe 'default options' do
    let(:search_query) { Papertrail::SearchQuery.new(connection) }
    let(:target_params) do
      {
        :min_id => 122,
        :limit => Papertrail::SearchQuery.subsequent_search_limit
      }
    end

    def test_sets_min_id_for_initial_and_subsequent_requests
      # Test that the first request happens with the default_initial_params
      connection.expects(:get).with(api_url, default_initial_params).returns(get_response)
      search_query.next_results_page
      # And that subsequent requests use the updated min_id and limit
      connection.expects(:get).with(api_url, target_params).returns(get_response)
      search_query.next_results_page
    end
  end

  describe 'passed options' do
    let(:options) do
      {
        :group_id => 12,
        :system_id => 22,
        :min_id => 100,
        :limit => 2
      }
    end
    let(:search_query) { Papertrail::SearchQuery.new(connection, 'some search', options) }
    let(:target_first_params) { options.merge(:q => 'some search') }
    let(:target_subsequent_params) { target_first_params.merge(:min_id => 122) } # Max ID from get_response

    def test_sets_options_from_passed_options_and_ups_min_id
      connection.expects(:get).with(api_url, target_first_params).returns(get_response)
      search_query.next_results_page
      connection.expects(:get).with(api_url, target_subsequent_params).returns(get_response)
      search_query.next_results_page
    end
  end
end


text:
<!DOCTYPE html>

  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
  <title>Nature of the Product</title>

  <link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet">
  <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css" rel="stylesheet">
  <link href="/assets/stylesheets/application.css" rel="stylesheet" />
  <link href="http://fonts.googleapis.com/css?family=Open+Sans:300,400" rel="stylesheet" type="text/css">
  <link href="http://fonts.googleapis.com/css?family=Lora:700,700italic|Lato|Pacifico" rel="stylesheet" type="text/css">

      <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".nav-primary">
        Toggle navigation

      </button>

Home

About

Contact

Media Pattern

Welcome the Media Pattern

        September 1, 2014

Curabitur blandit tempus porttitor. Curabitur blandit tempus porttitor. Donec id elit non mi porta gravida at eget metus. Cras justo odio, dapibus ac facilisis in, egestas eget quam. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus. Morbi leo risus, porta ac consectetur ac, vestibulum at eros. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Sed posuere consectetur est at lobortis. Etiam porta sem malesuada magna mollis euismod. Maecenas sed diam eget risus varius blandit sit amet non magna.

        Read More

          Nature of the Product © 2017

We are a participant in the Amazon Services LLC Associates Program, an affiliate advertising program designed to provide a means for us to earn fees by linking to Amazon.com and affiliated sites.


text:
/* -*- Mode: C; c-basic-offset:4 ; -*- */
/*
 *  (C) 2001 by Argonne National Laboratory.
 *      See COPYRIGHT in top-level directory.
 */

// MainFrm.cpp : implementation of the CMainFrame class
//

#include "stdafx.h"
#include "rimshot.h"

#include "MainFrm.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

/////////////////////////////////////////////////////////////////////////////
// CMainFrame

IMPLEMENT_DYNCREATE(CMainFrame, CFrameWnd)

BEGIN_MESSAGE_MAP(CMainFrame, CFrameWnd)
	//{{AFX_MSG_MAP(CMainFrame)
	ON_WM_CREATE()
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

static UINT indicators[] =
{
	ID_SEPARATOR,           // status line indicator
	ID_INDICATOR_CAPS,
	ID_INDICATOR_NUM,
	ID_INDICATOR_SCRL,
};

/////////////////////////////////////////////////////////////////////////////
// CMainFrame construction/destruction

CMainFrame::CMainFrame()
{
}

CMainFrame::~CMainFrame()
{
}

int CMainFrame::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
	if (CFrameWnd::OnCreate(lpCreateStruct) == -1)
		return -1;

	if (!m_wndToolBar.CreateEx(this, TBSTYLE_FLAT, WS_CHILD | WS_VISIBLE | CBRS_TOP
		| CBRS_GRIPPER | CBRS_TOOLTIPS | CBRS_FLYBY | CBRS_SIZE_DYNAMIC) ||
		!m_wndToolBar.LoadToolBar(IDR_MAINFRAME))
	{
		TRACE0("Failed to create toolbar\n");
		return -1;      // fail to create
	}

	if (!m_wndStatusBar.Create(this) ||
		!m_wndStatusBar.SetIndicators(indicators,
		  sizeof(indicators)/sizeof(UINT)))
	{
		TRACE0("Failed to create status bar\n");
		return -1;      // fail to create
	}

	m_wndToolBar.EnableDocking(CBRS_ALIGN_ANY);
	EnableDocking(CBRS_ALIGN_ANY);
	DockControlBar(&m_wndToolBar);

	return 0;
}

BOOL CMainFrame::PreCreateWindow(CREATESTRUCT& cs)
{
	if( !CFrameWnd::PreCreateWindow(cs) )
		return FALSE;
	return TRUE;
}

/////////////////////////////////////////////////////////////////////////////
// CMainFrame diagnostics

#ifdef _DEBUG
void CMainFrame::AssertValid() const
{
	CFrameWnd::AssertValid();
}

void CMainFrame::Dump(CDumpContext& dc) const
{
	CFrameWnd::Dump(dc);
}

#endif //_DEBUG

/////////////////////////////////////////////////////////////////////////////
// CMainFrame message handlers


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

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.11"/>
<title>GrPPI: pipeline.h File Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="search/search.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

GrPPI
    0.2

Generic and Reusable Parallel Pattern Interface

Main Page

Related Pages

Modules

Namespaces

Classes

Files

          <input type="text" id="MSearchField" value="Search" accesskey="S"
               onfocus="searchBox.OnSearchFieldFocus(true)"
               onblur="searchBox.OnSearchFieldFocus(false)"
               onkeyup="searchBox.OnSearchFieldChange(event)"/>

File List

include

native

Namespaces |
Functions

native/pipeline.h File Reference

#include "parallel_execution_native.h"

#include "../common/pack_traits.h"

#include "../common/callable_traits.h"

#include <thread>

#include <experimental/optional>

Include dependency graph for native/pipeline.h:

<map name="pipeline_8h" id="pipeline_8h">
<area shape="rect" id="node2" href="parallel__execution__native_8h.html" title="parallel_execution\l_native.h" alt="" coords="497,80,623,121"/>
<area shape="rect" id="node16" href="pack__traits_8h.html" title="../common/pack_traits.h" alt="" coords="792,87,955,114"/>
<area shape="rect" id="node17" href="callable__traits_8h.html" title="../common/callable\l_traits.h" alt="" coords="979,80,1111,121"/>
<area shape="rect" id="node3" href="mpmc__queue_8h.html" title="../common/mpmc_queue.h" alt="" coords="197,169,374,196"/>
<area shape="rect" id="node9" href="pool_8h.html" title="pool.h" alt="" coords="486,169,543,196"/>
</map>

This graph shows which files directly or indirectly include this file:

<map name="pipeline_8hdep" id="pipeline_8hdep">
<area shape="rect" id="node2" href="pipeline_8h.html" title="pipeline.h" alt="" coords="5,80,83,107"/>
<area shape="rect" id="node3" href="grppi_8h.html" title="grppi.h" alt="" coords="13,155,75,181"/>
</map>

Go to the source code of this file.

Namespaces

  	grppi

Functions

template<typename InQueue , typename OutQueue , int Index, typename... MoreTransformers, internal::requires_index_last< Index, MoreTransformers... >  = 0>

void 	grppi::composed_pipeline (InQueue &input_queue, const pipeline_info< parallel_execution_native, MoreTransformers... > &pipe, OutQueue &output_queue, std::vector< std::thread > &tasks)

template<typename InQueue , typename Transformer , typename OutQueue >

void 	grppi::composed_pipeline (parallel_execution_native &ex, InQueue &input_queue, Transformer &&transform_op, OutQueue &output_queue, std::vector< std::thread > &tasks)

template<typename InQueue , typename Consumer >

void 	grppi::pipeline_impl (parallel_execution_native &ex, InQueue &input_queue, Consumer &&consume)

template<typename Combiner , typename Identity , typename InQueue , typename... MoreTransformers>

void 	grppi::pipeline_impl (parallel_execution_native &ex, InQueue &input_queue, reduction_info< parallel_execution_native, Combiner, Identity > &reduction_obj, MoreTransformers...more_transform_ops)

template<typename Combiner , typename Identity , typename InQueue , typename... MoreTransformers>

void 	grppi::pipeline_impl (parallel_execution_native &ex, InQueue &input_queue, reduction_info< parallel_execution_native, Combiner, Identity > &&reduction_obj, MoreTransformers...more_transform_ops)

template<typename Combiner , typename Identity , typename InQueue , typename... MoreTransformers>

void 	grppi::pipeline_impl_ordered (parallel_execution_native &ex, InQueue &input_queue, reduction_info< parallel_execution_native, Combiner, Identity > &&reduction_obj, MoreTransformers...more_transform_ops)

template<typename Transformer , typename InQueue , typename... MoreTransformers>

void 	grppi::pipeline_impl (parallel_execution_native &ex, InQueue &input_queue, filter_info< parallel_execution_native, Transformer > &filter_obj, MoreTransformers &&...more_transform_ops)

template<typename Transformer , typename InQueue , typename... MoreTransformers>

void 	grppi::pipeline_impl_ordered (parallel_execution_native &ex, InQueue &input_queue, filter_info< parallel_execution_native, Transformer > &&filter_obj, MoreTransformers &&...more_transform_ops)

template<typename Transformer , typename InQueue , typename... MoreTransformers>

void 	grppi::pipeline_impl_unordered (parallel_execution_native &ex, InQueue &input_queue, filter_info< parallel_execution_native, Transformer > &&filter_obj, MoreTransformers &&...more_transform_ops)

template<typename Transformer , typename InQueue , typename... MoreTransformers>

void 	grppi::pipeline_impl (parallel_execution_native &ex, InQueue &input_queue, filter_info< parallel_execution_native, Transformer > &&filter_obj, MoreTransformers &&...more_transform_ops)

template<typename Transformer , typename InQueue , typename... MoreTransformers>

void 	grppi::pipeline_impl (parallel_execution_native &ex, InQueue &input_queue, farm_info< parallel_execution_native, Transformer > &farm_obj, MoreTransformers &&...more_transform_ops)

template<typename Transformer , typename InQueue , typename... MoreTransformers>

void 	grppi::pipeline_impl (parallel_execution_native &p, InQueue &input_queue, farm_info< parallel_execution_native, Transformer > &&farm_obj, MoreTransformers &&...more_transform_ops)

template<typename Transformer , typename InQueue , typename... MoreTransformers>

void 	grppi::pipeline_impl (parallel_execution_native &ex, InQueue &input_queue, Transformer &&transform_op, MoreTransformers &&...more_transform_ops)

template<typename Generator , typename... Transformers, requires_no_arguments< Generator >  = 0>

void 	grppi::pipeline (parallel_execution_native &ex, Generator &&generate_op, Transformers &&...transform_ops)

 	Invoke Pipeline pattern on a data stream with native parallel execution.  More...

<address class="footer">
Generated by

 1.8.11
</address>


text:
package org.triiskelion.tinyspring.apidoc.model;

public enum ApiParameterType {
	PATH, QUERY, HEADER, BODY
}


text:
/*	$NetBSD: resultclass.h,v 1.4 2014/07/08 05:43:40 spz Exp $	*/

/*
 * Copyright (C) 2004-2007, 2009, 2014  Internet Systems Consortium, Inc. ("ISC")
 * Copyright (C) 1999-2001  Internet Software Consortium.
 *
 * Permission to use, copy, modify, and/or distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
 * REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
 * AND FITNESS.  IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
 * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
 * LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
 * OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
 * PERFORMANCE OF THIS SOFTWARE.
 */

/* Id: resultclass.h,v 1.20 2009/09/02 23:48:03 tbox Exp  */

#ifndef ISC_RESULTCLASS_H
#define ISC_RESULTCLASS_H 1

/*! \file isc/resultclass.h
 * \brief Registry of Predefined Result Type Classes
 *
 * A result class number is an unsigned 16 bit number.  Each class may
 * contain up to 65536 results.  A result code is formed by adding the
 * result number within the class to the class number multiplied by 65536.
 *
 * Classes < 1024 are reserved for ISC use.
 * Result classes >= 1024 and <= 65535 are reserved for application use.
 */

#define ISC_RESULTCLASS_FROMNUM(num)		((num) << 16)
#define ISC_RESULTCLASS_TONUM(rclass)		((rclass) >> 16)
#define ISC_RESULTCLASS_SIZE			65536
#define ISC_RESULTCLASS_INCLASS(rclass, result) \
	((rclass) == ((result) & 0xFFFF0000))

#define	ISC_RESULTCLASS_ISC		ISC_RESULTCLASS_FROMNUM(0)
#define	ISC_RESULTCLASS_DNS		ISC_RESULTCLASS_FROMNUM(1)
#define	ISC_RESULTCLASS_DST		ISC_RESULTCLASS_FROMNUM(2)
#define	ISC_RESULTCLASS_DNSRCODE	ISC_RESULTCLASS_FROMNUM(3)
#define	ISC_RESULTCLASS_OMAPI		ISC_RESULTCLASS_FROMNUM(4)
#define	ISC_RESULTCLASS_ISCCC		ISC_RESULTCLASS_FROMNUM(5)
#define	ISC_RESULTCLASS_DHCP		ISC_RESULTCLASS_FROMNUM(6)
#define	ISC_RESULTCLASS_PK11		ISC_RESULTCLASS_FROMNUM(7)

#endif /* ISC_RESULTCLASS_H */


text:
layout: command
title: Command
lang: en
---

# team device unlink

Unlink device sessions (Irreversible operation)

# Security

`watermint toolbox` stores credentials into the file system. That is located at below path:

| OS      | Path                                                               |
|---------|--------------------------------------------------------------------|
| Windows | `%HOMEPATH%\.toolbox\secrets` (e.g. C:\Users\bob\.toolbox\secrets) |
| macOS   | `$HOME/.toolbox/secrets` (e.g. /Users/bob/.toolbox/secrets)        |
| Linux   | `$HOME/.toolbox/secrets` (e.g. /home/bob/.toolbox/secrets)         |

Please do not share those files to anyone including Dropbox support.
You can delete those files after use if you want to remove it. If you want to make sure removal of credentials, revoke application access from setting or the admin console.

Please see below help article for more detail:
* Dropbox Business: https://help.dropbox.com/installs-integrations/third-party/business-api#manage

## Auth scopes

| Description                                                                                |
|---------------------------------------------------------------------------------------------------------|
| Dropbox Business: View and manage your team's sessions, devices, and apps                               |
| Dropbox Business: View basic information about your team including names, user count, and team settings |

# Authorization

For the first run, `tbx` will ask you an authentication with your Dropbox account.
Please copy the link and paste it into your browser. Then proceed to authorization. After authorization, Dropbox will show you an authorization code. Please copy that code and paste it to the `tbx`.
```

watermint toolbox xx.x.xxx
==========================

© 2016-2022 Takayuki Okazaki
Licensed under open source licenses. Use the `license` command for more detail.

1. Visit the URL for the auth dialogue:

https://www.dropbox.com/oauth2/authorize?client_id=xxxxxxxxxxxxxxx&response_type=code&state=xxxxxxxx

2. Click 'Allow' (you might have to login first):
3. Copy the authorisation code:
Enter the authorisation code
```

# Installation

Please download the pre-compiled binary from [Latest Release](https://github.com/watermint/toolbox/releases/latest). If you are using Windows, please download the zip file like `tbx-xx.x.xxx-win.zip`. Then, extract the archive and place `tbx.exe` on the Desktop folder.
The watermint toolbox can run from any path in the system if allowed by the system. But the instruction samples are using the Desktop folder. Please replace the path if you placed the binary other than the Desktop folder.

# Usage

This document uses the Desktop folder for command example.

## Run

Windows:
```
cd $HOME\Desktop
.\tbx.exe team device unlink -file /path/to/data/file.csv
```

macOS, Linux:
```
$HOME/Desktop/tbx team device unlink -file /path/to/data/file.csv
```

Note for macOS Catalina 10.15 or above: macOS verifies Developer identity. Currently, `tbx` is not ready for it. Please select "Cancel" on the first dialogue. Then please proceed "System Preference", then open "Security & Privacy", select "General" tab.
You may find the message like:
> "tbx" was blocked from use because it is not from an identified developer.

And you may find the button "Allow Anyway". Please hit the button with your risk. At second run, please hit button "Open" on the dialogue.

## Options:

| Option              | Description            | Default |
|---------------------|------------------------|---------|
| `-delete-on-unlink` | Delete files on unlink | false   |
| `-file`             | Data file              |         |
| `-peer`             | Account alias          | default |

## Common options:

| Option             | Description                                                                               | Default              |
|--------------------|-------------------------------------------------------------------------------------------|----------------------|
| `-auth-database`   | Custom path to auth database (default: $HOME/.toolbox/secrets/secrets.db)                 |                      |
| `-auto-open`       | Auto open URL or artifact folder                                                          | false                |
| `-bandwidth-kb`    | Bandwidth limit in K bytes per sec for upload/download content. 0 for unlimited           | 0                    |
| `-budget-memory`   | Memory budget (limits some feature to reduce memory footprint)                            | normal               |
| `-budget-storage`  | Storage budget (limits logs or some feature to reduce storage usage)                      | normal               |
| `-concurrency`     | Maximum concurrency for running operation                                                 | Number of processors |
| `-debug`           | Enable debug mode                                                                         | false                |
| `-experiment`      | Enable experimental feature(s).                                                           |                      |
| `-extra`           | Extra parameter file path                                                                 |                      |
| `-lang`            | Display language                                                                          | auto                 |
| `-output`          | Output format (none/text/markdown/json)                                                   | text                 |
| `-proxy`           | HTTP/HTTPS proxy (hostname:port). Please specify `DIRECT` if you want skip setting proxy. |                      |
| `-quiet`           | Suppress non-error messages, and make output readable by a machine (JSON format)          | false                |
| `-retain-job-data` | Job data retain policy                                                                    | default              |
| `-secure`          | Do not store tokens into a file                                                           | false                |
| `-skip-logging`    | Skip logging in the local storage                                                         | false                |
| `-verbose`         | Show current operations for more detail.                                                  | false                |
| `-workspace`       | Workspace path                                                                            |                      |

# File formats

## Format: File

This report shows a list of current existing sessions in the team with team member information.

| Column                        | Description                                                                          | Example                                    |
|-------------------------------|--------------------------------------------------------------------------------------|--------------------------------------------|
| team_member_id                | ID of user as a member of a team.                                                    | dbmid:xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx  |
| email                         | Email address of user.                                                               | john.smith@example.com                     |
| status                        | The user's status as a member of a specific team. (active/invited/suspended/removed) | active                                     |
| given_name                    | Also known as a first name                                                           | John                                       |
| surname                       | Also known as a last name or family name.                                            | Smith                                      |
| familiar_name                 | Locale-dependent name                                                                | John Smith                                 |
| display_name                  | A name that can be used directly to represent the name of a user's Dropbox account.  | John Smith                                 |
| abbreviated_name              | An abbreviated form of the person's name.                                            | JS                                         |
| external_id                   | External ID that a team can attach to the user.                                      |                                            |
| account_id                    | A user's account identifier.                                                         | dbid:xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx   |
| device_tag                    | Type of the session (web_session, desktop_client, or mobile_client)                  | desktop_client                             |
| id                            | The session id.                                                                      | dbdsid:xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx |
| user_agent                    | Information on the hosting device.                                                   |                                            |
| os                            | Information on the hosting operating system                                          |                                            |
| browser                       | Information on the browser used for this web session.                                |                                            |
| ip_address                    | The IP address of the last activity from this session.                               | xx.xxx.x.xxx                               |
| country                       | The country from which the last activity from this session was made.                 | United States                              |
| created                       | The time this session was created.                                                   | 2019-09-20T23:47:33Z                       |
| updated                       | The time of the last activity from this session.                                     | 2019-10-25T04:42:16Z                       |
| expires                       | The time this session expires                                                        |                                            |
| host_name                     | Name of the hosting desktop.                                                         | nihonbashi                                 |
| client_type                   | The Dropbox desktop client type (windows, mac, or linux)                             | windows                                    |
| client_version                | The Dropbox client version.                                                          | 83.4.152                                   |
| platform                      | Information on the hosting platform.                                                 | Windows 10 1903                            |
| is_delete_on_unlink_supported | Whether it's possible to delete all of the account files upon unlinking.             | TRUE                                       |
| device_name                   | The device name.                                                                     |                                            |
| os_version                    | The hosting OS version.                                                              |                                            |
| last_carrier                  | Last carrier used by the device.                                                     |                                            |

The first line is a header line. The program will accept a file without the header.
```
team_member_id,email,status,given_name,surname,familiar_name,display_name,abbreviated_name,external_id,account_id,device_tag,id,user_agent,os,browser,ip_address,country,created,updated,expires,host_name,client_type,client_version,platform,is_delete_on_unlink_supported,device_name,os_version,last_carrier
dbmid:xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx,john.smith@example.com,active,John,Smith,John Smith,John Smith,JS,,dbid:xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx,desktop_client,dbdsid:xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx,,,,xx.xxx.x.xxx,United States,2019-09-20T23:47:33Z,2019-10-25T04:42:16Z,,nihonbashi,windows,83.4.152,Windows 10 1903,TRUE,,,
```

# Results

Report file path will be displayed last line of the command line output. If you missed command line output, please see path below. [job-id] will be the date/time of the run. Please see the latest job-id.

| OS      | Path pattern                                | Example                                                |
|---------|---------------------------------------------|--------------------------------------------------------|
| Windows | `%HOMEPATH%\.toolbox\jobs\[job-id]\reports` | C:\Users\bob\.toolbox\jobs\20190909-115959.597\reports |
| macOS   | `$HOME/.toolbox/jobs/[job-id]/reports`      | /Users/bob/.toolbox/jobs/20190909-115959.597/reports   |
| Linux   | `$HOME/.toolbox/jobs/[job-id]/reports`      | /home/bob/.toolbox/jobs/20190909-115959.597/reports    |

## Report: operation_log

This report shows the transaction result.
The command will generate a report in three different formats. `operation_log.csv`, `operation_log.json`, and `operation_log.xlsx`.

| Column                              | Description                                                                          |
|-------------------------------------|--------------------------------------------------------------------------------------|
| status                              | Status of the operation                                                              |
| reason                              | Reason of failure or skipped operation                                               |
| input.team_member_id                | ID of user as a member of a team.                                                    |
| input.email                         | Email address of user.                                                               |
| input.status                        | The user's status as a member of a specific team. (active/invited/suspended/removed) |
| input.given_name                    | Also known as a first name                                                           |
| input.surname                       | Also known as a last name or family name.                                            |
| input.display_name                  | A name that can be used directly to represent the name of a user's Dropbox account.  |
| input.device_tag                    | Type of the session (web_session, desktop_client, or mobile_client)                  |
| input.id                            | The session id.                                                                      |
| input.user_agent                    | Information on the hosting device.                                                   |
| input.os                            | Information on the hosting operating system                                          |
| input.browser                       | Information on the browser used for this web session.                                |
| input.ip_address                    | The IP address of the last activity from this session.                               |
| input.country                       | The country from which the last activity from this session was made.                 |
| input.created                       | The time this session was created.                                                   |
| input.updated                       | The time of the last activity from this session.                                     |
| input.expires                       | The time this session expires                                                        |
| input.host_name                     | Name of the hosting desktop.                                                         |
| input.client_type                   | The Dropbox desktop client type (windows, mac, or linux)                             |
| input.client_version                | The Dropbox client version.                                                          |
| input.platform                      | Information on the hosting platform.                                                 |
| input.is_delete_on_unlink_supported | Whether it's possible to delete all of the account files upon unlinking.             |
| input.device_name                   | The device name.                                                                     |
| input.os_version                    | The hosting OS version.                                                              |
| input.last_carrier                  | Last carrier used by the device.                                                     |

If you run with `-budget-memory low` option, the command will generate only JSON format report.

In case of a report become large, a report in `.xlsx` format will be split into several chunks like follows; `operation_log_0000.xlsx`, `operation_log_0001.xlsx`, `operation_log_0002.xlsx`, ...

# Proxy configuration

The executable automatically detects your proxy configuration from the environment. However, if you got an error or you want to specify explicitly, please add -proxy option, like -proxy hostname:port. Currently, the executable doesn't support proxies which require authentication.


text:
import React from 'react';
import BudgetList from '../components/BudgetList';
import {saveNewCategory, editBudgetItem} from '../utils/persistence';
import {yearMonthAsString, navYearMonth} from '../utils/helpers'
import { loadData } from '../utils/persistence';
var PropTypes = React.PropTypes;

class BudgetListContainer extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            year: props.year,
            month: props.month
        };
        this.handleAddCategoryClicked = this.handleAddCategoryClicked.bind(this);
        this.handleAddNewTransactionClicked = this.handleAddNewTransactionClicked.bind(this);
        this.handleSubmitCategory = this.handleSubmitCategory.bind(this);
        this.handleSubmitBudgetItem = this.handleSubmitBudgetItem.bind(this);
        this.handlePrevMonthButtonClicked = this.handlePrevMonthButtonClicked.bind(this);
        this.handleNextMonthButtonClicked = this.handleNextMonthButtonClicked.bind(this);
    }

    handlePrevMonthButtonClicked(e) {
        console.log("Prev Button Clicked");
        var obj = navYearMonth(this.state.year, this.state.month, "prev");
        this.setState({
            year: obj.year,
            month: obj.month
        })
    }

    handleNextMonthButtonClicked(e) {
        console.log("Next Button Clicked");
        var obj = navYearMonth(this.state.year, this.state.month, "next");
        this.setState({
            year: obj.year,
            month: obj.month
        })
    }

    handleAddCategoryClicked(e) {
        console.log("handleAddCategory - E: ", e);
        $('#categoryNameInput').val("");
        $('#categoryModal').modal('show');
    }

    handleSubmitCategory(e) {
        saveNewCategory(e.target.categoryName.value, e.target.isPermanent.checked, yearMonthAsString(this.state.year, this.state.month));
    }

    handleSubmitBudgetItem(e) {
        console.log("Saving Budget Item...", e);
        editBudgetItem(e.target.category.value, e.target.budget.value, yearMonthAsString(this.props.year, this.props.month));
    }

    handleAddNewTransactionClicked(e) {
        console.log("Clicked to add new transaction")
        $('#newTransactionCategory').val("");
        $('#newTransactionDescription').val("");
        $('#newTransactionModal').modal('show');
        ;
    }

    render() {
        return (
            <BudgetList
                year={this.state.year} month={this.state.month}
                budgetItems={loadData(yearMonthAsString(this.state.year, this.state.month))}
                onAddCategory={this.handleAddCategoryClicked}
                onAddNewTransaction={this.handleAddNewTransactionClicked}
                onSubmitCategory={this.handleSubmitCategory}
                onSubmitBudgetItem={this.handleSubmitBudgetItem}
                onPrevButtonClicked={this.handlePrevMonthButtonClicked}
                onNextButtonClicked={this.handleNextMonthButtonClicked}
            />
        );
    }
}

BudgetListContainer.contextTypes = {
  router: React.PropTypes.object.isRequired
}

BudgetListContainer.propTypes = {
  month: PropTypes.string.isRequired,
  year: PropTypes.number.isRequired
}

export default BudgetListContainer;


text:
create table t1(a int);
insert into t1 values (1);
insert into t1 values (2);
insert into t1 values (3);

select * from t1 order by 1+2 desc;
select a from t1 order by 1+2 desc;

drop table t1;


text:
using System;
using System.Collections.Generic;
using System.Text;

namespace NAudio.Wave
{
    /// <summary>
    /// Event Args for WaveInStream event
    /// </summary>
    public class WaveInEventArgs : EventArgs
    {
        private byte[] buffer;
        private int bytes;

        /// <summary>
        /// Creates new WaveInEventArgs
        /// </summary>
        public WaveInEventArgs(byte[] buffer, int bytes)
        {
            this.buffer = buffer;
            this.bytes = bytes;
        }

        /// <summary>
        /// Buffer containing recorded data. Note that it might not be completely
        /// full. <seealso cref="BytesRecorded"/>
        /// </summary>
        public byte[] Buffer
        {
            get { return buffer; }
        }

        /// <summary>
        /// The number of recorded bytes in Buffer. <seealso cref="Buffer"/>
        /// </summary>
        public int BytesRecorded
        {
            get { return bytes; }
        }
    }
}


text:
package org.seasar.doma.internal.apt.meta;

import static org.seasar.doma.internal.util.AssertionUtil.*;

import org.seasar.doma.internal.apt.cttype.MapCtType;

/**
 * @author taedium
 *
 */
public class MapListParameterMeta implements CallableSqlParameterMeta {

    protected final String name;

    protected final MapCtType mapCtType;

    public MapListParameterMeta(String name, MapCtType mapCtType) {
        assertNotNull(name, mapCtType);
        this.name = name;
        this.mapCtType = mapCtType;
    }

    public String getName() {
        return name;
    }

    public MapCtType getMapCtType() {
        return mapCtType;
    }

    @Override
    public <R, P> R accept(CallableSqlParameterMetaVisitor<R, P> visitor, P p) {
        return visitor.visitMapListParameterMeta(this, p);
    }

}


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

package com.google.api.services.identitytoolkit.v2.model;

/**
 * Additional config for Apple for code flow.
 *
 *
 This is the Java data model class that specifies how to parse/serialize into the JSON that is
 * transmitted over HTTP when working with the Identity Toolkit API. For a detailed explanation see:
 * https://developers.google.com/api-client-library/java/google-http-java-client/json
 *

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

  /**
   * Key ID for the private key.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String keyId;

  /**
   * Private key used for signing the client secret JWT.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String privateKey;

  /**
   * Apple Developer Team ID.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String teamId;

  /**
   * Key ID for the private key.
   * @return value or {@code null} for none
   */
  public java.lang.String getKeyId() {
    return keyId;
  }

  /**
   * Key ID for the private key.
   * @param keyId keyId or {@code null} for none
   */
  public GoogleCloudIdentitytoolkitAdminV2CodeFlowConfig setKeyId(java.lang.String keyId) {
    this.keyId = keyId;
    return this;
  }

  /**
   * Private key used for signing the client secret JWT.
   * @return value or {@code null} for none
   */
  public java.lang.String getPrivateKey() {
    return privateKey;
  }

  /**
   * Private key used for signing the client secret JWT.
   * @param privateKey privateKey or {@code null} for none
   */
  public GoogleCloudIdentitytoolkitAdminV2CodeFlowConfig setPrivateKey(java.lang.String privateKey) {
    this.privateKey = privateKey;
    return this;
  }

  /**
   * Apple Developer Team ID.
   * @return value or {@code null} for none
   */
  public java.lang.String getTeamId() {
    return teamId;
  }

  /**
   * Apple Developer Team ID.
   * @param teamId teamId or {@code null} for none
   */
  public GoogleCloudIdentitytoolkitAdminV2CodeFlowConfig setTeamId(java.lang.String teamId) {
    this.teamId = teamId;
    return this;
  }

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

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

}


text:
Allows  importing `.svg` graphics files into javascript source for use in styles and as image source.

## Usage

### Setup
Import from FuseBox

```js
const {SVGPlugin} = require("fuse-box");
```

Inject into a chain

```js
fuse.plugin(
     SVGPlugin()
)
```

Or add it to the main config plugins list to make it available across bundles

```js
FuseBox.init({
    plugins : [
         SVGPlugin()
    ]
});
```

### Require file in your code

```js
import logo from './logo.svg';
```

Here is an [example](https://github.com/fuse-box/react-example/blob/master/fuse.js) usage, and the [source](https://github.com/fuse-box/react-example/blob/master/src/App.jsx#L10) file that imports the SVG.

## Options
None.

## Test
To run tests
```
node test --file=SVGPlugin.test.ts
```


text:
require 'csv'
require 'parallel'

require 'aether/salesforce_helper'
require 'aether/redshift_helper'
require 'aether/types'

module Aether
  def self.sync(connections:, config:, targets:)
    staging_schema = config['redshift']['staging_schema']
    RedshiftHelper::recreate_schema(
      connection: connections.redshift,
      schema_name: staging_schema
    )

    targets ||= SalesforceHelper::all_sobject_names(
      connection: connections.salesforce)

    Parallel.map(targets, in_processes: config['number_of_processes']) do |sobject_name|
      sync_sobject(
        connections: connections,
        config: config,
        sobject_name: sobject_name)
    end

    target_schema = config['redshift']['target_schema']
    swap_schema = config['redshift']['swap_schema']

    connections.reestablish_redshift

    # grant access to staging_schema before swap
    apply_grants_to_stage =
      config['stages_to_apply_group_grants'].include?(config['stage'])
    has_readonly_groups =
      config['readonly_groups'] and config['readonly_groups'].length > 0
    if apply_grants_to_stage and has_readonly_groups
      group_fragments = config['readonly_groups'].map { |g| "GROUP #{g}" }

      schema_grant = [
        "GRANT USAGE ON SCHEMA #{staging_schema}",
        "TO #{group_fragments.join(', ')}"
      ].join(' ')
      connections.redshift.exec(schema_grant)

      table_grant = [
        'GRANT SELECT ON ALL TABLES',
        "IN SCHEMA #{staging_schema} TO #{group_fragments.join(', ')}"
      ].join(' ')
      connections.redshift.exec(table_grant)
    end

    RedshiftHelper::swap_schemas(
      connection: connections.redshift,
      staging_schema: staging_schema,
      target_schema: target_schema,
      swap_schema: swap_schema)
  end

  private

  def self.sync_sobject(connections:, config:, sobject_name:)
    sf_fields = SalesforceHelper::field_to_type(
      connection: connections.salesforce,
      sobject_name: sobject_name)

    staging_schema = config['redshift']['staging_schema']
    rs_table = sobject_name.downcase

    rs_fields = get_rs_fields(sf_fields: sf_fields)

    populate_table(
      connections: connections,
      config: config,
      target_schema: staging_schema,
      target_table: rs_table,
      sobject_name: sobject_name,
      sf_fields: sf_fields,
      rs_fields: rs_fields)
  end

  def self.populate_table(
    connections:,
    config:,
    target_schema:,
    target_table:,
    sobject_name:,
    sf_fields:,
    rs_fields:)

    # get all data

    headers = rs_fields.keys

    query = "SELECT #{sf_fields.keys.join(', ')} FROM #{sobject_name}"

    begin
      sobjects = connections.salesforce_bulk.query(sobject_name, query)
    rescue RuntimeError => e
      puts "ERROR: Got exception '#{e}' while querying '#{query}'"

      return
    end

    csv_contents = CSV.generate(headers: true, write_headers: true) do |csv|
      csv << headers

      sobjects[:results].each do |sobject|
        csv << sobject.map do |sobject_field, sf_type|
          sobject_value = sobject[sobject_field]
          rs_type = rs_fields[sobject_field.downcase]

          rs_type.transform_from_salesforce(sobject_value)
        end
      end
    end

    # upload to s3
    # TODO use gzip or lzo compression
    bucket_name = config['s3']['bucket']
    bucket = connections.s3.buckets[bucket_name]
    object_name = config['s3']['object_prefix'] + '/' + target_table + '.csv'
    object = bucket.objects[object_name]
    object.write(csv_contents)

    # reestablish pg connection:
    # https://devcenter.heroku.com/articles/forked-pg-connections#forked-environments
    connections.reestablish_redshift

    create_table(
      connection: connections.redshift,
      target_schema: target_schema,
      target_table: target_table,
      structure: rs_fields)

    aws_access_credentials =
      "'aws_access_key_id=#{connections.aws_access_key};" +
      "aws_secret_access_key=#{connections.aws_secret_key}'"

    # call copy to redshift
    copy_query = [
      "COPY #{target_schema}.#{target_table} (#{headers.join(', ')})",
      "FROM 's3://#{bucket_name}/#{object_name}'",
      'CREDENTIALS',
      aws_access_credentials,
      'CSV',
      'IGNOREHEADER 1',
      'TRUNCATECOLUMNS'
    ].join(' ')
    connections.redshift.exec(copy_query)

    # cleanup
    object.delete
  end

  def self.create_table(
    connection:,
    target_schema:,
    target_table:,
    structure:)

    create_column_fragmets = structure.map do |field_name, rs_type|
      rs_type.to_rs_schema(field_name: field_name)
    end

    create_table_query = [
      "CREATE TABLE #{target_schema}.#{target_table}",
      '(',
      create_column_fragmets.join(', '),
      ')'
    ].join(' ')

    connection.exec(create_table_query)
  end

  def self.get_rs_fields(sf_fields:)
    sf_fields.reduce({}) do |acc, (field, type)|
      key = field.downcase
      value = type.to_rs_type

      acc.merge({key => value})
    end
  end
end


text:
module Shoulda # :nodoc:
  module ActionController # :nodoc:
    module Matchers

      # Ensures that the controller rendered with the given layout.
      #
      # Example:
      #
      #   it { should render_with_layout }
      #   it { should render_with_layout(:special) }
      #   it { should_not render_with_layout }
      def render_with_layout(layout = nil)
        RenderWithLayout.new(layout)
      end

      class RenderWithLayout # :nodoc:

        def initialize(layout)
          @layout = layout.to_s unless layout.nil?
        end

        def matches?(controller)
          @controller = controller
          rendered_with_layout? && rendered_with_expected_layout?
        end

        def failure_message
          "Expected #{expectation}, but #{result}"
        end

        def negative_failure_message
          "Did not expect #{expectation}, but #{result}"
        end

        def description
          description = "render with "
          if @layout.nil?
            description << "a layout"
          else
            description << "the #{@layout.inspect} layout"
          end
          description
        end

        private

        def rendered_with_layout?
          !layout.blank?
        end

        def rendered_with_expected_layout?
          return true if @layout.nil?
          layout == @layout
        end

        def layout
          layout = @controller.response.layout
          if layout.nil?
            nil
          else
            layout.split('/').last
          end
        end

        def expectation
          "to #{description}"
        end

        def result
          if rendered_with_layout?
            "rendered with the #{layout.inspect} layout"
          else
            "rendered without a layout"
          end
        end

      end

    end
  end
end


text:
<?php

namespace Coogle\Mvc\View;

use \Coogle\Utils\Registry;

/**
 * The renderer class is responsible for actually loading the
 * view template, injecting the variables into it, providing
 * escape functionality, etc.
 */
class Renderer
{
	/**
	 * @var array
	 */
	protected $_config = [];

	/**
	 * @var string
	 */
	protected $_contentTemplate = null;

	/**
	 * The variables available in the view template
	 * @var array
	 */
	protected $_renderVars = [];

	/**
	 * The constructor
	 */
	public function __construct()
	{
		$this->setConfig(Registry::get('Config')['view']);
	}

	/**
	 * This magic method is used from within a view template to provide
	 * access to the variables.. i.e. from within view $this->foobar
	 *
	 * @param string $key
	 * @return multitype:
	 */
	public function __get($key)
	{
		if(isset($this->_renderVars[$key])) {
			return $this->_renderVars[$key];
		}
	}

	/**
	 * Called by the View class to render a given template, given layout with
	 * the given variables injected into it.
	 *
	 * @param unknown $__templateFile
	 * @param unknown $__layoutFile
	 * @param array $__vars
	 * @throws \Exception
	 * @return string
	 */
	public function render($__templateFile, $__layoutFile, array $__vars = [])
	{
		if(!file_exists($__templateFile) && is_readable($__templateFile)) {
			throw new \Exception("Could not locate view: {$__templateFile}");
		}

		$this->setContentTemplate($__templateFile);
		$this->setRenderVars($__vars);

		ob_start();

		if(isset($__layoutFile)) {
			include $__layoutFile;
		} else {
			include $__templateFile;
		}

		return ob_get_clean();
	}

	/**
	 * @param array $_renderVars
	 */
	public function setRenderVars(array $_renderVars) {
		$this->_renderVars = $_renderVars;
		return $this;
	}

	/**
	 * @return string the $_contentTemplate
	 */
	public function getContentTemplate() {
		return $this->_contentTemplate;
	}

	/**
	 * @param string $_contentTemplate
	 */
	public function setContentTemplate($_contentTemplate) {
		$this->_contentTemplate = $_contentTemplate;
		return $this;
	}

	/**
	 * @return array the $_config
	 */
	public function getConfig() {
		return $this->_config;
	}

	/**
	 * @param multitype: $_config
	 */
	public function setConfig(array $_config) {
		$this->_config = $_config;
		return $this;
	}

	/**
	 * Return the actual content of the template, used
	 * when using layouts
	 */
	public function content()
	{
		include $this->getContentTemplate();
	}

	/**
	 * Make the given string HTML friendly.
	 * @param unknown $data
	 * @return string
	 */
	public function esc($data)
	{
		return htmlspecialchars($data, ENT_QUOTES, 'UTF-8');
	}
}


text:
<?xml version="1.0"?>
<!--

-->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../vendor/magento/mtf/etc/variations.xsd">
    <testCase name="Mage\Sales\Test\TestCase\CancelCreatedOrderTest">
        <variation name="CancelCreatedOrderTestVariation1">
            <data name="description" xsi:type="string">Cancel order and check status on the frontend.</data>
            <data name="order/dataSet" xsi:type="string">with_simple_qty_3</data>
            <data name="status" xsi:type="string">Canceled</data>
            <constraint name="Mage\Sales\Test\Constraint\AssertOrderCancelSuccessMessage" />
            <constraint name="Mage\Sales\Test\Constraint\AssertOrderInOrdersGrid" />
            <constraint name="Mage\Sales\Test\Constraint\AssertOrderInOrdersGridOnFrontend" />
            <constraint name="Mage\Catalog\Test\Constraint\AssertProductInStock" />
        </variation>
    </testCase>
</config>


text:
package io.kubernetes.client.openapi.models;

import io.kubernetes.client.fluent.Fluent;
import io.kubernetes.client.fluent.Nested;
import java.util.Collection;
import java.util.List;
import java.util.function.Predicate;

/** Generated */
public interface V1WebhookConversionFluent<A extends V1WebhookConversionFluent<A>>
    extends Fluent<A> {

  /**
   * This method has been deprecated, please use method buildClientConfig instead.
   *
   * @return The buildable object.
   */
  @Deprecated
  public ApiextensionsV1WebhookClientConfig getClientConfig();

  public ApiextensionsV1WebhookClientConfig buildClientConfig();

  public A withClientConfig(ApiextensionsV1WebhookClientConfig clientConfig);

  public Boolean hasClientConfig();

  public V1WebhookConversionFluent.ClientConfigNested<A> withNewClientConfig();

  public V1WebhookConversionFluent.ClientConfigNested<A> withNewClientConfigLike(
      ApiextensionsV1WebhookClientConfig item);

  public V1WebhookConversionFluent.ClientConfigNested<A> editClientConfig();

  public V1WebhookConversionFluent.ClientConfigNested<A> editOrNewClientConfig();

  public V1WebhookConversionFluent.ClientConfigNested<A> editOrNewClientConfigLike(
      ApiextensionsV1WebhookClientConfig item);

  public A addToConversionReviewVersions(Integer index, String item);

  public A setToConversionReviewVersions(Integer index, String item);

  public A addToConversionReviewVersions(java.lang.String... items);

  public A addAllToConversionReviewVersions(Collection<String> items);

  public A removeFromConversionReviewVersions(java.lang.String... items);

  public A removeAllFromConversionReviewVersions(Collection<String> items);

  public List<String> getConversionReviewVersions();

  public String getConversionReviewVersion(Integer index);

  public String getFirstConversionReviewVersion();

  public String getLastConversionReviewVersion();

  public String getMatchingConversionReviewVersion(Predicate<String> predicate);

  public Boolean hasMatchingConversionReviewVersion(Predicate<String> predicate);

  public A withConversionReviewVersions(List<String> conversionReviewVersions);

  public A withConversionReviewVersions(java.lang.String... conversionReviewVersions);

  public Boolean hasConversionReviewVersions();

  public interface ClientConfigNested<N>
      extends Nested<N>,
          ApiextensionsV1WebhookClientConfigFluent<
              V1WebhookConversionFluent.ClientConfigNested<N>> {
    public N and();

    public N endClientConfig();
  }
}


text:
use Digest::MD5 qw(md5 md5_hex md5_base64);
use CGI;
use JSON;
use HTTP::Request::Common;
use LWP::UserAgent;
use Data::Dumper;
use HTML::Entities;
use CGI::Session;
use warnings;
print qq(Content-type: text/html\n\n);

# @file
# Example of Sequencing API usage for external developers.

# ID of your oauth2 app (oauth2 client).
#
# You will be able to get this value from Sequencing website.
#
my $client_id = 'oAuth2 Demo Perl';

# Secret of your oauth2 app (oauth2 client).
#
# You will be able to get this value from Sequencing website. Keep this value
# private.
my $client_secret = 'z7EaaKQGzLGSqXGQ7yOJlcCqynIyYaKCaxahwWuC2YBAhoduP18jWLM5VtkWOWq9-kOhVoWtWmwE5aBjlpcsaA';

# Redirect URI of your oauth2 app, where it expects Sequencing oAuth2 to
# redirect browser.
my $redirect_uri = 'https://perl-oauth-demo.sequencing.com/Default/Authcallback';

# Array of scopes, access to which you request.
my @scopes = ('demo');

# URI of Sequencing oAuth2 where you can obtain access token.
my $oauth2_token_uri = 'https://sequencing.com/oauth2/token';

# URI of Sequencing oAuth2 where you can request user to authorize your app.
my $oauth2_authorization_uri = 'https://sequencing.com/oauth2/authorize';

# oAuth2 state.

# It should be some random generated string. State you sent to authorize URI
# must match the state you get, when browser is redirected to the redirect URI
# you provided.
my $state = md5_hex('abc');

# Sequencing API endpoint.
my $api_uri = 'https://api.sequencing.com';

# Our session
my  $session = new CGI::Session();

#subroutine for geting value by parameter from GET request
sub get_value_of_parameter
{
   if ($ENV{'REQUEST_METHOD'} eq "GET")
   {
	my $parameter = @_[0];
	my $buffer = $ENV{'QUERY_STRING'};
	my @pairs = split(/&/, $buffer);

	foreach $pair (@pairs)
	{
           ($name, $value) = split(/=/, $pair);
           $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;
           $in{$name} = $value;
	}

	return $in{"$parameter"};
   }
   else
   {
	return;
   }
}

# Return access token
sub get_token
{
	  if (!defined $session->param('access_token'))
	  {
	          my $ua = LWP::UserAgent->new;
        	  $ua->agent("$0/0.1 " . $ua->agent);
	          my $post_req = POST ($oauth2_token_uri,
        	          [
                	          grant_type => 'authorization_code',
                        	  code => @_[0],
	                          redirect_uri => $redirect_uri
        	          ]);
	          $post_req->authorization_basic($client_id, $client_secret);
	          my $response = $ua->request($post_req);
        	  # print $response->decoded_content;

		  my $json = JSON->new->utf8->allow_nonref;
	          my $response_parsed = $json->decode($response->content());
        	  unless (defined $response_parsed)
	          {
        	       print 'Error in oauth2 token response: ' . $response;
             	       exit;
	          }

       	          # You are to save these 2 tokens somewhere in a permanent storage, such as
        	  # database. When access token expires, you will be able to use refresh
         	  # token to fetch a new access token without need of re-authorization by
          	  # user.

		  my $access_token = $response_parsed->{'access_token'};
	          my $refresh_token = $response_parsed->{'refresh_token'};

		  $session->param('last_refresh',  time());
		  $session->param('access_token',  $access_token);
		  $session->param('refresh_token', $refresh_token);

		  return $access_token;
	  }
 	  # We refresh token every 50 minutes
	  elsif($session->param('last_refresh') + 50*60 < time() )
	  {
	  	return refresh_token();
	  }

	  else
	  {
		return $session->param('access_token');
	  }
}

# Subroutine for refreshing token
sub refresh_token
{
          my $ua = LWP::UserAgent->new;
          $ua->agent("$0/0.1 " . $ua->agent);
          my $post_req = POST ($oauth2_token_uri,
                  [
                          grant_type => 'refresh_token',
                          refresh_token => $refresh_token
                  ]);
          $post_req->authorization_basic($client_id, $client_secret);
          my $response = $ua->request($post_req);

          my $response_parsed = $json->decode($response->content());
          unless (defined $response_parsed)
          {
               print 'Error in oauth2 token response: ' . $response;
               exit;
          }

          $access_token = $response_parsed->{'access_token'};
	  $session->param('last_refresh',  time());
	  $session->param('access_token',  $access_token);

	  return $access_token;
}

if (!defined get_value_of_parameter('code'))
{
     # We just being the oauth2 authorization loop. So we redirect the client to
     # Sequencing website and ask the user to allow our app to use his data.

     my $joined_scopes = join(' ', @scopes);
     my $url_for_redirect = $oauth2_authorization_uri
	  . "?redirect_uri=$redirect_uri"
	  . "&response_type=code"
	  . "&state=$state"
	  . "&client_id=$client_id"
	  . "&scope=$joined_scopes";

     my $t = 0; # time until redirect activates
     print "<META HTTP-EQUIV=refresh CONTENT=\"$t;URL=$url_for_redirect\">\n";
 }
else
{
     # We came back from Sequencing website and if state argument matches with our
     # state, then we proceed and exchange the authorization code that we are
     # given in GET for the access and refresh tokens. The former will be used for
     # authorization, when we make requests to Sequencing API.

     if(get_value_of_parameter('state') eq $state)
     {
	  my $code = get_value_of_parameter('code');

	  my $access_token = get_token($code);

	  my $browser = LWP::UserAgent->new;
	  my $second_response = $browser->get($api_uri.'/DataSourceList?sample=true', Authorization => 'Bearer '.$access_token);
	  my $json = JSON->new->utf8->allow_nonref;
	  our @response_json = @{$json->decode($second_response->content())};

	  unless (defined @response_json)
	  {
	       print 'Unexpected return from the Sequencing API: ' . $second_response;
	       exit;
	  }

	  require 'result.pl';
     }
     else
     {
	  print 'State argument mismatch.';
	  exit;
     }
}


text:
using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using Microsoft.DotNet.Cli.Utils;

namespace Dockerize.NET.Tests
{
    public class DotnetToolTest
    {
        private string _testProjectPath;
        private readonly Assembly _toolAssembly;

        public DotnetToolTest(Assembly toolAssembly)
        {
            _toolAssembly = toolAssembly;
        }

        public DotnetToolTest WithDisposableTestProject()
        {
            var projectName = Guid.NewGuid().ToString();
            _testProjectPath = Path.Combine(
                Path.GetDirectoryName(Path.GetTempFileName()),
                projectName,
                projectName + ".csproj");

            Directory.CreateDirectory(Path.GetDirectoryName(_testProjectPath));

            Command.CreateDotNet("new", new[] {"console"})
                .CaptureStdOut()
                .CaptureStdErr()
                .WorkingDirectory(Path.GetDirectoryName(_testProjectPath))
                .Execute();

            return this;
        }

        public int ExecuteTool(string[] args)
        {
            var muxer = new Muxer();
            var toolDepsFile = Directory.EnumerateFiles(AppContext.BaseDirectory, "*.deps.json").Single();
            var toolRuntimeConfig = Directory.EnumerateFiles(AppContext.BaseDirectory, "*.runtimeconfig.json").Single();

            var dotnetArgs = new []
            {
                "exec",
                "--runtimeconfig",
                toolRuntimeConfig,
                "--depsfile",
                toolDepsFile,
                _toolAssembly.Location
            }.Concat(args).ToArray();

            var arguments = ArgumentEscaper.EscapeAndConcatenateArgArrayForProcessStart(dotnetArgs);
            var process = Process.Start(new ProcessStartInfo()
            {
                Arguments = arguments,
                FileName = muxer.MuxerPath,
                UseShellExecute = true,
                WorkingDirectory = Path.GetDirectoryName(_testProjectPath)
            });

            process.WaitForExit();

            return process.ExitCode;
        }
    }
}


text:
ActiveRecord::Schema.define(:version => 20130417155546) do

  create_table "notes", :id => false, :force => true do |t|
    t.datetime "datetime"
    t.string   "summary"
    t.string   "type"
    t.integer  "request_id"
  end

  create_table "requests", :id => false, :force => true do |t|
    t.string "service_request_id"
    t.string "status"
    t.string "service_name"
    t.string "service_code"
    t.string "description"
    t.string "requested_datetime"
    t.string "updated_datetime"
  end

end


text:
define([
	'intern!tdd',
	'intern/chai!assert',
	'dojo/_base/declare',
	'dojo/on',
	'dgrid/List',
	'dgrid/OnDemandList',
	'dstore/Memory'
], function (test, assert, declare, on, List, OnDemandList, Memory) {
	test.suite('createDestroy', function () {
		test.test('no params list', function () {
			var list = new List();
			document.body.appendChild(list.domNode);
			list.startup();
			list.renderArray([ 'foo', 'bar', 'baz' ]);

			assert.strictEqual(list.contentNode.children.length, 3,
				'List\'s contentNode has expected number of children after renderArray');

			list.destroy();
			assert.notStrictEqual(document.body, list.parentNode,
				'List is removed from body after destroy');
		});

		// Test for issue #1030
		test.test('OnDemandList#refresh should not throw error if domNode is nullified when destroyed', function () {
			var CustomList = declare(OnDemandList, {
				destroy: function () {
					this.inherited(arguments);
					// If dgrid is mixed in with dijit hierarchy, destroy() may unset domNode
					this.domNode = null;
				}
			});
			var dfd = this.async();

			var grid = new CustomList({
				collection: new Memory({ data: [
					{ id: 1 },
					{ id: 2 },
					{ id: 3 }
				] })
			});
			document.body.appendChild(grid.domNode);
			grid.startup();

			assert.strictEqual(grid.contentNode.children.length, 5,
				'Grid\'s contentNode has expected number of children after renderArray');

			grid.destroy();

			assert.notStrictEqual(document.body, grid.parentNode, 'Grid is removed from body after destroy');

			// Start watching for global error. There should be none.
			// (Can't use assert.doesNotThrow since this will be thrown asynchronously)
			var errorCatchingHandle = on(window, 'error', function (error) {
				dfd.reject(error);
			});

			// The error had been happening in a callback queued with setTimeout(0) in
			// refresh(). Here we queue another which will run after that one to close
			// out the test.
			setTimeout(dfd.callback(function () {
				errorCatchingHandle.remove();
			}), 0);
		});
	});
});


text:
using System;

namespace EasyGCaptchaMVC.Exceptions
{
	public class InvalidKeyException : ApplicationException
	{
		public InvalidKeyException() { }
		public InvalidKeyException(string message) : base(message) { }
		public InvalidKeyException(string message, Exception inner) : base(message, inner) { }
	}
}


text:
CREATE TABLE  IF NOT EXISTS application_vulnerability (
  id BIGSERIAL PRIMARY KEY,
  application_id BIGINT,
  workflow_id BIGINT,
  workflow_run_id BIGINT,
  workflow_node_run_id BIGINT,
  workflow_number BIGINT,
  title VARCHAR(100),
  description TEXT,
  cve VARCHAR(100),
  link TEXT,
  component VARCHAR(200),
  version VARCHAR(50),
  origin TEXT,
  severity VARCHAR(25),
  fix_in VARCHAR(100),
  ignored BOOL
);
SELECT create_foreign_key_idx_cascade('FK_APPLICATION_VULN_APPLICATION', 'application_vulnerability', 'application', 'application_id', 'id');
SELECT create_foreign_key_idx_cascade('FK_APPLICATION_VULN_RUN', 'application_vulnerability', 'workflow_run', 'workflow_run_id', 'id');

-- +migrate Down
DROP TABLE application_vulnerability;


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="folderit.net.ejemplos">

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

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/titulo"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".clase2.DatepickerActivity" />
        <activity android:name=".clase2.TimepickerActivity" />
        <activity android:name=".clase2.SimpleListActivity" />
        <activity android:name=".clase3.CustomListActivity" />
        <activity android:name=".clase3.RecyclerListActivity" />
        <activity android:name=".clase2.Clase2Activity" />
        <activity android:name=".clase3.Clase3Activity" />
        <activity android:name=".clase4.AnrActivity" />
        <activity android:name=".clase4.HandlerActivity" />
        <activity android:name=".clase4.AsyncTaskActivity" />

        <service
            android:name=".clase5.StartedService"
            android:enabled="true"
            android:exported="true" />
        <service
            android:name=".clase5.BoundService"
            android:enabled="true"
            android:exported="true" />

        <receiver
            android:name=".clase5.AlarmReceiver"
            android:enabled="true"
            android:exported="true" />

        <activity android:name=".clase4.Clase4Activity" />
        <activity android:name=".clase6.SQLiteActivity" />

        <provider
            android:name=".clase6.MyContentProvider"
            android:authorities="com.folderit.net.MyProvider"
            android:enabled="true"
            android:exported="true" />

        <activity android:name=".clase5.PermisosActivity" />
        <activity android:name=".clase4.HttpUrlConnectionClientActivity" />
        <activity android:name=".clase4.IonClientActivity" />
        <activity android:name=".clase4.RetrofitClientActivity" />
        <activity android:name=".clase6.Clase6Activity" />
        <activity android:name=".clase5.Clase5Activity" />
        <activity android:name=".clase3.InefficientListActivity" />
        <activity android:name=".clase3.ExampleFormActivity" />
        <activity android:name=".clase3.StartForResultActivity" />
    </application>

</manifest>


text:
var express = require('express');
var path = require('path');
var logger = require('morgan');
var bodyParser = require('body-parser');
var http = require('http');
var routes = require('./routes/index');
var app = express();

app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use('/', routes);

app.use(function(req, res, next) {
    var err = new Error('Not Found');
    err.status = 404;
    next(err);
});

app.use(function(err, req, res, next) {
    res.locals.message = err.message;
    res.locals.error = req.app.get('env') === 'development' ? err : {};
    res.status(err.status || 500);
    res.render('error');
});

app.listen(8125, () => {
    console.log('Listening on localhost:8125');
});

module.exports = app;


text:
package io.soabase.guice;

import com.fasterxml.jackson.databind.BeanProperty;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.InjectableValues;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.ImmutableSet;
import com.google.inject.AbstractModule;
import com.google.inject.Binding;
import com.google.inject.Injector;
import com.google.inject.Key;
import com.google.inject.Module;
import io.dropwizard.Configuration;
import io.dropwizard.ConfiguredBundle;
import io.dropwizard.configuration.ConfigurationFactory;
import io.dropwizard.configuration.ConfigurationFactoryFactory;
import io.dropwizard.jersey.DropwizardResourceConfig;
import io.dropwizard.setup.Bootstrap;
import io.dropwizard.setup.Environment;
import org.glassfish.hk2.api.ServiceLocator;
import org.glassfish.jersey.ServiceLocatorProvider;
import org.glassfish.jersey.server.monitoring.ApplicationEvent;
import org.glassfish.jersey.server.monitoring.ApplicationEventListener;
import org.glassfish.jersey.server.monitoring.RequestEvent;
import org.glassfish.jersey.server.monitoring.RequestEventListener;
import org.jvnet.hk2.guice.bridge.api.GuiceBridge;
import org.jvnet.hk2.guice.bridge.api.GuiceIntoHK2Bridge;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.DispatcherType;
import javax.servlet.Filter;
import javax.servlet.FilterRegistration;
import javax.servlet.ServletRegistration;
import javax.servlet.http.HttpServlet;
import javax.validation.Validator;
import javax.ws.rs.Path;
import javax.ws.rs.client.ClientRequestFilter;
import javax.ws.rs.client.ClientResponseFilter;
import javax.ws.rs.container.ContainerRequestFilter;
import javax.ws.rs.container.ContainerResponseFilter;
import javax.ws.rs.container.DynamicFeature;
import javax.ws.rs.core.Feature;
import javax.ws.rs.core.FeatureContext;
import javax.ws.rs.ext.ReaderInterceptor;
import javax.ws.rs.ext.WriterInterceptor;
import java.lang.reflect.Type;
import java.util.Collection;
import java.util.EnumSet;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * Bundle for adding Guice support to Jersey 2.0 Resources
 */
public class GuiceBundle<T extends Configuration> implements ConfiguredBundle<T>
{
    // guarded by sync
    private Injector injector = null;
    private final Logger log = LoggerFactory.getLogger(getClass());
    private final InjectorProvider<T> injectorProvider;
    private final DropwizardResourceConfig loggingConfig = new DropwizardResourceConfig()
    {
        @Override
        public String getEndpointsInfo()
        {
            return "GuiceBundle - " + super.getEndpointsInfo();
        }
    };

    @SuppressWarnings("unchecked")
    private static final Collection<Class<?>> componentClasses = ImmutableSet.of
        (
            ContainerRequestFilter.class,
            ContainerResponseFilter.class,
            ClientResponseFilter.class,
            ClientRequestFilter.class,
            DynamicFeature.class,
            ReaderInterceptor.class,
            WriterInterceptor.class
        );

    /**
     * @param injectorProvider a provider for the Guice injector to use
     */
    public GuiceBundle(InjectorProvider<T> injectorProvider)
    {
        this.injectorProvider = injectorProvider;
    }

    @Override
    public void initialize(Bootstrap<?> bootstrap)
    {
        final InjectableValues injectableValues = new InjectableValues()
        {
            @Override
            public Object findInjectableValue(Object valueId, DeserializationContext ctxt, BeanProperty forProperty, Object beanInstance)
            {
                return null;
            }
        };
        final ConfigurationFactoryFactory<? extends Configuration> configurationFactoryFactory = bootstrap.getConfigurationFactoryFactory();
        ConfigurationFactoryFactory factoryFactory = new ConfigurationFactoryFactory()
        {
            @Override
            public ConfigurationFactory create(Class klass, Validator validator, ObjectMapper objectMapper, String propertyPrefix)
            {
                objectMapper.setInjectableValues(injectableValues);
                //noinspection unchecked
                return configurationFactoryFactory.create(klass, validator, objectMapper, propertyPrefix);
            }
        };
        //noinspection unchecked
        bootstrap.setConfigurationFactoryFactory(factoryFactory);
    }

    @Override
    public void run(final T configuration, final Environment environment) throws Exception
    {
        Feature feature = new GuiceBundleFeature()
        {
            private final AtomicBoolean firstTime = new AtomicBoolean(true);

            @Override
            public boolean configure(FeatureContext context)
            {
                internalApply(context);
                return true;
            }

            private void internalApply(FeatureContext context)
            {
                ServiceLocator serviceLocator = ServiceLocatorProvider.getServiceLocator(context);
                GuiceBridge.getGuiceBridge().initializeGuiceBridge(serviceLocator);
                GuiceIntoHK2Bridge guiceBridge = serviceLocator.getService(GuiceIntoHK2Bridge.class);
                AbstractModule additionalModule = new AbstractModule()
                {
                    @Override
                    protected void configure()
                    {
                        try
                        {
                            // make sure there are no compile-time references to Soa by using reflection
                            Class.forName("io.soabase.core.SoaFeatures");
                            log.info("Installing SoaIntegrationModule");
                            Module soaIntegrationModule = (Module)Class.forName("io.soabase.guice.SoaIntegrationModule").getConstructor(Environment.class).newInstance(environment);
                            install(soaIntegrationModule);
                        }
                        catch ( ClassNotFoundException ignore )
                        {
                            // Soa has not been included - ignore
                            log.info("SoaFeatures not available");
                        }
                        catch ( Exception e )
                        {
                            log.error("Could not instantiate SoaIntegrationModule", e);
                        }
                    }
                };
                Injector localInjector = getInjector(configuration, environment, additionalModule);
                guiceBridge.bridgeGuiceInjector(localInjector);
                if ( firstTime.compareAndSet(true, false) )
                {
                    registerBoundJerseyComponents(localInjector, context, environment);
                }
            }
        };
        environment.jersey().register(feature);

        ApplicationEventListener listener = new ApplicationEventListener()
        {
            @Override
            public void onEvent(ApplicationEvent event)
            {
                if ( event.getType() == ApplicationEvent.Type.INITIALIZATION_APP_FINISHED )
                {
                    loggingConfig.logComponents();
                }
            }

            @Override
            public RequestEventListener onRequest(RequestEvent requestEvent)
            {
                return null;
            }
        };
        environment.jersey().register(listener);
    }

    private void registerBoundJerseyComponents(Injector injector, FeatureContext context, Environment environment)
    {
        // mostly copied from GuiceComponentProviderFactory#register(ResourceConfig, Injector)
        while ( injector != null )
        {
            for ( Key<?> key : injector.getBindings().keySet() )
            {
                Type type = key.getTypeLiteral().getType();
                if ( type instanceof Class )
                {
                    Class<?> c = (Class)type;
                    if ( isProviderClass(c) )
                    {
                        log.info(String.format("Registering %s as a provider class", c.getName()));
                        context.register(c);
                        loggingConfig.register(c);
                    }
                    else if ( isRootResourceClass(c) )
                    {
                        log.info(String.format("Registering %s as a root resource class", c.getName()));
                        context.register(c);
                        loggingConfig.register(c);
                    }
                    else if ( componentClasses.contains(c) )
                    {
                        log.info(String.format("Registering %s", c.getName()));
                        context.register(c);
                        loggingConfig.register(c);
                    }
                    else if ( FilterDefinition.class.equals(c) )
                    {
                        registerFilter(injector, environment, injector.getBinding(key));
                        loggingConfig.register(c);
                    }
                    else if ( ServletDefinition.class.equals(c) )
                    {
                        registerServlet(injector, environment, injector.getBinding(key));
                        loggingConfig.register(c);
                    }
                    else if ( InternalFilter.class.equals(c) )
                    {
                        log.debug("Registering internal filter");
                        context.register(injector.getBinding(key).getProvider().get());
                        loggingConfig.register(c);
                    }
                    else if ( InternalCommonConfig.class.equals(c) )
                    {
                        applyInternalCommonConfig(context, (InternalCommonConfig)injector.getBinding(key).getProvider().get());
                        loggingConfig.register(c);
                    }
                }
            }
            injector = injector.getParent();
        }
    }

    private synchronized Injector getInjector(T configuration, Environment environment, Module module)
    {
        if ( injector == null )
        {
            injector = injectorProvider.get(configuration, environment, module);
        }
        return injector;
    }

    private void applyInternalCommonConfig(FeatureContext context, InternalCommonConfig internalCommonConfig)
    {
        for ( Class<?> clazz : internalCommonConfig.getClasses() )
        {
            log.info(String.format("Registering %s as a component", clazz));
            context.register(clazz);
        }
        for ( Object obj : internalCommonConfig.getInstances() )
        {
            log.info(String.format("Registering instance of %s as a component", obj.getClass()));
            context.register(obj);
        }
        for ( Map.Entry<String, Object> entry : internalCommonConfig.getProperties().entrySet() )
        {
            String key = entry.getKey();
            Object value = entry.getValue();
            log.info(String.format("Registering property key: %s\tvalue: %s", key, value));
            context.property(key, value);
        }
    }

    private void registerServlet(Injector injector, Environment environment, Binding<?> binding)
    {
        ServletDefinition servletDefinition = (ServletDefinition)binding.getProvider().get();
        log.info("Registering servlet: " + servletDefinition);
        HttpServlet servletInstance = servletDefinition.getServletInstance();
        if ( servletInstance == null )
        {
            servletInstance = injector.getInstance(servletDefinition.getServletKey());
        }
        ServletRegistration.Dynamic registration = environment.servlets().addServlet(servletDefinition.getServletKey().toString(), servletInstance);
        registration.setInitParameters(servletDefinition.getInitParams());
        registration.addMapping(servletDefinition.getPatterns());
    }

    private void registerFilter(Injector injector, Environment environment, Binding<?> binding)
    {
        FilterDefinition filterDefinition = (FilterDefinition)binding.getProvider().get();
        log.info("Registering filter: " + filterDefinition);
        Filter filterInstance = filterDefinition.getFilterInstance();
        if ( filterInstance == null )
        {
            filterInstance = injector.getInstance(filterDefinition.getFilterKey());
        }
        FilterRegistration.Dynamic registration = environment.servlets().addFilter(filterDefinition.getFilterKey().toString(), filterInstance);
        registration.setInitParameters(filterDefinition.getInitParams());
        registration.addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.class), true, filterDefinition.getUriPatterns());
    }

    // copied from Jersey 1.17.1
    private static boolean isProviderClass(Class<?> c)
    {
        return (c != null) && c.isAnnotationPresent(javax.ws.rs.ext.Provider.class);
    }

    // copied from Jersey 1.17.1
    private static boolean isRootResourceClass(Class<?> c)
    {
        if ( c == null )
        {
            return false;
        }
        else if ( c.isAnnotationPresent(Path.class) )
        {
            return true;
        }
        else
        {
            Class[] arr = c.getInterfaces();
            int len = arr.length;

            //noinspection ForLoopReplaceableByForEach
            for ( int i = 0; i < len; ++i )
            {
                Class clazz = arr[i];
                if ( clazz.isAnnotationPresent(Path.class) )
                {
                    return true;
                }
            }

            return false;
        }
    }
}


text:
//
// UniqueIdMap.cs
//
// Author: Jeffrey Stedfast <jeff@xamarin.com>
//
// Copyright (c) 2013-2016 Xamarin Inc. (www.xamarin.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//

using System;
using System.Collections;
using System.Collections.Generic;

namespace MailKit {
	/// <summary>
	/// A mapping of unique identifiers.
	/// </summary>
	/// <remarks>
	/// <para>A <see cref="UniqueIdMap"/> can be used to discover the mapping of one set of unique identifiers
	/// to another.</para>
	/// <para>For example, when copying or moving messages from one folder to another, it is often desirable
	/// to know what the unique identifiers are for each of the messages in the destination folder.</para>
	/// </remarks>
	public class UniqueIdMap
#if !NET_4_0
		: IReadOnlyDictionary<UniqueId, UniqueId>
#else
		: IEnumerable<KeyValuePair<UniqueId, UniqueId>>
#endif
	{
		/// <summary>
		/// Any empty mapping of unique identifiers.
		/// </summary>
		/// <remarks>
		/// Any empty mapping of unique identifiers.
		/// </remarks>
		public static readonly UniqueIdMap Empty = new UniqueIdMap ();

		/// <summary>
		/// Initializes a new instance of the <see cref="MailKit.UniqueIdMap"/> class.
		/// </summary>
		/// <remarks>
		/// Creates a new <see cref="MailKit.UniqueIdMap"/>.
		/// </remarks>
		/// <param name="source">The unique identifiers used in the source folder.</param>
		/// <param name="destination">The unique identifiers used in the destination folder.</param>
		/// <exception cref="System.ArgumentNullException">
		/// <para><paramref name="source"/> is <c>null</c>.</para>
		/// <para>-or-</para>
		/// <para><paramref name="destination"/> is <c>null</c>.</para>
		/// </exception>
		public UniqueIdMap (IList<UniqueId> source, IList<UniqueId> destination)
		{
			if (source == null)
				throw new ArgumentNullException ("source");

			if (destination == null)
				throw new ArgumentNullException ("destination");

			Destination = destination;
			Source = source;
		}

		UniqueIdMap ()
		{
			Destination = Source = new UniqueId[0];
		}

		/// <summary>
		/// Gets the list of unique identifiers used in the source folder.
		/// </summary>
		/// <remarks>
		/// Gets the list of unique identifiers used in the source folder.
		/// </remarks>
		/// <value>The unique identifiers used in the source folder.</value>
		public IList<UniqueId> Source {
			get; private set;
		}

		/// <summary>
		/// Gets the list of unique identifiers used in the destination folder.
		/// </summary>
		/// <remarks>
		/// Gets the list of unique identifiers used in the destination folder.
		/// </remarks>
		/// <value>The unique identifiers used in the destination folder.</value>
		public IList<UniqueId> Destination {
			get; private set;
		}

		/// <summary>
		/// Gets the number of unique identifiers that have been remapped.
		/// </summary>
		/// <remarks>
		/// Gets the number of unique identifiers that have been remapped.
		/// </remarks>
		/// <value>The count.</value>
		public int Count {
			get { return Source.Count; }
		}

		/// <summary>
		/// Gets the keys.
		/// </summary>
		/// <remarks>
		/// Gets the keys.
		/// </remarks>
		/// <value>The keys.</value>
		public IEnumerable<UniqueId> Keys {
			get { return Source; }
		}

		/// <summary>
		/// Gets the values.
		/// </summary>
		/// <remarks>
		/// Gets the values.
		/// </remarks>
		/// <value>The values.</value>
		public IEnumerable<UniqueId> Values {
			get { return Destination; }
		}

		/// <summary>
		/// Checks if the specified unique identifier has been remapped.
		/// </summary>
		/// <remarks>
		/// Checks if the specified unique identifier has been remapped.
		/// </remarks>
		/// <returns><c>true</c> if the unique identifier has been remapped; otherwise, <c>false</c>.</returns>
		/// <param name="key">The unique identifier.</param>
		public bool ContainsKey (UniqueId key)
		{
			return Source.Contains (key);
		}

		/// <summary>
		/// Tries to get the remapped unique identifier.
		/// </summary>
		/// <remarks>
		/// Attempts to get the remapped unique identifier.
		/// </remarks>
		/// <returns><c>true</c> on success; otherwise, <c>false</c>.</returns>
		/// <param name="key">The unique identifier of the message in the source folder.</param>
		/// <param name="value">The unique identifier of the message in the destination folder.</param>
		public bool TryGetValue (UniqueId key, out UniqueId value)
		{
			int index = Source.IndexOf (key);

			if (index == -1 || index >= Destination.Count) {
				value = UniqueId.Invalid;
				return false;
			}

			value = Destination[index];

			return true;
		}

		/// <summary>
		/// Gets the remapped unique identifier.
		/// </summary>
		/// <remarks>
		/// Gets the remapped unique identifier.
		/// </remarks>
		/// <param name="index">The unique identifier of the message in the source folder.</param>
		/// <exception cref="System.ArgumentOutOfRangeException">
		/// <paramref name="index"/> is out of range.
		/// </exception>
		public UniqueId this [UniqueId index] {
			get {
				UniqueId uid;

				if (!TryGetValue (index, out uid))
					throw new ArgumentOutOfRangeException ("index");

				return uid;
			}
		}

		/// <summary>
		/// Gets the enumerator for the remapped unique identifiers.
		/// </summary>
		/// <remarks>
		/// Gets the enumerator for the remapped unique identifiers.
		/// </remarks>
		/// <returns>The enumerator.</returns>
		public IEnumerator<KeyValuePair<UniqueId, UniqueId>> GetEnumerator ()
		{
			var dst = Destination.GetEnumerator ();
			var src = Source.GetEnumerator ();

			while (src.MoveNext () && dst.MoveNext ())
				yield return new KeyValuePair<UniqueId, UniqueId> (src.Current, dst.Current);

			yield break;
		}

		/// <summary>
		/// Gets the enumerator for the remapped unique identifiers.
		/// </summary>
		/// <remarks>
		/// Gets the enumerator for the remapped unique identifiers.
		/// </remarks>
		/// <returns>The enumerator.</returns>
		IEnumerator IEnumerable.GetEnumerator ()
		{
			return GetEnumerator ();
		}
	}
}