text:
namespace Nancy.Tests.Unit.Bootstrapper
{
    using System;
    using System.Collections.Generic;

    using Nancy.Bootstrapper;

    using Xunit;

    public class BootstrapperLocatorFixture
    {
        /// <summary>
        /// Internal stuff
        /// </summary>
        public interface IBootstwapper
        {

        }

        /// <summary>
        /// Base
        /// </summary>
        public abstract class BootstwapperBase : IBootstwapper
        {

        }

        /// <summary>
        /// Default
        /// </summary>
        public class DefaultBootstwapper : BootstwapperBase
        {

        }

        /// <summary>
        /// Custom
        /// </summary>
        public class MyOwnDefaultBootstwapper : BootstwapperBase
        {

        }

        /// <summary>
        /// Custom
        /// </summary>
        public class MyFirstBootstwapper : DefaultBootstwapper
        {

        }

        /// <summary>
        /// Custom
        /// </summary>
        public class AnotherFirstBootstwapper : DefaultBootstwapper
        {

        }

        /// <summary>
        /// Another custom one
        /// </summary>
        public class MySecondBootstwapper: MyFirstBootstwapper
        {

        }

        /// <summary>
        /// Another custom one
        /// </summary>
        public class MyThirdBootstwapper: MyFirstBootstwapper
        {

        }

        /// <summary>
        /// Another custom one
        /// </summary>
        public class MyFourthBootstwapper : MySecondBootstwapper
        {

        }

        public class TestTypeCatalog : ITypeCatalog
        {
            private readonly IReadOnlyCollection<Type> types;

            public TestTypeCatalog(IReadOnlyCollection<Type> types)
            {
                this.types = types;
            }

            public IReadOnlyCollection<Type> GetTypesAssignableTo(Type type, TypeResolveStrategy strategy)
            {
                return types;
            }
        }

        [Fact]
        public void Should_throw_exception_when_multiple_bootstrappers_are_located()
        {
            // Given
            var list = new List<Type> { typeof(MyFirstBootstwapper), typeof(AnotherFirstBootstwapper) };
            var typeCatalog = new TestTypeCatalog(list);

            // When
            var result = Record.Exception(() => NancyBootstrapperLocator.GetBootstrapperType(typeCatalog));

            // Then
            result.ShouldNotBeNull();
            result.GetType().ShouldEqual(typeof(BootstrapperException));
        }

        [Fact]
        public void Should_resolve_bootstrapper_type_from_unique_type()
        {
            // Given
            var list = new List<Type> {typeof (MyFirstBootstwapper)};
            var typeCatalog = new TestTypeCatalog(list);

            // When
            var bootstrapperType = NancyBootstrapperLocator.GetBootstrapperType(typeCatalog);

            // Then
            bootstrapperType.ShouldEqual(typeof(MyFirstBootstwapper));
        }

        [Fact]
        public void Should_automatically_resolve_the_most_derived_bootstrapper()
        {
            // Given
            var list = new List<Type> {typeof (MyFirstBootstwapper), typeof (MySecondBootstwapper), typeof(MyFourthBootstwapper)};
            Type found;

            // When
            var res = NancyBootstrapperLocator.TryFindMostDerivedType(list, out found);

            // Then
            res.ShouldEqual(true);
            found.ShouldEqual(typeof(MyFourthBootstwapper));
        }

        [Fact]
        public void Should_return_false_when_there_are_more_than_one_most_derived_types_and_their_base_is_not_included()
        {
            // Given
            var list = new List<Type> { typeof(MyFirstBootstwapper), typeof(AnotherFirstBootstwapper)};
            Type found;

            // When
            var res = NancyBootstrapperLocator.TryFindMostDerivedType(list, out found);

            // Then
            res.ShouldEqual(false);
            found.ShouldEqual(null);
        }

        [Fact]
        public void Should_return_false_when_there_are_more_than_one_most_derived_types()
        {
            // Given
            var list = new List<Type> { typeof(MyFirstBootstwapper), typeof(MySecondBootstwapper), typeof(MyThirdBootstwapper) };
            Type found;

            // When
            var res = NancyBootstrapperLocator.TryFindMostDerivedType(list, out found);

            // Then
            res.ShouldEqual(false);
            found.ShouldEqual(null);
        }

        [Fact]
        public void Should_be_able_to_handle_parent_and_grandparent_inheritance_of_internal_stuff()
        {
            // Given
            var list = new List<Type> { typeof(MyOwnDefaultBootstwapper), typeof(MyFirstBootstwapper) };
            Type found;

            // When
            var res = NancyBootstrapperLocator.TryFindMostDerivedType(list, out found);

            // Then
            res.ShouldEqual(false);
            found.ShouldEqual(null);
        }

        [Fact]
        public void Should_be_able_to_handle_a_complete_graph()
        {
            // Given
            var list = new List<Type> { typeof(BootstwapperBase), typeof(DefaultBootstwapper), typeof(MyFirstBootstwapper), typeof(MySecondBootstwapper) };
            Type found;

            // When
            var res = NancyBootstrapperLocator.TryFindMostDerivedType(list, out found);

            // Then
            res.ShouldEqual(true);
            found.ShouldEqual(typeof(MySecondBootstwapper));
        }
    }
}


text:
<!doctype html>

      <meta charset="utf-8">
      <title>2013-CZ-05</title>
    <link class="module" rel="stylesheet" href="../../../_common/modules/pemFioi/taskStyles-0.1.css" id="http://www.france-ioi.org/modules/pemFioi/taskStyles-0.1.css">

    <link class="stdAnswerTypes module" rel="stylesheet" type="text/css" href="../../../_common/modules/integrationAPI.01/installationAPI.01/pemFioi/answerTypes.css" id="http://www.france-ioi.org/modules/integrationAPI.01/installationAPI.01/pemFioi/stdAnsTypes.css" />

Pièce de puzzle

Castor fait un puzzle sur son ordinateur.
            Quand il clique sur une pièce, celle-ci tourne d'un quart de tour vers la droite.

Quel est le nombre minimum de fois que Castor doit cliquer sur la pièce ci-dessous avant de pouvoir la glisser dans son emplacement ?

            Pièce

            Emplacement

La solution

Pour placer la pièce dans son emplacement, il faut la faire tourner 3 fois vers la droite. Cela donnera successivement :

C'est de l'informatique

         Faire tourner une image, c'est-à-dire effectuer une rotation, est une opération très utile en informatique. La rotation ne sert pas seulement dans les logiciels de dessins. La notion de rotation est également au cœur de tous les logiciels manipulant des données en 3 dimensions, comme par exemple dans les jeux vidéos ou les logiciels de conception de plans. Les autres notions utiles sont la translation (déplacer un objet) et l'homothétie (faire grossir ou rétrécir un objet).

         Lorsque l'on écrit le code source d'un programme manipulant des objets en 2 ou en 3 dimensions et que l'on a besoin de « faire tourner » les objets dans différentes directions, il est important de visualiser dans quel sens un objet va tourner en fonction des opérations de base que l'on va appliquer sur cet objet. Le sujet demandait ici de visualiser une succession de rotations, dans un cas relativement facile.

redpajama_set_name: RedPajamaGithub


text:
import _ from 'lodash';

import { FETCH_POSTS, FETCH_POST } from '../actions/types';

const INITIAL_STATE = {
	all: [],
	totalPosts: 0,
	totalPages: 0,
	pageNumber: 1,
	selected: null,
	loading: null
};

export default ( state = INITIAL_STATE, action ) => {

	console.log(action);

	switch(action.type) {
		case FETCH_POSTS:
			return {
				...state,
				all: action.payload,
				totalPosts: action.payload._paging.total ,
				totalPages: action.payload._paging.totalPages
			}
		case FETCH_POST:
			return { ...state, selected: action.payload }
		default:
			return state;
	}
};


text:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package org.antlr.gunit.swingui;

import org.antlr.gunit.swingui.ImageFactory;
import java.awt.*;
import javax.swing.*;

/**
 *
 * @author scai
 */
public class WorkSpaceView extends JFrame {

    protected JSplitPane splitListClient ;
    protected JTabbedPane tabEditors;
    protected JPanel paneToolBar;
    protected StatusBarController paneStatus;
    protected TestCaseEditController paneEditor;
    protected JToolBar toolbar;
    protected JTextArea txtEditor;
    protected RuleListController listRules;
    protected JMenuBar menuBar;
    protected JScrollPane scrollCode;
    protected JPanel resultPane;

    protected JButton btnOpenGrammar;

    public WorkSpaceView() {
        super();
    }

    protected void initComponents() {

        this.paneEditor = new TestCaseEditController(this);
        this.paneStatus = new StatusBarController();

        this.toolbar = new JToolBar();
        this.toolbar.setBorder(BorderFactory.createEmptyBorder());
        this.toolbar.setFloatable(false);
        this.toolbar.setBorder(BorderFactory.createEmptyBorder());

        this.txtEditor = new JTextArea();
        this.txtEditor.setLineWrap(false);
        this.txtEditor.setFont(new Font("Courier New", Font.PLAIN, 13));
        this.scrollCode = new JScrollPane(txtEditor,
                JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
                JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
        this.scrollCode.setBorder(BorderFactory.createLineBorder(Color.LIGHT_GRAY));

        this.tabEditors = new JTabbedPane();
        this.tabEditors.addTab("Case Editor", ImageFactory.getSingleton().TEXTFILE16, this.paneEditor.getView());
        this.tabEditors.addTab("Script Source", ImageFactory.getSingleton().WINDOW16, this.scrollCode);

        this.listRules = new RuleListController();

        this.splitListClient = new JSplitPane( JSplitPane.HORIZONTAL_SPLIT,
                this.listRules.getView(), this.tabEditors);
        this.splitListClient.setResizeWeight(0.4);
        this.splitListClient.setBorder(BorderFactory.createEmptyBorder());

        this.getContentPane().add(this.toolbar, BorderLayout.NORTH);
        this.getContentPane().add(this.splitListClient, BorderLayout.CENTER);
        this.getContentPane().add(this.paneStatus.getView(), BorderLayout.SOUTH);

        // self
        this.setPreferredSize(new Dimension(900, 500));
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

}


text:
package com.buterfleoge.whale.biz.order.discount;

import org.springframework.stereotype.Service;

import com.buterfleoge.whale.type.DiscountType;
import com.buterfleoge.whale.type.entity.TravelRoute;
import com.buterfleoge.whale.type.protocol.order.GetDiscountRequest;
import com.buterfleoge.whale.type.protocol.order.GetDiscountResponse;

/**
 *
 * @author xiezhenzong
 *
 */
@Service("studentDiscountStrategy")
public class StudentDiscountStrategy extends DiscountStrategy {

    @Override
    public void handleDiscount(Long accountid, GetDiscountRequest request, GetDiscountResponse response) {
        try {
            Long routeid = request.getRouteid();
            TravelRoute travelRoute = travelRouteRepository.findByRouteidAndVisibleTrue(routeid);
            if (travelRoute != null) {
                response.setStudentDiscount(
                        discountRepository.findByTypeAndRouteid(DiscountType.STUDENT.value, routeid));
            }
        } catch (Exception e) {
            LOG.error("find student discount type failed, reqid: " + request.getReqid(), e);
        }
    }

}


text:
package org.apache.flink.streaming.examples.async;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.state.ListState;
import org.apache.flink.api.common.state.ListStateDescriptor;
import org.apache.flink.api.common.typeutils.base.IntSerializer;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.api.java.utils.ParameterTool;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.runtime.state.FunctionInitializationContext;
import org.apache.flink.runtime.state.FunctionSnapshotContext;
import org.apache.flink.streaming.api.CheckpointingMode;
import org.apache.flink.streaming.api.checkpoint.CheckpointedFunction;
import org.apache.flink.streaming.api.datastream.AsyncDataStream;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.async.AsyncFunction;
import org.apache.flink.streaming.api.functions.async.ResultFuture;
import org.apache.flink.streaming.api.functions.async.RichAsyncFunction;
import org.apache.flink.streaming.api.functions.source.SourceFunction;
import org.apache.flink.util.Collector;
import org.apache.flink.util.ExecutorUtils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.Collections;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;

/** Example to illustrates how to use {@link AsyncFunction}. */
public class AsyncIOExample {

    private static final Logger LOG = LoggerFactory.getLogger(AsyncIOExample.class);

    private static final String EXACTLY_ONCE_MODE = "exactly_once";
    private static final String ORDERED = "ordered";

    /** A checkpointed source. */
    private static class SimpleSource implements SourceFunction<Integer>, CheckpointedFunction {
        private static final long serialVersionUID = 1L;

        private volatile boolean isRunning = true;
        private int counter = 0;
        private int start = 0;

        private ListState<Integer> state;

        @Override
        public void initializeState(FunctionInitializationContext context) throws Exception {
            state =
                    context.getOperatorStateStore()
                            .getListState(
                                    new ListStateDescriptor<>("state", IntSerializer.INSTANCE));

            // restore any state that we might already have to our fields, initialize state
            // is also called in case of restore.
            for (Integer i : state.get()) {
                start = i;
            }
        }

        @Override
        public void snapshotState(FunctionSnapshotContext context) throws Exception {
            state.clear();
            state.add(start);
        }

        public SimpleSource(int maxNum) {
            this.counter = maxNum;
        }

        @Override
        public void run(SourceContext<Integer> ctx) throws Exception {
            while ((start < counter || counter == -1) && isRunning) {
                synchronized (ctx.getCheckpointLock()) {
                    ctx.collect(start);
                    ++start;

                    // loop back to 0
                    if (start == Integer.MAX_VALUE) {
                        start = 0;
                    }
                }
                Thread.sleep(10L);
            }
        }

        @Override
        public void cancel() {
            isRunning = false;
        }
    }

    /**
     * An example of {@link AsyncFunction} using a thread pool and executing working threads to
     * simulate multiple async operations.
     *
     * <p>For the real use case in production environment, the thread pool may stay in the async
     * client.
     */
    private static class SampleAsyncFunction extends RichAsyncFunction<Integer, String> {
        private static final long serialVersionUID = 2098635244857937717L;

        private transient ExecutorService executorService;

        /**
         * The result of multiplying sleepFactor with a random float is used to pause the working
         * thread in the thread pool, simulating a time consuming async operation.
         */
        private final long sleepFactor;

        /**
         * The ratio to generate an exception to simulate an async error. For example, the error may
         * be a TimeoutException while visiting HBase.
         */
        private final float failRatio;

        private final long shutdownWaitTS;

        SampleAsyncFunction(long sleepFactor, float failRatio, long shutdownWaitTS) {
            this.sleepFactor = sleepFactor;
            this.failRatio = failRatio;
            this.shutdownWaitTS = shutdownWaitTS;
        }

        @Override
        public void open(Configuration parameters) throws Exception {
            super.open(parameters);
            executorService = Executors.newFixedThreadPool(30);
        }

        @Override
        public void close() throws Exception {
            super.close();
            ExecutorUtils.gracefulShutdown(shutdownWaitTS, TimeUnit.MILLISECONDS, executorService);
        }

        @Override
        public void asyncInvoke(final Integer input, final ResultFuture<String> resultFuture) {
            executorService.submit(
                    () -> {
                        // wait for while to simulate async operation here
                        long sleep = (long) (ThreadLocalRandom.current().nextFloat() * sleepFactor);
                        try {
                            Thread.sleep(sleep);

                            if (ThreadLocalRandom.current().nextFloat() < failRatio) {
                                resultFuture.completeExceptionally(new Exception("wahahahaha..."));
                            } else {
                                resultFuture.complete(
                                        Collections.singletonList("key-" + (input % 10)));
                            }
                        } catch (InterruptedException e) {
                            resultFuture.complete(new ArrayList<>(0));
                        }
                    });
        }
    }

    private static void printUsage() {
        System.out.println(
                "To customize example, use: AsyncIOExample [--fsStatePath <path to fs state>] "
                        + "[--checkpointMode <exactly_once or at_least_once>] "
                        + "[--maxCount <max number of input from source, -1 for infinite input>] "
                        + "[--sleepFactor <interval to sleep for each stream element>] [--failRatio <possibility to throw exception>] "
                        + "[--waitMode <ordered or unordered>] [--waitOperatorParallelism <parallelism for async wait operator>] "
                        + "[--eventType <EventTime or IngestionTime>] [--shutdownWaitTS <milli sec to wait for thread pool>]"
                        + "[--timeout <Timeout for the asynchronous operations>]");
    }

    public static void main(String[] args) throws Exception {

        // obtain execution environment
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        // parse parameters
        final ParameterTool params = ParameterTool.fromArgs(args);

        final String statePath;
        final String cpMode;
        final int maxCount;
        final long sleepFactor;
        final float failRatio;
        final String mode;
        final int taskNum;
        final long shutdownWaitTS;
        final long timeout;

        try {
            // check the configuration for the job
            statePath = params.get("fsStatePath", null);
            cpMode = params.get("checkpointMode", "exactly_once");
            maxCount = params.getInt("maxCount", 100000);
            sleepFactor = params.getLong("sleepFactor", 100);
            failRatio = params.getFloat("failRatio", 0.001f);
            mode = params.get("waitMode", "ordered");
            taskNum = params.getInt("waitOperatorParallelism", 1);
            shutdownWaitTS = params.getLong("shutdownWaitTS", 20000);
            timeout = params.getLong("timeout", 10000L);
        } catch (Exception e) {
            printUsage();

            throw e;
        }

        StringBuilder configStringBuilder = new StringBuilder();

        final String lineSeparator = System.getProperty("line.separator");

        configStringBuilder
                .append("Job configuration")
                .append(lineSeparator)
                .append("FS state path=")
                .append(statePath)
                .append(lineSeparator)
                .append("Checkpoint mode=")
                .append(cpMode)
                .append(lineSeparator)
                .append("Max count of input from source=")
                .append(maxCount)
                .append(lineSeparator)
                .append("Sleep factor=")
                .append(sleepFactor)
                .append(lineSeparator)
                .append("Fail ratio=")
                .append(failRatio)
                .append(lineSeparator)
                .append("Waiting mode=")
                .append(mode)
                .append(lineSeparator)
                .append("Parallelism for async wait operator=")
                .append(taskNum)
                .append(lineSeparator)
                .append("Shutdown wait timestamp=")
                .append(shutdownWaitTS);

        LOG.info(configStringBuilder.toString());

        if (statePath != null) {
            // setup state and checkpoint mode
            env.getCheckpointConfig().setCheckpointStorage(statePath);
        }

        if (EXACTLY_ONCE_MODE.equals(cpMode)) {
            env.enableCheckpointing(1000L, CheckpointingMode.EXACTLY_ONCE);
        } else {
            env.enableCheckpointing(1000L, CheckpointingMode.AT_LEAST_ONCE);
        }

        // create input stream of a single integer
        DataStream<Integer> inputStream = env.addSource(new SimpleSource(maxCount));

        // create async function, which will "wait" for a while to simulate the process of async i/o
        AsyncFunction<Integer, String> function =
                new SampleAsyncFunction(sleepFactor, failRatio, shutdownWaitTS);

        // add async operator to streaming job
        DataStream<String> result;
        if (ORDERED.equals(mode)) {
            result =
                    AsyncDataStream.orderedWait(
                                    inputStream, function, timeout, TimeUnit.MILLISECONDS, 20)
                            .setParallelism(taskNum);
        } else {
            result =
                    AsyncDataStream.unorderedWait(
                                    inputStream, function, timeout, TimeUnit.MILLISECONDS, 20)
                            .setParallelism(taskNum);
        }

        // add a reduce to get the sum of each keys.
        result.flatMap(
                        new FlatMapFunction<String, Tuple2<String, Integer>>() {
                            private static final long serialVersionUID = -938116068682344455L;

                            @Override
                            public void flatMap(
                                    String value, Collector<Tuple2<String, Integer>> out)
                                    throws Exception {
                                out.collect(new Tuple2<>(value, 1));
                            }
                        })
                .keyBy(value -> value.f0)
                .sum(1)
                .print();

        // execute the program
        env.execute("Async IO Example");
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html" charset="utf-8">
<title>MinimalJavadocOptions (Gradle API 2.8)</title>
<meta name="date" content="2015-10-20">
<link rel="stylesheet" type="text/css" href="../../../../javadoc.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

org.gradle.external.javadoc

Interface MinimalJavadocOptions

All Known Implementing Classes:

CoreJavadocOptions, StandardJavadocDocletOptions

public interface MinimalJavadocOptions

Provides the core Javadoc options.

Method Summary

Methods

Modifier and Type
Method and Description

MinimalJavadocOptions
bootClasspath(File... bootClasspath)

MinimalJavadocOptions
breakIterator()

MinimalJavadocOptions
breakIterator(boolean breakIterator)

MinimalJavadocOptions
classpath(File... classpath)

MinimalJavadocOptions
classpath(List<File> classpath)

void
contributeCommandLineOptions(ExecSpec execHandleBuilder)

MinimalJavadocOptions
destinationDirectory(File directory)

MinimalJavadocOptions
doclet(String docletClass)

MinimalJavadocOptions
docletpath(File... docletpath)

MinimalJavadocOptions
encoding(String encoding)

MinimalJavadocOptions
extDirs(File... extDirs)

List<File>
getBootClasspath()

List<File>
getClasspath()

File
getDestinationDirectory()

String
getDoclet()

List<File>
getDocletpath()

String
getEncoding()

List<File>
getExtDirs()

String
getHeader()

List<String>
getJFlags()

String
getLocale()

JavadocMemberLevel
getMemberLevel()

List<File>
getOptionFiles()

JavadocOutputLevel
getOutputLevel()

String
getOverview()

String
getSource()

List<String>
getSourceNames()

String
getWindowTitle()

StandardJavadocDocletOptions
header(String header)

boolean
isBreakIterator()

boolean
isVerbose()

MinimalJavadocOptions
jFlags(String... jFlags)

MinimalJavadocOptions
locale(String locale)

MinimalJavadocOptions
optionFiles(File... argumentFiles)

MinimalJavadocOptions
overview(String overview)

MinimalJavadocOptions
quiet()

void
setBootClasspath(List<File> bootClasspath)

void
setBreakIterator(boolean breakIterator)

void
setClasspath(List<File> classpath)

void
setDestinationDirectory(File directory)

void
setDoclet(String docletClass)

void
setDocletpath(List<File> docletpath)

void
setEncoding(String encoding)

void
setExtDirs(List<File> extDirs)

void
setHeader(String header)

void
setJFlags(List<String> jFlags)

void
setLocale(String locale)

void
setMemberLevel(JavadocMemberLevel memberLevel)

void
setOptionFiles(List<File> optionFiles)

void
setOutputLevel(JavadocOutputLevel outputLevel)

void
setOverview(String overview)

void
setSource(String source)

void
setSourceNames(List<String> sourceNames)

void
setWindowTitle(String windowTitle)

MinimalJavadocOptions
showAll()

MinimalJavadocOptions
showFromPackage()

MinimalJavadocOptions
showFromPrivate()

MinimalJavadocOptions
showFromProtected()

MinimalJavadocOptions
showFromPublic()

MinimalJavadocOptions
source(String source)

MinimalJavadocOptions
sourceNames(String... sourceNames)

MinimalJavadocOptions
verbose()

StandardJavadocDocletOptions
windowTitle(String windowTitle)

void
write(File outputFile)

Method Detail

getOverview

@Input
@Optional
String getOverview()

setOverview

void setOverview(String overview)

overview

MinimalJavadocOptions overview(String overview)

getMemberLevel

@Input
@Optional
JavadocMemberLevel getMemberLevel()

setMemberLevel

void setMemberLevel(JavadocMemberLevel memberLevel)

showFromPublic

MinimalJavadocOptions showFromPublic()

showFromProtected

MinimalJavadocOptions showFromProtected()

showFromPackage

MinimalJavadocOptions showFromPackage()

showFromPrivate

MinimalJavadocOptions showFromPrivate()

showAll

MinimalJavadocOptions showAll()

getDoclet

@Input
@Optional
String getDoclet()

setDoclet

void setDoclet(String docletClass)

doclet

MinimalJavadocOptions doclet(String docletClass)

getDocletpath

@InputFiles
List<File> getDocletpath()

setDocletpath

void setDocletpath(List<File> docletpath)

docletpath

MinimalJavadocOptions docletpath(File... docletpath)

getSource

@Input
@Optional
String getSource()

setSource

void setSource(String source)

source

MinimalJavadocOptions source(String source)

getClasspath

List<File> getClasspath()

setClasspath

void setClasspath(List<File> classpath)

classpath

MinimalJavadocOptions classpath(List<File> classpath)

classpath

MinimalJavadocOptions classpath(File... classpath)

getBootClasspath

@InputFiles
List<File> getBootClasspath()

setBootClasspath

void setBootClasspath(List<File> bootClasspath)

bootClasspath

MinimalJavadocOptions bootClasspath(File... bootClasspath)

getExtDirs

@InputFiles
List<File> getExtDirs()

setExtDirs

void setExtDirs(List<File> extDirs)

extDirs

MinimalJavadocOptions extDirs(File... extDirs)

getOutputLevel

JavadocOutputLevel getOutputLevel()

setOutputLevel

void setOutputLevel(JavadocOutputLevel outputLevel)

verbose

MinimalJavadocOptions verbose()

isVerbose

boolean isVerbose()

quiet

MinimalJavadocOptions quiet()

isBreakIterator

@Input
boolean isBreakIterator()

setBreakIterator

void setBreakIterator(boolean breakIterator)

breakIterator

MinimalJavadocOptions breakIterator(boolean breakIterator)

breakIterator

MinimalJavadocOptions breakIterator()

getLocale

@Input
@Optional
String getLocale()

setLocale

void setLocale(String locale)

locale

MinimalJavadocOptions locale(String locale)

getEncoding

@Input
@Optional
String getEncoding()

setEncoding

void setEncoding(String encoding)

encoding

MinimalJavadocOptions encoding(String encoding)

getJFlags

List<String> getJFlags()

setJFlags

void setJFlags(List<String> jFlags)

jFlags

MinimalJavadocOptions jFlags(String... jFlags)

getOptionFiles

List<File> getOptionFiles()

setOptionFiles

void setOptionFiles(List<File> optionFiles)

optionFiles

MinimalJavadocOptions optionFiles(File... argumentFiles)

getDestinationDirectory

File getDestinationDirectory()

setDestinationDirectory

void setDestinationDirectory(File directory)

destinationDirectory

MinimalJavadocOptions destinationDirectory(File directory)

getWindowTitle

@Input
@Optional
String getWindowTitle()

setWindowTitle

void setWindowTitle(String windowTitle)

windowTitle

StandardJavadocDocletOptions windowTitle(String windowTitle)

getHeader

@Input
@Optional
String getHeader()

setHeader

void setHeader(String header)

header

StandardJavadocDocletOptions header(String header)

write

void write(File outputFile)
           throws IOException

Throws:

IOException

getSourceNames

List<String> getSourceNames()

setSourceNames

void setSourceNames(List<String> sourceNames)

sourceNames

MinimalJavadocOptions sourceNames(String... sourceNames)

contributeCommandLineOptions

void contributeCommandLineOptions(ExecSpec execHandleBuilder)

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
from __future__ import absolute_import, unicode_literals

import unittest

import pykka

from mopidy import core
from mopidy.backend import dummy
from mopidy.mpd.dispatcher import MpdDispatcher
from mopidy.mpd.exceptions import MpdAckError

class MpdDispatcherTest(unittest.TestCase):
    def setUp(self):  # noqa: N802
        config = {
            'mpd': {
                'password': None,
            }
        }
        self.backend = dummy.create_dummy_backend_proxy()
        self.core = core.Core.start(backends=[self.backend]).proxy()
        self.dispatcher = MpdDispatcher(config=config)

    def tearDown(self):  # noqa: N802
        pykka.ActorRegistry.stop_all()

    def test_call_handler_for_unknown_command_raises_exception(self):
        try:
            self.dispatcher._call_handler('an_unknown_command with args')
            self.fail('Should raise exception')
        except MpdAckError as e:
            self.assertEqual(
                e.get_mpd_ack(),
                'ACK [5@0] {} unknown command "an_unknown_command"')

    def test_handling_unknown_request_yields_error(self):
        result = self.dispatcher.handle_request('an unhandled request')
        self.assertEqual(result[0], 'ACK [5@0] {} unknown command "an"')


text:
'use strict';

/* jshint ignore:start */
/**
 * This code was generated by
 * \ / _    _  _|   _  _
 *  | (_)\/(_)(_|\/| |(/_  v1.0.0
 *       /       /
 */
/* jshint ignore:end */

var Q = require('q');  /* jshint ignore:line */
var _ = require('lodash');  /* jshint ignore:line */
var util = require('util');  /* jshint ignore:line */
var Page = require('../../../base/Page');  /* jshint ignore:line */
var ParticipantList = require('./room/participant').ParticipantList;
var deserialize = require(
    '../../../base/deserialize');  /* jshint ignore:line */
var serialize = require('../../../base/serialize');  /* jshint ignore:line */
var values = require('../../../base/values');  /* jshint ignore:line */

var RoomList;
var RoomPage;
var RoomInstance;
var RoomContext;

/* jshint ignore:start */
/**
 * Initialize the RoomList
 *
 * PLEASE NOTE that this class contains beta products that are subject to change.
 * Use them with caution.
 *
 * @constructor Twilio.Insights.V1.RoomList
 *
 * @param {Twilio.Insights.V1} version - Version of the resource
 */
/* jshint ignore:end */
RoomList = function RoomList(version) {
  /* jshint ignore:start */
  /**
   * @function rooms
   * @memberof Twilio.Insights.V1#
   *
   * @param {string} sid - sid of instance
   *
   * @returns {Twilio.Insights.V1.RoomContext}
   */
  /* jshint ignore:end */
  function RoomListInstance(sid) {
    return RoomListInstance.get(sid);
  }

  RoomListInstance._version = version;
  // Path Solution
  RoomListInstance._solution = {};
  RoomListInstance._uri = `/Video/Rooms`;
  /* jshint ignore:start */
  /**
   * Streams RoomInstance records from the API.
   *
   * This operation lazily loads records as efficiently as possible until the limit
   * is reached.
   *
   * The results are passed into the callback function, so this operation is memory
   * efficient.
   *
   * If a function is passed as the first argument, it will be used as the callback
   * function.
   *
   * @function each
   * @memberof Twilio.Insights.V1.RoomList#
   *
   * @param {object} [opts] - Options for request
   * @param {room.room_type|list} [opts.roomType] - Type of room.
   * @param {room.codec|list} [opts.codec] - Codecs used by participants in the room.
   * @param {string} [opts.roomName] - Room friendly name.
   * @param {Date} [opts.createdAfter] -
   *          Only read rooms that started on or after this ISO 8601 timestamp.
   * @param {Date} [opts.createdBefore] -
   *          Only read rooms that started before this ISO 8601 timestamp.
   * @param {number} [opts.limit] -
   *         Upper limit for the number of records to return.
   *         each() guarantees never to return more than limit.
   *         Default is no limit
   * @param {number} [opts.pageSize] -
   *         Number of records to fetch per request,
   *         when not set will use the default value of 50 records.
   *         If no pageSize is defined but a limit is defined,
   *         each() will attempt to read the limit with the most efficient
   *         page size, i.e. min(limit, 1000)
   * @param {Function} [opts.callback] -
   *         Function to process each record. If this and a positional
   *         callback are passed, this one will be used
   * @param {Function} [opts.done] -
   *          Function to be called upon completion of streaming
   * @param {Function} [callback] - Function to process each record
   */
  /* jshint ignore:end */
  RoomListInstance.each = function each(opts, callback) {
    if (_.isFunction(opts)) {
      callback = opts;
      opts = {};
    }
    opts = opts || {};
    if (opts.callback) {
      callback = opts.callback;
    }
    if (_.isUndefined(callback)) {
      throw new Error('Callback function must be provided');
    }

    var done = false;
    var currentPage = 1;
    var currentResource = 0;
    var limits = this._version.readLimits({
      limit: opts.limit,
      pageSize: opts.pageSize
    });

    function onComplete(error) {
      done = true;
      if (_.isFunction(opts.done)) {
        opts.done(error);
      }
    }

    function fetchNextPage(fn) {
      var promise = fn();
      if (_.isUndefined(promise)) {
        onComplete();
        return;
      }

      promise.then(function(page) {
        _.each(page.instances, function(instance) {
          if (done || (!_.isUndefined(opts.limit) && currentResource >= opts.limit)) {
            done = true;
            return false;
          }

          currentResource++;
          callback(instance, onComplete);
        });

        if (!done) {
          currentPage++;
          fetchNextPage(_.bind(page.nextPage, page));
        } else {
          onComplete();
        }
      });

      promise.catch(onComplete);
    }

    fetchNextPage(_.bind(this.page, this, _.merge(opts, limits)));
  };

  /* jshint ignore:start */
  /**
   * Lists RoomInstance records from the API as a list.
   *
   * If a function is passed as the first argument, it will be used as the callback
   * function.
   *
   * @function list
   * @memberof Twilio.Insights.V1.RoomList#
   *
   * @param {object} [opts] - Options for request
   * @param {room.room_type|list} [opts.roomType] - Type of room.
   * @param {room.codec|list} [opts.codec] - Codecs used by participants in the room.
   * @param {string} [opts.roomName] - Room friendly name.
   * @param {Date} [opts.createdAfter] -
   *          Only read rooms that started on or after this ISO 8601 timestamp.
   * @param {Date} [opts.createdBefore] -
   *          Only read rooms that started before this ISO 8601 timestamp.
   * @param {number} [opts.limit] -
   *         Upper limit for the number of records to return.
   *         list() guarantees never to return more than limit.
   *         Default is no limit
   * @param {number} [opts.pageSize] -
   *         Number of records to fetch per request,
   *         when not set will use the default value of 50 records.
   *         If no page_size is defined but a limit is defined,
   *         list() will attempt to read the limit with the most
   *         efficient page size, i.e. min(limit, 1000)
   * @param {function} [callback] - Callback to handle list of records
   *
   * @returns {Promise} Resolves to a list of records
   */
  /* jshint ignore:end */
  RoomListInstance.list = function list(opts, callback) {
    if (_.isFunction(opts)) {
      callback = opts;
      opts = {};
    }
    opts = opts || {};
    var deferred = Q.defer();
    var allResources = [];
    opts.callback = function(resource, done) {
      allResources.push(resource);

      if (!_.isUndefined(opts.limit) && allResources.length === opts.limit) {
        done();
      }
    };

    opts.done = function(error) {
      if (_.isUndefined(error)) {
        deferred.resolve(allResources);
      } else {
        deferred.reject(error);
      }
    };

    if (_.isFunction(callback)) {
      deferred.promise.nodeify(callback);
    }

    this.each(opts);
    return deferred.promise;
  };

  /* jshint ignore:start */
  /**
   * Retrieve a single page of RoomInstance records from the API.
   *
   * The request is executed immediately.
   *
   * If a function is passed as the first argument, it will be used as the callback
   * function.
   *
   * @function page
   * @memberof Twilio.Insights.V1.RoomList#
   *
   * @param {object} [opts] - Options for request
   * @param {room.room_type|list} [opts.roomType] - Type of room.
   * @param {room.codec|list} [opts.codec] - Codecs used by participants in the room.
   * @param {string} [opts.roomName] - Room friendly name.
   * @param {Date} [opts.createdAfter] -
   *          Only read rooms that started on or after this ISO 8601 timestamp.
   * @param {Date} [opts.createdBefore] -
   *          Only read rooms that started before this ISO 8601 timestamp.
   * @param {string} [opts.pageToken] - PageToken provided by the API
   * @param {number} [opts.pageNumber] -
   *          Page Number, this value is simply for client state
   * @param {number} [opts.pageSize] - Number of records to return, defaults to 50
   * @param {function} [callback] - Callback to handle list of records
   *
   * @returns {Promise} Resolves to a list of records
   */
  /* jshint ignore:end */
  RoomListInstance.page = function page(opts, callback) {
    if (_.isFunction(opts)) {
      callback = opts;
      opts = {};
    }
    opts = opts || {};

    var deferred = Q.defer();
    var data = values.of({
      'RoomType': serialize.map(_.get(opts, 'roomType'), function(e) { return e; }),
      'Codec': serialize.map(_.get(opts, 'codec'), function(e) { return e; }),
      'RoomName': _.get(opts, 'roomName'),
      'CreatedAfter': serialize.iso8601DateTime(_.get(opts, 'createdAfter')),
      'CreatedBefore': serialize.iso8601DateTime(_.get(opts, 'createdBefore')),
      'PageToken': opts.pageToken,
      'Page': opts.pageNumber,
      'PageSize': opts.pageSize
    });

    var promise = this._version.page({uri: this._uri, method: 'GET', params: data});

    promise = promise.then(function(payload) {
      deferred.resolve(new RoomPage(this._version, payload, this._solution));
    }.bind(this));

    promise.catch(function(error) {
      deferred.reject(error);
    });

    if (_.isFunction(callback)) {
      deferred.promise.nodeify(callback);
    }

    return deferred.promise;
  };

  /* jshint ignore:start */
  /**
   * Retrieve a single target page of RoomInstance records from the API.
   *
   * The request is executed immediately.
   *
   * If a function is passed as the first argument, it will be used as the callback
   * function.
   *
   * @function getPage
   * @memberof Twilio.Insights.V1.RoomList#
   *
   * @param {string} [targetUrl] - API-generated URL for the requested results page
   * @param {function} [callback] - Callback to handle list of records
   *
   * @returns {Promise} Resolves to a list of records
   */
  /* jshint ignore:end */
  RoomListInstance.getPage = function getPage(targetUrl, callback) {
    var deferred = Q.defer();

    var promise = this._version._domain.twilio.request({method: 'GET', uri: targetUrl});

    promise = promise.then(function(payload) {
      deferred.resolve(new RoomPage(this._version, payload, this._solution));
    }.bind(this));

    promise.catch(function(error) {
      deferred.reject(error);
    });

    if (_.isFunction(callback)) {
      deferred.promise.nodeify(callback);
    }

    return deferred.promise;
  };

  /* jshint ignore:start */
  /**
   * Constructs a room
   *
   * @function get
   * @memberof Twilio.Insights.V1.RoomList#
   *
   * @param {string} roomSid - The SID of the Room resource.
   *
   * @returns {Twilio.Insights.V1.RoomContext}
   */
  /* jshint ignore:end */
  RoomListInstance.get = function get(roomSid) {
    return new RoomContext(this._version, roomSid);
  };

  /* jshint ignore:start */
  /**
   * Provide a user-friendly representation
   *
   * @function toJSON
   * @memberof Twilio.Insights.V1.RoomList#
   *
   * @returns Object
   */
  /* jshint ignore:end */
  RoomListInstance.toJSON = function toJSON() {
    return this._solution;
  };

  RoomListInstance[util.inspect.custom] = function inspect(depth, options) {
    return util.inspect(this.toJSON(), options);
  };

  return RoomListInstance;
};

/* jshint ignore:start */
/**
 * Initialize the RoomPage
 *
 * PLEASE NOTE that this class contains beta products that are subject to change.
 * Use them with caution.
 *
 * @constructor Twilio.Insights.V1.RoomPage
 *
 * @param {V1} version - Version of the resource
 * @param {Response<string>} response - Response from the API
 * @param {RoomSolution} solution - Path solution
 *
 * @returns RoomPage
 */
/* jshint ignore:end */
RoomPage = function RoomPage(version, response, solution) {
  // Path Solution
  this._solution = solution;

  Page.prototype.constructor.call(this, version, response, this._solution);
};

_.extend(RoomPage.prototype, Page.prototype);
RoomPage.prototype.constructor = RoomPage;

/* jshint ignore:start */
/**
 * Build an instance of RoomInstance
 *
 * @function getInstance
 * @memberof Twilio.Insights.V1.RoomPage#
 *
 * @param {RoomPayload} payload - Payload response from the API
 *
 * @returns RoomInstance
 */
/* jshint ignore:end */
RoomPage.prototype.getInstance = function getInstance(payload) {
  return new RoomInstance(this._version, payload);
};

/* jshint ignore:start */
/**
 * Provide a user-friendly representation
 *
 * @function toJSON
 * @memberof Twilio.Insights.V1.RoomPage#
 *
 * @returns Object
 */
/* jshint ignore:end */
RoomPage.prototype.toJSON = function toJSON() {
  let clone = {};
  _.forOwn(this, function(value, key) {
    if (!_.startsWith(key, '_') && ! _.isFunction(value)) {
      clone[key] = value;
    }
  });
  return clone;
};

RoomPage.prototype[util.inspect.custom] = function inspect(depth, options) {
  return util.inspect(this.toJSON(), options);
};

/* jshint ignore:start */
/**
 * Initialize the RoomContext
 *
 * PLEASE NOTE that this class contains beta products that are subject to change.
 * Use them with caution.
 *
 * @constructor Twilio.Insights.V1.RoomInstance
 *
 * @property {string} accountSid - Account SID associated with this room.
 * @property {string} roomSid - Unique identifier for the room.
 * @property {string} roomName - room friendly name.
 * @property {Date} createTime - Creation time of the room.
 * @property {Date} endTime - End time for the room.
 * @property {room.room_type} roomType - Type of room.
 * @property {room.room_status} roomStatus - Status of the room.
 * @property {string} statusCallback - Webhook provided for status callbacks.
 * @property {string} statusCallbackMethod -
 *          HTTP method provided for status callback URL.
 * @property {room.created_method} createdMethod - How the room was created.
 * @property {room.end_reason} endReason - Reason the room ended.
 * @property {number} maxParticipants -
 *          Max number of total participants allowed by the application settings.
 * @property {number} uniqueParticipants -
 *          Number of participants. May include duplicate identities for participants who left and rejoined.
 * @property {number} uniqueParticipantIdentities -
 *          Unique number of participant identities.
 * @property {number} concurrentParticipants -
 *          Actual number of concurrent participants.
 * @property {number} maxConcurrentParticipants -
 *          Maximum number of participants allowed in the room at the same time allowed by the application settings.
 * @property {room.codec} codecs - Codecs used by participants in the room.
 * @property {room.twilio_realm} mediaRegion -
 *          Region of Twilio media servers for the room.
 * @property {number} durationSec -
 *          Total room duration from create time to end time.
 * @property {number} totalParticipantDurationSec -
 *          Combined amount of participant time in the room.
 * @property {number} totalRecordingDurationSec -
 *          Combined amount of recorded seconds for participants in the room.
 * @property {room.processing_state} processingState -
 *          Video Log Analyzer resource state. Will be either `in-progress` or `complete`.
 * @property {boolean} recordingEnabled -
 *          Boolean indicating if recording is enabled for the room.
 * @property {room.edge_location} edgeLocation -
 *          Edge location of Twilio media servers for the room.
 * @property {string} url - URL for the room resource.
 * @property {string} links - Room subresources.
 *
 * @param {V1} version - Version of the resource
 * @param {RoomPayload} payload - The instance payload
 * @param {sid_like} roomSid - The SID of the Room resource.
 */
/* jshint ignore:end */
RoomInstance = function RoomInstance(version, payload, roomSid) {
  this._version = version;

  // Marshaled Properties
  this.accountSid = payload.account_sid; // jshint ignore:line
  this.roomSid = payload.room_sid; // jshint ignore:line
  this.roomName = payload.room_name; // jshint ignore:line
  this.createTime = deserialize.iso8601DateTime(payload.create_time); // jshint ignore:line
  this.endTime = deserialize.iso8601DateTime(payload.end_time); // jshint ignore:line
  this.roomType = payload.room_type; // jshint ignore:line
  this.roomStatus = payload.room_status; // jshint ignore:line
  this.statusCallback = payload.status_callback; // jshint ignore:line
  this.statusCallbackMethod = payload.status_callback_method; // jshint ignore:line
  this.createdMethod = payload.created_method; // jshint ignore:line
  this.endReason = payload.end_reason; // jshint ignore:line
  this.maxParticipants = deserialize.integer(payload.max_participants); // jshint ignore:line
  this.uniqueParticipants = deserialize.integer(payload.unique_participants); // jshint ignore:line
  this.uniqueParticipantIdentities = deserialize.integer(payload.unique_participant_identities); // jshint ignore:line
  this.concurrentParticipants = deserialize.integer(payload.concurrent_participants); // jshint ignore:line
  this.maxConcurrentParticipants = deserialize.integer(payload.max_concurrent_participants); // jshint ignore:line
  this.codecs = payload.codecs; // jshint ignore:line
  this.mediaRegion = payload.media_region; // jshint ignore:line
  this.durationSec = deserialize.integer(payload.duration_sec); // jshint ignore:line
  this.totalParticipantDurationSec = deserialize.integer(payload.total_participant_duration_sec); // jshint ignore:line
  this.totalRecordingDurationSec = deserialize.integer(payload.total_recording_duration_sec); // jshint ignore:line
  this.processingState = payload.processing_state; // jshint ignore:line
  this.recordingEnabled = payload.recording_enabled; // jshint ignore:line
  this.edgeLocation = payload.edge_location; // jshint ignore:line
  this.url = payload.url; // jshint ignore:line
  this.links = payload.links; // jshint ignore:line

  // Context
  this._context = undefined;
  this._solution = {roomSid: roomSid || this.roomSid, };
};

Object.defineProperty(RoomInstance.prototype,
  '_proxy', {
    get: function() {
      if (!this._context) {
        this._context = new RoomContext(this._version, this._solution.roomSid);
      }

      return this._context;
    }
});

/* jshint ignore:start */
/**
 * fetch a RoomInstance
 *
 * @function fetch
 * @memberof Twilio.Insights.V1.RoomInstance#
 *
 * @param {function} [callback] - Callback to handle processed record
 *
 * @returns {Promise} Resolves to processed RoomInstance
 */
/* jshint ignore:end */
RoomInstance.prototype.fetch = function fetch(callback) {
  return this._proxy.fetch(callback);
};

/* jshint ignore:start */
/**
 * Access the participants
 *
 * @function participants
 * @memberof Twilio.Insights.V1.RoomInstance#
 *
 * @returns {Twilio.Insights.V1.RoomContext.ParticipantList}
 */
/* jshint ignore:end */
RoomInstance.prototype.participants = function participants() {
  return this._proxy.participants;
};

/* jshint ignore:start */
/**
 * Provide a user-friendly representation
 *
 * @function toJSON
 * @memberof Twilio.Insights.V1.RoomInstance#
 *
 * @returns Object
 */
/* jshint ignore:end */
RoomInstance.prototype.toJSON = function toJSON() {
  let clone = {};
  _.forOwn(this, function(value, key) {
    if (!_.startsWith(key, '_') && ! _.isFunction(value)) {
      clone[key] = value;
    }
  });
  return clone;
};

RoomInstance.prototype[util.inspect.custom] = function inspect(depth, options) {
  return util.inspect(this.toJSON(), options);
};

/* jshint ignore:start */
/**
 * Initialize the RoomContext
 *
 * PLEASE NOTE that this class contains beta products that are subject to change.
 * Use them with caution.
 *
 * @constructor Twilio.Insights.V1.RoomContext
 *
 * @property {Twilio.Insights.V1.RoomContext.ParticipantList} participants -
 *          participants resource
 *
 * @param {V1} version - Version of the resource
 * @param {sid_like} roomSid - The SID of the Room resource.
 */
/* jshint ignore:end */
RoomContext = function RoomContext(version, roomSid) {
  this._version = version;

  // Path Solution
  this._solution = {roomSid: roomSid, };
  this._uri = `/Video/Rooms/${roomSid}`;

  // Dependents
  this._participants = undefined;
};

/* jshint ignore:start */
/**
 * fetch a RoomInstance
 *
 * @function fetch
 * @memberof Twilio.Insights.V1.RoomContext#
 *
 * @param {function} [callback] - Callback to handle processed record
 *
 * @returns {Promise} Resolves to processed RoomInstance
 */
/* jshint ignore:end */
RoomContext.prototype.fetch = function fetch(callback) {
  var deferred = Q.defer();
  var promise = this._version.fetch({uri: this._uri, method: 'GET'});

  promise = promise.then(function(payload) {
    deferred.resolve(new RoomInstance(this._version, payload, this._solution.roomSid));
  }.bind(this));

  promise.catch(function(error) {
    deferred.reject(error);
  });

  if (_.isFunction(callback)) {
    deferred.promise.nodeify(callback);
  }

  return deferred.promise;
};

Object.defineProperty(RoomContext.prototype,
  'participants', {
    get: function() {
      if (!this._participants) {
        this._participants = new ParticipantList(this._version, this._solution.roomSid);
      }
      return this._participants;
    }
});

/* jshint ignore:start */
/**
 * Provide a user-friendly representation
 *
 * @function toJSON
 * @memberof Twilio.Insights.V1.RoomContext#
 *
 * @returns Object
 */
/* jshint ignore:end */
RoomContext.prototype.toJSON = function toJSON() {
  return this._solution;
};

RoomContext.prototype[util.inspect.custom] = function inspect(depth, options) {
  return util.inspect(this.toJSON(), options);
};

module.exports = {
  RoomList: RoomList,
  RoomPage: RoomPage,
  RoomInstance: RoomInstance,
  RoomContext: RoomContext
};


text:
package org.terasology.logic.console.commandSystem;

import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import com.google.common.primitives.Primitives;
import org.terasology.entitySystem.entity.EntityRef;
import org.terasology.logic.console.commandSystem.adapter.ParameterAdapterManager;
import org.terasology.logic.console.commandSystem.exceptions.CommandParameterParseException;
import org.terasology.logic.console.commandSystem.exceptions.SuggesterInstantiationException;
import org.terasology.registry.CoreRegistry;

import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.List;
import java.util.Set;

/**
 * @author Limeth
 */
public final class CommandParameter<T> implements Parameter {
    private final String name;
    private final Class<T> type;
    private final CommandParameterSuggester<T> suggester;
    private final boolean required;

    @SuppressWarnings("unchecked")
    private CommandParameter(String name, Class<T> typeParam, boolean required, CommandParameterSuggester<T> suggester) {
        Preconditions.checkNotNull(name, "The parameter name must not be null!");

        if (name.length() <= 0) {
            throw new IllegalArgumentException("The parameter name must not be empty!");
        }

        Preconditions.checkNotNull(typeParam, "The parameter type must not be null!");

        Class<T> resultType;

        if (typeParam.isPrimitive()) {
            if (required) {
                resultType = Primitives.wrap(typeParam);
            } else {
                throw new IllegalArgumentException("An optional parameter must not be primitive!"
                        + " Use " + Primitives.wrap(typeParam).getSimpleName()
                        + " instead of " + typeParam.getSimpleName() + ".");
            }
        } else {
            resultType = typeParam;
        }

        Preconditions.checkNotNull(suggester, "The suggester must not be null!");

        this.name = name;
        this.type = resultType;
        this.suggester = suggester;
        this.required = required;
    }

    public static <T> CommandParameter single(String name, Class<T> type, boolean required,
                                              CommandParameterSuggester<T> suggester) {
        if (type.isArray()) {
            throw new IllegalArgumentException("The type of a simple CommandParameterDefinition must not be an array!");
        }

        return new CommandParameter(name, type, required, suggester);
    }

    public static <T> CommandParameter single(String name, Class<T> type, boolean required,
                                              Class<? extends CommandParameterSuggester<T>> suggesterClass)
            throws SuggesterInstantiationException {
        try {
            return single(name, type, required, suggesterClass != null ? suggesterClass.newInstance() : null);
        } catch (InstantiationException | IllegalAccessException e) {
            throw new SuggesterInstantiationException(e);
        }
    }

    @SuppressWarnings("unchecked")
    public static CommandParameter single(String name, Class<?> type, boolean required) {
        return single(name, type, required, (CommandParameterSuggester) null);
    }

    public static <T> CommandParameter array(String name, Class<T> childType, Character arrayDelimiter,
                                             boolean required, CommandParameterSuggester<T> suggester) {
        if (childType.isArray()) {
            throw new IllegalArgumentException("The child type of an array CommandParameterDefinition must not be an array!");
        }

        Class<?> type = getArrayClass(childType);

        return new CommandParameter(name, type, required, suggester);
    }

    public static <T> CommandParameter array(String name, Class<T> childType, Character arrayDelimiter,
                                             boolean required, Class<? extends CommandParameterSuggester<T>> suggesterClass)
            throws SuggesterInstantiationException {
        try {
            return array(name, childType, arrayDelimiter, required, suggesterClass != null ? suggesterClass.newInstance() : null);
        } catch (InstantiationException | IllegalAccessException e) {
            throw new SuggesterInstantiationException(e);
        }
    }

    @SuppressWarnings("unchecked")
    public static CommandParameter array(String name, Class<?> childType, Character arrayDelimiter,
                                         boolean required) {
        return array(name, childType, arrayDelimiter, required, (CommandParameterSuggester) null);
    }

    public static <T> CommandParameter array(String name, Class<T> childType, boolean required,
                                             CommandParameterSuggester<T> suggester) {
        return array(name, childType, null, required, suggester);
    }

    public static <T> CommandParameter array(String name, Class<T> childType, boolean required,
                                             Class<? extends CommandParameterSuggester<T>> suggesterClass)
            throws SuggesterInstantiationException {
        try {
            return array(name, childType, required, suggesterClass != null ? suggesterClass.newInstance() : null);
        } catch (InstantiationException | IllegalAccessException e) {
            throw new SuggesterInstantiationException(e);
        }
    }

    @SuppressWarnings("unchecked")
    public static CommandParameter array(String name, Class<?> childType, boolean required) {
        return array(name, childType, required, (CommandParameterSuggester) null);
    }

    public static <T> CommandParameter varargs(String name, Class<T> childType, boolean required, CommandParameterSuggester<T> suggester) {
        return array(name, childType, required, suggester);
    }

    public static <T> CommandParameter varargs(String name, Class<T> childType, boolean required,
                                               Class<? extends CommandParameterSuggester<T>> suggester)
            throws SuggesterInstantiationException {
        try {
            return varargs(name, childType, required, suggester != null ? suggester.newInstance() : null);
        } catch (InstantiationException | IllegalAccessException e) {
            throw new SuggesterInstantiationException(e);
        }
    }

    @SuppressWarnings("unchecked")
    public static CommandParameter varargs(String name, Class<?> childType, boolean required) {
        return varargs(name, childType, required, (CommandParameterSuggester) null);
    }

    /**
     * @param clazz The child class of the array class returned
     * @return The array class of {@code clazz}
     */
    @SuppressWarnings("unchecked")
    private static <T> Class<? extends T[]> getArrayClass(Class<T> clazz) {
        return (Class<? extends T[]>) Array.newInstance(clazz, 0).getClass();
    }

    public Object getValue(String param) throws CommandParameterParseException {
        if (!isArray()) {
            return parse(param);
        } else {
            return getArrayValue(Arrays.asList(param));
        }
    }

    public Object getArrayValue(List<String> params) throws CommandParameterParseException {
        Object arrayInstance = Array.newInstance(getType(), params.size());
        for (int i = 0; i < params.size(); ++i) {
            Array.set(arrayInstance, i, parse(params.get(i)));
        }
        return arrayInstance;
    }

    private Object parse(String string) throws CommandParameterParseException {
        ParameterAdapterManager parameterAdapterManager = CoreRegistry.get(ParameterAdapterManager.class);
        Class<?> childType = getTypeNotPrimitive();

        if (parameterAdapterManager.isAdapterRegistered(childType)) {
            try {
                return parameterAdapterManager.parse(childType, string);
            } catch (Error | Exception e) {
                throw new CommandParameterParseException("An error occurred while parsing " + getType().getCanonicalName(), e, string);
            }
        }

        throw new CommandParameterParseException("Cannot parse a " + childType.getCanonicalName(), string);
    }

    public String convertToString(Object object) {
        ParameterAdapterManager parameterAdapterManager = CoreRegistry.get(ParameterAdapterManager.class);

        return parameterAdapterManager.convertToString(object, (Class<? super Object>) getType());
    }

    @SuppressWarnings("unchecked")
    public Set<T> suggest(EntityRef sender, Object... parameters) {
        return suggester.suggest(sender, parameters);
    }

    public String getUsage() {
        String simpleTypeName = getType().getSimpleName();
        StringBuilder usage = new StringBuilder(simpleTypeName);

        if (hasName()) {
            usage.append(' ').append(getName());
        }

        if (isArray()) {
            usage.insert(0, '(');
            usage.append("...)");
        } else if (isRequired()) {
            usage.insert(0, '<');
            usage.append('>');
        } else {
            usage.insert(0, '(');
            usage.append(')');
        }

        return usage.toString();
    }

    public boolean isArray() {
        return type.isArray();
    }

    public boolean hasName() {
        return name.length() >= 0;
    }

    public String getName() {
        return name;
    }

    public Class<?> getType() {
        if (type.isArray()) {
            return type.getComponentType();
        }

        return type;
    }

    public Class<?> getTypeNotPrimitive() {
        Class<?> componentType = getType();

        if (componentType.isPrimitive()) {
            return Primitives.wrap(componentType);
        } else {
            return componentType;
        }
    }

    public Class<T> getTypeRaw() {
        return type;
    }

    public CommandParameterSuggester<T> getSuggester() {
        return suggester;
    }

    public boolean isRequired() {
        return required && !isArray();
    }

    @Override
    public Optional<? extends Class<?>> getProvidedType() {
        return Optional.of(getTypeRaw());
    }
}


text:
package org.jkiss.dbeaver.ext.snowflake.model;

import org.jkiss.code.NotNull;
import org.jkiss.code.Nullable;
import org.jkiss.dbeaver.DBException;
import org.jkiss.dbeaver.ext.generic.model.GenericCatalog;
import org.jkiss.dbeaver.ext.generic.model.GenericDataSource;
import org.jkiss.dbeaver.ext.generic.model.GenericSchema;
import org.jkiss.dbeaver.ext.snowflake.SnowflakeConstants;
import org.jkiss.dbeaver.model.DBPDataSourceContainer;
import org.jkiss.dbeaver.model.access.DBAUserPasswordManager;
import org.jkiss.dbeaver.model.connection.DBPConnectionConfiguration;
import org.jkiss.dbeaver.model.connection.DBPDriver;
import org.jkiss.dbeaver.model.impl.jdbc.JDBCExecutionContext;
import org.jkiss.dbeaver.model.impl.jdbc.JDBCRemoteInstance;
import org.jkiss.dbeaver.model.runtime.DBRProgressMonitor;
import org.jkiss.utils.CommonUtils;

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

public class SnowflakeDataSource extends GenericDataSource {

    public SnowflakeDataSource(DBRProgressMonitor monitor, DBPDataSourceContainer container, SnowflakeMetaModel metaModel)
        throws DBException
    {
        super(monitor, container, metaModel, new SnowflakeSQLDialect());
    }

    @Override
    protected Map<String, String> getInternalConnectionProperties(DBRProgressMonitor monitor, DBPDriver driver, JDBCExecutionContext context, String purpose, DBPConnectionConfiguration connectionInfo) {
        Map<String, String> props = new HashMap<>();

        // Backward compatibility - use legacy provider property
        // Newer versions use auth model
        String authProp = connectionInfo.getProviderProperty(SnowflakeConstants.PROP_AUTHENTICATOR_LEGACY);
        if (!CommonUtils.isEmpty(authProp)) {
            props.put("authenticator", authProp);
        }

        return props;
    }

    @Override
    protected boolean isPopulateClientAppName() {
        return false;
    }

    @NotNull
    @Override
    protected JDBCExecutionContext createExecutionContext(JDBCRemoteInstance instance, String type) {
        return new SnowflakeExecutionContext(instance, type);
    }

    @Override
    protected void initializeContextState(@NotNull DBRProgressMonitor monitor, @NotNull JDBCExecutionContext context,
                                          @Nullable JDBCExecutionContext initFrom) throws DBException {
        SnowflakeExecutionContext executionContext = (SnowflakeExecutionContext) context;
        if (initFrom == null) {
            executionContext.refreshDefaults(monitor, true);
            return;
        }
        SnowflakeExecutionContext executionMetaContext = (SnowflakeExecutionContext) initFrom;
        GenericCatalog defaultCatalog = executionMetaContext.getDefaultCatalog();
        GenericSchema defaultSchema = executionMetaContext.getDefaultSchema();
        if (defaultCatalog != null) {
            executionContext.setDefaultCatalog(monitor, defaultCatalog, defaultSchema, true);
        } else if (defaultSchema != null) {
            executionContext.setDefaultSchema(monitor, defaultSchema, true);
        }
    }

    @Override
    public <T> T getAdapter(Class<T> adapter) {
        if (adapter == DBAUserPasswordManager.class) {
            return adapter.cast(new SnowflakeChangeUserPasswordManager(this));
        }
        return super.getAdapter(adapter);
    }
}


text:
#pragma once

#include "base/AFPlatform.hpp"
#include "base/AFMacros.hpp"
#include "net/include/AFNetDefine.hpp"

#pragma pack(push, 1)

namespace ark {

class AFNetEvent final
{
    AFNetEventType type_{AFNetEventType::NONE};
    conv_id_t id_{0};
    std::string ip_{};
    bus_id_t bus_id_{0};

public:
    static AFNetEvent* AllocEvent()
    {
        return ARK_NEW AFNetEvent();
    }

    static void Release(AFNetEvent*& event)
    {
        ARK_DELETE(event);
    }

    AFNetEventType GetType() const
    {
        return type_;
    }

    conv_id_t GetId() const
    {
        return id_;
    }

    const std::string& GetIP() const
    {
        return ip_;
    }

    bus_id_t GetBusId() const
    {
        return bus_id_;
    }

    void SetType(AFNetEventType value)
    {
        type_ = value;
    }

    void SetId(conv_id_t value)
    {
        id_ = value;
    }

    void SetIP(const std::string& value)
    {
        ip_ = value;
    }

    void SetBusId(bus_id_t value)
    {
        bus_id_ = value;
    }
};

} // namespace ark

#pragma pack(pop)


text:
#include "pch.h"
#include "Grid.h"
#include "Constants.h"

Grid::Grid()
{

}

Grid::~Grid()
{

}

void Grid::SetWindowWidth(float fWindowWidth)
{
	this->m_fWindowWidth = fWindowWidth;

	m_fGridWidth = m_fWindowWidth -
		(m_fWindowWidth * LEFT_MARGIN_RATIO) -
		(m_fWindowWidth * RIGHT_MARGIN_RATIO);
}

void Grid::SetWindowHeight(float fWindowHeight)
{
	this->m_fWindowHeight = fWindowHeight;

	m_fGridHeight = fWindowHeight;
}

void Grid::Draw(
	ComPtr<ID2D1DeviceContext1> context,
	const shared_ptr<DeviceResources>& deviceResources,
	int nFramesPerSecond)
{
	if (m_bIsVisible)
	{
		DrawMajorHorizontalLines(
			context,
			deviceResources->m_mapBrushes["black"]);

		DrawMajorVerticalLines(
			context,
			deviceResources->m_mapBrushes["black"]);

		float fFramesPerGrid =
			(float)nFramesPerSecond *
			WALKING_SECONDS_PER_GRID;

		DrawMinorHorizontalLines(
			context,
			deviceResources->m_mapBrushes["red"],
			fFramesPerGrid);

		DrawMinorVerticalLines(
			context,
			deviceResources->m_mapBrushes["red"],
			fFramesPerGrid);
	}
}

float Grid::GetColumnWidth()
{
	return (m_fGridWidth - 2.0f * MARGIN) / NUM_GRID_COLUMNS;
}

float Grid::GetRowHeight()
{
	return (m_fWindowHeight - 2.0f * MARGIN) / NUM_GRID_ROWS;
}

void Grid::SetNumColumns(int nNumColumns)
{
	this->m_nNumColumns = nNumColumns;
}

void Grid::SetNumRows(int nNumRows)
{
	this->m_nNumRows = nNumRows;
}

void Grid::SetVisibility(boolean bVisibility)
{
	this->m_bIsVisible = bVisibility;
}

void Grid::DrawMajorHorizontalLines(
	ComPtr<ID2D1DeviceContext1> context,
	ComPtr<ID2D1SolidColorBrush> brush)
{
	// Draw the horizontal lines.
	for (int row = 0; row <= NUM_GRID_ROWS; row++)
	{
		D2D1_POINT_2F src
		{
			(m_fWindowWidth * LEFT_MARGIN_RATIO) + MARGIN,
			MARGIN + (GetRowHeight() * (float)row)
		};

		D2D1_POINT_2F dst
		{
			m_fWindowWidth - (m_fWindowWidth * RIGHT_MARGIN_RATIO) - MARGIN,
			MARGIN + (GetRowHeight() * (float)row)
		};

		context->DrawLine(src, dst, brush.Get(), 0.2f);
	}
}

void Grid::DrawMajorVerticalLines(
	ComPtr<ID2D1DeviceContext1> context,
	ComPtr<ID2D1SolidColorBrush> brush)
{
	// Draw the vertical lines.
	for (int column = 0; column <= NUM_GRID_COLUMNS; column++)
	{
		D2D1_POINT_2F src
		{
			(m_fWindowWidth * LEFT_MARGIN_RATIO) + MARGIN + (GetColumnWidth() * (float)column),
			MARGIN
		};

		D2D1_POINT_2F dst
		{
			(m_fWindowWidth * LEFT_MARGIN_RATIO) + MARGIN + (GetColumnWidth() * (float)column),
			m_fWindowHeight - MARGIN,
		};

		context->DrawLine(src, dst, brush.Get(), 0.2f);
	}

}

// Ticks along the y-axis.
void Grid::DrawMinorHorizontalLines(
	ComPtr<ID2D1DeviceContext1> context,
	ComPtr<ID2D1SolidColorBrush> brush,
	float fFramesPerGrid)
{
	float fPixelsPerFrame =
		m_fGridHeight / fFramesPerGrid;

	for (int i = 0; i < (int)fFramesPerGrid; i++)
	{
		D2D1_POINT_2F src
		{
			m_fWindowWidth / 2.0f - (m_fGridWidth * 0.005f),
			fPixelsPerFrame * (float)i
		};

		D2D1_POINT_2F dst
		{
			m_fWindowWidth / 2.0f + (m_fGridWidth * 0.005f),
			fPixelsPerFrame * (float)i
		};

		context->DrawLine(src, dst, brush.Get(), 0.75f);
	}

	// Draw horizontal has marks for pixels/frame.
	D2D1_POINT_2F srcVMiddle
	{
		m_fWindowWidth / 2.0f,
		m_fWindowHeight * TOP_MARGIN_RATIO
	};

	D2D1_POINT_2F dstVMiddle
	{
		m_fWindowWidth / 2.0f,
		m_fWindowHeight * (1.0f - BOTTOM_MARGIN_RATIO)
	};

	context->DrawLine(srcVMiddle, dstVMiddle, brush.Get(), 0.75f);
}

// Ticks along the x-axis.
void Grid::DrawMinorVerticalLines(
	ComPtr<ID2D1DeviceContext1> context,
	ComPtr<ID2D1SolidColorBrush> brush,
	float fFramesPerGrid)
{
	float fPixelsPerFrame =
		m_fGridWidth / fFramesPerGrid;

	for (int i = 0; i < (int)fFramesPerGrid; i++)
	{
		D2D1_POINT_2F src
		{
			(m_fWindowWidth * LEFT_MARGIN_RATIO) + (fPixelsPerFrame * (float)i),
			m_fWindowHeight / 2.0f - m_fWindowHeight * 0.005f
		};

		D2D1_POINT_2F dst
		{
			(m_fWindowWidth * LEFT_MARGIN_RATIO) + (fPixelsPerFrame * (float)i),
			m_fWindowHeight / 2.0f + m_fWindowHeight * 0.005f
		};

		context->DrawLine(src, dst, brush.Get(), 0.75f);
	}

	// Draw horizontal has marks for pixels/frame.
	D2D1_POINT_2F srcHMiddle
	{
		m_fWindowWidth * LEFT_MARGIN_RATIO,
		m_fWindowHeight / 2.0f
	};

	D2D1_POINT_2F dstHMiddle
	{
		m_fWindowWidth - (m_fWindowWidth * RIGHT_MARGIN_RATIO),
		m_fWindowHeight / 2.0f
	};

	context->DrawLine(srcHMiddle, dstHMiddle, brush.Get(), 0.75f);
}

float Grid::CalculateGridsPerFrame(
	float fVelocity,
	int nFramesPerSecond)
{
	// Calculate the frames/grid at the current FPS.
	//	Ex: 60 FPS * 5 (seconds per grid) = 300 frames per grid.
	float fFramesPerGrid = (float)nFramesPerSecond * fVelocity;

	// Length of each ratio division.
	// Ex: 1.0f / 300 (frames per grid) = 0.00333 grid / frame.
	//	Or ("Move 0.003333 grid for every frame")
	return 1.0f / fFramesPerGrid;
}


text:
pub mod fixture;

use std::env;
use std::path::Path;
use std::process::Command;
use std::time;

use fixture::vhost_user::CmdType;
use fixture::vhost_user::Config as VuConfig;
use fixture::vhost_user::VhostUserBackend;
use fixture::vm::Config as VmConfig;
use fixture::vm::TestVm;
use tempfile::NamedTempFile;

const DEFAULT_BLOCK_SIZE: u64 = 1024 * 1024;

/// Prepare a temporary ext4 disk file.
fn prepare_disk_img() -> NamedTempFile {
    let mut disk = NamedTempFile::new().unwrap();
    disk.as_file_mut().set_len(DEFAULT_BLOCK_SIZE).unwrap();

    // Add /sbin and /usr/sbin to PATH since some distributions put mkfs.ext4 in one of those
    // directories but don't add them to non-root PATH.
    let path = env::var("PATH").unwrap();
    let path = [&path, "/sbin", "/usr/sbin"].join(":");

    // TODO(b/243127910): Use `mkfs.ext4 -d` to include test data.
    Command::new("mkfs.ext4")
        .arg(disk.path().to_str().unwrap())
        .env("PATH", path)
        .output()
        .expect("failed to execute process");
    disk
}

/// Tests virtio-blk device is mountable.
// TODO(b/243127498): Add tests for write and sync operations.
#[test]
fn mount_block() {
    let disk = prepare_disk_img();
    let disk_path = disk.path().to_str().unwrap();
    println!("disk={disk_path}");

    let config =
        VmConfig::new().extra_args(vec!["--block".to_string(), format!("{},ro", disk_path)]);
    let mut vm = TestVm::new(config).unwrap();
    assert_eq!(
        vm.exec_in_guest("mount -t ext4 /dev/vdb /mnt && echo 42")
            .unwrap()
            .trim(),
        "42"
    );
}

/// Tests `crosvm disk resize` works.
#[test]
fn resize() {
    let disk = prepare_disk_img();
    let disk_path = disk.path().to_str().unwrap().to_string();
    println!("disk={disk_path}");

    let config = VmConfig::new().extra_args(vec!["--block".to_string(), disk_path]);
    let mut vm = TestVm::new(config).unwrap();

    // Check the initial block device size.
    assert_eq!(
        vm.exec_in_guest("blockdev --getsize64 /dev/vdb")
            .unwrap()
            .trim()
            .parse::<u64>()
            .unwrap(),
        DEFAULT_BLOCK_SIZE
    );

    let new_size = DEFAULT_BLOCK_SIZE * 2;

    // The index of the disk to resize.
    let disk_index = 1;

    vm.disk(vec![
        "resize".to_string(),
        disk_index.to_string(),
        new_size.to_string(),
    ])
    .expect("Disk resizing command failed");

    // Allow block device size to be updated within 500ms
    let now = time::Instant::now();

    while now.elapsed() <= time::Duration::from_millis(500) {
        if vm
            .exec_in_guest("blockdev --getsize64 /dev/vdb")
            .unwrap()
            .trim()
            .parse::<u64>()
            .unwrap()
            == new_size
        {
            return;
        }
    }
    // Check the new block device size.
    assert_eq!(
        vm.exec_in_guest("blockdev --getsize64 /dev/vdb")
            .unwrap()
            .trim()
            .parse::<u64>()
            .unwrap(),
        new_size
    );
}

fn create_vu_config(cmd_type: CmdType, socket: &Path, disk: &Path) -> VuConfig {
    let socket_path = socket.to_str().unwrap();
    let disk_path = disk.to_str().unwrap();
    println!("disk={disk_path}, socket={socket_path}");
    match cmd_type {
        CmdType::Device => VuConfig::new(cmd_type, "block").extra_args(vec![
            "block".to_string(),
            "--socket".to_string(),
            socket_path.to_string(),
            "--file".to_string(),
            disk_path.to_string(),
        ]),
        CmdType::Devices => VuConfig::new(cmd_type, "block").extra_args(vec![
            "--block".to_string(),
            format!("vhost={},path={}", socket_path, disk_path),
        ]),
    }
}

fn run_vhost_user_test(cmd_type: CmdType) {
    let socket = NamedTempFile::new().unwrap();
    let disk = prepare_disk_img();

    let vu_config = create_vu_config(cmd_type, socket.path(), disk.path());
    let _vu_device = VhostUserBackend::new(vu_config).unwrap();

    let config = VmConfig::new().extra_args(vec![
        "--vhost-user-blk".to_string(),
        socket.path().to_str().unwrap().to_string(),
    ]);
    let mut vm = TestVm::new(config).unwrap();
    assert_eq!(
        vm.exec_in_guest("mount -t ext4 /dev/vdb /mnt && echo 42")
            .unwrap()
            .trim(),
        "42"
    );
}

/// Tests vhost-user block device with `crosvm device`.
#[test]
fn vhost_user_mount() {
    run_vhost_user_test(CmdType::Device);
}

/// Tests vhost-user block device with `crosvm devices` (not `device`).
#[test]
fn vhost_user_mount_with_devices() {
    run_vhost_user_test(CmdType::Devices);
}


text:
<!DOCTYPE html>

        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <title>{% if page.title %}{{ page.title }}{% else %}{{ site.title }}{% endif %}</title>
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta name="description" content="{{ site.description }}">
        <link rel="canonical" href="{{ page.url | replace:'index.html','' | prepend: site.baseurl | prepend: site.url }}">
        {% if site.favicon_img %}
        <link rel="shortcut icon" href="{{ site.favicon_img_path }}" />
        {% endif %}
        <link rel="stylesheet" href="{{ "/css/front.css" | prepend: site.baseurl }}">
        <link href='https://fonts.googleapis.com/css?family=Open+Sans:400,700&subset=latin' rel='stylesheet' type='text/css'>
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css">

            {% if site.front_img %}

            {% endif %}

            {% if site.avatar %}

	        {% if page.layout == 'default' %}

	        {% else %}

	        {% endif %}

            {% endif %}

{{ site.name }}

{{ site.description }}

	  {{ content }}


text:
package unquietcode.tools.flapi.examples.house;

import java.awt.*;

/**
 * @author Ben Fagin
 * @version 05-28-2012
 */
public class Wall {
	private Color color;
	private double width;
	private boolean isWeightBearing;

	public Color getColor() {
		return color;
	}

	public void setColor(Color color) {
		this.color = color;
	}

	public double getWidth() {
		return width;
	}

	public void setWidth(double width) {
		this.width = width;
	}

	public void isWeightBearing(boolean value) {
		isWeightBearing = value;
	}

	public boolean isWeightBearing() {
		return isWeightBearing;
	}
}


text:
Bootstrap Switch
================

Turn checkboxes and radio buttons in toggle switches.

**Version 2.1 is almost ready and features a entire API redesign and source rewriting. Knowing that, your help would be decisive to ship it within days. Give the branch `2.1` a try and post any bugs you might encounter or improvements you would like to integrate in the final release.
With heart, many thanks.**

Demo and Documentation
----------------------
http://www.bootstrap-switch.org

Usage
-----

Include the dependencies: jQuery, Bootstrap and Bootstrap Switch CSS + Javascript:

``` html
[...]
<link href="bootstrap.css" rel="stylesheet">
<link href="bootstrap-switch.css" rel="stylesheet">
<script src="jquery.js"></script>
<script src="bootstrap-switch.js"></script>
[...]
```

Add your checkbox:

```html
<input type="checkbox" name="my-checkbox" checked>
```

Initialize Bootstrap Switch on it:

```javascript
$("[name='my-checkbox']").bootstrapSwitch();
```

Enjoy.

Less
----
If you want to use your bootstrap variables, include `bootstrap-switch.less` in your compilation stack. You can even choose among Bootstrap versions 2.3.2 or 3.*.* compatible source.

Supported browsers
------------------
IE8+ and all the other modern browsers (until proven otherwise: submit a issue and let's see what we can do).

License
-------
Licensed under the Apache License, Version 2.0
http://www.apache.org/licenses/LICENSE-2.0


text:
.class Lcom/android/server/am/ActivityRecord$Token;
.super Landroid/view/IApplicationToken$Stub;
.source "ActivityRecord.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Lcom/android/server/am/ActivityRecord;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x8
    name = "Token"
.end annotation

# instance fields
.field final weakActivity:Ljava/lang/ref/WeakReference;
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "Ljava/lang/ref/WeakReference",
            "<",
            "Lcom/android/server/am/ActivityRecord;",
            ">;"
        }
    .end annotation
.end field

# direct methods
.method constructor <init>(Lcom/android/server/am/ActivityRecord;)V
    .locals 1
    .parameter "activity"

    .prologue
    .line 259
    invoke-direct {p0}, Landroid/view/IApplicationToken$Stub;-><init>()V

    .line 260
    new-instance v0, Ljava/lang/ref/WeakReference;

    invoke-direct {v0, p1}, Ljava/lang/ref/WeakReference;-><init>(Ljava/lang/Object;)V

    iput-object v0, p0, Lcom/android/server/am/ActivityRecord$Token;->weakActivity:Ljava/lang/ref/WeakReference;

    .line 261
    return-void
.end method

# virtual methods
.method public getKeyDispatchingTimeout()J
    .locals 3
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Landroid/os/RemoteException;
        }
    .end annotation

    .prologue
    .line 293
    iget-object v1, p0, Lcom/android/server/am/ActivityRecord$Token;->weakActivity:Ljava/lang/ref/WeakReference;

    invoke-virtual {v1}, Ljava/lang/ref/WeakReference;->get()Ljava/lang/Object;

    move-result-object v0

    check-cast v0, Lcom/android/server/am/ActivityRecord;

    .line 294
    .local v0, activity:Lcom/android/server/am/ActivityRecord;
    if-eqz v0, :cond_0

    .line 295
    invoke-virtual {v0}, Lcom/android/server/am/ActivityRecord;->getKeyDispatchingTimeout()J

    move-result-wide v1

    .line 297
    :goto_0
    return-wide v1

    :cond_0
    const-wide/16 v1, 0x0

    goto :goto_0
.end method

.method public keyDispatchingTimedOut()Z
    .locals 2
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Landroid/os/RemoteException;
        }
    .end annotation

    .prologue
    .line 285
    iget-object v1, p0, Lcom/android/server/am/ActivityRecord$Token;->weakActivity:Ljava/lang/ref/WeakReference;

    invoke-virtual {v1}, Ljava/lang/ref/WeakReference;->get()Ljava/lang/Object;

    move-result-object v0

    check-cast v0, Lcom/android/server/am/ActivityRecord;

    .line 286
    .local v0, activity:Lcom/android/server/am/ActivityRecord;
    if-eqz v0, :cond_0

    .line 287
    invoke-virtual {v0}, Lcom/android/server/am/ActivityRecord;->keyDispatchingTimedOut()Z

    move-result v1

    .line 289
    :goto_0
    return v1

    :cond_0
    const/4 v1, 0x0

    goto :goto_0
.end method

.method public toString()Ljava/lang/String;
    .locals 2

    .prologue
    .line 301
    new-instance v0, Ljava/lang/StringBuilder;

    const/16 v1, 0x80

    invoke-direct {v0, v1}, Ljava/lang/StringBuilder;-><init>(I)V

    .line 302
    .local v0, sb:Ljava/lang/StringBuilder;
    const-string v1, "Token{"

    invoke-virtual {v0, v1}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    .line 303
    invoke-static {p0}, Ljava/lang/System;->identityHashCode(Ljava/lang/Object;)I

    move-result v1

    invoke-static {v1}, Ljava/lang/Integer;->toHexString(I)Ljava/lang/String;

    move-result-object v1

    invoke-virtual {v0, v1}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    .line 304
    const/16 v1, 0x20

    invoke-virtual {v0, v1}, Ljava/lang/StringBuilder;->append(C)Ljava/lang/StringBuilder;

    .line 305
    iget-object v1, p0, Lcom/android/server/am/ActivityRecord$Token;->weakActivity:Ljava/lang/ref/WeakReference;

    invoke-virtual {v1}, Ljava/lang/ref/WeakReference;->get()Ljava/lang/Object;

    move-result-object v1

    invoke-virtual {v0, v1}, Ljava/lang/StringBuilder;->append(Ljava/lang/Object;)Ljava/lang/StringBuilder;

    .line 306
    const/16 v1, 0x7d

    invoke-virtual {v0, v1}, Ljava/lang/StringBuilder;->append(C)Ljava/lang/StringBuilder;

    .line 307
    invoke-virtual {v0}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;

    move-result-object v1

    return-object v1
.end method

.method public windowsDrawn()V
    .locals 2
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Landroid/os/RemoteException;
        }
    .end annotation

    .prologue
    .line 264
    iget-object v1, p0, Lcom/android/server/am/ActivityRecord$Token;->weakActivity:Ljava/lang/ref/WeakReference;

    invoke-virtual {v1}, Ljava/lang/ref/WeakReference;->get()Ljava/lang/Object;

    move-result-object v0

    check-cast v0, Lcom/android/server/am/ActivityRecord;

    .line 265
    .local v0, activity:Lcom/android/server/am/ActivityRecord;
    if-eqz v0, :cond_0

    .line 266
    invoke-virtual {v0}, Lcom/android/server/am/ActivityRecord;->windowsDrawn()V

    .line 268
    :cond_0
    return-void
.end method

.method public windowsGone()V
    .locals 2
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Landroid/os/RemoteException;
        }
    .end annotation

    .prologue
    .line 278
    iget-object v1, p0, Lcom/android/server/am/ActivityRecord$Token;->weakActivity:Ljava/lang/ref/WeakReference;

    invoke-virtual {v1}, Ljava/lang/ref/WeakReference;->get()Ljava/lang/Object;

    move-result-object v0

    check-cast v0, Lcom/android/server/am/ActivityRecord;

    .line 279
    .local v0, activity:Lcom/android/server/am/ActivityRecord;
    if-eqz v0, :cond_0

    .line 280
    invoke-virtual {v0}, Lcom/android/server/am/ActivityRecord;->windowsGone()V

    .line 282
    :cond_0
    return-void
.end method

.method public windowsVisible()V
    .locals 2
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Landroid/os/RemoteException;
        }
    .end annotation

    .prologue
    .line 271
    iget-object v1, p0, Lcom/android/server/am/ActivityRecord$Token;->weakActivity:Ljava/lang/ref/WeakReference;

    invoke-virtual {v1}, Ljava/lang/ref/WeakReference;->get()Ljava/lang/Object;

    move-result-object v0

    check-cast v0, Lcom/android/server/am/ActivityRecord;

    .line 272
    .local v0, activity:Lcom/android/server/am/ActivityRecord;
    if-eqz v0, :cond_0

    .line 273
    invoke-virtual {v0}, Lcom/android/server/am/ActivityRecord;->windowsVisible()V

    .line 275
    :cond_0
    return-void
.end method


text:
'use strict';

angular.module('scenarioEditor.charView', ['ngRoute', 'scenarioServices'])

    .config(['$routeProvider', function ($routeProvider) {
        $routeProvider.when('/charView', {
            templateUrl: '/scenario/charView/',
            controller: 'CharCtrl'
        });
    }])

    .controller('CharCtrl', ['$scope', '$http', 'charService', 'convoService', 'itemService', 'jointService', 'textureService', function ($scope, $http, charService, convoService, itemService, jointService, textureService) {
        $scope.editVisible = false;

        $scope.currBodyPart = "";
        $scope.editBodyPartVisible = false;

        $scope.nameQuery = null;
        $scope.tagsQuery = null;

        $scope.componentSets = [];

        $scope.selectedItem = null;

        $scope.charToImgMap = {};
        $scope.animations = [
            "WAVE",
            "DANCE_1",
            "DANCE_2",
            "CROSS_ARMS",
            "SICK_1",
            "IDLE_TALK_1",
            "IDLE_TALK_2",
            "IDLE_TALK_3",
            "WALK_1",
            "WALK_2",
            "DRUNK_WALK_1",
            "DRUNK_WAVE_1",
            "FLAILING",
            "SWAY",
            "JUMPING_JACKS",
            "BUTLER",
            "DEAD"
        ];

        $scope.getChars = function () {
            return charService.chars();
        };

        $scope.addChar = function () {
            charService.addChar();
            var char = charService.chars()[charService.chars().length - 1];
            $scope.charToImgMap[char.id] = {
                HEAD: [],
                LEFT_ARM: [],
                RIGHT_ARM: [],
                TORSO: [],
                PELVIS: [],
                LEFT_LEG: [],
                RIGHT_LEG: []
            }
        };

        $scope.deleteChar = function (chara) {
            return charService.deleteChar(chara);
        };

        $scope.editChar = function (chara) {
            $scope.editVisible = true;
            $scope.stateId = charService.getStatesLength(chara);
            return charService.editChar(chara);
        };

        $scope.getCurrChar = function () {
            return charService.getCurrChar();
        };

        $scope.getConvos = function () {
            return convoService.conversations();
        };

        $scope.getStates = function (character) {
            return character.states;
        };

        $scope.addState = function (character) {
            return charService.addStateToChar(character, $scope.stateId);
        };

        $scope.deleteState = function (character, state) {
            character.states.splice(character.states.indexOf(state), 1);
        };

        $scope.editBodyPart = function (name) {
            $scope.componentSets = [];
            $scope.nameQuery = null;
            $scope.tagsQuery = null;
            $scope.editBodyPartVisible = true;
            $scope.currBodyPart = name;
            $scope.getComponentImages(name, null, null);
        };

        $scope.closeBodyPart = function () {
            $scope.editBodyPartVisible = false;
        };

        $scope.queryChanged = function () {
            $scope.getComponentImages($scope.currBodyPart, $scope.tagsQuery, $scope.nameQuery);
        };

        $scope.selectComponent = function (component) {
            $scope.updateTexture(charService.getCurrChar(), $scope.currBodyPart, component.jsonRepresentation);
        };

        $scope.updateTexture = function(char, component, jsonUrl){
            charService.setComponentSourceForType(char, $scope.currBodyPart, jsonUrl);

            if(jsonUrl != "" && jsonUrl != undefined) {
                jointService.getJoint(jsonUrl).then(
                    // Success
                    function (joint) {
                        for (var i = 0; i < joint.textures.length; i++) {
                            textureService.getTextureById(joint.textures[i].id).then(
                                function (texture) {
                                    try {
                                        if($scope.charToImgMap.hasOwnProperty(char.id) && $scope.charToImgMap[char.id].hasOwnProperty(component)){
                                            $scope.charToImgMap[char.id][component].push(texture);
                                        }
                                    }catch (err){
                                        //console.log(err);
                                    }
                                },
                                function (response) {
                                }
                            )
                        }
                    },
                    // Failure
                    function (response) {
                    }
                );
                $scope.closeBodyPart();
            }
        };

        $scope.updateTextures = function(char){
            $scope.updateTexture(char, "HEAD", char.getComponentForType("HEAD").src);
            $scope.updateTexture(char, "TORSO", char.getComponentForType("TORSO").src);
            $scope.updateTexture(char, "LEFT_ARM", char.getComponentForType("LEFT_ARM").src);
            $scope.updateTexture(char, "RIGHT_ARM", char.getComponentForType("RIGHT_ARM").src);
            $scope.updateTexture(char, "PELVIS", char.getComponentForType("PELVIS").src);
            $scope.updateTexture(char, "LEFT_LEG", char.getComponentForType("LEFT_LEG").src);
            $scope.updateTexture(char, "RIGHT_LEG", char.getComponentForType("RIGHT_LEG").src);
        };

        $scope.getTexturesForComponent = function (char, component) {
            if (char != null) {
                if (!$scope.charToImgMap.hasOwnProperty(char.id)) {
                    $scope.charToImgMap[char.id] = {
                        HEAD: [],
                        LEFT_ARM: [],
                        RIGHT_ARM: [],
                        TORSO: [],
                        PELVIS: [],
                        LEFT_LEG: [],
                        RIGHT_LEG: []
                    }
                }
                return $scope.charToImgMap[char.id][component];
            } else {
                return [];
            }
        };

        $scope.getTextureUrlsForComponent = function (component) {
            jointService.getJoint(charService.getCurrChar().getComponentForType(component));
        };

        $scope.getUnusedItems = function () {
            var items = itemService.getUnusedItems();
            if (items.length > 0) {
                $scope.selectedItem = items[0].id;
            }
            return items;
        };

        $scope.addSelectedItem = function () {
            if ($scope.selectedItem != null) {
                $scope.getCurrChar().items.push($scope.selectedItem);
            }
        };

        $scope.itemsForCurrentChar = function () {
            var itemObjs = [];
            if (charService.getCurrChar() != null) {
                for (var i = 0; i < charService.getCurrChar().items.length; i++) {
                    itemObjs.push(itemService.getById(charService.getCurrChar().items[i]));
                }
            }
            return itemObjs;
        };

        $scope.getComponentImages = function (setType, tags, name) {
            var params = {};
            if (setType != null && setType.length > 0) {
                var s = setType;
                var splitSetType = setType.split("_");
                if (splitSetType.length > 1) {
                    s = splitSetType[1];
                }
                params["setType"] = s;
            }
            if (tags != null && tags.length > 0) {
                params["tags"] = tags;
            }
            if (name != null && name.length > 0) {
                params["name"] = name;
            }
            $http.get("/scenario/service/component_set", {
                    params: params
                })
                .then(function success(response) {
                        var correctedData = response.data;
                        $scope.componentSets = correctedData;
                    },
                    function failure(response) {
                        console.log("Failure");
                    }
                );
        };

        $scope.getChars = function(){
          return charService.chars();
        };

        $scope.$watch('getChars()', function () {
            for (var i = 0; i < charService.chars().length; i++) {
                $scope.updateTextures(charService.chars()[i]);
            }
        });

        $scope.clearComponent = function(component){
            charService.getCurrChar().getComponentForType(component).src = "";
            $scope.charToImgMap[charService.getCurrChar().id][component] = [];
        };

        $scope.getVoices = function(){
            var voices = {
                1 :  '1 - Male - "EEEE"',
                2 :  '2 - Male - "AHH"',
                3 :  '3 - Male - "ooawh"',
                4 :  '4 - High Pitch Male - "AH" like a bird',
                5 :  '5 - Male - "Ahh" like at the dentist, fast',
                6 :  '6 - Low Male - "ooo" dumb sounding',
                7 :  '7 - Male - "Ehh" dumb sounding, like you\'ve moved your tounge to the back of your throat',
                8 :  '8 - Low Male - "Ooeh" dumb sounding',
                9 :  '9 - Low Male - "Ah" dumb sounding',
                10 : '10 - "Wuaaah" - kinda sounds like a duck quack',
                11 : '11 - "Khaah" - kinda sounds like a duck quack kinda',
                12 : '12 - Low Male - "eh" dumb sounding',
                13 : '13 - "Ueeeeh" - kinda sounds like a duck quack',
                14 : '14 - Cat - "Wuuhh" ',
                15 : '15 - Cat - "Neeeeuh"',
                16 : '16 - Cat- "Neeh"',
                17 : '17 - Cat- "Meow"',
                18 : '18 - Low Male - "Boum"',
                19 : '19 - Male - "Buaop"',
                20 : '20 - Male - Kinda sounds like a seal "arf"',
                21 : '21 - Low Male - "Orw"',
                22 : '22 - Male - "Oowh"',
                23 : '23 - Male - "Arl"',
                24 : '24 - High Male - "Mah"',
                25 : '25 - High Male -  "Mowh"',
                26 : '26 - Male - "Ehh" - sounds annoyed',
                27 : '27 - Male - "Grrrrah" - sounds annoyed/mad',
                28 : '28 - Male - "Uhh" - sounds dumb/scared',
                29 : '29 - High Robot - 1 beep',
                30 : '30 - High Robot - Wobbly Squeek + fade down',
                31 : '31 - High Robot - Wobbly Squeek + fade up',
                32 : '32 - Robot - Extra Wobble',
                33 : '33 - High Robot  - Bing',
                34 : '34 - Robot - Bing',
                35 : '35 - Lower Robot - Bing',
                36 : '36 - Low Robot - Boop',
            }

            return voices;
        }

        for(var i = 0; i < charService.chars().length; i++){
            $scope.updateTextures(charService.chars()[i]);

        }

    }]);


text:
/**
 * Created by Werlon on 20/05/2017.
 */
export class Localizacao {

  constructor(
    public lat?: Number,
    public lon?: Number,
    public org?: String,
    public query?: String,
    public country?: String,
    public dataHora?: String,
    public dominio?: String,
    public _id?: String) {

  }
}