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

class Inventory extends CI_Controller {

	/**
	 * This controller facilitates the registration, updates, deletion
	 * and the overall statistic involved  from both Inventory & Stock Control
	 */

	#loads the primary dashboard each instance its Inventory is Loaded
	public function index()
	{
		$this->products_overview();
	}

	##>>> Inventory functionality

	public function products_overview()
	{
		$this->load->view('inventory/base/head');
		$this->load->view('inventory/base/side_menu');
		$this->load->view('inventory/base/top_nav');
		$this->load->view('inventory/stats/overview_stats');
		$this->load->view('inventory/products_overview');
		$this->load->view('inventory/base/footer');
		$this->load->view('inventory/base/scripts');
	}
	public function new_egory()
	{
		$this->load->view('inventory/base/head');
		$this->load->view('inventory/base/side_menu');
		$this->load->view('inventory/base/top_nav');
		$this->load->view('inventory/stats/category_stats');
		$this->load->view('inventory/category');
		$this->load->view('inventory/base/footer');
		$this->load->view('inventory/base/scripts');
	}
	public function new_product()
	{
		$this->load->view('inventory/base/head');
		$this->load->view('inventory/base/side_menu');
		$this->load->view('inventory/base/top_nav');
		$this->load->view('inventory/stats/product_stats');
		$this->load->view('inventory/new_product');
		$this->load->view('inventory/base/footer');
		$this->load->view('inventory/base/scripts');
	}

	public function product_list()
	{
		$this->load->view('inventory/base/head');
		$this->load->view('inventory/base/side_menu');
		$this->load->view('inventory/base/top_nav');
		$this->load->view('inventory/product_list');
		$this->load->view('inventory/base/footer');
		$this->load->view('inventory/base/scripts');
	}

	public function new_tool()
	{
		$this->load->view('inventory/base/head');
		$this->load->view('inventory/base/side_menu');
		$this->load->view('inventory/base/top_nav');
		$this->load->view('inventory/stats/tools_stats');
		$this->load->view('inventory/new_tool');
		$this->load->view('inventory/base/footer');
		$this->load->view('inventory/base/scripts');
	}

	public function tool_list()
	{
		$this->load->view('inventory/base/head');
		$this->load->view('inventory/base/side_menu');
		$this->load->view('inventory/base/top_nav');
		$this->load->view('inventory/tool_list');
		$this->load->view('inventory/base/footer');
		$this->load->view('inventory/base/scripts');
	}

	##>>> Stock functionality
	public function stock_overview()
	{
		$this->load->view('inventory/base/head');
		$this->load->view('inventory/base/side_menu');
		$this->load->view('inventory/base/top_nav');
		$this->load->view('inventory/stats/overview_stats');
		$this->load->view('inventory/stock_overview');
		$this->load->view('inventory/base/footer');
		$this->load->view('inventory/base/scripts');
	}

	public function new_stock()
	{
		$this->load->view('inventory/base/head');
		$this->load->view('inventory/base/side_menu');
		$this->load->view('inventory/base/top_nav');
		$this->load->view('inventory/stats/stock_stats');
		$this->load->view('inventory/new_stock');
		$this->load->view('inventory/base/footer');
		$this->load->view('inventory/base/scripts');
	}

	public function stock_list()
	{
		$this->load->view('inventory/base/head');
		$this->load->view('inventory/base/side_menu');
		$this->load->view('inventory/base/top_nav');
		$this->load->view('inventory/stock_list');
		$this->load->view('inventory/base/footer');
		$this->load->view('inventory/base/scripts');
	}
}


text:
using System.IO;

using Microsoft.VisualStudio.TestTools.UnitTesting;

using AM.IO;

using JetBrains.Annotations;

using Moq;

namespace UnitTests.AM.IO
{
    [TestClass]
    public class BinaryReaderUtilityTest
    {
    }
}

redpajama_set_name: RedPajamaGithub


text:
namespace vlp {
	ResourceLoader::ResourceLoader() {
		m_textureParsers["dds"] = new DDSParser();
	}

	ResourceLoader::~ResourceLoader() {
		for (auto& parser : m_textureParsers) {
			delete parser.second;
		}
	}

	const TextureResource ResourceLoader::loadDDS(const std::vector<uint8_t>& data) {
		return m_textureParsers["dds"]->parse(data);
	}

	std::vector<uint8_t> ResourceLoader::readFile(const std::string& path) {
		std::ifstream file(path, std::ios::binary);
		if (!file) {
			logger.log("Unable to open file '%s'", path.c_str());
			return std::vector<uint8_t>();
		}

		std::vector<uint8_t> data;
		const size_t chunkSize = 4096;
		uint8_t buffer[chunkSize];

		while (!file.eof()) {
			file.read(reinterpret_cast<char*>(buffer), chunkSize);

			auto bytesRead = file.gcount();
			if (bytesRead < chunkSize) {
				data.insert(data.end(), buffer, buffer + bytesRead);
				break;
			}

			data.insert(data.end(), buffer, buffer + chunkSize);
		}
		file.close();

		return data;
	}
}


text:
<?php $this->load->view('auth/auth_header');?>

<?php $this->load->view($content_view);?>

<?php $this->load->view('auth/auth_footer');?>


text:
package net.myrrix.online.eval;

import java.io.Serializable;

import com.google.common.base.Preconditions;

final class IRStatisticsImpl implements MyrrixIRStatistics, EvaluationResult, Serializable {

  private final double precision;
  private final double recall;
  private final double nDCG;
  private final double meanAveragePrecision;

  IRStatisticsImpl(double precision, double recall, double nDCG, double meanAveragePrecision) {
    Preconditions.checkArgument(precision >= 0.0 && precision <= 1.0, "Illegal precision: %s", precision);
    Preconditions.checkArgument(recall >= 0.0 && recall <= 1.0, "Illegal recall: %s", recall);
    Preconditions.checkArgument(nDCG >= 0.0 && nDCG <= 1.0, "Illegal nDCG: %s", nDCG);
    Preconditions.checkArgument(meanAveragePrecision >= 0.0 && meanAveragePrecision <= 1.0,
                                "Illegal meanAveragePrecision: %s", meanAveragePrecision);
    this.precision = precision;
    this.recall = recall;
    this.nDCG = nDCG;
    this.meanAveragePrecision = meanAveragePrecision;
  }

  /**
   * @return {@link #getMeanAveragePrecision()}
   */
  @Override
  public double getScore() {
    return getMeanAveragePrecision();
  }

  @Override
  public double getPrecision() {
    return precision;
  }

  @Override
  public double getRecall() {
    return recall;
  }

  /**
   * @throws UnsupportedOperationException
   */
  @Override
  public double getFallOut() {
    throw new UnsupportedOperationException();
  }

  @Override
  public double getF1Measure() {
    return getFNMeasure(1.0);
  }

  @Override
  public double getFNMeasure(double b) {
    double b2 = b * b;
    double sum = b2 * precision + recall;
    return sum == 0.0 ? Double.NaN : (1.0 + b2) * precision * recall / sum;
  }

  @Override
  public double getNormalizedDiscountedCumulativeGain() {
    return nDCG;
  }

  @Override
  public double getMeanAveragePrecision() {
    return meanAveragePrecision;
  }

  /**
   * @throws UnsupportedOperationException
   */
  @Override
  public double getReach() {
    throw new UnsupportedOperationException();
  }

  @Override
  public String toString() {
    return "Precision: " + precision + "; Recall: " + recall + "; nDCG: " + nDCG + "; MAP: " + meanAveragePrecision;
  }

}


text:
package org.apache.jackrabbit.jcr2spi.state;

import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.Set;

import javax.jcr.InvalidItemStateException;
import javax.jcr.ItemExistsException;
import javax.jcr.RepositoryException;
import javax.jcr.nodetype.ConstraintViolationException;

import org.apache.commons.collections.iterators.IteratorChain;
import org.apache.jackrabbit.jcr2spi.hierarchy.HierarchyEntry;
import org.apache.jackrabbit.jcr2spi.hierarchy.NodeEntry;
import org.apache.jackrabbit.jcr2spi.hierarchy.PropertyEntry;
import org.apache.jackrabbit.jcr2spi.operation.Operation;
import org.apache.jackrabbit.spi.Name;
import org.apache.jackrabbit.spi.QNodeDefinition;
import org.apache.jackrabbit.spi.QPropertyDefinition;
import org.apache.jackrabbit.spi.QValue;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * TransientItemStateManager adds support for transient changes on
 * {@link ItemState}s and also provides methods to create new item states.
 * While all other modifications can be invoked on the item state instances itself,
 * creating a new node state is done using
 * {@link #createNewNodeState(Name, String, Name, QNodeDefinition, NodeState)}
 * and
 * {@link #createNewPropertyState(Name, NodeState, QPropertyDefinition, QValue[], int)}.
 */
public class TransientItemStateManager implements ItemStateCreationListener {

    /**
     * Logger instance for this class.
     */
    private static final Logger log = LoggerFactory.getLogger(TransientItemStateManager.class);

    /**
     * Added states
     */
    private final Set<ItemState> addedStates = new LinkedHashSet<ItemState>();

    /**
     * Modified states
     */
    private final Set<ItemState> modifiedStates = new LinkedHashSet<ItemState>();

    /**
     * Removed states
     */
    private final Set<ItemState> removedStates = new LinkedHashSet<ItemState>();
    /**
     * Stale states
     */
    private final Set<ItemState> staleStates = new LinkedHashSet<ItemState>();

    /**
     * Set of operations
     */
    private final Set<Operation> operations = new LinkedHashSet<Operation>();

    /**
     *
     */
    TransientItemStateManager() {
    }

    /**
     * @return the operations that have been recorded until now.
     */
    Iterator<Operation> getOperations() {
        return operations.iterator();
    }

    /**
     * Add the given operation to the list of operations to be recorded within
     * this TransientItemStateManager.
     *
     * @param operation
     */
    void addOperation(Operation operation) {
        operations.add(operation);
    }

    /**
     * @return true if this transient ISM has pending changes.
     */
    boolean hasPendingChanges() {
        return !operations.isEmpty();
    }

    /**
     * Create the change log for the tree starting at target. This
     * includes a  check if the ChangeLog to be created is totally 'self-contained'
     * and independent; items within the scope of this update operation (i.e.
     * below the target) must not have dependencies outside of this tree (e.g.
     * moving a node requires that the target node including both old and new
     * parents are saved).
     *
     * @param target
     * @param throwOnStale Throws InvalidItemStateException if either the given
     * ItemState or any of its descendants is stale and the flag is true.
     * @return
     * @throws InvalidItemStateException if a stale ItemState is
     * encountered while traversing the state hierarchy. The changeLog
     * might have been populated with some transient item states. A client should
     * therefore not reuse the changeLog if such an exception is thrown.
     * @throws RepositoryException if state is a new item state.
     */
    ChangeLog getChangeLog(ItemState target, boolean throwOnStale) throws InvalidItemStateException, ConstraintViolationException, RepositoryException {
        // fail-fast test: check status of this item's state
        if (target.getStatus() == Status.NEW) {
            String msg = "Cannot save/revert an item with status NEW (" +target+ ").";
            log.debug(msg);
            throw new RepositoryException(msg);
        }
        if (throwOnStale && Status.isStale(target.getStatus())) {
            String msg =  "Attempt to save/revert an item, that has been externally modified (" +target+ ").";
            log.debug(msg);
            throw new InvalidItemStateException(msg);
        }

        Set<Operation> ops = new LinkedHashSet<Operation>();
        Set<ItemState> affectedStates = new LinkedHashSet<ItemState>();

        HierarchyEntry he = target.getHierarchyEntry();
        if (he.getParent() == null) {
            // the root entry -> the complete change log can be used for
            // simplicity. collecting ops, states can be omitted.
            if (throwOnStale && !staleStates.isEmpty()) {
                String msg = "Cannot save changes: States has been modified externally.";
                log.debug(msg);
                throw new InvalidItemStateException(msg);
            } else {
                affectedStates.addAll(staleStates);
            }
            ops.addAll(operations);
            affectedStates.addAll(addedStates);
            affectedStates.addAll(modifiedStates);
            affectedStates.addAll(removedStates);
        } else {
            // not root entry:
            // - check if there is a stale state in the scope (save only)
            if (throwOnStale) {
                for (ItemState state : staleStates) {
                    if (containedInTree(target, state)) {
                        String msg = "Cannot save changes: States has been modified externally.";
                        log.debug(msg);
                        throw new InvalidItemStateException(msg);
                    }
                }
            }
            // - collect all affected states within the scope of save/undo
            Iterator[] its = new Iterator[] {
                    addedStates.iterator(),
                    removedStates.iterator(),
                    modifiedStates.iterator()
            };
            IteratorChain chain = new IteratorChain(its);
            if (!throwOnStale) {
                chain.addIterator(staleStates.iterator());
            }
            while (chain.hasNext()) {
                ItemState state = (ItemState) chain.next();
                if (containedInTree(target, state)) {
                    affectedStates.add(state);
                }
            }
            // - collect the set of operations and
            //   check if the affected states listed by the operations are all
            //   listed in the modified,removed or added states collected by this
            //   changelog.
            for (Operation op : operations) {
                Collection<ItemState> opStates = op.getAffectedItemStates();
                for (ItemState state : opStates) {
                    if (affectedStates.contains(state)) {
                        // operation needs to be included
                        if (!affectedStates.containsAll(opStates)) {
                            // incomplete changelog: need to save a parent as well
                            String msg = "ChangeLog is not self contained.";
                            throw new ConstraintViolationException(msg);
                        }
                        // no violation: add operation an stop iteration over
                        // all affected states present in the operation.
                        ops.add(op);
                        break;
                    }
                }
            }
        }

        ChangeLog cl = new ChangeLog(target, ops, affectedStates);
        return cl;
    }

    /**
     * Creates a new transient {@link NodeState} that does not overlay any other
     * {@link NodeState}.
     *
     * @param nodeName     the name of the NodeState to create.
     * @param uniqueID     the uniqueID of the NodeState to create or
     *                     null if the created NodeState
     *                     cannot be identified by a unique ID.
     * @param nodeTypeName name of the node type of the new node state.
     * @param definition   The definition for the new node state.
     * @param parent       the parent of the new node state.
     * @return a new transient {@link NodeState}.
     */
    NodeState createNewNodeState(Name nodeName, String uniqueID, Name nodeTypeName,
                                 QNodeDefinition definition, NodeState parent)
            throws RepositoryException {
        NodeEntry ne = ((NodeEntry) parent.getHierarchyEntry()).addNewNodeEntry(nodeName, uniqueID, nodeTypeName, definition);
        try {
            parent.markModified();
        } catch (RepositoryException e) {
            ne.remove();
            throw e;
        }
        return ne.getNodeState();
    }

    /**
     * Creates a new transient property state for a given parent
     * node state.
     *
     * @param propName the name of the property state to create.
     * @param parent   the node state where to the new property is added.
     * @param definition
     * @return the created property state.
     * @throws ItemExistsException if parent already has a property
     * with the given name.
     * @throws ConstraintViolationException
     * @throws RepositoryException
     */
    PropertyState createNewPropertyState(Name propName, NodeState parent,
                                         QPropertyDefinition definition,
                                         QValue[] values, int propertyType)
            throws ItemExistsException, ConstraintViolationException, RepositoryException {
        // NOTE: callers must make sure, the property type is not 'undefined'
        NodeEntry nodeEntry = (NodeEntry) parent.getHierarchyEntry();
        PropertyEntry pe = nodeEntry.addNewPropertyEntry(propName, definition, values, propertyType);
        try {
            parent.markModified();
        } catch (RepositoryException e) {
            pe.remove();
            throw e;
        }
        return pe.getPropertyState();
    }

    /**
     * Disposes this transient item state manager. Clears all references to
     * transiently modified item states.
     */
    void dispose() {
        addedStates.clear();
        modifiedStates.clear();
        removedStates.clear();
        staleStates.clear();
        // also clear all operations
        operations.clear();
    }

    /**
     * Remove the states and operations listed in the changeLog from internal
     * list of modifications.
     *
     * @param subChangeLog
     */
    void dispose(ChangeLog subChangeLog) {
        Set<ItemState> affectedStates = subChangeLog.getAffectedStates();
        addedStates.removeAll(affectedStates);
        modifiedStates.removeAll(affectedStates);
        removedStates.removeAll(affectedStates);
        staleStates.removeAll(affectedStates);

        operations.removeAll(subChangeLog.getOperations());
    }

    /**
     * A state has been removed. If the state is not a new state
     * (not in the collection of added ones), then remove
     * it from the modified states collection and add it to the
     * removed states collection.
     *
     * @param state state that has been removed
     */
    private void removed(ItemState state) {
        if (!addedStates.remove(state)) {
            modifiedStates.remove(state);
        }
        removedStates.add(state);
    }

    /**
     *
     * @param parent
     * @param state
     * @return
     */
    private static boolean containedInTree(ItemState parent, ItemState state) {
        HierarchyEntry he = state.getHierarchyEntry();
        HierarchyEntry pHe = parent.getHierarchyEntry();
        // short cuts first
        if (he == pHe || he.getParent() == pHe) {
            return true;
        }
        if (!parent.isNode() || he == pHe.getParent()) {
            return false;
        }
        // none of the simple cases: walk up hierarchy
        HierarchyEntry pe = he.getParent();
        while (pe != null) {
            if (pe == pHe) {
                return true;
            }
            pe = pe.getParent();
        }

        // state isn't descendant of 'parent'
        return false;
    }

    //-----------------------------------------< ItemStateLifeCycleListener >---
    /**
     * Depending on status of the given state adapt change log.
     * E.g. a revert on states will reset the status from 'existing modified' to
     * 'existing'. A state which changes from 'existing' to 'existing modified'
     * will go into the modified set of the change log, etc.
     *
     * @see ItemStateLifeCycleListener#statusChanged(ItemState, int)
     */
    public void statusChanged(ItemState state, int previousStatus) {
        /*
        Update the collections of states that were transiently modified.
        NOTE: cleanup of operations is omitted here. this is expected to
        occur upon {@link ChangeLog#save()} and {@link ChangeLog#undo()}.
        External modifications in contrast that clash with transient modifications
        render the corresponding states stale.
        */
        switch (state.getStatus()) {
            case (Status.EXISTING):
                switch (previousStatus) {
                    case Status.EXISTING_MODIFIED:
                        // was modified and got persisted or reverted
                        modifiedStates.remove(state);
                        break;
                    case Status.EXISTING_REMOVED:
                        // was transiently removed and is now reverted
                        removedStates.remove(state);
                        break;
                    case Status.STALE_MODIFIED:
                        // was modified and stale and is now reverted
                        staleStates.remove(state);
                        break;
                    case Status.NEW:
                        // was new and has been saved now
                        addedStates.remove(state);
                        break;
                    //default:
                        // INVALIDATED, MODIFIED ignore. no effect to transient modifications.
                        // any other status change is invalid -> see Status#isValidStatusChange(int, int
                }
                break;
            case Status.EXISTING_MODIFIED:
                // transition from EXISTING to EXISTING_MODIFIED
                modifiedStates.add(state);
                break;
            case (Status.EXISTING_REMOVED):
                // transition from EXISTING or EXISTING_MODIFIED to EXISTING_REMOVED
                removed(state);
                break;
            case (Status.REMOVED):
                switch (previousStatus) {
                    case Status.EXISTING_REMOVED:
                        // was transiently removed and removal was persisted.
                        // -> ignore
                        break;
                    case Status.NEW:
                        // a new entry was removed again: remember as removed
                        // in order to keep the operations and the affected
                        // states in sync
                        removed(state);
                        break;
                }
                // in any case: stop listening to status changes
                state.removeListener(this);
                break;
            case Status.STALE_DESTROYED:
            case Status.STALE_MODIFIED:
                /**
                 state is stale due to external modification -> move it to
                 the collection of stale item states.
                 validation omitted for only 'existing_modified' states can
                 become stale see {@link Status#isValidStatusChange(int, int)}
                 */
                modifiedStates.remove(state);
                staleStates.add(state);
                break;
            case Status.MODIFIED:
            case Status.INVALIDATED:
                // MODIFIED, INVALIDATED: ignore.
                log.debug("Item " + state.getName() + " changed status from " + Status.getName(previousStatus) + " to " + Status.getName(state.getStatus()) + ".");
                break;
            default:
                log.error("ItemState "+ state.getName() + " has invalid status: " + state.getStatus());
        }
    }

    //-----------------------------------------< ItemStateCreationListener >---
    /**
     * @see ItemStateCreationListener#created(ItemState)
     */
    public void created(ItemState state) {
        // new state has been created
        if (state.getStatus() == Status.NEW) {
            addedStates.add(state);
        }
    }
}


text:
<?php

namespace Concrete\Core\File\Import;

use Concrete\Core\Application\Application;
use Concrete\Core\Entity\File\Version as FileVersionEntity;
use Concrete\Core\File\File;
use Concrete\Core\File\Incoming;
use Concrete\Core\File\Service\Application as ApplicationFileService;
use Concrete\Core\File\Service\VolatileDirectory;
use Concrete\Core\Logging\Channels;
use Concrete\Core\Logging\LoggerFactory;
use Exception;
use League\Flysystem\Adapter\AbstractAdapter;
use League\Flysystem\AdapterInterface;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Throwable;

/**
 * A class to be used to import files into the application file manager.
 */
class FileImporter
{
    /**
     * The container instance to be used to build dependencies.
     *
     * @var \Concrete\Core\Application\Application
     */
    protected $app;

    /**
     * @var \Concrete\Core\File\Import\ProcessorManager
     */
    private $processorManager;

    /**
     * @var \Concrete\Core\File\Service\Application
     */
    private $applicationFileService;

    /**
     * @var \Concrete\Core\File\Incoming
     */
    private $incoming;

    /**
     * Initialize the instance.
     *
     * @param \Concrete\Core\Application\Application $app
     * @param \Concrete\Core\File\Import\ProcessorManager $processorManager
     * @param \Concrete\Core\File\Service\Application $applicationFileService
     * @param Incoming $incoming
     */
    public function __construct(Application $app, ProcessorManager $processorManager, ApplicationFileService $applicationFileService, Incoming $incoming)
    {
        $this->app = $app;
        $this->processorManager = $processorManager;
        $this->applicationFileService = $applicationFileService;
        $this->incoming = $incoming;
    }

    /**
     * Get the processor list manager.
     *
     * @return \Concrete\Core\File\Import\ProcessorManager
     */
    public function getProcessorManager()
    {
        return $this->processorManager;
    }

    /**
     * Import a local file into the application file manager.
     *
     * @param string $localFilename The path to the file
     * @param string $concreteFilename A custom name to give to the file (if empty we'll derive it from $localFilename)
     * @param \Concrete\Core\File\Import\ImportOptions|null $options the options to be used to import the file
     *
     * @throws \Concrete\Core\File\Import\ImportException
     *
     * @return \Concrete\Core\Entity\File\Version
     */
    public function importLocalFile($localFilename, $concreteFilename = '', ImportOptions $options = null)
    {
        if ($options === null) {
            $options = $this->app->make(ImportOptions::class);
        }
        if ($options->canChangeLocalFile() === false && is_file($localFilename)) {
            $vd = $this->app->make(VolatileDirectory::class);
            $tempFilename = $vd->getPath() . '/file';
            copy($localFilename, $tempFilename);
            if (!$concreteFilename) {
                $concreteFilename = $localFilename;
            }
            $localFilename = $tempFilename;
        }
        $importingFile = $this->app->make(ImportingFile::class, ['localFilename' => $localFilename, 'concreteFilename' => $concreteFilename]);

        return $this->import($importingFile, $options);
    }

    /**
     * Import a file from the incoming directory into the application file manager.
     *
     * @param string $incomingFilename The path to the file
     * @param string $concreteFilename A custom name to give to the file (if empty we'll derive it from $incomingFilename)
     * @param \Concrete\Core\File\Import\ImportOptions|null $options the options to be used to import the file
     *
     * @throws \Concrete\Core\File\Import\ImportException
     *
     * @return \Concrete\Core\Entity\File\Version
     */
    public function importFromIncoming($incomingFilename, $concreteFilename = '', ImportOptions $options = null)
    {
        $localFilename = $this->resolveIncomingFilename($incomingFilename, $copiedLocally, $volatileDirectory);
        if ($copiedLocally) {
            $options = $options ? clone $options : $this->app->make(ImportOptions::class);
            $options->setCanChangeLocalFile(true);
        }

        return $this->importLocalFile($localFilename, $concreteFilename ?: $incomingFilename, $options);
    }

    /**
     * Import a file received via a POST request into the application file manager.
     *
     * @param \Symfony\Component\HttpFoundation\File\UploadedFile $uploadedFile The uploaded file
     * @param string $concreteFilename A custom name to give to the file (if empty we'll derive it from $uploadedFile)
     * @param \Concrete\Core\File\Import\ImportOptions|null $options the options to be used to import the file
     *
     * @throws \Concrete\Core\File\Import\ImportException
     *
     * @return \Concrete\Core\Entity\File\Version
     *
     * @example
     *

     * $app = \Concrete\Core\Support\Facade\Application::getFacadeApplication();
     * $request = $app->make(\Concrete\Core\Http\Request::class);
     * $importer = $app->make(\Concrete\Core\File\Import\FileImporter::class);
     * try {
     *     $fv = $importer->importUploadedFile($request->files->get('field_name'));
     * } catch (\Concrete\Core\File\Import\ImportException $x) {
     *     // Manage the import exception
     * }
     *

     */
    public function importUploadedFile(UploadedFile $uploadedFile = null, $concreteFilename = '', ImportOptions $options = null)
    {
        if ($uploadedFile === null) {
            throw ImportException::fromErrorCode(ImportException::E_PHP_NO_FILE);
        }
        if (!$uploadedFile->isValid()) {
            throw ImportException::fromErrorCode($uploadedFile->getError());
        }
        $options = $options ? clone $options : $this->app->make(ImportOptions::class);
        $options->setCanChangeLocalFile(true);

        return $this->importLocalFile($uploadedFile->getPathname(), $concreteFilename ?: $uploadedFile->getClientOriginalName(), $options);
    }

    /**
     * Generate a file prefix.
     *
     * @return string
     */
    public function generatePrefix()
    {
        $prefix = mt_rand(10, 99) . time();

        return $prefix;
    }

    /**
     * Import a file into the application file manager.
     *
     * @param \Concrete\Core\File\Import\ImportingFile $importingFile the file being imported
     * @param \Concrete\Core\File\Import\ImportOptions $options the options to be used to import the file
     *
     * @throws \Concrete\Core\File\Import\ImportException
     *
     * @return \Concrete\Core\Entity\File\Version
     */
    protected function import(ImportingFile $importingFile, ImportOptions $options)
    {
        $this->applyValidators($importingFile, $options);
        $this->applyPreProcessors($importingFile, $options);
        $importingFile->releaseImage();
        $fileVersion = $this->save($importingFile, $options);
        $this->applyPostProcessors($importingFile, $options, $fileVersion);
        $fileVersion->releaseImagineImage();

        /** @var LoggerFactory $loggerFactory */
        $loggerFactory = $this->app->make(LoggerFactory::class);
        $logger = $loggerFactory->createLogger(Channels::CHANNEL_FILES);

        try {
            $logger->notice(t("File %s successfully imported.", $fileVersion->getFileName()));
        } catch (Exception $err) {
            // Skip any errors while logging to pass the automated tests
        }

        return $fileVersion;
    }

    /**
     * Apply the validators to the file being imported.
     *
     * @param \Concrete\Core\File\Import\ImportingFile $importingFile
     * @param \Concrete\Core\File\Import\ImportOptions $options
     *
     * @throws \Concrete\Core\File\Import\ImportException
     */
    protected function applyValidators(ImportingFile $importingFile, ImportOptions $options)
    {
        foreach ($this->getProcessorManager()->getValidators() as $validator) {
            if ($validator->shouldValidate($importingFile, $options)) {
                $validator->validate($importingFile, $options);
            }
        }
    }

    /**
     * Apply the pre-processors to the file being imported.
     *
     * @param \Concrete\Core\File\Import\ImportingFile $importingFile
     * @param \Concrete\Core\File\Import\ImportOptions $options
     */
    protected function applyPreProcessors(ImportingFile $importingFile, ImportOptions $options)
    {
        foreach ($this->getProcessorManager()->getPreProcessors() as $preProcessor) {
            if ($preProcessor->shouldPreProcess($importingFile, $options)) {
                $preProcessor->preProcess($importingFile, $options);
            }
        }
    }

    /**
     * Actually import a file into the application file manager.
     *
     * @param \Concrete\Core\File\Import\ImportingFile $importingFile the file being imported
     * @param \Concrete\Core\File\Import\ImportOptions $options the options to be used to import the file
     *
     * @throws \Concrete\Core\File\Import\ImportException
     *
     * @return \Concrete\Core\Entity\File\Version
     */
    protected function save(ImportingFile $importingFile, ImportOptions $options)
    {
        $prefix = $options->getCustomPrefix();
        if ($prefix === '') {
            $prefixIsAutoGenerated = true;
            $prefix = $this->generatePrefix();
        } else {
            $prefixIsAutoGenerated = false;
        }
        $storageLocation = $options->getStorageLocation();
        $filesystem = $storageLocation->getFileSystemObject();

        $src = @fopen($importingFile->getLocalFilename(), 'rb');
        if ($src === false) {
            throw ImportException::fromErrorCode(ImportException::E_FILE_INVALID);
        }
        try {
            $filesystem->writeStream(
                $this->applicationFileService->prefix($prefix, $importingFile->getConcreteFilenameSanitized()),
                $src,
                [
                    'visibility' => AdapterInterface::VISIBILITY_PUBLIC,
                    'mimetype' => $importingFile->getMimeType(),
                ]
            );
            $writeError = null;
        } catch (Exception $e) {
            $writeError = $e;
        } catch (Throwable $e) {
            $writeError = $e;
        }
        @fclose($src);
        if ($writeError !== null) {
            throw ImportException::fromErrorCode($prefixIsAutoGenerated ? ImportException::E_FILE_UNABLE_TO_STORE : ImportException::E_FILE_UNABLE_TO_STORE_PREFIX_PROVIDED, $writeError);
        }

        $file = $options->getAddNewVersionTo();
        if ($file !== null) {
            // We get a new version to modify
            $fileVersion = $file->getVersionToModify(true);
            $fileVersion->updateFile(
                $importingFile->getConcreteFilenameSanitized(),
                $prefix
            );
        } else {
            // We create a new File instance
            $fileVersion = File::add(
                $importingFile->getConcreteFilenameSanitized(),
                $prefix,
                ['fvTitle' => $importingFile->getConcreteFilename()],
                $storageLocation,
                $options->getImportToFolder()
            );
        }
        $fileVersion->refreshAttributes(false);

        return $fileVersion;
    }

    /**
     * Apply the post-processors to the imported file.
     *
     * @param \Concrete\Core\File\Import\ImportingFile $importingFile
     * @param \Concrete\Core\File\Import\ImportOptions $options
     * @param \Concrete\Core\Entity\File\Version $fileVersion
     *
     * @throws \Concrete\Core\File\Import\ImportException
     */
    protected function applyPostProcessors(ImportingFile $importingFile, ImportOptions $options, FileVersionEntity $fileVersion)
    {
        foreach ($this->getProcessorManager()->getPostProcessors() as $postProcessor) {
            if ($postProcessor->shouldPostProcess($importingFile, $options, $fileVersion)) {
                $postProcessor->postProcess($importingFile, $options, $fileVersion);
            }
        }
    }

    /**
     * Get the local path of an incoming file (if the incoming file system is not local, we'll create a copy of it in a volatile directory).
     *
     * @param string $incomingFilename The file name in the incoming file system
     * @param bool $copiedLocally this output parameter will be set to true if we had to copy the file locally
     * @param \Concrete\Core\File\Service\VolatileDirectory|null $volatileDirectory this output parameter will be set to a VolatileDirectory instance if we had to copy the file locally
     *
     * @throws \Concrete\Core\File\Import\ImportException
     *
     * @return string
     */
    protected function resolveIncomingFilename($incomingFilename, &$copiedLocally, VolatileDirectory &$volatileDirectory = null)
    {
        $copiedLocally = false;
        $incoming = $this->app->make(Incoming::class);
        $incomingStorageLocation = $incoming->getIncomingStorageLocation();
        $incomingFilesystem = $incomingStorageLocation->getFileSystemObject();
        $incomingPath = $incoming->getIncomingPath();
        if (!$incomingFilesystem->has($incomingPath . '/' . $incomingFilename)) {
            throw ImportException::fromErrorCode(ImportException::E_FILE_INVALID);
        }
        $incomingAdapter = $incomingFilesystem->getAdapter();
        if ($incomingAdapter instanceof AbstractAdapter) {
            $localPath = $incomingAdapter->applyPathPrefix($incomingPath . '/' . $incomingFilename);
            if (is_file($localPath)) {
                return $localPath;
            }
        }
        $fromStream = null;
        $toStream = null;
        try {
            $volatileDirectory = $this->app->make(VolatileDirectory::class);
            $localPath = $volatileDirectory->getPath() . '/file';
            try {
                $fromStream = $incomingFilesystem->readStream($incomingPath . '/' . $incomingFilename);
            } catch (Exception $x) {
                $fromStream = false;
            }
            if ($fromStream === false) {
                throw ImportException::fromErrorCode(ImportException::E_FILE_INVALID);
            }
            $toStream = @fopen($localPath);
            if ($toStream === false) {
                throw ImportException::fromErrorCode(ImportException::E_FILE_INVALID);
            }
            if (@stream_copy_to_stream($fromStream, $toStream) === false) {
                throw ImportException::fromErrorCode(ImportException::E_FILE_INVALID);
            }
            $copiedLocally = true;

            return $localPath;
        } finally {
            if ($toStream) {
                @fclose($toStream);
            }
            if ($fromStream) {
                @fclose($fromStream);
            }
        }
    }
}


text:
namespace dev
{
namespace eth
{
namespace jit
{
using namespace evmjit;
class Stack;

class RuntimeManager: public CompilerHelper
{
public:
	RuntimeManager(llvm::IRBuilder<>& _builder, code_iterator _codeBegin, code_iterator _codeEnd);

	llvm::Value* getRuntimePtr();
	llvm::Value* getDataPtr();
	llvm::Value* getEnvPtr();

	llvm::Value* get(RuntimeData::Index _index);
	llvm::Value* get(Instruction _inst);
	llvm::Value* getGas();
	llvm::Value* getGasPtr();
	llvm::Value* getCallData();
	llvm::Value* getCode();
	llvm::Value* getCodeSize();
	llvm::Value* getCallDataSize();
	llvm::Value* getJmpBuf() { return m_jmpBuf; }
	void setGas(llvm::Value* _gas);

	llvm::Value* getMem();

	void registerReturnData(llvm::Value* _index, llvm::Value* _size); // TODO: Move to Memory.
	void registerSuicide(llvm::Value* _balanceAddress);

	void exit(ReturnCode _returnCode);

	void abort(llvm::Value* _jmpBuf);

	void setStack(Stack& _stack) { m_stack = &_stack; }
	void setJmpBuf(llvm::Value* _jmpBuf) { m_jmpBuf = _jmpBuf; }

	static llvm::StructType* getRuntimeType();
	static llvm::StructType* getRuntimeDataType();

	void checkStackLimit(ssize_t _min, ssize_t _max, ssize_t _diff);

private:
	llvm::Value* getPtr(RuntimeData::Index _index);
	void set(RuntimeData::Index _index, llvm::Value* _value);

	llvm::Function* m_longjmp = nullptr;
	llvm::Value* m_jmpBuf = nullptr;
	llvm::Value* m_dataPtr = nullptr;
	llvm::Value* m_gasPtr = nullptr;
	llvm::Value* m_memPtr = nullptr;
	llvm::Value* m_envPtr = nullptr;

	std::array<llvm::Value*, RuntimeData::numElements> m_dataElts;

	llvm::Value* m_stackSize = nullptr;
	llvm::Function* m_checkStackLimit = nullptr;

	code_iterator m_codeBegin = {};
	code_iterator m_codeEnd = {};

	Stack* m_stack = nullptr;
};

}
}
}


text:
package stsc.general.statistic.cost.comparator;

import stsc.general.statistic.Metrics;

/**
 * Compare {@link Metrics} by {@link Metrics#equals()} method.
 *
 * @return 0 if Metrics#equals() == true, left {@link Metrics#hashCode()} -
 *         right {@link Metrics#hashCode()} otherwise.
 */
public class MetricsSameComparator implements MetricsComparator {

	@Override
	public int compare(Metrics o1, Metrics o2) {
		return o1.equals(o2) ? 0 : o1.hashCode() - o2.hashCode();
	}

}


text:
(function ($) {

  $(document).ready(function () {
    lastObj = false;
    strs = Drupal.settings.thmrStrings;
    $('body').addClass("thmr_call").attr("id", "thmr_" + Drupal.settings.page_id);

    var themerEnabled = 0;
    var themerToggle = function () {
      themerEnabled = 1 - themerEnabled;
      $('#themer-toggle :checkbox').attr('checked', themerEnabled ? 'checked' : '');
      $('#themer-popup').css('display', themerEnabled ? 'block' : 'none');
      if (themerEnabled) {
        document.onclick = themerEvent;
        if (lastObj != false) {
          $(lastObj).css('outline', '3px solid #999');
        }
        $('[data-thmr]').hover(
          function () {
            if (this.parentNode.nodeName != 'BODY' && $(this).attr('thmr_curr') != 1) {
              $(this).css('outline', 'red solid 1px');
            }
          },
          function () {
            if ($(this).attr('thmr_curr') != 1) {
              $(this).css('outline', 'none');
            }
          }
        );
      }
      else {
        document.onclick = null;
        if (lastObj != false) {
          $(lastObj).css('outline', 'none');
        }
        $('[data-thmr]').unbind('mouseenter mouseleave');
      }
    };
    $(Drupal.settings.thmr_popup)
      .appendTo($('body'));

    $('
<input type="checkbox" />'+ strs.themer_info +'
')
      .appendTo($('body'))
      .click(themerToggle);
    $('#themer-popup').resizable();
    $('#themer-popup')
       .draggable({
               opacity: .6,
               handle: $('#themer-popup .topper')
             })
      .prepend(strs.toggle_throbber)
    ;

    // close box
    $('#themer-popup .topper .close').click(function() {
      themerToggle();
    });
  });

  /**
   * Known issue: IE does NOT support outline css property.
   * Solution: use another browser
   */
  function themerHilight(obj) {
    // hilight the current object (and un-highlight the last)
    if (lastObj != false) {
      $(lastObj).css('outline', 'none').attr('thmr_curr', 0);
    }
    $(obj).css('outline', '#999 solid 3px').attr('thmr_curr', 1);
    lastObj = obj;
  }

  function themerDoIt(obj) {
    if (thmrInPop(obj)) {
      return true;
    }
    // start throbber
    //$('#themer-popup img.throbber').show();
    var objs = thmrFindParents(obj);
    if (objs.length) {
      themerHilight(objs[0]);
      thmrRebuildPopup(objs);
    }
    return false;
  }

  function thmrInPop(obj) {
    //is the element in either the popup box or the toggle div?
    if (obj.id == "themer-popup" || obj.id == "themer-toggle") return true;
    if (obj.parentNode) {
      while (obj = obj.parentNode) {
        if (obj.id=="themer-popup" || obj.id == "themer-toggle") return true;
      }
    }
    return false;
  }

  function themerEvent(e) {
    if (!e) {
      var e = window.event;
    };
    if (e.target) var tg = e.target;
    else if (e.srcElement) var tg = e.srcElement;
    return themerDoIt(tg);
  }

  /**
   * Find all parents with @data-thmr"
   */
  function thmrFindParents(obj) {
    var parents = new Array();
    if ($(obj).attr('data-thmr') != undefined) {
      parents[parents.length] = obj;
    }
    if (obj && obj.parentNode) {
      while ((obj = obj.parentNode) && (obj.nodeType != 9)) {
        if ($(obj).attr('data-thmr') != undefined) {
          parents[parents.length] = obj;
        }
      }
    }
    return parents;
  }

  /**
   * Check to see if object is a block element
   */
  function thmrIsBlock(obj) {
    if (obj.style.display == 'block') {
      return true;
    }
    else if (obj.style.display == 'inline' || obj.style.display == 'none') {
      return false;
    }
    if (obj.tagName != undefined) {
      var i = blocks.length;
      if (i > 0) {
        do {
          if (blocks[i] === obj.tagName) {
            return true;
          }
        } while (i--);
      }
    }
    return false;
  }

  function thmrRefreshCollapse() {
    $('#themer-popup .devel-obj-output dt').each(function() {
        $(this).toggle(function() {
              $(this).parent().children('dd').show();
            }, function() {
              $(this).parent().children('dd').hide();
            });
      });
  }

  /**
   * Rebuild the popup
   *
   * @param objs
   *   The array of the current object and its parents. Current object is first element of the array
   */
  function thmrRebuildPopup(objs) {
    // rebuild the popup box
    var id = objs[0].getAttribute('data-thmr').split(' ').reverse()[0];
    // vars is the settings array element for this theme item
    var vars = Drupal.settings[id];
    // strs is the translatable strings
    var strs = Drupal.settings.thmrStrings;
    var type = vars.type;
    var key = vars.used;

    // clear out the initial "click on any element" starter text
    $('#themer-popup div.starter').empty();

    $('#themer-popup dd.key').empty().prepend(''+ key + '');
    $('#themer-popup dt.key-type').empty().prepend((type == 'function') ? strs.function_called : strs.template_called);

    // parents
    var parents = '';
    var parents = strs.parents +' ';
    var isFirst = true;
    for (i = 0; i < objs.length; i++) {
      thmr_ids = objs[i].getAttribute('data-thmr').split(' ').reverse();
      for (j = (i==0?1:0); j < thmr_ids.length; j++) {
        var thmrid = thmr_ids[j];
        var pvars = Drupal.settings[thmrid];
        parents += (isFirst) ? '' : '< ';
        // populate the parents
        // each parent is wrapped with a span containing a 'trig' attribute with the id of the element it represents
        parents += ''+ pvars.name +' ';
        isFirst = false;
      }
    }
    parents += '';
    // stick the parents spans in the #parents div
    $('#themer-popup #parents').empty().prepend(parents);
    $('#themer-popup span.parent')
      .click(function() {
        var thmr_id = $(this).attr('trig');
        var thmr_obj = $('[data-thmr = "' + thmr_id + '"]')[0];
        themerDoIt(thmr_obj);
      })
      .hover(
        function() {
          // make them highlight their element on mouseover
          $('#'+ $(this).attr('trig')).trigger('mouseover');
        },
        function() {
          // and unhilight on mouseout
          $('#'+ $(this).attr('trig')).trigger('mouseout');
        }
      );

    if (vars == undefined) {
      // if there's no item in the settings array for this element
      $('#themer-popup dd.candidates').empty();
      $('#themer-popup dd.preprocessors').empty();
      $('#themer-popup div.attributes').empty();
      $('#themer-popup div.used').empty();
      $('#themer-popup div.duration').empty();
    }
    else {
      $('#themer-popup div.duration').empty().prepend('' + strs.duration + '' + vars.duration + ' ms');

      if (vars.candidates.length > 0) {
        $('#themer-popup dd.candidates').show().empty().prepend(vars.candidates.join(' < '));

        if (type == 'function') {
          // populate the candidates
          $('#themer-popup dt.candidates-type').show().empty().prepend(strs.candidate_functions);
        }
        else {
          $('#themer-popup dt.candidates-type').show().empty().prepend(strs.candidate_files);
        }
      }
      else {
        $('#themer-popup dt.candidates-type, #themer-popup dd.candidates').hide();
      }

      if (vars.preprocessors.length > 0) {
        $('#themer-popup dd.preprocessors').show().empty().prepend(vars.preprocessors.join(' + '));
        $('#themer-popup dt.preprocessors-type').show().empty().prepend(strs.preprocessors);
      }
      else {
        $('#themer-popup dd.preprocessors, #themer-popup dt.preprocessors-type').hide();
      }

      if (vars.processors.length > 0) {
        $('#themer-popup dd.processors').show().empty().prepend(vars.processors.join(' + '));
        $('#themer-popup dt.processors-type').show().empty().prepend(strs.processors);
      }
      else {
        $('#themer-popup dd.processors, #themer-popup dt.processors-type').hide();
      }

      // Use drupal ajax to do what we need
      vars_div_array = $('div.themer-variables');
      vars_div = vars_div_array[0];
      var uri = Drupal.settings.devel_themer_uri + '/' + vars['variables'];
      // Programatically using the drupal ajax things is tricky, so cheat.
      dummy_link = $('Loading Vars');
      $(vars_div).append(dummy_link);
      Drupal.attachBehaviors(vars_div);
      dummy_link.click();

      thmrRefreshCollapse();
    }
    // stop throbber
    //$('#themer-popup img.throbber').hide();
  }

})(jQuery);


text:
module GameUpdater

  def self.remove_old_games
    p "I'm removing old games"
    Game.where("start_time < ?", Time.now).each {|game| game.destroy}
  end

  def self.setup_game_info(params, team)
    time = Time.parse(params[:date].to_s).localtime("-07:00")

    Game.new(
      start_time: DateTime.parse(time.to_s),
      address: params[:address],
      city: params[:city],
      team_size: 5,
      zip_code: params[:zip_code].to_i
    )
  end

  def self.add_team_to_game(game, team)
      if game.home_team_id.nil?
        game.update(home_team_id: team.id)
      elsif game.away_team_id.nil?
        game.update(away_team_id: team.id)
        # email = Email.new
        # email.send_game_on_email(game.home_team,game.away_team, game)
      end
  end
end


text:
package libldt3.model.objekte;

import java.util.List;

import libldt3.annotations.Feld;
import libldt3.annotations.Feldart;
import libldt3.annotations.Objekt;
import libldt3.annotations.Regelsatz;
import libldt3.model.enums.MedikationsStatus;
import lombok.Getter;
import lombok.Setter;

/**
 * Hier werden Informationen zu Medikamenten zusammengefasst.
 */
@Objekt("0070")
public @Getter @Setter class Medikament {

	@Feld(value = "8243", name = "Timestamp_Zeitpunkt_Medikamenteneinnahme", feldart = Feldart.kann)
	@Regelsatz(laenge = 40)
	private Timestamp timestampZeitpunktMedikamenteneinnahme;
	@Feld(value = "6208", feldart = Feldart.muss)
	@Regelsatz(maxLaenge = 60)
	private String handelsname;
	@Feld(value = "6207", feldart = Feldart.kann)
	@Regelsatz(maxLaenge = 60)
	private String rezeptur;
	@Feld(value = "8171", feldart = Feldart.kann)
	@Regelsatz(laenge = 9)
	private List<Wirkstoff> wirkstoff;
	@Feld(value = "8523", feldart = Feldart.kann)
	@Regelsatz(maxLaenge = 60)
	private String wirkstoffmenge;
	@Feld(value = "8421", feldart = Feldart.bedingt_muss)
	@Regelsatz(maxLaenge = 20)
	private String einheit;
	@Feld(value = "3689", feldart = Feldart.kann)
	@Regelsatz(laenge = 1)
	private List<MedikationsStatus> status;
	@Feld(value = "8226", name = "Timestamp_Gueltig_ab", feldart = Feldart.kann)
	@Regelsatz(laenge = 20)
	private Timestamp timestampGueltigAb;
	@Feld(value = "8227", name = "Timestamp_Gueltig_bis", feldart = Feldart.kann)
	@Regelsatz(laenge = 21)
	private Timestamp timestampGueltigBis;
	@Feld(value = "8167", name = "Zusaetzliche_Informationen", feldart = Feldart.kann)
	@Regelsatz(laenge = 26)
	private Fliesstext zusaetzlicheInformationen;

}


text:
package com.thegongoliers.input.odometry;

import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.only;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

import com.thegongoliers.utils.Resettable;

import org.junit.Test;

import edu.wpi.first.wpilibj.Encoder;

public class BaseEncoderSensorTest {

    @Test
    public void getDistance(){
        var encoder = new BaseEncoderSensor(() -> 10.0, () -> 20.0);
        assertEquals(10.0, encoder.getDistance(), 0.0001);
    }

    @Test
    public void getVelocity(){
        var encoder = new BaseEncoderSensor(() -> 10.0, () -> 20.0);
        assertEquals(20.0, encoder.getVelocity(), 0.0001);
    }

    @Test
    public void resetNoResettable(){
        var distance = mock(DistanceSensor.class);
        when(distance.getDistance()).thenReturn(10.0);

        var encoder = new BaseEncoderSensor(distance, () -> 20.0);

        assertEquals(10.0, encoder.getDistance(), 0.0001);
        assertEquals(20.0, encoder.getVelocity(), 0.0001);
        encoder.reset();
        assertEquals(0.0, encoder.getDistance(), 0.0001);
        when(distance.getDistance()).thenReturn(12.0);
        assertEquals(2.0, encoder.getDistance(), 0.0001);
        assertEquals(20.0, encoder.getVelocity(), 0.0001);
    }

    @Test
    public void resetResettable(){
        var distance = mock(DistanceSensor.class);
        var resettable = mock(Resettable.class);

        when(distance.getDistance()).thenReturn(10.0);

        var encoder = new BaseEncoderSensor(distance, () -> 20.0, resettable);

        assertEquals(10.0, encoder.getDistance(), 0.0001);
        assertEquals(20.0, encoder.getVelocity(), 0.0001);
        verify(resettable, times(0)).reset();
        encoder.reset();
        verify(resettable, times(1)).reset();
        assertEquals(10.0, encoder.getDistance(), 0.0001);
        assertEquals(20.0, encoder.getVelocity(), 0.0001);
    }

    @Test
    public void inverted(){
        var encoder = new BaseEncoderSensor(() -> 10.0, () -> 20.0).inverted();
        assertEquals(-10.0, encoder.getDistance(), 0.0001);
        assertEquals(-20.0, encoder.getVelocity(), 0.0001);
    }

    @Test
    public void scaled(){
        var encoder = new BaseEncoderSensor(() -> 10.0, () -> 20.0).scaledBy(2.0);
        assertEquals(20.0, encoder.getDistance(), 0.0001);
        assertEquals(40.0, encoder.getVelocity(), 0.0001);
    }

    @Test
    public void invertedResetNoResettable(){
        var distance = mock(DistanceSensor.class);
        when(distance.getDistance()).thenReturn(10.0);

        var encoder = new BaseEncoderSensor(distance, () -> 20.0).inverted();
        assertEquals(-10.0, encoder.getDistance(), 0.0001);
        assertEquals(-20.0, encoder.getVelocity(), 0.0001);

        encoder.reset();

        when(distance.getDistance()).thenReturn(12.0);

        assertEquals(-2.0, encoder.getDistance(), 0.0001);
        assertEquals(-20.0, encoder.getVelocity(), 0.0001);
    }

    @Test
    public void scaledResetNoResettable(){
        var distance = mock(DistanceSensor.class);
        when(distance.getDistance()).thenReturn(10.0);

        var encoder = new BaseEncoderSensor(distance, () -> 20.0).scaledBy(2.0);
        assertEquals(20.0, encoder.getDistance(), 0.0001);
        assertEquals(40.0, encoder.getVelocity(), 0.0001);

        encoder.reset();

        when(distance.getDistance()).thenReturn(12.0);

        assertEquals(4.0, encoder.getDistance(), 0.0001);
        assertEquals(40.0, encoder.getVelocity(), 0.0001);
    }

    @Test
    public void invertedResetResettable(){
        var distance = mock(DistanceSensor.class);
        when(distance.getDistance()).thenReturn(10.0);

        var reset = mock(Resettable.class);

        var encoder = new BaseEncoderSensor(distance, () -> 20.0, reset).inverted();
        assertEquals(-10.0, encoder.getDistance(), 0.0001);
        assertEquals(-20.0, encoder.getVelocity(), 0.0001);

        encoder.reset();

        when(distance.getDistance()).thenReturn(12.0);
        verify(reset, times(1)).reset();
        assertEquals(-12.0, encoder.getDistance(), 0.0001);
        assertEquals(-20.0, encoder.getVelocity(), 0.0001);
    }

    @Test
    public void scaledResetResettable(){
        var distance = mock(DistanceSensor.class);
        when(distance.getDistance()).thenReturn(10.0);

        var reset = mock(Resettable.class);

        var encoder = new BaseEncoderSensor(distance, () -> 20.0, reset).scaledBy(2.0);
        assertEquals(20.0, encoder.getDistance(), 0.0001);
        assertEquals(40.0, encoder.getVelocity(), 0.0001);

        encoder.reset();

        when(distance.getDistance()).thenReturn(12.0);
        verify(reset, times(1)).reset();
        assertEquals(24.0, encoder.getDistance(), 0.0001);
        assertEquals(40.0, encoder.getVelocity(), 0.0001);
    }

}


text:
/**
 *  \file
 *
 *  \par Purpose
 *
 *  Standard output methods for reporting debug information, warnings and
 *  errors, which can be easily be turned on/off.
 *
 *  \par Usage
 *  -# Initialize the DBGU using TRACE_CONFIGURE() if you intend to eventually
 *     disable ALL traces; otherwise use DBGU_Configure().
 *  -# Uses the TRACE_DEBUG(), TRACE_INFO(), TRACE_WARNING(), TRACE_ERROR()
 *     TRACE_FATAL() macros to output traces throughout the program.
 *  -# Each type of trace has a level : Debug 5, Info 4, Warning 3, Error 2
 *     and Fatal 1. Disable a group of traces by changing the value of
 *     TRACE_LEVEL during compilation; traces with a level bigger than TRACE_LEVEL
 *     are not generated. To generate no trace, use the reserved value 0.
 *  -# Trace disabling can be static or dynamic. If dynamic disabling is selected
 *     the trace level can be modified in runtime. If static disabling is selected
 *     the disabled traces are not compiled.
 *
 *  \par traceLevels Trace level description
 *  -# TRACE_DEBUG (5): Traces whose only purpose is for debugging the program,
 *     and which do not produce meaningful information otherwise.
 *  -# TRACE_INFO (4): Informational trace about the program execution. Should
 *     enable the user to see the execution flow.
 *  -# TRACE_WARNING (3): Indicates that a minor error has happened. In most case
 *     it can be discarded safely; it may even be expected.
 *  -# TRACE_ERROR (2): Indicates an error which may not stop the program execution,
 *     but which indicates there is a problem with the code.
 *  -# TRACE_FATAL (1): Indicates a major error which prevents the program from going
 *     any further.
 */

#ifndef _TRACE_
#define _TRACE_

/*
 *         Headers
 */

#include "pio.h"

#include <stdio.h>

/*
 *         Global Definitions
 */

/**  Softpack Version */
#define SOFTPACK_VERSION       "0.1"

#define TRACE_LEVEL_DEBUG      5
#define TRACE_LEVEL_INFO       4
#define TRACE_LEVEL_WARNING    3
#define TRACE_LEVEL_ERROR      2
#define TRACE_LEVEL_FATAL      1
#define TRACE_LEVEL_NO_TRACE   0

/* By default, all traces are output except the debug one. */
#if !defined(TRACE_LEVEL)
#define TRACE_LEVEL TRACE_LEVEL_INFO
#endif

/* By default, trace level is static (not dynamic) */
#if !defined(DYN_TRACES)
#define DYN_TRACES 0
#endif

#if defined(NOTRACE)
#error "Error: NOTRACE has to be not defined !"
#endif

#undef NOTRACE
#if (DYN_TRACES==0)
    #if (TRACE_LEVEL == TRACE_LEVEL_NO_TRACE)
        #define NOTRACE
    #endif
#endif

/* ------------------------------------------------------------------------------
 *         Global Macros
 * ------------------------------------------------------------------------------
 */

extern void TRACE_CONFIGURE( uint32_t dwBaudRate, uint32_t dwMCk ) ;

/**
 *  Initializes the DBGU for ISP project
 *
 *  \param mode  DBGU mode.
 *  \param baudrate  DBGU baudrate.
 *  \param mck  Master clock frequency.
 */
#ifndef DYNTRACE
#define DYNTRACE 0
#endif

#if (TRACE_LEVEL==0) && (DYNTRACE==0)
#define TRACE_CONFIGURE_ISP(mode, baudrate, mck) {}
#else
#define TRACE_CONFIGURE_ISP(mode, baudrate, mck) { \
    const Pin pinsUART0[] = {PINS_UART}; \
    PIO_Configure(pinsUART0, PIO_LISTSIZE(pinsUART0)); \
    UART_Configure( baudrate, mck ) ; \
    }
#endif

/**
 *  Outputs a formatted string using 'printf' if the log level is high
 *  enough. Can be disabled by defining TRACE_LEVEL=0 during compilation.
 *  \param ...  Additional parameters depending on formatted string.
 */
#if defined(NOTRACE)

/* Empty macro */
#define TRACE_DEBUG(...)      { }
#define TRACE_INFO(...)       { }
#define TRACE_WARNING(...)    { }
#define TRACE_ERROR(...)      { }
#define TRACE_FATAL(...)      { while(1); }

#define TRACE_DEBUG_WP(...)   { }
#define TRACE_INFO_WP(...)    { }
#define TRACE_WARNING_WP(...) { }
#define TRACE_ERROR_WP(...)   { }
#define TRACE_FATAL_WP(...)   { while(1); }

#elif (DYN_TRACES == 1)

/* Trace output depends on dwTraceLevel value */
#define TRACE_DEBUG(...)      { if (dwTraceLevel >= TRACE_LEVEL_DEBUG)   { printf("-D- " __VA_ARGS__); } }
#define TRACE_INFO(...)       { if (dwTraceLevel >= TRACE_LEVEL_INFO)    { printf("-I- " __VA_ARGS__); } }
#define TRACE_WARNING(...)    { if (dwTraceLevel >= TRACE_LEVEL_WARNING) { printf("-W- " __VA_ARGS__); } }
#define TRACE_ERROR(...)      { if (dwTraceLevel >= TRACE_LEVEL_ERROR)   { printf("-E- " __VA_ARGS__); } }
#define TRACE_FATAL(...)      { if (dwTraceLevel >= TRACE_LEVEL_FATAL)   { printf("-F- " __VA_ARGS__); while(1); } }

#define TRACE_DEBUG_WP(...)   { if (dwTraceLevel >= TRACE_LEVEL_DEBUG)   { printf(__VA_ARGS__); } }
#define TRACE_INFO_WP(...)    { if (dwTraceLevel >= TRACE_LEVEL_INFO)    { printf(__VA_ARGS__); } }
#define TRACE_WARNING_WP(...) { if (dwTraceLevel >= TRACE_LEVEL_WARNING) { printf(__VA_ARGS__); } }
#define TRACE_ERROR_WP(...)   { if (dwTraceLevel >= TRACE_LEVEL_ERROR)   { printf(__VA_ARGS__); } }
#define TRACE_FATAL_WP(...)   { if (dwTraceLevel >= TRACE_LEVEL_FATAL)   { printf(__VA_ARGS__); while(1); } }

#else

/* Trace compilation depends on TRACE_LEVEL value */
#if (TRACE_LEVEL >= TRACE_LEVEL_DEBUG)
#define TRACE_DEBUG(...)      { printf("-D- " __VA_ARGS__); }
#define TRACE_DEBUG_WP(...)   { printf(__VA_ARGS__); }
#else
#define TRACE_DEBUG(...)      { }
#define TRACE_DEBUG_WP(...)   { }
#endif

#if (TRACE_LEVEL >= TRACE_LEVEL_INFO)
#define TRACE_INFO(...)       { printf("-I- " __VA_ARGS__); }
#define TRACE_INFO_WP(...)    { printf(__VA_ARGS__); }
#else
#define TRACE_INFO(...)       { }
#define TRACE_INFO_WP(...)    { }
#endif

#if (TRACE_LEVEL >= TRACE_LEVEL_WARNING)
#define TRACE_WARNING(...)    { printf("-W- " __VA_ARGS__); }
#define TRACE_WARNING_WP(...) { printf(__VA_ARGS__); }
#else
#define TRACE_WARNING(...)    { }
#define TRACE_WARNING_WP(...) { }
#endif

#if (TRACE_LEVEL >= TRACE_LEVEL_ERROR)
#define TRACE_ERROR(...)      { printf("-E- " __VA_ARGS__); }
#define TRACE_ERROR_WP(...)   { printf(__VA_ARGS__); }
#else
#define TRACE_ERROR(...)      { }
#define TRACE_ERROR_WP(...)   { }
#endif

#if (TRACE_LEVEL >= TRACE_LEVEL_FATAL)
#define TRACE_FATAL(...)      { printf("-F- " __VA_ARGS__); while(1); }
#define TRACE_FATAL_WP(...)   { printf(__VA_ARGS__); while(1); }
#else
#define TRACE_FATAL(...)      { while(1); }
#define TRACE_FATAL_WP(...)   { while(1); }
#endif

#endif

/**
 *        Exported variables
 */
/** Depending on DYN_TRACES, dwTraceLevel is a modifable runtime variable or a define */
#if !defined(NOTRACE) && (DYN_TRACES == 1)
    extern uint32_t dwTraceLevel ;
#endif

#endif //#ifndef TRACE_H


text:
using System.IO;
using CollectionsOnline.Core.Extensions;

namespace CollectionsOnline.Core.Models
{
    public class MediaFile
    {
        public string Uri { get; set; }

        public long Size { get; set; }

        public string SizeShortened
        {
            get
            {
                return this.Size.BytesToString();
            }
        }

        public string Extension
        {
            get
            {
                var extension = Path.GetExtension(Uri);

                if (extension != null)
                    return extension.Replace(".", string.Empty);

                return string.Empty;
            }
        }
    }

    public class ImageMediaFile : MediaFile
    {
        public int Width { get; set; }

        public int Height { get; set; }
    }
}


text:
require 'spec_helper'

describe DimeloBbQuoteParser::Buffer do
  before(:each) do
    @buffer = DimeloBbQuoteParser::Buffer.new()
  end

  describe 'open_quote' do
    it "should increase the meta size by 1 (v1)" do
      expect{
        @buffer.open_quote('[quote="superman"]')
      }.to change(@buffer.meta, :count).from(0).to(1)
    end

    it "should increase the meta size by 1 (v2)" do
      @buffer.open_quote('[quote="superman"]')

      expect{
        @buffer.open_quote('[quote="batman"]')
      }.to change(@buffer.meta, :count).from(1).to(2)
    end

    it "should add the author to meta (if present) (v1)" do
      @buffer.open_quote('[quote="superman"]')
      @buffer.meta.last.should == 'superman'
    end

    it "should add the author to meta (if present) (v2)" do
      @buffer.open_quote('[quote="dark vador"]')
      @buffer.meta.last.should == 'dark vador'
    end

    it "should add a nil  to meta if author is missing (v1)" do
      @buffer.open_quote('[quote]')
      @buffer.meta.last.should be_nil
    end

    it "should add a nil  to meta if author is missing (v2)" do
      @buffer.open_quote('[quote:12qn6cfu]')
      @buffer.meta.last.should be_nil
    end

    it "should increase the buffer size by 1 (v1)" do
      expect{
        @buffer.open_quote('[quote="superman"]')
      }.to change(@buffer.buffer, :count).from(0).to(1)
    end

    it "should increase the buffer size by 1 (v2)" do
      @buffer.open_quote('[quote="superman"]')

      expect{
        @buffer.open_quote('[quote="batman"]')
      }.to change(@buffer.buffer, :count).from(1).to(2)
    end

    it "should init the buffer with a blank string " do
      @buffer.open_quote('[quote]')
      @buffer.buffer.last.should be_blank
    end
  end

  describe "add_content" do

    it "will not change the buffer depth (v1)" do
      expect {
        @buffer.add_content("anything")
      }.not_to change(@buffer, :depth).from(0)

    end
    it "will not change the buffer depth (v2)" do
      @buffer.open_quote('[quote="superman"]')
      expect {
        @buffer.add_content("anything")
      }.not_to change(@buffer, :depth).from(1)

    end

    it "when buffer is empty will add to html_buffer (v1)" do
      expect {
        @buffer.add_content("A")
      }.to change(@buffer, :html_buffer).from("").to("
A
")
    end

    it "when buffer is empty will add to html_buffer (v2)" do
      @buffer.add_content("A")
      expect {
        @buffer.add_content("B")
      }.to change(@buffer, :html_buffer).from("
A
").to("
A

B
")
    end

    it "when adding html to empty buffer => it will not apply simple_format " do
      @buffer.add_content("A")
      expect {
        @buffer.add_content("
B
", true)
      }.to change(@buffer, :html_buffer).from("
A
").to("
A

B
")
    end

    it "when buffer is not empty will add to last (v1)" do
      @buffer.open_quote('[quote="superman"]')
      expect {
        @buffer.add_content("A")
      }.to change(@buffer.buffer, :last).from("").to("
A
")
    end

    it "when buffer is not empty will add to last (v2)" do
      @buffer.open_quote('[quote="superman"]')
      @buffer.add_content("A")
      expect {
        @buffer.add_content("B")
      }.to change(@buffer.buffer, :last).from("
A
").to("
A

B
")
    end

    it "when adding html to a non empty buffer => it will not apply simple_format " do
      @buffer.open_quote('[quote="superman"]')
      @buffer.add_content("A")
      expect {
        @buffer.add_content("
B
", true)
      }.to change(@buffer.buffer, :last).from("
A
").to("
A

B
")
    end

  end

  describe "pop_quote" do
      it "should pop return nil if there is nothing in the buffer" do
        @buffer.open_quote('[quote="superman"]')
        #no content
        @buffer.pop_quote.should be_blank
      end

      it "should not include the author div if meta is blank" do
        @buffer.open_quote('[quote:ER3313]')
        @buffer.add_content("I can fly")
        @buffer.pop_quote.should == '

I can fly

'
      end

      it "should include the author div if meta is not blank" do
        @buffer.open_quote('[quote="superman"]')
        @buffer.add_content("I can fly")
        @buffer.pop_quote.should == '

superman a écrit:

I can fly

'
      end

     it "should return a second level quote if there are 2 open quotes" do
       @buffer.open_quote('[quote="superman"]')
       @buffer.add_content("I can fly")
       @buffer.open_quote('[quote="bat man"]')
       @buffer.add_content("I can jump")

       quote = @buffer.pop_quote

       quote.should include('quote_2')
       quote.should_not include('quote_1')
     end
  end

  describe "close_quote" do
    before(:each)  do
      @buffer.open_quote('[quote="superman"]')
      @buffer.add_content("I can fly")
      @buffer.open_quote('[quote="bat man"]')
      @buffer.add_content("I can jump")
    end

    it "should modify depth" do
      expect {
        @buffer.close_quote
      }.to change(@buffer, :depth).from(2).to(1)

      expect {
        @buffer.close_quote
      }.to change(@buffer, :depth).from(1).to(0)
    end

    it "should add the quote to the previous level" do
      expect {
        @buffer.close_quote
      }.to change{@buffer.buffer[0]}.from("
I can fly
").to("
I can fly

bat man a écrit:

I can jump

")
    end

  end

  describe "unmatching closing quotes" do
    before(:each) do
      @buffer.add_content("A")
      @buffer.open_quote('[quote]')
      @buffer.add_content("B")
      @buffer.close_quote
    end

    it {@buffer.depth.should == 0}

    it {@buffer.html_buffer.should == "
A

B

"}

    it "should ignore unmatched close_quote (v1)" do
      expect {
        @buffer.close_quote
      }.not_to raise_exception
    end

    it "should ignore unmatched close_quote (v2)" do
      expect {
        @buffer.close_quote
      }.not_to change(@buffer, :depth)
    end

    it "should ignore unmatched close_quote (v3)" do
      expect {
        @buffer.close_quote
      }.not_to change(@buffer, :html_buffer)
    end
  end

  describe "unmatched opened quotes"  do
    it "should flush 1 opened quote" do
      @buffer.add_content("A")
      @buffer.open_quote('[quote]')
      @buffer.add_content("B")

      expect{
        @buffer.flush
      }.to change(@buffer, :html_buffer).from("
A
").to("
A

B

")
    end

    it "should flush 2 opened quote" do
      @buffer.add_content("A")
      @buffer.open_quote('[quote]')
      @buffer.add_content("B")
      @buffer.open_quote('[quote]')
      @buffer.add_content("C")

      expect{
        @buffer.flush
      }.to change(@buffer, :html_buffer).from("
A
").to("
A

B

C

")
    end
  end

  describe "extract_author" do
    it{@buffer.extract_author('[quote="superman"]').should == 'superman'}
    it{@buffer.extract_author('[quote="superman"]').should == 'superman'}
    it{@buffer.extract_author('[quote="super man"]').should == 'super man'}
    it{@buffer.extract_author('[quote="super man"]').should == 'super man'}
  end

end


text:
// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

package org.chromium.android_webview.test;

import android.support.test.InstrumentationRegistry;

import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;

import org.chromium.android_webview.AwContents;
import org.chromium.android_webview.AwQuotaManagerBridge;
import org.chromium.android_webview.AwSettings;
import org.chromium.android_webview.test.util.AwQuotaManagerBridgeTestUtil;
import org.chromium.base.test.util.CallbackHelper;
import org.chromium.base.test.util.DisabledTest;
import org.chromium.net.test.util.TestWebServer;

/**
 * Tests for the AwQuotaManagerBridge.
 */
@RunWith(AwJUnit4ClassRunner.class)
public class AwQuotaManagerBridgeTest {
    @Rule
    public AwActivityTestRule mActivityTestRule = new AwActivityTestRule();

    private TestAwContentsClient mContentsClient;
    private AwTestContainerView mTestView;
    private AwContents mAwContents;
    private TestWebServer mWebServer;
    private String mOrigin;

    @Before
    public void setUp() throws Exception {
        mContentsClient = new TestAwContentsClient();
        mTestView = mActivityTestRule.createAwTestContainerViewOnMainSync(mContentsClient);
        mAwContents = mTestView.getAwContents();
        mWebServer = TestWebServer.start();
        mOrigin = mWebServer.getBaseUrl();

        AwSettings settings = mActivityTestRule.getAwSettingsOnUiThread(mAwContents);
        settings.setJavaScriptEnabled(true);
        settings.setDomStorageEnabled(true);
    }

    @After
    public void tearDown() {
        deleteAllData();
        if (mWebServer != null) {
            mWebServer.shutdown();
        }
    }

    private void deleteAllData() {
        final AwQuotaManagerBridge bridge =
                mActivityTestRule.getAwBrowserContext().getQuotaManagerBridge();
        InstrumentationRegistry.getInstrumentation().runOnMainSync(() -> bridge.deleteAllData());
    }

    private void deleteOrigin(final String origin) {
        final AwQuotaManagerBridge bridge =
                mActivityTestRule.getAwBrowserContext().getQuotaManagerBridge();
        InstrumentationRegistry.getInstrumentation().runOnMainSync(
                () -> bridge.deleteOrigin(origin));
    }

    private static class LongValueCallbackHelper extends CallbackHelper {
        private long mValue;

        public void notifyCalled(long value) {
            mValue = value;
            notifyCalled();
        }

        public long getValue() {
            assert getCallCount() > 0;
            return mValue;
        }
    }

    private long getQuotaForOrigin() throws Exception {
        final LongValueCallbackHelper callbackHelper = new LongValueCallbackHelper();
        final AwQuotaManagerBridge bridge =
                mActivityTestRule.getAwBrowserContext().getQuotaManagerBridge();

        int callCount = callbackHelper.getCallCount();
        InstrumentationRegistry.getInstrumentation().runOnMainSync(
                () -> bridge.getQuotaForOrigin("foo.com",
                        quota -> callbackHelper.notifyCalled(quota)));
        callbackHelper.waitForCallback(callCount);

        return callbackHelper.getValue();
    }

    private long getUsageForOrigin(final String origin) throws Exception {
        final LongValueCallbackHelper callbackHelper = new LongValueCallbackHelper();
        final AwQuotaManagerBridge bridge =
                mActivityTestRule.getAwBrowserContext().getQuotaManagerBridge();

        int callCount = callbackHelper.getCallCount();
        InstrumentationRegistry.getInstrumentation().runOnMainSync(
                () -> bridge.getUsageForOrigin(origin,
                        usage -> callbackHelper.notifyCalled(usage)));
        callbackHelper.waitForCallback(callCount);

        return callbackHelper.getValue();
    }

    /*
    @LargeTest
    @Feature({"AndroidWebView", "WebStore"})
    */
    @Test
    @DisabledTest(message = "crbug.com/609977")
    public void testDeleteAll() throws Exception {
        final long initialUsage = getUsageForOrigin(mOrigin);

        AwActivityTestRule.pollInstrumentationThread(
                () -> getUsageForOrigin(mOrigin) > initialUsage);

        deleteAllData();
        AwActivityTestRule.pollInstrumentationThread(() -> getUsageForOrigin(mOrigin) == 0);
    }

    /*
    @LargeTest
    @Feature({"AndroidWebView", "WebStore"})
    */
    @Test
    @DisabledTest(message = "crbug.com/609977")
    public void testDeleteOrigin() throws Exception {
        final long initialUsage = getUsageForOrigin(mOrigin);

        AwActivityTestRule.pollInstrumentationThread(
                () -> getUsageForOrigin(mOrigin) > initialUsage);

        deleteOrigin(mOrigin);
        AwActivityTestRule.pollInstrumentationThread(() -> getUsageForOrigin(mOrigin) == 0);
    }

    /*
    @LargeTest
    @Feature({"AndroidWebView", "WebStore"})
    */
    @Test
    @DisabledTest(message = "crbug.com/609977")
    public void testGetResultsMatch() throws Exception {
        AwQuotaManagerBridge bridge =
                mActivityTestRule.getAwBrowserContext().getQuotaManagerBridge();
        AwActivityTestRule.pollInstrumentationThread(
                () -> AwQuotaManagerBridgeTestUtil.getOrigins(bridge).mOrigins.length > 0);

        AwQuotaManagerBridge.Origins origins = AwQuotaManagerBridgeTestUtil.getOrigins(bridge);
        Assert.assertEquals(origins.mOrigins.length, origins.mUsages.length);
        Assert.assertEquals(origins.mOrigins.length, origins.mQuotas.length);

        for (int i = 0; i < origins.mOrigins.length; ++i) {
            Assert.assertEquals(origins.mUsages[i], getUsageForOrigin(origins.mOrigins[i]));
            Assert.assertEquals(origins.mQuotas[i], getQuotaForOrigin());
        }
    }
}


text:
package com.github.sedubois.factorization.service;

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

public class Factorizer {

  // TODO change to parallelizable algorithm to spread across workers
  public static List<Long> factorize(long number) {
    long n = number;
    List<Long> factors = new ArrayList<>();
    for (long i = 2; i <= n; i++) {
      while (n % i == 0) {
        factors.add(i);
        n /= i;
      }
    }
    return factors;
  }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <data>

        <variable
            name="user"
            type="br.com.liveo.mvp.model.User" />
    </data>

    <android.support.constraint.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="?attr/selectableItemBackground"
        android:padding="10dp">

        <ImageView
            android:id="@+id/img_user"
            android:layout_width="50dp"
            android:layout_height="50dp"
            android:layout_marginLeft="6dp"
            android:layout_marginStart="6dp"
            android:contentDescription="@string/clear"
            app:imageLoadRounded="@{user.getAvatar()}"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintTop_toTopOf="parent" />

        <TextView
            android:id="@+id/txt_name"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:maxLines="1"
            android:textSize="16sp"
            android:layout_marginLeft="8dp"
            android:layout_marginStart="8dp"
            app:layout_constraintBottom_toBottomOf="@+id/img_user"
            app:layout_constraintLeft_toRightOf="@+id/img_user"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toTopOf="@+id/img_user"
            app:nameWithLastName="@{user}" />
    </android.support.constraint.ConstraintLayout>
</layout>


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Web;

namespace Dragonstone
{
    public class Webserver
    {
        public delegate void RequestReceivedHanlder(object sender, HttpListenerContext context);
        public event RequestReceivedHanlder RequestReceived;
        public static List<string> FileRequest, AvailableServices, Clients;
        public static Dictionary<string,List<Message>> ListOfClientQueue;

        private readonly HttpListener _listener;
        private bool _running;
        private readonly Thread _connectionThread;

        public Webserver(string prefix)
        {
            ListOfClientQueue = new Dictionary<string, List<Message>>();
            // Add Files that is available on the server
            FileRequest = new List<string>() {
                ""
                ,"client.js"
                ,"ace.min.css"
            };

            // Add Service Request that is Available
            AvailableServices = new List<string>() {
                "connect"
                ,"send"
                ,"dequeue"
                ,"disconnect"
            };

            _listener = new HttpListener();
            _listener.Prefixes.Add(prefix);
            _connectionThread = new Thread(ConnectionThread);
        }

        private void ConnectionThread()
        {
            try
            {
                _running = true;
                _listener.Start();
                while (_running)
                    ProcessRequest();
            }
            catch (HttpListenerException) { }
            catch (ThreadAbortException) { }
            catch (Exception){}
        }

        private void ProcessRequest()
        {
            IAsyncResult result = _listener.BeginGetContext(ListenerCallback, _listener);
            result.AsyncWaitHandle.WaitOne();
        }

        protected void ListenerCallback(IAsyncResult result)
        {
            if (_listener == null || !_listener.IsListening) return;
            var context = _listener.EndGetContext(result);
            OnRequestReceived(context);
        }

        protected void OnRequestReceived(HttpListenerContext context)
        {
            if (RequestReceived != null)
                RequestReceived(this, context);
        }

        public void Start()
        {
            _connectionThread.Start();
        }

        public void Stop()
        {
            _running = false;
            _listener.Stop();
        }

        // Method to locate and read a file to serve
        public static string GetFile(string filename)
        {
            string html = "";

            try
            {
                var filePath = String.Concat(Directory.GetCurrentDirectory(), @"\Client\"+filename);

                if (File.Exists(filePath))
                {
                    html = File.ReadAllText(filePath);
                }
                else
                {
                    html = "
Client File not Found!
";
                }
            }
            catch (Exception ex)
            {
                LogException(ex);
            }
            return html;
        }

        // Method to add client to collection
        public static bool Connect(HttpListenerContext context)
        {
            bool connected = false;
            try
            {
                string client = context.Request.Cookies["clientID"].Value;

                if (String.IsNullOrEmpty(client))
                    return false;

                string client_guid = client.Replace("-", "");

                if (!ListOfClientQueue.ContainsKey(client_guid))
                {
                    // Add client to collection
                    ListOfClientQueue.Add(client_guid, new List<Message>());
                    connected = true;
                    Console.WriteLine("New Client: {0} connected.", client_guid);
                }
                else // Client is already on the list
                    connected = true;

            }
            catch (Exception ex)
            {
                LogException(ex);
                return false;
            }
            return connected;
        }

        // Method to disconnect client from server
        public static bool Disconnect(HttpListenerContext context)
        {
            bool disconnected = true;
            try
            {
                string client = context.Request.Cookies["clientID"].Value;

                if (String.IsNullOrEmpty(client))
                    return false;

                string client_guid = client.Replace("-", "");

                if (ListOfClientQueue.ContainsKey(client_guid))
                {
                    // Remove client and all of its queues from the collection
                    ListOfClientQueue.Remove(client_guid);
                    disconnected = true;
                }
            }
            catch (Exception ex)
            {
                LogException(ex);
            }

            return disconnected;
        }

        // Method to Add Message to Client Queue
        public static string AddMessageToClientQueue(HttpListenerContext context)
        {
            string response = "false";
            string sender_message;
            try
            {
                string client = context.Request.Cookies["clientID"].Value;
                string client_guid = client.Replace("-", "");
                Guid messageGuid = Guid.NewGuid();
                string guid = messageGuid.ToString().Replace("-", "");

                // Get Posted Data Message
                using (var reader=new StreamReader(context.Request.InputStream,context.Request.ContentEncoding))
                {
                    var data_text = reader.ReadToEnd();
                    sender_message=HttpUtility.UrlDecode(data_text);
                }

                if (ListOfClientQueue.Count > 0)
                {
                    // Add Message to Clients Queue
                    foreach (var item in ListOfClientQueue)
                    {
                        Message message_data = new Message {
                            message_guid=guid,
                            message_sender = client_guid,
                            message_timestamp=DateTime.Now.ToShortTimeString(),
                            message_text=sender_message.Split('=')[1]
                        };

                        item.Value.Add(message_data);
                    }

                    response = guid;
                }
            }
            catch (Exception ex)
            {
                LogException(ex);
                return "false";
            }
            return response;
        }

        // Method to Retreive client messages
        public static List<Message> DequeueClientMessages(HttpListenerContext context)
        {
            List<Message> client_messages = new List<Message>();
            try
            {
                string client = context.Request.Cookies["clientID"].Value;

                if (String.IsNullOrEmpty(client))
                    return client_messages;

                string client_guid = client.Replace("-", "");

                // Make sure the collection is not empty, else it will return an exception
                if (ListOfClientQueue.Count>0)
                {
                    // Get Messages from the Client Queue
                    client_messages = ListOfClientQueue[client_guid];

                    // Remove messages after Dequeueing
                    ListOfClientQueue[client_guid] = new List<Message>();
                }
            }
            catch (Exception ex)
            {
                LogException(ex);
            }
            return client_messages;
        }

        private static void LogException(Exception ex)
        {
            Console.WriteLine("Error: "+ex);
        }
    }
}


text:
package de.adesso.jenkinshue.common.service;

import java.util.List;

import de.adesso.jenkinshue.common.dto.lamp.LampCreateDTO;
import de.adesso.jenkinshue.common.dto.lamp.LampDTO;
import de.adesso.jenkinshue.common.dto.lamp.LampGroupedScenariosDTO;
import de.adesso.jenkinshue.common.dto.lamp.LampHueDTO;
import de.adesso.jenkinshue.common.dto.lamp.LampNameDTO;
import de.adesso.jenkinshue.common.dto.lamp.LampRenameDTO;
import de.adesso.jenkinshue.common.dto.lamp.LampTestDTO;
import de.adesso.jenkinshue.common.dto.lamp.LampTurnOffDTO;
import de.adesso.jenkinshue.common.dto.lamp.LampUpdateDTO;
import de.adesso.jenkinshue.common.dto.lamp.LampUpdateLastShownScenarioDTO;
import de.adesso.jenkinshue.common.dto.team.TeamLampsDTO;

/**
 *
 * @author wennier
 *
 */
public interface LampService {

	LampDTO create(LampCreateDTO lamp);

	LampDTO update(LampUpdateDTO lamp);

	LampDTO updateLastShownScenario(LampUpdateLastShownScenarioDTO lamp);

	LampDTO rename(LampRenameDTO lamp);

	void remove(long id);

	List<LampDTO> findAll();

	LampGroupedScenariosDTO findOne(long id);

	long count();

	long count(long teamId);

	List<LampHueDTO> findAllAvailable();

	TeamLampsDTO findAllOfATeam(long teamId);

	List<LampNameDTO> findAllLampNamesOfATeam(long teamId);

	void testScenario(LampTestDTO lamp);

	void pulseOnce(String hueUniqueId);

	void turnOff(LampTurnOffDTO lamp);

}


text:
package com.qhvv.englishforalllevel.util;

import android.view.View;

/**
 * Created by Vo Quang Hoa on 12/23/2015.
 */
public class ViewUtils {
    public static void setViewVisibility(View view, boolean isShow){
        view.setVisibility(isShow?View.VISIBLE: View.GONE);
    }
}


text:
name: Questions
about: Questions about Neo Platform
title: ''
labels: question
assignees: ''
---

**Delete this: We would like to use GitHub for bug reports and feature requests only however if you are unable to get support from our team in: our [Discord](https://discord.io/neo) server or in our [offical documentation](https://docs.neo.org/docs/en-us/index.html), feel encouraged to create an issue here on GitHub.**


text:
namespace Microsoft.WindowsAzure.Management.HDInsight.Framework.Core.Library
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading;

    /// <summary>
    /// Adds extension methods to the Cancelation Token class.
    /// </summary>
#if Non_Public_SDK
    public static class CancellationTokenExtensions
#else
    internal static class CancellationTokenExtensions
#endif
    {
        /// <summary>
        /// Waits on a cancellation token for a given interval.
        /// </summary>
        /// <param name="token">
        /// The Cancellation Token.
        /// </param>
        /// <param name="interval">
        /// The period of time to wait.
        /// </param>
        public static void WaitForInterval(this CancellationToken token, TimeSpan interval)
        {
            var start = DateTime.Now;
            var waitFor = Math.Min((int)interval.TotalMilliseconds, 1000);
            while (DateTime.Now - start < interval)
            {
                if (token.IsCancellationRequested)
                {
                    throw new OperationCanceledException("The operation was canceled by user request.");
                }
                Thread.Sleep(waitFor);
            }
        }
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>

         <meta property="rnews:description"
            content="The broadcaster, Sir Michael Parkinson, has revealed that he has prostate cancer."/>
         <meta property="rnews:datePublished" content="2013-07-07T10:36:17"/>
         <meta property="rnews:thumbnailUrl"
            content="http://news.bbcimg.co.uk/media/images/68592000/jpg/_68592019_parky.jpg"/>
         <meta property="rnews:headline" content="Parkinson reveals cancer treatment"/>
         <meta name="CPS_SECTION_PATH" content="Entertainment and Arts"/>
         <meta property="rnews:creator" content="http://www.bbc.co.uk#org"/>
         <link rel="copyright"
            href="http://www.bbc.co.uk/terms/"
            title="Terms of Use"/>
         <link rel="http://purl.org/dc/terms/source"
            href="http://www.bbc.co.uk/news/entertainment-arts-23216579"/>
         <title>BBC News - Sir Michael Parkinson reveals he has
cancer</title>

               7 July 2013
               Last updated
at
               11:36

Sir Michael Parkinson reveals he has
cancer

               Sir Michael Parkinson was diagnosed
after a routine health check

Sir Michael
Parkinson has revealed that he has prostate cancer.

The veteran broadcaster and former chat show host said he was
having radiotherapy and was confident of returning to full
health.

"It was a great shock, but I have been told to expect to make a
full recovery," he said.

Sir Michael, 78, known as Parky to his fans, was diagnosed with
the disease in May after a routine health check last year.

"When you are told you have something like cancer, it is a
shock. But the cancer specialist said: 'I will assure you, you will
not die of this.'

"I am concerned about it, of course, but I am not frightened of
it."

Sir Michael said he continues to live "a normal life", aside
from the "distraction" of his five weekly sessions of
radiotherapy.

Describing his treatment as "extraordinary", he said had not
felt any pain or discomfort.

"If anything, it's boring," he said. "You have to lie there
completely still, for six minutes.

"But I have had no side effects at all."

Sir Michael admitted that the diagnosis was a shock, but said he
was "in wonder" at the "marvellous" work of medical staff and was
"very grateful".

"When you get involved in this, you begin to understand the
extraordinary work of those involved in treating cancer," he
added.

The journalist and renowned interviewer urged men to pay more
attention to their health and to take notice of any unusual
symptoms.

"I don't want to trivialise it, but men know when there's a
problem. I have been lucky, but men are silly about their
health.

"Get it checked out - it might be something else."

Sir Michael, whose career spanned 50 years and saw him interview
high-profile guests such as Muhammad Ali, Sir Elton John and Rod
Hull with puppet Emu, announced his retirement in 2007.

He said he had no intention of letting cancer get in the
way.

"I'm 78 and I have had a good life," he said.

"I shall be around for a while yet, to the delight of my friends
and the dismay of my enemies."

Related Stories

                  Sir Michael Parkinson
on Joe Frazier Listen

                  Parkinson accepts libel
damages

                  Parkinson
collects knighthood Watch


text: module.exports = require('./app/main');


text:
NS_ASSUME_NONNULL_BEGIN

@interface MSRequestManager (Private)

#pragma mark - Private Base Methods

- (void)GET:(NSString *)URLString
    parameters:(nullable id)parameters
      progress:(nullable void (^)(NSProgress *downloadProgress))downloadProgress
       success:(nullable void (^)(NSURLSessionDataTask *task, id _Nullable responseObject))success
       failure:(nullable void (^)(NSURLSessionDataTask *_Nullable task, NSError *error))failure;

- (void)POST:(NSString *)URLString
    parameters:(nullable id)parameters
       success:(nullable void (^)(NSURLSessionDataTask *task, id _Nullable responseObject))success
       failure:(nullable void (^)(NSURLSessionDataTask *_Nullable task, NSError *error))failure;

- (void)PUT:(NSString *)URLString
    parameters:(nullable id)parameters
       success:(nullable void (^)(NSURLSessionDataTask *task, id _Nullable responseObject))success
       failure:(nullable void (^)(NSURLSessionDataTask *_Nullable task, NSError *error))failure;

#pragma mark - Private Request Methods

- (void)addActiveRequest:(NSString *)URLString;
- (void)removeActiveRequest:(NSString *)URLString;
- (BOOL)isActiveRequest:(NSString *)URLString;

#pragma mark - Private Call Methods

- (NSString *)apiCall:(NSString *)call;

#pragma mark - Private Error Methods

- (NSInteger)statusCodeFromTask:(NSURLSessionDataTask *)task;

@end

NS_ASSUME_NONNULL_END