text:
package com.google.j2cl.transpiler;

import static com.google.common.collect.ImmutableList.toImmutableList;
import static com.google.common.collect.ImmutableSet.toImmutableSet;

import com.google.common.base.Joiner;
import com.google.common.base.Splitter;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Sets;
import com.google.j2cl.common.OutputUtils;
import com.google.j2cl.common.OutputUtils.Output;
import com.google.j2cl.common.Problems;
import com.google.j2cl.common.Problems.FatalError;
import com.google.j2cl.common.SourceUtils;
import com.google.j2cl.common.SourceUtils.FileInfo;
import com.google.j2cl.common.bazel.BazelWorker;
import com.google.j2cl.transpiler.backend.Backend;
import com.google.j2cl.transpiler.frontend.Frontend;
import java.io.File;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.kohsuke.args4j.Argument;
import org.kohsuke.args4j.Option;
import org.kohsuke.args4j.spi.MapOptionHandler;

/**
 * The J2cl builder for Bazel that runs as a worker.
 *
 * <p>Bazel workers allow J2CL to run in a JVM that is not being terminated after every compile and
 * thus gain significant speedups.
 */
final class BazelJ2clBuilder extends BazelWorker {

  @Argument(
      metaVar = "<source files>",
      required = true,
      usage = "Specifies individual files and jars/zips of sources (.java, .js, .native.js).")
  List<String> sources = new ArrayList<>();

  @Option(
      name = "-ktcommonsources",
      metaVar = "<common source filepaths>",
      usage =
          "Specifies which individual files are considered common sources. The filepaths might"
              + " refer to source files passed directly as arguments or be relative paths for"
              + " sources in the source jars passed as arguments.")
  List<String> kotlinCommonSources = new ArrayList<>();

  @Option(
      name = "-classpath",
      required = true,
      metaVar = "<path>",
      usage = "Specifies where to find user class files and annotation processors.")
  String classPath;

  @Option(
      name = "-output",
      required = true,
      metaVar = "<path>",
      usage = "Directory or zip into which to place compiled output.")
  Path output;

  @Option(
      name = "-libraryinfooutput",
      metaVar = "<path>",
      usage = "Specifies the file into which to place the call graph.")
  Path libraryInfoOutput;

  @Option(name = "-readablelibraryinfo", hidden = true)
  boolean readableLibraryInfo = false;

  @Option(name = "-readablesourcemaps", hidden = true)
  boolean readableSourceMaps = false;

  @Option(name = "-generatekytheindexingmetadata", hidden = true)
  boolean generateKytheIndexingMetadata = false;

  @Option(
      name = "-optimizeautovalue",
      usage = "Enables optimizations of AutoValue types.",
      hidden = true)
  boolean optimizeAutoValue = false;

  @Option(
      name =
          "-experimentalenablejspecifysupportdonotenablewithoutjspecifystaticcheckingoryoumightcauseanoutage",
      usage =
          "Enables support for JSpecify semantics. Do not use if the code is not being actually"
              + " separately checked by a static checker. When these annotations applied the code"
              + " will mislead developers to think that a null check is unnecessary without the"
              + " compile time validation. Such misleading code has caused outages in the past for"
              + " products.",
      hidden = true)
  boolean enableJSpecifySupport = false;

  @Option(
      name = "-experimentalJavaFrontend",
      usage = "Select the java frontend to use: JDT (default), JAVAC (experimental).",
      hidden = true)
  Frontend javaFrontend = Frontend.JDT;

  @Option(
      name = "-experimentalBackend",
      usage =
          "Select the backend to use: CLOSURE (default), WASM (experimental), KOTLIN"
              + " (experimental).",
      hidden = true)
  Backend backend = Backend.CLOSURE;

  @Option(name = "-kotlincOptions", hidden = true)
  List<String> kotlincOptions = new ArrayList<>();

  @Option(name = "-experimentalGenerateWasmExport", hidden = true)
  List<String> wasmEntryPoints = new ArrayList<>();

  @Option(name = "-experimentalDefineForWasm", handler = MapOptionHandler.class, hidden = true)
  Map<String, String> definesForWasm = new HashMap<>();

  @Option(name = "-experimentalWasmRemoveAssertStatement", hidden = true)
  boolean wasmRemoveAssertStatement = false;

  @Override
  protected void run(Problems problems) {
    try (Output out = OutputUtils.initOutput(this.output, problems)) {
      J2clTranspiler.transpile(createOptions(out, problems), problems);
    }
  }

  private J2clTranspilerOptions createOptions(Output output, Problems problems) {

    if (this.readableSourceMaps && this.generateKytheIndexingMetadata) {
      problems.warning(
          "Readable source maps are not available when generating Kythe indexing metadata.");
      this.readableSourceMaps = false;
    }

    if (backend == Backend.CLOSURE && libraryInfoOutput == null) {
      problems.fatal(FatalError.LIBRARY_INFO_OUTPUT_ARG_MISSING);
    }

    if (!javaFrontend.isJavaFrontend()) {
      problems.fatal(FatalError.INVALID_JAVA_FRONTEND, javaFrontend);
    }

    ImmutableList<FileInfo> allSources =
        SourceUtils.getAllSources(this.sources, problems).collect(toImmutableList());

    ImmutableList<FileInfo> allJavaSources =
        allSources.stream()
            .filter(p -> p.sourcePath().endsWith(".java"))
            .collect(toImmutableList());

    ImmutableList<FileInfo> allKotlinSources =
        allSources.stream().filter(p -> p.sourcePath().endsWith(".kt")).collect(toImmutableList());

    // TODO(dramaix): add support for transpiling java and kotlin simultaneously.
    if (!allJavaSources.isEmpty()
        && (!allKotlinSources.isEmpty() || !kotlinCommonSources.isEmpty())) {
      throw new AssertionError(
          "Transpilation of Java and Kotlin files together is not supported yet.");
    }

    // TODO(b/144721781): Remove this guard when we now that common srcs will always end up in the
    //  srcjar under a common-srcs/ root folder.
    boolean isUsingNewKotlinSrcJarZipper =
        allKotlinSources.stream()
            .anyMatch(fileInfo -> fileInfo.originalPath().startsWith("common-srcs/"));
    if (!isUsingNewKotlinSrcJarZipper) {
      // Common kotlin file paths should be a strict subset of the sources.
      Set<String> unmatchedKotlinCommonSources =
          Sets.difference(
              ImmutableSet.copyOf(kotlinCommonSources),
              allKotlinSources.stream().map(FileInfo::originalPath).collect(toImmutableSet()));
      if (!unmatchedKotlinCommonSources.isEmpty()) {
        problems.fatal(
            FatalError.INVALID_KOTLIN_COMMON_SOURCES,
            Joiner.on(", ").join(unmatchedKotlinCommonSources));
      }
    }

    ImmutableList<FileInfo> allNativeSources =
        allSources.stream()
            .filter(p -> p.sourcePath().endsWith(".native.js"))
            .collect(toImmutableList());

    // Directly put all supplied js sources into the zip file.
    allSources.stream()
        .filter(p -> p.sourcePath().endsWith(".js") && !p.sourcePath().endsWith("native.js"))
        .forEach(f -> output.copyFile(f.sourcePath(), f.targetPath()));

    return J2clTranspilerOptions.newBuilder()
        .setSources(allKotlinSources.isEmpty() ? allJavaSources : allKotlinSources)
        .setNativeSources(allNativeSources)
        .setKotlinCommonSources(this.kotlinCommonSources)
        .setClasspaths(getPathEntries(this.classPath))
        .setOutput(output)
        .setLibraryInfoOutput(this.libraryInfoOutput)
        .setEmitReadableLibraryInfo(readableLibraryInfo)
        .setEmitReadableSourceMap(this.readableSourceMaps)
        .setGenerateKytheIndexingMetadata(this.generateKytheIndexingMetadata)
        .setOptimizeAutoValue(this.optimizeAutoValue)
        .setFrontend(allKotlinSources.isEmpty() ? javaFrontend : Frontend.KOTLIN)
        .setBackend(this.backend)
        .setWasmEntryPoints(ImmutableSet.copyOf(wasmEntryPoints))
        .setDefinesForWasm(ImmutableMap.copyOf(definesForWasm))
        .setWasmRemoveAssertStatement(wasmRemoveAssertStatement)
        .setNullMarkedSupported(this.enableJSpecifySupport)
        .setKotlincOptions(ImmutableList.copyOf(kotlincOptions))
        .build();
  }

  private static List<String> getPathEntries(String path) {
    List<String> entries = new ArrayList<>();
    for (String entry : Splitter.on(File.pathSeparatorChar).omitEmptyStrings().split(path)) {
      if (new File(entry).exists()) {
        entries.add(entry);
      }
    }
    return entries;
  }

  public static void main(String[] workerArgs) throws Exception {
    BazelWorker.start(workerArgs, BazelJ2clBuilder::new);
  }
}


text: package marketplacecatalog

redpajama_set_name: RedPajamaGithub


text:
var fieldTests = require('../commonFieldTestUtils.js');

module.exports = {
	before: fieldTests.before,
	after: fieldTests.after,
	'Markdown field can be filled via the initial modal': function(browser) {
		browser.app.openFieldList('Markdown');
		browser.listPage.createFirstItem();
		browser.app.waitForInitialFormScreen();
		browser.initialFormPage.fillInputs({
			listName: 'Markdown',
			fields: {
				'name': {value: 'Markdown Field Test 1'},
				'fieldA': {md: 'Some __test__ markdown for **field A**'},
			}
		});
		browser.initialFormPage.assertInputs({
			listName: 'Markdown',
			fields: {
				'name': {value: 'Markdown Field Test 1'},
				'fieldA': {md: 'Some __test__ markdown for **field A**'},
			}
		});
		browser.initialFormPage.section.form.section.markdownList.section.fieldA.togglePreview();
		browser.initialFormPage.assertInputs({
			listName: 'Markdown',
			fields: {
				'name': {value: 'Markdown Field Test 1'},
				'fieldA': {html: '
Some test markdown for field A
\n'},
			}
		});
		browser.initialFormPage.save();
		browser.app.waitForItemScreen();
		browser.itemPage.assertFlashMessage('New Markdown Markdown Field Test 1 created.');
		browser.itemPage.assertInputs({
			listName: 'Markdown',
			fields: {
				'name': {value: 'Markdown Field Test 1'},
				'fieldA': {md: 'Some __test__ markdown for **field A**'},
			}
		})
	},
	'Markdown field can be filled via the edit form': function(browser) {
		browser.itemPage.fillInputs({
			listName: 'Markdown',
			fields: {
				'fieldB': {md: 'Some __test__ markdown for **field B**'}
			}
		});
		browser.itemPage.save();
		browser.itemPage.assertFlashMessage('Your changes have been saved.');
		browser.itemPage.assertInputs({
			listName: 'Markdown',
			fields: {
				'name': {value: 'Markdown Field Test 1'},
				'fieldA': {md: 'Some __test__ markdown for **field A**'},
				'fieldB': {md: 'Some __test__ markdown for **field B**'}
			}
		});
		browser.itemPage.section.form.section.markdownList.section.fieldA.togglePreview();
		browser.itemPage.section.form.section.markdownList.section.fieldB.togglePreview();
		browser.itemPage.assertInputs({
			listName: 'Markdown',
			fields: {
				'name': {value: 'Markdown Field Test 1'},
				'fieldA': {html: '
Some test markdown for field A
\n'},
				'fieldB': {html: '
Some test markdown for field A
\n'}
			}
		});
	},
};


text:
package com.pchudzik.springmock.mockito.configuration;

import com.pchudzik.springmock.infrastructure.annotation.AutowiredMock;
import com.pchudzik.springmock.infrastructure.annotation.AutowiredSpy;
import com.pchudzik.springmock.infrastructure.definition.registry.DoubleSearch;
import org.junit.Test;
import org.mockito.MockSettings;
import org.mockito.Mockito;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

import static com.pchudzik.springmock.mockito.configuration.ConfigurationHelper.*;
import static org.mockito.Mockito.never;

public class StubTest {
	private MockSettings mockSettings = mockSettingsMock();

	@Test
	public void should_not_set_stub_only_for_not_annotated_element() {
		//given
		final DoubleSearch doubles = findDoublesInClass(AnyTest.class);

		//when
		getConfiguration(doubles.findOneDefinition(AnyTest.notStubField)).createMockSettings(mockSettings);

		//then
		Mockito
				.verify(mockSettings, never())
				.stubOnly();
	}

	@Test
	public void should_set_serializable_mode_in_moc_settings() {
		//given
		final DoubleSearch doubles = findDoublesInClass(AnyTest.class);

		//when
		getConfiguration(doubles.findOneDefinition(AnyTest.stubOnlyField)).createMockSettings(mockSettings);

		//then
		Mockito
				.verify(mockSettings)
				.stubOnly();
	}

	@Test
	public void should_resolve_serializable_mode_from_meta_annotations() {
		//given
		final DoubleSearch doubles = findDoublesInClass(AnyTest.class);

		//when
		getConfiguration(doubles.findOneDefinition(AnyTest.metaAnnotatedField)).createMockSettings(mockSettings);

		//then
		Mockito
				.verify(mockSettings)
				.stubOnly();
	}

	private static class AnyTest {
		public static final String notStubField = "notStub";
		public static final String stubOnlyField = "stubOnly";
		public static final String metaAnnotatedField = "complexMock";

		@AutowiredMock
		Object notStub;

		@AutowiredSpy
		@MockitoDouble(stub = true)
		Object stubOnly;

		@ComplexMock
		Object complexMock;
	}

	@Retention(RetentionPolicy.RUNTIME)
	@Target(ElementType.FIELD)
	@AutowiredMock
	@MockitoDouble(stub = true)
	@interface ComplexMock {}
}


text:
namespace Wailea {

namespace Directed {

template <class BASE_GRAPH, class BASE_NODE, class BASE_EDGE>
void DFSDiExplorer<BASE_GRAPH,BASE_NODE,BASE_EDGE>::setStartNode(
    DDiNode& s
) noexcept
{
    mCurrentNodeIt = s.backIt();
    s.initExploration(mG.nodes().second);
}

template <class BASE_GRAPH, class BASE_NODE, class BASE_EDGE>
void DFSDiExplorer<BASE_GRAPH,BASE_NODE,BASE_EDGE>::reset(
    DDiGraph& g,
    bool      reversed
) noexcept
{

    auto nodeItPair = g.nodes();
    for (auto nit = nodeItPair.first; nit != nodeItPair.second; nit++) {
        dynamic_cast<DDiNode&>(*(*nit)).resetForDFS(reversed);
    }

    auto edgeItPair = g.edges();
    for (auto eit = edgeItPair.first; eit != edgeItPair.second; eit++) {
        dynamic_cast<DDiEdge&>(*(*eit)).resetForDFS();
    }

}

template <class BASE_GRAPH, class BASE_NODE, class BASE_EDGE>
void DFSDiExplorer<BASE_GRAPH,BASE_NODE,BASE_EDGE>::run(DDiNode& st) noexcept
{
    setStartNode(st);
    mStrategy.resetEarlyOut();
    while (oneStep());
}

template <class BASE_GRAPH, class BASE_NODE, class BASE_EDGE>
bool DFSDiExplorer<BASE_GRAPH,BASE_NODE,BASE_EDGE>::oneStep()
{

    DDiNode& currentNode = dynamic_cast<DDiNode&>(*(*mCurrentNodeIt));

    if ( !currentNode.isVisited() ) {

         // It has just entered this node.
         mStrategy.enterNode(currentNode);
         currentNode.setVisited();
         currentNode.resetWaitingForChild();

    }
    else {

        if (!currentNode.isWaitingForChild()) {

            // Ready to explore a new edge if there is one.
            if (!currentNode.hasExploredAllEdges()) {

                // It has at least an unexplored edge.
                DDiEdge& currentEdge = currentNode.currentDFSEdge();

                if (currentEdge.isVisited()) {

                    // The edge has been already processed as a frond
                    // when the adjacent node was explored. Skipping.
                    currentNode.advanceDFSEdge();
                }
                else {

                    DDiNode& adjacentNode = dynamic_cast<DDiNode&>(
                                    currentEdge.adjacentNode(currentNode));

                    if (adjacentNode.isVisited()) {

                        // The current edge is a frond.

                        // Call setWaitingForChild  and resetWaitingForChild
                        // here to cope with the
                        // situation where setNextDFSEdge() is called
                        // in processFrond below, in which case,
                        // the currentEdge is not changed but the next one
                        // to visit will be set by setNextDFSEdge().
                        currentNode.setWaitingForChild();
                        mStrategy.processFrond(currentNode,currentEdge);
                        currentNode.resetWaitingForChild();

                        currentEdge.setVisited();
                        // Move on to the next unexplored edge.
                        currentNode.advanceDFSEdge();

                    }
                    else {

                        if(mStrategy.isVisitingChild(currentNode,currentEdge)){

                            // Visit the current edge and the adjacent node.

                            // Call setWaitingForChild here to cope with the
                            // situation where setNextDFSEdge() is called
                            // in beforeVisitingChild below, in which case,
                            // the currentEdge is not changed but the next one
                            // to visit will be set by setNextDFSEdge().
                            currentNode.setWaitingForChild();
                            mStrategy.beforeVisitingChild
                                                     (currentNode,currentEdge);
                            currentEdge.setVisited();

                            // Going to the adjacent node at the next itration.
                            adjacentNode.initExploration(mCurrentNodeIt);
                            mCurrentNodeIt = adjacentNode.backIt();

                        }
                        else {

                            mStrategy.notVisitingChild
                                                     (currentNode,currentEdge);
                            // Move on to the next unexplored edge.
                            currentNode.advanceDFSEdge();
                        }
                    }
                }
            }
            else {

                // There is no more unexplored edge.
                mStrategy.leaveNode(currentNode);

                // Going back to the parent node.
                mCurrentNodeIt = currentNode.parentInDFS();
            }
        }
        else {

            // It has come back from the last child.
            mStrategy.afterVisitingChild(currentNode,
                                                currentNode.currentDFSEdge());
            currentNode.resetWaitingForChild();
            currentNode.advanceDFSEdge();
        }
    }

    return !mStrategy.isEarlyOut() &&  mCurrentNodeIt != mG.nodes().second;
}

}// namespace Directed

}// namespace Wailea


text:
package org.jetbrains.plugins.scala
package codeInspection
package collections

import com.intellij.testFramework.EditorTestUtil.{SELECTION_END_TAG => END, SELECTION_START_TAG => START}

/**
 * @author Markus.Hauck
 */
abstract class SortedMaxMinInspectionTest extends OperationsOnCollectionInspectionTest {
  override val classOfInspection: Class[_ <: OperationOnCollectionInspection] =
    classOf[SortedMaxMinInspection]
}

class SortedMaxInspectionTest extends SortedMaxMinInspectionTest {

  override protected val hint: String =
    InspectionBundle.message("replace.sorted.head.with.min")

  def test(): Unit = {
    doTest(
      s"Seq(1,2,3).${START}sorted.head$END",
      "Seq(1,2,3).sorted.head",
      "Seq(1, 2, 3).min"
    )
  }
}

class SortedMinInspectionTest extends SortedMaxMinInspectionTest {

  override protected val hint: String =
    InspectionBundle.message("replace.sorted.last.with.max")

  def test(): Unit = {
    doTest(
      s"Seq(1,2,3).${START}sorted.last$END",
      "Seq(1,2,3).sorted.last",
      "Seq(1, 2, 3).max"
    )
  }
}

class SortByMaxInspectionTest extends SortedMaxMinInspectionTest {

  override protected val hint: String =
    InspectionBundle.message("replace.sortBy.head.with.minBy")

  def test(): Unit = {
    doTest(
      s"Seq(1,2,3).${START}sortBy(_.toString).head$END",
      "Seq(1,2,3).sortBy(_.toString).head",
      "Seq(1, 2, 3).minBy(_.toString)"
    )
  }
}

class SortByMinInspectionTest extends SortedMaxMinInspectionTest {

  override protected val hint: String =
    InspectionBundle.message("replace.sortBy.last.with.maxBy")

  def test(): Unit = {
    doTest(
      s"Seq(1,2,3).${START}sortBy(_.toString).last$END",
      "Seq(1,2,3).sortBy(_.toString).last",
      "Seq(1, 2, 3).maxBy(_.toString)"
    )
  }
}


text:
#ifndef BOX_H
#define BOX_H

/**
 * Box is a Shape.
 *  A box for now only implemented to work as a static object
 *  i.e. a floor or a wall.
 */
class Box : public Shape {
public:
    Box() { };
    Box(float, float);

    void draw();
    int getType();
    float calculateMass();
    float calculateMomentOfInertia();

    float _base;
    float _height;

    glm::vec2 _min;
    glm::vec2 _max;
};

#endif // BOX_H


text:
var Phaser = require('Phaser'),
    _ = require('lodash'),
    properties = require('./properties'),
    states = {
        boot: require('./states/boot.js'),
        preloader: require('./states/preloader.js'),
        game: require('./states/game.js'),
        level1: require('./states/level1.js'),
        level2: require('./states/level2.js'),
        level3: require('./states/level3.js'),
        level4: require('./states/level4.js'),
        gameover: require('./states/gameover.js'),
    },
    game = new Phaser.Game(properties.size.x, properties.size.y, Phaser.CANVAS, 'game');

// Automatically register each state.
_.each(states, function(state, key) {
  game.state.add(key, state(game));
});

game.state.start('boot');


text:
package org.fcrepo.common.rdf;

/**
 * The Fedora RDF namespace.
 *
 *

 * Namespace URI    : info:fedora/
 * Preferred Prefix : fedora
 *

 *
 * @see
 *      "info" URI Scheme Registry page
 * @author Chris Wilper
 */
public class FedoraNamespace
        extends RDFNamespace {

    private static final long serialVersionUID = 1L;

    public FedoraNamespace() {

        uri = "info:fedora/";
        prefix = "fedora";
    }

}


text:
package ca.uwaterloo.iss4e.demographics.dao.census.mapper;

import java.sql.ResultSet;
import java.sql.SQLException;

import org.springframework.jdbc.core.RowMapper;

import ca.uwaterloo.iss4e.demographics.model.census.WorkCommuteTransportation;

public class WorkCommuteTransportationMapper implements
		RowMapper<WorkCommuteTransportation> {
	public WorkCommuteTransportation mapRow(ResultSet rs, int rowNum)
			throws SQLException {
		WorkCommuteTransportation workCommuteTransportation = new WorkCommuteTransportation();
		workCommuteTransportation.setSamplePercentage(rs
				.getInt("work_commute_transportation.sample_percentage"));
		workCommuteTransportation.setTotalCount(rs
				.getDouble("work_commute_transportation.total"));
		workCommuteTransportation.setCarTruckVanDriver(rs
				.getDouble("work_commute_transportation.car_trk_van_driver"));
		workCommuteTransportation
				.setCarTruckVanPassenger(rs
						.getDouble("work_commute_transportation.car_trk_van_passenger"));
		workCommuteTransportation.setPublicTransit(rs
				.getDouble("work_commute_transportation.public_transit"));
		workCommuteTransportation.setWalked(rs
				.getDouble("work_commute_transportation.walked"));
		workCommuteTransportation.setBicycle(rs
				.getDouble("work_commute_transportation.bicycle"));
		workCommuteTransportation.setMotorcycle(rs
				.getDouble("work_commute_transportation.motorcycle"));
		workCommuteTransportation.setTaxicab(rs
				.getDouble("work_commute_transportation.taxicab"));
		workCommuteTransportation.setOtherMethod(rs
				.getDouble("work_commute_transportation.other"));
		return workCommuteTransportation;
	}
}


text:
import {init as initTranslation} from './translation';
import translationResources from './translation/resources';
initTranslation('fr', translationResources);

// Global configuration uese for tests.
require('babel-core/register')({
    presets: [
        'focus'
    ]
});

const chai = require('chai');
const sinon = require('sinon');
const sinonChai = require('sinon-chai');
const chaiSubset = require('chai-subset');
chai.use(chaiSubset);
chai.use(sinonChai);

// Js dom
import jsdom from 'jsdom';
global.document = jsdom.jsdom('<!doctype html>');
global.window = document.defaultView;
global.navigator = {
    userAgent: 'node.js'
};
const React = require('react');
// Globals
global.React = require('react');
global.ReactDOM = require('react-dom');
global.expect = chai.expect;
global.sinon = sinon;
global.TestUtils = require('react-addons-test-utils');
global.componentHandler = {upgradeElement: function(){}};
global.__DEV__ = process.env.DEV ? JSON.parse(process.env.DEV) : true;
global.Element = window.Element;

// take all properties of the window object and also attach it to the
// from mocha-jsdom https://github.com/rstacruz/mocha-jsdom/blob/master/index.js#L80
function propagateToGlobal (window) {
    for (const key in window) {
        if (!window.hasOwnProperty(key)) {continue; }
        if (key in global) {continue; }
        global[key] = window[key];
    }
}
// mocha global object
propagateToGlobal(window);

process.on('unhandledRejection', (error)=>{
    console.error('Unhandled Promise Rejection:');
    console.error(error && error.stack || error);
});


text:
'use strict';

var axios = require('axios');
var Promise = require('../../../lib/promise-proxy');
var sdk = require('../../../');
var baseUrl = 'https://api.mendeley.com';
var mockAuth = require('../../mocks/auth');

describe('institution trees api', function() {
    var institutionTreesApi = sdk({
      baseUrl: baseUrl,
      authFlow: mockAuth.mockImplicitGrantFlow()
    }).institutionTrees;

    describe('list method', function() {
        /* jshint camelcase: false */
        var ajaxSpy;
        var ajaxRequest;
        var params = {
            institution_id: '123'
        };

        beforeEach(function(done) {
            ajaxSpy = spyOn(axios, 'request').and.returnValue(Promise.resolve({headers: {}}));
            institutionTreesApi.list(params).then(_finally, _finally);

            function _finally() {
                expect(ajaxSpy).toHaveBeenCalled();
                ajaxRequest = ajaxSpy.calls.mostRecent().args[0];
                done();
            }
        });

        it('should be defined', function() {
            expect(typeof institutionTreesApi.list).toBe('function');
        });

        it('should use GET', function() {
            expect(ajaxRequest.method).toBe('get');
        });

        it('should use endpoint /institution_trees', function() {
            expect(ajaxRequest.url).toBe(baseUrl + '/institution_trees');
        });

        it('should NOT have a Content-Type header', function() {
            expect(ajaxRequest.headers['Content-Type']).not.toBeDefined();
        });

        it('should have an Authorization header', function() {
            expect(ajaxRequest.headers.Authorization).toBeDefined();
            expect(ajaxRequest.headers.Authorization).toBe('Bearer auth');
        });

        it('should allow parameters', function() {
            expect(ajaxRequest.params).toEqual(params);
        });

    });

    describe('retrieve method', function() {
        var ajaxSpy;
        var ajaxRequest;

        beforeEach(function(done) {
            ajaxSpy = spyOn(axios, 'request').and.returnValue(Promise.resolve({headers: {}}));
            institutionTreesApi.retrieve('123').then(_finally, _finally);

            function _finally() {
                expect(ajaxSpy).toHaveBeenCalled();
                ajaxRequest = ajaxSpy.calls.mostRecent().args[0];
                done();
            }
        });

        it('should be defined', function() {
            expect(typeof institutionTreesApi.retrieve).toBe('function');
        });

        it('should use GET', function() {
            expect(ajaxRequest.method).toBe('get');
        });

        it('should use endpoint /institution_trees/123', function() {
            expect(ajaxRequest.url).toBe(baseUrl + '/institution_trees/123');
        });

        it('should NOT have a Content-Type header', function() {
            expect(ajaxRequest.headers['Content-Type']).not.toBeDefined();
        });

        it('should have an Authorization header', function() {
            expect(ajaxRequest.headers.Authorization).toBeDefined();
            expect(ajaxRequest.headers.Authorization).toBe('Bearer auth');
        });
    });
});


text:
package consul

import (
	"errors"
	"fmt"
	"io/ioutil"
	"net"
	"os"
	"testing"
	"time"

	"github.com/hashicorp/consul/testutil"
)

var nextPort = 15000

func getPort() int {
	p := nextPort
	nextPort++
	return p
}

func tmpDir(t *testing.T) string {
	dir, err := ioutil.TempDir("", "consul")
	if err != nil {
		t.Fatalf("err: %v", err)
	}
	return dir
}

func configureTLS(config *Config) {
	config.CAFile = "../test/ca/root.cer"
	config.CertFile = "../test/key/ourdomain.cer"
	config.KeyFile = "../test/key/ourdomain.key"
}

func testServerConfig(t *testing.T, NodeName string) (string, *Config) {
	dir := tmpDir(t)
	config := DefaultConfig()

	config.NodeName = NodeName
	config.Bootstrap = true
	config.Datacenter = "dc1"
	config.DataDir = dir
	config.RPCAddr = &net.TCPAddr{
		IP:   []byte{127, 0, 0, 1},
		Port: getPort(),
	}
	config.SerfLANConfig.MemberlistConfig.BindAddr = "127.0.0.1"
	config.SerfLANConfig.MemberlistConfig.BindPort = getPort()
	config.SerfLANConfig.MemberlistConfig.SuspicionMult = 2
	config.SerfLANConfig.MemberlistConfig.ProbeTimeout = 50 * time.Millisecond
	config.SerfLANConfig.MemberlistConfig.ProbeInterval = 100 * time.Millisecond
	config.SerfLANConfig.MemberlistConfig.GossipInterval = 100 * time.Millisecond

	config.SerfWANConfig.MemberlistConfig.BindAddr = "127.0.0.1"
	config.SerfWANConfig.MemberlistConfig.BindPort = getPort()
	config.SerfWANConfig.MemberlistConfig.SuspicionMult = 2
	config.SerfWANConfig.MemberlistConfig.ProbeTimeout = 50 * time.Millisecond
	config.SerfWANConfig.MemberlistConfig.ProbeInterval = 100 * time.Millisecond
	config.SerfWANConfig.MemberlistConfig.GossipInterval = 100 * time.Millisecond

	config.RaftConfig.LeaderLeaseTimeout = 20 * time.Millisecond
	config.RaftConfig.HeartbeatTimeout = 40 * time.Millisecond
	config.RaftConfig.ElectionTimeout = 40 * time.Millisecond

	config.ReconcileInterval = 100 * time.Millisecond
	return dir, config
}

func testServer(t *testing.T) (string, *Server) {
	return testServerDC(t, "dc1")
}

func testServerDC(t *testing.T, dc string) (string, *Server) {
	return testServerDCBootstrap(t, dc, true)
}

func testServerDCBootstrap(t *testing.T, dc string, bootstrap bool) (string, *Server) {
	name := fmt.Sprintf("Node %d", getPort())
	dir, config := testServerConfig(t, name)
	config.Datacenter = dc
	config.Bootstrap = bootstrap
	server, err := NewServer(config)
	if err != nil {
		t.Fatalf("err: %v", err)
	}
	return dir, server
}

func testServerDCExpect(t *testing.T, dc string, expect int) (string, *Server) {
	name := fmt.Sprintf("Node %d", getPort())
	dir, config := testServerConfig(t, name)
	config.Datacenter = dc
	config.Bootstrap = false
	config.BootstrapExpect = expect
	server, err := NewServer(config)
	if err != nil {
		t.Fatalf("err: %v", err)
	}
	return dir, server
}

func testServerWithConfig(t *testing.T, cb func(c *Config)) (string, *Server) {
	name := fmt.Sprintf("Node %d", getPort())
	dir, config := testServerConfig(t, name)
	cb(config)
	server, err := NewServer(config)
	if err != nil {
		t.Fatalf("err: %v", err)
	}
	return dir, server
}

func TestServer_StartStop(t *testing.T) {
	dir := tmpDir(t)
	defer os.RemoveAll(dir)

	config := DefaultConfig()
	config.DataDir = dir

	private, err := GetPrivateIP()
	if err != nil {
		t.Fatalf("err: %v", err)
	}

	config.RPCAdvertise = &net.TCPAddr{
		IP:   private,
		Port: 8300,
	}

	server, err := NewServer(config)
	if err != nil {
		t.Fatalf("err: %v", err)
	}

	if err := server.Shutdown(); err != nil {
		t.Fatalf("err: %v", err)
	}

	// Idempotent
	if err := server.Shutdown(); err != nil {
		t.Fatalf("err: %v", err)
	}
}

func TestServer_JoinLAN(t *testing.T) {
	dir1, s1 := testServer(t)
	defer os.RemoveAll(dir1)
	defer s1.Shutdown()

	dir2, s2 := testServer(t)
	defer os.RemoveAll(dir2)
	defer s2.Shutdown()

	// Try to join
	addr := fmt.Sprintf("127.0.0.1:%d",
		s1.config.SerfLANConfig.MemberlistConfig.BindPort)
	if _, err := s2.JoinLAN([]string{addr}); err != nil {
		t.Fatalf("err: %v", err)
	}

	// Check the members
	testutil.WaitForResult(func() (bool, error) {
		return len(s1.LANMembers()) == 2, nil
	}, func(err error) {
		t.Fatalf("bad len")
	})

	testutil.WaitForResult(func() (bool, error) {
		return len(s2.LANMembers()) == 2, nil
	}, func(err error) {
		t.Fatalf("bad len")
	})
}

func TestServer_JoinWAN(t *testing.T) {
	dir1, s1 := testServer(t)
	defer os.RemoveAll(dir1)
	defer s1.Shutdown()

	dir2, s2 := testServerDC(t, "dc2")
	defer os.RemoveAll(dir2)
	defer s2.Shutdown()

	// Try to join
	addr := fmt.Sprintf("127.0.0.1:%d",
		s1.config.SerfWANConfig.MemberlistConfig.BindPort)
	if _, err := s2.JoinWAN([]string{addr}); err != nil {
		t.Fatalf("err: %v", err)
	}

	// Check the members
	testutil.WaitForResult(func() (bool, error) {
		return len(s1.WANMembers()) == 2, nil
	}, func(err error) {
		t.Fatalf("bad len")
	})

	testutil.WaitForResult(func() (bool, error) {
		return len(s2.WANMembers()) == 2, nil
	}, func(err error) {
		t.Fatalf("bad len")
	})

	// Check the remoteConsuls has both
	if len(s1.remoteConsuls) != 2 {
		t.Fatalf("remote consul missing")
	}

	testutil.WaitForResult(func() (bool, error) {
		return len(s2.remoteConsuls) == 2, nil
	}, func(err error) {
		t.Fatalf("remote consul missing")
	})
}

func TestServer_Leave(t *testing.T) {
	dir1, s1 := testServer(t)
	defer os.RemoveAll(dir1)
	defer s1.Shutdown()

	// Second server not in bootstrap mode
	dir2, s2 := testServerDCBootstrap(t, "dc1", false)
	defer os.RemoveAll(dir2)
	defer s2.Shutdown()

	// Try to join
	addr := fmt.Sprintf("127.0.0.1:%d",
		s1.config.SerfLANConfig.MemberlistConfig.BindPort)
	if _, err := s2.JoinLAN([]string{addr}); err != nil {
		t.Fatalf("err: %v", err)
	}

	var p1 []net.Addr
	var p2 []net.Addr

	testutil.WaitForResult(func() (bool, error) {
		p1, _ = s1.raftPeers.Peers()
		return len(p1) == 2, errors.New(fmt.Sprintf("%v", p1))
	}, func(err error) {
		t.Fatalf("should have 2 peers: %v", err)
	})

	testutil.WaitForResult(func() (bool, error) {
		p2, _ = s2.raftPeers.Peers()
		return len(p2) == 2, errors.New(fmt.Sprintf("%v", p1))
	}, func(err error) {
		t.Fatalf("should have 2 peers: %v", err)
	})

	// Issue a leave
	if err := s2.Leave(); err != nil {
		t.Fatalf("err: %v", err)
	}

	// Should lose a peer
	p1, _ = s1.raftPeers.Peers()
	if len(p1) != 1 {
		t.Fatalf("should have 1 peer: %v", p1)
	}
}

func TestServer_RPC(t *testing.T) {
	dir1, s1 := testServer(t)
	defer os.RemoveAll(dir1)
	defer s1.Shutdown()

	var out struct{}
	if err := s1.RPC("Status.Ping", struct{}{}, &out); err != nil {
		t.Fatalf("err: %v", err)
	}
}

func TestServer_JoinLAN_TLS(t *testing.T) {
	dir1, conf1 := testServerConfig(t, "a.testco.internal")
	conf1.VerifyIncoming = true
	conf1.VerifyOutgoing = true
	configureTLS(conf1)
	s1, err := NewServer(conf1)
	if err != nil {
		t.Fatalf("err: %v", err)
	}
	defer os.RemoveAll(dir1)
	defer s1.Shutdown()

	dir2, conf2 := testServerConfig(t, "b.testco.internal")
	conf2.Bootstrap = false
	conf2.VerifyIncoming = true
	conf2.VerifyOutgoing = true
	configureTLS(conf2)
	s2, err := NewServer(conf2)
	if err != nil {
		t.Fatalf("err: %v", err)
	}
	defer os.RemoveAll(dir2)
	defer s2.Shutdown()

	// Try to join
	addr := fmt.Sprintf("127.0.0.1:%d",
		s1.config.SerfLANConfig.MemberlistConfig.BindPort)
	if _, err := s2.JoinLAN([]string{addr}); err != nil {
		t.Fatalf("err: %v", err)
	}

	// Check the members
	testutil.WaitForResult(func() (bool, error) {
		return len(s1.LANMembers()) == 2, nil
	}, func(err error) {
		t.Fatalf("bad len")
	})

	testutil.WaitForResult(func() (bool, error) {
		return len(s2.LANMembers()) == 2, nil
	}, func(err error) {
		t.Fatalf("bad len")
	})

	// Verify Raft has established a peer
	testutil.WaitForResult(func() (bool, error) {
		return s1.Stats()["raft"]["num_peers"] == "1", nil
	}, func(err error) {
		t.Fatalf("no peer established")
	})

	testutil.WaitForResult(func() (bool, error) {
		return s2.Stats()["raft"]["num_peers"] == "1", nil
	}, func(err error) {
		t.Fatalf("no peer established")
	})
}

func TestServer_Expect(t *testing.T) {
	// all test servers should be in expect=3 mode
	dir1, s1 := testServerDCExpect(t, "dc1", 3)
	defer os.RemoveAll(dir1)
	defer s1.Shutdown()

	dir2, s2 := testServerDCExpect(t, "dc1", 3)
	defer os.RemoveAll(dir2)
	defer s2.Shutdown()

	dir3, s3 := testServerDCExpect(t, "dc1", 0)
	defer os.RemoveAll(dir3)
	defer s3.Shutdown()

	// Try to join
	addr := fmt.Sprintf("127.0.0.1:%d",
		s1.config.SerfLANConfig.MemberlistConfig.BindPort)
	if _, err := s2.JoinLAN([]string{addr}); err != nil {
		t.Fatalf("err: %v", err)
	}

	var p1 []net.Addr
	var p2 []net.Addr

	// should have no peers yet
	testutil.WaitForResult(func() (bool, error) {
		p1, _ = s1.raftPeers.Peers()
		return len(p1) == 0, errors.New(fmt.Sprintf("%v", p1))
	}, func(err error) {
		t.Fatalf("should have 0 peers: %v", err)
	})

	testutil.WaitForResult(func() (bool, error) {
		p2, _ = s2.raftPeers.Peers()
		return len(p2) == 0, errors.New(fmt.Sprintf("%v", p2))
	}, func(err error) {
		t.Fatalf("should have 0 peers: %v", err)
	})

	// join the third node
	if _, err := s3.JoinLAN([]string{addr}); err != nil {
		t.Fatalf("err: %v", err)
	}

	var p3 []net.Addr

	// should now have all three peers
	testutil.WaitForResult(func() (bool, error) {
		p1, _ = s1.raftPeers.Peers()
		return len(p1) == 3, errors.New(fmt.Sprintf("%v", p1))
	}, func(err error) {
		t.Fatalf("should have 3 peers: %v", err)
	})

	testutil.WaitForResult(func() (bool, error) {
		p2, _ = s2.raftPeers.Peers()
		return len(p2) == 3, errors.New(fmt.Sprintf("%v", p2))
	}, func(err error) {
		t.Fatalf("should have 3 peers: %v", err)
	})

	testutil.WaitForResult(func() (bool, error) {
		p3, _ = s3.raftPeers.Peers()
		return len(p3) == 3, errors.New(fmt.Sprintf("%v", p3))
	}, func(err error) {
		t.Fatalf("should have 3 peers: %v", err)
	})

	// check if there is one leader now
	testutil.WaitForLeader(t, s1.RPC, "dc1")
}

func TestServer_BadExpect(t *testing.T) {
	// this one is in expect=3 mode
	dir1, s1 := testServerDCExpect(t, "dc1", 3)
	defer os.RemoveAll(dir1)
	defer s1.Shutdown()

	// this one is in expect=2 mode
	dir2, s2 := testServerDCExpect(t, "dc1", 2)
	defer os.RemoveAll(dir2)
	defer s2.Shutdown()

	// and this one is in expect=3 mode
	dir3, s3 := testServerDCExpect(t, "dc1", 3)
	defer os.RemoveAll(dir3)
	defer s3.Shutdown()

	// Try to join
	addr := fmt.Sprintf("127.0.0.1:%d",
		s1.config.SerfLANConfig.MemberlistConfig.BindPort)
	if _, err := s2.JoinLAN([]string{addr}); err != nil {
		t.Fatalf("err: %v", err)
	}

	var p1 []net.Addr
	var p2 []net.Addr

	// should have no peers yet
	testutil.WaitForResult(func() (bool, error) {
		p1, _ = s1.raftPeers.Peers()
		return len(p1) == 0, errors.New(fmt.Sprintf("%v", p1))
	}, func(err error) {
		t.Fatalf("should have 0 peers: %v", err)
	})

	testutil.WaitForResult(func() (bool, error) {
		p2, _ = s2.raftPeers.Peers()
		return len(p2) == 0, errors.New(fmt.Sprintf("%v", p2))
	}, func(err error) {
		t.Fatalf("should have 0 peers: %v", err)
	})

	// join the third node
	if _, err := s3.JoinLAN([]string{addr}); err != nil {
		t.Fatalf("err: %v", err)
	}

	var p3 []net.Addr

	// should still have no peers (because s2 is in expect=2 mode)
	testutil.WaitForResult(func() (bool, error) {
		p1, _ = s1.raftPeers.Peers()
		return len(p1) == 0, errors.New(fmt.Sprintf("%v", p1))
	}, func(err error) {
		t.Fatalf("should have 0 peers: %v", err)
	})

	testutil.WaitForResult(func() (bool, error) {
		p2, _ = s2.raftPeers.Peers()
		return len(p2) == 0, errors.New(fmt.Sprintf("%v", p2))
	}, func(err error) {
		t.Fatalf("should have 0 peers: %v", err)
	})

	testutil.WaitForResult(func() (bool, error) {
		p3, _ = s3.raftPeers.Peers()
		return len(p3) == 0, errors.New(fmt.Sprintf("%v", p3))
	}, func(err error) {
		t.Fatalf("should have 0 peers: %v", err)
	})

}


text:
package org.springframework.jdbc.core.support;

import java.io.IOException;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.springframework.dao.DataAccessException;
import org.springframework.dao.IncorrectResultSizeDataAccessException;
import org.springframework.jdbc.LobRetrievalFailureException;
import org.springframework.jdbc.support.lob.LobCreator;
import org.springframework.jdbc.support.lob.LobHandler;

import static org.junit.Assert.*;
import static org.mockito.BDDMockito.*;

/**
 * @author Alef Arendsen
 */
public class LobSupportTests {

	@Rule
	public ExpectedException thrown = ExpectedException.none();

	@Test
	public void testCreatingPreparedStatementCallback() throws SQLException {
		LobHandler handler = mock(LobHandler.class);
		LobCreator creator = mock(LobCreator.class);
		PreparedStatement ps = mock(PreparedStatement.class);

		given(handler.getLobCreator()).willReturn(creator);
		given(ps.executeUpdate()).willReturn(3);

		class SetValuesCalled {
			boolean b = false;
		}

		final SetValuesCalled svc = new SetValuesCalled();

		AbstractLobCreatingPreparedStatementCallback psc = new AbstractLobCreatingPreparedStatementCallback(
				handler) {
			@Override
			protected void setValues(PreparedStatement ps, LobCreator lobCreator)
					throws SQLException, DataAccessException {
				svc.b = true;
			}
		};

		assertEquals(Integer.valueOf(3), psc.doInPreparedStatement(ps));
		assertTrue(svc.b);
		verify(creator).close();
		verify(handler).getLobCreator();
		verify(ps).executeUpdate();
	}

	@Test
	public void testAbstractLobStreamingResultSetExtractorNoRows() throws SQLException {
		ResultSet rset = mock(ResultSet.class);
		AbstractLobStreamingResultSetExtractor<Void> lobRse = getResultSetExtractor(false);
		thrown.expect(IncorrectResultSizeDataAccessException.class);
		try {
			lobRse.extractData(rset);
		}
		finally {
			verify(rset).next();
		}
	}

	@Test
	public void testAbstractLobStreamingResultSetExtractorOneRow() throws SQLException {
		ResultSet rset = mock(ResultSet.class);
		given(rset.next()).willReturn(true, false);
		AbstractLobStreamingResultSetExtractor<Void> lobRse = getResultSetExtractor(false);
		lobRse.extractData(rset);
		verify(rset).clearWarnings();
	}

	@Test
	public void testAbstractLobStreamingResultSetExtractorMultipleRows()
			throws SQLException {
		ResultSet rset = mock(ResultSet.class);
		given(rset.next()).willReturn(true, true, false);
		AbstractLobStreamingResultSetExtractor<Void> lobRse = getResultSetExtractor(false);
		thrown.expect(IncorrectResultSizeDataAccessException.class);
		try {
			lobRse.extractData(rset);
		}
		finally {
			verify(rset).clearWarnings();
		}
	}

	@Test
	public void testAbstractLobStreamingResultSetExtractorCorrectException()
			throws SQLException {
		ResultSet rset = mock(ResultSet.class);
		given(rset.next()).willReturn(true);
		AbstractLobStreamingResultSetExtractor<Void> lobRse = getResultSetExtractor(true);
		thrown.expect(LobRetrievalFailureException.class);
		lobRse.extractData(rset);
	}

	private AbstractLobStreamingResultSetExtractor<Void> getResultSetExtractor(final boolean ex) {
		AbstractLobStreamingResultSetExtractor<Void> lobRse = new AbstractLobStreamingResultSetExtractor<Void>() {

			@Override
			protected void streamData(ResultSet rs) throws SQLException, IOException {
				if (ex) {
					throw new IOException();
				}
				else {
					rs.clearWarnings();
				}
			}
		};
		return lobRse;
	}
}


text:
<?php
    include ('process.php');
    date_default_timezone_set("Asia/Manila");
    $date=date("Y/m/d");
    $connect = connect();
$printoutdate=date("Y/m/d");
$printouttime=date("h:i:sa");
$category="All";
$location="All";
$productcode="101";
$productname="Electric Fan";
$customerorder="each";
$supplierorder="2";
$total="120.00";
$result=listitems($connect);

?>

	Inventory Planning Report

	Print Out Date: <?php echo $printoutdate?>&nbsp<?php echo $printouttime?>

	Product Code
	Product Name
	Customer Order
	Supplier Order

<?php 	while($row=mysqli_fetch_assoc($result)){ ?>

	<?=$row['item_code']?>
	<?=$row['name']?>
	<?php echo $customerorder?>
	<?php $getsupplierorder=mysqli_fetch_assoc(getsupplierorder($connect, $row['name'])); echo $getsupplierorder['quantity'];?>

	<?php } ?>


text:
package org.androidpn.server.xmpp.session;

import org.androidpn.server.service.UserNotFoundException;
import org.androidpn.server.xmpp.auth.AuthToken;
import org.androidpn.server.xmpp.net.Connection;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmpp.packet.JID;
import org.xmpp.packet.Presence;

/**
 * This class represents a session between the server and a client.
 *
 * @author Sehwan Noh (devnoh@gmail.com)
 */
public class ClientSession extends Session {

    private static final Log log = LogFactory.getLog(ClientSession.class);

    private static final String ETHERX_NAMESPACE = "http://etherx.jabber.org/streams";

    private AuthToken authToken;

    private boolean initialized;

    private boolean wasAvailable = false;

    private Presence presence = null;

    /**
     * Constructor.
     *
     * @param serverName the server name
     * @param connection the connection
     * @param streamID the stream ID
     */
    public ClientSession(String serverName, Connection connection,
            String streamID) {
        super(serverName, connection, streamID);
        presence = new Presence();
        presence.setType(Presence.Type.unavailable);
    }

    /**
     * Creates a new session between the server and a client, and returns it.
     *
     * @param serverName the server name
     * @param connection the connection
     * @param xpp the XML parser to handle incoming data
     * @return a newly created session
     * @throws XmlPullParserException if an error occurs while parsing incoming data
     */
    public static ClientSession createSession(String serverName,
            Connection connection, XmlPullParser xpp)
            throws XmlPullParserException {
        log.debug("createSession()...");

        if (!xpp.getName().equals("stream")) {
            throw new XmlPullParserException("Bad opening tag (not stream)");
        }

        if (!xpp.getNamespace(xpp.getPrefix()).equals(ETHERX_NAMESPACE)) {
            throw new XmlPullParserException("Stream not in correct namespace");
        }

        String language = "en";
        for (int i = 0; i < xpp.getAttributeCount(); i++) {
            if ("lang".equals(xpp.getAttributeName(i))) {
                language = xpp.getAttributeValue(i);
            }
        }

        // Store language and version information
        connection.setLanaguage(language);
        connection.setXMPPVersion(MAJOR_VERSION, MINOR_VERSION);

        // Create a ClientSession
        ClientSession session = SessionManager.getInstance()
                .createClientSession(connection);

        // Build the start packet response
        StringBuilder sb = new StringBuilder(200);
        sb.append("<?xml version='1.0' encoding='UTF-8'?>");
        sb.append("<stream:stream ");
        sb
                .append("xmlns:stream=\"http://etherx.jabber.org/streams\" xmlns=\"jabber:client\" from=\"");
        sb.append(serverName);
        sb.append("\" id=\"");
        sb.append(session.getStreamID().toString());
        sb.append("\" xml:lang=\"");
        sb.append(language);
        sb.append("\" version=\"");
        sb.append(MAJOR_VERSION).append(".").append(MINOR_VERSION);
        sb.append("\">");
        connection.deliverRawText(sb.toString());

        // XMPP 1.0 needs stream features
        sb = new StringBuilder();
        sb.append("<stream:features>");
        if (connection.getTlsPolicy() != Connection.TLSPolicy.disabled) {
            sb.append("<starttls xmlns=\"urn:ietf:params:xml:ns:xmpp-tls\">");
            if (connection.getTlsPolicy() == Connection.TLSPolicy.required) {
                sb.append("<required/>");
            }
            sb.append("</starttls>");
        }

        String specificFeatures = session.getAvailableStreamFeatures();
        if (specificFeatures != null) {
            sb.append(specificFeatures);
        }
        sb.append("</stream:features>");

        connection.deliverRawText(sb.toString());
        return session;
    }

    /**
     * Returns the username associated with this session.
     *
     * @return the username
     * @throws UserNotFoundException if a user has not authenticated yet
     */
    public String getUsername() throws UserNotFoundException {
        if (authToken == null) {
            throw new UserNotFoundException();
        }
        return getAddress().getNode();
    }

    /**
     * Returns the authentication token associated with this session.
     *
     * @return the authentication token
     */
    public AuthToken getAuthToken() {
        return authToken;
    }

    /**
     * Initialize the session with an authentication token
     * @param authToken the authentication token
     */
    public void setAuthToken(AuthToken authToken) {
        this.authToken = authToken;
    }

    /**
     * Initialize the session with an authentication token and resource name.
     *
     * @param authToken the authentication token
     * @param resource the resource
     */
    public void setAuthToken(AuthToken authToken, String resource) {
        setAddress(new JID(authToken.getUsername(), getServerName(), resource));
        this.authToken = authToken;
        setStatus(Session.STATUS_AUTHENTICATED);
        // Add session to the session manager
        sessionManager.addSession(this);
    }

    /**
     * Indicates if the session has been initialized.
     *
     * @return true if the session has been initialized, false otherwise.
     */
    public boolean isInitialized() {
        return initialized;
    }

    /**
     * Sets the initialization state of the session.
     *
     * @param initialized true if the session has been initialized
     */
    public void setInitialized(boolean initialized) {
        this.initialized = initialized;
    }

    /**
     * Indicates if the session was available ever.
     *
     * @return true if the session was available ever, false otherwise.
     */
    public boolean wasAvailable() {
        return wasAvailable;
    }

    /**
     * Returns the presence of this session.
     *
     * @return the presence
     */
    public Presence getPresence() {
        return presence;
    }

    /**
     * Sets the presence of this session.
     *
     * @param presence the presence
     */
    public void setPresence(Presence presence) {
        Presence oldPresence = this.presence;
        this.presence = presence;
        if (oldPresence.isAvailable() && !this.presence.isAvailable()) {
            setInitialized(false);
        } else if (!oldPresence.isAvailable() && this.presence.isAvailable()) {
            wasAvailable = true;
        }
    }

    /**
     * Returns a text with the available stream features.
     */
    public String getAvailableStreamFeatures() {
        StringBuilder sb = new StringBuilder();
        if (getAuthToken() == null) {
            // Supports Non-SASL Authentication
            sb.append("<auth xmlns=\"http://jabber.org/features/iq-auth\"/>");
            // Supports In-Band Registration
            sb
                    .append("<register xmlns=\"http://jabber.org/features/iq-register\"/>");
        } else {
            // If the session has been authenticated
            sb.append("<bind xmlns=\"urn:ietf:params:xml:ns:xmpp-bind\"/>");
            sb
                    .append("<session xmlns=\"urn:ietf:params:xml:ns:xmpp-session\"/>");
        }
        return sb.toString();
    }

    @Override
    public String toString() {
        return super.toString() + " presence: " + presence;
    }

}


text:
namespace base {
namespace trace_event {

class ConvertableToTraceFormat;
class MemoryDumpManager;
class MemoryDumpSessionState;

// ProcessMemoryDump is as a strongly typed container which enforces the data
// model for each memory dump and holds the dumps produced by the
// MemoryDumpProvider(s) for a specific process.
// At trace generation time (i.e. when AsValue() is called), ProcessMemoryDump
// will compose a key-value dictionary of the various dumps obtained at trace
// dump point time.
class BASE_EXPORT ProcessMemoryDump {
 public:
  // Maps allocator dumps absolute names (allocator_name/heap/subheap) to
  // MemoryAllocatorDump instances.
  using AllocatorDumpsMap =
      SmallMap<hash_map<std::string, MemoryAllocatorDump*>>;

  ProcessMemoryDump(const scoped_refptr<MemoryDumpSessionState>& session_state);
  ~ProcessMemoryDump();

  // Called at trace generation time to populate the TracedValue.
  void AsValueInto(TracedValue* value) const;

  ProcessMemoryTotals* process_totals() { return &process_totals_; }
  bool has_process_totals() const { return has_process_totals_; }
  void set_has_process_totals() { has_process_totals_ = true; }

  ProcessMemoryMaps* process_mmaps() { return &process_mmaps_; }
  bool has_process_mmaps() const { return has_process_mmaps_; }
  void set_has_process_mmaps() { has_process_mmaps_ = true; }

  // Creates a new MemoryAllocatorDump with the given name and returns the
  // empty object back to the caller.
  // Arguments:
  //   absolute_name: a name that uniquely identifies allocator dumps produced
  //       by this provider. It is possible to specify nesting by using a
  //       path-like string (e.g., v8/isolate1/heap1, v8/isolate1/heap2).
  //       Leading or trailing slashes are not allowed.
  // ProcessMemoryDump handles the memory ownership of its MemoryAllocatorDumps.
  MemoryAllocatorDump* CreateAllocatorDump(const std::string& absolute_name);

  // Looks up a MemoryAllocatorDump given its allocator and heap names, or
  // nullptr if not found.
  MemoryAllocatorDump* GetAllocatorDump(const std::string& absolute_name) const;

  // Returns the map of the MemoryAllocatorDumps added to this dump.
  const AllocatorDumpsMap& allocator_dumps() const { return allocator_dumps_; }

  const scoped_refptr<MemoryDumpSessionState>& session_state() const {
    return session_state_;
  }

 private:
  ProcessMemoryTotals process_totals_;
  bool has_process_totals_;

  ProcessMemoryMaps process_mmaps_;
  bool has_process_mmaps_;

  AllocatorDumpsMap allocator_dumps_;

  // ProcessMemoryDump handles the memory ownership of all its belongings.
  ScopedVector<MemoryAllocatorDump> allocator_dumps_storage_;

  // State shared among all PMDs instances created in a given trace session.
  scoped_refptr<MemoryDumpSessionState> session_state_;

  DISALLOW_COPY_AND_ASSIGN(ProcessMemoryDump);
};

}  // namespace trace_event
}  // namespace base

#endif  // BASE_TRACE_EVENT_PROCESS_MEMORY_DUMP_H_


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

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.9.1"/>
<title>"LO21 | Pistache": LO21</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

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

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

"LO21 | Pistache"

Projet de LO21 de Loïc Deryckère et Mewen Michel

Main Page

Related Pages

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

LO21

Project of a calendar + task manager in a POO course

<address class="footer">
Generated on Sat Jun 13 2015 18:07:02 for "LO21 | Pistache" by

 1.8.9.1
</address>


text:
% defaultSaliencyParams - returns a default salParams structure.
%
% params = defaultSaliencyParams
%    Returns a default structure with saliency parameters.
%
% params = defaultSaliencyParams(pyramidType)
%    Initializes parameters for a particular pyramidType:
%       'dyadic' - pyramids with downsampling by a factor of 2 (default)
%       'sqrt2'  - pyramids with downsampling by a factor of sqrt(2)
%    This makes a difference for the levels for the computation of the
%    center-surround differences.
%
% params = defaultSaliencyParams(...,imgSize)
%    Initializes params.foaSize to 1/6*min(w,h) (default: -1).
%    This is only important for params.IORtype='disk'.
%
% See also runSaliency, makeSaliencyMap, estimateShape, applyIOR,
%          removeColorFeatures, winnerToImgCoords, dataStructures.

% This file is part of the SaliencyToolbox - Copyright (C) 2006-2013
% by Dirk B. Walther and the California Institute of Technology.
% See the enclosed LICENSE.TXT document for the license agreement.
% More information about this project is available at:
% http://www.saliencytoolbox.net

function params = defaultSaliencyParams(varargin)

% this is only important for IORtype='disk'.
params.foaSize = -1;

% one of: 'dyadic','sqrt2'
params.pyramidType = 'dyadic';

% scan the arguments
for i = 1:length(varargin)
  switch class(varargin{i})
    case 'double'
      params.foaSize = round(max(varargin{i}(1:2)) / 6);
    case 'char'
      params.pyramidType = varargin{i};
    otherwise
      error(['Unknown data type for this function: ' class(varargin{i})]);
  end
end

% a cell array with a combination of:
% 'Color','Intensities','Orientations','Hue','Skin','TopDown'
params.features = {'Color','Intensities','Orientations'};

% the weights in the same order as params.features
params.weights = [1 1 1];

% one of: 'shape','disk','None'
params.IORtype = 'shape';

% one of: 'None','shapeSM','shapeCM','shapeFM','shapePyr'
%params.shapeMode = 'shapePyr';
params.shapeMode = 'shapeFM';

% the pyramid level parameters
params.levelParams = defaultLevelParams(params.pyramidType);

% one of: 'None','LocalMax','Iterative'
params.normtype = 'Iterative';

% number of iterations for Iterative normalization
params.numIter = 3;

% 1 for using random jitter in converting from saliency map
%   coordinates to image coordinates,
% 0 for not using random jitter
params.useRandom = 1;

% one of: 'Fast','LTU'
params.segmentComputeType = 'Fast';

params.IORdecay = 0.9999;
params.smOutputRange = 1e-9;
params.noiseAmpl = 1e-17;
params.noiseConst = 1e-14;

% parameters for the gabor filters for orientation maps
params.gaborParams = defaultGaborParams;

% angles (in degrees) for orientation maps
params.oriAngles = [0 45 90 135];

% oriComputeMode: 'efficient', 'full'
% efficient: only compute orientation filters for the pyramid levels
% that are actually going to be used (based on levelParams)
% full: compute orientation filters for all pyramid levels
params.oriComputeMode = 'efficient';

% visualizationMode: 'Contour', 'ContrastModulate', or 'None'
params.visualizationStyle = 'Contour';

% map that is true foer excluded regions
params.exclusionMask = [];


text:
import numpy as np
import pyrtools
from PIL import Image
from sys import argv

def normalize(img):
    return (img - img.min()) / (img.max() - img.min()) * 255

img = Image.open('../examples/einsteinCorrect.pgm')
img = np.asarray(img)
sfpyr = pyrtools.SCFpyr(img, int(argv[1]), int(argv[2]))
sfpyr.showPyr()
recon = sfpyr.reconPyr()
pyrtools.showIm(normalize(recon))


text:
package ru.rkhaustov.list;

import org.junit.Test;
import java.util.Iterator;

import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;

/**
 * Created by rvkha_000 on 30.05.2017.
 */
public class LinkedArrayTest {
    /**
     * test method add and get <String>.
     */
    @Test
    public void  whenAddStringThenGetString() {
        SimpleContainer<String> list = new LinkedArray<>();

        list.add("test");
        String result = list.get(0);

        assertThat(result, is("test"));
    }
    /**
     * test method removeFirst <String>.
     */
    @Test
    public void  whenRemoveFirstStringThenDelFirstObject() {
        SimpleContainer<String> list = new LinkedArray<>();

        list.add("first");
        list.add("second");

        String result = list.get(0);

        assertThat(result, is("first"));
    }
    /**
     * test method removeLast <String>.
     */
    @Test
    public void  whenRemoveLastStringThenDelLastObject() {
        SimpleContainer<String> list = new LinkedArray<>();

        list.add("first");
        list.add("second");
        list.add("third");

        String result = list.get(1);

        assertThat(result, is("second"));
    }
    /**
     * test method next() Iterator <Integer>.
     */
    @Test
    public void whenNextThenPointerForward() {
        SimpleContainer<Integer> list = new LinkedArray<>();

        list.add(4);
        list.add(3);
        list.add(2);
        list.add(1);

        Iterator<Integer> iterator = list.iterator();

        int result = iterator.next();
        assertThat(result, is(4));

        result = iterator.next();
        assertThat(result, is(3));

        result = iterator.next();
        assertThat(result, is(2));

        result = iterator.next();
        assertThat(result, is(1));
    }
    /**
     * Test hasNext() Iterator <Float>.
     */
    @Test
    public void whenHasNextCheckNextThenReturnFalse() {
        SimpleContainer<Float> list = new LinkedArray<>();

        list.add(4f);
        list.add(3f);

        Iterator<Float> iterator = list.iterator();

        iterator.next();
        iterator.next();

        boolean result = iterator.hasNext();

        assertThat(result, is(false));
    }
}


text:
package com.game.graphics.renderer;

public class FontData {
	public final Glyph[] glyphs;
	public final int fontHeight;

	public FontData(int numGlyphs, int fontHeight) {
		glyphs = new Glyph[numGlyphs];
		this.fontHeight = fontHeight;
	}
}


text:
/*  Title:      Pure/Admin/jenkins.scala
    Author:     Makarius

Support for Jenkins continuous integration service.
*/

package isabelle

import java.net.URL
import java.time.ZoneId

import scala.util.matching.Regex

object Jenkins
{
  /* server API */

  def root(): String =
    Isabelle_System.getenv_strict("ISABELLE_JENKINS_ROOT")

  def invoke(url: String, args: String*): Any =
  {
    val req = url + "/api/json?" + args.mkString("&")
    val result = Url.read(req)
    try { JSON.parse(result) }
    catch { case ERROR(_) => error("Malformed JSON from " + quote(req)) }
  }

  /* build jobs */

  def build_job_names(): List[String] =
    for {
      job <- JSON.array(invoke(root()), "jobs").getOrElse(Nil)
      _class <- JSON.string(job, "_class")
      if _class == "hudson.model.FreeStyleProject"
      name <- JSON.string(job, "name")
    } yield name

  def download_logs(job_names: List[String], dir: Path, progress: Progress = No_Progress)
  {
    val store = Sessions.store()
    val infos = job_names.flatMap(build_job_infos(_))
    Par_List.map((info: Job_Info) => info.download_log(store, dir, progress), infos)
  }

  /* build log status */

  val build_log_jobs = List("isabelle-nightly-benchmark", "isabelle-nightly-slow")

  val build_status_profiles: List[Build_Status.Profile] =
    build_log_jobs.map(job_name =>
      Build_Status.Profile("jenkins " + job_name, 0,
        Build_Log.Prop.build_engine + " = " + SQL.string(Build_Log.Jenkins.engine) + " AND " +
        Build_Log.Data.session_name + " <> " + SQL.string("Pure") + " AND " +
        Build_Log.Data.status + " = " + SQL.string(Build_Log.Session_Status.finished.toString) +
        " AND " + Build_Log.Data.log_name + " LIKE " + SQL.string("%" + job_name)))

  /* job info */

  sealed case class Job_Info(
    job_name: String,
    identify: Boolean,
    timestamp: Long,
    main_log: URL,
    session_logs: List[(String, String, URL)])
  {
    val date: Date = Date(Time.ms(timestamp), ZoneId.of("Europe/Berlin"))

    def log_filename: Path =
      Build_Log.log_filename(Build_Log.Jenkins.engine, date, List(job_name))

    def read_ml_statistics(store: Sessions.Store, session_name: String): List[Properties.T] =
    {
      def get_log(ext: String): Option[URL] =
        session_logs.collectFirst({ case (a, b, url) if a == session_name && b == ext => url })

      get_log("db") match {
        case Some(url) =>
          Isabelle_System.with_tmp_file(session_name, "db") { database =>
            Bytes.write(database, Bytes.read(url))
            using(SQLite.open_database(database))(db => store.read_ml_statistics(db, session_name))
          }
        case None =>
          get_log("gz") match {
            case Some(url) =>
              val log_file = Build_Log.Log_File(session_name, Url.read_gzip(url))
              log_file.parse_session_info(ml_statistics = true).ml_statistics
            case None => Nil
          }
      }
    }

    def download_log(store: Sessions.Store, dir: Path, progress: Progress = No_Progress)
    {
      val log_dir = dir + Build_Log.log_subdir(date)
      val log_path = log_dir + (if (identify) log_filename else log_filename.ext("xz"))

      if (!log_path.is_file) {
        progress.echo(log_path.expand.implode)
        Isabelle_System.mkdirs(log_dir)

        if (identify) {
          val log_file = Build_Log.Log_File(main_log.toString, Url.read(main_log))
          val isabelle_version = log_file.find_match(Build_Log.Jenkins.Isabelle_Version)
          val afp_version = log_file.find_match(Build_Log.Jenkins.AFP_Version)

          File.write(log_path,
            Build_Log.Identify.content(date, isabelle_version, afp_version) + "\n" +
              main_log.toString)
        }
        else {
          val ml_statistics =
            session_logs.map(_._1).toSet.toList.sorted.flatMap(session_name =>
              read_ml_statistics(store, session_name).
                map(props => (Build_Log.SESSION_NAME -> session_name) :: props))

          File.write_xz(log_path,
            terminate_lines(Url.read(main_log) ::
              ml_statistics.map(Build_Log.Log_File.print_props(Build_Log.ML_STATISTICS_MARKER, _))),
            XZ.options(6))
        }
      }
    }
  }

  def build_job_infos(job_name: String): List[Job_Info] =
  {
    val Session_Log = new Regex("""^.*/log/([^/]+)\.(db|gz)$""")

    val identify = job_name == "identify"
    val job = if (identify) "isabelle-nightly-slow" else job_name

    val infos =
      for {
        build <-
          JSON.array(
            invoke(root() + "/job/" + job, "tree=allBuilds[number,timestamp,artifacts[*]]"),
            "allBuilds").getOrElse(Nil)
        number <- JSON.int(build, "number")
        timestamp <- JSON.long(build, "timestamp")
      } yield {
        val job_prefix = root() + "/job/" + job + "/" + number
        val main_log = Url(job_prefix + "/consoleText")
        val session_logs =
          if (identify) Nil
          else {
            for {
              artifact <- JSON.array(build, "artifacts").getOrElse(Nil)
              log_path <- JSON.string(artifact, "relativePath")
              (name, ext) <- (log_path match { case Session_Log(a, b) => Some((a, b)) case _ => None })
            } yield (name, ext, Url(job_prefix + "/artifact/" + log_path))
          }
        Job_Info(job_name, identify, timestamp, main_log, session_logs)
      }

    infos.sortBy(info => - info.timestamp)
  }
}


text:
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.

package com.intellij.uiDesigner.radComponents;

import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.fileEditor.FileDocumentManager;
import com.intellij.openapi.module.ResourceFileUtil;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiClass;
import com.intellij.psi.util.PsiUtil;
import com.intellij.uiDesigner.*;
import com.intellij.uiDesigner.compiler.Utils;
import com.intellij.uiDesigner.lw.CompiledClassPropertiesProvider;
import com.intellij.uiDesigner.lw.LwRootContainer;
import org.jetbrains.annotations.NotNull;

import javax.swing.*;
import java.awt.*;

/**
 * @author yole
 */
public class RadNestedForm extends RadComponent {
  private static final Logger LOG = Logger.getInstance(RadNestedForm.class);

  private final String myFormFileName;
  private final RadRootContainer myRootContainer;

  public RadNestedForm(final ModuleProvider module, final String formFileName, final String id) throws Exception {
    super(module, JPanel.class, id);
    myFormFileName = formFileName;
    LOG.debug("Loading nested form " + formFileName);
    VirtualFile formFile = ResourceFileUtil.findResourceFileInDependents(getModule(), formFileName);
    if (formFile == null) {
      throw new IllegalArgumentException("Couldn't find virtual file for nested form " + formFileName);
    }
    Document doc = FileDocumentManager.getInstance().getDocument(formFile);
    final ClassLoader classLoader = LoaderFactory.getInstance(getProject()).getLoader(formFile);
    final LwRootContainer rootContainer = Utils.getRootContainer(doc.getText(), new CompiledClassPropertiesProvider(classLoader));
    myRootContainer = XmlReader.createRoot(module, rootContainer, classLoader, null);
    if (myRootContainer.getComponentCount() > 0) {
      getDelegee().setLayout(new BorderLayout());
      JComponent nestedFormDelegee = myRootContainer.getComponent(0).getDelegee();
      getDelegee().add(nestedFormDelegee, BorderLayout.CENTER);

      setRadComponentRecursive(nestedFormDelegee);
    }

    if (isCustomCreateRequired()) {
      setCustomCreate(true);
    }
  }

  private void setRadComponentRecursive(final JComponent component) {
    component.putClientProperty(CLIENT_PROP_RAD_COMPONENT, this);
    for (int i = 0; i < component.getComponentCount(); i++) {
      final Component child = component.getComponent(i);
      if (child instanceof JComponent) {
        setRadComponentRecursive((JComponent)child);
      }
    }
  }

  @Override
  public void write(XmlWriter writer) {
    writer.startElement(UIFormXmlConstants.ELEMENT_NESTED_FORM);
    try {
      writeId(writer);
      writer.addAttribute(UIFormXmlConstants.ATTRIBUTE_FORM_FILE, myFormFileName);
      writeBinding(writer);
      writeConstraints(writer);
    }
    finally {
      writer.endElement(); // component
    }
  }

  @Override
  @NotNull
  public String getComponentClassName() {
    return myRootContainer.getClassToBind();
  }

  @Override
  public boolean hasIntrospectedProperties() {
    return false;
  }

  @Override
  public boolean isCustomCreateRequired() {
    if (super.isCustomCreateRequired()) return true;
    PsiClass boundClass = FormEditingUtil.findClassToBind(getModule(), myRootContainer.getClassToBind());
    return isNonStaticInnerClass(boundClass);
  }

  private static boolean isNonStaticInnerClass(final PsiClass boundClass) {
    if (boundClass == null) return false;
    return PsiUtil.isInnerClass(boundClass) || isNonStaticInnerClass(boundClass.getContainingClass());
  }
}


text:
const utils = require('../utils.js');

module.exports = function() {
  return function(files, metalsmith, done) {
    const metadata = metalsmith.metadata();
    const normalize = utils.compose(batchReplacePath, replaceType, replaceAction, replaceModule)();
    normalize(files, metadata);
    done(null);
  };
};

function batchReplacePath(fn) {
  return (files, ctx) => {
    Object
      .keys(files)
      .forEach(filePath => {
        const newPath = fn(filePath, ctx);
        if (newPath !== filePath) {
          files[newPath] = files[filePath];
          delete files[filePath];
        }
      });
  };
}

function replaceType(fn) {
  return (path, ctx) => fn(path, ctx).replace(/(\[type\])/g, type => (ctx[type.substring(1, type.length - 1)] || ''));
}

function replaceAction(fn) {
  return (path, ctx) => fn(path, ctx).replace(/(\[action\])/g, action => (ctx[action.substring(1, action.length - 1)] || ''));
}

function replaceModule() {
  return (path, ctx) => path.replace(/(\[moduleName\])/g, module => (ctx[module.substring(1, module.length - 1)] || ctx['defaultModule'] || ''));
}


text:
<?php

namespace ZendTest\Cache;

use Zend\Cache;

/**
 * @group      Zend_Cache
 */
class PatternFactoryTest extends \PHPUnit_Framework_TestCase
{
    public function setUp()
    {
        Cache\PatternFactory::resetPluginManager();
    }

    public function tearDown()
    {
        Cache\PatternFactory::resetPluginManager();
    }

    public function testDefaultPluginManager()
    {
        $plugins = Cache\PatternFactory::getPluginManager();
        $this->assertInstanceOf('Zend\Cache\PatternPluginManager', $plugins);
    }

    public function testChangePluginManager()
    {
        $plugins = new Cache\PatternPluginManager();
        Cache\PatternFactory::setPluginManager($plugins);
        $this->assertSame($plugins, Cache\PatternFactory::getPluginManager());
    }

    public function testFactory()
    {
        $pattern1 = Cache\PatternFactory::factory('capture');
        $this->assertInstanceOf('Zend\Cache\Pattern\CaptureCache', $pattern1);

        $pattern2 = Cache\PatternFactory::factory('capture');
        $this->assertInstanceOf('Zend\Cache\Pattern\CaptureCache', $pattern2);

        $this->assertNotSame($pattern1, $pattern2);
    }
}


text:
	/*
  	Flaticon icon font: Flaticon
  	Creation date: 19/02/2016 14:50
  	*/

@font-face {
  font-family: "Flaticon81";
  src: url("./Flaticon.eot");
  src: url("./Flaticon.eot?#iefix") format("embedded-opentype"),
       url("./Flaticon.woff") format("woff"),
       url("./Flaticon.ttf") format("truetype"),
       url("./Flaticon.svg#Flaticon") format("svg");
  font-weight: normal;
  font-style: normal;
}

@media screen and (-webkit-min-device-pixel-ratio:0) {
  @font-face {
    font-family: "Flaticon81";
    src: url("./Flaticon.svg#Flaticon") format("svg");
  }
}

[class^="flaticon81-"]:before, [class*=" flaticon81-"]:before,
[class^="flaticon81-"]:after, [class*=" flaticon81-"]:after {
  font-family: flaticon81;
        font-size: 20px;
font-style: normal;
margin-left: 20px;
}

.flaticon81-administrator:before { content: "\f100"; }
.flaticon81-agreement:before { content: "\f101"; }
.flaticon81-armchair:before { content: "\f102"; }
.flaticon81-badge:before { content: "\f103"; }
.flaticon81-bank:before { content: "\f104"; }
.flaticon81-bank-card:before { content: "\f105"; }
.flaticon81-basket:before { content: "\f106"; }
.flaticon81-binocoulars:before { content: "\f107"; }
.flaticon81-box:before { content: "\f108"; }
.flaticon81-box-1:before { content: "\f109"; }
.flaticon81-bullseye:before { content: "\f10a"; }
.flaticon81-business-card:before { content: "\f10b"; }
.flaticon81-cabinet:before { content: "\f10c"; }
.flaticon81-calculator:before { content: "\f10d"; }
.flaticon81-calculator-1:before { content: "\f10e"; }
.flaticon81-calendar:before { content: "\f10f"; }
.flaticon81-calendar-1:before { content: "\f110"; }
.flaticon81-calendar-2:before { content: "\f111"; }
.flaticon81-cart:before { content: "\f112"; }
.flaticon81-cart-with-boxes:before { content: "\f113"; }
.flaticon81-certificate:before { content: "\f114"; }
.flaticon81-check:before { content: "\f115"; }
.flaticon81-check-mark:before { content: "\f116"; }
.flaticon81-clip:before { content: "\f117"; }
.flaticon81-clock:before { content: "\f118"; }
.flaticon81-container:before { content: "\f119"; }
.flaticon81-conversation:before { content: "\f11a"; }
.flaticon81-customer-relationship-management:before { content: "\f11b"; }
.flaticon81-desk:before { content: "\f11c"; }
.flaticon81-destination:before { content: "\f11d"; }
.flaticon81-diagram:before { content: "\f11e"; }
.flaticon81-director-desk:before { content: "\f11f"; }
.flaticon81-document-with-tables:before { content: "\f120"; }
.flaticon81-documents:before { content: "\f121"; }
.flaticon81-exchange-personel:before { content: "\f122"; }
.flaticon81-flag:before { content: "\f123"; }
.flaticon81-folders:before { content: "\f124"; }
.flaticon81-gear:before { content: "\f125"; }
.flaticon81-glasses:before { content: "\f126"; }
.flaticon81-graph:before { content: "\f127"; }
.flaticon81-graph-1:before { content: "\f128"; }
.flaticon81-graph-2:before { content: "\f129"; }
.flaticon81-graph-3:before { content: "\f12a"; }
.flaticon81-growth:before { content: "\f12b"; }
.flaticon81-hammer:before { content: "\f12c"; }
.flaticon81-hand:before { content: "\f12d"; }
.flaticon81-head:before { content: "\f12e"; }
.flaticon81-idea:before { content: "\f12f"; }
.flaticon81-idea-1:before { content: "\f130"; }
.flaticon81-info:before { content: "\f131"; }
.flaticon81-job:before { content: "\f132"; }
.flaticon81-lamp:before { content: "\f133"; }
.flaticon81-laptop:before { content: "\f134"; }
.flaticon81-list:before { content: "\f135"; }
.flaticon81-list-1:before { content: "\f136"; }
.flaticon81-man:before { content: "\f137"; }
.flaticon81-manager:before { content: "\f138"; }
.flaticon81-megaphone:before { content: "\f139"; }
.flaticon81-network:before { content: "\f13a"; }
.flaticon81-note:before { content: "\f13b"; }
.flaticon81-notebook:before { content: "\f13c"; }
.flaticon81-notebook-1:before { content: "\f13d"; }
.flaticon81-office-building:before { content: "\f13e"; }
.flaticon81-office-buildings:before { content: "\f13f"; }
.flaticon81-open-box:before { content: "\f140"; }
.flaticon81-pencin-and-eraser:before { content: "\f141"; }
.flaticon81-percent:before { content: "\f142"; }
.flaticon81-phone-book:before { content: "\f143"; }
.flaticon81-phone-call:before { content: "\f144"; }
.flaticon81-piggy-bank:before { content: "\f145"; }
.flaticon81-pin:before { content: "\f146"; }
.flaticon81-presentation:before { content: "\f147"; }
.flaticon81-pyramid:before { content: "\f148"; }
.flaticon81-sand-clock:before { content: "\f149"; }
.flaticon81-scales:before { content: "\f14a"; }
.flaticon81-search:before { content: "\f14b"; }
.flaticon81-search-1:before { content: "\f14c"; }
.flaticon81-search-2:before { content: "\f14d"; }
.flaticon81-search-3:before { content: "\f14e"; }
.flaticon81-search-4:before { content: "\f14f"; }
.flaticon81-shield:before { content: "\f150"; }
.flaticon81-shirt:before { content: "\f151"; }
.flaticon81-stats:before { content: "\f152"; }
.flaticon81-steering-wheel:before { content: "\f153"; }
.flaticon81-stopwatch:before { content: "\f154"; }
.flaticon81-store:before { content: "\f155"; }
.flaticon81-suitcase:before { content: "\f156"; }
.flaticon81-suitcase-1:before { content: "\f157"; }
.flaticon81-summary:before { content: "\f158"; }
.flaticon81-table:before { content: "\f159"; }
.flaticon81-target:before { content: "\f15a"; }
.flaticon81-tea:before { content: "\f15b"; }
.flaticon81-team:before { content: "\f15c"; }
.flaticon81-tie:before { content: "\f15d"; }
.flaticon81-tones:before { content: "\f15e"; }
.flaticon81-tribune:before { content: "\f15f"; }
.flaticon81-truck:before { content: "\f160"; }
.flaticon81-wallet:before { content: "\f161"; }
.flaticon81-watch:before { content: "\f162"; }
.flaticon81-workers:before { content: "\f163"; }


text:
/*
 * Created on Nov 24, 2005
 */
package uk.org.ponder.rsf.mappings;

import uk.org.ponder.rsf.components.UIComponent;
import uk.org.ponder.saxalizer.SAXAccessMethodSpec;
import uk.org.ponder.saxalizer.mapping.SAXalizerMapperEntry;
import uk.org.ponder.saxalizer.mapping.SAXalizerMapperInferrer;

public class ComponentMapperInferrer implements SAXalizerMapperInferrer {

  private SAXalizerMapperInferrer upchain;

  public void setChainedInferrer(SAXalizerMapperInferrer target) {
    upchain = target;
  }

  private SAXalizerMapperEntry filterComponentEntry(Class clazz, SAXalizerMapperEntry entry) {
    for (int i = entry.size() - 1; i >= 0; -- i) {
      SAXAccessMethodSpec spec = entry.specAt(i);
      if ("getFullID".equals(spec.getmethodname) ||
          "parent".equals(spec.fieldname))
        entry.remove(i);
      else if ("ID".equals(spec.fieldname)) {
        spec.xmlform = SAXAccessMethodSpec.XML_ATTRIBUTE;
        spec.xmlname = "id";
      }
    }
    return entry;
  }

  public SAXalizerMapperEntry inferEntry(Class clazz, SAXalizerMapperEntry entry) {
    SAXalizerMapperEntry togo = upchain.inferEntry(clazz, entry);
    if (UIComponent.class.isAssignableFrom(clazz)) {
      return filterComponentEntry(clazz, togo);
    }
    return togo;
  }

  public boolean isDefaultInferrible(Class clazz) {
    if (UIComponent.class.isAssignableFrom(clazz)) return true;
    else return upchain.isDefaultInferrible(clazz);
  }

  public void setDefaultInferrible(Class clazz) {
    upchain.setDefaultInferrible(clazz);
  }

}


text:
package org.knowm.xchange.globitex.dto.marketdata;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import java.io.Serializable;
import java.math.BigDecimal;

@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({
  "symbol",
  "ask",
  "bid",
  "last",
  "low",
  "high",
  "open",
  "volume",
  "volumeQuote",
  "timestamp"
})
public class GlobitexTicker implements Serializable {

  @JsonProperty("symbol")
  private final String symbol;

  @JsonProperty("ask")
  private final BigDecimal ask;

  @JsonProperty("bid")
  private final BigDecimal bid;

  @JsonProperty("last")
  private final BigDecimal last;

  @JsonProperty("low")
  private final BigDecimal low;

  @JsonProperty("high")
  private final BigDecimal high;

  @JsonProperty("open")
  private final BigDecimal open;

  @JsonProperty("volume")
  private final BigDecimal volume;

  @JsonProperty("volumeQuote")
  private final BigDecimal volumeQuote;

  @JsonProperty("timestamp")
  private final long timestamp;

  /**
   * @param timestamp
   * @param open
   * @param last
   * @param symbol
   * @param volume
   * @param high
   * @param low
   * @param ask
   * @param bid
   * @param volumeQuote
   */
  public GlobitexTicker(
      @JsonProperty("symbol") String symbol,
      @JsonProperty("ask") BigDecimal ask,
      @JsonProperty("bid") BigDecimal bid,
      @JsonProperty("last") BigDecimal last,
      @JsonProperty("low") BigDecimal low,
      @JsonProperty("high") BigDecimal high,
      @JsonProperty("open") BigDecimal open,
      @JsonProperty("volume") BigDecimal volume,
      @JsonProperty("volumeQuote") BigDecimal volumeQuote,
      @JsonProperty("timestamp") long timestamp) {
    super();
    this.symbol = symbol;
    this.ask = ask;
    this.bid = bid;
    this.last = last;
    this.low = low;
    this.high = high;
    this.open = open;
    this.volume = volume;
    this.volumeQuote = volumeQuote;
    this.timestamp = timestamp;
  }

  public String getSymbol() {
    return symbol;
  }

  public BigDecimal getAsk() {
    return ask;
  }

  public BigDecimal getBid() {
    return bid;
  }

  public BigDecimal getLast() {
    return last;
  }

  public BigDecimal getLow() {
    return low;
  }

  public BigDecimal getHigh() {
    return high;
  }

  public BigDecimal getOpen() {
    return open;
  }

  public BigDecimal getVolume() {
    return volume;
  }

  public BigDecimal getVolumeQuote() {
    return volumeQuote;
  }

  public long getTimestamp() {
    return timestamp;
  }

  @Override
  public String toString() {
    return "GlobitexTicker{"
        + "symbol='"
        + symbol
        + '\''
        + ", ask='"
        + ask
        + '\''
        + ", bid='"
        + bid
        + '\''
        + ", last='"
        + last
        + '\''
        + ", low='"
        + low
        + '\''
        + ", high='"
        + high
        + '\''
        + ", open='"
        + open
        + '\''
        + ", volume='"
        + volume
        + '\''
        + ", volumeQuote='"
        + volumeQuote
        + '\''
        + ", timestamp="
        + timestamp
        + '}';
  }
}


text:
#ifndef JACE_JARGUMENTS_H
#define JACE_JARGUMENTS_H

#include "jace/Namespace.h"
#include "jace/proxy/JValue.h"

#include <list>

BEGIN_NAMESPACE(jace)

/**
 * Represents the list of arguments for a java method.
 *
 * @author Toby Reyelts
 */
class JArguments
{
public:
	/**
	 * Constructs a new argument list.
	 */
	JArguments();

	/**
	 * Adds a new JValue to the argument list.
	 *
	 * The order that the arguments are added is significant. They must
	 * be in the same order as the parameter types for the method.
	 */
	JArguments& add(const ::jace::proxy::JValue& value);

	/**
	 * An overloaded operator for JArguments::add.
	 *
	 * This method is provided to make code more maintainable. For example,
	 *   JArguments arguments.add(arg1).add(arg2).add(arg3) ...
	 *
	 * can become,
	 *   JArguments arguments << arg1
	 *                        << arg2
	 *                        << arg3;
	 *
	 * This syntax is noticeably different in temporary constructions:
	 *
	 *   method.invoke(JArguments().add(arg1).add(arg2).add(arg3));
	 *
	 * versus
	 *
	 *   method.invoke(JArguments() << arg1 << arg2 << arg3);
	 */
	JArguments& operator<<(const ::jace::proxy::JValue& value);

	/**
	 * Returns this JArguments as a list of JValue*'s.
	 */
	std::list<const ::jace::proxy::JValue*> asList() const;

private:
	std::list<const ::jace::proxy::JValue*> mList;
};

END_NAMESPACE(jace)

#endif


text:
from setuptools import setup, find_packages

setup(
    name='django-massmedia',
    version = '0.1',
    description = 'Allows for site staff can upload and edit the media files through the site, and the filesystem is maintained in the background.',
    author='Populous',
    url='https://code.launchpad.net/~wnielson/django-massmedia/devel',
    packages=find_packages(),
    classifiers=[
        'Development Status :: 3 - Alpha',
        'Environment :: Web Environment',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: BSD License',
        'Operating System :: OS Independent',
        'Programming Language :: Python',
        'Framework :: Django',
    ],
    include_package_data=True,
    zip_safe=False,
    install_requires=['setuptools', 'setuptools_bzr'],
)


text:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.RecyclerView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/list"
    android:name="com.ichangmao.app.ui.MainFragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_marginLeft="16dp"
    android:layout_marginRight="16dp"
    app:layoutManager="LinearLayoutManager"
    tools:context="com.ichangmao.app.ui.MainFragment"
    tools:listitem="@layout/item_func" />


text:
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });

const core_1 = require("@angular-devkit/core");
const schematics_1 = require("@angular-devkit/schematics");
const ts = require("../third_party/github.com/Microsoft/TypeScript/lib/typescript");
const ast_utils_1 = require("../utility/ast-utils");
const change_1 = require("../utility/change");
const find_module_1 = require("../utility/find-module");
const lint_fix_1 = require("../utility/lint-fix");
const parse_name_1 = require("../utility/parse-name");
const validation_1 = require("../utility/validation");
const workspace_1 = require("../utility/workspace");
function addDeclarationToNgModule(options) {
    return (host) => {
        if (options.skipImport || !options.module) {
            return host;
        }
        const modulePath = options.module;
        const text = host.read(modulePath);
        if (text === null) {
            throw new schematics_1.SchematicsException(`File ${modulePath} does not exist.`);
        }
        const sourceText = text.toString('utf-8');
        const source = ts.createSourceFile(modulePath, sourceText, ts.ScriptTarget.Latest, true);
        const directivePath = `/${options.path}/`
            + (options.flat ? '' : core_1.strings.dasherize(options.name) + '/')
            + core_1.strings.dasherize(options.name)
            + '.directive';
        const relativePath = find_module_1.buildRelativePath(modulePath, directivePath);
        const classifiedName = core_1.strings.classify(`${options.name}Directive`);
        const declarationChanges = ast_utils_1.addDeclarationToModule(source, modulePath, classifiedName, relativePath);
        const declarationRecorder = host.beginUpdate(modulePath);
        for (const change of declarationChanges) {
            if (change instanceof change_1.InsertChange) {
                declarationRecorder.insertLeft(change.pos, change.toAdd);
            }
        }
        host.commitUpdate(declarationRecorder);
        if (options.export) {
            // Need to refresh the AST because we overwrote the file in the host.
            const text = host.read(modulePath);
            if (text === null) {
                throw new schematics_1.SchematicsException(`File ${modulePath} does not exist.`);
            }
            const sourceText = text.toString('utf-8');
            const source = ts.createSourceFile(modulePath, sourceText, ts.ScriptTarget.Latest, true);
            const exportRecorder = host.beginUpdate(modulePath);
            const exportChanges = ast_utils_1.addExportToModule(source, modulePath, core_1.strings.classify(`${options.name}Directive`), relativePath);
            for (const change of exportChanges) {
                if (change instanceof change_1.InsertChange) {
                    exportRecorder.insertLeft(change.pos, change.toAdd);
                }
            }
            host.commitUpdate(exportRecorder);
        }
        return host;
    };
}
function buildSelector(options, projectPrefix) {
    let selector = options.name;
    if (options.prefix) {
        selector = `${options.prefix}-${selector}`;
    }
    else if (options.prefix === undefined && projectPrefix) {
        selector = `${projectPrefix}-${selector}`;
    }
    return core_1.strings.camelize(selector);
}
function default_1(options) {
    return async (host) => {
        const workspace = await workspace_1.getWorkspace(host);
        const project = workspace.projects.get(options.project);
        if (!project) {
            throw new schematics_1.SchematicsException(`Invalid project name (${options.project})`);
        }
        if (options.path === undefined) {
            options.path = workspace_1.buildDefaultPath(project);
        }
        options.module = find_module_1.findModuleFromOptions(host, options);
        const parsedPath = parse_name_1.parseName(options.path, options.name);
        options.name = parsedPath.name;
        options.path = parsedPath.path;
        options.selector = options.selector || buildSelector(options, project.prefix || '');
        validation_1.validateHtmlSelector(options.selector);
        // todo remove these when we remove the deprecations
        options.skipTests = options.skipTests || !options.spec;
        const templateSource = schematics_1.apply(schematics_1.url('./files'), [
            options.skipTests ? schematics_1.filter(path => !path.endsWith('.spec.ts.template')) : schematics_1.noop(),
            schematics_1.applyTemplates({
                ...core_1.strings,
                'if-flat': (s) => options.flat ? '' : s,
                ...options,
            }),
            schematics_1.move(parsedPath.path),
        ]);
        return schematics_1.chain([
            addDeclarationToNgModule(options),
            schematics_1.mergeWith(templateSource),
            options.lintFix ? lint_fix_1.applyLintFix(options.path) : schematics_1.noop(),
        ]);
    };
}
exports.default = default_1;


text:
<?php

defined('_JEXEC') or die('Restricted access');

class mod_ariquizuserresultInstallerScript
{
	function preflight($type, $parent)
	{
		$type = strtolower($type);
		if ($type == 'install' || $type == 'update')
			$this->updateManifest($parent);
	}

	function postflight($type, $parent)
	{
		$type = strtolower($type);
		if ($type == 'install' || $type == 'update')
			$this->deleteHelpManifest($parent);
	}

	private function updateManifest($parent)
	{
		jimport('joomla.filesystem.file');

		$installer = $parent->getParent();
		$manifestFile = basename($installer->getPath('manifest'));
		$cleanManifestFile = preg_replace('/^\_+/i', '', $manifestFile);

		$dir = dirname(__FILE__) . '/install/';

		JFile::delete($dir . $cleanManifestFile);
		JFile::copy($dir . '../' . $cleanManifestFile, $dir . $cleanManifestFile);
	}

	private function deleteHelpManifest($parent)
	{
		jimport('joomla.filesystem.file');

		$installer = $parent->getParent();
		$manifestFile = basename($installer->getPath('manifest'));

		JFile::delete(JPATH_ROOT . '/modules/mod_ariquizuserresult/' . $manifestFile);
	}
}


text:
@interface MagicManager : NSObject
{
	int magicsState[magicsNum+1];
	int magicMana, lastCastedMagic;
	CXMLDocument* XMLDoc;
}

@property (nonatomic, assign, readwrite) int magicMana;
@property (nonatomic, assign, readwrite) int lastCastedMagic;

+(MagicManager*) sharedManager;
-(void) saveLearnedMagics;
-(void) loadLearnedMagics;

@end