text:
import {expect} from 'chai'
import td from 'testdouble'
import proxyquire from 'proxyquire'

describe("post-processors.js", () => {
  var postProcessors
  var transactionStats
  var invertCreditCard
  var clearTextValues

  beforeEach(() => {
    transactionStats = td.object(['generateStatistics'])
    invertCreditCard = td.object(['shouldApply', 'processTransactions'])
    clearTextValues = td.object(['shouldApply', 'processTransactions'])
    postProcessors = proxyquire('../src/scripts/ynab/processors/post-processors.js', {
      '../transaction-stats': transactionStats,
      './invert-credit-card': invertCreditCard,
      './clear-text-values': clearTextValues
    })
  })

  afterEach(() => {
    td.reset()
  })

  describe("processTransactions", () => {
    it("should apply processors", () => {
      // given:
      let stats = 'test-stats'
      let transactions = 'test-transactions'

      // expect:
      td.when(transactionStats.generateStatistics(transactions))
        .thenReturn(stats)

      td.when(invertCreditCard.shouldApply(transactions, stats))
        .thenReturn(true)
      td.when(clearTextValues.shouldApply('processed-transactions', stats))
        .thenReturn(true)

      td.when(invertCreditCard.processTransactions(transactions, stats))
        .thenReturn('processed-transactions')
      td.when(clearTextValues.processTransactions('processed-transactions', stats))
        .thenReturn('processed-transactions-2')

      // when, then:
      expect(postProcessors.processTransactions(transactions)).to.equal('processed-transactions-2')
    })

    it("should not apply processors", () => {
      // given:
      let stats = 'test-stats'
      let transactions = 'test-transactions'

      // expect:
      td.when(transactionStats.generateStatistics(transactions))
        .thenReturn(stats)
      td.when(invertCreditCard.shouldApply(transactions, stats))
        .thenReturn(false)
      td.when(clearTextValues.shouldApply(transactions, stats))
        .thenReturn(false)
      td.when(invertCreditCard.processTransactions(transactions, stats))
        .thenReturn('processed-transactions')
      td.when(clearTextValues.processTransactions('processed-transactions', stats))
        .thenReturn('processed-transactions-2')

      // when, then:
      expect(postProcessors.processTransactions(transactions)).to.equal('test-transactions')
    })
  })
})


text:
package edu.missouristate.mote.propertygrid;

import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.table.DefaultTableModel;
import edu.missouristate.mote.events.ChangeListener;
import edu.missouristate.mote.events.ChangeNotifier;
import edu.missouristate.mote.Constants;

/**
 * Table component of the property grid.
 */
public final class PropertyTable extends JTable {

    // *************************************************************************
    // FIELDS
    // *************************************************************************

    /** Selected object backing the model. */
    private ChangeNotifier selectedObject;

    /** Data for each row in the table. */
    private final transient List<PropertyTableRow> tableRows;

    // *************************************************************************
    // CONSTRUCTORS
    // *************************************************************************

    /**
     * Initialize a new instance of a PropertyTable.
     */
    public PropertyTable() {
        super();
        tableRows = new ArrayList<>();
        // Setup an empty model
        final Object[][] data = new Object[][]{{null, null}};
        this.setModel(new DefaultTableModel(data, Constants.GRID_COL_NAMES));
        // General settings
        this.setCellSelectionEnabled(true);
        this.setEditingColumn(1);
        this.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        this.setGridColor(Constants.GRAPH_GRID_COLOR);
        this.setShowGrid(true);
        this.setRowHeight(Constants.CELL_HEIGHT);
    }

    // *************************************************************************
    // PRIVATE METHODS
    // *************************************************************************

    /**
     * Return the row number for the next non-category row searching either
     * forwards or backwards through the table. If no non-category row can be
     * found, return the current row number.
     *
     * @param isForward true to search forwards; false, backwards
     * @return next non-category row number
     */
    private int getNextRow(final boolean isForward) {
        final int step = isForward ? 1 : -1;
        int counter = 0, currentRow = getSelectedRow();
        boolean isFound = false;
        while (!isFound && counter < tableRows.size() + 1) {
            currentRow += step;
            if (currentRow >= tableRows.size()) {
                currentRow = 0;
            } else if (currentRow < 0) {
                currentRow = tableRows.size() - 1;
            }
            if (!tableRows.get(currentRow).isCategory()) {
                //&& !tableRows.get(currentRow).isReadonly()) {
                isFound = true;
            }
            counter++;
        }
        return isFound ? currentRow : getSelectedRow();
    }

    /**
     * Resize the columns in this table.
     */
    private void resizeColumns() {
        final int nameWidth = (int) (this.getWidth() * Constants.GRID_NAME_PCT);
        this.getColumnModel().getColumn(0).setPreferredWidth(nameWidth);
    }

    // *************************************************************************
    // PROTECTED METHODS
    // *************************************************************************

    /**
     * Handle key events, only allowing certain cells to be selected.
     *
     * @param e event arguments
     */
    @Override
    protected void processKeyEvent(final KeyEvent e) {
        final int code = e.getKeyCode();
        if (e.getID() != KeyEvent.KEY_PRESSED) {
        // Let anything other than key presses pass through
            super.processKeyEvent(e);
        } else if (code == KeyEvent.VK_LEFT || code == KeyEvent.VK_RIGHT) {
            // Ignore the left/right arrow keys
            e.consume();
        } else if (code == KeyEvent.VK_UP
                || (code == KeyEvent.VK_ENTER && e.isShiftDown())
                || (code == KeyEvent.VK_TAB && e.isShiftDown())) {
            // Move backward
            final int newRow = getNextRow(false);
            super.processKeyEvent(e);
            this.changeSelection(newRow, 1, false, false);
        }  else if (code == KeyEvent.VK_DOWN
                || (code == KeyEvent.VK_ENTER && !e.isShiftDown())
                || (code == KeyEvent.VK_TAB && !e.isShiftDown())) {
            // Move forward
            final int newRow = getNextRow(true);
            super.processKeyEvent(e);
            this.changeSelection(newRow, 1, false, false);
        } else {
            // Normal processing
            super.processKeyEvent(e);
        }
    }

    /**
     * Handle mouse events, only allowing certain cells to be selected.
     *
     * @param e event arguments
     */
    @Override
    protected void processMouseEvent(final MouseEvent e) {
        final int row = this.rowAtPoint(e.getPoint());
        final int col = this.columnAtPoint(e.getPoint());
        boolean ignore = false;
        if (e.getClickCount() == 0) {
            // Only care about clicks
            ignore = true;
        } else if (row < 0 || row >= tableRows.size() || col < 0 || col > 1) {
            // Invalid rows/cols
            ignore = true;
        } else if (col == 0 || tableRows.get(row).isCategory()) {
            // Can't click on property name/category cells
            ignore = true;
        }
        if (ignore) {
            e.consume();
        } else {
            super.processMouseEvent(e);
        }
    }

    // *************************************************************************
    // PUBLIC METHODS
    // *************************************************************************

    /**
     * Return the description for the current selection.
     *
     * @return current row description
     */
    public String getDescription() {
        final int row = this.getSelectedRow();
        if (row > -1 && row < tableRows.size()) {
            return tableRows.get(row).getDescription();
        }
        return "";
    }

    /**
     * Return the object backing the table model.
     *
     * @return selected object
     */
    public Object getSelectedObject() {
        return selectedObject;
    }

    /**
     * Return false for any cell in the name column or category row; otherwise
     * the default value for the editable property of the cell.
     *
     * @param row row number
     * @param col column number
     * @return True if the cell is editable; false, otherwise
     */
    @Override
    public boolean isCellEditable(final int row, final int col) {
        // Invalid row
        if (row < 0 || row >= tableRows.size()) {
            return false;
        }
        // Property/category name
        if (col == 0) {
            return false;
        }
        // Category row
        if (tableRows.get(row).isCategory()) {
            return false;
        }
        // Read-only column
        if (tableRows.get(row).isReadonly()) {
            return false;
        }
        return super.isCellEditable(row, col);
    }

    /**
     * Refresh the model from the underlying object.
     */
    public void refresh() {
        for (int row = 0; row < tableRows.size(); row++) {
            final Method getter = tableRows.get(row).getGetter();
            try {
                if (getter != null) {
                    final Double value = (Double) getter.invoke(selectedObject);
                    this.setValueAt(value.toString(), row, 1);
                }
            } catch (IllegalAccessException | InvocationTargetException ex) {
                this.setValueAt("", row, 1);
            }
        }
    }

    /**
     * Set the object backing the table model.
     *
     * @param object object
     */
    public void setSelectedObject(final ChangeNotifier object) {
        // Set object and rows
        selectedObject = object;
        tableRows.clear();
        tableRows.addAll(ObjectLoader.getRows(object));
        // Create a new model
        final Object[][] data = new Object[tableRows.size()][2];
        for (int index = 0; index < tableRows.size(); index++) {
            data[index][0] = tableRows.get(index).getName();
            try {
                final Method getter = tableRows.get(index).getGetter();
                if (getter != null) {
                    data[index][1] = getter.invoke(object);
                }
            } catch (IllegalAccessException | InvocationTargetException ex) {
                data[index][1] = "";
            }
        }
        this.setModel(new DefaultTableModel(data, Constants.GRID_COL_NAMES));
        resizeColumns();
        // Add custom renderers for each column and an editor for the values
        final PropertyCellEditor editor = new PropertyCellEditor(selectedObject,
                tableRows);
        final PropertyCellRenderer renderer = new PropertyCellRenderer(
                tableRows);
        this.getColumnModel().getColumn(0).setCellRenderer(renderer);
        this.getColumnModel().getColumn(1).setCellRenderer(renderer);
        this.getColumnModel().getColumn(1).setCellEditor(editor);
        // Set our row to the first available one to edit
        this.changeSelection(0, 1, false, false);
        final int row = getNextRow(true);
        this.changeSelection(row, 1, false, false);
        // Listen to change events on the underlying object
        selectedObject.addChangeListener(new ChangeListener() {
            @Override
            public void stateChanged() {
                refresh();
            }
        });
    }
}

redpajama_set_name: RedPajamaGithub


text:
package main

import (
	"bytes"
	"strings"
	"text/template"

	"golang.org/x/perf/benchstat"
)

var renderTemplate = template.Must(template.New("").Funcs(renderFuncs).Parse(`
{{- range $i, $table := . }}
Benchmark|Old {{.Metric}}|New {{.Metric}}{{if .OldNewDelta}}|Delta{{end}}
-|-|-{{if .OldNewDelta}}|-{{end}}

	{{- range $group := group $table.Rows }}
		{{- range $row := . }}
{{ .Benchmark }}{{range .Metrics}}|{{.Format $row.Scaler}}{{end}}{{if $table.OldNewDelta}}|{{replace .Delta "-" "−" -1}} {{.Note}}{{ end }}
		{{- end }}
	{{- end }}
{{ end }}`))

var renderFuncs = template.FuncMap{
	"replace": strings.Replace,
	"group":   formGroup,
}

func formGroup(rows []*benchstat.Row) (out [][]*benchstat.Row) {
	var group string
	var cur []*benchstat.Row
	for _, r := range rows {
		if r.Group != group {
			group = r.Group
			if len(cur) > 0 {
				out = append(out, cur)
				cur = nil
			}
		}
		cur = append(cur, r)
	}
	if len(cur) > 0 {
		out = append(out, cur)
	}
	return
}

func formatMarkdown(buf *bytes.Buffer, tables []*benchstat.Table) error {
	return renderTemplate.Execute(buf, tables)
}


text:
package br.puc_rio.ele.lvc.interimage.common.udf;

import java.io.IOException;
import java.util.Map;

import org.apache.pig.EvalFunc;
import org.apache.pig.data.DataType;
import org.apache.pig.data.Tuple;
import org.apache.pig.impl.logicalLayer.schema.Schema;

/**
 * A UDF that updates the properties map with the given field.

 * Example:

 * 		A = load 'mydata' as (field, props);

 * 		B = foreach A generate ToProps(field, 'name', props) as props;
 * @author Rodrigo Ferreira
 *
 */
public class ToProps extends EvalFunc<Map<String,Object>> {

	/**
     * Method invoked on every tuple during foreach evaluation.
     * @param input tuple; first column is assumed to have the value

     * second column is assumed to have the field name

     * third column is assumed to have the properties map
     * @exception java.io.IOException
     * @return map with the given field
     */
	@Override
	public Map<String,Object> exec(Tuple input) throws IOException {
		if (input == null || input.size() < 3)
            return null;

		try {
			Object objField = input.get(0);
			String name = DataType.toString(input.get(1));
			Map<String,Object> objProperties = DataType.toMap(input.get(2));

			objProperties.put(name,objField);

			return objProperties;

		} catch (Exception e) {
			throw new IOException("Caught exception processing input row ", e);
		}
	}

	@Override
    public Schema outputSchema(Schema input) {
        return new Schema(new Schema.FieldSchema(null, DataType.MAP));
    }

}


text:
"use strict"

// Get our tools.
const Joi = require("@hapi/joi")

class Multicolour_CSRF_Token {
  /**
   * Register this plugin with hapijs.
   * @param  {Hapi.Server} server to register this plugin to.
   * @return {void}
   */
  register(multicolour_server) {
    // Get the server.
    const server = multicolour_server.request("raw")

    // Register the plugin.
    server.register({
      register: require("crumb"),
      options: {
        restful: true
      }
    }, err => {
      if (err) {
        throw err
      }
    })

    // Set the csrf token header validator.
    multicolour_server.request("header_validator")
      .set("x-csrf-token", Joi.string().required().description("The CSRF token to validate."))

    // Make sure, before we respond we add the CSRF token.
    server.ext("onPreResponse", (request, reply) => {
      // Make sure we set the x-csrf-token regardless of
      // whether it was an error or a successful request.
      if (request.response.isBoom) {
        request.response.output.headers["x-csrf-token"] = request.plugins.crumb
      }
      else {
        request.response.header("x-csrf-token", request.plugins.crumb)
      }

      // Continue with the reply.
      reply.continue()
    })

    // Create a route to get a new CSRF token.
    server.route({
      method: "GET",
      path: "/csrf",
      config: {
        auth: false,
        handler: (request, reply) => reply({ crumb: request.plugins.crumb }),
        description: "Get a CSRF token.",
        notes: "Get a valid CSRF token for future requests",
        tags: ["api", "csrf"],
        response: {
          schema: Joi.object({ crumb: Joi.string().required() })
            .meta({ className: "Get a CSRF token" })
        }
      }
    })
  }
}

module.exports = Multicolour_CSRF_Token


text:
package forimpatient.chapter11

/**
  * Created by Iryna Kharaborkina on 8/8/16.
  *
  * Solution to the Chapter 11 Exercise 01 'Scala for the Impatient' by Horstmann C.S.
  *
  * According to the precedence rules, how are 3 + 4 -> 5 and 3 -> 4 + 5 evaluated?
  */
object Exercise01 extends App {
  println("the Chapter 11 Exercise 01")

  // First from left to right
  println(3 + 4 -> 5)

  // Second is incorrect as 3 -> 4 produce Tuple2 and + is not defined, can be fixed such as
  println(3 -> (4 + 5))
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WProject.WebApiClasses.Classes;
using WProject.WebApiClasses.Data;
using Task = WProject.WebApiClasses.Classes.Task;

namespace WProject.Classes
{
    public static class WPSuite
    {
        public static User ConnectedUser { get; set; }
        public static Project SelectedProject { get; set; }
        public static Spring SelectedSpring { get; set; }
        public static Category SelectedCategory { get; set; }

        public static int ConnectedUserId => ConnectedUser?.Id ?? 0;
        public static int SelectedProjectId => SelectedProject?.Id ?? 0;

        public static Task CreateTask(Backlog backlog)
        {
            return new Task
            {
                BacklogId = backlog.Id,
                CreatedAt = DateTime.Now,
                CreatedById = ConnectedUserId,
                TypeId = GetTaskTypeId()
            };
        }

        private static int GetTaskTypeId()
        {
            return SimpleCache.GetAll<DictItem>()
                              .FirstOrDefault(di => di.Type == DictItem.Types.TaskType && di.Code == Task.Types.TASK)?
                              .Id ?? 0;
        }

        public static Backlog CreateBacklog(Category category)
        {
            return new Backlog
            {
                CategoryId = category.Id,
                CreatedAt = DateTime.Now,
                CreatedById = ConnectedUserId,
                TypeId = GetBacklogTypeId()
            };
        }
        private static int GetBacklogTypeId()
        {
            return SimpleCache.GetAll<DictItem>()
                              .FirstOrDefault(di => di.Type == DictItem.Types.BacklogType && di.Code == Backlog.Types.BACKLOG)?
                              .Id ?? 0;
        }
    }
}


text:
<?php

/**
 * Class LaraCartTest.
 */
class LaraCartTest extends Orchestra\Testbench\TestCase
{
    use \LukePOLO\LaraCart\Tests\LaraCartTestTrait;

    /**
     * Test getting the laracart instance.
     */
    public function testGetInstance()
    {
        $this->assertEquals(
            new \LukePOLO\LaraCart\LaraCart($this->session, $this->events, $this->authManager),
            $this->app->make('laracart')
        );
    }

    /**
     * Test setting the instance.
     */
    public function testSetInstance()
    {
        $this->assertNotEquals(
            new \LukePOLO\LaraCart\LaraCart($this->session, $this->events, $this->authManager),
            $this->laracart->setInstance('test')
        );
    }

    /**
     * Test to make sure we get default instance.
     */
    public function testGetInstancesDefault()
    {
        $this->assertEquals('default', $this->laracart->getInstances()[0]);
    }

    /**
     * Test to make sure we can get instances.
     */
    public function testGetInstances()
    {
        $this->laracart->setInstance('test');
        $this->laracart->setInstance('test');
        $this->laracart->setInstance('test');
        $this->laracart->setInstance('test-2');
        $this->laracart->setInstance('test-3');

        $this->assertCount(4, $this->laracart->getInstances());
    }

    /**
     * Testing the money format function.
     */
    public function testFormatMoney()
    {
        $this->assertEquals('$25.00', $this->laracart->formatMoney('25.00'));
        $this->assertEquals('€25.00', $this->laracart->formatMoney('25.00', null, 'EUR'));
        $this->assertEquals('25.00', $this->laracart->formatMoney('25.00', null, null, false));

        $this->assertEquals('$25.56', $this->laracart->formatMoney('25.555'));
        $this->assertEquals('$25.54', $this->laracart->formatMoney('25.544'));
    }

    /**
     * Testing the money format function with the prices_in_cents config setting.
     */
    public function testFormatMoneyPricesInCents()
    {
        $this->app['config']->set('laracart.prices_in_cents', true);

        $this->assertEquals('$25.00', $this->laracart->formatMoney(2500));
        $this->assertEquals('CA$25.00', $this->laracart->formatMoney(2500, null, 'CAD'));
        $this->assertEquals(2500, $this->laracart->formatMoney(2500, null, null, false));

        $this->assertEquals('$25.01', $this->laracart->formatMoney(2500.55));
        $this->assertEquals('$25.00', $this->laracart->formatMoney(2500.44));

        $this->assertEquals(2501, $this->laracart->formatMoney(2500.55, null, null, false));
        $this->assertEquals(2500, $this->laracart->formatMoney(2500.44, null, null, false));
    }

    /**
     * Test getting the attributes from the cart.
     */
    public function testGetAttributes()
    {
        $this->laracart->setAttribute('test1', 1);
        $this->laracart->setAttribute('test2', 2);

        $this->assertCount(2, $attributes = $this->laracart->getAttributes());

        $this->assertEquals(1, $attributes['test1']);
        $this->assertEquals(2, $attributes['test2']);
    }

    /**
     * Test removing attributes from the cart.
     */
    public function testRemoveAttribute()
    {
        $this->laracart->setAttribute('test1', 1);

        $this->assertEquals(1, $this->laracart->getAttribute('test1'));

        $this->laracart->removeAttribute('test1');

        $this->assertNull($this->laracart->getAttribute('test1'));
    }

    /**
     * Testing if the item count matches.
     */
    public function testCount()
    {
        $this->addItem(2);

        $this->assertEquals(2, $this->laracart->count());
        $this->assertEquals(1, $this->laracart->count(false));
    }

    /**
     * Makes sure that when we empty the cart it deletes all items.
     */
    public function testEmptyCart()
    {
        $this->addItem();

        $this->laracart->setAttribute('test', 1);

        $this->laracart->emptyCart();

        $this->assertEquals(1, $this->laracart->getAttribute('test'));
        $this->assertEquals(0, $this->laracart->count());
    }

    /**
     * Test destroying the cart rather than just emptying it.
     */
    public function testDestroyCart()
    {
        $this->addItem();

        $this->laracart->setAttribute('test', 1);

        $this->laracart->destroyCart();

        $this->assertEquals(null, $this->laracart->getAttribute('test'));
        $this->assertEquals(0, $this->laracart->count());
    }

    /**
     * Testing to make sure if we switch carts and destroy it destroys the proper cart.
     */
    public function testDestroyOtherCart()
    {
        $this->addItem();

        $this->laracart->setInstance('test');

        $this->addItem();

        $cart = $this->laracart->get('test');

        $this->assertEquals(1, $cart->count());

        $this->laracart->destroyCart();

        $cart = $this->laracart->get('test');

        $this->assertEquals(0, $cart->count());

        $cart = $this->laracart->get();

        $this->assertEquals(1, $cart->count());
    }

    /**
     * Tests if generating a new hash when we change an option.
     */
    public function testGeneratingHashes()
    {
        $item = $this->addItem();

        $prevHash = $item->getHash();

        $item->name = 'NEW NAME';

        $this->assertNotEquals($prevHash, $item->getHash());
    }

    /**
     * Tests if generating a same hash when we change an excluded option.
     */
    public function testGeneratingHashesExistConfig()
    {
        $this->app['config']->set('laracart.exclude_from_hash', ['some_option']);

        $item = $this->addItem(1, 1, true, ['some_option' => 'some value']);

        $prevHash = $item->getHash();

        $item->some_option = 'NEW VALUE';

        $this->assertEquals($prevHash, $item->getHash());
    }

    /**
     * Tests the facade.
     */
    public function getFacadeName()
    {
        $facade = new \LukePOLO\LaraCart\Facades\LaraCart();
        $this->assertEquals('laracart', $facade::getFacadeAccessor());
    }
}


text:
package com.google.cloud.pso.bq_pii_classifier.functions.dispatcher;

import com.google.cloud.pso.bq_pii_classifier.entities.DispatcherType;
import com.google.cloud.pso.bq_pii_classifier.entities.NonRetryableApplicationException;
import com.google.cloud.pso.bq_pii_classifier.entities.Operation;
import com.google.cloud.pso.bq_pii_classifier.entities.SolutionMode;
import com.google.cloud.pso.bq_pii_classifier.services.bq.BigQueryServiceImpl;
import com.google.cloud.pso.bq_pii_classifier.services.scan.StandardDlpResultsScannerImpl;
import com.google.cloud.pso.bq_pii_classifier.services.pubsub.PubSubPublishResults;
import com.google.cloud.pso.bq_pii_classifier.services.pubsub.PubSubServiceImpl;
import com.google.cloud.pso.bq_pii_classifier.services.pubsub.FailedPubSubMessage;
import com.google.cloud.pso.bq_pii_classifier.services.pubsub.SuccessPubSubMessage;
import com.google.common.collect.Lists;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import static org.junit.Assert.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.lenient;
import static org.mockito.Mockito.mock;

@RunWith(MockitoJUnitRunner.class)
public class DispatcherTest {

    @Mock
    StandardDlpResultsScannerImpl dlpResultsService;
    @Mock BigQueryServiceImpl bqServiceMock;
    @Mock DispatcherConfig config = new DispatcherConfig(
            "testProjectId",
            "testComputeRegionId",
            "testDataRegionId",
            "testTaggerTopic",
            DispatcherType.INSPECTION,
            SolutionMode.STANDARD_DLP
    );
    @Mock String runId = "R-testxxxxxxx";

    @InjectMocks Dispatcher function;

    @Before
    public void setUp() throws IOException, NonRetryableApplicationException, InterruptedException {

        // mock dlpResultsService

        // use lenient() to disable strict stubbing. Mockito detects that the stubs are not used by they actually are!
        lenient().when(dlpResultsService.listParents("p1")).thenReturn(
                Arrays.asList("p1.d1","p1.d2")
        );
        lenient().when(dlpResultsService.listParents("p2")).thenReturn(
                Arrays.asList("p2.d1","p2.d2")
        );

        // list p1 tables
        lenient().when(dlpResultsService.listChildren("p1", "d1")).thenReturn(
                Arrays.asList("p1.d1.t1", "p1.d1.t2")
        );

        lenient().when(dlpResultsService.listChildren("p1", "d2")).thenReturn(
                Arrays.asList("p1.d2.t1", "p1.d2.t2")
        );

        // list p2 tables
        lenient().when(dlpResultsService.listChildren("p2", "d1")).thenReturn(
                Arrays.asList("p2.d1.t1", "p2.d1.t2")
        );

        lenient().when(dlpResultsService.listChildren("p2", "d2")).thenReturn(
                Arrays.asList("p2.d2.t1")
        );

        // Mock bqService
        lenient().when(bqServiceMock.getDatasetLocation(anyString(), anyString())).thenReturn("supported-region");
        lenient().when(bqServiceMock.getDatasetLocation("p2", "d2")).thenReturn("unsupported-region");

    }

    @Test
    public void testDispatcher_withTables () throws IOException, NonRetryableApplicationException, InterruptedException {

        BigQueryScope bigQueryScope = new BigQueryScope(
                Arrays.asList("p1", "p2"),
                Arrays.asList("p1.d2"), // should have no effect
                new ArrayList<>(),
                Arrays.asList("p1.d1.t1", "p1.d1.t2"),
                new ArrayList<>()
        );

        List<String> expectedOutput = Lists.newArrayList("p1.d1.t1", "p1.d1.t2");
        List<String> actualOutput = testWithInput(bigQueryScope);

        assertEquals(expectedOutput, actualOutput);
    }

//    @Test
//    public void testDispatcher_withDatasets () throws IOException {
//
//        String jsonPayLoad = "{\"tablesInclude\":\"\""
//                + ",\"tablesExclude\":\"p1.d1.t1\""
//                + ",\"datasetsInclude\":\"p1.d1, p1.d2\""
//                + ",\"datasetsExclude\":\"\""
//                + ",\"projectsInclude\":\"p2\"" // should have no effect
//                + "}";
//
//        List<String> expectedOutput = Lists.newArrayList("p1.d1.t2", "p1.d2.t1", "p1.d2.t2");
//        List<String> actualOutput = testWithInput(jsonPayLoad);
//
//        assertEquals(expectedOutput, actualOutput);
//    }
//
//    @Test
//    public void testDispatcher_withProjects () throws IOException {
//
//        String jsonPayLoad = "{\"tablesInclude\":\"\""
//                + ",\"tablesExclude\":\"p1.d2.t1\""
//                + ",\"datasetsInclude\":\"\""
//                + ",\"datasetsExclude\":\"p1.d1\""
//                + ",\"projectsInclude\":\"p1, p2\"" // should have no effect
//                + "}";
//
//        List<String> expectedOutput = Lists.newArrayList("p1.d2.t2", "p2.d1.t1", "p2.d1.t2");
//        List<String> actualOutput = testWithInput(jsonPayLoad);
//
//        assertEquals(expectedOutput, actualOutput);
//    }

    private List<String> testWithInput (BigQueryScope bigQueryScope) throws IOException, NonRetryableApplicationException, InterruptedException {

        //Dispatcher function = new Dispatcher(envMock, bqServiceMock, cloudTasksServiceMock);
        PubSubPublishResults results = function.execute(bigQueryScope, "");

        PubSubServiceImpl pubSubServiceMock = mock(PubSubServiceImpl.class);
        lenient().when(pubSubServiceMock.publishTableOperationRequests(anyString(), anyString(), any())).thenReturn(
                new PubSubPublishResults(
                        Arrays.asList(
                                new SuccessPubSubMessage(
                                        new Operation("p1.d1.t1", "runId", "trackingId"),
                                        "publishedMessageId"
                                ),
                                new SuccessPubSubMessage(
                                        new Operation("p1.d1.t2", "runId", "trackingId"),
                                        "publishedMessageId"
                                )
                        ),
                        Arrays.asList(
                                new FailedPubSubMessage(
                                        new Operation("","",""),
                                        new Exception("test fail message")
                                )
                        )
                ));

        return results.getSuccessMessages().stream().map(x -> ((Operation) x.getMsg()).getEntityKey()).collect(Collectors.toList());
    }
}


text:
package core

import (
	"fmt"
	"github.com/nazarazzUA/app"
	"github.com/nazarazzUA/app/cli"
)

type WebCommands struct {
	webApp *app.WebApplication
}

func (web * WebCommands) RegisterCommand(cli *cli.CliApplication) {

	handler := func (){
		web.webApp.Run();
	}

	cli.AddHandler("web.start-server", "start golang dev server as port 8080", handler);
	cli.AddHandler("web.stop-server", "stop golang dev server as port 8080", web.stopWebServer);
}

func (web * WebCommands) stopWebServer() {
	fmt.Println("Stop web server");
}


text:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

$lang	= array(

	'authenticate_module_name'			=> 'Authenticate',
	'authenticate_module_description'	=> 'Front-end authentication that doesn\'t suck',

	'authenticate_failed_message_email'	=> 'That e-mail address and password was not found',
	'authenticate_failed_message_user'	=> 'That username and password was not found',
	'authenticate_invalid_email'		=> 'That is not an e-mail that has been previously registered',
	'authenticate_error_sending_email'  => 'An error occurred when sending an email to that address',

	'authenticate_member_not_active'	=> 'Your account has not been activated',
	'authenticate_required_field'       => 'The %s field is required',
	'authenticate_valid_email'          => 'The %s field does not contain a valid email',

	//--------------------------------------------
	'', ''
);


text:
<?php

namespace Hecke29\DomainOffensiveClient\Service;

abstract class AbstractClient
{
    /**
     * Determines if a response is successful or not
     *
     * @param array $response
     * @return bool
     */
    protected function isSuccessfulResponse(array $response)
    {
        return $response['result'] === 'success';
    }

    /**
     * Throws exception based on the description message of a failed response
     *
     * @param $response
     * @param array $exceptionMapping
     * @param $defaultException
     */
    protected function handleFailedResponse($response, array $exceptionMapping = [], $defaultException = \Exception::class)
    {
        $responseDescription = $response['description'];

        foreach ($exceptionMapping as $knownMessage => $exceptionType) {
            if (strpos($responseDescription, $knownMessage) !== false) {
                throw new $exceptionType($responseDescription);
            }
        }

        throw new $defaultException($responseDescription);
    }
}


text:
/*
 * This file is released under terms of BSD license
 * See LICENSE file for more information
 * @author Mikhail Zhigun
 */
package clawfc.depscan;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * FilteredContentSequence is a container for sequences of
 * Add/Remove operations performed by the text filters.
 *
 */
public class FilteredContentSequence
{
    public enum OpType {
        ADD, REMOVE
    }

    public static class Op
    {
        public final OpType type;
        public final int pos;
        public final String txt;

        public Op(OpType type, int pos, String txt)
        {
            this.type = type;
            this.pos = pos;
            this.txt = txt;
        }
    }

    List<FilteredContent> data;

    public int size()
    {
        return data.size();
    }

    public FilteredContentSequence get(int idx)
    {
        return new FilteredContentSequence(Arrays.asList(data.get(idx)));
    }

    public FilteredContentSequence(List<FilteredContent> data)
    {
        this.data = data;
    }

    public FilteredContentSequence()
    {
        this.data = new ArrayList<FilteredContent>();
    }

    public void add(FilteredContent el)
    {
        data.add(el);
    }

    public void add(FilteredContentSequence seq)
    {
        data.addAll(seq.data);
    }

    public static FilteredContentSequence decomposeIntoSeqs(List<Op> ops)
    {
        InsertedFilteredContent add = new InsertedFilteredContent();
        RemovedFilteredContent rem = new RemovedFilteredContent();
        for (Op op : ops)
        {
            if (op.type == OpType.ADD)
            {
                add.addSequence(op.pos, op.txt);
            }
        }
        for (Op op : ops)
        {
            if (op.type == OpType.REMOVE)
            {
                int newPos = add.getChrIdxFiltered(op.pos);
                rem.addSequence(newPos, op.txt);
            }
        }
        FilteredContentSequence res = new FilteredContentSequence(
                Collections.unmodifiableList(Arrays.asList(add, rem)));
        return res;
    }

    public static String toString(List<Op> ops)
    {
        StringBuilder sb = new StringBuilder();
        for (Op op : ops)
        {
            if (op.type == OpType.ADD)
            {
                sb.append("add ");
            } else
            {
                sb.append("rem ");
            }
            sb.append(op.pos).append(" \"").append(op.txt).append("\"\n");
        }
        return sb.toString();
    }

    /**
     * Reverses the rearrangement effects of the successively applied sequence of
     * filters
     */
    public Integer getOriginalChrIdx(int chrIdxFiltered)
    {
        if (chrIdxFiltered < 0)
        {
            return null;
        }
        Integer idx = chrIdxFiltered;
        for (int i = data.size() - 1; i >= 0; --i)
        {
            FilteredContent content = data.get(i);
            Integer newIdx = content.getOriginalChrIdx(idx);
            idx = newIdx;
            if (idx == null)
            {
                return idx;
            }
        }
        return idx;
    }

    /**
     * Reverses the rearrangement effects of the successively applied sequence of
     * filters
     */
    public FortranStatementBasicPosition getOriginal(FortranStatementBasicPosition basicPos)
    {
        int newStartChrIdx = getOriginalChrIdx(basicPos.getStartCharIdx());
        int newEndChrIdx = getOriginalChrIdx(basicPos.getEndCharIdx() - 1) + 1;// Index is not inclusive
        return new FortranStatementBasicPosition(basicPos.getName(), newStartChrIdx, newEndChrIdx);
    }

    public String partialReverse(String filteredStr, char fillChr)
    {
        Map<Integer, Character> res = new LinkedHashMap<Integer, Character>();
        int lastIdx = -1;
        for (int i = 0; i < filteredStr.length(); ++i)
        {
            Integer idx = getOriginalChrIdx(i);
            if (idx != null)
            {
                if (idx < lastIdx)
                {
                    throw new RuntimeException();
                }
                lastIdx = idx;
                if (res.put(idx, filteredStr.charAt(i)) != null)
                {
                    throw new RuntimeException();
                }
            }
        }

        StringBuilder sB = new StringBuilder(lastIdx + 1);
        for (int i = 0; i <= lastIdx; ++i)
        {
            Character chr = res.get(i);
            if (chr == null)
            {
                sB.append(fillChr);
            } else
            {
                sB.append(chr);
            }

        }
        return sB.toString();
    }
}


text:
//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//     Runtime Version:4.0.30319.42000
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

namespace TeamSpark.AzureDay.WebSite.Localization.Host.Views.Profile {
    using System;

    /// <summary>
    ///   A strongly-typed resource class, for looking up localized strings, etc.
    /// </summary>
    // This class was auto-generated by the StronglyTypedResourceBuilder
    // class via a tool like ResGen or Visual Studio.
    // To add or remove a member, edit your .ResX file then rerun ResGen
    // with the /str option, or rebuild your VS project.
    [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
    [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
    [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
    public class ConfirmEmail {

        private static global::System.Resources.ResourceManager resourceMan;

        private static global::System.Globalization.CultureInfo resourceCulture;

        [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
        internal ConfirmEmail() {
        }

        /// <summary>
        ///   Returns the cached ResourceManager instance used by this class.
        /// </summary>
        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
        public static global::System.Resources.ResourceManager ResourceManager {
            get {
                if (object.ReferenceEquals(resourceMan, null)) {
                    global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("TeamSpark.AzureDay.WebSite.Localization.Host.Views.Profile.ConfirmEmail", typeof(ConfirmEmail).Assembly);
                    resourceMan = temp;
                }
                return resourceMan;
            }
        }

        /// <summary>
        ///   Overrides the current thread's CurrentUICulture property for all
        ///   resource lookups using this strongly typed resource class.
        /// </summary>
        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
        public static global::System.Globalization.CultureInfo Culture {
            get {
                return resourceCulture;
            }
            set {
                resourceCulture = value;
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to E-mail confirmation.
        /// </summary>
        public static string ConfirmMail {
            get {
                return ResourceManager.GetString("ConfirmMail", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Registration succesful. To complete the registration, please follow the link in the letter on your e-mail..
        /// </summary>
        public static string Success {
            get {
                return ResourceManager.GetString("Success", resourceCulture);
            }
        }
    }
}


text:
using testing::_;

namespace content {

class MockMediaStreamVideoCapturerSource : public MockMediaStreamVideoSource {
 public:
  MockMediaStreamVideoCapturerSource(
      const StreamDeviceInfo& device,
      const SourceStoppedCallback& stop_callback,
      PeerConnectionDependencyFactory* factory)
  : MockMediaStreamVideoSource(false) {
    SetDeviceInfo(device);
    SetStopCallback(stop_callback);
  }
};

class MockMediaDevicesDispatcherHost
    : public ::mojom::MediaDevicesDispatcherHost {
 public:
  MockMediaDevicesDispatcherHost() {}
  void EnumerateDevices(bool request_audio_input,
                        bool request_video_input,
                        bool request_audio_output,
                        const url::Origin& security_origin,
                        const EnumerateDevicesCallback& callback) override {
    std::vector<std::vector<MediaDeviceInfo>> result(NUM_MEDIA_DEVICE_TYPES);
    if (request_audio_input) {
      result[MEDIA_DEVICE_TYPE_AUDIO_INPUT].push_back(MediaDeviceInfo(
          "fake_audio_input 1", "Fake Audio Input 1", "fake_group 1"));
      result[MEDIA_DEVICE_TYPE_AUDIO_INPUT].push_back(MediaDeviceInfo(
          "fake_audio_input 2", "Fake Audio Input 2", "fake_group 2"));
    }
    if (request_video_input) {
      result[MEDIA_DEVICE_TYPE_VIDEO_INPUT].push_back(
          MediaDeviceInfo("fake_video_input 1", "Fake Video Input 1", ""));
      result[MEDIA_DEVICE_TYPE_VIDEO_INPUT].push_back(
          MediaDeviceInfo("fake_video_input 2", "Fake Video Input 2", ""));
    }
    if (request_audio_output) {
      result[MEDIA_DEVICE_TYPE_AUDIO_OUTPUT].push_back(MediaDeviceInfo(
          "fake_audio_output 1", "Fake Audio Input 1", "fake_group 1"));
    }
    callback.Run(result);
  }

  MOCK_METHOD3(SubscribeDeviceChangeNotifications,
               void(MediaDeviceType type,
                    uint32_t subscription_id,
                    const url::Origin& security_origin));
  MOCK_METHOD2(UnsubscribeDeviceChangeNotifications,
               void(MediaDeviceType type, uint32_t subscription_id));
};

class UserMediaClientImplUnderTest : public UserMediaClientImpl {
 public:
  enum RequestState {
    REQUEST_NOT_STARTED,
    REQUEST_NOT_COMPLETE,
    REQUEST_SUCCEEDED,
    REQUEST_FAILED,
  };

  UserMediaClientImplUnderTest(
      PeerConnectionDependencyFactory* dependency_factory,
      std::unique_ptr<MediaStreamDispatcher> media_stream_dispatcher)
      : UserMediaClientImpl(NULL,
                            dependency_factory,
                            std::move(media_stream_dispatcher)),
        state_(REQUEST_NOT_STARTED),
        result_(NUM_MEDIA_REQUEST_RESULTS),
        result_name_(""),
        factory_(dependency_factory),
        create_source_that_fails_(false),
        video_source_(NULL) {}

  void RequestUserMedia(const blink::WebUserMediaRequest& user_media_request) {
    state_ = REQUEST_NOT_COMPLETE;
    requestUserMedia(user_media_request);
  }

  void RequestUserMedia() {
    blink::WebUserMediaRequest user_media_request;
    RequestUserMedia(user_media_request);
  }

  void RequestMediaDevices() {
    blink::WebMediaDevicesRequest media_devices_request;
    state_ = REQUEST_NOT_COMPLETE;
    requestMediaDevices(media_devices_request);
  }

  void SetMediaDeviceChangeObserver() {
    blink::WebMediaDeviceChangeObserver observer(true);
    setMediaDeviceChangeObserver(observer);
  }

  void RemoveMediaDeviceChangeObserver() {
    setMediaDeviceChangeObserver(blink::WebMediaDeviceChangeObserver());
  }

  void GetUserMediaRequestSucceeded(
      const blink::WebMediaStream& stream,
      blink::WebUserMediaRequest request_info) override {
    last_generated_stream_ = stream;
    state_ = REQUEST_SUCCEEDED;
  }

  void GetUserMediaRequestFailed(
      blink::WebUserMediaRequest request_info,
      content::MediaStreamRequestResult result,
      const blink::WebString& result_name) override {
    last_generated_stream_.reset();
    state_ = REQUEST_FAILED;
    result_ = result;
    result_name_ = result_name;
  }

  void EnumerateDevicesSucceded(
      blink::WebMediaDevicesRequest* request,
      blink::WebVector<blink::WebMediaDeviceInfo>& devices) override {
    state_ = REQUEST_SUCCEEDED;
    last_devices_ = devices;
  }

  void SetCreateSourceThatFails(bool should_fail) {
    create_source_that_fails_ = should_fail;
  }

  MediaStreamAudioSource* CreateAudioSource(
      const StreamDeviceInfo& device,
      const blink::WebMediaConstraints& constraints) override {
    MediaStreamAudioSource* source;
    if (create_source_that_fails_) {
      class FailedAtLifeAudioSource : public MediaStreamAudioSource {
       public:
        FailedAtLifeAudioSource() : MediaStreamAudioSource(true) {}
        ~FailedAtLifeAudioSource() override {}
       protected:
        bool EnsureSourceIsStarted() override {
          return false;
        }
      };
      source = new FailedAtLifeAudioSource();
    } else {
      source = new MediaStreamAudioSource(true);
    }
    source->SetDeviceInfo(device);
    return source;
  }

  MediaStreamVideoSource* CreateVideoSource(
      const StreamDeviceInfo& device,
      const MediaStreamSource::SourceStoppedCallback& stop_callback) override {
    video_source_ = new MockMediaStreamVideoCapturerSource(device,
                                                           stop_callback,
                                                           factory_);
    return video_source_;
  }

  const blink::WebMediaStream& last_generated_stream() {
    return last_generated_stream_;
  }

  const blink::WebVector<blink::WebMediaDeviceInfo>& last_devices() {
    return last_devices_;
  }

  void ClearLastGeneratedStream() {
    last_generated_stream_.reset();
  }

  MockMediaStreamVideoCapturerSource* last_created_video_source() const {
    return video_source_;
  }

  RequestState request_state() const { return state_; }
  content::MediaStreamRequestResult error_reason() const { return result_; }
  blink::WebString error_name() const { return result_name_; }

  // Access to the request queue for testing.
  bool UserMediaRequestHasAutomaticDeviceSelection(int request_id) {
    auto* request = FindUserMediaRequestInfo(request_id);
    EXPECT_TRUE(request != nullptr);
    return request && request->enable_automatic_output_device_selection;
  }

  void DeleteRequest(int request_id) {
    auto* request = FindUserMediaRequestInfo(request_id);
    DeleteUserMediaRequestInfo(request);
  }

 private:
  blink::WebMediaStream last_generated_stream_;
  RequestState state_;
  content::MediaStreamRequestResult result_;
  blink::WebString result_name_;
  blink::WebVector<blink::WebMediaDeviceInfo> last_devices_;
  PeerConnectionDependencyFactory* factory_;
  bool create_source_that_fails_;
  MockMediaStreamVideoCapturerSource* video_source_;
};

class UserMediaClientImplTest : public ::testing::Test {
 public:
  UserMediaClientImplTest()
      : binding_user_media(&media_devices_dispatcher_),
        binding_event_dispatcher_(&media_devices_dispatcher_) {}

  void SetUp() override {
    // Create our test object.
    child_process_.reset(new ChildProcess());
    dependency_factory_.reset(new MockPeerConnectionDependencyFactory());
    ms_dispatcher_ = new MockMediaStreamDispatcher();
    used_media_impl_.reset(new UserMediaClientImplUnderTest(
        dependency_factory_.get(),
        std::unique_ptr<MediaStreamDispatcher>(ms_dispatcher_)));
    used_media_impl_->SetMediaDevicesDispatcherForTesting(
        binding_user_media.CreateInterfacePtrAndBind());
    base::WeakPtr<MediaDevicesEventDispatcher> event_dispatcher =
        MediaDevicesEventDispatcher::GetForRenderFrame(nullptr);
    event_dispatcher->SetMediaDevicesDispatcherForTesting(
        binding_event_dispatcher_.CreateInterfacePtrAndBind());
  }

  void TearDown() override {
    MediaDevicesEventDispatcher::GetForRenderFrame(nullptr)->OnDestruct();
    used_media_impl_.reset();
    blink::WebHeap::collectAllGarbageForTesting();
  }

  void LoadNewDocumentInFrame() {
    used_media_impl_->WillCommitProvisionalLoad();
  }

  blink::WebMediaStream RequestLocalMediaStream() {
    used_media_impl_->RequestUserMedia();
    FakeMediaStreamDispatcherRequestUserMediaComplete();
    StartMockedVideoSource();

    EXPECT_EQ(UserMediaClientImplUnderTest::REQUEST_SUCCEEDED,
              used_media_impl_->request_state());

    blink::WebMediaStream desc = used_media_impl_->last_generated_stream();
    content::MediaStream* native_stream =
        content::MediaStream::GetMediaStream(desc);
    if (!native_stream) {
      ADD_FAILURE();
      return desc;
    }

    blink::WebVector<blink::WebMediaStreamTrack> audio_tracks;
    desc.audioTracks(audio_tracks);
    blink::WebVector<blink::WebMediaStreamTrack> video_tracks;
    desc.videoTracks(video_tracks);

    EXPECT_EQ(1u, audio_tracks.size());
    EXPECT_EQ(1u, video_tracks.size());
    EXPECT_NE(audio_tracks[0].id(), video_tracks[0].id());
    return desc;
  }

  void FakeMediaStreamDispatcherRequestUserMediaComplete() {
    // Audio request ID is used as the shared request ID.
    used_media_impl_->OnStreamGenerated(
        ms_dispatcher_->audio_input_request_id(),
        ms_dispatcher_->stream_label(),
        ms_dispatcher_->audio_input_array(),
        ms_dispatcher_->video_array());
  }

  void StartMockedVideoSource() {
    MockMediaStreamVideoCapturerSource* video_source =
        used_media_impl_->last_created_video_source();
    if (video_source->SourceHasAttemptedToStart())
      video_source->StartMockedSource();
  }

  void FailToStartMockedVideoSource() {
    MockMediaStreamVideoCapturerSource* video_source =
        used_media_impl_->last_created_video_source();
    if (video_source->SourceHasAttemptedToStart())
      video_source->FailToStartMockedSource();
    blink::WebHeap::collectGarbageForTesting();
  }

  bool AudioRequestHasAutomaticDeviceSelection(
      const blink::WebMediaConstraints& audio_constraints) {
    blink::WebMediaConstraints null_constraints;
    blink::WebUserMediaRequest request =
        blink::WebUserMediaRequest::createForTesting(audio_constraints,
                                                     null_constraints);
    used_media_impl_->RequestUserMedia(request);
    bool result = used_media_impl_->UserMediaRequestHasAutomaticDeviceSelection(
        ms_dispatcher_->audio_input_request_id());
    used_media_impl_->DeleteRequest(ms_dispatcher_->audio_input_request_id());
    return result;
  }

 protected:
  base::MessageLoop message_loop_;
  std::unique_ptr<ChildProcess> child_process_;
  MockMediaStreamDispatcher* ms_dispatcher_;  // Owned by |used_media_impl_|.
  MockMediaDevicesDispatcherHost media_devices_dispatcher_;
  mojo::Binding<::mojom::MediaDevicesDispatcherHost> binding_user_media;
  mojo::Binding<::mojom::MediaDevicesDispatcherHost> binding_event_dispatcher_;

  std::unique_ptr<UserMediaClientImplUnderTest> used_media_impl_;
  std::unique_ptr<MockPeerConnectionDependencyFactory> dependency_factory_;
};

TEST_F(UserMediaClientImplTest, GenerateMediaStream) {
  // Generate a stream with both audio and video.
  blink::WebMediaStream mixed_desc = RequestLocalMediaStream();
}

// Test that the same source object is used if two MediaStreams are generated
// using the same source.
TEST_F(UserMediaClientImplTest, GenerateTwoMediaStreamsWithSameSource) {
  blink::WebMediaStream desc1 = RequestLocalMediaStream();
  blink::WebMediaStream desc2 = RequestLocalMediaStream();

  blink::WebVector<blink::WebMediaStreamTrack> desc1_video_tracks;
  desc1.videoTracks(desc1_video_tracks);
  blink::WebVector<blink::WebMediaStreamTrack> desc2_video_tracks;
  desc2.videoTracks(desc2_video_tracks);
  EXPECT_EQ(desc1_video_tracks[0].source().id(),
            desc2_video_tracks[0].source().id());

  EXPECT_EQ(desc1_video_tracks[0].source().getExtraData(),
            desc2_video_tracks[0].source().getExtraData());

  blink::WebVector<blink::WebMediaStreamTrack> desc1_audio_tracks;
  desc1.audioTracks(desc1_audio_tracks);
  blink::WebVector<blink::WebMediaStreamTrack> desc2_audio_tracks;
  desc2.audioTracks(desc2_audio_tracks);
  EXPECT_EQ(desc1_audio_tracks[0].source().id(),
            desc2_audio_tracks[0].source().id());

  EXPECT_EQ(MediaStreamAudioSource::From(desc1_audio_tracks[0].source()),
            MediaStreamAudioSource::From(desc2_audio_tracks[0].source()));
}

// Test that the same source object is not used if two MediaStreams are
// generated using different sources.
TEST_F(UserMediaClientImplTest, GenerateTwoMediaStreamsWithDifferentSources) {
  blink::WebMediaStream desc1 = RequestLocalMediaStream();
  // Make sure another device is selected (another |session_id|) in  the next
  // gUM request.
  ms_dispatcher_->IncrementSessionId();
  blink::WebMediaStream desc2 = RequestLocalMediaStream();

  blink::WebVector<blink::WebMediaStreamTrack> desc1_video_tracks;
  desc1.videoTracks(desc1_video_tracks);
  blink::WebVector<blink::WebMediaStreamTrack> desc2_video_tracks;
  desc2.videoTracks(desc2_video_tracks);
  EXPECT_NE(desc1_video_tracks[0].source().id(),
            desc2_video_tracks[0].source().id());

  EXPECT_NE(desc1_video_tracks[0].source().getExtraData(),
            desc2_video_tracks[0].source().getExtraData());

  blink::WebVector<blink::WebMediaStreamTrack> desc1_audio_tracks;
  desc1.audioTracks(desc1_audio_tracks);
  blink::WebVector<blink::WebMediaStreamTrack> desc2_audio_tracks;
  desc2.audioTracks(desc2_audio_tracks);
  EXPECT_NE(desc1_audio_tracks[0].source().id(),
            desc2_audio_tracks[0].source().id());

  EXPECT_NE(MediaStreamAudioSource::From(desc1_audio_tracks[0].source()),
            MediaStreamAudioSource::From(desc2_audio_tracks[0].source()));
}

TEST_F(UserMediaClientImplTest, StopLocalTracks) {
  // Generate a stream with both audio and video.
  blink::WebMediaStream mixed_desc = RequestLocalMediaStream();

  blink::WebVector<blink::WebMediaStreamTrack> audio_tracks;
  mixed_desc.audioTracks(audio_tracks);
  MediaStreamTrack* audio_track = MediaStreamTrack::GetTrack(audio_tracks[0]);
  audio_track->Stop();
  EXPECT_EQ(1, ms_dispatcher_->stop_audio_device_counter());

  blink::WebVector<blink::WebMediaStreamTrack> video_tracks;
  mixed_desc.videoTracks(video_tracks);
  MediaStreamTrack* video_track = MediaStreamTrack::GetTrack(video_tracks[0]);
  video_track->Stop();
  EXPECT_EQ(1, ms_dispatcher_->stop_video_device_counter());
}

// This test that a source is not stopped even if the tracks in a
// MediaStream is stopped if there are two MediaStreams with tracks using the
// same device. The source is stopped
// if there are no more MediaStream tracks using the device.
TEST_F(UserMediaClientImplTest, StopLocalTracksWhenTwoStreamUseSameDevices) {
  // Generate a stream with both audio and video.
  blink::WebMediaStream desc1 = RequestLocalMediaStream();
  blink::WebMediaStream desc2 = RequestLocalMediaStream();

  blink::WebVector<blink::WebMediaStreamTrack> audio_tracks1;
  desc1.audioTracks(audio_tracks1);
  MediaStreamTrack* audio_track1 = MediaStreamTrack::GetTrack(audio_tracks1[0]);
  audio_track1->Stop();
  EXPECT_EQ(0, ms_dispatcher_->stop_audio_device_counter());

  blink::WebVector<blink::WebMediaStreamTrack> audio_tracks2;
  desc2.audioTracks(audio_tracks2);
  MediaStreamTrack* audio_track2 = MediaStreamTrack::GetTrack(audio_tracks2[0]);
  audio_track2->Stop();
  EXPECT_EQ(1, ms_dispatcher_->stop_audio_device_counter());

  blink::WebVector<blink::WebMediaStreamTrack> video_tracks1;
  desc1.videoTracks(video_tracks1);
  MediaStreamTrack* video_track1 = MediaStreamTrack::GetTrack(video_tracks1[0]);
  video_track1->Stop();
  EXPECT_EQ(0, ms_dispatcher_->stop_video_device_counter());

  blink::WebVector<blink::WebMediaStreamTrack> video_tracks2;
  desc2.videoTracks(video_tracks2);
  MediaStreamTrack* video_track2 = MediaStreamTrack::GetTrack(video_tracks2[0]);
  video_track2->Stop();
  EXPECT_EQ(1, ms_dispatcher_->stop_video_device_counter());
}

TEST_F(UserMediaClientImplTest, StopSourceWhenMediaStreamGoesOutOfScope) {
  // Generate a stream with both audio and video.
  RequestLocalMediaStream();
  // Makes sure the test itself don't hold a reference to the created
  // MediaStream.
  used_media_impl_->ClearLastGeneratedStream();
  blink::WebHeap::collectAllGarbageForTesting();

  // Expect the sources to be stopped when the MediaStream goes out of scope.
  EXPECT_EQ(1, ms_dispatcher_->stop_audio_device_counter());
  EXPECT_EQ(1, ms_dispatcher_->stop_video_device_counter());
}

// Test that the MediaStreams are deleted if a new document is loaded in the
// frame.
TEST_F(UserMediaClientImplTest, LoadNewDocumentInFrame) {
  // Test a stream with both audio and video.
  blink::WebMediaStream mixed_desc = RequestLocalMediaStream();
  blink::WebMediaStream desc2 = RequestLocalMediaStream();
  LoadNewDocumentInFrame();
  blink::WebHeap::collectAllGarbageForTesting();
  EXPECT_EQ(1, ms_dispatcher_->stop_audio_device_counter());
  EXPECT_EQ(1, ms_dispatcher_->stop_video_device_counter());
}

// This test what happens if a video source to a MediaSteam fails to start.
TEST_F(UserMediaClientImplTest, MediaVideoSourceFailToStart) {
  used_media_impl_->RequestUserMedia();
  FakeMediaStreamDispatcherRequestUserMediaComplete();
  FailToStartMockedVideoSource();
  EXPECT_EQ(UserMediaClientImplUnderTest::REQUEST_FAILED,
            used_media_impl_->request_state());
  EXPECT_EQ(MEDIA_DEVICE_TRACK_START_FAILURE,
            used_media_impl_->error_reason());
  blink::WebHeap::collectAllGarbageForTesting();
  EXPECT_EQ(1, ms_dispatcher_->request_stream_counter());
  EXPECT_EQ(1, ms_dispatcher_->stop_audio_device_counter());
  EXPECT_EQ(1, ms_dispatcher_->stop_video_device_counter());
}

// This test what happens if an audio source fail to initialize.
TEST_F(UserMediaClientImplTest, MediaAudioSourceFailToInitialize) {
  used_media_impl_->SetCreateSourceThatFails(true);
  used_media_impl_->RequestUserMedia();
  FakeMediaStreamDispatcherRequestUserMediaComplete();
  StartMockedVideoSource();
  EXPECT_EQ(UserMediaClientImplUnderTest::REQUEST_FAILED,
            used_media_impl_->request_state());
  EXPECT_EQ(MEDIA_DEVICE_TRACK_START_FAILURE,
            used_media_impl_->error_reason());
  blink::WebHeap::collectAllGarbageForTesting();
  EXPECT_EQ(1, ms_dispatcher_->request_stream_counter());
  EXPECT_EQ(1, ms_dispatcher_->stop_audio_device_counter());
  EXPECT_EQ(1, ms_dispatcher_->stop_video_device_counter());
}

// This test what happens if UserMediaClientImpl is deleted before a source has
// started.
TEST_F(UserMediaClientImplTest, MediaStreamImplShutDown) {
  used_media_impl_->RequestUserMedia();
  FakeMediaStreamDispatcherRequestUserMediaComplete();
  EXPECT_EQ(1, ms_dispatcher_->request_stream_counter());
  EXPECT_EQ(UserMediaClientImplUnderTest::REQUEST_NOT_COMPLETE,
            used_media_impl_->request_state());
  used_media_impl_.reset();
}

// This test what happens if a new document is loaded in the frame while the
// MediaStream is being generated by the MediaStreamDispatcher.
TEST_F(UserMediaClientImplTest, ReloadFrameWhileGeneratingStream) {
  used_media_impl_->RequestUserMedia();
  LoadNewDocumentInFrame();
  EXPECT_EQ(1, ms_dispatcher_->request_stream_counter());
  EXPECT_EQ(0, ms_dispatcher_->stop_audio_device_counter());
  EXPECT_EQ(0, ms_dispatcher_->stop_video_device_counter());
  EXPECT_EQ(UserMediaClientImplUnderTest::REQUEST_NOT_COMPLETE,
            used_media_impl_->request_state());
}

// This test what happens if a newdocument is loaded in the frame while the
// sources are being started.
TEST_F(UserMediaClientImplTest, ReloadFrameWhileGeneratingSources) {
  used_media_impl_->RequestUserMedia();
  FakeMediaStreamDispatcherRequestUserMediaComplete();
  EXPECT_EQ(1, ms_dispatcher_->request_stream_counter());
  LoadNewDocumentInFrame();
  EXPECT_EQ(1, ms_dispatcher_->stop_audio_device_counter());
  EXPECT_EQ(1, ms_dispatcher_->stop_video_device_counter());
  EXPECT_EQ(UserMediaClientImplUnderTest::REQUEST_NOT_COMPLETE,
            used_media_impl_->request_state());
}

// This test what happens if stop is called on a track after the frame has
// been reloaded.
TEST_F(UserMediaClientImplTest, StopTrackAfterReload) {
  blink::WebMediaStream mixed_desc = RequestLocalMediaStream();
  EXPECT_EQ(1, ms_dispatcher_->request_stream_counter());
  LoadNewDocumentInFrame();
  blink::WebHeap::collectAllGarbageForTesting();
  EXPECT_EQ(1, ms_dispatcher_->stop_audio_device_counter());
  EXPECT_EQ(1, ms_dispatcher_->stop_video_device_counter());

  blink::WebVector<blink::WebMediaStreamTrack> audio_tracks;
  mixed_desc.audioTracks(audio_tracks);
  MediaStreamTrack* audio_track = MediaStreamTrack::GetTrack(audio_tracks[0]);
  audio_track->Stop();
  EXPECT_EQ(1, ms_dispatcher_->stop_audio_device_counter());

  blink::WebVector<blink::WebMediaStreamTrack> video_tracks;
  mixed_desc.videoTracks(video_tracks);
  MediaStreamTrack* video_track = MediaStreamTrack::GetTrack(video_tracks[0]);
  video_track->Stop();
  EXPECT_EQ(1, ms_dispatcher_->stop_video_device_counter());
}

TEST_F(UserMediaClientImplTest, EnumerateMediaDevices) {
  used_media_impl_->RequestMediaDevices();
  base::RunLoop().RunUntilIdle();

  EXPECT_EQ(UserMediaClientImplUnderTest::REQUEST_SUCCEEDED,
            used_media_impl_->request_state());
  EXPECT_EQ(static_cast<size_t>(5), used_media_impl_->last_devices().size());

  // Audio input device with matched output ID.
  const blink::WebMediaDeviceInfo* device =
      &used_media_impl_->last_devices()[0];
  EXPECT_FALSE(device->deviceId().isEmpty());
  EXPECT_EQ(blink::WebMediaDeviceInfo::MediaDeviceKindAudioInput,
            device->kind());
  EXPECT_FALSE(device->label().isEmpty());
  EXPECT_FALSE(device->groupId().isEmpty());

  // Audio input device without matched output ID.
  device = &used_media_impl_->last_devices()[1];
  EXPECT_FALSE(device->deviceId().isEmpty());
  EXPECT_EQ(blink::WebMediaDeviceInfo::MediaDeviceKindAudioInput,
            device->kind());
  EXPECT_FALSE(device->label().isEmpty());
  EXPECT_FALSE(device->groupId().isEmpty());

  // Video input devices.
  device = &used_media_impl_->last_devices()[2];
  EXPECT_FALSE(device->deviceId().isEmpty());
  EXPECT_EQ(blink::WebMediaDeviceInfo::MediaDeviceKindVideoInput,
            device->kind());
  EXPECT_FALSE(device->label().isEmpty());
  EXPECT_TRUE(device->groupId().isEmpty());

  device = &used_media_impl_->last_devices()[3];
  EXPECT_FALSE(device->deviceId().isEmpty());
  EXPECT_EQ(blink::WebMediaDeviceInfo::MediaDeviceKindVideoInput,
            device->kind());
  EXPECT_FALSE(device->label().isEmpty());
  EXPECT_TRUE(device->groupId().isEmpty());

  // Audio output device.
  device = &used_media_impl_->last_devices()[4];
  EXPECT_FALSE(device->deviceId().isEmpty());
  EXPECT_EQ(blink::WebMediaDeviceInfo::MediaDeviceKindAudioOutput,
            device->kind());
  EXPECT_FALSE(device->label().isEmpty());
  EXPECT_FALSE(device->groupId().isEmpty());

  // Verfify group IDs.
  EXPECT_TRUE(used_media_impl_->last_devices()[0].groupId().equals(
                  used_media_impl_->last_devices()[4].groupId()));
  EXPECT_FALSE(used_media_impl_->last_devices()[1].groupId().equals(
                   used_media_impl_->last_devices()[4].groupId()));
}

TEST_F(UserMediaClientImplTest, RenderToAssociatedSinkConstraint) {
  // For a null UserMediaRequest (no audio requested), we expect false.
  used_media_impl_->RequestUserMedia();
  EXPECT_FALSE(used_media_impl_->UserMediaRequestHasAutomaticDeviceSelection(
      ms_dispatcher_->audio_input_request_id()));
  used_media_impl_->DeleteRequest(ms_dispatcher_->audio_input_request_id());

  // If audio is requested, but no constraint, it should be true.
  // Currently we expect it to be false due to a suspected bug in the
  // device-matching code causing issues with some sound adapters.
  // See crbug.com/604523
  MockConstraintFactory factory;
  blink::WebMediaConstraints audio_constraints =
      factory.CreateWebMediaConstraints();
  EXPECT_FALSE(AudioRequestHasAutomaticDeviceSelection(
      factory.CreateWebMediaConstraints()));

  // If the constraint is present, it should dictate the result.
  factory.Reset();
  factory.AddAdvanced().renderToAssociatedSink.setExact(true);
  EXPECT_TRUE(AudioRequestHasAutomaticDeviceSelection(
      factory.CreateWebMediaConstraints()));

  factory.Reset();
  factory.AddAdvanced().renderToAssociatedSink.setExact(false);
  EXPECT_FALSE(AudioRequestHasAutomaticDeviceSelection(
      factory.CreateWebMediaConstraints()));

  factory.Reset();
  factory.basic().renderToAssociatedSink.setExact(false);
  EXPECT_FALSE(AudioRequestHasAutomaticDeviceSelection(
      factory.CreateWebMediaConstraints()));
}

TEST_F(UserMediaClientImplTest, ObserveMediaDeviceChanges) {
  EXPECT_CALL(
      media_devices_dispatcher_,
      SubscribeDeviceChangeNotifications(MEDIA_DEVICE_TYPE_AUDIO_INPUT, _, _));
  EXPECT_CALL(
      media_devices_dispatcher_,
      SubscribeDeviceChangeNotifications(MEDIA_DEVICE_TYPE_VIDEO_INPUT, _, _));
  EXPECT_CALL(
      media_devices_dispatcher_,
      SubscribeDeviceChangeNotifications(MEDIA_DEVICE_TYPE_AUDIO_OUTPUT, _, _));
  used_media_impl_->SetMediaDeviceChangeObserver();
  base::RunLoop().RunUntilIdle();

  base::WeakPtr<MediaDevicesEventDispatcher> event_dispatcher =
      MediaDevicesEventDispatcher::GetForRenderFrame(nullptr);
  event_dispatcher->DispatchDevicesChangedEvent(MEDIA_DEVICE_TYPE_AUDIO_INPUT,
                                                MediaDeviceInfoArray());
  event_dispatcher->DispatchDevicesChangedEvent(MEDIA_DEVICE_TYPE_VIDEO_INPUT,
                                                MediaDeviceInfoArray());
  event_dispatcher->DispatchDevicesChangedEvent(MEDIA_DEVICE_TYPE_AUDIO_OUTPUT,
                                                MediaDeviceInfoArray());
  base::RunLoop().RunUntilIdle();

  EXPECT_CALL(media_devices_dispatcher_, UnsubscribeDeviceChangeNotifications(
                                             MEDIA_DEVICE_TYPE_AUDIO_INPUT, _));
  EXPECT_CALL(media_devices_dispatcher_, UnsubscribeDeviceChangeNotifications(
                                             MEDIA_DEVICE_TYPE_VIDEO_INPUT, _));
  EXPECT_CALL(
      media_devices_dispatcher_,
      UnsubscribeDeviceChangeNotifications(MEDIA_DEVICE_TYPE_AUDIO_OUTPUT, _));
  used_media_impl_->RemoveMediaDeviceChangeObserver();
  base::RunLoop().RunUntilIdle();
}

// This test what happens if the audio stream has same id with video stream.
TEST_F(UserMediaClientImplTest, AudioVideoWithSameId) {
  ms_dispatcher_->TestSameId();

  // Generate a stream with both audio and video.
  blink::WebMediaStream mixed_desc = RequestLocalMediaStream();

  // Remove video track. This should trigger
  // UserMediaClientImpl::OnLocalSourceStopped, and has video track to be
  // removed from its |local_sources_|.
  blink::WebVector<blink::WebMediaStreamTrack> video_tracks;
  mixed_desc.videoTracks(video_tracks);
  MediaStreamTrack* video_track = MediaStreamTrack::GetTrack(video_tracks[0]);
  video_track->Stop();
  EXPECT_EQ(1, ms_dispatcher_->stop_video_device_counter());
  EXPECT_EQ(0, ms_dispatcher_->stop_audio_device_counter());

  // Now we load a new document in the web frame. If in the above Stop() call,
  // UserMediaClientImpl accidentally removed audio track, then video track will
  // be removed again here, which is incorrect.
  LoadNewDocumentInFrame();
  blink::WebHeap::collectAllGarbageForTesting();
  EXPECT_EQ(1, ms_dispatcher_->stop_video_device_counter());
  EXPECT_EQ(1, ms_dispatcher_->stop_audio_device_counter());
}

}  // namespace content


text:
package util.visitor;

import analyzer.level1.JimpleInjector;
import soot.Local;
import soot.jimple.*;
import util.logging.L1Logger;

import java.util.logging.Logger;

/**
 * This class handles now the right hand side of an Assign Expression
 * as Switch it implements the Visitor Pattern for the Values present in
 * the Soot Framework.
 *
 * An Assignment is something like:
 *  l = e[x] + f(c.foo, Math.PI);
 *
 * This switch only treats the right hand side of that Expression, so
 * therefore are only for interesting or possible cases:
 *  local Variables, Array References, static or instance Field access.
 *
 * @author Karsten Fix, 13.Sept 2017
 */
public class RHSInstrumentationSwitch extends AbstractJimpleValueSwitch {

    /** Gets the Logger to log different, important messages */
    private static final Logger logger = Logger.getLogger(RHSInstrumentationSwitch.class.getName());

    /** Saves the Statement, that calls the referring Method of its type.
     * The Statement shall be known at creation of the Switch. */
    private final AssignStmt callStmt;

    /**
     * Creates a new Value Switch for the Right Side of an Assignment.
     * Therefore the given Stmt has to be an Assignment.
     *
     * @param call The Assignment Stmt, that is found in the
     * {@link AnnotationStmtSwitch::caseAssignStmt } and calls the apply Method.
     */
    public RHSInstrumentationSwitch(AssignStmt call) {
        callStmt = call;
        logger.finer("Created RightAssignVS for: "+call);
    }

    // <editor-fold desc="Variable Cases">

    /**
     * The Case of a local Variable is interesting for the Right Side of an Assignment.
     * Let h = l; be the callStmt, then the given Local shall be l
     * @param l The Local, that is calling this case fulfilling the Visitor Pattern.
     * @see JimpleInjector ::addLevelInAssignStmt
     */
    @Override
    public void caseLocal(Local l) {
        logger.finest("case Local with: " + l);
        JimpleInjector.addLevelInAssignStmt(l, callStmt);
    }

    /**
     * The Case of an ArrayRef is interesting for the Left Side of an Assignment.
     * Let h = x[0]; be the callStmt, then the given ArrayRef shall be x[0]
     * @param v The ArrayRef, that is calling this case fulfilling the Visitor Pattern.
     * @see JimpleInjector::addLevelInAssignStmt
     */
    @Override
    public void caseArrayRef(ArrayRef v) {
        logger.finest("case ArrayRef with: " + v);
        JimpleInjector.addLevelInAssignStmt(v, callStmt);
    }

    /**
     * The Case of an StaticFieldRef is interesting for the Left Side of an Assignment.
     * Let x[3] = Math.PI; be the callStmt, then the given StaticFieldRef shall be Math.PI
     * Therefore PI is accessed from a static Context.
     * @param v The StaticFieldRef, that is calling this case fulfilling the Visitor Pattern.
     * @see JimpleInjector::addLevelInAssignStmt
     */
    @Override
    public void caseStaticFieldRef(StaticFieldRef v) {
        logger.finest("case StaticFieldRef with: " + v);
        JimpleInjector.addLevelInAssignStmt(v, callStmt);
    }

    /**
     * The Case of an InstanceFieldRef is interesting for the Left Side of an Assignment.
     * Let bar = c.foo; be the callStmt, then the given InstanceFieldRef shall be c.foo
     * Therefore foo is accessed from a non-static Context, means it uses an instance.
     * @param v The InstanceFieldRef, that is calling this case fulfilling the Visitor Pattern.
     * @see JimpleInjector::addLevelInAssignStmt
     */
    @Override
    public void caseInstanceFieldRef(InstanceFieldRef v) {
        logger.finest("case InstanceFieldRef with: " + v);
        JimpleInjector.addLevelInAssignStmt(v, callStmt);
    }

    // </editor-fold>

    // <editor-fold desc="Array Cases">

    /**
     * On the right hand side of an assignment could be an array declaration.
     * Let l = new int[1]; be the statement, then new int[1] would be the given
     * newArrayExpression v
     * @param v The NewArrayExpr, that is calling this case fulfilling the Visitor Pattern.
     * @see JimpleInjector::addArrayToObjectMap
     */
    @Override
    public void caseNewArrayExpr(NewArrayExpr v) {
        logger.finest("case NewArrayExpr: " + v);
        JimpleInjector.addArrayToObjectMap((Local) callStmt.getLeftOp(), callStmt);
    }

    /**
     * On the right hand side of an assignment could be an multiArray declaration.
     * Let l = new int[1][6]; be the statement, then new int[1][6] would be the given
     * newMultiArrayExpression v
     * @param v The NewMultiArrayExpr, that is calling this case fulfilling the Visitor Pattern.
     * @see JimpleInjector::addArrayToObjectMap
     */
    @Override
    public void caseNewMultiArrayExpr(NewMultiArrayExpr v) {
        logger.finest("case NewMultiArrayExpr: " + v);
        JimpleInjector.addArrayToObjectMap((Local) callStmt.getLeftOp(), callStmt);
    }

    // </editor-fold>

    // <editor-fold desc="Invoke Cases">

    // </editor-fold>

    @Override
    public void defaultCase(Object obj) {

    }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Syn. Fung. (Oslo) 226: 46 (2009)

#### Original name
Hypochnicium rickii Hjortstam & Ryvarden

### Remarks
null


text:
package org.wso2.msf4j;

import java.util.Map;

/**
 * Default SessionManager to manage MSF4J transport sessions.
 */
public class DefaultSessionManager extends AbstractSessionManager {

    @Override
    public void loadSessions(Map<String, Session> sessions) {
        checkValidity();
        // Nothing to do because this is an in-memory implementation
    }

    @Override
    public void saveSession(Session session) {
        checkValidity();
        // Nothing to do because this is an in-memory implementation
    }

    @Override
    public Session readSession(String sessionId) {
        checkValidity();
        // Nothing to do because this is an in-memory implementation
        return null;
    }

    @Override
    public void deleteSession(Session session) {
        checkValidity();
        // Nothing to do because this is an in-memory implementation
    }

    @Override
    public void updateSession(Session session) {
        checkValidity();
        // Nothing to do because this is an in-memory implementation
    }
}


text:
var mongoose = require( 'mongoose');
var Schema = mongoose.Schema;

var auditSchema = new mongoose.Schema({
    type:{type: String, required: true, enum: ['exercise', 'nextlevel','needhelp']},
    userId:{type: Schema.Types.ObjectId, ref: 'users'},
    level:Number,
    exerciseId:{type: Schema.Types.ObjectId, ref: 'exercises'},
    subsubjectId:{type: Schema.Types.ObjectId, ref: 'subsubjects'},
    createdDate: {type: Date, default: Date.now},
    outcome:{type: String, enum: ['success', 'failure','needhelp']}
    },{ collection: 'userAudit' });

mongoose.model('UserAudit', auditSchema);

var progressSchema = new mongoose.Schema({
    userId:{type: Schema.Types.ObjectId, ref: 'users'},
    level:{type: Number, default:0},
    subsubjectId:{type: Schema.Types.ObjectId, ref: 'subsubjects'},
    assignmentId:{type: Schema.Types.ObjectId, ref: 'assignments'},
    createdDate: {type: Date, default: Date.now},
    isDone: {type: Boolean, default:false}
    },{ collection: 'userProgress' });

mongoose.model('userProgress', progressSchema);


text:
using namespace std;

class TileExtractor {
	Tile* getTile(FIBITMAP* bmp);

	void fillTileByRows(Tile* tile, FIBITMAP* bmp);
	void fillTileByCols(Tile* tile, FIBITMAP* bmp);
	void fillTileRLE(Tile* tile, FIBITMAP* bmp);
	void fillTileSCR(Tile* tile, FIBITMAP* bmp);
	void getByteAt(Tile* tile, FIBITMAP* bmp, int col, int row, bool flip, bool halfFlip);

	ColorAndMaskValues getColorAndMask(FIBITMAP* bmp, int x, int y, bool flip, bool halfFlip);
	vector<unsigned char> extractPixels(FIBITMAP* bmp, int x, int y, bool flip, bool halfFlip);
	vector<unsigned char> extractTransPixels(vector<unsigned char> colors);
	unsigned int getModeIncrement();
	string removeExtension(const string &fileName);
	string sanitize(const string &name);

	unsigned int TileWidth;
	unsigned int TileHeight;
	unsigned int ModeIncrement;
	unsigned int Pitch;

public:
	ConversionOptions Options;
	vector<Tile*> GetTiles(const string &fileName);
};

#endif


text:
    stroke: steelblue;
    stroke-width: 2px;
    fill: none;
}

#results .axis path,
#results .axis line {
    fill: none;
    stroke: grey;
    stroke-width: 2px;
    shape-rendering: crispEdges;
}

#exporter{
  text-align: left;
}
.small{
  margin-top: 10px;
  font: 10px monospace;
}

.userblock{
  padding: 20px;
  margin: 20px;
  margin-bottom: 40px;
}

p.user-position{
  display: block;
  padding-bottom: 5px;
  padding-top: 5px;
  font: 20px Helvetica,Arial,sans-serif;
}

.usersubcontainer{
  overflow: hidden;
  padding-bottom: 5px;
}

.usersubcontainer img{
  display: block;
  float: left;
  width: 64px;
  height: 64px;
  padding: 5px;
}

.user-name{
  float: left;
  font: bold 30px Helvetica,Arial,sans-serif;
  padding-left: 20px;
}

.user-nick{
  float: left;
  padding: 5px;
  font: italic 10px monospace;
}

.user-count{
  float: left;
  padding: 5px;
  font: italic bold 18px Helvetica,Arial,sans-serif;
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using Core.Common;
using Core.IO;

namespace Core.Shell.Common.FileSystems
{
	public static class FileSystemSubsystems
	{
		public static List<FileSystemSubsystem> Subsystems = new List<FileSystemSubsystem> {
		};

		public static VirtualDirectory DefaultRootDirectory { get; set; }

		public static VirtualFile File (Path path)
		{
			return getElement (path: path, internalFunc: (s, p) => s.File (p));
		}

		public static VirtualDirectory Directory (Path path)
		{
			return getElement (path: path, internalFunc: (s, p) => s.Directory (p));
		}

		public static VirtualLink Link (Path path)
		{
			return getElement (path: path, internalFunc: (s, p) => s.Link (p));
		}

		public static VirtualNode Node (Path path)
		{
			return getElement (path: path, internalFunc: (s, p) => s.Node (p));
		}

		static T getElement<T> (Path path, Func<FileSystemSubsystem,Path,T> internalFunc) where T : class
		{
			T result = null;
			foreach (FileSystemSubsystem subsystem in Subsystems) {
				result = internalFunc (subsystem, path);
				if (result != null) {
					break;
				}
			}
			return result;
		}

		public static Func<string, Path> ResolveRelativePath (ExecutionEnvironment env)
		{
			return possibleRelativePath => {
				// check if it's recognized by any filesystem prefix!
				foreach (FileSystemSubsystem subsystem in Subsystems) {
					foreach (Prefix prefix in subsystem.Prefixes) {
						if (prefix.Matches (possibleRelativePath)) {
							return prefix.CreatePath (possibleRelativePath);
						}
					}
				}

				// seems to be a relative path!
				Path absolutePath = env.WorkingDirectory.Path.CombinePath (possibleRelativePath);
				return absolutePath;
			};
		}

		public static VirtualNode ParseNativePath (string nativePath)
		{
			nativePath = PathHelper.NormalizePath (path: nativePath);

			VirtualNode result = null;
			foreach (FileSystemSubsystem subsystem in Subsystems) {
				result = subsystem.ParseNativePath (nativePath);
				if (result != null) {
					break;
				}
			}
			return result;
		}
	}
}