text:
A simple API wrapper service for NG 1.x, providing a more consistent interface,
intelligent cache clearance for complex GET requests and other edge-case features.

##### Reasoning:
Having developed _n^many_ Angular-based sites, services and components,
I got tired of having to deal with a few subtle boilerplate issues interacting
with REST API's in most common scenarios...

1. GET request cache clearance is a pain when complex querystrings are involved

2. Say you want to append data to your request, if you GET you need to add _params_ but if you POST/PUT
you need to add _data_

3. Content transfer encoding often needs to be set to UTF-8 for a variety of reasons, project-depending

4. Standard DELETE requests do not allow body parameters in almost all cases

5. I also wanted to be able to configure the location of the API from _outside_ the NG app, before it bootstrapped,
so it's trivial to move an API to a different location and be able to update the client-side app
for **anybody** - even a very front-end junior developer

This wrapper attempts to go some way to resolving these issues as much as is possible from the client-side.

##### Caveats:
Some cases - such as appending and allowing body parameters in DELETE requests are as much as server-side issues
as client-side ones, so the wrapper does as much as it can to facilitate this where possible.

##### To get started:
- Open your terminal and run `npm install`
- When complete, run `npm start`
- Once the test server is up and running, open your browser and point it to: _[http://localhost:3000](http://localhost:3000 "localhost")_
- You should be presented with a cutting-edge (lolz) interface which gives you the opportunity to view and delete
as many company employees as your inner-evil-CEO wishes.

##### Notes:
- The server / API is generated using a simple json-server generator script, Faker and Lodash
- In the 'sample' folder, only the api-wrapper javascript file is compressed (a result of the bundle process),
everything else is left un-bundled for ease of reading
- The client-side app uses UI Router for state management, to simplify view controllers
and to bring some consistency to app structure

##### TODO:
- Write specs
- Make the wrapper injectable and configurable _per-service_ so we can wrap
multiple APIs easily in a single NG app
- Modularize the Sample app properly
- Convert client-side sample and wrapper to ES6
- Remove Gulp, move to Webpack build
- Another approach that I might use in future is to write in the default request amendment behaviours as
interceptors for a more 'transparent' solution


text:
class HomeController < ApplicationController
  def index
  end

  def acerca_de
  end

  # POST home/login
  # Realiza procedimiento de validacion de usuario y crea la variable de sesion en caso de autentificarse correctamente
  def login
  	user = User.find_by_username(params[:username])
  	if user
  		if user.password == params[:password]
  			session[:user] = user.username
  			session[:id] = user.id
        session[:full_name] = user.person.full_name
        session[:initials] = user.person.initials
        session[:academic_degree] = user.person.academic_degree
  		end
  	end
  	redirect_to home_index_path
  end

  # GET home/logout
  # Limpia variable de sesion
  def logout
    # Se limpia la variable de sesion
    reset_session
    # Redirecciona al indes de la web
    redirect_to home_index_path
  end

  def acceso_denegado

  end

end

redpajama_set_name: RedPajamaGithub


text:
(function () {
    'use strict';

    /*
     * Attributes
     */
    var timeout = null;

    angular.module('confin.ui')
           .directive('userUnique', function ($http, URL) {
               return {
                   require: 'ngModel',
                   link: function (scope, element, attrs, ngModel) {

                       /*
                        * Catch change Value from Element
                        */
                       scope.$watch(
                           attrs.ngModel,
                           function (newValue, oldValue, scope) {
                               try {

                                   if (newValue.length == 0 && oldValue.length == 0)
                                       throw 'Argumentos vazios';

                                   if (newValue == oldValue)
                                       throw 'Argumentos iguais';

                                   if (timeout != null)
                                       clearTimeout(timeout);

                                   timeout = setTimeout(function () {

                                       /*
                                        * Send Data to Server
                                        */
                                       $http({
                                           method: 'POST',
                                           url: URL.OAUTH_CHECK_EMAIL_UNIQUE,
                                           data: {
                                               'Email': newValue
                                           }
                                       })
                                       .then(function (response, status, headers, cfg) {
                                           ngModel.$setValidity('unique', response.data.isUnique);
                                       },
                                       function (data, status, headers, cfg) {
                                           throw 'username error';
                                       });

                                   }, 500);

                               } catch (ex) {
                                   ngModel.$setValidity('unique', true);
                                   return;
                               }
                           });

                   }
               };
           });

})();


text:
<!DOCTYPE html>

	<meta charset="utf-8">

	<title>MBVariableSpace Class Reference</title>

	<link rel="stylesheet" href="../css/style.css">
	<meta name="viewport" content="initial-scale=1, maximum-scale=1.4">
	<meta name="generator" content="appledoc 2.2.1 (build 1334)">

				MBDataEnvironment

				Gilt Groupe

Index

Hierarchy

							On This Page

							<select id="jump-to">
	<option value="top">Jump To…</option>

	<option value="overview">Overview</option>

	<option value="tasks">Tasks</option>

	<optgroup label="Class Methods">

		<option value="//api/name/instance">+ instance</option>

		<option value="//api/name/name:withSuffix:">+ name:withSuffix:</option>

	</optgroup>

	<optgroup label="Instance Methods">

		<option value="//api/name/addObserverForUserDefault:target:action:">- addObserverForUserDefault:target:action:</option>

		<option value="//api/name/declarationForVariable:">- declarationForVariable:</option>

		<option value="//api/name/declareFunction:">- declareFunction:</option>

		<option value="//api/name/declareVariable:">- declareVariable:</option>

		<option value="//api/name/functionNames">- functionNames</option>

		<option value="//api/name/functionWithName:">- functionWithName:</option>

		<option value="//api/name/isReadOnlyVariable:">- isReadOnlyVariable:</option>

		<option value="//api/name/objectForKeyedSubscript:">- objectForKeyedSubscript:</option>

		<option value="//api/name/popVariable:">- popVariable:</option>

		<option value="//api/name/pushVariable:value:">- pushVariable:value:</option>

		<option value="//api/name/removeObserver:forUserDefault:">- removeObserver:forUserDefault:</option>

		<option value="//api/name/setListVariable:listIndex:value:">- setListVariable:listIndex:value:</option>

		<option value="//api/name/setMapVariable:mapKey:value:">- setMapVariable:mapKey:value:</option>

		<option value="//api/name/setObject:forKeyedSubscript:">- setObject:forKeyedSubscript:</option>

		<option value="//api/name/unsetVariable:">- unsetVariable:</option>

		<option value="//api/name/variableAsString:">- variableAsString:</option>

		<option value="//api/name/variableAsString:defaultValue:">- variableAsString:defaultValue:</option>

		<option value="//api/name/variableIsStack:">- variableIsStack:</option>

		<option value="//api/name/variableStackDepth:">- variableStackDepth:</option>

	</optgroup>

</select>

MBVariableSpace Class Reference

	Inherits from
	MBEnvironmentLoader : NSObject

	Conforms to
	MBInstanceVendor

	Declared in
	MBVariableSpace.h

Overview

The MBVariableSpace class is responsible for loading variable declarations
from MBML files and for maintaining the current values of named Mockingbird
variables across the lifetime of the application.

Each MBEnvironment will have an associated MBVariableSpace that will be
consulted when Mockingbird expressions are evaluated. When a given environment
is active, its MBVariableSpace will provide the values when variables are
referenced.

Getting the current variable space

+ instance

Retrieves the MBVariableSpace instance associated with the currently-active
MBEnvironment.

+ (nullable instancetype)instance

Return Value

The current variable space.

Declared In

MBVariableSpace.h

Accessing variable values

– objectForKeyedSubscript:

Returns the current value for the variable with the given name using
the keyed subscripting notation.

- (nullable id)objectForKeyedSubscript:(nonnull NSString *)variableName

Parameters

						variableName

The name of the MBML variable whose value is to be
            retrieved.

Return Value

The current variable value. Will return nil if there is no
            variable with the given name or if there was an error retrieving
            the variable’s value.

Discussion

For example, the following Objective-C code:

NSString* addr = [MBVariableSpace instance][@"email"];

would set the value of the Objective-C string addr to the value of the MBML
variable named email.

Declared In

MBVariableSpace.h

– variableAsString:

Returns the current string value of the variable with the given name.

- (nullable NSString *)variableAsString:(nonnull NSString *)varName

Parameters

						varName

The name of the variable whose string value is being
            retrieved.

Return Value

The current string value of the variable. Will return nil if
            there is no variable with the given name or if there was an error
            retrieving the variable’s value.

Discussion

If the underlying variable value is not an NSString, the value’s
description method will be called to convert the value into a string.

Declared In

MBVariableSpace.h

– variableAsString:defaultValue:

Returns the current string value for the variable with the given name, or a
default value if there is no available variable value.

- (nullable NSString *)variableAsString:(nonnull NSString *)varName defaultValue:(nullable NSString *)def

Parameters

						varName

The name of the variable whose string value is being
            retrieved.

						def

A default value to return in cases where the method would
            otherwise return nil.

Return Value

The current string value of the variable. Will return def if
            there is no variable with the given name or if there was an error
            retrieving the variable’s value.

Discussion

If the underlying variable value is not an NSString, the value’s
description method will be called to convert the value into a string.

Declared In

MBVariableSpace.h

Modifying variable values

– setObject:forKeyedSubscript:

Sets a variable to the given value using the keyed subscripting notation.

- (void)setObject:(nullable id)value forKeyedSubscript:(nonnull NSString *)variableName

Parameters

						value

The value to set for the variable named variableName.

						variableName

The name of the variable whose value is to be set.
            If the name represents a read-only variable, the call will be
            ignored and an error will be logged to the console.

Discussion

For example, the following Objective-C code:

[MBVariableSpace instance][@"title"] = @"MBML";

would set the MBML variable named title to the string “MBML”.

Warning: An NSInvalidArgumentException is raised if variableName
            is nil or is not an NSString.

Declared In

MBVariableSpace.h

– pushVariable:value:

Pushes a new value onto the stack for the variable with the given name.

- (void)pushVariable:(nonnull NSString *)variableName value:(nullable id)value

Parameters

						variableName

The name of the variable whose value is to be set.
            If the name represents a read-only variable, the call will be
            ignored and an error will be logged to the console.

						value

The value to set for the variable named variableName.

Declared In

MBVariableSpace.h

– popVariable:

Pops the current value from the stack for the variable with the given name.
(The value of the variable prior to the previous call to pushVariable:value:
will be restored.)

- (nullable id)popVariable:(nonnull NSString *)varName

Parameters

						varName

The name of the variable whose value is to be set.
            If the name represents a read-only variable, the call will be
            ignored and an error will be logged to the console.

Return Value

The value of the variable varName that was popped from the stack.
            If there were no stack values for the variable, nil will be
            returned.

Discussion

If there are no stack values for the variable, an error will be logged to
the console.

Declared In

MBVariableSpace.h

– variableIsStack:

Determines if the variable with the given name is a stack variable.

- (BOOL)variableIsStack:(nonnull NSString *)varName

Parameters

						varName

The name of the variable.

Return Value

YES if varName represents a stack variable; NO otherwise.

Discussion

A stack variable is one for which you can successfully issue a popVariable:
request. Such a variable has had its value populated by pushVariable:value:
at least one more time than a corresponding popVariable: has been issued.

Declared In

MBVariableSpace.h

– variableStackDepth:

Returns the stack depth of the given variable.

- (NSUInteger)variableStackDepth:(nonnull NSString *)varName

Parameters

						varName

The name of the variable whose stack depth is sought.

Return Value

The stack depth of the variable varName. A depth of 0 (zero)
            indicates that the variable is not a stack variable (i.e.,
            variableIsStack: would return NO and popVariable: would
            fail).

Discussion

The stack depth indicates the number of distinct values that are “hidden below”
the variable’s current value. The stack depth therefore also represents the
number of times popVariable: can be successfully called for the variable.

Declared In

MBVariableSpace.h

– setMapVariable:mapKey:value:

Sets the value of a given key for the type="map" variable with the specified
name. (This method will also operate on any variable whose value is of type
NSDictionary.)

- (void)setMapVariable:(nonnull NSString *)varName mapKey:(nonnull NSString *)key value:(nullable id)val

Parameters

						varName

The name of the map variable whose key-value is being set.
            If the name represents a read-only variable, the call will be
            ignored and an error will be logged to the console.

						key

The map key whose value is being set.

						val

The new value for the given key. If nil, the value for key
            will be removed.

Declared In

MBVariableSpace.h

– setListVariable:listIndex:value:

Sets the value of a given key for the type="list" variable with the specified
name. (This method will also operate on any variable whose value is of type
NSArray.)

- (void)setListVariable:(nonnull NSString *)varName listIndex:(NSUInteger)idx value:(nullable id)val

Parameters

						varName

The name of the list variable whose index-value is being
            set. If the name represents a read-only variable, the call will be
            ignored and an error will be logged to the console.

						idx

The list index whose value is being set. If idx is
            greater than the last index of the list, the list array will be
            expanded to include the new index, and any empty index slots
            will be filled with NSNull.

						val

The new value to set at the given index. If nil, the value
            will be set as NSNull.

Declared In

MBVariableSpace.h

– unsetVariable:

Removes the current value of the variable with the specified name. Values on
the variable stack will not be affected.

- (void)unsetVariable:(nonnull NSString *)varName

Parameters

						varName

The name of the variable whose value is to be unset.
            If the name represents a read-only variable, the call will be
            ignored and an error will be logged to the console.

Declared In

MBVariableSpace.h

Constructing variable-related names

+ name:withSuffix:

Constructs a string for a variable-related name with the given suffix.

+ (nullable NSString *)name:(nullable NSString *)name withSuffix:(nullable NSString *)suffix

Parameters

						name

The name to use for the root of the returned string. If
            nil, this method returns nil.

						suffix

The optional suffix to apply to name. If nil, this
            method returns name.

Return Value

If name and suffix are both non-nil, the concatenation of
            name, “:” and suffix is returned. Otherwise, the value of the
            name parameter is returned.

Discussion

Calling this method with the name “Foo” and the suffix “willBar” would
return the string “Foo:willBar”.

Declared In

MBVariableSpace.h

Accessing variable information

– isReadOnlyVariable:

Determines whether the variable with the given name is a read-only variable.

- (BOOL)isReadOnlyVariable:(nonnull NSString *)varName

Parameters

						varName

The name of the variable.

Return Value

YES if the variable named varName is read-only; NO otherwise.

Discussion

Read-only variables are marked as such in MBML or when they are declared
programmatically via declareVariable:.

Certain types of variable declarations—such as those represented by
MBSingletonVariableDeclaration and MBDynamicVariableDeclaration—are always
read-only.

MBConcreteVariableDeclarations declared in MBML with a mutable="F"
attribute are read-only.

Otherwise, variables are not considered read-only.

Note that the read-only concept only applies to whether or not the
MBVariableSpace will allow you to change the value through its interface.

In this way, even immutable objects such as NSArray may be considered
read/write as far as the Mockingbird Data Environment goes.

Conversely, a NSMutableDictionary, for example, may be declared as a
read-only Mockingbird variable, but the dictionary can still be mutated
directly.

Declared In

MBVariableSpace.h

Accessing variable declarations

– declareVariable:

Programmatically declares a variable.

- (BOOL)declareVariable:(nonnull MBVariableDeclaration *)declaration

Parameters

						declaration

An MBVariableDeclaration representing the variable.
            Note that this method ignores the shouldDeclare property of the
            variable declaration.

Return Value

YES if the variable represented by declaration was successfully
            declared; NO if an error occured.

Declared In

MBVariableSpace.h

– declarationForVariable:

Returns the MBVariableDeclaration for the variable with the given name.

- (nullable MBVariableDeclaration *)declarationForVariable:(nonnull NSString *)varName

Parameters

						varName

The name of the variable whose declaration is being
            retrieved.

Return Value

The declaration for varName, or nil if no declaration exists.

Discussion

Note that not all variables will have explicit declarations; only variables
declared in MBML or created programmatically using declareVariable: will
have an associated MBVariableDeclaration. Undeclared variables can be
created implicitly by being set directly using keyed subscripting and
other methods.

Declared In

MBVariableSpace.h

Accessing MBML functions

– declareFunction:

Programmatically declares an MBML function.

- (BOOL)declareFunction:(nonnull MBMLFunction *)function

Parameters

						function

An MBMLFunction representing the function and its
            implementation.

Return Value

YES if function was successfully declared; NO if an error
            occurred.

Declared In

MBVariableSpace.h

– functionNames

Returns the names of the currently-declared MBML functions.

- (nonnull NSArray *)functionNames

Return Value

An NSArray containing the names of the declared MBML functions.

Declared In

MBVariableSpace.h

– functionWithName:

Returns the MBMLFunction associated with the given name.

- (nullable MBMLFunction *)functionWithName:(nonnull NSString *)name

Parameters

						name

The name of the function whose MBMLFunction is sought.

Return Value

The MBMLFunction, or nil if there is no function declared having
            the given name.

Declared In

MBVariableSpace.h

						<a title="Observing changes to variables bound to `NSUserDefaults`" name="task_Observing changes to variables bound to `NSUserDefaults`">

Observing changes to variables bound to `NSUserDefaults`

– addObserverForUserDefault:target:action:

Adds an observer to be notified of changes to the value of the Mockingbird
variable with the given NSUserDefaults key name.

- (void)addObserverForUserDefault:(nonnull NSString *)userDefaultsName target:(nonnull id)observer action:(nonnull SEL)action

Parameters

						userDefaultsName

The userDefaultsName of the variable to observe.
            Note that this is not necessarily the same as the variable name.

						observer

The object to notify.

						action

The method selector of observer to call when notifying.

Declared In

MBVariableSpace.h

– removeObserver:forUserDefault:

Stops an observer from being notified of changes to the value of the
Mockingbird variable with the given NSUserDefaults key name.

- (void)removeObserver:(nonnull id)observer forUserDefault:(nonnull NSString *)userDefaultsName

Parameters

						observer

The observer to remove.

						userDefaultsName

The userDefaultsName of the variable to stop
            observing.

Declared In

MBVariableSpace.h

Copyright © 2017 Gilt Groupe. All rights reserved. Updated: 2017-04-20

Generated by appledoc 2.2.1 (build 1334).


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

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.amazonaws.AmazonClientException;
import com.amazonaws.Request;
import com.amazonaws.DefaultRequest;
import com.amazonaws.services.ec2.model.*;
import com.amazonaws.transform.Marshaller;
import com.amazonaws.util.StringUtils;

/**
 * Describe Availability Zones Request Marshaller
 */
public class DescribeAvailabilityZonesRequestMarshaller implements Marshaller<Request<DescribeAvailabilityZonesRequest>, DescribeAvailabilityZonesRequest> {

    public Request<DescribeAvailabilityZonesRequest> marshall(DescribeAvailabilityZonesRequest describeAvailabilityZonesRequest) {

        if (describeAvailabilityZonesRequest == null) {
		    throw new AmazonClientException("Invalid argument passed to marshall(...)");
		}

        Request<DescribeAvailabilityZonesRequest> request = new DefaultRequest<DescribeAvailabilityZonesRequest>(describeAvailabilityZonesRequest, "AmazonEC2");
        request.addParameter("Action", "DescribeAvailabilityZones");
        request.addParameter("Version", "2012-08-15");

        java.util.List<String> zoneNamesList = describeAvailabilityZonesRequest.getZoneNames();
        int zoneNamesListIndex = 1;

        for (String zoneNamesListValue : zoneNamesList) {
            if (zoneNamesListValue != null) {
                request.addParameter("ZoneName." + zoneNamesListIndex, StringUtils.fromString(zoneNamesListValue));
            }

            zoneNamesListIndex++;
        }

        java.util.List<Filter> filtersList = describeAvailabilityZonesRequest.getFilters();
        int filtersListIndex = 1;

        for (Filter filtersListValue : filtersList) {
            Filter filterMember = filtersListValue;
            if (filterMember != null) {
                if (filterMember.getName() != null) {
                    request.addParameter("Filter." + filtersListIndex + ".Name", StringUtils.fromString(filterMember.getName()));
                }

                java.util.List<String> valuesList = filterMember.getValues();
                int valuesListIndex = 1;

                for (String valuesListValue : valuesList) {
                    if (valuesListValue != null) {
                        request.addParameter("Filter." + filtersListIndex + ".Value." + valuesListIndex, StringUtils.fromString(valuesListValue));
                    }

                    valuesListIndex++;
                }
            }

            filtersListIndex++;
        }

        return request;
    }
}


text:
var LIBRARYNAME = require("LIBRARYNAME").default;
var when = require("when");
var counter = 0;

var promise = when.promise(function(resolve, reject, notify) {
	var stimulation = stimulate({
		duration:200,
		frame: function(){
			counter++;
			console.log(counter);
			if(counter > 5){
				stimulation.stop();
				resolve();
			}
		}
	});
});
await promise;


text:
<?php

/**
 * Export edit form block
 *
 * @category    Mage
 * @package     Mage_ImportExport
 * @author      Magento Core Team <core@magentocommerce.com>
 */
class Mage_ImportExport_Block_Adminhtml_Export_Edit_Form extends Mage_Adminhtml_Block_Widget_Form
{
    /**
     * Prepare form before rendering HTML.
     *
     * @return Mage_ImportExport_Block_Adminhtml_Export_Edit_Form
     */
    protected function _prepareForm()
    {
        $form = new Varien_Data_Form(array(
            'id'     => 'edit_form',
            'action' => $this->getUrl('*/*/getFilter'),
            'method' => 'post'
        ));
        $fieldset = $form->addFieldset('base_fieldset', array('legend' => Mage::helper('importexport')->__('Export Settings')));
        $fieldset->addField('entity', 'select', array(
            'name'     => 'entity',
            'title'    => Mage::helper('importexport')->__('Entity Type'),
            'label'    => Mage::helper('importexport')->__('Entity Type'),
            'required' => false,
            'onchange' => 'editForm.getFilter();',
            'values'   => Mage::getModel('importexport/source_export_entity')->toOptionArray()
        ));
        $fieldset->addField('file_format', 'select', array(
            'name'     => 'file_format',
            'title'    => Mage::helper('importexport')->__('Export File Format'),
            'label'    => Mage::helper('importexport')->__('Export File Format'),
            'required' => false,
            'values'   => Mage::getModel('importexport/source_export_format')->toOptionArray()
        ));

        $form->setUseContainer(true);
        $this->setForm($form);

        return parent::_prepareForm();
    }
}


text:
from tweet import Tweet
from quote import Quote


text:
package org.jclouds.openstack.swift.functions;

import static com.google.common.base.Preconditions.checkArgument;
import static org.jclouds.http.HttpUtils.attemptToParseSizeAndRangeFromHeaders;

import javax.inject.Inject;

import org.jclouds.blobstore.domain.BlobMetadata;
import org.jclouds.blobstore.functions.ParseSystemAndUserMetadataFromHeaders;
import org.jclouds.http.HttpRequest;
import org.jclouds.http.HttpResponse;
import org.jclouds.openstack.swift.blobstore.functions.ResourceToObjectInfo;
import org.jclouds.openstack.swift.domain.MutableObjectInfoWithMetadata;
import org.jclouds.openstack.swift.utils.ETagUtils;
import org.jclouds.rest.InvocationContext;
import org.jclouds.rest.internal.GeneratedHttpRequest;

import com.google.common.base.Function;
import com.google.common.net.HttpHeaders;

/**
 * This parses @{link {@link MutableObjectInfoWithMetadata} from HTTP headers.
 */
public class ParseObjectInfoFromHeaders implements Function<HttpResponse, MutableObjectInfoWithMetadata>,
         InvocationContext<ParseObjectInfoFromHeaders> {
   private final ParseSystemAndUserMetadataFromHeaders blobMetadataParser;
   private final ResourceToObjectInfo blobToObjectInfo;
   private String container;

   @Inject
   public ParseObjectInfoFromHeaders(ParseSystemAndUserMetadataFromHeaders blobMetadataParser,
            ResourceToObjectInfo blobToObjectInfo) {
      this.blobMetadataParser = blobMetadataParser;
      this.blobToObjectInfo = blobToObjectInfo;
   }

   /**
    * parses the http response headers to create a new {@link MutableObjectInfoWithMetadata} object.
    */
   public MutableObjectInfoWithMetadata apply(HttpResponse from) {
      BlobMetadata base = blobMetadataParser.apply(from);
      MutableObjectInfoWithMetadata to = blobToObjectInfo.apply(base);
      to.setBytes(attemptToParseSizeAndRangeFromHeaders(from));
      to.setContainer(container);
      to.setUri(base.getUri());
      String eTagHeader = from.getFirstHeaderOrNull(HttpHeaders.ETAG);
      if (eTagHeader != null) {
         to.setHash(ETagUtils.convertHexETagToByteArray(eTagHeader));
      }
      to.setObjectManifest(from.getFirstHeaderOrNull("X-Object-Manifest"));

      return to;
   }

   @Override
   public ParseObjectInfoFromHeaders setContext(HttpRequest request) {
      blobMetadataParser.setContext(request);
      checkArgument(request instanceof GeneratedHttpRequest, "note this handler requires a GeneratedHttpRequest");
      return setContainer(GeneratedHttpRequest.class.cast(request).getInvocation().getArgs().get(0).toString());
   }

   private ParseObjectInfoFromHeaders setContainer(String container) {
      this.container = container;
      return this;
   }

}


text:
{include file=$header}

{literal}

{/literal}{if $ismap}
{$mapstr}
{else}

{$content.title}

{$content.content}

 {if $previousContent}
      link}" class="prevpage">上一条:{$previousContent->title}{/if}
      {if $nextContent}link}" class="nextpage">下一条:{$nextContent->title}{/if}

返回列表

{/if}
{include file=$footer}


text:
var expect = require('chai').expect;
var lycamplus = require('./');
var _ = require('underscore');

setTimeout(function() {

    describe('Stream', function() {
        var uuid = '9039f550-d703-11e6-9734-f5ae8989dd5f';
        var streamInstance = null;
        var streamObj = null;
        before(function() {
            streamInstance = lycamplus.newStream();
        });
        after(function() {
            streamInstance = null;
            streamObj = null;
        });

        describe('Stream.create()', function() {
            it('it should return an object', function(done) {
                streamInstance.create({user: uuid, title: 'test'}, function(err, result) {
                    if (err) {
                        done(err);
                    } else {
                           console.log(result);
                        streamObj = result;
                        expect(result).to.be.an('object');
                        done();
                    }
                });
            });
        });

        describe('Stream.update()', function() {
            it('it should return an object', function(done) {
                var str = 'test live';
                streamInstance.update(streamObj.streamId, {'description': str},
                     function(err, result) {
                    if (err) {
                        done(err);
                    } else {
                        expect(result.description).to.equal(str);
                        done();
                    }
                });
            });
        });

        describe('Stream.show()', function() {
            it('it should have title property', function(done) {
                streamInstance.show(streamObj.streamId, function(err, result) {
                    if (err) {
                        done(err);
                    } else {
                        expect(result).to.have.property('title');
                        done();
                    }
                });
            });
        });

        describe('Stream.list()', function() {
            it('it should have totalItems property', function(done) {
                streamInstance.list(function(err, result) {
                    if (err) {
                        done(err);
                    } else {
                        expect(result).to.have.property('totalItems');
                        done();
                    }
                });
            });
        });

        describe('Stream.listSince()', function() {
            it('it should have totalItems property', function(done) {
                streamInstance.listSince(_.now(), function(err, result) {
                    if (err) {
                        done(err);
                    } else {
                        expect(result).to.have.property('totalItems');
                        done();
                    }
                });
            });
        });

        describe('Stream.searchByKeyword()', function() {
            it('it should have totalItems property', function(done) {
                var params = {title: 'test'};
                streamInstance.searchByKeyword(params, function(err, result) {
                    if (err) {
                        done(err);
                    } else {
                        expect(result).to.have.property('totalItems');
                        done();
                    }
                });
            });
        });

        describe('Stream.searchByLocation()', function() {
            it('it should have totalItems property', function(done) {
                var params = {lon: '0',  lat: '0'};
                streamInstance.searchByLocation(params, function(err, result) {
                    if (err) {
                        done(err);
                    } else {
                        expect(result).to.have.property('totalItems');
                        done();
                    }
                });
            });
        });

        describe('Stream.destroy()', function() {
            it('it should have success property', function(done) {
                streamInstance.destroy(streamObj.streamId, function(err, result) {
                    if (err) {
                        done(err);
                    } else {
                        expect(result).to.have.property('success');
                        done();
                    }
                });
            });
        });

    });

    run();
}, 3500);


text:
// This is an open source non-commercial project. Dear PVS-Studio, please check it.
// PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com

/* QueryHeader.cs
 */

#region Using directives

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using JetBrains.Annotations;

using MoonSharp.Interpreter;

#endregion

namespace ManagedClient
{
    /// <summary>
    /// Заголовок запроса, уходящего на сервер.
    /// </summary>
    [PublicAPI]
    [Serializable]
    [MoonSharpUserData]
    public sealed class QueryHeader
    {
        #region Properties

        /// <summary>
        /// Код команды.
        /// </summary>
        public char Command { get; set; }

        /// <summary>
        /// Код подкоманды.
        /// </summary>
        public char Subcommand { get; set; }

        /// <summary>
        /// Код АРМа.
        /// </summary>
        public char Workstation { get; set; }

        /// <summary>
        /// Идентификатор программы-клиента.
        /// </summary>
        public int ClientID { get; set; }

        /// <summary>
        /// Идентификатор запроса (последовательно возрастающее целое).
        /// </summary>
        public int QueryID { get; set; }

        /// <summary>
        /// Пароль.
        /// </summary>
        public string Password { get; set; }

        /// <summary>
        /// Логин.
        /// </summary>
        public string UserName { get; set; }

        #endregion

        #region Private members

        private string _GlueCommand ()
        {
            StringBuilder result = new StringBuilder(Command.ToInvariantString());
            if (Subcommand != 0)
            {
                result.Append(Subcommand);
            }
            return result.ToString();
        }

        #endregion

        #region Public methods

        /// <summary>
        /// Кодирование заголовка запроса в формат,
        /// пригодный для отправки на сервер.
        /// </summary>
        /// <returns></returns>
        public IEnumerable<string> Encode()
        {
            string glued = _GlueCommand();
            List<string> result = new List<string>
                                      {
                                          glued,
                                          Workstation.ToInvariantString(),
                                          glued,
                                          ClientID.ToInvariantString(),
                                          QueryID.ToInvariantString()
                                      };

            // Документация на сервер неверно описывает формат
            // клиентского пакета. На самом деле он таков (для команды А):
            // общая длина пакета
            // 'A'
            // АРМ, например 'C'
            // 'A'
            // ID клиента, например 523444
            // номер команды, для A всегда 1
            // пароль
            // имя пользователя
            // пустая строка
            // пустая строка
            // пустая строка

            if (!string.IsNullOrEmpty(Password))
            {
                result.Add(Password);
            }

            if (!string.IsNullOrEmpty(UserName))
            {
                result.Add(UserName);
            }

            while (result.Count < 10)
            {
                result.Add(string.Empty);
            }

            return result;
        }

        #endregion

        #region Object members

        /// <inheritdoc cref="object.ToString"/>
        public override string ToString()
        {
            return string.Join
                (
                    "\r\n",
                    Encode().ToArray()
                );
        }

        #endregion
    }
}


text:
#include <linux/etherdevice.h>
#include <linux/if_macvlan.h>
#include <linux/if_vlan.h>
#include <linux/interrupt.h>
#include <linux/nsproxy.h>
#include <linux/compat.h>
#include <linux/if_tun.h>
#include <linux/module.h>
#include <linux/skbuff.h>
#include <linux/cache.h>
#include <linux/sched.h>
#include <linux/types.h>
#include <linux/slab.h>
#include <linux/init.h>
#include <linux/wait.h>
#include <linux/cdev.h>
#include <linux/idr.h>
#include <linux/fs.h>

#include <net/net_namespace.h>
#include <net/rtnetlink.h>
#include <net/sock.h>
#include <linux/virtio_net.h>

/*
 * A macvtap queue is the central object of this driver, it connects
 * an open character device to a macvlan interface. There can be
 * multiple queues on one interface, which map back to queues
 * implemented in hardware on the underlying device.
 *
 * macvtap_proto is used to allocate queues through the sock allocation
 * mechanism.
 *
 * TODO: multiqueue support is currently not implemented, even though
 * macvtap is basically prepared for that. We will need to add this
 * here as well as in virtio-net and qemu to get line rate on 10gbit
 * adapters from a guest.
 */
struct macvtap_queue {
	struct sock sk;
	struct socket sock;
	struct socket_wq wq;
	int vnet_hdr_sz;
	struct macvlan_dev __rcu *vlan;
	struct file *file;
	unsigned int flags;
};

static struct proto macvtap_proto = {
	.name = "macvtap",
	.owner = THIS_MODULE,
	.obj_size = sizeof (struct macvtap_queue),
};

/*
 * Variables for dealing with macvtaps device numbers.
 */
static dev_t macvtap_major;
#define MACVTAP_NUM_DEVS (1U << MINORBITS)
static DEFINE_MUTEX(minor_lock);
static DEFINE_IDR(minor_idr);

#define GOODCOPY_LEN 128
static struct class *macvtap_class;
static struct cdev macvtap_cdev;

static const struct proto_ops macvtap_socket_ops;

/*
 * RCU usage:
 * The macvtap_queue and the macvlan_dev are loosely coupled, the
 * pointers from one to the other can only be read while rcu_read_lock
 * or macvtap_lock is held.
 *
 * Both the file and the macvlan_dev hold a reference on the macvtap_queue
 * through sock_hold(&q->sk). When the macvlan_dev goes away first,
 * q->vlan becomes inaccessible. When the files gets closed,
 * macvtap_get_queue() fails.
 *
 * There may still be references to the struct sock inside of the
 * queue from outbound SKBs, but these never reference back to the
 * file or the dev. The data structure is freed through __sk_free
 * when both our references and any pending SKBs are gone.
 */
static DEFINE_SPINLOCK(macvtap_lock);

/*
 * get_slot: return a [unused/occupied] slot in vlan->taps[]:
 *	- if 'q' is NULL, return the first empty slot;
 *	- otherwise, return the slot this pointer occupies.
 */
static int get_slot(struct macvlan_dev *vlan, struct macvtap_queue *q)
{
	int i;

	for (i = 0; i < MAX_MACVTAP_QUEUES; i++) {
		if (rcu_dereference(vlan->taps[i]) == q)
			return i;
	}

	/* Should never happen */
	BUG_ON(1);
}

static int macvtap_set_queue(struct net_device *dev, struct file *file,
				struct macvtap_queue *q)
{
	struct macvlan_dev *vlan = netdev_priv(dev);
	int index;
	int err = -EBUSY;

	spin_lock(&macvtap_lock);
	if (vlan->numvtaps == MAX_MACVTAP_QUEUES)
		goto out;

	err = 0;
	index = get_slot(vlan, NULL);
	rcu_assign_pointer(q->vlan, vlan);
	rcu_assign_pointer(vlan->taps[index], q);
	sock_hold(&q->sk);

	q->file = file;
	file->private_data = q;

	vlan->numvtaps++;

out:
	spin_unlock(&macvtap_lock);
	return err;
}

/*
 * The file owning the queue got closed, give up both
 * the reference that the files holds as well as the
 * one from the macvlan_dev if that still exists.
 *
 * Using the spinlock makes sure that we don't get
 * to the queue again after destroying it.
 */
static void macvtap_put_queue(struct macvtap_queue *q)
{
	struct macvlan_dev *vlan;

	spin_lock(&macvtap_lock);
	vlan = rcu_dereference_protected(q->vlan,
					 lockdep_is_held(&macvtap_lock));
	if (vlan) {
		int index = get_slot(vlan, q);

		RCU_INIT_POINTER(vlan->taps[index], NULL);
		RCU_INIT_POINTER(q->vlan, NULL);
		sock_put(&q->sk);
		--vlan->numvtaps;
	}

	spin_unlock(&macvtap_lock);

	synchronize_rcu();
	sock_put(&q->sk);
}

/*
 * Select a queue based on the rxq of the device on which this packet
 * arrived. If the incoming device is not mq, calculate a flow hash
 * to select a queue. If all fails, find the first available queue.
 * Cache vlan->numvtaps since it can become zero during the execution
 * of this function.
 */
static struct macvtap_queue *macvtap_get_queue(struct net_device *dev,
					       struct sk_buff *skb)
{
	struct macvlan_dev *vlan = netdev_priv(dev);
	struct macvtap_queue *tap = NULL;
	int numvtaps = vlan->numvtaps;
	__u32 rxq;

	if (!numvtaps)
		goto out;

	/* Check if we can use flow to select a queue */
	rxq = skb_get_rxhash(skb);
	if (rxq) {
		tap = rcu_dereference(vlan->taps[rxq % numvtaps]);
		if (tap)
			goto out;
	}

	if (likely(skb_rx_queue_recorded(skb))) {
		rxq = skb_get_rx_queue(skb);

		while (unlikely(rxq >= numvtaps))
			rxq -= numvtaps;

		tap = rcu_dereference(vlan->taps[rxq]);
		if (tap)
			goto out;
	}

	/* Everything failed - find first available queue */
	for (rxq = 0; rxq < MAX_MACVTAP_QUEUES; rxq++) {
		tap = rcu_dereference(vlan->taps[rxq]);
		if (tap)
			break;
	}

out:
	return tap;
}

/*
 * The net_device is going away, give up the reference
 * that it holds on all queues and safely set the pointer
 * from the queues to NULL.
 */
static void macvtap_del_queues(struct net_device *dev)
{
	struct macvlan_dev *vlan = netdev_priv(dev);
	struct macvtap_queue *q, *qlist[MAX_MACVTAP_QUEUES];
	int i, j = 0;

	/* macvtap_put_queue can free some slots, so go through all slots */
	spin_lock(&macvtap_lock);
	for (i = 0; i < MAX_MACVTAP_QUEUES && vlan->numvtaps; i++) {
		q = rcu_dereference_protected(vlan->taps[i],
					      lockdep_is_held(&macvtap_lock));
		if (q) {
			qlist[j++] = q;
			RCU_INIT_POINTER(vlan->taps[i], NULL);
			RCU_INIT_POINTER(q->vlan, NULL);
			vlan->numvtaps--;
		}
	}
	BUG_ON(vlan->numvtaps != 0);
	/* guarantee that any future macvtap_set_queue will fail */
	vlan->numvtaps = MAX_MACVTAP_QUEUES;
	spin_unlock(&macvtap_lock);

	synchronize_rcu();

	for (--j; j >= 0; j--)
		sock_put(&qlist[j]->sk);
}

/*
 * Forward happens for data that gets sent from one macvlan
 * endpoint to another one in bridge mode. We just take
 * the skb and put it into the receive queue.
 */
static int macvtap_forward(struct net_device *dev, struct sk_buff *skb)
{
	struct macvtap_queue *q = macvtap_get_queue(dev, skb);
	if (!q)
		goto drop;

	if (skb_queue_len(&q->sk.sk_receive_queue) >= dev->tx_queue_len)
		goto drop;

	skb_queue_tail(&q->sk.sk_receive_queue, skb);
	wake_up_interruptible_poll(sk_sleep(&q->sk), POLLIN | POLLRDNORM | POLLRDBAND);
	return NET_RX_SUCCESS;

drop:
	kfree_skb(skb);
	return NET_RX_DROP;
}

/*
 * Receive is for data from the external interface (lowerdev),
 * in case of macvtap, we can treat that the same way as
 * forward, which macvlan cannot.
 */
static int macvtap_receive(struct sk_buff *skb)
{
	skb_push(skb, ETH_HLEN);
	return macvtap_forward(skb->dev, skb);
}

static int macvtap_get_minor(struct macvlan_dev *vlan)
{
	int retval = -ENOMEM;
	int id;

	mutex_lock(&minor_lock);
	if (idr_pre_get(&minor_idr, GFP_KERNEL) == 0)
		goto exit;

	retval = idr_get_new_above(&minor_idr, vlan, 1, &id);
	if (retval < 0) {
		if (retval == -EAGAIN)
			retval = -ENOMEM;
		goto exit;
	}
	if (id < MACVTAP_NUM_DEVS) {
		vlan->minor = id;
	} else {
		printk(KERN_ERR "too many macvtap devices\n");
		retval = -EINVAL;
		idr_remove(&minor_idr, id);
	}
exit:
	mutex_unlock(&minor_lock);
	return retval;
}

static void macvtap_free_minor(struct macvlan_dev *vlan)
{
	mutex_lock(&minor_lock);
	if (vlan->minor) {
		idr_remove(&minor_idr, vlan->minor);
		vlan->minor = 0;
	}
	mutex_unlock(&minor_lock);
}

static struct net_device *dev_get_by_macvtap_minor(int minor)
{
	struct net_device *dev = NULL;
	struct macvlan_dev *vlan;

	mutex_lock(&minor_lock);
	vlan = idr_find(&minor_idr, minor);
	if (vlan) {
		dev = vlan->dev;
		dev_hold(dev);
	}
	mutex_unlock(&minor_lock);
	return dev;
}

static int macvtap_newlink(struct net *src_net,
			   struct net_device *dev,
			   struct nlattr *tb[],
			   struct nlattr *data[])
{
	/* Don't put anything that may fail after macvlan_common_newlink
	 * because we can't undo what it does.
	 */
	return macvlan_common_newlink(src_net, dev, tb, data,
				      macvtap_receive, macvtap_forward);
}

static void macvtap_dellink(struct net_device *dev,
			    struct list_head *head)
{
	macvtap_del_queues(dev);
	macvlan_dellink(dev, head);
}

static void macvtap_setup(struct net_device *dev)
{
	macvlan_common_setup(dev);
	dev->tx_queue_len = TUN_READQ_SIZE;
}

static struct rtnl_link_ops macvtap_link_ops __read_mostly = {
	.kind		= "macvtap",
	.setup		= macvtap_setup,
	.newlink	= macvtap_newlink,
	.dellink	= macvtap_dellink,
};

static void macvtap_sock_write_space(struct sock *sk)
{
	wait_queue_head_t *wqueue;

	if (!sock_writeable(sk) ||
	    !test_and_clear_bit(SOCK_ASYNC_NOSPACE, &sk->sk_socket->flags))
		return;

	wqueue = sk_sleep(sk);
	if (wqueue && waitqueue_active(wqueue))
		wake_up_interruptible_poll(wqueue, POLLOUT | POLLWRNORM | POLLWRBAND);
}

static void macvtap_sock_destruct(struct sock *sk)
{
	skb_queue_purge(&sk->sk_receive_queue);
}

static int macvtap_open(struct inode *inode, struct file *file)
{
	struct net *net = current->nsproxy->net_ns;
	struct net_device *dev = dev_get_by_macvtap_minor(iminor(inode));
	struct macvtap_queue *q;
	int err;

	err = -ENODEV;
	if (!dev)
		goto out;

	err = -ENOMEM;
	q = (struct macvtap_queue *)sk_alloc(net, AF_UNSPEC, GFP_KERNEL,
					     &macvtap_proto);
	if (!q)
		goto out;

	q->sock.wq = &q->wq;
	init_waitqueue_head(&q->wq.wait);
	q->sock.type = SOCK_RAW;
	q->sock.state = SS_CONNECTED;
	q->sock.file = file;
	q->sock.ops = &macvtap_socket_ops;
	sock_init_data(&q->sock, &q->sk);
	q->sk.sk_write_space = macvtap_sock_write_space;
	q->sk.sk_destruct = macvtap_sock_destruct;
	q->flags = IFF_VNET_HDR | IFF_NO_PI | IFF_TAP;
	q->vnet_hdr_sz = sizeof(struct virtio_net_hdr);

	/*
	 * so far only KVM virtio_net uses macvtap, enable zero copy between
	 * guest kernel and host kernel when lower device supports zerocopy
	 *
	 * The macvlan supports zerocopy iff the lower device supports zero
	 * copy so we don't have to look at the lower device directly.
	 */
	if ((dev->features & NETIF_F_HIGHDMA) && (dev->features & NETIF_F_SG))
		sock_set_flag(&q->sk, SOCK_ZEROCOPY);

	err = macvtap_set_queue(dev, file, q);
	if (err)
		sock_put(&q->sk);

out:
	if (dev)
		dev_put(dev);

	return err;
}

static int macvtap_release(struct inode *inode, struct file *file)
{
	struct macvtap_queue *q = file->private_data;
	macvtap_put_queue(q);
	return 0;
}

static unsigned int macvtap_poll(struct file *file, poll_table * wait)
{
	struct macvtap_queue *q = file->private_data;
	unsigned int mask = POLLERR;

	if (!q)
		goto out;

	mask = 0;
	poll_wait(file, &q->wq.wait, wait);

	if (!skb_queue_empty(&q->sk.sk_receive_queue))
		mask |= POLLIN | POLLRDNORM;

	if (sock_writeable(&q->sk) ||
	    (!test_and_set_bit(SOCK_ASYNC_NOSPACE, &q->sock.flags) &&
	     sock_writeable(&q->sk)))
		mask |= POLLOUT | POLLWRNORM;

out:
	return mask;
}

static inline struct sk_buff *macvtap_alloc_skb(struct sock *sk, size_t prepad,
						size_t len, size_t linear,
						int noblock, int *err)
{
	struct sk_buff *skb;

	/* Under a page?  Don't bother with paged skb. */
	if (prepad + len < PAGE_SIZE || !linear)
		linear = len;

	skb = sock_alloc_send_pskb(sk, prepad + linear, len - linear, noblock,
				   err);
	if (!skb)
		return NULL;

	skb_reserve(skb, prepad);
	skb_put(skb, linear);
	skb->data_len = len - linear;
	skb->len += len - linear;

	return skb;
}

/* set skb frags from iovec, this can move to core network code for reuse */
static int zerocopy_sg_from_iovec(struct sk_buff *skb, const struct iovec *from,
				  int offset, size_t count)
{
	int len = iov_length(from, count) - offset;
	int copy = skb_headlen(skb);
	int size, offset1 = 0;
	int i = 0;

	/* Skip over from offset */
	while (count && (offset >= from->iov_len)) {
		offset -= from->iov_len;
		++from;
		--count;
	}

	/* copy up to skb headlen */
	while (count && (copy > 0)) {
		size = min_t(unsigned int, copy, from->iov_len - offset);
		if (copy_from_user(skb->data + offset1, from->iov_base + offset,
				   size))
			return -EFAULT;
		if (copy > size) {
			++from;
			--count;
			offset = 0;
		} else
			offset += size;
		copy -= size;
		offset1 += size;
	}

	if (len == offset1)
		return 0;

	while (count--) {
		struct page *page[MAX_SKB_FRAGS];
		int num_pages;
		unsigned long base;
		unsigned long truesize;

		len = from->iov_len - offset;
		if (!len) {
			offset = 0;
			++from;
			continue;
		}
		base = (unsigned long)from->iov_base + offset;
		size = ((base & ~PAGE_MASK) + len + ~PAGE_MASK) >> PAGE_SHIFT;
		if (i + size > MAX_SKB_FRAGS)
			return -EMSGSIZE;
		num_pages = get_user_pages_fast(base, size, 0, &page[i]);
		if (num_pages != size) {
			for (i = 0; i < num_pages; i++)
				put_page(page[i]);
			return -EFAULT;
		}
		truesize = size * PAGE_SIZE;
		skb->data_len += len;
		skb->len += len;
		skb->truesize += truesize;
		atomic_add(truesize, &skb->sk->sk_wmem_alloc);
		while (len) {
			int off = base & ~PAGE_MASK;
			int size = min_t(int, len, PAGE_SIZE - off);
			__skb_fill_page_desc(skb, i, page[i], off, size);
			skb_shinfo(skb)->nr_frags++;
			/* increase sk_wmem_alloc */
			base += size;
			len -= size;
			i++;
		}
		offset = 0;
		++from;
	}
	return 0;
}

/*
 * macvtap_skb_from_vnet_hdr and macvtap_skb_to_vnet_hdr should
 * be shared with the tun/tap driver.
 */
static int macvtap_skb_from_vnet_hdr(struct sk_buff *skb,
				     struct virtio_net_hdr *vnet_hdr)
{
	unsigned short gso_type = 0;
	if (vnet_hdr->gso_type != VIRTIO_NET_HDR_GSO_NONE) {
		switch (vnet_hdr->gso_type & ~VIRTIO_NET_HDR_GSO_ECN) {
		case VIRTIO_NET_HDR_GSO_TCPV4:
			gso_type = SKB_GSO_TCPV4;
			break;
		case VIRTIO_NET_HDR_GSO_TCPV6:
			gso_type = SKB_GSO_TCPV6;
			break;
		case VIRTIO_NET_HDR_GSO_UDP:
			gso_type = SKB_GSO_UDP;
			break;
		default:
			return -EINVAL;
		}

		if (vnet_hdr->gso_type & VIRTIO_NET_HDR_GSO_ECN)
			gso_type |= SKB_GSO_TCP_ECN;

		if (vnet_hdr->gso_size == 0)
			return -EINVAL;
	}

	if (vnet_hdr->flags & VIRTIO_NET_HDR_F_NEEDS_CSUM) {
		if (!skb_partial_csum_set(skb, vnet_hdr->csum_start,
					  vnet_hdr->csum_offset))
			return -EINVAL;
	}

	if (vnet_hdr->gso_type != VIRTIO_NET_HDR_GSO_NONE) {
		skb_shinfo(skb)->gso_size = vnet_hdr->gso_size;
		skb_shinfo(skb)->gso_type = gso_type;

		/* Header must be checked, and gso_segs computed. */
		skb_shinfo(skb)->gso_type |= SKB_GSO_DODGY;
		skb_shinfo(skb)->gso_segs = 0;
	}
	return 0;
}

static int macvtap_skb_to_vnet_hdr(const struct sk_buff *skb,
				   struct virtio_net_hdr *vnet_hdr)
{
	memset(vnet_hdr, 0, sizeof(*vnet_hdr));

	if (skb_is_gso(skb)) {
		struct skb_shared_info *sinfo = skb_shinfo(skb);

		/* This is a hint as to how much should be linear. */
		vnet_hdr->hdr_len = skb_headlen(skb);
		vnet_hdr->gso_size = sinfo->gso_size;
		if (sinfo->gso_type & SKB_GSO_TCPV4)
			vnet_hdr->gso_type = VIRTIO_NET_HDR_GSO_TCPV4;
		else if (sinfo->gso_type & SKB_GSO_TCPV6)
			vnet_hdr->gso_type = VIRTIO_NET_HDR_GSO_TCPV6;
		else if (sinfo->gso_type & SKB_GSO_UDP)
			vnet_hdr->gso_type = VIRTIO_NET_HDR_GSO_UDP;
		else
			BUG();
		if (sinfo->gso_type & SKB_GSO_TCP_ECN)
			vnet_hdr->gso_type |= VIRTIO_NET_HDR_GSO_ECN;
	} else
		vnet_hdr->gso_type = VIRTIO_NET_HDR_GSO_NONE;

	if (skb->ip_summed == CHECKSUM_PARTIAL) {
		vnet_hdr->flags = VIRTIO_NET_HDR_F_NEEDS_CSUM;
		vnet_hdr->csum_start = skb_checksum_start_offset(skb);
		vnet_hdr->csum_offset = skb->csum_offset;
	} else if (skb->ip_summed == CHECKSUM_UNNECESSARY) {
		vnet_hdr->flags = VIRTIO_NET_HDR_F_DATA_VALID;
	} /* else everything is zero */

	return 0;
}

/* Get packet from user space buffer */
static ssize_t macvtap_get_user(struct macvtap_queue *q, struct msghdr *m,
				const struct iovec *iv, unsigned long total_len,
				size_t count, int noblock)
{
	struct sk_buff *skb;
	struct macvlan_dev *vlan;
	unsigned long len = total_len;
	int err;
	struct virtio_net_hdr vnet_hdr = { 0 };
	int vnet_hdr_len = 0;
	int copylen = 0;
	bool zerocopy = false;

	if (q->flags & IFF_VNET_HDR) {
		vnet_hdr_len = q->vnet_hdr_sz;

		err = -EINVAL;
		if (len < vnet_hdr_len)
			goto err;
		len -= vnet_hdr_len;

		err = memcpy_fromiovecend((void *)&vnet_hdr, iv, 0,
					   sizeof(vnet_hdr));
		if (err < 0)
			goto err;
		if ((vnet_hdr.flags & VIRTIO_NET_HDR_F_NEEDS_CSUM) &&
		     vnet_hdr.csum_start + vnet_hdr.csum_offset + 2 >
							vnet_hdr.hdr_len)
			vnet_hdr.hdr_len = vnet_hdr.csum_start +
						vnet_hdr.csum_offset + 2;
		err = -EINVAL;
		if (vnet_hdr.hdr_len > len)
			goto err;
	}

	err = -EINVAL;
	if (unlikely(len < ETH_HLEN))
		goto err;

	err = -EMSGSIZE;
	if (unlikely(count > UIO_MAXIOV))
		goto err;

	if (m && m->msg_control && sock_flag(&q->sk, SOCK_ZEROCOPY))
		zerocopy = true;

	if (zerocopy) {
		/* Userspace may produce vectors with count greater than
		 * MAX_SKB_FRAGS, so we need to linearize parts of the skb
		 * to let the rest of data to be fit in the frags.
		 */
		if (count > MAX_SKB_FRAGS) {
			copylen = iov_length(iv, count - MAX_SKB_FRAGS);
			if (copylen < vnet_hdr_len)
				copylen = 0;
			else
				copylen -= vnet_hdr_len;
		}
		/* There are 256 bytes to be copied in skb, so there is enough
		 * room for skb expand head in case it is used.
		 * The rest buffer is mapped from userspace.
		 */
		if (copylen < vnet_hdr.hdr_len)
			copylen = vnet_hdr.hdr_len;
		if (!copylen)
			copylen = GOODCOPY_LEN;
	} else
		copylen = len;

	skb = macvtap_alloc_skb(&q->sk, NET_IP_ALIGN, copylen,
				vnet_hdr.hdr_len, noblock, &err);
	if (!skb)
		goto err;

	if (zerocopy)
		err = zerocopy_sg_from_iovec(skb, iv, vnet_hdr_len, count);
	else
		err = skb_copy_datagram_from_iovec(skb, 0, iv, vnet_hdr_len,
						   len);
	if (err)
		goto err_kfree;

	skb_set_network_header(skb, ETH_HLEN);
	skb_reset_mac_header(skb);
	skb->protocol = eth_hdr(skb)->h_proto;

	if (vnet_hdr_len) {
		err = macvtap_skb_from_vnet_hdr(skb, &vnet_hdr);
		if (err)
			goto err_kfree;
	}

	rcu_read_lock_bh();
	vlan = rcu_dereference_bh(q->vlan);
	/* copy skb_ubuf_info for callback when skb has no error */
	if (zerocopy) {
		skb_shinfo(skb)->destructor_arg = m->msg_control;
		skb_shinfo(skb)->tx_flags |= SKBTX_DEV_ZEROCOPY;
	}
	if (vlan)
		macvlan_start_xmit(skb, vlan->dev);
	else
		kfree_skb(skb);
	rcu_read_unlock_bh();

	return total_len;

err_kfree:
	kfree_skb(skb);

err:
	rcu_read_lock_bh();
	vlan = rcu_dereference_bh(q->vlan);
	if (vlan)
		vlan->dev->stats.tx_dropped++;
	rcu_read_unlock_bh();

	return err;
}

static ssize_t macvtap_aio_write(struct kiocb *iocb, const struct iovec *iv,
				 unsigned long count, loff_t pos)
{
	struct file *file = iocb->ki_filp;
	ssize_t result = -ENOLINK;
	struct macvtap_queue *q = file->private_data;

	result = macvtap_get_user(q, NULL, iv, iov_length(iv, count), count,
				  file->f_flags & O_NONBLOCK);
	return result;
}

/* Put packet to the user space buffer */
static ssize_t macvtap_put_user(struct macvtap_queue *q,
				const struct sk_buff *skb,
				const struct iovec *iv, int len)
{
	struct macvlan_dev *vlan;
	int ret;
	int vnet_hdr_len = 0;
	int vlan_offset = 0;
	int copied;

	if (q->flags & IFF_VNET_HDR) {
		struct virtio_net_hdr vnet_hdr;
		vnet_hdr_len = q->vnet_hdr_sz;
		if ((len -= vnet_hdr_len) < 0)
			return -EINVAL;

		ret = macvtap_skb_to_vnet_hdr(skb, &vnet_hdr);
		if (ret)
			return ret;

		if (memcpy_toiovecend(iv, (void *)&vnet_hdr, 0, sizeof(vnet_hdr)))
			return -EFAULT;
	}
	copied = vnet_hdr_len;

	if (!vlan_tx_tag_present(skb))
		len = min_t(int, skb->len, len);
	else {
		int copy;
		struct {
			__be16 h_vlan_proto;
			__be16 h_vlan_TCI;
		} veth;
		veth.h_vlan_proto = htons(ETH_P_8021Q);
		veth.h_vlan_TCI = htons(vlan_tx_tag_get(skb));

		vlan_offset = offsetof(struct vlan_ethhdr, h_vlan_proto);
		len = min_t(int, skb->len + VLAN_HLEN, len);

		copy = min_t(int, vlan_offset, len);
		ret = skb_copy_datagram_const_iovec(skb, 0, iv, copied, copy);
		len -= copy;
		copied += copy;
		if (ret || !len)
			goto done;

		copy = min_t(int, sizeof(veth), len);
		ret = memcpy_toiovecend(iv, (void *)&veth, copied, copy);
		len -= copy;
		copied += copy;
		if (ret || !len)
			goto done;
	}

	ret = skb_copy_datagram_const_iovec(skb, vlan_offset, iv, copied, len);
	copied += len;

done:
	rcu_read_lock_bh();
	vlan = rcu_dereference_bh(q->vlan);
	if (vlan)
		macvlan_count_rx(vlan, copied - vnet_hdr_len, ret == 0, 0);
	rcu_read_unlock_bh();

	return ret ? ret : copied;
}

static ssize_t macvtap_do_read(struct macvtap_queue *q, struct kiocb *iocb,
			       const struct iovec *iv, unsigned long len,
			       int noblock)
{
	DECLARE_WAITQUEUE(wait, current);
	struct sk_buff *skb;
	ssize_t ret = 0;

	add_wait_queue(sk_sleep(&q->sk), &wait);
	while (len) {
		current->state = TASK_INTERRUPTIBLE;

		/* Read frames from the queue */
		skb = skb_dequeue(&q->sk.sk_receive_queue);
		if (!skb) {
			if (noblock) {
				ret = -EAGAIN;
				break;
			}
			if (signal_pending(current)) {
				ret = -ERESTARTSYS;
				break;
			}
			/* Nothing to read, let's sleep */
			schedule();
			continue;
		}
		ret = macvtap_put_user(q, skb, iv, len);
		kfree_skb(skb);
		break;
	}

	current->state = TASK_RUNNING;
	remove_wait_queue(sk_sleep(&q->sk), &wait);
	return ret;
}

static ssize_t macvtap_aio_read(struct kiocb *iocb, const struct iovec *iv,
				unsigned long count, loff_t pos)
{
	struct file *file = iocb->ki_filp;
	struct macvtap_queue *q = file->private_data;
	ssize_t len, ret = 0;

	len = iov_length(iv, count);
	if (len < 0) {
		ret = -EINVAL;
		goto out;
	}

	ret = macvtap_do_read(q, iocb, iv, len, file->f_flags & O_NONBLOCK);
	ret = min_t(ssize_t, ret, len); /* XXX copied from tun.c. Why? */
out:
	return ret;
}

/*
 * provide compatibility with generic tun/tap interface
 */
static long macvtap_ioctl(struct file *file, unsigned int cmd,
			  unsigned long arg)
{
	struct macvtap_queue *q = file->private_data;
	struct macvlan_dev *vlan;
	void __user *argp = (void __user *)arg;
	struct ifreq __user *ifr = argp;
	unsigned int __user *up = argp;
	unsigned int u;
	int __user *sp = argp;
	int s;
	int ret;

	switch (cmd) {
	case TUNSETIFF:
		/* ignore the name, just look at flags */
		if (get_user(u, &ifr->ifr_flags))
			return -EFAULT;

		ret = 0;
		if ((u & ~IFF_VNET_HDR) != (IFF_NO_PI | IFF_TAP))
			ret = -EINVAL;
		else
			q->flags = u;

		return ret;

	case TUNGETIFF:
		rcu_read_lock_bh();
		vlan = rcu_dereference_bh(q->vlan);
		if (vlan)
			dev_hold(vlan->dev);
		rcu_read_unlock_bh();

		if (!vlan)
			return -ENOLINK;

		ret = 0;
		if (copy_to_user(&ifr->ifr_name, vlan->dev->name, IFNAMSIZ) ||
		    put_user(q->flags, &ifr->ifr_flags))
			ret = -EFAULT;
		dev_put(vlan->dev);
		return ret;

	case TUNGETFEATURES:
		if (put_user(IFF_TAP | IFF_NO_PI | IFF_VNET_HDR, up))
			return -EFAULT;
		return 0;

	case TUNSETSNDBUF:
		if (get_user(u, up))
			return -EFAULT;

		q->sk.sk_sndbuf = u;
		return 0;

	case TUNGETVNETHDRSZ:
		s = q->vnet_hdr_sz;
		if (put_user(s, sp))
			return -EFAULT;
		return 0;

	case TUNSETVNETHDRSZ:
		if (get_user(s, sp))
			return -EFAULT;
		if (s < (int)sizeof(struct virtio_net_hdr))
			return -EINVAL;

		q->vnet_hdr_sz = s;
		return 0;

	case TUNSETOFFLOAD:
		/* let the user check for future flags */
		if (arg & ~(TUN_F_CSUM | TUN_F_TSO4 | TUN_F_TSO6 |
			    TUN_F_TSO_ECN | TUN_F_UFO))
			return -EINVAL;

		/* TODO: only accept frames with the features that
			 got enabled for forwarded frames */
		if (!(q->flags & IFF_VNET_HDR))
			return  -EINVAL;
		return 0;

	default:
		return -EINVAL;
	}
}

#ifdef CONFIG_COMPAT
static long macvtap_compat_ioctl(struct file *file, unsigned int cmd,
				 unsigned long arg)
{
	return macvtap_ioctl(file, cmd, (unsigned long)compat_ptr(arg));
}
#endif

static const struct file_operations macvtap_fops = {
	.owner		= THIS_MODULE,
	.open		= macvtap_open,
	.release	= macvtap_release,
	.aio_read	= macvtap_aio_read,
	.aio_write	= macvtap_aio_write,
	.poll		= macvtap_poll,
	.llseek		= no_llseek,
	.unlocked_ioctl	= macvtap_ioctl,
#ifdef CONFIG_COMPAT
	.compat_ioctl	= macvtap_compat_ioctl,
#endif
};

static int macvtap_sendmsg(struct kiocb *iocb, struct socket *sock,
			   struct msghdr *m, size_t total_len)
{
	struct macvtap_queue *q = container_of(sock, struct macvtap_queue, sock);
	return macvtap_get_user(q, m, m->msg_iov, total_len, m->msg_iovlen,
			    m->msg_flags & MSG_DONTWAIT);
}

static int macvtap_recvmsg(struct kiocb *iocb, struct socket *sock,
			   struct msghdr *m, size_t total_len,
			   int flags)
{
	struct macvtap_queue *q = container_of(sock, struct macvtap_queue, sock);
	int ret;
	if (flags & ~(MSG_DONTWAIT|MSG_TRUNC))
		return -EINVAL;
	ret = macvtap_do_read(q, iocb, m->msg_iov, total_len,
			  flags & MSG_DONTWAIT);
	if (ret > total_len) {
		m->msg_flags |= MSG_TRUNC;
		ret = flags & MSG_TRUNC ? ret : total_len;
	}
	return ret;
}

/* Ops structure to mimic raw sockets with tun */
static const struct proto_ops macvtap_socket_ops = {
	.sendmsg = macvtap_sendmsg,
	.recvmsg = macvtap_recvmsg,
};

/* Get an underlying socket object from tun file.  Returns error unless file is
 * attached to a device.  The returned object works like a packet socket, it
 * can be used for sock_sendmsg/sock_recvmsg.  The caller is responsible for
 * holding a reference to the file for as long as the socket is in use. */
struct socket *macvtap_get_socket(struct file *file)
{
	struct macvtap_queue *q;
	if (file->f_op != &macvtap_fops)
		return ERR_PTR(-EINVAL);
	q = file->private_data;
	if (!q)
		return ERR_PTR(-EBADFD);
	return &q->sock;
}
EXPORT_SYMBOL_GPL(macvtap_get_socket);

static int macvtap_device_event(struct notifier_block *unused,
				unsigned long event, void *ptr)
{
	struct net_device *dev = ptr;
	struct macvlan_dev *vlan;
	struct device *classdev;
	dev_t devt;
	int err;

	if (dev->rtnl_link_ops != &macvtap_link_ops)
		return NOTIFY_DONE;

	vlan = netdev_priv(dev);

	switch (event) {
	case NETDEV_REGISTER:
		/* Create the device node here after the network device has
		 * been registered but before register_netdevice has
		 * finished running.
		 */
		err = macvtap_get_minor(vlan);
		if (err)
			return notifier_from_errno(err);

		devt = MKDEV(MAJOR(macvtap_major), vlan->minor);
		classdev = device_create(macvtap_class, &dev->dev, devt,
					 dev, "tap%d", dev->ifindex);
		if (IS_ERR(classdev)) {
			macvtap_free_minor(vlan);
			return notifier_from_errno(PTR_ERR(classdev));
		}
		break;
	case NETDEV_UNREGISTER:
		devt = MKDEV(MAJOR(macvtap_major), vlan->minor);
		device_destroy(macvtap_class, devt);
		macvtap_free_minor(vlan);
		break;
	}

	return NOTIFY_DONE;
}

static struct notifier_block macvtap_notifier_block __read_mostly = {
	.notifier_call	= macvtap_device_event,
};

static int macvtap_init(void)
{
	int err;

	err = alloc_chrdev_region(&macvtap_major, 0,
				MACVTAP_NUM_DEVS, "macvtap");
	if (err)
		goto out1;

	cdev_init(&macvtap_cdev, &macvtap_fops);
	err = cdev_add(&macvtap_cdev, macvtap_major, MACVTAP_NUM_DEVS);
	if (err)
		goto out2;

	macvtap_class = class_create(THIS_MODULE, "macvtap");
	if (IS_ERR(macvtap_class)) {
		err = PTR_ERR(macvtap_class);
		goto out3;
	}

	err = register_netdevice_notifier(&macvtap_notifier_block);
	if (err)
		goto out4;

	err = macvlan_link_register(&macvtap_link_ops);
	if (err)
		goto out5;

	return 0;

out5:
	unregister_netdevice_notifier(&macvtap_notifier_block);
out4:
	class_unregister(macvtap_class);
out3:
	cdev_del(&macvtap_cdev);
out2:
	unregister_chrdev_region(macvtap_major, MACVTAP_NUM_DEVS);
out1:
	return err;
}
module_init(macvtap_init);

static void macvtap_exit(void)
{
	rtnl_link_unregister(&macvtap_link_ops);
	unregister_netdevice_notifier(&macvtap_notifier_block);
	class_unregister(macvtap_class);
	cdev_del(&macvtap_cdev);
	unregister_chrdev_region(macvtap_major, MACVTAP_NUM_DEVS);
}
module_exit(macvtap_exit);

MODULE_ALIAS_RTNL_LINK("macvtap");
MODULE_AUTHOR("Arnd Bergmann <arnd@arndb.de>");
MODULE_LICENSE("GPL");


text:
FROM ubuntu:16.10
LABEL maintainer="takahasi <3263ta@gmail.com>" \
      description="OpenRTM on Docker: OpenRTM-aist on Docker images." \
      build_type="ubuntu-python"

ENV DEBIAN_FRONTEND noninteractive

RUN set -x && apt-get update -qq

RUN apt-get install -y curl bc bsdmainutils apt-utils aptitude iputils-ping net-tools && \
    apt-get install -y python-pip && \
    curl -O http://svn.openrtm.org/OpenRTM-aist-Python/tags/RELEASE_1_1_2/OpenRTM-aist-Python/installer/install_scripts/pkg_install_python_ubuntu.sh && \
    chmod a+x pkg_install_python_ubuntu.sh && sync && \
    ./pkg_install_python_ubuntu.sh -y

RUN apt-get autoclean -y && apt-get autoremove -y

ENTRYPOINT ["/bin/bash", "-c"]


text:
;(function() {

    'use strict';

    angular
        .module('<%= moduleName %>')
        .directive('<%= moduleName %>', <%= moduleName %>);

    /* @ngInject */
    function <%= moduleName %>() {

        var directive = {
            restrict: 'EA',
            scope:true,
            template:'<div data-ng-transclude></div>',
            transclude:true,
            controller: '<%= moduleName %>Controller as vm',
            link:link
        };

        return directive;

        function link(scope, element, attrs, ctrl, transclude) {}

    }

}).call(this);


text:
package com.thoughtworks.go.server.dao;

import com.thoughtworks.go.config.*;
import com.thoughtworks.go.config.elastic.ClusterProfile;
import com.thoughtworks.go.config.elastic.ElasticProfile;
import com.thoughtworks.go.config.materials.MaterialConfigs;
import com.thoughtworks.go.config.materials.dependency.DependencyMaterial;
import com.thoughtworks.go.domain.*;
import com.thoughtworks.go.domain.buildcause.BuildCause;
import com.thoughtworks.go.domain.materials.Material;
import com.thoughtworks.go.domain.materials.Modification;
import com.thoughtworks.go.domain.materials.dependency.DependencyMaterialRevision;
import com.thoughtworks.go.helper.*;
import com.thoughtworks.go.server.cache.GoCache;
import com.thoughtworks.go.server.domain.PipelineTimeline;
import com.thoughtworks.go.server.domain.Username;
import com.thoughtworks.go.server.persistence.AgentDao;
import com.thoughtworks.go.server.persistence.MaterialRepository;
import com.thoughtworks.go.server.persistence.PipelineRepository;
import com.thoughtworks.go.server.service.InstanceFactory;
import com.thoughtworks.go.server.service.ManualBuild;
import com.thoughtworks.go.server.service.MaterialConfigConverter;
import com.thoughtworks.go.server.service.PipelineService;
import com.thoughtworks.go.server.transaction.TransactionSynchronizationManager;
import com.thoughtworks.go.server.transaction.TransactionTemplate;
import com.thoughtworks.go.util.Clock;
import com.thoughtworks.go.util.GoConstants;
import com.thoughtworks.go.util.TimeProvider;
import org.apache.ibatis.cache.Cache;
import org.apache.ibatis.session.SqlSessionFactory;
import org.dbunit.DataSourceDatabaseTester;
import org.dbunit.IDatabaseTester;
import org.dbunit.database.AmbiguousTableNameException;
import org.dbunit.dataset.DefaultDataSet;
import org.dbunit.dataset.DefaultTable;
import org.dbunit.operation.DatabaseOperation;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.joda.time.DateTime;
import org.junit.Assert;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.stereotype.Component;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallbackWithoutResult;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.*;

import static com.thoughtworks.go.domain.JobResult.Failed;
import static com.thoughtworks.go.domain.PersistentObject.NOT_PERSISTED;
import static com.thoughtworks.go.helper.ModificationsMother.modifyOneFile;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.not;

@Component
public class DatabaseAccessHelper extends HibernateDaoSupport {
    private IDatabaseTester databaseTester;
    private StageDao stageDao;
    private PipelineSqlMapDao pipelineDao;
    private JobInstanceDao jobInstanceDao;
    private AgentDao agentDao;
    private PipelineTimeline pipelineTimeline;
    private TransactionTemplate transactionTemplate;
    private TransactionSynchronizationManager transactionSynchronizationManager;

    public static final String AGENT_UUID = "123456789-123";
    private DataSource dataSource;
    private SqlSessionFactory sqlMapClient;
    private MaterialRepository materialRepository;
    private GoCache goCache;
    private PipelineService pipelineService;
    private String md5 = "md5-test";
    private InstanceFactory instanceFactory;
    private JobAgentMetadataDao jobAgentMetadataDao;

    @Deprecated // Should not be creating a new spring context for every test
    public DatabaseAccessHelper() throws AmbiguousTableNameException {
        ClassPathXmlApplicationContext context = createDataContext();
        dataSource = (DataSource) context.getBean("dataSource");
        initialize(dataSource);
    }

    private ClassPathXmlApplicationContext createDataContext() {
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("classpath*:WEB-INF/applicationContext-dataLocalAccess.xml");
        this.stageDao = (StageSqlMapDao) context.getBean("stageDao");
        this.jobInstanceDao = (JobInstanceDao) context.getBean("buildInstanceDao");
        this.pipelineDao = (PipelineSqlMapDao) context.getBean("pipelineDao");
        this.agentDao = (AgentDao) context.getBean("agentDao");
        this.materialRepository = (MaterialRepository) context.getBean("materialRepository");
        this.goCache = (GoCache) context.getBean("goCache");
        this.instanceFactory = (InstanceFactory) context.getBean("instanceFactory");
        this.jobAgentMetadataDao = (JobAgentMetadataDao) context.getBean("jobAgentMetadataDao");
        setSessionFactory((SessionFactory) context.getBean("sessionFactory"));
        return context;
    }

    @Deprecated //use Autowired version
    public DatabaseAccessHelper(DataSource dataSource) throws AmbiguousTableNameException {
        this.dataSource = dataSource;
        initialize(dataSource);
    }

    @Autowired
    public DatabaseAccessHelper(DataSource dataSource,
                                SqlSessionFactory sqlMapClient,
                                StageDao stageDao,
                                JobInstanceDao jobInstanceDao,
                                PipelineDao pipelineDao,
                                MaterialRepository materialRepository,
                                SessionFactory sessionFactory,
                                PipelineTimeline pipelineTimeline,
                                TransactionTemplate transactionTemplate,
                                TransactionSynchronizationManager transactionSynchronizationManager,
                                GoCache goCache,
                                PipelineService pipelineService, InstanceFactory instanceFactory,
                                JobAgentMetadataDao jobAgentMetadataDao,
                                AgentDao agentDao) throws AmbiguousTableNameException {
        this.dataSource = dataSource;
        this.sqlMapClient = sqlMapClient;
        this.stageDao = stageDao;
        this.jobInstanceDao = jobInstanceDao;
        this.pipelineTimeline = pipelineTimeline;
        this.transactionTemplate = transactionTemplate;
        this.transactionSynchronizationManager = transactionSynchronizationManager;
        this.goCache = goCache;
        this.pipelineService = pipelineService;
        this.instanceFactory = instanceFactory;
        this.jobAgentMetadataDao = jobAgentMetadataDao;
        this.pipelineDao = (PipelineSqlMapDao) pipelineDao;
        this.materialRepository = materialRepository;
        this.agentDao = agentDao;
        setSessionFactory(sessionFactory);
        initialize(dataSource);
    }

    private void initialize(DataSource dataSource) throws AmbiguousTableNameException {
        databaseTester = new DataSourceDatabaseTester(dataSource);
        databaseTester.setSetUpOperation(DatabaseOperation.CLEAN_INSERT);
        databaseTester.setTearDownOperation(DatabaseOperation.DELETE_ALL);
        DefaultDataSet dataSet = new DefaultDataSet();
        dataSet.addTable(new DefaultTable("agents"));

        dataSet.addTable(new DefaultTable("pipelines"));
        dataSet.addTable(new DefaultTable("pipelinestates"));
        dataSet.addTable(new DefaultTable("materials"));
        dataSet.addTable(new DefaultTable("modifications"));
        dataSet.addTable(new DefaultTable("pipelineMaterialRevisions"));
        dataSet.addTable(new DefaultTable("modifiedFiles"));

        dataSet.addTable(new DefaultTable("notificationfilters"));
        dataSet.addTable(new DefaultTable("users"));
        dataSet.addTable(new DefaultTable("stages"));
        dataSet.addTable(new DefaultTable("pipelineLabelCounts"));
        dataSet.addTable(new DefaultTable("environmentVariables"));
        dataSet.addTable(new DefaultTable("artifactPlans"));
        dataSet.addTable(new DefaultTable("buildStateTransitions"));
        dataSet.addTable(new DefaultTable("resources"));
        dataSet.addTable(new DefaultTable("builds"));

        dataSet.addTable(new DefaultTable("stageArtifactCleanupProhibited"));
        dataSet.addTable(new DefaultTable("serverBackups"));
        dataSet.addTable(new DefaultTable("jobAgentMetadata"));
        dataSet.addTable(new DefaultTable("DataSharingSettings"));
        dataSet.addTable(new DefaultTable("UsageDataReporting"));
        dataSet.addTable(new DefaultTable("AccessToken"));

        databaseTester.setDataSet(dataSet);
    }

    public void onSetUp() throws Exception {
        databaseTester.onSetup();
        pipelineTimeline.clearWhichIsEvilAndShouldNotBeUsedInRealWorld();
        if (sqlMapClient != null) {
            for (Cache cache : sqlMapClient.getConfiguration().getCaches()) {
                cache.clear();
            }
        }
    }

    public void onTearDown() throws Exception {
        databaseTester.onTearDown();
        goCache.clear();
    }

    public TransactionTemplate txTemplate() {
        return transactionTemplate;
    }

    public TransactionSynchronizationManager txSynchronizationManager() {
        return transactionSynchronizationManager;
    }

    public JobInstanceDao getBuildInstanceDao() {
        return jobInstanceDao;
    }

    public StageDao getStageDao() {
        return stageDao;
    }

    public PipelineDao getPipelineDao() {
        return pipelineDao;
    }

    public void pass(Pipeline pipeline) {
        for (Stage stage : pipeline.getStages()) {
            passStage(stage);
        }
    }

    public long getScheduledStageId(String pipelineName, String stageName) throws SQLException {
        Pipeline pipeline = saveTestPipeline(pipelineName, stageName);
        return pipeline.getStages().get(0).getId();
    }

    public Pipeline saveTestPipeline(String pipelineName, String stageName, String... jobConfigNames)
            throws SQLException {
        PipelineConfig pipelineConfig = configurePipeline(pipelineName, stageName, jobConfigNames);
        Pipeline pipeline = scheduleWithFileChanges(pipelineConfig);
        pipeline = savePipelineWithStagesAndMaterials(pipeline);
        return pipeline;
    }

    public Pipeline savePipelineWithStagesAndMaterials(Pipeline pipeline) {
        saveRevs(pipeline.getBuildCause().getMaterialRevisions());
        return save(pipeline);
    }

    public Pipeline savePipelineWithMaterials(Pipeline pipeline) {
        saveRevs(pipeline.getBuildCause().getMaterialRevisions());
        return save(pipeline);
    }

    public Pipeline save(Pipeline pipeline) {
        return pipelineDao.saveWithStages(pipeline);
    }

    private PipelineConfig configurePipeline(String pipelineName, String stageName, String... jobConfigNames) {
        final String[] defaultBuildPlanNames = {"functional", "unit"};
        jobConfigNames = jobConfigNames.length == 0 ? defaultBuildPlanNames : jobConfigNames;
        StageConfig stageConfig = StageConfigMother.stageConfig(stageName,
                BuildPlanMother.withBuildPlans(jobConfigNames));
        MaterialConfigs materialConfigs = MaterialConfigsMother.multipleMaterialConfigs();
        PipelineConfig pipelineConfig = new PipelineConfig(new CaseInsensitiveString(pipelineName), materialConfigs, stageConfig);
        return pipelineConfig;
    }

    private Pipeline scheduleWithFileChanges(PipelineConfig pipelineConfig) {
        BuildCause buildCause = BuildCause.createWithModifications(modifyOneFile(pipelineConfig), "");
        saveRevs(buildCause.getMaterialRevisions());
        return instanceFactory.createPipelineInstance(pipelineConfig, buildCause, new DefaultSchedulingContext(
                GoConstants.DEFAULT_APPROVED_BY), md5, new TimeProvider());
    }

    public Pipeline saveTestPipelineWithoutSchedulingBuilds(String pipelineName, String stageName,
                                                            String... jobConfigNames)
            throws SQLException {
        PipelineConfig pipelineConfig = configurePipeline(pipelineName, stageName, jobConfigNames);
        Pipeline pipeline = scheduleWithFileChanges(pipelineConfig);
        clearAllBuildInstances(pipeline);
        return savePipelineWithStagesAndMaterials(pipeline);
    }

    private void clearAllBuildInstances(Pipeline pipeline) {
        pipeline.getFirstStage().setJobInstances(new JobInstances());
    }

    public Pipeline rescheduleTestPipeline(String pipelineName, String stageName, String userName) throws SQLException {
        String[] jobConfigNames = new String[]{};
        PipelineConfig pipelineConfig = configurePipeline(pipelineName, stageName, jobConfigNames);

        BuildCause buildCause = BuildCause.createManualForced(modifyOneFile(new MaterialConfigConverter().toMaterials(pipelineConfig.materialConfigs()),
                ModificationsMother.currentRevision()), Username.ANONYMOUS);

        Pipeline pipeline = instanceFactory.createPipelineInstance(pipelineConfig, buildCause, new DefaultSchedulingContext(
                GoConstants.DEFAULT_APPROVED_BY), md5, new TimeProvider());
        return savePipelineWithStagesAndMaterials(pipeline);
    }

    @Deprecated // Only actually passes the first stage. Use newPipelineWithAllStagesPassed instead
    public Pipeline passPipeline(Pipeline pipeline) {
        for (Stage stage : pipeline.getStages()) {
            passStage(stage);
        }
        Stages loadedStages = new Stages();
        for (Stage stage : pipeline.getStages()) {
            loadedStages.add(stageDao.stageById(stage.getId()));
        }
        Pipeline loadedPipeline = this.pipelineDao.loadPipeline(pipeline.getId());
        loadedPipeline.setStages(loadedStages);
        return loadedPipeline;
    }

    public Pipeline newPipelineWithFirstStagePassed(PipelineConfig config) throws SQLException {
        Pipeline pipeline = instanceFactory.createPipelineInstance(config,
                BuildCause.createManualForced(modifyOneFile(new MaterialConfigConverter().toMaterials(config.materialConfigs()), ModificationsMother.nextRevision()), Username.ANONYMOUS),
                new DefaultSchedulingContext(
                        GoConstants.DEFAULT_APPROVED_BY), md5, new TimeProvider());
        saveMaterialsWIthPassedStages(pipeline);
        return pipeline;
    }

    public void saveMaterialsWIthPassedStages(Pipeline pipeline) {
        savePipelineWithStagesAndMaterials(pipeline);
        passStage(pipeline.getFirstStage());
    }

    public Pipeline newPipelineWithFirstStageFailed(PipelineConfig config) throws SQLException {
        Pipeline pipeline = instanceFactory.createPipelineInstance(config, BuildCause.createManualForced(modifyOneFile(new MaterialConfigConverter().toMaterials(config.materialConfigs()),
                ModificationsMother.currentRevision()), Username.ANONYMOUS),
                new DefaultSchedulingContext(
                        GoConstants.DEFAULT_APPROVED_BY), md5, new TimeProvider());
        savePipelineWithStagesAndMaterials(pipeline);
        failStage(pipeline.getFirstStage());
        return pipeline;
    }

    public Pipeline newPipelineWithFirstStageScheduled(PipelineConfig config) throws SQLException {
        Pipeline pipeline = instanceFactory.createPipelineInstance(config,
                BuildCause.createManualForced(modifyOneFile(new MaterialConfigConverter().toMaterials(config.materialConfigs()), ModificationsMother.nextRevision()), Username.ANONYMOUS),
                new DefaultSchedulingContext(
                        GoConstants.DEFAULT_APPROVED_BY), md5, new TimeProvider());
        savePipelineWithStagesAndMaterials(pipeline);
        return pipeline;
    }

    public Pipeline newPipelineWithAllStagesPassed(PipelineConfig config) throws SQLException {
        Pipeline pipeline = newPipelineWithFirstStagePassed(config);
        for (StageConfig stageConfig : config) {
            if (config.first().equals(stageConfig)) {
                continue;
            }
            Stage instance = instanceFactory.createStageInstance(stageConfig, new DefaultSchedulingContext(
                    GoConstants.DEFAULT_APPROVED_BY), md5, new TimeProvider());
            stageDao.saveWithJobs(pipeline, instance);
            passStage(instance);
        }
        return pipelineDao.loadPipeline(pipeline.getId());
    }

    public Stage saveBuildingStage(String pipelineName, String stageName) throws SQLException {
        Pipeline pipeline = saveTestPipeline(pipelineName, stageName);
        Stage stage = saveBuildingStage(pipeline.getStages().byName(stageName));
        for (JobInstance job : stage.getJobInstances()) {
            job.setIdentifier(new JobIdentifier(pipeline, stage, job));
        }
        return stage;
    }

    public Stage saveBuildingStage(Stage stage) {
        for (JobInstance jobInstance : stage.getJobInstances()) {
            JobInstanceMother.setBuildingState(jobInstance);
            jobInstance.setAgentUuid(AGENT_UUID);
            jobInstanceDao.updateAssignedInfo(jobInstance);
        }
        return stage;
    }

    public Stage scheduleStage(Pipeline pipeline, StageConfig stageConfig) {
        return scheduleStage(pipeline, stageConfig, 0);
    }

    public Stage scheduleStage(Pipeline pipeline, StageConfig stageConfig, int order) {
        Stage instance = instanceFactory.createStageInstance(stageConfig, new DefaultSchedulingContext("cruise"), md5, new TimeProvider());
        return saveStage(pipeline, instance, order);
    }

    public Stage saveStage(Pipeline pipeline, Stage instance, int order) {
        instance.setOrderId(order);
        return stageDao.saveWithJobs(pipeline, instance);
    }

    public void passStage(Stage stage) {
        completeStage(stage, JobResult.Passed);
    }

    public void completeStage(final Stage stage, final JobResult jobResult) {
        final StageResult stageResult = completeAllJobs(stage, jobResult);
        updateResultInTransaction(stage, stageResult);
    }

    private void updateResultInTransaction(final Stage stage, final StageResult stageResult) {
        transactionTemplate.execute(new TransactionCallbackWithoutResult() {
            @Override
            protected void doInTransactionWithoutResult(TransactionStatus status) {
                stageDao.updateResult(stage, stageResult, null);
            }
        });
    }

    public StageResult completeAllJobs(Stage stage, JobResult jobResult) {
        for (JobInstance job : stage.getJobInstances()) {
            JobInstanceMother.setBuildingState(job);
            job.setAgentUuid(AGENT_UUID);
            job.completing(jobResult);
            job.completed(new DateTime().plusMinutes(5).toDate());
            jobInstanceDao.updateAssignedInfo(job);
        }
        StageResult stageResult;
        switch (jobResult) {
            case Failed:
                stageResult = StageResult.Failed;
                break;
            case Cancelled:
                stageResult = StageResult.Cancelled;
                break;
            default:
                stageResult = StageResult.Passed;
        }
        stage.calculateResult();
        return stageResult;
    }

    public void failStage(Stage stage) {
        failStage(stage, new Date());
    }

    public void failStage(Stage stage, Date completionDate) {
        for (JobInstance job : stage.getJobInstances()) {
            job.completing(Failed, completionDate);
            job.completed(completionDate);
            jobInstanceDao.updateStateAndResult(job);
        }
        stage.calculateResult();
        updateResultInTransaction(stage, StageResult.Failed);
    }

    public void buildingBuildInstance(Stage stage) {
        if (!stage.getJobInstances().isEmpty()) {
            JobInstance jobInstance = stage.getJobInstances().get(0);
            jobInstance.setAgentUuid(AGENT_UUID);
            jobInstance.changeState(JobState.Building);
            jobInstanceDao.updateAssignedInfo(jobInstance);
        }
    }

    public void assignToAgent(JobInstance jobInstance, String agentId) {
        jobInstance.setAgentUuid(agentId);
        jobInstance.changeState(JobState.Assigned);
        jobInstanceDao.updateAssignedInfo(jobInstance);
    }

    public void onefailAndOnePassedBuildInstances(Stage instance) {
        final JobInstance first = instance.getJobInstances().get(0);
        final JobInstance second = instance.getJobInstances().get(1);
        first.completing(Failed);
        second.completing(Failed);
        first.completed(new Date());
        second.completed(new Date());
        jobInstanceDao.updateStateAndResult(first);
        jobInstanceDao.updateStateAndResult(second);
    }

    public void failJob(Stage stage, JobInstance instance) {
        instance.completing(Failed);
        instance.completed(new Date());
        jobInstanceDao.updateStateAndResult(instance);
        stage.calculateResult();
        updateResultInTransaction(stage, stage.getResult());
    }

    public void cancelStage(Stage stage) {
        for (JobInstance job : stage.getJobInstances()) {
            job.cancel();
            jobInstanceDao.updateStateAndResult(job);
        }
        stage.calculateResult();
        updateResultInTransaction(stage, StageResult.Cancelled);
    }

    public void buildInstanceWithDiscontinuedState(Stage instance) {
        final JobInstance first = instance.getJobInstances().get(0);
        final JobInstance second = instance.getJobInstances().get(1);
        first.completing(JobResult.Passed);
        second.changeState(JobState.Discontinued);
        second.setResult(JobResult.Passed);
        first.completed(new Date());
        jobInstanceDao.updateStateAndResult(first);
        jobInstanceDao.updateStateAndResult(second);
        updateResultInTransaction(instance, StageResult.Passed);
    }

    public void saveMaterials(final MaterialRevisions materialRevisions) {
        saveRevs(materialRevisions);
    }

    public void saveRevs(final MaterialRevisions materialRevisions) {
        final MaterialRevisions unsavedRevisions = new MaterialRevisions();
        for (MaterialRevision materialRevision : materialRevisions) {
            unsavedRevisions.addRevision(filterUnsaved(materialRevision));
        }
        if (unsavedRevisions.isEmpty()) {
            return;
        }

        transactionTemplate.execute(new TransactionCallbackWithoutResult() {
            @Override
            protected void doInTransactionWithoutResult(TransactionStatus status) {
                materialRepository.save(unsavedRevisions);
            }
        });
    }

    private MaterialRevision filterUnsaved(MaterialRevision materialRevision) {
        ArrayList<Modification> unsavedModifications = new ArrayList<>();
        for (Modification modification : materialRevision.getModifications()) {
            if (!modification.hasId()) {
                unsavedModifications.add(modification);
            }
        }
        return new MaterialRevision(materialRevision.getMaterial(), unsavedModifications);
    }

    public void execute(String sql) throws SQLException {
        Connection connection = dataSource.getConnection();
        try {
            execute(sql, connection);
        } finally {
            if (!connection.getAutoCommit()) {
                connection.commit();
            }
            connection.close();
        }
    }

    public void execute(String sql, Connection connection) throws SQLException {
        Statement stmt = null;
        try {
            stmt = connection.createStatement();
            stmt.execute(sql);
        } finally {
            if (stmt != null) {
                stmt.close();
            }
        }
    }

    static void assertNotInserted(long instanceId) {
        Assert.assertThat("Already thinks it's inserted", instanceId, is(NOT_PERSISTED));
    }

    static void assertIsInserted(long instanceId) {
        Assert.assertThat("Not inserted", instanceId, is(not(NOT_PERSISTED)));
    }

    public Pipeline schedulePipeline(PipelineConfig pipelineConfig, Clock clock) {
        return schedulePipeline(pipelineConfig, ModificationsMother.modifySomeFiles(pipelineConfig), clock);
    }

    public Pipeline schedulePipeline(PipelineConfig pipelineConfig, BuildCause buildCause, Clock clock) {
        return schedulePipeline(pipelineConfig, buildCause, GoConstants.DEFAULT_APPROVED_BY, clock);
    }

    public Pipeline schedulePipeline(PipelineConfig pipelineConfig, BuildCause buildCause, String approvedBy, final Clock clock) {
        Pipeline pipeline = instanceFactory.createPipelineInstance(pipelineConfig, buildCause, new DefaultSchedulingContext(approvedBy), md5, clock);
        return scheduleJobInstancesAndSavePipeline(pipeline);
    }

    public Pipeline schedulePipeline(PipelineConfig pipelineConfig, BuildCause buildCause, String approvedBy, final Clock clock, Map<String, ElasticProfile> profiles, Map<String, ClusterProfile> clusterProfiles) {
        Pipeline pipeline = instanceFactory.createPipelineInstance(pipelineConfig, buildCause, new DefaultSchedulingContext(approvedBy, new Agents(), profiles, clusterProfiles), md5, clock);
        return scheduleJobInstancesAndSavePipeline(pipeline);
    }

    public Pipeline schedulePipelineWithAllStages(PipelineConfig pipelineConfig, BuildCause buildCause) {
        buildCause.assertMaterialsMatch(pipelineConfig.materialConfigs());
        DefaultSchedulingContext defaultSchedulingContext = new DefaultSchedulingContext(GoConstants.DEFAULT_APPROVED_BY);
        Stages stages = new Stages();
        Pipeline pipeline = instanceFactory.createPipelineInstance(pipelineConfig, buildCause, defaultSchedulingContext, md5, new TimeProvider());
        for (StageConfig stageConfig : pipelineConfig) {
            stages.add(instanceFactory.createStageInstance(stageConfig, defaultSchedulingContext, md5, new TimeProvider()));
        }
        pipeline.setStages(stages);
        return scheduleJobInstancesAndSavePipeline(pipeline);
    }

    private Pipeline scheduleJobInstancesAndSavePipeline(Pipeline pipeline) {
        assertNotInserted(pipeline.getId());
        for (Stage stage : pipeline.getStages()) {
            for (JobInstance jobInstance : stage.getJobInstances()) {
                jobInstance.schedule();
            }
        }
        this.savePipelineWithStagesAndMaterials(pipeline);

        long pipelineId = pipeline.getId();
        assertIsInserted(pipelineId);
        return pipeline;
    }

    public Integer updateNaturalOrder(final long pipelineId, final double naturalOrder) {
        return (Integer) getHibernateTemplate().execute(new HibernateCallback() {
            @Override
            public Object doInHibernate(Session session) throws HibernateException, SQLException {
                return PipelineRepository.updateNaturalOrderForPipeline(session, pipelineId, naturalOrder);
            }
        });
    }

    public MaterialRevision addRevisionsWithModifications(Material material, Modification... modifications) {
        final MaterialRevision revision = filterUnsaved(new MaterialRevision(material, modifications));
        if (revision.getModifications().isEmpty()) {
            return revision;
        }
        transactionTemplate.execute(new TransactionCallbackWithoutResult() {
            @Override
            protected void doInTransactionWithoutResult(TransactionStatus status) {
                materialRepository.saveMaterialRevision(revision);
            }
        });
        return revision;
    }

    public void addAgent(Agent agent){
        if(agent != null){
            agentDao.saveOrUpdate(agent);
        }
    }

    public Pipeline checkinRevisionsToBuild(ManualBuild build, PipelineConfig pipelineConfig, MaterialRevision... materialRevisions) {
        return checkinRevisionsToBuild(build, pipelineConfig, Arrays.asList(materialRevisions));
    }

    public Pipeline checkinRevisionsToBuild(ManualBuild build, PipelineConfig pipelineConfig, List<MaterialRevision> revisions) {
        return pipelineService.save(
                instanceFactory.createPipelineInstance(pipelineConfig, build.onModifications(new MaterialRevisions(revisions), false, null), new DefaultSchedulingContext(), "md5-test",
                        new TimeProvider()));
    }

    public List<MaterialRevision> addDependencyRevisionModification(List<MaterialRevision> materialRevisions, DependencyMaterial dependencyMaterial, Pipeline... upstreams) {
        String stageName = CaseInsensitiveString.str(dependencyMaterial.getStageName());
        String label = upstreams[0].getLabel();
        List<Modification> modifications = new ArrayList<>();
        for (Pipeline upstream : upstreams) {
            modifications.add(new Modification(new Date(),
                    DependencyMaterialRevision.create(CaseInsensitiveString.str(dependencyMaterial.getPipelineName()), upstream.getCounter(), label, stageName, upstream.findStage(stageName
                    ).getCounter()).getRevision(),
                    label, upstream.getId()));
        }
        MaterialRevision depRev = addRevisionsWithModifications(dependencyMaterial, modifications.toArray(new Modification[0]));
        materialRevisions.add(depRev);
        return Arrays.asList(depRev);
    }

    public void addJobAgentMetadata(JobAgentMetadata jobAgentMetadata) {
        jobAgentMetadataDao.save(jobAgentMetadata);
    }
}


text:
package javax.usb;

/**
 * Exception indicating a device has been disconnected.
 * <p>
 * This indicates the device has been disconnected from the system.  This
 * is a terminal error; the UsbDevice and subcomponents are no longer usable.
 * If the physical device is reconnected, a new UsbDevice (and subcomponents)
 * will be created.
 * @author Dan Streetman
 */
public class UsbDisconnectedException extends RuntimeException
{
	/**
	 * Constructor.
	 */
	public UsbDisconnectedException() { super(); }

	/**
	 * Constructor.
	 * @param s The detail message.
	 */
	public UsbDisconnectedException(String s) { super(s); }
}