text:
@interface NSString (SKPersian)

-(NSString *) persianDigits;
-(NSString *) englishDigits;

-(NSString *) persianChars;

@end


text:
Insert New Parent Class
=======================

The existing 'Create Ancestor' CodeProvider that comes with CodeRush does not function if the Class in question already has a code ancestor.

This plugin is intended to fill that void.

### Usage ###

 * Place your caret (That blinky thing where text comes out in the editor) in a class declaration (on it's name is good)
 * Trigger the CodeRush?\Refactor SmartMenu.
 * Choose Insert New Parent Class
 * Name the generated class.
 * You're done :)

An animated picture often works better than words ->
![](./Screenshots/InsertNewParentClass.gif)

redpajama_set_name: RedPajamaGithub


text:
package org.qcri.rheem.profiler.log;

import org.qcri.rheem.core.api.Configuration;
import org.qcri.rheem.core.optimizer.costs.EstimationContext;
import org.qcri.rheem.core.optimizer.costs.LoadProfileEstimator;
import org.qcri.rheem.core.optimizer.costs.TimeEstimate;
import org.qcri.rheem.core.platform.AtomicExecutionGroup;
import org.qcri.rheem.core.platform.PartialExecution;
import org.qcri.rheem.core.platform.Platform;
import org.qcri.rheem.core.util.Bitmask;

import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.function.ToDoubleFunction;
import java.util.stream.DoubleStream;

/**
 * Context for the optimization of {@link LoadProfileEstimator}s.
 */
public class Individual {

    /**
     * Orders {@link Individual}s by their fitness descendingly.
     */
    public static Comparator<Individual> fitnessComparator =
            (i1, i2) -> Double.compare(i2.getFitness(), i1.getFitness());

    private final double[] genome;

    private final double[] maturity;

    private double minMaturity = Double.NaN, maxMaturity = Double.NaN;

    private double fitness = Double.NaN;

    Individual(int genomeSize) {
        this.genome = new double[genomeSize];
        this.maturity = new double[genomeSize];
    }

    public double[] getGenome() {
        return this.genome;
    }

    public void setGene(int index, double value, double maturity) {
        this.genome[index] = value;
        this.updateMaturity(index, maturity);
    }

    private void updateMaturity(int index, double maturity) {
        maturity = 1d;
        this.maturity[index] = maturity;
        if (Double.isNaN(this.minMaturity) || this.minMaturity > maturity) {
            this.minMaturity = maturity;
        }
        if (Double.isNaN(this.maxMaturity) || this.maxMaturity < maturity) {
            this.maxMaturity = maturity;
        }
    }

    public Individual mutate(Random random,
                             Bitmask activatedGenes,
                             OptimizationSpace optimizationSpace,
                             double mutationProb,
                             double resetProb) {

        // Make at least one mutation more likely.
        if (mutationProb > 0d) mutationProb = Math.max(mutationProb, 1 / activatedGenes.cardinality());

        final double smoothing = 1d;
        int numActivatedGenes = activatedGenes.cardinality();
        double logGainProduct = 0d;
        for (int i = activatedGenes.nextSetBit(0); i != -1; i = activatedGenes.nextSetBit(i + 1)) {
            final double gain = this.maturity[i] - this.minMaturity;
            logGainProduct += Math.log(gain + smoothing);
        }
        double meanGain = Math.exp((logGainProduct / numActivatedGenes)) - smoothing;

        Individual mutant = new Individual(this.genome.length);
        for (int i = 0; i < this.genome.length; i++) {
            if (!activatedGenes.get(i)) {
                mutant.setGene(i, this.genome[i], this.maturity[i]);
                continue;
            }
            final double gain = this.maturity[i] - this.minMaturity;
            double boost = (meanGain + smoothing) / (gain + smoothing);
            final double uniform = random.nextDouble() * boost;
            if (uniform <= mutationProb) {
                final double mutatedGene = optimizationSpace.getVariable(i).mutate(this.genome[i], random);
                mutant.setGene(i, mutatedGene, Double.NaN);
            } else if (uniform <= mutationProb + resetProb) {
                mutant.setGene(i, optimizationSpace.getVariable(i).createRandomValue(random), Double.NaN);
            } else {
                mutant.setGene(i, this.genome[i], this.maturity[i]);
            }
        }
        return mutant;
    }

    public Individual crossOver(Individual that, Random random) {
        Individual offspring = new Individual(this.genome.length);
        double minMaturity = Math.min(this.minMaturity, that.minMaturity);
        for (int i = 0; i < this.genome.length; i++) {
            double thisProb = GeneticOptimizer.getSelectionProbability(this.maturity[i], that.maturity[i], minMaturity);
            if (random.nextDouble() < thisProb) {
                offspring.setGene(i, this.genome[i], this.maturity[i]);
            } else {
                offspring.setGene(i, that.genome[i], that.maturity[i]);
            }
        }
        return offspring;
    }

//    /**
//     * Calculate the fitness as the arithmetic mean the individual fitnesses of the estimation subjects.
//     */
//    double calcluateSubjectbasedFitness(GeneticOptimizer geneticOptimizer) {
//
//        Map<Object, FitnessAggregator> subjectAggregators = new HashMap<>();
//        for (PartialExecution partialExecution : geneticOptimizer.getData()) {
//            // Calculate values for the given partialExecution
//            double timeEstimate = this.estimateTime(
//                    partialExecution,
//                    geneticOptimizer.getEstimators(),
//                    geneticOptimizer.getPlatformOverheads(),
//                    geneticOptimizer.getConfiguration()
//            );
//            double partialFitness = this.calculateRelativeDelta(timeEstimate, partialExecution.getMeasuredExecutionTime());
//            double weight = Math.log(Math.max(timeEstimate, partialExecution.getMeasuredExecutionTime()) + 2d) / Math.log(2);
////            double weight = Math.max(timeEstimate.getGeometricMeanEstimate(), partialExecution.getMeasuredExecutionTime()) + 1;
//
//            // Attribute the fitness to all involved subjects.
//            for (PartialExecution.OperatorExecution operatorExecution : partialExecution.getOperatorExecutions()) {
//                Object subject = operatorExecution.getOperator().getClass();
//                final FitnessAggregator aggregator = subjectAggregators.computeIfAbsent(subject, k -> new FitnessAggregator(0, 0));
//                aggregator.fitnessAccumulator += weight * partialFitness;
//                aggregator.weightAccumulator += weight;
//                aggregator.numObservations++;
//            }
//            for (Platform subject : partialExecution.getInitializedPlatforms()) {
//                final FitnessAggregator aggregator = subjectAggregators.computeIfAbsent(subject, k -> new FitnessAggregator(0, 0));
//                aggregator.fitnessAccumulator += weight * partialFitness;
//                aggregator.weightAccumulator += weight;
//                aggregator.numObservations++;
//            }
//        }
//
//        // Aggregate the fitness values of the different subjects.
//        FitnessAggregator aggregator = new FitnessAggregator(0, 0);
//        for (FitnessAggregator subjectAggregator : subjectAggregators.values()) {
//            double subjectFitness = subjectAggregator.fitnessAccumulator / subjectAggregator.weightAccumulator;
//            double subjectWeight = 1;//Math.log(1 + subjectAggregator.numObservations);
//            aggregator.fitnessAccumulator += subjectWeight * subjectFitness;
//            aggregator.weightAccumulator += subjectWeight;
//            aggregator.numObservations++;
//        }
//
//        return aggregator.fitnessAccumulator / aggregator.weightAccumulator;
//
//    }

//    private static class FitnessAggregator {
//
//        private double fitnessAccumulator;
//
//        private double weightAccumulator;
//
//        private int numObservations = 0;
//
//        public FitnessAggregator(double fitnessAccumulator, double weightAccumulator) {
//            this.fitnessAccumulator = fitnessAccumulator;
//            this.weightAccumulator = weightAccumulator;
//        }
//    }

    public void updateMaturity(Bitmask activatedGenes) {
        final double newMaturity = this.getFitness();
        for (int activatedGene = activatedGenes.nextSetBit(0);
             activatedGene != -1;
             activatedGene = activatedGenes.nextSetBit(activatedGene + 1)) {
            double currentMaturity = this.maturity[activatedGene];
            if (Double.isNaN(currentMaturity) || newMaturity > currentMaturity) {
                this.updateMaturity(activatedGene, newMaturity);
            }
        }
    }

    /**
     * Update the fitness of this instance.
     *
     * @param fitnessFunction calculates the fitness for this instance
     * @return the new fitness
     */
    public double updateFitness(ToDoubleFunction<Individual> fitnessFunction) {
        return this.fitness = fitnessFunction.applyAsDouble(this);
    }

    public double getFitness() {
        if (Double.isNaN(this.fitness)) {
            throw new IllegalStateException("The fitness of the individual has not yet been calculated.");
        }
        return this.fitness;
    }

    /**
     * Calculate the fitness as weighted harmonic mean of the relative prediction accuracies.
     */
    double calculateRelativeFitness(GeneticOptimizer geneticOptimizer) {
        // Some settings.
        double harmonicSmoothing = .1d;
        double weightSum = 0d;
        double fitnessSum = 0d;

        // Calculate the arithmetic mean of the partial fitnesses for each data point.
        for (PartialExecution partialExecution : geneticOptimizer.getData()) {
            // Estimate the time with the current variables.
            double timeEstimate = this.estimateTime(
                    partialExecution,
                    geneticOptimizer.getPlatformOverheads(),
                    geneticOptimizer.getConfiguration()
            );

            // Calculate the weight.
//            double weight = Math.log(partialExecution.getMeasuredExecutionTime() + 2d) / Math.log(2);
//            double weight = Math.sqrt(Math.max(timeEstimate, partialExecution.getMeasuredExecutionTime())) + 1;
            double weight = geneticOptimizer.calculateObservationBasedWeight(partialExecution);
//                    + geneticOptimizer.calculateRuntimeBasedWeight(partialExecution);

            // Calculate the partial fitness.
            double relativeDelta = this.calculateRelativeDelta(timeEstimate, partialExecution.getMeasuredExecutionTime());

            // Prepare mean calculation.
//            fitnessSum += weight / (partialFitness + harmonicSmoothing);
            fitnessSum += weight * (relativeDelta * relativeDelta);
            weightSum += weight;
        }
//        return (weightSum / fitnessSum) - harmonicSmoothing;
        return -Math.sqrt(fitnessSum) / weightSum;
    }

    private double calculateRelativeDelta(double timeEstimate, long actualTime) {
        // Get important values.
        final double smoothing = 1000d;
        final long meanEstimate = Math.round(timeEstimate);
        final long delta = Math.abs(meanEstimate - actualTime);
        return (delta + smoothing) / (actualTime + smoothing);
    }

    /**
     * Calculate the fitness as weighted arithmetic mean of the absolute prediction accuracies.
     */
    double calculateAbsoluteFitness(GeneticOptimizer geneticOptimizer) {
        double weightSum = 0d;
        double fitnessSum = 0d;
        for (PartialExecution partialExecution : geneticOptimizer.getData()) {
            double timeEstimate = this.estimateTime(
                    partialExecution,
                    geneticOptimizer.getPlatformOverheads(),
                    geneticOptimizer.getConfiguration()
            );
            double weight = geneticOptimizer.calculateObservationBasedWeight(partialExecution)
                    + 3 * geneticOptimizer.calculateRuntimeBasedWeight(partialExecution);
            double partialFitness = this.calculateAbsolutePartialFitness(timeEstimate, partialExecution.getMeasuredExecutionTime());
            weightSum += weight;
            fitnessSum += weight * -(partialFitness * partialFitness);
        }
        return fitnessSum / weightSum;
    }

    private double calculateAbsolutePartialFitness(double timeEstimate, long actualTime) {
        final long delta = Math.abs(Math.round(timeEstimate) - actualTime);
        return -delta;
    }

    double estimateTime(PartialExecution partialExecution,
                        Map<Platform, Variable> platformOverheads,
                        Configuration configuration) {
        final DoubleStream operatorEstimates = partialExecution.getAtomicExecutionGroups().stream()
                .map(atomicExecutionGroup -> this.estimateTime(atomicExecutionGroup, configuration))
                .mapToDouble(TimeEstimate::getGeometricMeanEstimate);
        final DoubleStream platformEstimates = partialExecution.getInitializedPlatforms().stream()
                .mapToDouble(p -> {
                    final Variable variable = platformOverheads.get(p);
                    return variable == null ? 0d : variable.getValue(this);
                });
        return DoubleStream.concat(operatorEstimates, platformEstimates).sum();
    }

    /**
     * Estimates the execution time for the given {@link AtomicExecutionGroup} with the genome of this instance.
     *
     * @param executionGroup the {@link AtomicExecutionGroup}
     * @param configuration  provides estimation context
     * @return the {@link TimeEstimate}
     */
    private TimeEstimate estimateTime(AtomicExecutionGroup executionGroup,
                                      Configuration configuration) {
        final EstimationContext estimationContext = executionGroup.getEstimationContext();
        return executionGroup.estimateExecutionTime(new DynamicEstimationContext(this, estimationContext));
    }
}


text:
require 'spec_helper'

describe Minke::Generators::ConfigProcessor do

  let (:variable_replacements) do
    Minke::Generators::ConfigVariables.new.tap do |cv|
      cv.src_root = "/src/mypath"
      cv.namespace = "namespace"
      cv.application_name = "myapp"
    end
  end

  let(:generator_config) do
    config = Minke::Generators::Config.new
    config.name = 'test generator'
    config.template_location = './somewhere'

    config.generate_settings = Minke::Generators::GenerateSettings.new.tap do |s|
      s.command = 'mycommand'
      s.docker_image = 'myimage'
      s.docker_file = './soemthing/something'
    end

    config.build_settings = Minke::Generators::BuildSettings.new.tap do |s|
      s.build_commands = Minke::Generators::BuildCommands.new.tap do |b|
        b.fetch = ['stuff']
        b.build = ['build', 'stuff']
        b.test = ['test stuff']
      end

      s.docker_settings = Minke::Generators::DockerSettings.new.tap do |d|
        d.image = 'dockerimage:latest'
        d.env = ['BLAH=BLAH']
        d.binds = ['/src:/src']
        d.working_directory = '/src'
      end
    end

    return config
  end

  let(:generate_settings) { generator_config.generate_settings }
  let(:build_settings) { generator_config.build_settings }
  let(:build_commands) { build_settings.build_commands }
  let(:docker_settings) { build_settings.docker_settings }

  def process config
    processor = Minke::Generators::ConfigProcessor.new variable_replacements
    processor.process config
  end

  describe '<%= src_root %> replacements' do
    it 'replaces <%= src_root %> in template_location' do
      generator_config.template_location = '<%= src_root %>/subfolder'
      process generator_config

      expect(generator_config.template_location).to eq("#{variable_replacements.src_root}/subfolder")
    end

    it 'replaces <%= src_root %> in generate_settings.command' do
      generate_settings.command = 'build -o <%= src_root %>'
      process generator_config

      expect(generator_config.generate_settings.command).to eq("build -o #{variable_replacements.src_root}")
    end

    it 'replaces <%= src_root %> in generate_settings.command' do
      generate_settings.docker_file = '<%= src_root %>/dockerfile'
      process generator_config

      expect(generator_config.generate_settings.docker_file).to eq("#{variable_replacements.src_root}/dockerfile")
    end

    it 'replaces <%= src_root %> in build_settings.build_commands.fetch' do
      build_commands.fetch = ['fetch <%= src_root %>']
      process generator_config

      expect(generator_config.build_settings.build_commands.fetch).to eq(["fetch #{variable_replacements.src_root}"])
    end

    it 'replaces <%= src_root %> in build_settings.build_commands.build' do
      build_commands.build = ['build <%= src_root %>']
      process generator_config

      expect(generator_config.build_settings.build_commands.build).to eq(["build #{variable_replacements.src_root}"])
    end

    it 'replaces <%= src_root %> in build_settings.build_commands.test' do
      build_commands.test = ['test <%= src_root %>', 'test2 <%= src_root %>']
      process generator_config

      expect(generator_config.build_settings.build_commands.test).to eq(
        ["test #{variable_replacements.src_root}", "test2 #{variable_replacements.src_root}"])
    end

    it 'replaces <%= src_root %> in build_settings.docker_settings.image' do
      docker_settings.image = 'image <%= src_root %>'
      process generator_config

      expect(generator_config.build_settings.docker_settings.image).to eq("image #{variable_replacements.src_root}")
    end

    it 'replaces <%= src_root %> in build_settings.docker_settings.env' do
      docker_settings.env = ['test=<%= src_root %>', 'test2=<%= src_root %>']
      process generator_config

      expect(generator_config.build_settings.docker_settings.env).to eq(
        ["test=#{variable_replacements.src_root}", "test2=#{variable_replacements.src_root}"])
    end

    it 'replaces <%= src_root %> in build_settings.docker_settings.binds' do
      docker_settings.binds = ['test:<%= src_root %>', 'test2:<%= src_root %>']
      process generator_config

      expect(generator_config.build_settings.docker_settings.binds).to eq(
        ["test:#{variable_replacements.src_root}", "test2:#{variable_replacements.src_root}"])
    end

    it 'replaces <%= src_root %> in build_settings.docker_settings.working_directory' do
      docker_settings.working_directory = '/test:<%= src_root %>'
      process generator_config

      expect(generator_config.build_settings.docker_settings.working_directory).to eq("/test:#{variable_replacements.src_root}")
    end

  end
end


text:
package a

import (
	"c"
	"go/token"

	"golang.org/x/tools/go/analysis"
)

var Analyzer = &analysis.Analyzer{
	Name:     "a",
	Doc:      "an analyzer that depends on c.Analyzer",
	Run:      run,
	Requires: []*analysis.Analyzer{c.Analyzer},
}

func run(pass *analysis.Pass) (interface{}, error) {
	pass.Reportf(token.NoPos, "a %s", pass.ResultOf[c.Analyzer])
	return nil, nil
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>JSDoc: Source: book.js</title>

    <link type="text/css" rel="stylesheet" href="styles/prettify-tomorrow.css">
    <link type="text/css" rel="stylesheet" href="styles/jsdoc-default.css">

Source: book.js

/**
 * This class represents a bookkeeping book that holds verifications on account changes.
 */

"use strict";

var _ = require("lodash");
var Account = require("./account.js");
var Verification = require("./verification.js");
var dateUtils = require("./date/date-utils.js");
var ExtensionHandler = require("./extension/extension-handler");
var FiscalYearHandler = require("./fiscal-year-handler");

module.exports = Book;

/**
 * Creates a bookkeeping book that holds verifications on account changes.
 * @constructor
 * @public
 */
function Book() {
    this.extensionHandler = new ExtensionHandler();
    this.fiscalYearHandler = new FiscalYearHandler();

    //The accounts of the book are stored as the account number as key.
    this.accounts = {};

    //The array of verifications. Verification number is key.
    this.verifications = {};
    this.numVerifications = 0;

    this.classifiers = {};
}

/**
 * Register an extension to be used by this book.
 * @public
 * @param {Extension} extension The extension object to be used.
 * @returns {Book} This book instance for chaining.
 */
Book.prototype.use = function(extension) {
    this.extensionHandler.register(this, extension);
    return this;
};

/**
 * Tells if an extension is being used by this book.
 * @public
 * @param {string|Extension} extension The extension to be checked if being used. If string, it will be used as name of the extension.
 * @returns {boolean} True if the extension is being used in this book.
 */
Book.prototype.using = function(extension) {
    return this.extensionHandler.isRegistered(extension);
};

/**
 * Gets the extension by the given extension name.
 * @param {string} name The name of the extension to get.
 * @returns The extension object with the given name. Returns null if it doesn't exist.
 */
Book.prototype.getExtension = function(name) {
    return this.extensionHandler.get(name);
};

/**
 * Creates a new {@link Account} and adds it to the book.
 * @public
 * @param {number} number The account number. Must be unique in the context of the book.
 * @param {string} name The account name. Must be unique in the context of the book.
 * @returns {Account} The created account.
 */
Book.prototype.createAccount = function(number, name) {
    if(this.accounts[number]) {
        throw new Error("An account with number " + number + "already exists.");
    }

    var account = new Account(this, number, name);
    this.accounts[number] = account;

    return account;
};

/**
 * Gets the {@link Account} with the given account number.
 * @public
 * @param {number} number The account number of the account to get.
 * @returns {?Account} The account with the given account number. Returns null if the given number didn't match any account in the book.
 */
Book.prototype.getAccount = function(number) {
    if(!_.isNumber(number)) {
        throw new Error("Invalid account number.");
    }

    var account = this.accounts[number];

    return account || null;
};

/**
 * Creates a {@link Verification} and adds it to the book. The book will decide which verification number the verification should have.
 * @public
 * @param {date|string} date The date that the verification happened. If string, it will be parsed to a date.
 * @param {string} text The text describing the verification.
 * @returns {Verification} The created verification.
 */
Book.prototype.createVerification = function(date, text) {
    var verification = new Verification(this, dateUtils.parse(date), text);

    var key = verification.number;

    if(this.verifications[key]) {
        throw new Error("Internal verification numbering error.");
    }

    this.verifications[key] = verification;
    this.numVerifications++;

    //Let the extensions do their work on the verification before returning it.
    var args = Array.prototype.slice.call(arguments);
    args.unshift(verification);
    args.unshift(this);

    this.extensionHandler.callMethods("createVerification", args);

    return verification;
};

/**
 * Gets a {@link Verification} given a verification number.
 * @public
 * @param {number} number The number of the verification to retrieve.
 * @returns {?Verification} The verification with the given verification number. If it doesn't exist null will be returned.
 */
Book.prototype.getVerification = function(number) {
    return this.verifications[number] || null;
};

/**
 * Gets an Array of all {@link Verification}'s in the given date range.
 * @public
 * @param {?(date|string)} from The lower inclusive bound of the date range of verifications retrieved. Will be parsed if string. If null there is no lower bound.
 * @param {?(data|string)} to The higher inclusive bound of the date range of the verifications retrieved. Will be parsed if string. If null there is no higher bound.
 * @returns {Verification[]} All verifications in the given date range.
 */
Book.prototype.getVerifications = function(from, to) {
    return _.filter(this.verifications, function(v) {
        return dateUtils.isInsideDates(v.date, from, to);
    });
};

/**
 * Gets the next {@link Verification} number that the next added verification will get.
 * @private
 * @returns {number} The next verification number.
 */
Book.prototype.getNextVerificationNumber = function() {
    return this.numVerifications + 1;
};

/**
 * Adds an account classifier function to the book.
 * @public
 * @param {string} type The type of the classifier. The type must be unique in the context of the book.
 * @param {function} classifier The classifier function to be added to the book.
 * @returns {Book} The book instance for chaining.
 */
Book.prototype.addClassifier = function(type, classifier) {
    if(!_.isString(type)) {
        throw new Error("Invalid type.");
    }

    if(!_.isFunction(classifier)) {
        throw new Error("Classifier function required.");
    }

    if(!_.isArray(this.classifiers[type])) {
        this.classifiers[type] = [];
    }

    this.classifiers[type].push(classifier);

    return this;
};

/**
 * Gets an array of {@link Account}'s. If a classifier type is given, only the accounts meeting the classifiers of the given type will be retrieved.
 * @param {?string} type The classifier type to use for filtering the returned accounts.
 * @returns {Account[]} The array of accounts given classifier type.
 */
Book.prototype.getAccounts = function(type) {
    var result = [];

    var classifiers = this.classifiers[type] || [];

    if(type && !classifiers.length) {
        throw new Error("Invalid classifier type: " + type);
    }

    _.forEach(this.accounts, function(account) {
        var good = true;
        classifiers.forEach(function(classifier) {
            return (good = classifier(account));
        });

        if(good) {
            result.push(account);
        }
    });

    return result;
};

/**
 * Tells about problems in the book. Will generate an array of warnings.
 * @public
 * @returns {string[]} An array containing string warnings about problems in the book.
 */
Book.prototype.doctor = function() {
    function unbalancedVerifications(verifications) {
        var unbalanced = _.filter(verifications, function(verification) {
            return !verification.isBalancedCreditDebit();
        });

        return _.map(unbalanced, function(verification) {
            return "Invalid verification: " + verification.number + " is unbalanced.";
        });
    }

    function verificationsOutOfFiscalYears(verifications, fiscalYears) {
        if(!fiscalYears.length) {
            if(_.size(verifications)) {
                return ["Verifications exists without any fiscal years present."];
            }

            return [];
        }

        var start = (_.first(fiscalYears)).from;
        var end = (_.last(fiscalYears)).to;

        var out = _.filter(verifications, function(verification) {
            return verification.date < start || verification.date > end;
        });

        return _.map(out, function(verification) {
            return "Verification out of fiscal years range. Verification: " + verification.number + ". Fiscal year range: " + dateUtils.stringify(start) + " to " + dateUtils.stringify(end) + ".";
        });
    }

    var result = [];

    result = result.concat(unbalancedVerifications(this.verifications));
    result = result.concat(verificationsOutOfFiscalYears(this.verifications, this.fiscalYearHandler.getAll()));

    _.forEach(this.extensionHandler.getMethods("doctor"), function(method) {
        result = result.concat(method(this));
    });

    return result;
};

Book.prototype.export = function() {

};

/**
 * Creates a {@link FiscalYear} and adds it to the book. All fiscal years must be adjacent to each other in the book.
 * @public
 * @param {date|string} from The lower inclusive bound of the fiscal year. If string, it will be parsed to a date.
 * @param {data|string} to The higher inclusive bound of the fiscal year. If string, it will be parsed to a date.
 * @returns {FiscalYear} The created fiscal year.
 * @throws If an invalid date range is give.
 */
Book.prototype.createFiscalYear = function(from, to) {
    var fiscalYear = this.fiscalYearHandler.create(from, to);

    //Let the extensions do their work on the fiscal year.
    var args = Array.prototype.slice.call(arguments);
    args.unshift(fiscalYear);
    args.unshift(this);
    this.extensionHandler.callMethods("createFiscalYear", args);

    return fiscalYear;
};

/**
 * Returns the {@link FiscalYear} that matches the selector.
 * @public
 * @param {number|date|string} selector If date or date string given, the fiscal year that contains the date will be returned. If selector is number it will retrieve the fiscal year at the number position in the fiscal year range (1 is first). If string, it will be parsed to a date.
 * @return {?FiscalYear} Returns the fiscal year that matched to selector. If not found null will be returned.
 */
Book.prototype.getFiscalYear = function(selector) {
    return this.fiscalYearHandler.get(selector);
};

/**
 * Gets the chronologically last {@link FiscalYear}.
 * @public
 * @returns {?FiscalYear} The chronologically last fiscal year. If no fiscal years present, null will be returned.
 */
Book.prototype.getLastFiscalYear = function() {
    return this.fiscalYearHandler.getLast();
};

Home

Modules

bookie

bookie/date

bookie/financialUtils

bookie/numberUtils

Classes

Account

Book

Extension

ExtensionHandler

FiscalYear

FiscalYearHandler

Verification

    Documentation generated by JSDoc 3.3.0-alpha11 on Sat Jan 17 2015 21:48:19 GMT+0100 (CET)


text:
(function( $ ){
	$(document).ready(function(){
		$("#suckerfishnav li").hover(
			function() { $(this).addClass("sfhover");},
			function() { $(this).removeClass("sfhover");}
		);
		$("#suckerfishnav a").focus(function(){$(this).parents("li").addClass("sfhover");}).blur(function(){$(this).parents("li").removeClass("sfhover");});
		$("#suckerfishnav_2 a").focus(function(){$(this).parents("li").addClass("sfhover");}).blur(function(){$(this).parents("li").removeClass("sfhover");});
	});
})( jQuery );


text:
<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Smart Home</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/vis/4.18.1/vis.min.css"></link>
    <link rel="stylesheet" href="index.css"></link>


text:
$('#bw-book-content').click(function() {
                down(true);
});


text:
SYNONYM

#### According to
Index Fungorum

#### Published in
null

#### Original name
Lactarius torminosus var. glabra Murrill

### Remarks
null


text:
package org.opencb.biodata.models.alignment;

public class ExonCoverageStats {

    private String id;
    private String chromosome;
    private int start;
    private int end;
    private double depthAvg;
    private double depthMin;
    private double depthMax;

    public ExonCoverageStats() {
    }

    public ExonCoverageStats(String id, String chromosome, int start, int end, double depthAvg, double depthMin, double depthMax) {
        this.id = id;
        this.chromosome = chromosome;
        this.start = start;
        this.end = end;
        this.depthAvg = depthAvg;
        this.depthMin = depthMin;
        this.depthMax = depthMax;
    }

    @Override
    public String toString() {
        final StringBuilder sb = new StringBuilder("ExonCoverageStats{");
        sb.append("id='").append(id).append('\'');
        sb.append(", chromosome='").append(chromosome).append('\'');
        sb.append(", start=").append(start);
        sb.append(", end=").append(end);
        sb.append(", depthAvg=").append(depthAvg);
        sb.append(", depthMin=").append(depthMin);
        sb.append(", depthMax=").append(depthMax);
        sb.append('}');
        return sb.toString();
    }

    public String getId() {
        return id;
    }

    public ExonCoverageStats setId(String id) {
        this.id = id;
        return this;
    }

    public String getChromosome() {
        return chromosome;
    }

    public ExonCoverageStats setChromosome(String chromosome) {
        this.chromosome = chromosome;
        return this;
    }

    public int getStart() {
        return start;
    }

    public ExonCoverageStats setStart(int start) {
        this.start = start;
        return this;
    }

    public int getEnd() {
        return end;
    }

    public ExonCoverageStats setEnd(int end) {
        this.end = end;
        return this;
    }

    public double getDepthAvg() {
        return depthAvg;
    }

    public ExonCoverageStats setDepthAvg(double depthAvg) {
        this.depthAvg = depthAvg;
        return this;
    }

    public double getDepthMin() {
        return depthMin;
    }

    public ExonCoverageStats setDepthMin(double depthMin) {
        this.depthMin = depthMin;
        return this;
    }

    public double getDepthMax() {
        return depthMax;
    }

    public ExonCoverageStats setDepthMax(double depthMax) {
        this.depthMax = depthMax;
        return this;
    }
}


text:
//
//  NSObject+IBAExtensions.m
//  IttyBittyBits
//
//  Created by Oliver Jones on 7/07/11.
//  Copyright 2011 Itty Bitty Apps Pty. Ltd. All rights reserved.
//
//  Licensed under the Apache License, Version 2.0 (the "License");
//  you may not use this file except in compliance with the License.
//  You may obtain a copy of the License at
//
//    http://www.apache.org/licenses/LICENSE-2.0
//
//  Unless required by applicable law or agreed to in writing, software
//  distributed under the License is distributed on an "AS IS" BASIS,
//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//  See the License for the specific language governing permissions and
//  limitations under the License.

#import "NSObject+IBAExtensions.h"

@implementation NSObject (IBAExtensions)

/*!
 \brief     Creates an instance of this class with its properties populated KVC-style with the keys and values of the passed dictionary

 \param     dictionary
 A dictionary whose keys and values are mapped to the properties of the instance returned by this method.

 \return    A new instance of this class.
  */
+ (id)ibaInstanceFromDictionary:(NSDictionary *)dictionary
{
    id result = [[[self class] alloc] init];
    [result setValuesForKeysWithDictionary:dictionary];

    return [result autorelease];
}

/*!
 \brief     Registers \ anObserver to receive KVO notifications for the specified \a keyPaths relative to the receiver.
 \details   Neither the receiver, nor anObserver, are retained.

 \param     anObserver
 The object to register for KVO notifications. The observer must implement the key-value observing method observeValueForKeyPath:ofObject:change:context:.

 \param     keyPaths
 The key paths, relative to the receiver, of the properties to observe. This value must not be nil.

 \param     options
 A combination of the NSKeyValueObservingOptions values that specifies what is included in observation notifications.

 \param     context
 Arbitrary data that is passed to anObserver in observeValueForKeyPath:ofObject:change:context:.

 \sa        ibaRemoveObserver:forKeyPaths:
 */
- (void)ibaAddObserver:(NSObject *)anObserver forKeyPaths:(NSArray *)keyPaths options:(NSKeyValueObservingOptions)options context:(void *)context
{
    for (NSString *keyPath in keyPaths)
    {
        [self addObserver:anObserver forKeyPath:keyPath options:options context:context];
    }
}

/*!
 \brief     Stops a given object from receiving change notifications for the properties specified by a given keyPaths relative to the receiver.
 \param      anObserver
 The object to remove as an observer.

 \param     keyPaths
 The key-paths, relative to the receiver, for which anObserver is registered to receive KVO change notifications.

 \sa        ibaAddObserver:forKeyPaths:options:context:
 */
- (void)ibaRemoveObserver:(NSObject *)anObserver forKeyPaths:(NSArray *)keyPaths
{
    for (NSString *keyPath in keyPaths)
    {
        [self removeObserver:anObserver forKeyPath:keyPath];
    }
}

@end


text:
/**
 * Pipedrive API v1
 * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
 *
 * The version of the OpenAPI document: 1.0.0
 *
 *
 * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
 * https://openapi-generator.tech
 * Do not edit the class manually.
 *
 */

import ApiClient from '../ApiClient';
import BaseResponse from './BaseResponse';
import FullRole from './FullRole';
import GetRolesAllOf from './GetRolesAllOf';
import RolesAdditionalData from './RolesAdditionalData';

/**
 * The GetRoles model module.
 * @module model/GetRoles
 * @version 1.0.0
 */
class GetRoles {
    /**
     * Constructs a new GetRoles.
     * @alias module:model/GetRoles
     * @implements module:model/BaseResponse
     * @implements module:model/GetRolesAllOf
     */
    constructor() {
        BaseResponse.initialize(this);GetRolesAllOf.initialize(this);
        GetRoles.initialize(this);
    }

    /**
     * Initializes the fields of this object.
     * This method is used by the constructors of any subclasses, in order to implement multiple inheritance (mix-ins).
     * Only for internal use.
     */
    static initialize(obj) {
    }

    /**
     * Constructs a GetRoles from a plain JavaScript object, optionally creating a new instance.
     * Copies all relevant properties from data to obj if supplied or a new instance if not.
     * @param {Object} data The plain JavaScript object bearing properties of interest.
     * @param {module:model/GetRoles} obj Optional instance to populate.
     * @return {module:model/GetRoles} The populated GetRoles instance.
     */
    static constructFromObject(data, obj) {
        if (data) {
            obj = obj || new GetRoles();
            BaseResponse.constructFromObject(data, obj);
            GetRolesAllOf.constructFromObject(data, obj);

            if (data.hasOwnProperty('success')) {
                obj['success'] = ApiClient.convertToType(data['success'], 'Boolean');

                delete data['success'];
            }
            if (data.hasOwnProperty('data')) {
                obj['data'] = ApiClient.convertToType(data['data'], [FullRole]);

                delete data['data'];
            }
            if (data.hasOwnProperty('additional_data')) {
                obj['additional_data'] = RolesAdditionalData.constructFromObject(data['additional_data']);

                delete data['additional_data'];
            }

            if (Object.keys(data).length > 0) {
                Object.assign(obj, data);
            }

        }
        return obj;
    }

}

/**
 * If the response is successful or not
 * @member {Boolean} success
 */
GetRoles.prototype['success'] = undefined;

/**
 * The array of roles
 * @member {Array.<module:model/FullRole>} data
 */
GetRoles.prototype['data'] = undefined;

/**
 * @member {module:model/RolesAdditionalData} additional_data
 */
GetRoles.prototype['additional_data'] = undefined;

// Implement BaseResponse interface:
/**
 * If the response is successful or not
 * @member {Boolean} success
 */
BaseResponse.prototype['success'] = undefined;
// Implement GetRolesAllOf interface:
/**
 * The array of roles
 * @member {Array.<module:model/FullRole>} data
 */
GetRolesAllOf.prototype['data'] = undefined;
/**
 * @member {module:model/RolesAdditionalData} additional_data
 */
GetRolesAllOf.prototype['additional_data'] = undefined;

export default GetRoles;


text:
import unittest

import mock
import requests

from ironic_discoverd_ramdisk import discover
from ironic_discoverd_ramdisk import main
from ironic_discoverd_ramdisk.test import test_discover

FAKE_ARGS = test_discover.get_fake_args()

class TestParseArgs(unittest.TestCase):
    def test(self):
        args = ['-d', 'http://url']
        parsed_args = main.parse_args(args)
        self.assertEqual('http://url', parsed_args.callback_url)
        self.assertTrue(parsed_args.daemonize_on_failure)

    def test_log_files(self):
        args = ['-L', 'log1', '-L', 'log2', 'url']
        parsed_args = main.parse_args(args)
        self.assertEqual(['log1', 'log2'],
                         parsed_args.system_log_file)

@mock.patch.object(main, 'setup_logging', lambda args: None)
@mock.patch.object(main, 'parse_args', return_value=FAKE_ARGS,
                   autospec=True)
@mock.patch.object(discover, 'fork_and_serve_logs', autospec=True)
@mock.patch.object(discover, 'setup_ipmi_credentials', autospec=True)
@mock.patch.object(discover, 'call_discoverd', autospec=True,
                   return_value={})
@mock.patch.object(discover, 'collect_logs', autospec=True)
@mock.patch.object(discover, 'discover_hardware', autospec=True)
class TestMain(unittest.TestCase):
    def test_success(self, mock_discover, mock_logs, mock_callback,
                     mock_setup_ipmi, mock_fork_serve, mock_parse):
        mock_logs.return_value = 'LOG'

        main.main()

        # FIXME(dtantsur): mock does not copy arguments, so the 2nd argument
        # actually is not what we expect ({})
        mock_discover.assert_called_once_with(FAKE_ARGS, mock.ANY, mock.ANY)
        mock_logs.assert_called_once_with(FAKE_ARGS)
        mock_callback.assert_called_once_with(FAKE_ARGS, {'logs': 'LOG'},
                                              mock.ANY)
        self.assertFalse(mock_fork_serve.called)
        self.assertFalse(mock_setup_ipmi.called)

    def test_discover_fails(self, mock_discover, mock_logs, mock_callback,
                            mock_setup_ipmi, mock_fork_serve, mock_parse):
        mock_logs.return_value = 'LOG'
        mock_discover.side_effect = RuntimeError('boom')

        self.assertRaisesRegexp(SystemExit, '1', main.main)

        mock_discover.assert_called_once_with(FAKE_ARGS, mock.ANY, mock.ANY)
        mock_logs.assert_called_once_with(FAKE_ARGS)
        mock_callback.assert_called_once_with(FAKE_ARGS, {'logs': 'LOG'},
                                              mock.ANY)
        failures = mock_callback.call_args[0][2]
        self.assertIn('boom', failures.get_error())
        mock_fork_serve.assert_called_once_with(FAKE_ARGS)

    def test_collect_logs_fails(self, mock_discover, mock_logs, mock_callback,
                                mock_setup_ipmi, mock_fork_serve, mock_parse):
        mock_logs.side_effect = RuntimeError('boom')

        main.main()

        mock_discover.assert_called_once_with(FAKE_ARGS, mock.ANY, mock.ANY)
        mock_logs.assert_called_once_with(FAKE_ARGS)
        mock_callback.assert_called_once_with(FAKE_ARGS, {}, mock.ANY)
        self.assertFalse(mock_fork_serve.called)

    def test_callback_fails(self, mock_discover, mock_logs, mock_callback,
                            mock_setup_ipmi, mock_fork_serve, mock_parse):
        mock_logs.return_value = 'LOG'
        mock_callback.side_effect = requests.HTTPError('boom')

        self.assertRaisesRegexp(SystemExit, '1', main.main)

        mock_discover.assert_called_once_with(FAKE_ARGS, mock.ANY, mock.ANY)
        mock_logs.assert_called_once_with(FAKE_ARGS)
        mock_callback.assert_called_once_with(FAKE_ARGS, {'logs': 'LOG'},
                                              mock.ANY)
        mock_fork_serve.assert_called_once_with(FAKE_ARGS)

    def test_callback_fails2(self, mock_discover, mock_logs, mock_callback,
                             mock_setup_ipmi, mock_fork_serve, mock_parse):
        mock_logs.return_value = 'LOG'
        mock_callback.side_effect = RuntimeError('boom')

        self.assertRaisesRegexp(SystemExit, '1', main.main)

        mock_discover.assert_called_once_with(FAKE_ARGS, mock.ANY, mock.ANY)
        mock_logs.assert_called_once_with(FAKE_ARGS)
        mock_callback.assert_called_once_with(FAKE_ARGS, {'logs': 'LOG'},
                                              mock.ANY)
        mock_fork_serve.assert_called_once_with(FAKE_ARGS)

    def test_no_daemonize(self, mock_discover, mock_logs, mock_callback,
                          mock_setup_ipmi, mock_fork_serve, mock_parse):
        new_fake_args = test_discover.get_fake_args()
        new_fake_args.daemonize_on_failure = None
        mock_parse.return_value = new_fake_args
        mock_logs.return_value = 'LOG'
        mock_callback.side_effect = RuntimeError('boom')

        self.assertRaisesRegexp(SystemExit, '1', main.main)

        mock_discover.assert_called_once_with(new_fake_args, mock.ANY,
                                              mock.ANY)
        mock_logs.assert_called_once_with(new_fake_args)
        mock_callback.assert_called_once_with(new_fake_args, {'logs': 'LOG'},
                                              mock.ANY)
        self.assertFalse(mock_fork_serve.called)

    def test_setup_ipmi(self, mock_discover, mock_logs, mock_callback,
                        mock_setup_ipmi, mock_fork_serve, mock_parse):
        mock_logs.return_value = 'LOG'
        mock_callback.return_value = {'ipmi_setup_credentials': True}

        main.main()

        mock_discover.assert_called_once_with(FAKE_ARGS, mock.ANY, mock.ANY)
        mock_logs.assert_called_once_with(FAKE_ARGS)
        mock_callback.assert_called_once_with(FAKE_ARGS, {'logs': 'LOG'},
                                              mock.ANY)
        mock_setup_ipmi.assert_called_once_with(mock_callback.return_value)
        self.assertFalse(mock_fork_serve.called)

    def test_setup_ipmi_fails(self, mock_discover, mock_logs, mock_callback,
                              mock_setup_ipmi, mock_fork_serve, mock_parse):
        mock_logs.return_value = 'LOG'
        mock_callback.return_value = {'ipmi_setup_credentials': True}
        mock_setup_ipmi.side_effect = RuntimeError('boom')

        self.assertRaisesRegexp(SystemExit, '1', main.main)

        mock_discover.assert_called_once_with(FAKE_ARGS, mock.ANY, mock.ANY)
        mock_logs.assert_called_once_with(FAKE_ARGS)
        mock_callback.assert_called_once_with(FAKE_ARGS, {'logs': 'LOG'},
                                              mock.ANY)
        mock_setup_ipmi.assert_called_once_with(mock_callback.return_value)
        mock_fork_serve.assert_called_once_with(FAKE_ARGS)


text:
[Home](../README.md)

# Browser
WebTester provides an abstraction layer on top of Selenium's WebDriver called (rather fittingly) `Browser`.

## Interfaces
There are several important interfaces related to browsers.

**Browser:**
A `Browser` provides a streamlined and context centric API for the interaction with a web browser.
It is the main entry point to the framework.

**BrowserBuilder:**
A `BrowserBuilder` provides a builder API for initializing `Browser` instances and setting custom service implementations
like the [`Configuration`](configuration.md).

## The Web Driver Browser
The `WebDriverBrowser` class implements `Browser` and is used to wrap a Selenium `WebDriver`.
Instances can be created by using the `WebDriverBrowser's` factory methods:

1. `WebDriverBrowser.forWebDriver(webDriver).build();`
2. `WebDriverBrowser.buildForWebDriver(webDriver);`

Both of these are equal. The first method can be used to customize same aspects of the browser before it is build.

## Examples
**Initialization of a new WebDriverBrowser instance:**
```java
WebDriver webDriver = createWebDriver();
Browser browser = WebDriverBrowser.buildForWebDriver(webDriver);
Browser browser = WebDriverBrowser.forWebDriver(webDriver).build();
Browser browser = new WebDriverBrowserBuilder(webDriver).build();
```
**Initialization of a new WebDriverBrowser instance with custom service implementations:**
```java
Configuration config = createConfiguration();
PageObjectFactory factory = createFactory();

Browser browser = WebDriverBrowser.forWebDriver(webDriver)
                        .withConfiguration(config)
                        .withFactory(factory)
                        .build();

Browser browser = new WebDriverBrowserBuilder(webDriver)
                        .withConfiguration(config)
                        .withFactory(factory)
                        .build();
```

# Linked Documentation

- [Configuration](configuration.md)
- [Browser Factories](browser-factories.md)


text:
<?php

namespace Xabbuh\XApi\Bundle\ClientBundle\Tests\DependencyInjection;

use Symfony\Component\DependencyInjection\ParameterBag\ParameterBag;
use Xabbuh\XApi\Bundle\ClientBundle\DependencyInjection\XabbuhXApiClientExtension;

/**
 * @author Christian Flothmann <christian.flothmann@xabbuh.de>
 */
class XabbuhXApiClientExtensionTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var XabbuhXApiClientExtension
     */
    private $extension;

    /**
     * @var \PHPUnit_Framework_MockObject_MockObject
     */
    private $containerBuilder;

    protected function setUp()
    {
        $this->extension = new XabbuhXApiClientExtension();
        $this->containerBuilder = $this->createContainerBuilderMock();
    }

    public function testHasClientManagerDefinition()
    {
        $this->containerBuilder
            ->expects($this->once())
            ->method('setDefinition')
            ->with('xabbuh_xapi_client.client_manager', $this->anything());

        $this->loadConfiguration(array());
    }

    public function testClientsParameterWithoutClients()
    {
        $this->containerBuilder
            ->expects($this->once())
            ->method('setParameter')
            ->with('xabbuh_xapi_client.clients', array());

        $this->loadConfiguration(array());
    }

    public function testClientsParameterWithOneClient()
    {
        $this->containerBuilder
            ->expects($this->once())
            ->method('setParameter')
            ->with(
                'xabbuh_xapi_client.clients',
                array('foo' => 'xabbuh_xapi_client.client.foo')
            );

        $this->loadConfiguration(array(
            'clients' => array(
                'foo' => array(
                    'base_url' => 'http://example.com/xapi',
                ),
            ),
        ));
    }

    public function testClientsParameterWithMultipleClients()
    {
        $this->containerBuilder
            ->expects($this->once())
            ->method('setParameter')
            ->with(
                'xabbuh_xapi_client.clients',
                array(
                    'foo' => 'xabbuh_xapi_client.client.foo',
                    'bar' => 'xabbuh_xapi_client.client.bar',
                )
            );

        $this->loadConfiguration(array(
            'clients' => array(
                'foo' => array(
                    'base_url' => 'http://example.com/xapi',
                ),
                'bar' => array(
                    'base_url' => 'http://example.com/xapi',
                ),
            ),
        ));
    }

    public function testBundleAlias()
    {
        $this->assertEquals('xabbuh_xapi_client', $this->extension->getAlias());
    }

    private function createContainerBuilderMock()
    {
        $containerBuilder = $this->getMockBuilder('\Symfony\Component\DependencyInjection\ContainerBuilder')
            ->setMethods(array('getParameterBag', 'setParameter', 'setDefinition'))
            ->getMock();
        $containerBuilder->expects($this->any())
            ->method('getParameterBag')
            ->will($this->returnValue(new ParameterBag()));

        return $containerBuilder;
    }

    private function loadConfiguration($config)
    {
        $this->extension->load(array($config), $this->containerBuilder);
    }
}


text:
@interface TCCard ()
@property (nonatomic, strong) NSMutableDictionary *data;
@property (nonatomic, assign) BOOL sending;
@end

@implementation TCCard

@synthesize data;
@synthesize sending;

static const NSString *kTCCardDataFrontText = @"frontText";
static const NSString *kTCCardDataFrontImage = @"frontImage";
static const NSString *kTCCardDataFrontImagePath = @"frontImagePath";
static const NSString *kTCCardDataBackText = @"backText";
static const NSString *kTCCardDataBackImage = @"backImage";
static const NSString *kTCCardDataBackImagePath = @"backImagePath";
static const NSString *kTCCardDataScoreRight = @"scoredRight";
static const NSString *kTCCardDataScoreWrong = @"scoredWrong";
static const NSString *kTCCardDataScoreLatest = @"scoredLatest";
static const NSString *kTCCardData = @"data";

- (instancetype)init {
    self = [super init];
    if (self) {
        data = [NSMutableDictionary dictionaryWithCapacity:4];
    }
    return self;
}

- (instancetype)initWithCoder:(NSCoder *)coder {
    self = [[[self class] alloc] init];
    if (self) {
        data = [coder decodeObjectForKey:(NSString *)kTCCardData];
        UIImage *frontImage = data[kTCCardDataFrontImage];
        UIImage *backImage = data[kTCCardDataBackImage];
        // create files for images
        if(frontImage) self.frontImage = frontImage;
        if(backImage) self.backImage = backImage;
        // clear images from data
        [data setValue:nil forKey:(NSString *)kTCCardDataFrontImage];
        [data setValue:nil forKey:(NSString *)kTCCardDataBackImage];
    }
    return self;
}

- (void)encodeWithCoder:(NSCoder *)coder {
    NSString *frontImagePath;
    NSString *backImagePath;
    if(sending) {
        frontImagePath = data[kTCCardDataFrontImagePath];
        backImagePath = data[kTCCardDataBackImagePath];
        [data setValue:self.frontImage forKey:(NSString *)kTCCardDataFrontImage];
        [data setValue:self.backImage forKey:(NSString *)kTCCardDataBackImage];
        [data setValue:nil forKey:(NSString *)kTCCardDataFrontImagePath];
        [data setValue:nil forKey:(NSString *)kTCCardDataBackImagePath];
    }

    [coder encodeObject:data forKey:(NSString *)kTCCardData];

    if(sending) {
        [data setValue:nil forKey:(NSString *)kTCCardDataFrontImage];
        [data setValue:nil forKey:(NSString *)kTCCardDataBackImage];
        [data setValue:frontImagePath forKey:(NSString *)kTCCardDataFrontImagePath];
        [data setValue:backImagePath forKey:(NSString *)kTCCardDataBackImagePath];
    }
}

- (void)encodeForSending:(BOOL)isSending {
    self.sending = isSending;
}

- (void)dealloc {
    // delete image files associated with the removed card
    self.frontImage = nil;
    self.backImage = nil;
}

#pragma mark - Setters

- (void)setFrontText:(NSString *)frontText {
    [data setValue:frontText forKey:(NSString *)kTCCardDataFrontText];
}

- (void)setBackText:(NSString *)backText {
    [data setValue:backText forKey:(NSString *)kTCCardDataBackText];
}

- (void)setFrontImage:(UIImage *)frontImage {
    [self setImage:frontImage forKey:(NSString *)kTCCardDataFrontImagePath];
}

- (void)setBackImage:(UIImage *)backImage {
    [self setImage:backImage forKey:(NSString *)kTCCardDataBackImagePath];
}

- (void)setImage:(UIImage *)image forKey:(NSString *)key {
    NSString *filePath = data[key];

    // delete file if it exists from previous
    if(filePath) {
        NSFileManager *fileManager = [NSFileManager defaultManager];
        [fileManager removeItemAtPath:filePath error:nil];
    }

    if(image) {
        filePath = [TCCard filePathForImageToSave:image];
    } else {
        filePath = nil;
    }

    [data setValue:filePath forKey:(NSString *)key];
}

- (void)incrementScoreRight {
    NSNumber *number = [NSNumber numberWithInteger:[self scoredRight] + 1];
    [data setValue:number forKey:(NSString *)kTCCardDataScoreRight];
    [data setValue:@1 forKey:(NSString *)kTCCardDataScoreLatest];
}

- (void)incrementScoreWrong {
    NSNumber *number = [NSNumber numberWithInteger:([self scoredWrong]) + 1];
    [data setValue:number forKey:(NSString *)kTCCardDataScoreWrong];
    [data setValue:@-1 forKey:(NSString *)kTCCardDataScoreLatest];
}

- (void)resetScores {
    NSNumber *number = @0;
    [data setValue:number forKey:(NSString *)kTCCardDataScoreRight];
    [data setValue:number forKey:(NSString *)kTCCardDataScoreWrong];
    [data setValue:@0 forKey:(NSString *)kTCCardDataScoreLatest];
}

- (void)resetLatestScore {
    [data setValue:@0 forKey:(NSString *)kTCCardDataScoreLatest];
}

#pragma mark - Getters

- (NSString *)frontText {
    return data[kTCCardDataFrontText];
}

- (NSString *)backText {
    return data[kTCCardDataBackText];
}

- (UIImage *)frontImage {
    NSString *uniquePath = data[kTCCardDataFrontImagePath];
    if(!uniquePath) {
        return nil;
    }
    NSString *docPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
    NSString *filePath = [docPath stringByAppendingPathComponent:uniquePath];
    return [UIImage imageWithContentsOfFile:filePath];
}

- (void)frontImageWithCompletion:(void (^)(UIImage* image))completion {
    if(!completion) {
        return;
    }
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        UIImage *image = self.frontImage;
        if(!image) dispatch_async(dispatch_get_main_queue(), ^{ completion(nil); });
        dispatch_async(dispatch_get_main_queue(), ^{ completion(image); });
    });
}

- (UIImage *)backImage {
    NSString *uniquePath = data[kTCCardDataBackImagePath];
    if(!uniquePath) {
        return nil;
    }
    NSString *docPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
    NSString *filePath = [docPath stringByAppendingPathComponent:uniquePath];
    return [UIImage imageWithContentsOfFile:filePath];
}

- (void)backImageWithCompletion:(void (^)(UIImage* image))completion {
    if(!completion) return;
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        UIImage *image = self.backImage;
        if(!image) dispatch_async(dispatch_get_main_queue(), ^{ completion(nil); });
        dispatch_async(dispatch_get_main_queue(), ^{ completion(image); });
    });
}

- (NSUInteger)scoredRight {
    NSNumber *number = data[kTCCardDataScoreRight];
    return number.integerValue;
}

- (NSUInteger)scoredWrong {
    NSNumber *number = data[kTCCardDataScoreWrong];
    return number.integerValue;
}

- (NSInteger)scoredNet {
    return [self scoredRight] - [self scoredWrong];
}

- (NSUInteger)scoredTotal {
    return [self scoredRight] + [self scoredWrong];
}

- (NSInteger)scoredLatest {
    NSNumber *number = data[kTCCardDataScoreLatest];
    return number.integerValue;
}

#pragma mark - image saving/retrieval

+ (NSString *)filePathForImageToSave:(UIImage *)image {
    CGSize screenSize = [UIScreen mainScreen].bounds.size;
    CGFloat scale = image.size.width / fminf(screenSize.width, screenSize.height);
    CGSize size = CGSizeMake(image.size.width / scale, image.size.height / scale);
    image = [image scaleImageToSize:size];
    NSString *filePath = [TCCard uniqueFilePath];
    NSData *imageData = UIImageJPEGRepresentation(image, 0.3);
    if(!imageData) {
        return nil;
    }
    NSString *docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    if(![imageData writeToFile:[docPath stringByAppendingPathComponent:filePath] atomically:YES]) {
        return nil;
    }
    return filePath;
}

+ (NSString *)uniqueFilePath {
    NSString *docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSString *filePath = [docPath stringByAppendingPathComponent:@"Photos"];
    BOOL exists = [[NSFileManager defaultManager] fileExistsAtPath:filePath isDirectory:nil];
    if (!exists) {
        if (![[NSFileManager defaultManager] createDirectoryAtPath:filePath
                                       withIntermediateDirectories:NO
                                                        attributes:nil
                                                             error:nil]) {
            return nil;
        }
    }
    NSString *md5hash = [NSData md5hash];
    if(!md5hash) {
        return nil;
    }
    NSString *file = [md5hash stringByAppendingString:@".jpg"];
    filePath = [@"Photos" stringByAppendingPathComponent:file];
    return filePath;
}

@end


text:
package cc.factorie.variable

import cc.factorie.la._
import java.io._
import java.util.zip.{GZIPInputStream, GZIPOutputStream}
import cc.factorie.util.Cubbie
import cc.factorie.variable

// For variables that hold a single discrete value, which is represented as a one-hot Tensor1.

/** A value in a DiscreteDomain.  Conceptually it is a single integer value ranging from 0 to the domain size minus one.
    But it is also a Tensor1, of length domain.size, with 0s in all positions except its integer value; this
    facilitates its use in various tensor statistics operations.
    @author Andrew McCallum */
trait DiscreteValue extends SingletonBinaryTensorLike1 {
  // def dim1: Int remains abstract
  @inline final def intValue: Int = singleIndex // TODO Consider swapping singleIndex <-> intValue
  @inline final def booleanValue = if (intValue == 0) false else true
  override def toString: String = singleIndex.toString
}

/** The domain of a DiscreteVar.  It has a finite size and provides a DiscreteValue for each integer from 0 to size-1.
    Because DiscreteDomain is an IndexedSeq it can be passed as a "sizeProxy" to various "growable tensors", etc.
    @author Andrew McCallum */
class DiscreteDomain(sizeProxy:Iterable[Any]) extends IndexedSeq[DiscreteValue] with VectorDomain with Domain {
  thisDomain =>
  type Value <: variable.DiscreteValue
  def this(size:Int) = { this(null.asInstanceOf[Iterable[Any]]); _size = size }
  def dimensionDomain: DiscreteDomain = this
  /** If true, do not allow this domain to change. */
  protected var _frozen = false
  override def freeze(): Unit = _frozen = true
  def unfreeze(): Unit = _frozen = false
  /** Can new category values be added to this Domain? */
  def frozen = _frozen
  var maxRequestedInt: Int = 0

  /** Maps from integer index to the DiscreteValue objects */
  private val __elements = new scala.collection.mutable.ArrayBuffer[Value]
  def _elements = __elements // Define this way so that _elements can be overridden

  // If _size >= 0, _size is used to determine DiscreteDomain.size, otherwise _sizeProxy.size is used.
  private var _size = -1
  private val _sizeProxy = sizeProxy
  def length = if (_size >= 0) _size else _sizeProxy.size
  def apply(index:Int): Value = {
    if (index > maxRequestedInt) maxRequestedInt = index
    if (index >= size) throw new IllegalArgumentException("DiscreteDomain.getValue: index "+index+" larger than size "+size)
    if (index >= __elements.size) {
      __elements synchronized { for (i <- __elements.size to index) __elements += new DiscreteValue(i).asInstanceOf[Value] }
    } //.asInstanceOf[Value] // Here new a DiscreteValue gets created
    __elements(index)
  }
  def unapply(value:Value): Option[Int] = value match { // TODO Is this callable?
    case dv:DiscreteValue => Some(dv.intValue)  //if (value.domain == this) Some(value.intValue) else None
    case _ => None
  }
  override def iterator: Iterator[Value] = _elements.iterator
  def getAll(c: Iterator[Int]) = c map apply
  def getAll(c: List[Int]) = c map apply
  def getAll(c: Array[Int]) = c map apply
  def getAll(c: Set[Int]) = c map apply

  protected class DiscreteValue(val singleIndex:Int) extends variable.DiscreteValue {
    def domain = thisDomain
    def dim1 = thisDomain.size // Do this rather than use a constant, so that it will grow dynamically if necessary.
    override def equals(other:Any): Boolean =
      other match { case other:DiscreteValue => this.singleIndex == other.singleIndex; case _ => false }
    // Note that we aren't also insisting that the Domain objects match, although it might be nice to do so. -akm
  }
}

/** A Cubbie for serializing a DiscreteDomain.
    Note that this Cubbie can only serialize DiscreteDomains with a fixed size, not with a growable sizeProxy.
    @author Andrew McCallum */
class DiscreteDomainCubbie extends Cubbie {
  val size = IntSlot("size")
  def store(d: DiscreteDomain): Unit = size := d.size
  def fetch(): DiscreteDomain = new DiscreteDomain(size.value)
}


text:
package org.apache.sling.hc.junitbridge;

import static org.junit.Assert.fail;
import static org.junit.Assert.assertNotNull;

import java.util.Arrays;

import junit.framework.TestSuite;

import org.junit.runner.RunWith;
import org.junit.runners.AllTests;
import org.osgi.framework.ServiceReference;

@RunWith(AllTests.class)
public class JUnitTestBridge {
    private static ThreadLocal<TestBridgeContext> testContext = new ThreadLocal<TestBridgeContext>();

    static void setThreadContext(TestBridgeContext c) {
        testContext.set(c);
    }

    public static junit.framework.Test suite() {
        final TestBridgeContext context = testContext.get();
        assertNotNull("Expecting non-null TestBridgeContext, via ThreadLocal", context);
        TestSuite suite = new TestSuite();
        for(ServiceReference ref : context.getFilter().getTaggedHealthCheckServiceReferences(context.getTags())) {
            suite.addTest(new HealthCheckTest(context, ref));
        }
        if(suite.countTestCases() == 0) {
            fail("No Health Checks found with tags " + Arrays.asList(context.getTags()));
        }
        return suite;
    }
}


text:
ServiceReference holds a reference to Service.legacy.k8s.io
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**name** | **str** | Name is the name of the service | [optional]
**namespace** | **str** | Namespace is the namespace of the service | [optional]
**port** | **int** | If specified, the port on the service that hosting webhook. Default to 443 for backward compatibility. `port` should be a valid port number (1-65535, inclusive). | [optional]

[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)


text:
import lcm

from lilylcm import L02Banana
def my_handler(channel, data):
    msg=L02Banana()
    msg.done=true
    lc.publish("L02Banana", msg. encode())

lc = lcm.LCM()
subscription = lc.subscribe("L01Apple", my_handler)

try:
    while True:
        lc.handle()
except KeyboardInterrupt:
    pass

lc.unsubscribe(subscription)


text:
"""
module for actually talking to the YubiHSM
"""

# Copyright (c) 2011 Yubico AB
# See the file COPYING for licence statement.

__all__ = [
    # constants
    # functions
    'read',
    'write',
    'flush',
    # classes
    'YHSM_Stick',
]

import sys
import serial

import pyhsm.util
import pyhsm.exception

class YHSM_Stick():
    """
    The current YHSM is a USB device using serial communication.

    This class exposes the basic functions read, write and flush (input).
    """
    def __init__(self, device, timeout=1, debug=False):
        """
        Open YHSM device.
        """
        self.debug = debug
        self.device = device
        self.num_read_bytes = 0
        self.num_write_bytes = 0
        self.ser = None # to not bomb in destructor on open fail
        self.ser = serial.serial_for_url(device)
        self.ser.baudrate = 115200
        self.ser.timeout = timeout
        if self.debug:
            sys.stderr.write("%s: OPEN %s\n" %(
                    self.__class__.__name__,
                    self.ser
                    ))
        return None

    def acquire(self):
        """
        Do nothing
        """
        return self.acquire

    def write(self, data, debug_info=None):
        """
        Write data to YHSM device.
        """
        self.num_write_bytes += len(data)
        if self.debug:
            if not debug_info:
                debug_info = str(len(data))
            sys.stderr.write("%s: WRITE %s:\n%s\n" %(
                    self.__class__.__name__,
                    debug_info,
                    pyhsm.util.hexdump(data)
                    ))
        return self.ser.write(data)

    def read(self, num_bytes, debug_info=None):
        """
        Read a number of bytes from YubiHSM device.
        """
        if self.debug:
            if not debug_info:
                debug_info = str(num_bytes)
            sys.stderr.write("%s: READING %s\n" %(
                    self.__class__.__name__,
                    debug_info
                    ))
        res = self.ser.read(num_bytes)
        if self.debug:
            sys.stderr.write("%s: READ %i:\n%s\n" %(
                    self.__class__.__name__,
                    len(res),
                    pyhsm.util.hexdump(res)
                    ))
        self.num_read_bytes += len(res)
        return res

    def flush(self):
        """
        Flush input buffers.
        """
        if self.debug:
            sys.stderr.write("%s: FLUSH INPUT (%i bytes waiting)\n" %(
                    self.__class__.__name__,
                    self.ser.inWaiting()
                    ))
        self.ser.flushInput()

    def drain(self):
        """ Drain input. """
        if self.debug:
            sys.stderr.write("%s: DRAIN INPUT (%i bytes waiting)\n" %(
                    self.__class__.__name__,
                    self.ser.inWaiting()
                    ))
        old_timeout = self.ser.timeout
        self.ser.timeout = 0.1
        data = self.ser.read(1)
        while len(data):
            if self.debug:
                sys.stderr.write("%s: DRAINED 0x%x (%c)\n" %(self.__class__.__name__, ord(data[0]), data[0]))
            data = self.ser.read(1)
        self.ser.timeout = old_timeout
        return True

    def raw_device(self):
        """ Get raw serial device. Only intended for test code/debugging! """
        return self.ser

    def set_debug(self, new):
        """
        Set debug mode (boolean).

        Returns old setting.
        """
        if type(new) is not bool:
            raise pyhsm.exception.YHSM_WrongInputType(
                'new', bool, type(new))
        old = self.debug
        self.debug = new
        return old

    def __repr__(self):
        return '<%s instance at %s: %s - r:%i w:%i>' % (
            self.__class__.__name__,
            hex(id(self)),
            self.device,
            self.num_read_bytes,
            self.num_write_bytes
            )

    def __del__(self):
        """
        Close device when YHSM instance is destroyed.
        """
        if self.debug:
            sys.stderr.write("%s: CLOSE %s\n" %(
                    self.__class__.__name__,
                    self.ser
                    ))
        if self.ser:
            self.ser.close()


text:
#ifndef QT3DRENDER_QSHADERDATA_P_H
#define QT3DRENDER_QSHADERDATA_P_H

//
//  W A R N I N G
//  -------------
//
// This file is not part of the Qt API.  It exists for the convenience
// of other Qt classes.  This header file may change from version to
// version without notice, or even be removed.
//
// We mean it.
//

#include <private/qcomponent_p.h>
#include <Qt3DRender/qshaderdata.h>
#include <Qt3DRender/private/qt3drender_global_p.h>

QT_BEGIN_NAMESPACE

namespace Qt3DRender {

namespace {

const int qVectorShaderDataTypeId = qMetaTypeId<QVector<QShaderData*> >();
const int qShaderDataTypeId = qMetaTypeId<QShaderData*>();

}

class QShaderDataPropertyReader: public PropertyReaderInterface
{
    QVariant readProperty(const QVariant &v) Q_DECL_OVERRIDE
    {
        QShaderData *shaderData = nullptr;

        if (v.userType() == qShaderDataTypeId && (shaderData = v.value<QShaderData *>()) != nullptr) {
            return QVariant::fromValue(shaderData->id());
        } else if (v.userType() == qVectorShaderDataTypeId) {
            QVariantList vlist;
            const auto data_ = v.value<QVector<QShaderData *> >();
            for (QShaderData *data : data_) {
                if (data)
                    vlist.append(QVariant::fromValue(data->id()));
            }
            return vlist;
        }
        return v;
    }
};

class QT3DRENDERSHARED_PRIVATE_EXPORT QShaderDataPrivate : public Qt3DCore::QComponentPrivate
{
public:
    QShaderDataPrivate();
    QShaderDataPrivate(PropertyReaderInterfacePtr reader);
    PropertyReaderInterfacePtr m_propertyReader;

    Q_DECLARE_PUBLIC(QShaderData)
};

struct QShaderDataData
{
    QVector<QPair<QByteArray, QVariant>> properties;
    PropertyReaderInterfacePtr propertyReader;
};

} // namespace Qt3DRender

QT_END_NAMESPACE

#endif // QT3DRENDER_QSHADERDATA_P_H


text:
using UnrealBuildTool;

public class SlateViewer : ModuleRules
{
	public SlateViewer(TargetInfo Target)
	{
		PublicIncludePaths.Add("Runtime/Launch/Public");

		PrivateDependencyModuleNames.AddRange(
			new string[] {
				"AppFramework",
				"Core",
				"Projects",
				"Slate",
				"SlateCore",
				"SlateReflector",
				"StandaloneRenderer",
				"SourceCodeAccess",
				"WebBrowser",
			}
		);

		if (Target.Platform == UnrealTargetPlatform.Mac)
		{
			PrivateDependencyModuleNames.Add("XCodeSourceCodeAccess");
			AddThirdPartyPrivateStaticDependencies(Target, "CEF3");
		}
		else if (Target.Platform == UnrealTargetPlatform.Win64)
		{
			PrivateDependencyModuleNames.Add("VisualStudioSourceCodeAccess");
		}

		PrivateIncludePaths.Add("Runtime/Launch/Private");		// For LaunchEngineLoop.cpp include

		if (Target.Platform == UnrealTargetPlatform.IOS)
		{
			PrivateDependencyModuleNames.AddRange(
                new string [] {
                    "NetworkFile",
                    "StreamingFile"
                }
            );
		}
	}
}


text:
package com.armadialogcreator;

import org.jetbrains.annotations.NotNull;

import java.util.Locale;

/**
 Created by Kayler on 10/16/2016.
 */
public class LocaleDescriptor {
	private Locale locale;

	public LocaleDescriptor(@NotNull Locale locale) {
		this.locale = locale;
	}

	@NotNull
	public Locale getLocale() {
		return locale;
	}

	@Override
	public String toString() {
		String displayCountry = locale.getDisplayCountry(locale);
		return locale.getDisplayLanguage(locale) + (displayCountry.length() == 0 ? "" : " (" + displayCountry + ")");
	}

	@Override
	public boolean equals(Object o) {
		if (o == this) {
			return true;
		}
		if (o instanceof LocaleDescriptor) {
			LocaleDescriptor that = (LocaleDescriptor) o;
			return this.locale.equals(that.locale);
		}
		return false;
	}
}


text:
<?php

namespace Seahinet\Admin\ViewModel\Distribution;

use Seahinet\Lib\ViewModel\Template;

class Percentage extends Template
{

    private static $showTemplate = true;

    public function __construct()
    {
        $this->template = 'distribution/percentage';
    }

    public function setTemplate($template, $force = true)
    {
        return $this;
    }

    public function showTemplate()
    {
        $result = static::$showTemplate;
        static::$showTemplate = false;
        return $result;
    }

}


text:
declare interface IFaqsWebPartStrings {
  categoryDataLabel: string;
  categoryPanelHeader: string;
  manageCategoryBtn: string;

  FaqDataLabel: string;
  FaqPanelHeader: string;
  manageFaqsBtn: string;

  questionTitleField: string;
  answerTextField: string;
  answerLinkTitleField: string;
  answerLinkField: string;
  categoryField: string;
  targetField: string;

  targetCurrent: string;
  targetNew: string;

  noFaqsIconText: string;
  noFaqsConfigured: string;
  noFaqsBtn: string;

  Type: string;
}

declare module 'FaqsWebPartStrings' {
  const strings: IFaqsWebPartStrings;
  export = strings;
}


text:
/*
 * Author: max
 * Date: Oct 9, 2001
 * Time: 8:43:17 PM
 */

package com.intellij.codeInspection.ex;

import com.intellij.codeInsight.daemon.impl.actions.AbstractBatchSuppressByNoInspectionCommentFix;
import com.intellij.codeInspection.*;
import com.intellij.icons.AllIcons;
import com.intellij.ide.impl.ContentManagerWatcher;
import com.intellij.ide.ui.search.SearchableOptionsRegistrar;
import com.intellij.openapi.application.Application;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.util.NotNullLazyValue;
import com.intellij.openapi.wm.ToolWindow;
import com.intellij.openapi.wm.ToolWindowAnchor;
import com.intellij.openapi.wm.ToolWindowId;
import com.intellij.openapi.wm.ToolWindowManager;
import com.intellij.profile.codeInspection.ui.InspectionToolsConfigurable;
import com.intellij.psi.PsiElement;
import com.intellij.ui.content.ContentFactory;
import com.intellij.ui.content.ContentManager;
import com.intellij.ui.content.TabbedPaneContentUI;
import com.intellij.util.Function;
import com.intellij.util.IncorrectOperationException;
import com.intellij.util.containers.ContainerUtil;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.annotations.TestOnly;

import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.regex.Pattern;

public class InspectionManagerEx extends InspectionManagerBase {
  private GlobalInspectionContextImpl myGlobalInspectionContext = null;
  private final NotNullLazyValue<ContentManager> myContentManager;
  private final Set<GlobalInspectionContextImpl> myRunningContexts = new HashSet<GlobalInspectionContextImpl>();

  public InspectionManagerEx(final Project project) {
    super(project);
    if (ApplicationManager.getApplication().isHeadlessEnvironment()) {
      myContentManager = new NotNullLazyValue<ContentManager>() {
        @NotNull
        @Override
        protected ContentManager compute() {
          return ContentFactory.SERVICE.getInstance().createContentManager(new TabbedPaneContentUI(), true, project);
        }
      };
    }
    else {
      myContentManager = new NotNullLazyValue<ContentManager>() {
        @NotNull
        @Override
        protected ContentManager compute() {
          ToolWindowManager toolWindowManager = ToolWindowManager.getInstance(project);
          ToolWindow toolWindow =
            toolWindowManager.registerToolWindow(ToolWindowId.INSPECTION, true, ToolWindowAnchor.BOTTOM, project);
          ContentManager contentManager = toolWindow.getContentManager();
          toolWindow.setIcon(AllIcons.Toolwindows.ToolWindowInspection);
          new ContentManagerWatcher(toolWindow, contentManager);
          return contentManager;
        }
      };
    }
  }

  @NotNull
  public static SuppressIntentionAction convertBatchToSuppressIntentionAction(@NotNull final SuppressQuickFix fix) {
    return new SuppressIntentionAction() {
      @Override
      public void invoke(@NotNull Project project, Editor editor, @NotNull PsiElement element) throws IncorrectOperationException {
        PsiElement container = fix instanceof AbstractBatchSuppressByNoInspectionCommentFix
                               ? ((AbstractBatchSuppressByNoInspectionCommentFix )fix).getContainer(element) : null;
        boolean caretWasBeforeStatement = editor != null && container != null && editor.getCaretModel().getOffset() == container.getTextRange().getStartOffset();
        try {
          ProblemDescriptor descriptor =
            new ProblemDescriptorImpl(element, element, "", null, ProblemHighlightType.GENERIC_ERROR_OR_WARNING, false, null, false);
          fix.applyFix(project, descriptor);
        }
        catch (IncorrectOperationException e) {
          if (!ApplicationManager.getApplication().isUnitTestMode() && editor != null) {
            Messages.showErrorDialog(editor.getComponent(),
                                     InspectionsBundle.message("suppress.inspection.annotation.syntax.error", e.getMessage()));
          }
          else {
            throw e;
          }
        }

        if (caretWasBeforeStatement) {
          editor.getCaretModel().moveToOffset(container.getTextRange().getStartOffset());
        }
      }

      @Override
      public boolean isAvailable(@NotNull Project project, Editor editor, @NotNull PsiElement element) {
        return fix.isAvailable(project, element);
      }

      @NotNull
      @Override
      public String getText() {
        return fix.getName();
      }

      @NotNull
      @Override
      public String getFamilyName() {
        return fix.getFamilyName();
      }
    };
  }

  @Nullable
  public static SuppressIntentionAction[] getSuppressActions(@NotNull InspectionProfileEntry tool) {
    if (tool instanceof CustomSuppressableInspectionTool) {
      return ((CustomSuppressableInspectionTool)tool).getSuppressActions(null);
    }
    if (tool instanceof BatchSuppressableTool) {
      LocalQuickFix[] actions = ((BatchSuppressableTool)tool).getBatchSuppressActions(null);
      return ContainerUtil.map2Array(actions, SuppressIntentionAction.class, new Function<LocalQuickFix, SuppressIntentionAction>() {
        @Override
        public SuppressIntentionAction fun(final LocalQuickFix fix) {
          return convertBatchToSuppressIntentionAction((SuppressQuickFix)fix);
        }
      });
    }
    return null;
  }

  @NotNull
  public ProblemDescriptor createProblemDescriptor(@NotNull final PsiElement psiElement,
                                                   @NotNull final String descriptionTemplate,
                                                   @NotNull final ProblemHighlightType highlightType,
                                                   @Nullable final HintAction hintAction,
                                                   boolean onTheFly,
                                                   final LocalQuickFix... fixes) {
    return new ProblemDescriptorImpl(psiElement, psiElement, descriptionTemplate, fixes, highlightType, false, null, hintAction, onTheFly);
  }

  public GlobalInspectionContextImpl createNewGlobalContext(boolean reuse) {
    final GlobalInspectionContextImpl inspectionContext;
    if (reuse) {
      if (myGlobalInspectionContext == null) {
        myGlobalInspectionContext = inspectionContext = new GlobalInspectionContextImpl(getProject(), myContentManager);
      }
      else {
        inspectionContext = myGlobalInspectionContext;
      }
    }
    else {
      inspectionContext = new GlobalInspectionContextImpl(getProject(), myContentManager);
    }
    myRunningContexts.add(inspectionContext);
    return inspectionContext;
  }

  public void setProfile(final String name) {
    myCurrentProfileName = name;
  }

  public void closeRunningContext(GlobalInspectionContextImpl globalInspectionContext){
    myRunningContexts.remove(globalInspectionContext);
  }

  public Set<GlobalInspectionContextImpl> getRunningContexts() {
    return myRunningContexts;
  }

  public static boolean inspectionResultSuppressed(@NotNull PsiElement place, @NotNull LocalInspectionTool tool) {
    if (tool instanceof CustomSuppressableInspectionTool) {
      return ((CustomSuppressableInspectionTool)tool).isSuppressedFor(place);
    }
    if (tool instanceof BatchSuppressableTool) {
      return ((BatchSuppressableTool)tool).isSuppressedFor(place);
    }
    String alternativeId;
    String id;

    return SuppressionUtil.isSuppressed(place, id = tool.getID()) ||
           (alternativeId = tool.getAlternativeID()) != null &&
           !alternativeId.equals(id) &&
           SuppressionUtil.isSuppressed(place, alternativeId);
  }

  @NotNull
  @Deprecated
  public ProblemDescriptor createProblemDescriptor(@NotNull final PsiElement psiElement,
                                                   @NotNull final String descriptionTemplate,
                                                   @NotNull final ProblemHighlightType highlightType,
                                                   @Nullable final HintAction hintAction,
                                                   final LocalQuickFix... fixes) {

    return new ProblemDescriptorImpl(psiElement, psiElement, descriptionTemplate, fixes, highlightType, false, null, hintAction, true);
  }

  @TestOnly
  public NotNullLazyValue<ContentManager> getContentManager() {
    return myContentManager;
  }

  private final AtomicBoolean myToolsAreInitialized = new AtomicBoolean(false);
  private static final Pattern HTML_PATTERN = Pattern.compile("<[^<>]*>");
  public void buildInspectionSearchIndexIfNecessary() {
    if (!myToolsAreInitialized.getAndSet(true)) {
      final SearchableOptionsRegistrar myOptionsRegistrar = SearchableOptionsRegistrar.getInstance();
      final InspectionToolRegistrar toolRegistrar = InspectionToolRegistrar.getInstance();
      final Application app = ApplicationManager.getApplication();
      if (app.isUnitTestMode() || app.isHeadlessEnvironment()) return;

      app.executeOnPooledThread(new Runnable(){
        @Override
        public void run() {
          List<InspectionToolWrapper> tools = toolRegistrar.createTools();
          for (InspectionToolWrapper toolWrapper : tools) {
            processText(toolWrapper.getDisplayName().toLowerCase(), toolWrapper, myOptionsRegistrar);

            final String description = toolWrapper.loadDescription();
            if (description != null) {
              @NonNls String descriptionText = HTML_PATTERN.matcher(description).replaceAll(" ");
              processText(descriptionText, toolWrapper, myOptionsRegistrar);
            }
          }
        }
      });
    }
  }

  private static void processText(@NotNull @NonNls String descriptionText,
                                  @NotNull InspectionToolWrapper tool,
                                  @NotNull SearchableOptionsRegistrar myOptionsRegistrar) {
    if (ApplicationManager.getApplication().isDisposed()) return;
    final Set<String> words = myOptionsRegistrar.getProcessedWordsWithoutStemming(descriptionText);
    for (String word : words) {
      myOptionsRegistrar.addOption(word, tool.getShortName(), tool.getDisplayName(), InspectionToolsConfigurable.ID, InspectionToolsConfigurable.DISPLAY_NAME);
    }
  }
}


text:
NS_FT_BEGIN

void ShaderNode::pre_draw(const Camera *camera) {
    current_shader_program_->use();
    current_shader_program_->updateUniforms(camera, this);
}

NS_FT_END


text:
namespace content {

using blink::WebInputEvent;
using blink::WebKeyboardEvent;
using blink::WebGestureEvent;
using blink::WebMouseEvent;
using blink::WebMouseWheelEvent;
using blink::WebTouchEvent;
using blink::WebTouchPoint;

WebMouseEvent SyntheticWebMouseEventBuilder::Build(
    blink::WebInputEvent::Type type) {
  WebMouseEvent result;
  result.type = type;
  return result;
}

WebMouseEvent SyntheticWebMouseEventBuilder::Build(
    blink::WebInputEvent::Type type,
    int window_x,
    int window_y,
    int modifiers) {
  DCHECK(WebInputEvent::isMouseEventType(type));
  WebMouseEvent result = Build(type);
  result.x = window_x;
  result.y = window_y;
  result.windowX = window_x;
  result.windowY = window_y;
  result.modifiers = modifiers;

  if (type == WebInputEvent::MouseDown || type == WebInputEvent::MouseUp)
    result.button = WebMouseEvent::ButtonLeft;
  else
    result.button = WebMouseEvent::ButtonNone;

  return result;
}

WebMouseWheelEvent SyntheticWebMouseWheelEventBuilder::Build(
    WebMouseWheelEvent::Phase phase) {
  WebMouseWheelEvent result;
  result.type = WebInputEvent::MouseWheel;
  result.phase = phase;
  return result;
}

WebMouseWheelEvent SyntheticWebMouseWheelEventBuilder::Build(float dx,
                                                             float dy,
                                                             int modifiers,
                                                             bool precise) {
  WebMouseWheelEvent result;
  result.type = WebInputEvent::MouseWheel;
  result.deltaX = dx;
  result.deltaY = dy;
  result.modifiers = modifiers;
  result.hasPreciseScrollingDeltas = precise;
  return result;
}

NativeWebKeyboardEvent SyntheticWebKeyboardEventBuilder::Build(
    WebInputEvent::Type type) {
  DCHECK(WebInputEvent::isKeyboardEventType(type));
  NativeWebKeyboardEvent result;
  result.type = type;
  result.windowsKeyCode = ui::VKEY_L;  // non-null made up value.
  return result;
}

WebGestureEvent SyntheticWebGestureEventBuilder::Build(
    WebInputEvent::Type type,
    WebGestureEvent::SourceDevice source_device) {
  DCHECK(WebInputEvent::isGestureEventType(type));
  WebGestureEvent result;
  result.type = type;
  result.sourceDevice = source_device;
  return result;
}

WebGestureEvent SyntheticWebGestureEventBuilder::BuildScrollUpdate(
    float dx,
    float dy,
    int modifiers) {
  WebGestureEvent result = Build(WebInputEvent::GestureScrollUpdate,
                                 WebGestureEvent::Touchscreen);
  result.data.scrollUpdate.deltaX = dx;
  result.data.scrollUpdate.deltaY = dy;
  result.modifiers = modifiers;
  return result;
}

WebGestureEvent SyntheticWebGestureEventBuilder::BuildPinchUpdate(
    float scale,
    float anchor_x,
    float anchor_y,
    int modifiers) {
  WebGestureEvent result = Build(WebInputEvent::GesturePinchUpdate,
                                 WebGestureEvent::Touchscreen);
  result.data.pinchUpdate.scale = scale;
  result.x = anchor_x;
  result.y = anchor_y;
  result.modifiers = modifiers;
  return result;
}

WebGestureEvent SyntheticWebGestureEventBuilder::BuildFling(
    float velocity_x,
    float velocity_y,
    WebGestureEvent::SourceDevice source_device) {
  WebGestureEvent result = Build(WebInputEvent::GestureFlingStart,
                                 source_device);
  result.data.flingStart.velocityX = velocity_x;
  result.data.flingStart.velocityY = velocity_y;
  return result;
}

SyntheticWebTouchEvent::SyntheticWebTouchEvent() : WebTouchEvent() {}

void SyntheticWebTouchEvent::ResetPoints() {
  int point = 0;
  for (unsigned int i = 0; i < touchesLength; ++i) {
    if (touches[i].state == WebTouchPoint::StateReleased)
      continue;

    touches[point] = touches[i];
    touches[point].state = WebTouchPoint::StateStationary;
    ++point;
  }
  touchesLength = point;
  type = WebInputEvent::Undefined;
}

int SyntheticWebTouchEvent::PressPoint(int x, int y) {
  if (touchesLength == touchesLengthCap)
    return -1;
  WebTouchPoint& point = touches[touchesLength];
  point.id = touchesLength;
  point.position.x = point.screenPosition.x = x;
  point.position.y = point.screenPosition.y = y;
  point.state = WebTouchPoint::StatePressed;
  point.radiusX = point.radiusY = 1.f;
  ++touchesLength;
  type = WebInputEvent::TouchStart;
  return point.id;
}

void SyntheticWebTouchEvent::MovePoint(int index, int x, int y) {
  CHECK(index >= 0 && index < touchesLengthCap);
  WebTouchPoint& point = touches[index];
  point.position.x = point.screenPosition.x = x;
  point.position.y = point.screenPosition.y = y;
  touches[index].state = WebTouchPoint::StateMoved;
  type = WebInputEvent::TouchMove;
}

void SyntheticWebTouchEvent::ReleasePoint(int index) {
  CHECK(index >= 0 && index < touchesLengthCap);
  touches[index].state = WebTouchPoint::StateReleased;
  type = WebInputEvent::TouchEnd;
}

void SyntheticWebTouchEvent::SetTimestamp(base::TimeDelta timestamp) {
  timeStampSeconds = timestamp.InSecondsF();
}

SyntheticWebTouchEvent SyntheticWebTouchEventBuilder::Build(
    WebInputEvent::Type type) {
  DCHECK(WebInputEvent::isTouchEventType(type));
  SyntheticWebTouchEvent result;
  result.type = type;
  return result;
};

}  // namespace content


text:
template<T, P> class ptr;
template<T, W> class local_ptr: ptr<T,local_ptr>;
#include "Managers.hpp"


text:
<?php

namespace ZQ\SunSearchBundle\Tests;

/**
 * Class DocumentStub
 */
class DocumentStub implements \Solarium\QueryType\Update\Query\Document\DocumentInterface
{
    public $id = 1;
    public $document_name_s = 'stub_document';

    /**
     * Constructor
     *
     * @param array $fields
     * @param array $boosts
     * @param array $modifiers
     */
    public function __construct(array $fields = array(), array $boosts = array(), array $modifiers = array())
    {

    }

    /**
     * @param string $fieldName
     *
     * @return mixed
     */
    public function getField($fieldName)
    {
        $fields = array('id' => $this->id, 'document_name' => $this->document_name_s);

        return $fields[$fieldName];
    }

    /**
     * @return array
     */
    public function getFields()
    {
        return array('id' => $this->id, 'document_name' => $this->document_name_s);
    }
}


text:
JAX-RS-demo
===========

JAX-RS (Java API for RESTful Web Services) demo for an academic project.

This demo uses [Jersey](https://jersey.java.net/) the reference implementation for the JSR 311 specification.


text:
import * as L from 'leaflet';
import { IGeocoder, GeocoderOptions, GeocodingCallback } from './api';
export interface HereOptions extends GeocoderOptions {
    app_id: string;
    app_code: string;
    reverseGeocodeProxRadius: null;
}
/**
 * Implementation of the [HERE Geocoder API](https://developer.here.com/documentation/geocoder/topics/introduction.html)
 */
export declare class HERE implements IGeocoder {
    options: HereOptions;
    constructor(options?: Partial<HereOptions>);
    geocode(query: string, cb: GeocodingCallback, context?: any): void;
    reverse(location: L.LatLngLiteral, scale: number, cb: GeocodingCallback, context?: any): void;
    getJSON(url: string, params: any, cb: GeocodingCallback, context?: any): void;
}
/**
 * [Class factory method](https://leafletjs.com/reference.html#class-class-factories) for {@link HERE}
 * @param options the options
 */
export declare function here(options?: Partial<HereOptions>): HERE;