text:
'use strict';

var _ = require('_');
var ash = require('ash');
var TodoItem = require('./TodoItem');

var toggleCompleteAll = require('../actions/toggleCompleteAll');

var MainSection = ash.Component.create({
	name: 'MainSection',

	render: function () {
		if (!_.keys(this.props.allTodos).length) {
			return null;
		}

		var todos = [];

		_.forOwn(this.props.allTodos, function (value, key, object) {
			todos.push(new TodoItem({
				key: key,
				todo: value
			}));
		});

		return ash.e('section', null, [ash.e('input', {
			id: 'toggle-all',
			type: 'checkbox',
			checked: this.props.areAllComplete ? 'checked' : '',
			events: {
				'change': this.onToggleCompleteAll
			}
		}), ash.e('label', {
			'for': 'toggle-all'
		}, 'Mark as complete'), ash.e('ul', {
			id: 'todo-list'
		}, todos)]);
	},

	onToggleCompleteAll: function () {
		toggleCompleteAll.trigger();
	}
});

module.exports = MainSection;


text:
package ofputil

import (
	"github.com/netrack/openflow/ofp"
)

// ActionsApply returns a list of instructions with a single element used
// to apply the set of specified actions.
func ActionsApply(actions ...ofp.Action) ofp.Instructions {
	return ofp.Instructions{&ofp.InstructionApplyActions{actions}}
}

// ActionsWrite returns a list of instructions with a single element used
// to write the set of specified actions.
func ActionsWrite(actions ...ofp.Action) ofp.Instructions {
	return ofp.Instructions{&ofp.InstructionWriteActions{actions}}
}

// ActionsClear returns a list of instructions with a single element used
// to clear actions.
func ActionsClear() ofp.Instructions {
	return ofp.Instructions{&ofp.InstructionClearActions{}}
}

redpajama_set_name: RedPajamaGithub


text:
Garbage collector statistics

                GC Live Data Size/GC Max Data Size ({{ garbageCollectorMetrics['jvm.gc.live.data.size'] / 1048576 | number: '1.0-0' }}M /
                {{ garbageCollectorMetrics['jvm.gc.max.data.size'] / 1048576 | number: '1.0-0' }}M)

            <ngb-progressbar
                [max]="garbageCollectorMetrics['jvm.gc.max.data.size']"
                [value]="garbageCollectorMetrics['jvm.gc.live.data.size']"
                [striped]="true"
                [animated]="false"
                type="success"
            >
                 {{ (100 * garbageCollectorMetrics['jvm.gc.live.data.size']) / garbageCollectorMetrics['jvm.gc.max.data.size'] | number: '1.0-2' }}%
            </ngb-progressbar>

                GC Memory Promoted/GC Memory Allocated ({{ garbageCollectorMetrics['jvm.gc.memory.promoted'] / 1048576 | number: '1.0-0' }}M /
                {{ garbageCollectorMetrics['jvm.gc.memory.allocated'] / 1048576 | number: '1.0-0' }}M)

            <ngb-progressbar
                [max]="garbageCollectorMetrics['jvm.gc.memory.allocated']"
                [value]="garbageCollectorMetrics['jvm.gc.memory.promoted']"
                [striped]="true"
                [animated]="false"
                type="success"
            >
                 {{ (100 * garbageCollectorMetrics['jvm.gc.memory.promoted']) / garbageCollectorMetrics['jvm.gc.memory.allocated'] | number: '1.0-2' }}%
            </ngb-progressbar>

Classes loaded

{{ garbageCollectorMetrics.classesLoaded }}

Classes unloaded

{{ garbageCollectorMetrics.classesUnloaded }}

                    Count
                    Mean
                    Min
                    p50
                    p75
                    p95
                    p99
                    Max

                    jvm.gc.pause
                    {{ garbageCollectorMetrics['jvm.gc.pause'].count }}
                    {{ garbageCollectorMetrics['jvm.gc.pause'].mean | number: '1.0-3' }}
                    {{ garbageCollectorMetrics['jvm.gc.pause']['0.0'] | number: '1.0-3' }}
                    {{ garbageCollectorMetrics['jvm.gc.pause']['0.5'] | number: '1.0-3' }}
                    {{ garbageCollectorMetrics['jvm.gc.pause']['0.75'] | number: '1.0-3' }}
                    {{ garbageCollectorMetrics['jvm.gc.pause']['0.95'] | number: '1.0-3' }}
                    {{ garbageCollectorMetrics['jvm.gc.pause']['0.99'] | number: '1.0-3' }}
                    {{ garbageCollectorMetrics['jvm.gc.pause'].max | number: '1.0-3' }}


text:
package net.anotheria.moskito.integration.cdi.monitor;

import net.anotheria.moskito.core.calltrace.CurrentlyTracedCall;
import net.anotheria.moskito.core.calltrace.RunningTraceContainer;
import net.anotheria.moskito.core.calltrace.TraceStep;
import net.anotheria.moskito.core.calltrace.TracedCall;
import net.anotheria.moskito.core.calltrace.TracingUtil;
import net.anotheria.moskito.core.dynamic.IOnDemandStatsFactory;
import net.anotheria.moskito.core.dynamic.OnDemandStatsProducer;
import net.anotheria.moskito.core.predefined.ServiceStats;
import net.anotheria.moskito.core.predefined.ServiceStatsFactory;
import net.anotheria.moskito.integration.cdi.AbstractInterceptor;

import javax.interceptor.AroundInvoke;
import javax.interceptor.AroundTimeout;
import javax.interceptor.Interceptor;
import javax.interceptor.InvocationContext;
import java.io.Serializable;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * Monitor interceptor.
 *
 * @author Alex Osadchy
 */
@Monitor
@Interceptor
public class MonitorInterceptor extends AbstractInterceptor<ServiceStats> implements Serializable {

    /**
     * Serial Version ID.
     */
    private static final long serialVersionUID = 1L;

    @Override
    protected final Class<ServiceStats> getStatsClass() {
        return ServiceStats.class;
    }

    @Override
    protected final IOnDemandStatsFactory<ServiceStats> getStatsFactory() {
        return ServiceStatsFactory.DEFAULT_INSTANCE;
    }

    /**
     *
     * @param ctx {@link InvocationContext}
     * @return result of the intercepted method
     * @throws Throwable
     */
    @AroundTimeout
    @AroundInvoke
    public Object intercept(final InvocationContext ctx) throws Throwable {
        final Method method = ctx.getMethod();
        final Monitor annotation = getAnnotationFromContext(ctx, Monitor.class);

        // if producer id isn't specified by client - use class name
        final String producerId = annotation.producerId().isEmpty() ? method.getDeclaringClass().getSimpleName() : annotation.producerId();

        final OnDemandStatsProducer onDemandProducer = getProducer(producerId, annotation.category(), annotation.subsystem());

        if (onDemandProducer == null) {
            return proceed(ctx);
        }

        final ServiceStats defaultStats = getDefaultStats(onDemandProducer);
        final ServiceStats methodStats = getStats(onDemandProducer, ctx.getMethod().getName());

        if (defaultStats != null)
            defaultStats.addRequest();

        if (methodStats != null)
            methodStats.addRequest();

        final TracedCall aRunningTrace = RunningTraceContainer.getCurrentlyTracedCall();
        TraceStep currentStep = null;
        final CurrentlyTracedCall currentTrace = aRunningTrace.callTraced() ? (CurrentlyTracedCall) aRunningTrace : null;
        if (currentTrace != null) {
            currentStep = currentTrace.startStep(TracingUtil.buildCall(method, ctx.getParameters()), onDemandProducer);
        }

        final long startTime = System.nanoTime();

        Object ret = null;
        try {
            ret = ctx.proceed();
            return ret;
        } catch (InvocationTargetException e) {
            if (defaultStats != null)
                defaultStats.notifyError();
            if (methodStats != null)
                methodStats.notifyError();
            if (currentStep != null)
                currentStep.setAborted();

            throw e.getCause();
        } catch (Throwable t) {
            if (defaultStats != null)
                defaultStats.notifyError();
            if (methodStats != null)
                methodStats.notifyError();
            if (currentStep != null)
                currentStep.setAborted();

            throw t;
        } finally {
            final long exTime = System.nanoTime() - startTime;

            if (defaultStats != null) {
                defaultStats.addExecutionTime(exTime);
                defaultStats.notifyRequestFinished();
            }

            if (methodStats != null) {
                methodStats.addExecutionTime(exTime);
                methodStats.notifyRequestFinished();
            }

            if (currentStep != null) {
                currentStep.setDuration(exTime);
                try {
                    currentStep.appendToCall(" = " + ret);
                } catch (Throwable t) {
                    currentStep.appendToCall(" = ERR: " + t.getMessage() + " (" + t.getClass() + ")");
                }
            }

            if (currentTrace != null) {
                currentTrace.endStep();
            }
        }
    }
}


text:
// CQuotaClient

#ifndef __CQUOTACLIENT__MULBERRY__
#define __CQUOTACLIENT__MULBERRY__

// CQuotaClient: Handles quotas for all resources

class CMbox;
class CQuotaProtocol;
class CQuotaRoot;

class CQuotaClient
{
public:
		CQuotaClient(CQuotaProtocol* owner)
			{ mOwner = owner;
			  mQuotaMbox = nil; }
		CQuotaClient(const CQuotaClient& copy, CQuotaProtocol* owner)
			{ mOwner = owner;
			  mQuotaMbox = nil; }
	virtual ~CQuotaClient() {}

	// These must be implemented by specific client
	virtual void _SetQuota(CQuotaRoot* root) = 0;			// Set quota root values on server
	virtual void _GetQuota(CQuotaRoot* root) = 0;			// Get quota root values from server
	virtual void _GetQuotaRoot(CMbox* mbox) = 0;			// Get quota roots for a mailbox

protected:
	CQuotaProtocol*	mOwner;
	CMbox*			mQuotaMbox;								// Mailbox to get quotas for

};

#endif


text:
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

from setuptools import find_packages
from setuptools import setup

from undebt import __version__

setup(
    name="undebt",
    version=__version__,
    description="A fast, straightforward, reliable tool for performing massive, automated code refactoring",
    long_description="Check out Undebt on `GitHub <https://github.com/Yelp/undebt>`_!",
    license="Copyright Yelp, Inc. 2016",
    url="https://github.com/Yelp/undebt",
    packages=find_packages(exclude=[
        "tests",
        "docs",
    ]),
    install_requires=[
        'pyparsing',
    ],
    extras_require={
        "testing": [
            "flake8",
            "pytest",
            "mock",
            "coverage",
        ],
        "cPyparsing": [
            "cPyparsing",
        ],
    },
    entry_points={
        'console_scripts': [
            'undebt = undebt.__main__:main',
        ],
    },
    classifiers=[
        "Programming Language :: Python :: 2",
        "Programming Language :: Python :: 3",
        "License :: OSI Approved :: Apache Software License",
        "Intended Audience :: Developers",
        "Topic :: Software Development",
        "Topic :: Utilities",
        "Environment :: Console",
        "Operating System :: OS Independent",
        "Development Status :: 5 - Production/Stable",
    ]
)


text:
import pytest

from mlflow.utils.autologging_utils import _get_new_training_session_class

_TrainingSession = _get_new_training_session_class()

class Parent:
    pass

class Child:
    pass

class Grandchild:
    pass

@pytest.fixture(autouse=True)
def clear_session_stack():
    yield
    _TrainingSession._session_stack.clear()

def assert_session_stack(classes):
    assert len(_TrainingSession._session_stack) == len(classes)

    for idx, (sess, (parent_clazz, clazz)) in enumerate(
        zip(_TrainingSession._session_stack, classes)
    ):
        assert sess.clazz == clazz
        if idx == 0:
            assert sess._parent is None
        else:
            assert sess._parent.clazz == parent_clazz

@pytest.fixture(params=[True, False])
def allow_children(request):
    return request.param

def test_should_log_always_returns_true_in_root_session(allow_children):
    with _TrainingSession(Parent, allow_children=allow_children) as p:
        assert_session_stack([(None, Parent)])
        assert p.should_log()

    assert_session_stack([])

def test_nested_sessions(allow_children):
    with _TrainingSession(Parent, allow_children=allow_children) as p:
        assert_session_stack([(None, Parent)])

        with _TrainingSession(Child, allow_children=True) as c:
            assert_session_stack([(None, Parent), (Parent, Child)])
            assert p.should_log()
            assert c.should_log() == allow_children

        assert_session_stack([(None, Parent)])
    assert_session_stack([])

def test_session_is_active():
    assert not _TrainingSession.is_active()
    with _TrainingSession(Parent, allow_children=True):
        assert _TrainingSession.is_active()

        with _TrainingSession(Child, allow_children=False):
            assert _TrainingSession.is_active()

        assert _TrainingSession.is_active()

    assert_session_stack([])
    assert not _TrainingSession.is_active()

def test_parent_session_overrides_child_session():
    with _TrainingSession(Parent, allow_children=False) as p:
        assert_session_stack([(None, Parent)])

        with _TrainingSession(Child, allow_children=True) as c:
            assert_session_stack([(None, Parent), (Parent, Child)])

            with _TrainingSession(Grandchild, allow_children=True) as g:
                assert_session_stack([(None, Parent), (Parent, Child), (Child, Grandchild)])

                assert p.should_log()
                assert not c.should_log()
                assert not g.should_log()

            assert_session_stack([(None, Parent), (Parent, Child)])
        assert_session_stack([(None, Parent)])
    assert_session_stack([])

def test_should_log_returns_false_when_parrent_session_has_the_same_class():
    # This test case corresponds to when Pipeline.fit() calls Transformer.fit_transform()
    # which calls Transformer.fit()
    with _TrainingSession(Parent, allow_children=True) as p:
        assert_session_stack([(None, Parent)])

        with _TrainingSession(Child, allow_children=True) as c1:
            assert_session_stack([(None, Parent), (Parent, Child)])

            with _TrainingSession(Child, allow_children=True) as c2:
                assert_session_stack([(None, Parent), (Parent, Child), (Child, Child)])

                assert p.should_log()
                assert c1.should_log()
                assert not c2.should_log()

            assert_session_stack([(None, Parent), (Parent, Child)])
        assert_session_stack([(None, Parent)])
    assert_session_stack([])


text:
using NUnit.Framework;
using Qiniu.JSON;

namespace Qiniu.UnitTest
{
    [TestFixture]
    public class JsonHelperTest
    {
        [Test]
        public void SerializeTest()
        {
            var putPolicy = new Qiniu.IO.Model.PutPolicy()
            {
                Scope = "test:file-1",
                CallbackUrl = "http://a.bb.ccc/dddd",
                CallbackBodyType = Qiniu.Http.ContentType.APPLICATION_JSON,
                CallbackBody = "Key = $(key), Name = x:name",
                CallbackHost = "0.0.0.0",
                DetectMime = null,
                DeleteAfterDays =1,
                EndUser = "USER",
                FsizeMin = 1000,
                FsizeLimit = 100000,
                InsertOnly = null,
                MimeLimit = "image/*",
                PersistentOps = "OPS",
                PersistentNotifyUrl = "http://notifyurl",
                PersistentPipeline = "PIPELINE",
                ReturnUrl = "http://return",
                ReturnBody = "RETURN",
                SaveKey = "file-1",
            };

            putPolicy.SetExpires(3600);

            JsonHelper.JsonSerializer = new AnotherJsonSerializer();

            string jstr = JsonHelper.Serialize(putPolicy);

            Assert.IsNotNull(jstr);
        }

        [Test]
        public void DeserializeTest()
        {
            string jstr = "{ \"scope\":\"test\", \"deadline\":12345 }";
            Qiniu.IO.Model.PutPolicy putPolicy = null;

            JsonHelper.JsonDeserializer = new AnotherJsonDeserializer();

            bool ok = JsonHelper.Deserialize(jstr,out putPolicy);

            Assert.IsTrue(ok);
            Assert.IsNotNull(putPolicy);
        }

    }

    class AnotherJsonSerializer:IJsonSerializer
    {
        public string Serialize<T>(T obj) where T:new()
        {
            var settings = new Newtonsoft.Json.JsonSerializerSettings();
            settings.ContractResolver = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver();
            settings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore;
            return Newtonsoft.Json.JsonConvert.SerializeObject(obj, settings);
        }
    }

    class AnotherJsonDeserializer:IJsonDeserializer
    {
        public bool Deserialize<T>(string str, out T obj) where T : new()
        {
            obj = default(T);

            bool ok = true;

            try
            {
                obj = Newtonsoft.Json.JsonConvert.DeserializeObject<T>(str);
            }
            catch (System.Exception)
            {
                ok = false;
            }

            return ok;
        }
    }

}


text:
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//
// Give information about a lot of media files
// Dispatch the file to be tested by all containers
//
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

//---------------------------------------------------------------------------
#ifndef Reader_FileH
#define Reader_FileH
//---------------------------------------------------------------------------

//---------------------------------------------------------------------------
#include "MediaInfo/Reader/Reader__Base.h"
#include "ZenLib/File.h"
//---------------------------------------------------------------------------

namespace MediaInfoLib
{

//***************************************************************************
/// @brief Reader_File
//***************************************************************************

class Reader_File : public Reader__Base
{
public :
    //Constructor/Destructor
    virtual ~Reader_File() {}

    //Format testing
    size_t Format_Test(MediaInfo_Internal* MI, String File_Name);
    size_t Format_Test_PerParser(MediaInfo_Internal* MI, const String &File_Name);
    size_t Format_Test_PerParser_Continue (MediaInfo_Internal* MI);
    size_t Format_Test_PerParser_Seek (MediaInfo_Internal* MI, size_t Method, int64u Value, int64u ID);

    ZenLib::File F;
    std::bitset<32> Status;
    int64u          Partial_Begin;
    int64u          Partial_End;
};

} //NameSpace
#endif


text:
package com.pip.restservicebootstrap.dao;

import com.pip.restservicebootstrap.model.User;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;

import java.util.List;

/**
 * Created by phsabo on 1/26/14.
 */
public class DataAccess {

	private static DataAccess dataAccess = null;
	private SessionFactory sessionFactory = null;

	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

	public static synchronized DataAccess getInstance() {
		if(dataAccess == null) {
			dataAccess = new DataAccess();
		}
		return dataAccess;
	}

	public List<User> getAllUsers(){
		Session session = sessionFactory.getCurrentSession();
		List<User> users = null;
		try {
			users = session.createCriteria(User.class).list();
		}
		catch (HibernateException e) {
			e.printStackTrace();
		}
		return users;
	}

	public Object getObjectByID(Class objectClass, int id) {
		Session session = sessionFactory.getCurrentSession();
		Object o = null;
		try {
			o = session.createCriteria(objectClass).add(Restrictions.eq("id",id)).uniqueResult();
		}
		catch (HibernateException e) {
			e.printStackTrace();
		}
		return o;
	}
}


text:
package org.w3c.domts.level1.core;

import org.w3c.dom.*;

import org.w3c.domts.DOMTestCase;
import org.w3c.domts.DOMTestDocumentBuilderFactory;

/**
 *     The "getNodeType()" method for a Processing Instruction
 *     node returns the constant value 7.
 *
 *     Retrieve a NodeList of child elements from the document.
 *     Retrieve the first child and invoke the "getNodeType()"
 *     method.   The method should return 7.
* @author NIST
* @author Mary Brady
* @see http://www.w3.org/TR/1998/REC-DOM-Level-1-19981001/level-one-core#ID-111237558
*/
public final class nodeprocessinginstructionnodetype extends DOMTestCase {

   /**
    * Constructor.
    * @param factory document factory, may not be null
    * @throws org.w3c.domts.DOMTestIncompatibleException Thrown if test is not compatible with parser configuration
    */
   public nodeprocessinginstructionnodetype(final DOMTestDocumentBuilderFactory factory)  throws org.w3c.domts.DOMTestIncompatibleException {
      super(factory);

    //
    //   check if loaded documents are supported for content type
    //
    String contentType = getContentType();
    preload(contentType, "staff", false);
    }

   /**
    * Runs the test case.
    * @throws Throwable Any uncaught exception causes test to fail
    */
   public void runTest() throws Throwable {
      Document doc;
      NodeList testList;
      Node piNode;
      int nodeType;
      doc = (Document) load("staff", false);
      testList = doc.getChildNodes();
      piNode = testList.item(0);
      nodeType = (int) piNode.getNodeType();
      assertEquals("nodeProcessingInstructionNodeTypeAssert1", 7, nodeType);
      }
   /**
    *  Gets URI that identifies the test.
    *  @return uri identifier of test
    */
   public String getTargetURI() {
      return "http://www.w3.org/2001/DOM-Test-Suite/level1/core/nodeprocessinginstructionnodetype";
   }
   /**
    * Runs this test from the command line.
    * @param args command line arguments
    */
   public static void main(final String[] args) {
        DOMTestCase.doMain(nodeprocessinginstructionnodetype.class, args);
   }
}


text:
package hudson.model;

import hudson.diagnosis.OldDataMonitor;
import hudson.model.Queue.Task;
import hudson.model.queue.FoldableAction;
import hudson.util.XStream2;
import org.kohsuke.stapler.export.Exported;
import org.kohsuke.stapler.export.ExportedBean;
import com.thoughtworks.xstream.converters.UnmarshallingContext;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import jenkins.model.RunAction2;

@ExportedBean
public class CauseAction implements FoldableAction, RunAction2 {
    /**
     * @deprecated since 2009-02-28
     */
    @Deprecated
    // there can be multiple causes, so this is deprecated
    private transient Cause cause;

    private List<Cause> causes = new ArrayList<Cause>();

    public CauseAction(Cause c) {
   		this.causes.add(c);
   	}

    public CauseAction(Cause... c) {
   		this(Arrays.asList(c));
   	}

    public CauseAction(Collection<? extends Cause> causes) {
   		this.causes.addAll(causes);
   	}

   	public CauseAction(CauseAction ca) {
   		this.causes.addAll(ca.causes);
   	}

	@Exported(visibility=2)
	public List<Cause> getCauses() {
		return causes;
	}

    /**
     * Finds the cause of the specific type.
     */
    public <T extends Cause> T findCause(Class<T> type) {
        for (Cause c : causes)
            if (type.isInstance(c))
                return type.cast(c);
        return null;
    }

	public String getDisplayName() {
		return "Cause";
	}

	public String getIconFileName() {
		// no icon
		return null;
	}

	public String getUrlName() {
		return "cause";
	}

    /**
     * Get list of causes with duplicates combined into counters.
     * @return Map of Cause to number of occurrences of that Cause
     */
    public Map<Cause,Integer> getCauseCounts() {
        Map<Cause,Integer> result = new LinkedHashMap<Cause,Integer>();
        for (Cause c : causes) {
            Integer i = result.get(c);
            result.put(c, i == null ? 1 : i.intValue() + 1);
        }
        return result;
    }

    /**
     * @deprecated as of 1.288
     *      but left here for backward compatibility.
     */
    public String getShortDescription() {
        if(causes.isEmpty())    return "N/A";
        return causes.get(0).getShortDescription();
    }

    @Override public void onLoad(Run<?,?> r) {
        // noop
    }

    /**
     * When hooked up to build, notify {@link Cause}s.
     */
    @Override public void onAttached(Run<?,?> owner) {
        if (owner instanceof AbstractBuild) {// this should be always true but being defensive here
            AbstractBuild b = (AbstractBuild) owner;
            for (Cause c : causes) {
                c.onAddedTo(b);
            }
        }
    }

    public void foldIntoExisting(hudson.model.Queue.Item item, Task owner, List<Action> otherActions) {
        CauseAction existing = item.getAction(CauseAction.class);
        if (existing!=null) {
            existing.causes.addAll(this.causes);
            return;
        }
        // no CauseAction found, so add a copy of this one
        item.getActions().add(new CauseAction(this));
    }

    public static class ConverterImpl extends XStream2.PassthruConverter<CauseAction> {
        public ConverterImpl(XStream2 xstream) { super(xstream); }
        @Override protected void callback(CauseAction ca, UnmarshallingContext context) {
            // if we are being read in from an older version
            if (ca.cause != null) {
                if (ca.causes == null) ca.causes = new ArrayList<Cause>();
                ca.causes.add(ca.cause);
                OldDataMonitor.report(context, "1.288");
            }
        }
    }
}


text:
from django.http import HttpResponse
from django.shortcuts import render

def index(request):
	return render(request, 'mainpage/index.html')
	#return HttpResponse('Hello world from Django!')


text:
class SevenGallery::Gallery < ActiveRecord::Base
  include SevenGallery::Concerns::Gallery
  belongs_to :item, :class_name => 'SevenPortfolio::Item'
end


text:
using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;

namespace ErrorProne.NET.Extensions
{
    public static class EnumerableExtensions
    {
        public static HashSet<T> ToHashSet<T>(this IEnumerable<T> sequence)
        {
            return new HashSet<T>(sequence);
        }

        public static Dictionary<TKey, TValue> ToDictionarySafe<T, TKey, TValue>(this IEnumerable<T> sequence,
            Func<T, TKey> keySelector, Func<T, TValue> valueSelector)
        {
            Contract.Requires(sequence != null);
            Contract.Requires(keySelector != null);
            Contract.Requires(valueSelector != null);

            var result = new Dictionary<TKey, TValue>();

            foreach (var e in sequence)
            {
                var key = keySelector(e);
                var value = valueSelector(e);
                if (!result.ContainsKey(key))
                {
                    result.Add(key, value);
                }
            }

            return result;
        }
    }
}


text:
'use strict';

/**
 * @ngdoc function
 * @name artgalleryApp.controller:AboutCtrl
 * @description
 * # AboutCtrl
 * Controller of the artgalleryApp
 */
angular.module('artgalleryApp')
  .controller('AboutCtrl', function ($scope) {
    $scope.awesomeThings = [
      'HTML5 Boilerplate',
      'AngularJS',
      'Karma'
    ];
  });


text:
#include "webrtc/modules/rtp_rtcp/source/fec_receiver_impl.h"

#include <assert.h>

#include "webrtc/modules/rtp_rtcp/source/rtp_receiver_video.h"
#include "webrtc/modules/rtp_rtcp/source/rtp_utility.h"
#include "webrtc/system_wrappers/interface/critical_section_wrapper.h"
#include "webrtc/system_wrappers/interface/scoped_ptr.h"
#include "webrtc/system_wrappers/interface/logging.h"

// RFC 5109
namespace webrtc {

FecReceiver* FecReceiver::Create(RtpData* callback) {
  return new FecReceiverImpl(callback);
}

FecReceiverImpl::FecReceiverImpl(RtpData* callback)
    : crit_sect_(CriticalSectionWrapper::CreateCriticalSection()),
      recovered_packet_callback_(callback),
      fec_(new ForwardErrorCorrection()) {}

FecReceiverImpl::~FecReceiverImpl() {
  while (!received_packet_list_.empty()) {
    delete received_packet_list_.front();
    received_packet_list_.pop_front();
  }
  if (fec_ != NULL) {
    fec_->ResetState(&recovered_packet_list_);
    delete fec_;
  }
}

//     0                   1                    2                   3
//     0 1 2 3 4 5 6 7 8 9 0 1 2 3  4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
//    +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
//    |F|   block PT  |  timestamp offset         |   block length    |
//    +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
//
//
// RFC 2198          RTP Payload for Redundant Audio Data    September 1997
//
//    The bits in the header are specified as follows:
//
//    F: 1 bit First bit in header indicates whether another header block
//        follows.  If 1 further header blocks follow, if 0 this is the
//        last header block.
//        If 0 there is only 1 byte RED header
//
//    block PT: 7 bits RTP payload type for this block.
//
//    timestamp offset:  14 bits Unsigned offset of timestamp of this block
//        relative to timestamp given in RTP header.  The use of an unsigned
//        offset implies that redundant data must be sent after the primary
//        data, and is hence a time to be subtracted from the current
//        timestamp to determine the timestamp of the data for which this
//        block is the redundancy.
//
//    block length:  10 bits Length in bytes of the corresponding data
//        block excluding header.

int32_t FecReceiverImpl::AddReceivedRedPacket(
    const RTPHeader& header, const uint8_t* incoming_rtp_packet,
    int packet_length, uint8_t ulpfec_payload_type) {
  CriticalSectionScoped cs(crit_sect_.get());
  uint8_t REDHeaderLength = 1;
  uint16_t payload_data_length = packet_length - header.headerLength;

  // Add to list without RED header, aka a virtual RTP packet
  // we remove the RED header

  ForwardErrorCorrection::ReceivedPacket* received_packet =
      new ForwardErrorCorrection::ReceivedPacket;
  received_packet->pkt = new ForwardErrorCorrection::Packet;

  // get payload type from RED header
  uint8_t payload_type =
      incoming_rtp_packet[header.headerLength] & 0x7f;

  received_packet->is_fec = payload_type == ulpfec_payload_type;
  received_packet->seq_num = header.sequenceNumber;

  uint16_t blockLength = 0;
  if (incoming_rtp_packet[header.headerLength] & 0x80) {
    // f bit set in RED header
    REDHeaderLength = 4;
    uint16_t timestamp_offset =
        (incoming_rtp_packet[header.headerLength + 1]) << 8;
    timestamp_offset +=
        incoming_rtp_packet[header.headerLength + 2];
    timestamp_offset = timestamp_offset >> 2;
    if (timestamp_offset != 0) {
      // |timestampOffset| should be 0. However, it's possible this is the first
      // location a corrupt payload can be caught, so don't assert.
      LOG(LS_WARNING) << "Corrupt payload found.";
      delete received_packet;
      return -1;
    }

    blockLength =
        (0x03 & incoming_rtp_packet[header.headerLength + 2]) << 8;
    blockLength += (incoming_rtp_packet[header.headerLength + 3]);

    // check next RED header
    if (incoming_rtp_packet[header.headerLength + 4] & 0x80) {
      // more than 2 blocks in packet not supported
      delete received_packet;
      assert(false);
      return -1;
    }
    if (blockLength > payload_data_length - REDHeaderLength) {
      // block length longer than packet
      delete received_packet;
      assert(false);
      return -1;
    }
  }

  ForwardErrorCorrection::ReceivedPacket* second_received_packet = NULL;
  if (blockLength > 0) {
    // handle block length, split into 2 packets
    REDHeaderLength = 5;

    // copy the RTP header
    memcpy(received_packet->pkt->data, incoming_rtp_packet,
           header.headerLength);

    // replace the RED payload type
    received_packet->pkt->data[1] &= 0x80;  // reset the payload
    received_packet->pkt->data[1] +=
        payload_type;                       // set the media payload type

    // copy the payload data
    memcpy(
        received_packet->pkt->data + header.headerLength,
        incoming_rtp_packet + header.headerLength + REDHeaderLength,
        blockLength);

    received_packet->pkt->length = blockLength;

    second_received_packet = new ForwardErrorCorrection::ReceivedPacket;
    second_received_packet->pkt = new ForwardErrorCorrection::Packet;

    second_received_packet->is_fec = true;
    second_received_packet->seq_num = header.sequenceNumber;

    // copy the FEC payload data
    memcpy(second_received_packet->pkt->data,
           incoming_rtp_packet + header.headerLength +
               REDHeaderLength + blockLength,
           payload_data_length - REDHeaderLength - blockLength);

    second_received_packet->pkt->length =
        payload_data_length - REDHeaderLength - blockLength;

  } else if (received_packet->is_fec) {
    // everything behind the RED header
    memcpy(
        received_packet->pkt->data,
        incoming_rtp_packet + header.headerLength + REDHeaderLength,
        payload_data_length - REDHeaderLength);
    received_packet->pkt->length = payload_data_length - REDHeaderLength;
    received_packet->ssrc =
        RtpUtility::BufferToUWord32(&incoming_rtp_packet[8]);

  } else {
    // copy the RTP header
    memcpy(received_packet->pkt->data, incoming_rtp_packet,
           header.headerLength);

    // replace the RED payload type
    received_packet->pkt->data[1] &= 0x80;  // reset the payload
    received_packet->pkt->data[1] +=
        payload_type;                       // set the media payload type

    // copy the media payload data
    memcpy(
        received_packet->pkt->data + header.headerLength,
        incoming_rtp_packet + header.headerLength + REDHeaderLength,
        payload_data_length - REDHeaderLength);

    received_packet->pkt->length =
        header.headerLength + payload_data_length - REDHeaderLength;
  }

  if (received_packet->pkt->length == 0) {
    delete second_received_packet;
    delete received_packet;
    return 0;
  }

  received_packet_list_.push_back(received_packet);
  if (second_received_packet) {
    received_packet_list_.push_back(second_received_packet);
  }
  return 0;
}

int32_t FecReceiverImpl::ProcessReceivedFec() {
  crit_sect_->Enter();
  if (!received_packet_list_.empty()) {
    // Send received media packet to VCM.
    if (!received_packet_list_.front()->is_fec) {
      ForwardErrorCorrection::Packet* packet =
          received_packet_list_.front()->pkt;
      crit_sect_->Leave();
      if (!recovered_packet_callback_->OnRecoveredPacket(packet->data,
                                                         packet->length)) {
        return -1;
      }
      crit_sect_->Enter();
    }
    if (fec_->DecodeFEC(&received_packet_list_, &recovered_packet_list_) != 0) {
      crit_sect_->Leave();
      return -1;
    }
    assert(received_packet_list_.empty());
  }
  // Send any recovered media packets to VCM.
  ForwardErrorCorrection::RecoveredPacketList::iterator it =
      recovered_packet_list_.begin();
  for (; it != recovered_packet_list_.end(); ++it) {
    if ((*it)->returned)  // Already sent to the VCM and the jitter buffer.
      continue;
    ForwardErrorCorrection::Packet* packet = (*it)->pkt;
    crit_sect_->Leave();
    if (!recovered_packet_callback_->OnRecoveredPacket(packet->data,
                                                       packet->length)) {
      return -1;
    }
    crit_sect_->Enter();
    (*it)->returned = true;
  }
  crit_sect_->Leave();
  return 0;
}

}  // namespace webrtc


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.zaradai</groupId>
    <artifactId>lattrac</artifactId>
    <version>0.1-SNAPSHOT</version>

    <name>${project.groupId}:${project.artifactId}</name>
    <description>Latency tracing service</description>
    <packaging>pom</packaging>
    <inceptionYear>2015</inceptionYear>
    <url>https://github.com/zaradai/lattrac</url>

    <developers>
        <developer>
            <id>Zaradai</id>
            <name>Stephen Hough</name>
            <email>stephen.c.hough@gmail.com</email>
            <organization>Zaradai</organization>
            <organizationUrl>https://github.com/zaradai</organizationUrl>
            <timezone>+8</timezone>
            <roles>
                <role>developer</role>
            </roles>
        </developer>
    </developers>

    <licenses>
        <license>
            <name>The Apache Software License, Version 2.0</name>
            <url>http://www.apache.org/licenses/LICENSE-2.0.txt</url>
            <distribution>repo</distribution>
            <comments>A business-friendly OSS license</comments>
        </license>
    </licenses>

    <organization>
        <name>Zaradai</name>
        <url>https://github.com/zaradai</url>
    </organization>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <javac.target>1.8</javac.target>
        <scala.version>2.11.5</scala.version>
        <!-- Project dependencies -->
        <scalalogging.version>2.1.2</scalalogging.version>
        <logback.version>1.1.2</logback.version>
        <slf4j.version>1.7.7</slf4j.version>
        <joda.version>2.7</joda.version>
        <joda.convert.version>1.2</joda.convert.version>
        <casbah.version>2.8.0</casbah.version>
        <disruptor.version>3.3.2</disruptor.version>
        <guava.version>17.0</guava.version>
        <google.jsr305.version>2.0.3</google.jsr305.version>
        <!-- Test -->
        <scalatest.version>2.3.0-SNAP2</scalatest.version>
        <mockito.version>1.9.5</mockito.version>
        <!-- Plugins -->
        <scala.plugin.version>3.1.6</scala.plugin.version>
        <scalatest.plugin.version>1.0</scalatest.plugin.version>
        <surefire.plugin.version>2.7</surefire.plugin.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.scala-lang</groupId>
            <artifactId>scala-library</artifactId>
            <version>${scala.version}</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>log4j-over-slf4j</artifactId>
            <version>${slf4j.version}</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>${slf4j.version}</version>
        </dependency>
        <dependency>
            <groupId>com.typesafe.scala-logging</groupId>
            <artifactId>scala-logging-slf4j_2.11</artifactId>
            <version>${scalalogging.version}</version>
        </dependency>
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-core</artifactId>
            <version>${logback.version}</version>
        </dependency>
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
            <version>${logback.version}</version>
        </dependency>
        <dependency>
            <groupId>joda-time</groupId>
            <artifactId>joda-time</artifactId>
            <version>${joda.version}</version>
        </dependency>
        <dependency>
            <groupId>org.joda</groupId>
            <artifactId>joda-convert</artifactId>
            <version>${joda.convert.version}</version>
        </dependency>
        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>${guava.version}</version>
        </dependency>
        <dependency>
            <groupId>com.google.code.findbugs</groupId>
            <artifactId>jsr305</artifactId>
            <version>${google.jsr305.version}</version>
        </dependency>
        <dependency>
            <groupId>com.lmax</groupId>
            <artifactId>disruptor</artifactId>
            <version>${disruptor.version}</version>
        </dependency>
        <dependency>
            <groupId>org.mongodb</groupId>
            <artifactId>casbah_2.11</artifactId>
            <version>${casbah.version}</version>
        </dependency>
        <dependency>
            <groupId>com.novus</groupId>
            <artifactId>salat_2.11</artifactId>
            <version>1.9.9</version>
        </dependency>
        <dependency>
            <groupId>com.espertech</groupId>
            <artifactId>esper</artifactId>
            <version>5.2.0</version>
        </dependency>
        <!-- Testing dependencies -->
        <dependency>
            <groupId>org.scalatest</groupId>
            <artifactId>scalatest-all_2.11</artifactId>
            <version>${scalatest.version}</version>
        </dependency>
        <dependency>
            <groupId>org.mockito</groupId>
            <artifactId>mockito-all</artifactId>
            <version>${mockito.version}</version>
        </dependency>
    </dependencies>

    <build>
        <pluginManagement>
            <plugins>
                <plugin>
                    <groupId>net.alchim31.maven</groupId>
                    <artifactId>scala-maven-plugin</artifactId>
                    <version>${scala.plugin.version}</version>
                    <executions>
                        <execution>
                            <goals>
                                <goal>add-source</goal>
                                <goal>compile</goal>
                                <goal>testCompile</goal>
                            </goals>
                        </execution>
                    </executions>
                    <configuration>
                        <displayCmd>true</displayCmd>
                        <scalaVersion>${scala.version}</scalaVersion>
                        <sourceDir>src/main/scala</sourceDir>
                        <testSourceDir>src/test/scala</testSourceDir>
                    </configuration>
                </plugin>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-surefire-plugin</artifactId>
                    <version>${surefire.plugin.version}</version>
                    <configuration>
                        <skipTests>true</skipTests>
                    </configuration>
                </plugin>
                <plugin>
                    <groupId>org.scalatest</groupId>
                    <artifactId>scalatest-maven-plugin</artifactId>
                    <version>${scalatest.plugin.version}</version>
                    <configuration>
                        <reportsDirectory>${project.build.directory}/surefire-reports</reportsDirectory>
                        <junitxml>.</junitxml>
                    </configuration>
                    <executions>
                        <execution>
                            <id>scala-test</id>
                            <goals>
                                <goal>test</goal>
                            </goals>
                        </execution>
                    </executions>
                </plugin>
            </plugins>
        </pluginManagement>
    </build>
</project>


text:
namespace PhysX
{
	public ref class VehicleSuspensionData
	{
		internal:
			static PxVehicleSuspensionData ToUnmanaged(VehicleSuspensionData^ data);
			static VehicleSuspensionData^ ToManaged(PxVehicleSuspensionData data);

		public:
			/// <summary>
			/// Spring strength of suspension unit, specified in N m^-1. Range: (0, inf).
			/// </summary>
			property float SpringStrength;

			/// <summary>
			/// Spring damper rate of suspension unit, specified in s^-1. Range: (0, inf).
			/// </summary>
			property float SpringDamperRate;

			/// <summary>
			/// Maximum compression allowed by suspension spring, specified in m. Range: (0, inf).
			/// </summary>
			property float MaxCompression;

			/// <summary>
			/// Maximum elongation allowed by suspension spring, specified in m. Range: (0, inf).
			/// </summary>
			property float MaxDroop;

			/// <summary>
			/// Mass of vehicle that is supported by suspension spring, specified in kg. Range: (0, inf).
			/// </summary>
			property float SprungMass;
	};
};


text:
Meteor.methods({
  insertSignup: function(signup){
    signup._id = signupCollection.insert(signup);
    return signup;
  },
  removeSignup: function(signup){
    //remove associated data
    volunteerCollection.remove({signupId: signup._id});
    signupCollection.remove(signup._id);
  }
});


text:
package com.opensoc.pcapservice.rest;

import java.util.HashSet;
import java.util.Set;

import javax.ws.rs.core.Application;

import com.opensoc.pcapservice.PcapReceiverImplRestEasy;

public class JettyServiceRunner extends Application  {

	private static Set services = new HashSet();

	public  JettyServiceRunner() {
		// initialize restful services
		services.add(new PcapReceiverImplRestEasy());
	}
	@Override
	public  Set getSingletons() {
		return services;
	}
	public  static Set getServices() {
		return services;
	}
}


text:
import argparse
import h5py
from itertools import count
from mayavi import mlab
from tvtk.api import tvtk
from tvtk.common import configure_input, configure_input_data

def main(hdf5_animation_file):
    weights = None
    with h5py.File(hdf5_animation_file, 'r') as f:
        verts = f['verts'].value
        tris = f['tris'].value
        if 'weights' in f:
            weights = f['weights'].value

    pd = tvtk.PolyData(points=verts[0], polys=tris)
    normals = tvtk.PolyDataNormals(splitting=False)
    configure_input_data(normals, pd)
    actor = tvtk.Actor(mapper=tvtk.PolyDataMapper())
    configure_input(actor.mapper, normals)
    actor.property.set(edge_color=(0.5, 0.5, 0.5), ambient=0.0,
                       specular=0.15, specular_power=128., shading=True, diffuse=0.8)

    fig = mlab.figure(bgcolor=(1,1,1))
    fig.scene.add_actor(actor)

    @mlab.animate(delay=40, ui=False)
    def animation():
        for i in count():
            if weights is not None:
                w_str = ",".join(["%0.2f"] * weights.shape[1])
                print ("Frame %d Weights = " + w_str) % tuple([i] + weights[i].tolist())
            frame = i % len(verts)
            pd.points = verts[frame]
            fig.scene.render()
            yield

    a = animation()
    fig.scene.z_minus_view()
    mlab.show()

if __name__ == '__main__':
    parser = argparse.ArgumentParser(
        description='Animation viewer for hdf5 mesh animationfiles '
                    '(use import scripts to convert other formats to hdf5)')
    parser.add_argument('input_filename')
    args = parser.parse_args()
    main(args.input_filename)


text:
package org.eclipse.microprofile.openapi.tck;

import static org.hamcrest.Matchers.both;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.containsInAnyOrder;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasItems;
import static org.hamcrest.Matchers.hasKey;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.Matchers.startsWith;
import static org.hamcrest.collection.IsMapWithSize.aMapWithSize;

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

import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.RunAsClient;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.testng.annotations.Test;

import io.restassured.response.ValidatableResponse;

public class ModelReaderAppTest extends AppTestBase {
    @Deployment(name = "airlinesModelReader")
    public static WebArchive createDeployment() {
        return ShrinkWrap.create(WebArchive.class, "airlinesReader.war")
                .addPackages(true, "org.eclipse.microprofile.openapi.apps.airlines")
                .addPackages(true, "org.eclipse.microprofile.openapi.reader")
                .addAsManifestResource("microprofile-reader.properties", "microprofile-config.properties");
    }

    @RunAsClient
    @Test(dataProvider = "formatProvider")
    public void testVersion(String type) {
        ValidatableResponse vr = callEndpoint(type);
        vr.body("openapi", startsWith("3.0."));
    }

    @RunAsClient
    @Test(dataProvider = "formatProvider")
    public void testInfo(String type) {
        ValidatableResponse vr = callEndpoint(type);
        vr.body("info.title", equalTo("AirlinesRatingApp API"));
        vr.body("info.version", equalTo("1.0"));
        vr.body("info.termsOfService", equalTo("http://airlinesratingapp.com/terms"));
    }

    @RunAsClient
    @Test(dataProvider = "formatProvider")
    public void testContact(String type) {
        ValidatableResponse vr = callEndpoint(type);
        vr.body("info.contact.name", equalTo("AirlinesRatingApp API Support"));
        vr.body("info.contact.url", equalTo("http://exampleurl.com/contact"));
        vr.body("info.contact.email", equalTo("techsupport@airlinesratingapp.com"));
    }

    @RunAsClient
    @Test(dataProvider = "formatProvider")
    public void testLicense(String type) {
        ValidatableResponse vr = callEndpoint(type);
        vr.body("info.license.name", equalTo("Apache 2.0"));
        vr.body("info.license.url", equalTo("http://www.apache.org/licenses/LICENSE-2.0.html"));
    }

    @RunAsClient
    @Test(dataProvider = "formatProvider")
    public void testExternalDocumentation(String type) {
        ValidatableResponse vr = callEndpoint(type);
        vr.body("externalDocs.description", equalTo("instructions for how to deploy this app"));
        vr.body("externalDocs.url", containsString("README.md"));
    }

    @RunAsClient
    @Test(dataProvider = "formatProvider")
    public void testServer(String type) {
        ValidatableResponse vr = callEndpoint(type);
        vr.body("servers", hasSize(2));
        vr.body("servers.url", hasSize(2));

        String url = "https://{username}.gigantic-server.com:{port}/{basePath}";
        String serverPath = "servers.find { it.url == '" + url + "' }";
        vr.body(serverPath + ".description", equalTo("The production API server"));
        vr.body(serverPath + ".variables", aMapWithSize(4));
        vr.body(serverPath + ".variables.username.description", equalTo("Reviews of the app by users"));
        vr.body(serverPath + ".variables.username.default", equalTo("user1"));
        vr.body(serverPath + ".variables.username.enum", containsInAnyOrder("user1", "user2"));
        vr.body(serverPath + ".variables.port.description", equalTo("Booking data"));
        vr.body(serverPath + ".variables.port.default", equalTo("8443"));
        vr.body(serverPath + ".variables.user.description", equalTo("User data"));
        vr.body(serverPath + ".variables.user.default", equalTo("user"));
        vr.body(serverPath + ".variables.basePath.default", equalTo("v2"));

        url = "https://test-server.com:80/basePath";
        serverPath = "servers.find { it.url == '" + url + "' }";
        vr.body(serverPath + ".description", equalTo("The test API server"));

    }

    @RunAsClient
    @Test(dataProvider = "formatProvider")
    public void testOperationAirlinesResource(String type) {
        ValidatableResponse vr = callEndpoint(type);
        vr.body("paths.'/modelReader/airlines'.get.summary", equalTo("Retrieve all available airlines"));
        vr.body("paths.'/modelReader/airlines'.get.operationId", equalTo("getAirlines"));
    }

    @RunAsClient
    @Test(dataProvider = "formatProvider")
    public void testOperationAvailabilityResource(String type) {
        ValidatableResponse vr = callEndpoint(type);
        vr.body("paths.'/availability'.get.summary", equalTo("Retrieve all available flights"));
        vr.body("paths.'/availability'.get.operationId", equalTo("getFlights"));
    }

    @RunAsClient
    @Test(dataProvider = "formatProvider")
    public void testOperationBookingResource(String type) {
        ValidatableResponse vr = callEndpoint(type);
        vr.body("paths.'/modelReader/bookings'.get.summary", equalTo("Retrieve all bookings for current user"));
        vr.body("paths.'/modelReader/bookings'.get.operationId", equalTo("getAllBookings"));

        vr.body("paths.'/modelReader/bookings'.post.summary", equalTo("Create a booking"));
        vr.body("paths.'/modelReader/bookings'.post.description", equalTo("Create a new booking record with the booking information provided."));
        vr.body("paths.'/modelReader/bookings'.post.operationId", equalTo("createBooking"));
    }

    @RunAsClient
    @Test(dataProvider = "formatProvider")
    public void testAPIResponse(String type) {
        ValidatableResponse vr = callEndpoint(type);
        // @APIResponse at method level
        vr.body("paths.'/availability'.get.responses", aMapWithSize(2));
        vr.body("paths.'/availability'.get.responses.'200'.description", equalTo("successful operation"));
        vr.body("paths.'/availability'.get.responses.'404'.description", equalTo("No available flights found"));
    }

    @RunAsClient
    @Test(dataProvider = "formatProvider")
    public void testAvailabilityGetParameter(String type) {
        ValidatableResponse vr = callEndpoint(type);
        String availabilityParameters = "paths.'/availabilityModel'.get.parameters";

        vr.body(availabilityParameters, hasSize(6));
        vr.body(availabilityParameters + ".findAll { it }.name",
                hasItems("airportFrom", "returningDate", "airportTo", "numberOfAdults", "numberOfChildren"));

        vr.body(availabilityParameters + ".findAll { it.$ref == '#/components/parameters/departureDate'}", notNullValue());

        List<String[]> list = new ArrayList<String[]>();
        list.add(new String[] { "airportFrom", "Airport the customer departs from" });
        list.add(new String[] { "returningDate", "Customer return date" });
        list.add(new String[] { "airportTo", "Airport the customer returns to" });
        list.add(new String[] { "numberOfAdults", "Number of adults on the flight" });
        list.add(new String[] { "numberOfChildren", "Number of children on the flight" });

        for (int i = 0; i < list.size(); i++) {
            String currentParam = list.get(i)[0];
            String query = availabilityParameters + ".findAll { it.name == '" + currentParam + "' }";

            vr.body(query + ".in", both(hasSize(1)).and(contains("query")));
            vr.body(query + ".description", both(hasSize(1)).and(contains(list.get(i)[1])));
            vr.body(query + ".required", both(hasSize(1)).and(contains(true)));
            vr.body(query + ".schema.type", both(hasSize(1)).and(contains("string")));
        }

        vr.body(availabilityParameters + ".findAll { it.name == 'numberOfAdults' }.schema.minimum", both(hasSize(1)).and(contains(0)));
        vr.body(availabilityParameters + ".findAll { it.name == 'numberOfChildren' }.schema.minimum", both(hasSize(1)).and(contains(0)));
    }

    @RunAsClient
    @Test(dataProvider = "formatProvider")
    public void testSecurityRequirement(String type) {
        ValidatableResponse vr = callEndpoint(type);

        vr.body("paths.'/bookings'.post.security.bookingSecurityScheme[0][0]", equalTo("write:bookings"));
        vr.body("paths.'/bookings'.post.security.bookingSecurityScheme[0][1]", equalTo("read:bookings"));
        vr.body("paths.'/reviews'.post.security.bookingSecurityScheme", hasSize(1));
        vr.body("paths.'/bookings'.post.security.bookingSecurityScheme[0]", hasSize(2));
    }

    @RunAsClient
    @Test(dataProvider = "formatProvider")
    public void testSecuritySchemes(String type) {
        ValidatableResponse vr = callEndpoint(type);
        String s = "components.securitySchemes";
        vr.body(s, hasKey("httpTestScheme"));
    }

    @RunAsClient
    @Test(dataProvider = "formatProvider")
    public void testSecurityScheme(String type) {
        ValidatableResponse vr = callEndpoint(type);
        String http = "components.securitySchemes.httpTestScheme.";
        vr.body(http + "type", equalTo("http"));
        vr.body(http + "description", equalTo("user security scheme"));
        vr.body(http + "scheme", equalTo("testScheme"));
    }

    @RunAsClient
    @Test(dataProvider = "formatProvider")
    public void testSchema(String type) {
        ValidatableResponse vr = callEndpoint(type);
        // Basic properties
        vr.body("components.schemas.AirlinesRef.$ref", equalTo("#/components/schemas/Airlines"));
        vr.body("components.schemas.Airlines.title", equalTo("Airlines"));
        vr.body("paths.'/modelReader/bookings'.post.responses.'201'.content.'text/plain'.schema.type", equalTo("string"));
        vr.body("components.schemas.id.format", equalTo("int32"));
        vr.body("paths.'/modelReader/bookings'.post.responses.'201'.content.'text/plain'.schema.description", equalTo("id of the new booking"));
    }

    @RunAsClient
    @Test(dataProvider = "formatProvider")
    public void testExampleObject(String type) {
        ValidatableResponse vr = callEndpoint(type);
        // Example in Components
        vr.body("components.examples.review.summary", equalTo("External review example"));
        vr.body("components.examples.review.description", equalTo("This example exemplifies the content on our site."));
        vr.body("components.examples.review.externalValue", equalTo("http://foo.bar/examples/review-example.json"));
    }

    @RunAsClient
    @Test(dataProvider = "formatProvider")
    public void testTagDeclarations(String type) {
        ValidatableResponse vr = callEndpoint(type);
        String tagsPath = "tags.find { it.name == '";
        String desc = "' }.description";
        vr.body(tagsPath + "user" + desc, equalTo("Operations about user"));
        vr.body(tagsPath + "create" + desc, equalTo("Operations about create"));
        vr.body(tagsPath + "Airlines" + desc, equalTo("All the airlines methods"));
        vr.body(tagsPath + "Availability" + desc, equalTo("All the availability methods"));
        vr.body(tagsPath + "Get Flights" + desc, equalTo("method to retrieve all flights available"));
        vr.body(tagsPath + "Get Flights" + "' }.externalDocs.description", equalTo("A list of all the flights offered by the app"));
        vr.body(tagsPath + "Get Flights" + "' }.externalDocs.url", equalTo("http://airlinesratingapp.com/ourflights"));
        vr.body(tagsPath + "Bookings" + desc, equalTo("All the bookings methods"));
        vr.body(tagsPath + "Get Airlines" + desc, equalTo("method to get all airlines"));
        vr.body(tagsPath + "Retrieve Airlines" + desc, equalTo("method to retrieve all airlines"));
    }

    @RunAsClient
    @Test(dataProvider = "formatProvider")
    public void testTagsInOperations(String type) {
        ValidatableResponse vr = callEndpoint(type);
        vr.body("paths.'/availability'.get.tags", containsInAnyOrder("Get Flights", "Availability"));
        vr.body("paths.'/modelReader/bookings'.get.tags", containsInAnyOrder("bookings"));
    }

    @RunAsClient
    @Test(dataProvider = "formatProvider")
    public void testComponents(String type) {
        ValidatableResponse vr = callEndpoint(type);

        // Tests to ensure that the reusable items declared using the
        // @Components annotation (within @OpenAPIDefinition) exist.
        // Each of these item types are tested elsewhere, so no need to test the
        // content of them here.
        vr.body("components.schemas.Bookings", notNullValue());
        vr.body("components.schemas.Airlines", notNullValue());
        vr.body("components.schemas.AirlinesRef", notNullValue());
        vr.body("components.responses.FoundAirlines", notNullValue());
        vr.body("components.responses.FoundBookings", notNullValue());
        vr.body("components.parameters.departureDate", notNullValue());
        vr.body("components.parameters.username", notNullValue());
        vr.body("components.examples.review", notNullValue());
        vr.body("components.examples.user", notNullValue());
        vr.body("components.requestBodies.review", notNullValue());
        vr.body("components.headers.Max-Rate", notNullValue());
        vr.body("components.headers.Request-Limit", notNullValue());
        vr.body("components.securitySchemes.httpTestScheme", notNullValue());
        vr.body("components.links.UserName", notNullValue());
    }

    @RunAsClient
    @Test(dataProvider = "formatProvider")
    public void testHeaderInComponents(String type) {
        ValidatableResponse vr = callEndpoint(type);
        String maxRate = "components.headers.Max-Rate";
        vr.body(maxRate + ".description", equalTo("Maximum rate"));
        vr.body(maxRate + ".required", equalTo(true));
        vr.body(maxRate + ".deprecated", equalTo(true));
        vr.body(maxRate + ".allowEmptyValue", equalTo(true));
    }

    @RunAsClient
    @Test(dataProvider = "formatProvider")
    public void testContentInAPIResponse(String type) {
        ValidatableResponse vr = callEndpoint(type);

        String content1 = "paths.'/availability'.get.responses.'200'.content.'application/json'";
        vr.body(content1, notNullValue());
        vr.body(content1 + ".schema.type", equalTo("array"));
        vr.body(content1 + ".schema.items", notNullValue());
    }
}


text:
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    style="@style/AugLargeText"
/>


text:
(function () {

	angular
	.module('mySiteApp')
	.controller('contactCtrl', contactCtrl);

	contactCtrl.$inject = ['$window', '$scope', 'contactData'];
	function contactCtrl ($window, $scope, contactData) {
		var vm = this;
		vm.pageHeader = 'Contact page';

        //write here your publickey
        //not secret, no problem ;)
        //be careful to use the PUBLIC key and NOT the PRIVATE key!!!!!
		vm.publicKey = '- insert your public key from https://www.google.com/recaptcha/admin -';

    vm.onSubmit = function () {
    	console.log(vm.formData);

        var response = $window.grecaptcha.getResponse("");

        console.log('Response is: ' + response);

        // Build the post data with the emailFormData and the response string
        var data = {
            response: response,
            emailFormData: vm.formData
        };

        //send the form with the captcha
        //if the result is "succes" display a message
        //otherwise print an error
        contactData.sendTheFormWithCaptcha(data)
            .success(function (result) {
                vm.formResultMessage = "Success! Captcha is valid, thank you.";
                vm.error = "success";
            })
            .error(function (result) {
                vm.formResultMessage = "Invalid Captcha!";
                vm.error = "danger";
            });
    };
  }
})();


text:
package org.chavera.swm.login.beans;

public class DbBean {
	private String username;
	private String dbName;
	private String password;
	private String host;
	private int port;
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public String getDbName() {
		return dbName;
	}
	public void setDbName(String dbName) {
		this.dbName = dbName;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	public String getHost() {
		return host;
	}
	public void setHost(String host) {
		this.host = host;
	}
	public int getPort() {
		return port;
	}
	public void setPort(int port) {
		this.port = port;
	}
}


text:
<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Importing data from EEG devices — MNE 0.20.7 documentation</title>
    <link rel="stylesheet" href="../../_static/bootstrap-sphinx.css" type="text/css" />
    <link rel="stylesheet" href="../../_static/pygments.css" type="text/css" />
    <link rel="stylesheet" type="text/css" href="../../_static/graphviz.css" />
    <link rel="stylesheet" type="text/css" href="../../_static/bootstrap_divs.css" />
    <link rel="stylesheet" type="text/css" href="../../_static/gallery.css" />
    <link rel="stylesheet" type="text/css" href="../../_static/gallery-binder.css" />
    <link rel="stylesheet" type="text/css" href="../../_static/gallery-dataframe.css" />

    <link rel="shortcut icon" href="../../_static/favicon.ico"/>
    <link rel="index" title="Index" href="../../genindex.html" />
    <link rel="search" title="Search" href="../../search.html" />

    <link rel="canonical" href="https://mne.tools/stable/index.html" />

    <link rel="stylesheet" href="../../_static/style.css " type="text/css" />
    <link rel="stylesheet" href="../../_static/font-awesome.css" type="text/css" />
    <link rel="stylesheet" href="../../_static/font-source-code-pro.css" type="text/css" />
    <link rel="stylesheet" href="../../_static/font-source-sans-pro.css" type="text/css" />
    <link rel="stylesheet" href="../../_static/flag-icon.css" type="text/css" />

<meta charset='utf-8'>
<meta http-equiv='X-UA-Compatible' content='IE=edge,chrome=1'>
<meta name='viewport' content='width=device-width, initial-scale=1.0, maximum-scale=1'>
<meta name="apple-mobile-web-app-capable" content="yes">

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

        </button>

        0.20.7

Install

Overview

Tutorials

Examples

Glossary

API

Contribute

  Site

  <button type="button" class="btn btn-primary navbar-btn dropdown-toggle" id="dropdownMenu1" data-toggle="dropdown">
    v0.20.7

  </button>

Development

v0.20 (stable)

v0.19

v0.18

v0.17

v0.16

v0.15

v0.14

v0.13

v0.12

v0.11

<form class="navbar-form navbar-right" action="../../search.html" method="get">

  <input type="text" name="q" class="form-control" placeholder="Search" />

  <input type="hidden" name="check_keywords" value="yes" />
  <input type="hidden" name="area" value="default" />
</form>

Importing data from EEG devices

BrainVision (.vhdr, .vmrk, .eeg)

European data format (.edf)

BioSemi data format (.bdf)

General data format (.gdf)

Neuroscan CNT data format (.cnt)

EGI simple binary (.egi)

EGI MFF (.mff)

EEGLAB set files (.set)

Nicolet (.data)

eXimia EEG data (.nxe)

Setting EEG references

Reading electrode locations and head shapes for EEG recordings

<form action="../../search.html" method="get">

  <input type="text" name="q" class="form-control" placeholder="Search" />

  <input type="hidden" name="check_keywords" value="yes" />
  <input type="hidden" name="area" value="default" />
</form>

Note

Click here     to download the full example code

Importing data from EEG devices¶

MNE includes various functions and utilities for reading EEG
data and electrode locations.

Page contents

BrainVision (.vhdr, .vmrk, .eeg)

European data format (.edf)

BioSemi data format (.bdf)

General data format (.gdf)

Neuroscan CNT data format (.cnt)

EGI simple binary (.egi)

EGI MFF (.mff)

EEGLAB set files (.set)

Nicolet (.data)

eXimia EEG data (.nxe)

Setting EEG references

Reading electrode locations and head shapes for EEG recordings

BrainVision (.vhdr, .vmrk, .eeg)¶

The BrainVision file format consists of three separate files:

A text header file (.vhdr) containing meta data

A text marker file (.vmrk) containing information about events in the
data

A binary data file (.eeg) containing the voltage values of the EEG

Both text files are based on the
Microsoft Windows INI format
consisting of:

sections marked as [square brackets]

comments marked as ; comment

key-value pairs marked as key=value

A documentation for core BrainVision file format is provided by Brain Products.
You can view the specification hosted on the
Brain Products website

BrainVision EEG files can be read in using mne.io.read_raw_brainvision()
with the .vhdr header file as an input.

Warning

Renaming BrainVision files can be problematic due to their
multifile structure. See this
example
for an instruction.

European data format (.edf)¶

EDF and EDF+ files can be read using mne.io.read_raw_edf().

EDF (European Data Format) and
EDF+ are 16-bit formats.

The EDF+ files may contain an annotation channel which can be used to store
trigger information. These annotations are available in raw.annotations.

Saving EDF files is not supported natively yet. This gist
can be used to save any mne.io.Raw into EDF/EDF+/BDF/BDF+.

BioSemi data format (.bdf)¶

The BDF format is a 24-bit
variant of the EDF format used by EEG systems manufactured by BioSemi. It can
be imported with mne.io.read_raw_bdf().

BioSemi amplifiers do not perform "common mode noise rejection" automatically.
The signals in the EEG file are the voltages between each electrode and CMS
active electrode, which still contain some CM noise (50 Hz, ADC reference
noise, etc., see the BioSemi FAQ
for further detail).
Thus, it is advisable to choose a reference (e.g., a single channel like Cz,
average of linked mastoids, average of all electrodes, etc.) on import of
BioSemi data to avoid losing signal information. The data can be re-referenced
later after cleaning if desired.

Warning

The data samples in a BDF file are represented in a 3-byte
(24-bit) format. Since 3-byte raw data buffers are not presently
supported in the fif format these data will be changed to 4-byte
integers in the conversion.

General data format (.gdf)¶

GDF files can be read in using mne.io.read_raw_gdf().

GDF (General Data Format) is a flexible
format for biomedical signals that overcomes some of the limitations of the
EDF format. The original specification (GDF v1) includes a binary header
and uses an event table. An updated specification (GDF v2) was released in
2011 and adds fields for additional subject-specific information (gender,
age, etc.) and allows storing several physical units and other properties.
Both specifications are supported in MNE.

Neuroscan CNT data format (.cnt)¶

CNT files can be read in using mne.io.read_raw_cnt().
The channel locations can be read from a montage or the file header. If read
from the header, the data channels (channels that are not assigned to EOG, ECG,
EMG or misc) are fit to a sphere and assigned a z-value accordingly. If a
non-data channel does not fit to the sphere, it is assigned a z-value of 0.

Warning

Reading channel locations from the file header may be dangerous, as the
x_coord and y_coord in ELECTLOC section of the header do not necessarily
translate to absolute locations. Furthermore, EEG-electrode locations that
do not fit to a sphere will distort the layout when computing the z-values.
If you are not sure about the channel locations in the header, use of a
montage is encouraged.

EGI simple binary (.egi)¶

EGI simple binary files can be read in using mne.io.read_raw_egi().
The EGI raw files are simple binary files with a header and can be exported
from using the EGI Netstation acquisition software.

EGI MFF (.mff)¶

These files can also be read with mne.io.read_raw_egi().

EEGLAB set files (.set)¶

EEGLAB .set files can be read in using mne.io.read_raw_eeglab()
and mne.read_epochs_eeglab().

Nicolet (.data)¶

These files can be read with mne.io.read_raw_nicolet().

eXimia EEG data (.nxe)¶

EEG data from the Nexstim eXimia system can be read in using the
mne.io.read_raw_eximia() function.

Setting EEG references¶

The preferred method for applying an EEG reference in MNE is
mne.set_eeg_reference(), or equivalent instance methods like
raw.set_eeg_reference(). By default,
the data are assumed to already be properly referenced. See
Setting the EEG reference for more information.

Reading electrode locations and head shapes for EEG recordings¶

Some EEG formats (EGI, EDF/EDF+, BDF) neither contain electrode location
information nor head shape digitization information. Therefore, this
information has to be provided separately. For that purpose all raw instances
have a mne.io.Raw.set_montage() method to set electrode locations.

When using the locations of the fiducial points the digitization data
are converted to the MEG head coordinate system employed in the
MNE software, see MEG/EEG and MRI coordinate systems.

Estimated memory usage:  8 MB

Download Python source code: plot_20_reading_eeg_data.py

Download Jupyter notebook: plot_20_reading_eeg_data.ipynb

Gallery generated by Sphinx-Gallery

GitHub

·

Mailing list

·

Gitter

·

What's new

·

Cite MNE

Back to top

© Copyright 2012-2020, MNE Developers. Last updated on 2020-07-10.


text:
package googlecompute

import (
	"errors"
	"strings"
	"testing"
	"time"

	"github.com/mitchellh/multistep"
	"github.com/stretchr/testify/assert"
)

func TestStepCreateInstance_impl(t *testing.T) {
	var _ multistep.Step = new(StepCreateInstance)
}

func TestStepCreateInstance(t *testing.T) {
	state := testState(t)
	step := new(StepCreateInstance)
	defer step.Cleanup(state)

	state.Put("ssh_public_key", "key")

	c := state.Get("config").(*Config)
	d := state.Get("driver").(*DriverMock)
	d.GetImageResult = StubImage("test-image", "test-project", []string{}, 100)

	// run the step
	assert.Equal(t, step.Run(state), multistep.ActionContinue, "Step should have passed and continued.")

	// Verify state
	nameRaw, ok := state.GetOk("instance_name")
	assert.True(t, ok, "State should have an instance name.")

	// cleanup
	step.Cleanup(state)

	// Check args passed to the driver.
	assert.Equal(t, d.DeleteInstanceName, nameRaw.(string), "Incorrect instance name passed to driver.")
	assert.Equal(t, d.DeleteInstanceZone, c.Zone, "Incorrect instance zone passed to driver.")
	assert.Equal(t, d.DeleteDiskName, c.InstanceName, "Incorrect disk name passed to driver.")
	assert.Equal(t, d.DeleteDiskZone, c.Zone, "Incorrect disk zone passed to driver.")
}

func TestStepCreateInstance_fromFamily(t *testing.T) {
	cases := []struct {
		Name   string
		Family string
		Expect bool
	}{
		{"test-image", "", false},
		{"test-image", "test-family", false}, // name trumps family
		{"", "test-family", true},
	}

	for _, tc := range cases {
		state := testState(t)
		step := new(StepCreateInstance)
		defer step.Cleanup(state)

		state.Put("ssh_public_key", "key")

		c := state.Get("config").(*Config)
		c.SourceImage = tc.Name
		c.SourceImageFamily = tc.Family
		d := state.Get("driver").(*DriverMock)
		d.GetImageResult = StubImage("test-image", "test-project", []string{}, 100)

		// run the step
		assert.Equal(t, step.Run(state), multistep.ActionContinue, "Step should have passed and continued.")

		// cleanup
		step.Cleanup(state)

		// Check args passed to the driver.
		if tc.Expect {
			assert.True(t, d.GetImageFromFamily, "Driver wasn't instructed to use an image family")
		} else {
			assert.False(t, d.GetImageFromFamily, "Driver was unexpectedly instructed to use an image family")
		}
	}
}

func TestStepCreateInstance_windowsNeedsPassword(t *testing.T) {

	state := testState(t)
	step := new(StepCreateInstance)
	defer step.Cleanup(state)

	state.Put("ssh_public_key", "key")
	c := state.Get("config").(*Config)
	d := state.Get("driver").(*DriverMock)
	d.GetImageResult = StubImage("test-image", "test-project", []string{"windows"}, 100)
	c.Comm.Type = "winrm"
	// run the step
	if action := step.Run(state); action != multistep.ActionContinue {
		t.Fatalf("bad action: %#v", action)
	}

	// Verify state
	nameRaw, ok := state.GetOk("instance_name")
	if !ok {
		t.Fatal("should have instance name")
	}

	createPassword, ok := state.GetOk("create_windows_password")

	if !ok || !createPassword.(bool) {
		t.Fatal("should need to create a windows password")
	}

	// cleanup
	step.Cleanup(state)

	if d.DeleteInstanceName != nameRaw.(string) {
		t.Fatal("should've deleted instance")
	}
	if d.DeleteInstanceZone != c.Zone {
		t.Fatalf("bad instance zone: %#v", d.DeleteInstanceZone)
	}

	if d.DeleteDiskName != c.InstanceName {
		t.Fatal("should've deleted disk")
	}
	if d.DeleteDiskZone != c.Zone {
		t.Fatalf("bad disk zone: %#v", d.DeleteDiskZone)
	}
}

func TestStepCreateInstance_windowsPasswordSet(t *testing.T) {

	state := testState(t)
	step := new(StepCreateInstance)
	defer step.Cleanup(state)

	state.Put("ssh_public_key", "key")

	config := state.Get("config").(*Config)
	driver := state.Get("driver").(*DriverMock)
	driver.GetImageResult = StubImage("test-image", "test-project", []string{"windows"}, 100)
	config.Comm.Type = "winrm"
	config.Comm.WinRMPassword = "password"

	// run the step
	if action := step.Run(state); action != multistep.ActionContinue {
		t.Fatalf("bad action: %#v", action)
	}

	// Verify state
	nameRaw, ok := state.GetOk("instance_name")
	if !ok {
		t.Fatal("should have instance name")
	}

	_, ok = state.GetOk("create_windows_password")

	if ok {
		t.Fatal("should not need to create windows password")
	}

	// cleanup
	step.Cleanup(state)

	if driver.DeleteInstanceName != nameRaw.(string) {
		t.Fatal("should've deleted instance")
	}
	if driver.DeleteInstanceZone != config.Zone {
		t.Fatalf("bad instance zone: %#v", driver.DeleteInstanceZone)
	}

	if driver.DeleteDiskName != config.InstanceName {
		t.Fatal("should've deleted disk")
	}
	if driver.DeleteDiskZone != config.Zone {
		t.Fatalf("bad disk zone: %#v", driver.DeleteDiskZone)
	}
}

func TestStepCreateInstance_error(t *testing.T) {
	state := testState(t)
	step := new(StepCreateInstance)
	defer step.Cleanup(state)

	state.Put("ssh_public_key", "key")

	d := state.Get("driver").(*DriverMock)
	d.RunInstanceErr = errors.New("error")
	d.GetImageResult = StubImage("test-image", "test-project", []string{}, 100)

	// run the step
	assert.Equal(t, step.Run(state), multistep.ActionHalt, "Step should have failed and halted.")

	// Verify state
	_, ok := state.GetOk("error")
	assert.True(t, ok, "State should have an error.")
	_, ok = state.GetOk("instance_name")
	assert.False(t, ok, "State should not have an instance name.")
}

func TestStepCreateInstance_errorOnChannel(t *testing.T) {
	state := testState(t)
	step := new(StepCreateInstance)
	defer step.Cleanup(state)

	state.Put("ssh_public_key", "key")

	errCh := make(chan error, 1)
	errCh <- errors.New("error")

	d := state.Get("driver").(*DriverMock)
	d.RunInstanceErrCh = errCh
	d.GetImageResult = StubImage("test-image", "test-project", []string{}, 100)

	// run the step
	assert.Equal(t, step.Run(state), multistep.ActionHalt, "Step should have failed and halted.")

	// Verify state
	_, ok := state.GetOk("error")
	assert.True(t, ok, "State should have an error.")
	_, ok = state.GetOk("instance_name")
	assert.False(t, ok, "State should not have an instance name.")
}

func TestStepCreateInstance_errorTimeout(t *testing.T) {
	state := testState(t)
	step := new(StepCreateInstance)
	defer step.Cleanup(state)

	state.Put("ssh_public_key", "key")

	errCh := make(chan error, 1)

	config := state.Get("config").(*Config)
	config.stateTimeout = 1 * time.Microsecond

	d := state.Get("driver").(*DriverMock)
	d.RunInstanceErrCh = errCh
	d.GetImageResult = StubImage("test-image", "test-project", []string{}, 100)

	// run the step
	assert.Equal(t, step.Run(state), multistep.ActionHalt, "Step should have failed and halted.")

	// Verify state
	_, ok := state.GetOk("error")
	assert.True(t, ok, "State should have an error.")
	_, ok = state.GetOk("instance_name")
	assert.False(t, ok, "State should not have an instance name.")
}

func TestCreateInstanceMetadata(t *testing.T) {
	state := testState(t)
	c := state.Get("config").(*Config)
	image := StubImage("test-image", "test-project", []string{}, 100)
	key := "abcdefgh12345678"

	// create our metadata
	metadata, err := c.createInstanceMetadata(image, key)

	assert.True(t, err == nil, "Metadata creation should have succeeded.")

	// ensure our key is listed
	assert.True(t, strings.Contains(metadata["sshKeys"], key), "Instance metadata should contain provided key")
}

func TestCreateInstanceMetadata_noPublicKey(t *testing.T) {
	state := testState(t)
	c := state.Get("config").(*Config)
	image := StubImage("test-image", "test-project", []string{}, 100)
	sshKeys := c.Metadata["sshKeys"]

	// create our metadata
	metadata, err := c.createInstanceMetadata(image, "")

	assert.True(t, err == nil, "Metadata creation should have succeeded.")

	// ensure the ssh metadata hasn't changed
	assert.Equal(t, metadata["sshKeys"], sshKeys, "Instance metadata should not have been modified")
}


text:
import proto  # type: ignore

__protobuf__ = proto.module(
    package="google.ads.googleads.v11.enums",
    marshal="google.ads.googleads.v11",
    manifest={"ListingGroupFilterBiddingCategoryLevelEnum",},
)

class ListingGroupFilterBiddingCategoryLevelEnum(proto.Message):
    r"""Container for enum describing the levels of bidding category
    used in ListingGroupFilterDimension.

    """

    class ListingGroupFilterBiddingCategoryLevel(proto.Enum):
        r"""The level of the listing group filter bidding category."""
        UNSPECIFIED = 0
        UNKNOWN = 1
        LEVEL1 = 2
        LEVEL2 = 3
        LEVEL3 = 4
        LEVEL4 = 5
        LEVEL5 = 6

__all__ = tuple(sorted(__protobuf__.manifest))