text:
package com.contrastsecurity.cassandra.migration.action;

import com.contrastsecurity.cassandra.migration.dao.SchemaVersionDAO;
import com.contrastsecurity.cassandra.migration.info.MigrationInfoService;
import com.contrastsecurity.cassandra.migration.info.MigrationVersion;
import com.contrastsecurity.cassandra.migration.logging.Log;
import com.contrastsecurity.cassandra.migration.logging.LogFactory;
import com.contrastsecurity.cassandra.migration.resolver.MigrationResolver;
import com.contrastsecurity.cassandra.migration.utils.StopWatch;
import com.contrastsecurity.cassandra.migration.utils.TimeFormat;

/**
 * Validates the applied migrations against the available ones.
 */
public class Validate {

	/**
	 * logging support
	 */
	private static final Log LOG = LogFactory.getLog(Validate.class);

	private SchemaVersionDAO schemaVersionDao;

	/**
	 * migration resolver
	 */
	private MigrationResolver migrationResolver;

	/**
	 * migration target
	 */
	private MigrationVersion migrationTarget;

	private boolean outOfOrder;

	private boolean pendingOrFuture;

	public Validate(MigrationResolver migrationResolver, SchemaVersionDAO schemaVersionDao, MigrationVersion migrationTarget, boolean outOfOrder, boolean pendingOrFuture) {
		this.schemaVersionDao = schemaVersionDao;
		this.migrationResolver = migrationResolver;
		this.migrationTarget = migrationTarget;
		this.outOfOrder = outOfOrder;
		this.pendingOrFuture = pendingOrFuture;
	}

	public String run() {
		StopWatch stopWatch = new StopWatch();
		stopWatch.start();

		MigrationInfoService infoService = new MigrationInfoService(migrationResolver, schemaVersionDao, migrationTarget, outOfOrder, pendingOrFuture);
		infoService.refresh();
		int count = infoService.all().length;
		String validationError = infoService.validate();

		stopWatch.stop();

		LOG.info(String.format("Validated %d migrations (execution time %s)", count, TimeFormat.format(stopWatch.getTotalTimeMillis())));

		return validationError;
	}
}


text:
package org.apache.flink.testutils.logging;

import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.core.Appender;
import org.apache.logging.log4j.core.Filter;
import org.apache.logging.log4j.core.LogEvent;
import org.apache.logging.log4j.core.LoggerContext;
import org.apache.logging.log4j.core.appender.AbstractAppender;
import org.apache.logging.log4j.core.config.AppenderRef;
import org.apache.logging.log4j.core.config.LoggerConfig;
import org.apache.logging.log4j.core.config.Property;
import org.apache.logging.log4j.core.filter.ThresholdFilter;
import org.junit.rules.ExternalResource;

import javax.annotation.Nullable;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.ConcurrentLinkedQueue;

/**
 * Utility for auditing logged messages.
 *
 *
Note: If a parent logger is already defined with a less specific log level, then using the
 * {@link TestLoggerResource} can increase the number of log messages received by this logger.
 *
 *
Example: You define a logger for org.apache.runtime with log level INFO and then use {@link
 * TestLoggerResource} to listen on org.apache.runtime.feature with log level DEBUG. In this case,
 * the log output for the parent logger will include DEBUG messages org.apache.runtime.feature.
 *
 *
Implementation note: Make sure to not expose log4j dependencies in the interface of this class
 * to ease updates in logging infrastructure.
 */
public class TestLoggerResource extends ExternalResource {
    private static final LoggerContext LOGGER_CONTEXT =
            (LoggerContext) LogManager.getContext(false);

    private final String loggerName;
    private final org.slf4j.event.Level level;
    @Nullable private LoggerConfig backupLoggerConfig = null;

    private ConcurrentLinkedQueue<String> loggingEvents;

    public TestLoggerResource(Class<?> clazz, org.slf4j.event.Level level) {
        this(clazz.getCanonicalName(), level);
    }

    private TestLoggerResource(String loggerName, org.slf4j.event.Level level) {
        this.loggerName = loggerName;
        this.level = level;
    }

    public List<String> getMessages() {
        return new ArrayList<>(loggingEvents);
    }

    private static String generateRandomString() {
        return UUID.randomUUID().toString().replace("-", "");
    }

    @Override
    protected void before() throws Throwable {
        loggingEvents = new ConcurrentLinkedQueue<>();

        final LoggerConfig previousLoggerConfig =
                LOGGER_CONTEXT.getConfiguration().getLoggerConfig(loggerName);

        final Level previousLevel = previousLoggerConfig.getLevel();
        final Level userDefinedLevel = Level.getLevel(level.name());

        // Set log level to least specific. This ensures that the parent still receives all log
        // lines.
        // WARN is more specific than INFO is more specific than DEBUG etc.
        final Level newLevel =
                userDefinedLevel.isMoreSpecificThan(previousLevel)
                        ? previousLevel
                        : userDefinedLevel;

        // Filter log lines according to user requirements.
        final Filter levelFilter =
                ThresholdFilter.createFilter(
                        userDefinedLevel, Filter.Result.ACCEPT, Filter.Result.DENY);

        final Appender testAppender =
                new AbstractAppender(
                        "test-appender-" + generateRandomString(),
                        levelFilter,
                        null,
                        false,
                        Property.EMPTY_ARRAY) {
                    @Override
                    public void append(LogEvent event) {
                        loggingEvents.add(event.getMessage().getFormattedMessage());
                    }
                };
        testAppender.start();

        final LoggerConfig loggerConfig =
                LoggerConfig.createLogger(
                        true,
                        newLevel,
                        loggerName,
                        null,
                        new AppenderRef[] {},
                        null,
                        LOGGER_CONTEXT.getConfiguration(),
                        null);
        loggerConfig.addAppender(testAppender, null, null);

        if (previousLoggerConfig.getName().equals(loggerName)) {
            // remove the previous logger config for the duration of the test
            backupLoggerConfig = previousLoggerConfig;
            LOGGER_CONTEXT.getConfiguration().removeLogger(loggerName);

            // combine appender set
            // Note: The appender may still receive more or less messages depending on the log level
            // difference between the two logger
            for (Appender appender : previousLoggerConfig.getAppenders().values()) {
                loggerConfig.addAppender(appender, null, null);
            }
        }

        LOGGER_CONTEXT.getConfiguration().addLogger(loggerName, loggerConfig);
        LOGGER_CONTEXT.updateLoggers();
    }

    @Override
    protected void after() {
        LOGGER_CONTEXT.getConfiguration().removeLogger(loggerName);
        if (backupLoggerConfig != null) {
            LOGGER_CONTEXT.getConfiguration().addLogger(loggerName, backupLoggerConfig);
            backupLoggerConfig = null;
        }
        LOGGER_CONTEXT.updateLoggers();
        loggingEvents = null;
    }

    /** Enables the use of {@link TestLoggerResource} for try-with-resources statement. */
    public static SingleTestResource asSingleTestResource(
            String loggerName, org.slf4j.event.Level level) throws Throwable {
        return new SingleTestResource(loggerName, level);
    }

    /**
     * SingleTestResource re-uses the code in {@link TestLoggerResource} for try-with-resources
     * statement.
     */
    public static class SingleTestResource implements AutoCloseable {
        final TestLoggerResource resource;

        private SingleTestResource(String loggerName, org.slf4j.event.Level level)
                throws Throwable {
            resource = new TestLoggerResource(loggerName, level);
            resource.before();
        }

        @Override
        public void close() throws Exception {
            resource.after();
        }

        public List<String> getMessages() {
            return resource.getMessages();
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
var jst = require('../index.js')
  , hogan = require('hogan.js');

// Returns a string of js with the compiled template
module.exports = function( options, nm, file_contents ){
  options.asString = 1;
  var func;
  try {
    func = [
      options.namespace + '.templates || (' + options.namespace + '.templates = {});',
      options.namespace + '.templates["'+ nm +'"] = new Hogan.Template(' + hogan.compile(file_contents, options) + ', "' + nm +'" );',
      options.namespace + '["'+ nm +'"] = function(d){ return ' + options.namespace + '.templates["'+ nm +'"].render(d, ' + options.namespace + '.templates' + '); };'
    ];
  } catch( e ){
    console.error( 'Error processing '+ nm, e, e.stack);
    return '/* Unable to compile ' + nm + ' */\n';
  }
  return func.join('\n');
};


text:
module Azure::DataFactory::Mgmt::V2018_06_01
  module Models
    #
    # Referenced tumbling window trigger dependency.
    #
    class TumblingWindowTriggerDependencyReference < TriggerDependencyReference

      include MsRestAzure

      def initialize
        @type = "TumblingWindowTriggerDependencyReference"
      end

      attr_accessor :type

      # @return [String] Timespan applied to the start time of a tumbling
      # window when evaluating dependency.
      attr_accessor :offset

      # @return [String] The size of the window when evaluating the dependency.
      # If undefined the frequency of the tumbling window will be used.
      attr_accessor :size

      #
      # Mapper for TumblingWindowTriggerDependencyReference class as Ruby Hash.
      # This will be used for serialization/deserialization.
      #
      def self.mapper()
        {
          client_side_validation: true,
          required: false,
          serialized_name: 'TumblingWindowTriggerDependencyReference',
          type: {
            name: 'Composite',
            class_name: 'TumblingWindowTriggerDependencyReference',
            model_properties: {
              type: {
                client_side_validation: true,
                required: true,
                serialized_name: 'type',
                type: {
                  name: 'String'
                }
              },
              reference_trigger: {
                client_side_validation: true,
                required: true,
                serialized_name: 'referenceTrigger',
                default_value: {},
                type: {
                  name: 'Composite',
                  class_name: 'TriggerReference'
                }
              },
              offset: {
                client_side_validation: true,
                required: false,
                serialized_name: 'offset',
                constraints: {
                  MaxLength: 15,
                  MinLength: 8,
                  Pattern: '-?((\d+)\.)?(\d\d):(60|([0-5][0-9])):(60|([0-5][0-9]))'
                },
                type: {
                  name: 'String'
                }
              },
              size: {
                client_side_validation: true,
                required: false,
                serialized_name: 'size',
                constraints: {
                  MaxLength: 15,
                  MinLength: 8,
                  Pattern: '((\d+)\.)?(\d\d):(60|([0-5][0-9])):(60|([0-5][0-9]))'
                },
                type: {
                  name: 'String'
                }
              }
            }
          }
        }
      end
    end
  end
end


text:
#if !defined(FUSION_INCLUDE_END)
#define FUSION_INCLUDE_END

#include <lslboost/fusion/sequence/intrinsic/end.hpp>

#endif


text:
package com.wolfretbusiness.ferretshinies;

import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.item.Item;

@Deprecated
public class FerretShinyTab extends CreativeTabs {
	// TODO Erdenshire 2014-09-06 Identify what "icon" is.
	private Item icon;

	public FerretShinyTab(String label) {
		super(label);
	}

	public void setTabIconItem(Item item) {
		icon = item;
	}

	@Override
	public Item getTabIconItem() {
		return icon;
	}
}


text:
This cookbook installs and configures Apache Zookeeper server.

> NOTE: This cookbook is meant to be used in conjunction with Cloudify and
> DICE TOSCA library.


text:
using System;
using System.Linq;
using System.Web.Mvc;

namespace Kendo.Mvc.Examples.Controllers
{
    public partial class EditorController : Controller
    {
        public ActionResult Rtl()
        {
            return View();
        }
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    android:id="@+id/linear_layout"
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

</LinearLayout>


text:
import { EventEmitter } from 'events';
import Dispatcher from '../dispatcher';
import * as c from '../constants/actions/product-actions';
import payloads from '../constants/actions/payloads';
import logger from '../helpers/logger/logger';

import percentify from '../helpers/math/percentify';

import companyCostHelper from '../helpers/products/compute-company-cost';

import * as PRODUCT_STAGES from '../constants/products/product-stages';
import * as EXPENSES from '../constants/expenses';
import * as JOB from '../constants/job';

import Product from '../classes/Product';

import { DefaultDescription, MarketDescription } from '../constants/products/types/product-description';

import productDescriptions from '../helpers/products/product-descriptions';

import sessionManager from '../helpers/session-manager';

import companyMerger from '../helpers/products/company-merger';

import getSpecialization from '../helpers/team/specialization';
import skillHelper from '../helpers/team/skills';

import workerGenerator from '../helpers/team/create-random-worker';

import stats from '../stats';

const EC = 'PRODUCT_EVENT_CHANGE';

let _money = 1000;
let _expenses = [];

let _points = {
  programming: 5300,
  marketing: 5200,
  analyst: 300
};

type Rent = {
  in: Number,
  out: Number,
  featureId: Number,
  price: Number,
  until: Number
};

type DescribedRent = {
  in: Number,
  out: Number,
  featureId: Number,
  price: Number,
  until: Number,

  senderName: String,
  acceptorName: String,
  senderValue: Number,
  techName: String
};

type MarketRecord = {
  companyId: Number,
  marketId: Number,
  level: Number,
};

let _rents: Array<Rent> = [
  { in: 2, out: 0, featureId: 3, price: 1000, until: 420 }
];

let _employees = [
  {
    name: 'Lynda',
    skills: {
      programming: 0,
      marketing: 500,
      analyst: 150
    },
    task: JOB.JOB_TASK_MARKETING_POINTS,
    jobMotivation: JOB.JOB_MOTIVATION_IDEA_FAN,
    salary: {
      money: 500,
      percent: 0,
      pricingType: 1
    }
  },
  {
    name: 'Xavier',
    skills: {
      programming: 600,
      marketing: 100,
      analyst: 150
    },
    task: JOB.JOB_TASK_PROGRAMMER_POINTS,
    jobMotivation: JOB.JOB_MOTIVATION_IDEA_FAN,
    salary: {
      money: 700,
      percent: 0,
      pricingType: 1
    }
  }
];

let _team = [
  {
    name: 'James',
    skills: {
      programming: 1000,
      marketing: 150,
      analyst: 300
    },
    task: JOB.JOB_TASK_PROGRAMMER_POINTS,
    jobMotivation: JOB.JOB_MOTIVATION_BUSINESS_OWNER,
    salary: {
      percent: 100,
      money: 100,
      pricingType: 0
    },
    isPlayer: true
  }
];

let _reputation = 50; // neutral reputation
let _fame = 0; // nobody knows you

let _loan = 0; // no loans;

let _products: Array<Product> = [];

let _markets: Array<MarketRecord> = [];

const initialize = ({ markets, products, rents, expenses, employees, team, reputation, fame, loan }) => {
  _products = products;
  _markets = markets;

  _expenses = expenses;
  _employees = employees;
  _team = team;
  _reputation = reputation;
  _fame = fame;
  _loan = loan;
  _rents = rents;
};

initialize(sessionManager.getProductStorageData());

const getCurrentMainFeatureDefaultsByIdea = (idea) => {
  const productsWithSameIdea = _products.filter((p, i) => p.idea === idea);

  return productDescriptions(idea).features.map((f, featureId) => {
    let max = f.data;

    productsWithSameIdea.forEach((p) => {
      let temp = p.getMainFeatureQualityByFeatureId(featureId);

      if (temp > max) {
        max = temp;
      }
    });

    return max;
  });
};

const getCurrentMainFeatureDefaultsById = (id) => {
  const p = _products[id];

  const idea = p.getIdea();

  return getCurrentMainFeatureDefaultsByIdea(idea);
};

function isMercenary(worker) {
  return worker.salary.pricingType === 1;
}

const sum = (arr) => arr.reduce((p, c) => p + c, 0);

const getMarketRecordIndex = (id, marketId) => {
  return _markets.findIndex((m, i) => m.companyId === id && m.marketId === marketId);
};

const getCurrentMainMarket = (id) => {
  return _markets.findIndex((m, i) => m.companyId === id && m.isMainMarket);
};

const clearPartnershipOf = (id, marketId) => {
  const index = getMarketRecordIndex(id, marketId);

  if (index >= 0) {
    const partnerId = _markets[index].partnerId;

    if (partnerId >= 0) {
      _markets[partnerId].partnerId = -1;
    }

    _markets[index].partnerId = -1;
  }
};

class ProductStore extends EventEmitter {
  addChangeListener(cb: Function) {
    this.addListener(EC, cb);
  }

  removeChangeListener(cb: Function) {
    this.removeListener(EC, cb);
  }

  emitChange() {
    this.emit(EC);
  }

  getMoney(id) {
    return Math.floor(_products[id]._money);
  }

  getExpenses() {
    return _expenses;
  }

  getLoanPaymentAmount() {
    return _loan ? _loan * 0.01 : 0;
  }

  getLoanSize() {
    return _loan;
  }

  getRents(): Array<DescribedRent> {
    return _rents.map(r => {
      const obj = Object.assign({} , r);

      obj.senderName = _products[r.out].getName();
      obj.acceptorName = _products[r.in].getName();
      obj.senderValue = this.getMainFeatureQualityByFeatureId(r.out, r.featureId);
      obj.techName = this.getPrettyFeatureNameByFeatureId(r.out, r.featureId);

      return obj;
    });
  };

  getMarketName(id, mId) {
    return this.getMarketInfo(id, mId).name;
  }

  getPoints(id) {
    return _products[id]._points;
  }

  enoughMarketingPoints(mp, id) {
    return _products[id]._points.marketing >= mp;
  }

  enoughProgrammingPoints(pp, id) {
    return _products[id]._points.programming >= pp;
  }

  getTeam() {
    return _team.map((e, i) => Object.assign({}, e, { id: i }));
  }

  getMonthlyMarketerPoints(id) {
    const bonus = 1 + _products[id].getBonusModifiers().marketingEfficiency / 100;

    const base = sum(this.getMarketers().map(skillHelper.getMarketingPointsProducedBy));

    return Math.floor(base * bonus);
  }

  getMonthlyProgrammerPoints(id) {
    const bonus = 1 + _products[id].getBonusModifiers().programmingEfficiency / 100;

    const base = sum(this.getProgrammers().map(skillHelper.getProgrammingPointsProducedBy));

    return Math.floor(base * bonus);
  }

  static getStoreData() {
    return {
      expenses: _expenses,
      employees: _employees,
      team: _team,
      reputation: _reputation,
      fame: _fame,
      loan: _loan,
      products: _products,
      rents: _rents,
      markets: _markets
    }
  }

  getTeamExpenses() {
    return sum(
      this.getTeam()
        .filter(isMercenary)
        .map(worker => worker.salary.money)
    );
  }

  getProgrammers() {
    return _team.filter(p => getSpecialization(p) === JOB.PROFESSION_PROGRAMMER)
  }

  getMarketers() {
    return _team.filter(p => getSpecialization(p) === JOB.PROFESSION_MARKETER)
  }

  getAnalysts() {
    return _team.filter(p => getSpecialization(p) === JOB.PROFESSION_ANALYST)
  }

  getDesigners() {
    return _team.filter(p => getSpecialization(p) === JOB.PROFESSION_DESIGNER)
  }

  getEmployees() {
    return _employees;
  }

  getProducts(): Array<Product> {
    return _products;
  }

  getOurProducts() {
    return _products.filter(this.isOurProduct);
  }

  isOurProduct(p) {
    // logger.debug('isOurProduct', p);
    return p.owner;
  }

  getProduct(id): Product {
    return _products[id];
  }

  getCompanyCost(id) {
    return companyCostHelper.compute(_products[id], this.getProductIncome(id), 0);
  }

  getCompanyCostStructured(id) {
    return companyCostHelper.structured(_products[id], this.getProductIncome(id), 0);
  }

  enforceFeaturesByRentedOnes(offer: Array<Number>, rented: Array<Rent>) {
    const list = offer.map(v => v);

    rented.forEach(r => {
      const id = r.featureId;

      const current = list[id];
      const next = this.getMainFeatureQualityByFeatureId(r.out, id);

      if (next >= current) {
        list[id] = next;
      }
    });

    return list;
  }

  canRentTechFromAtoB(sender, acceptor, featureId) {
    const result = _rents.find(r => r.featureId === featureId && (r.in === acceptor || r.out === acceptor || r.in === sender));

    return !result;
  }

  getRentIncomes(id) {
    const outgoingRents = this.getRents()
      .filter(r => r.out === id);

    const sum = outgoingRents.map(r => r.price).reduce((p, c) => p + c, 0);

    return {
      outgoingRents,
      sum
    };
  }

  getRentExpenses(id) {
    const incomingRents = this.getRents()
      .filter(r => r.in === id);

    const sum = incomingRents.map(r => r.price).reduce((p, c) => p + c, 0);

    return {
      incomingRents,
      sum
    };
  }

  getRentingStatus(id, featureId) {
    const canSend = !_rents.find(r => r.featureId === featureId && r.in === id);
    const canAccept = !_rents.find(r => r.featureId === featureId && (r.out === id || r.in === id));

    return {
      canSend,
      canAccept
    };
  }

  isRentingAlready(sender, acceptor, featureId) {
    return _rents.find(r => r.featureId === featureId && ((r.in === acceptor && r.out === sender) || (r.out === acceptor && r.in === sender)));
  }

  getRating(id, marketId, improvement = null) {
    if (!marketId) marketId = 0;

    const rented = this.incomingRentList(id);
    const features = this.enforceFeaturesByRentedOnes(_products[id].features.offer, rented);

    return Product.getRating(_products[id], features, marketId, improvement);
  }

  getMainFeatureQualityByFeatureId(id, featureId) {
    return _products[id].getMainFeatureQualityByFeatureId(featureId);
  }

  getPrettyFeatureNameByFeatureId(id, featureId){
    return _products[id].getPrettyFeatureNameByFeatureId(featureId);
  }

  getDefaults(id): DefaultDescription {
    return _products[id].getDefaults();
  }

  incomingRentList(id) {
    return _rents.filter(r => r.in === id);
  }

  outgoingRentList(id) {
    return _rents.filter(r => r.out === id);
  }

  hasIncomingRents(id) {
    return _rents.find(r => r.in === id);
  }

  hasOutgoingRents(id) {
    return _rents.find(r => r.out === id);
  }

  getPaymentModifier(id) {
    return _products[id].getPaymentModifier();
  }

  getFeatures(id, featureGroup) {
    return _products[id].getFeatures(featureGroup);
  }

  getNextFeature(id, groupType, featureList) {
    let unlockedFeature = '';

    featureList.forEach(f => {
      if (!this.getFeatureStatus(id, groupType, f.name) && !unlockedFeature) {
        unlockedFeature = f.name;
      }
    });

    if (!unlockedFeature) return null;

    let f = featureList.find(f => f.name === unlockedFeature);

    const canUpgrade = this.enoughMarketingPoints(f.points.marketing, id) && this.enoughProgrammingPoints(f.points.programming, id);

    return Object.assign({}, f, { canUpgrade })
  }

  getNearestMarketingFeature(id) {
    return this.getNextFeature(id, 'marketing', this.getMarketingFeatureList(id));
  }

  getNearestPaymentFeature(id) {
    return this.getNextFeature(id, 'payment', this.getPaymentFeatures(id));
  }

  getBenefitOnFeatureImprove(id, featureId) {
    return Math.floor(this.getProductIncomeIncreaseIfWeUpgradeFeature(id, featureId, 1000));
  }

  getMarkets(id): Array<MarketDescription> {
    return productDescriptions(_products[id].idea).markets;
  }

  getIncomeIncreaseForMarketIfWeUpgradeFeature(id, marketId, featureId, value) {
    if (this.isUpgradeWillResultTechBreakthrough(id, featureId)) return 0;

    const now = this.getMarketIncome(id, marketId, null);

    const willBe = this.getMarketIncome(id, marketId, { featureId, value });

    return willBe - now;
  }

  getProductIncomeIncreaseIfWeUpgradeFeature(id, featureId, value) {
    return this.getMarkets(id)
      .map((m, marketId) => this.getIncomeIncreaseForMarketIfWeUpgradeFeature(id, marketId, featureId, value))
      .reduce((p, c) => p + c, 0);
  }

  getPowerOfCompanyOnMarket(id, marketId) {
    logger.shit('need to count edicts, market-oriented features, campaigns');

    const base = this.getBaseMarketingInfluence(id, marketId);

    const mainMarketBonus = this.isMainMarket(id, marketId) ? 1.2 : 1;

    const record = this.getMarketRecord(id, marketId);

    let partnershipBonus = 0;
    if (record && record.partnerId >= 0) {
      partnershipBonus = this.getBaseMarketingInfluence(record.partnerId, marketId) * 0.3;
    }

    return base * mainMarketBonus + partnershipBonus;
  }

  getPowerListOnMarket(marketId) {
    let sum = 0;

    const marketRecords = _markets.filter(m => m.marketId === marketId);

    const influences = marketRecords
      .map(({ companyId, marketId }) => {
        const power = this.getPowerOfCompanyOnMarket(companyId, marketId);

        sum += power;

        return {
          name: this.getName(companyId),
          power,
          companyId,
          marketId
        };
      });

    return influences
      .map(m => Object.assign({}, m, { share: percentify(m.power / sum) }))
      .sort((a, b) => b.power - a.power);
  }

  isPartneredOnMarket(c1, c2, marketId) {
    const record = this.getMarketRecord(c1, marketId);

    if (!record) return false;

    return record.partnerId === c2;
  }

  getCompanyDevelopmentValue(id) {

  };

  getMarketInfo(id, marketId) {
    return this.getDefaults(id).markets[marketId];
  }

  getMarketInfluenceOfCompany(id, marketId) {
    const powers = this.getPowerListOnMarket(marketId);

    const power = powers.find(c => c.companyId === id).power;

    const sum = powers.map(p => p.power).reduce((p, c) => p + c, 0);

    return power / sum;
  }

  getMarketSize(id, marketId) {
    const { price, clients } = this.getMarketInfo(id, marketId);

    return price * clients;
  }

  calculateMarketIncome(id, marketId, improvement, influenceOnMarket) {
    const rating = this.getRating(id, marketId, improvement);

    const paymentModifier = this.getPaymentModifier(id);

    const efficiency = rating * paymentModifier / 10;

    return Math.floor(this.getMarketSize(id, marketId) * efficiency * influenceOnMarket);
  }

  isMarketFree(marketId) {
    return -1 === _markets.findIndex(m => m.marketId === marketId);
  }

  getPointModificationStructured(id) {
    const monthlyProgrammingPointsDifferenceStructured = (id = 0) => {
      logger.shit('getProgrammingSupportCost with zero index... ' +
        'we need real ID of our product!! /helpers/points/modification.js');

      const decrease = this.getProgrammingSupportCost(id);
      const increase = this.getMonthlyProgrammerPoints(id);

      return {
        increase,
        decrease,
        needToHireWorker: decrease > increase,
        diff: Math.abs(decrease - increase)
      }
    };

    const monthlyMarketingPointsDifferenceStructured = (id = 0) => {
      const decrease = this.getMarketingSupportCost(id);
      const increase = this.getMonthlyMarketerPoints(id);

      return {
        increase,
        decrease,
        detailed: {
          markets: this.getOurMarketsSupportCostList(id)
        },
        needToHireWorker: decrease > increase,
        diff: Math.abs(decrease - increase)
      }
    };

    return {
      programming: () => monthlyProgrammingPointsDifferenceStructured(id),
      marketing: () => monthlyMarketingPointsDifferenceStructured(id)
    }
  }

  getIncomeIncreaseIfWeIncreaseInfluenceOnMarket(id, marketId) {
    // logger.debug('getIncomeIncreaseIfWeIncreaseInfluenceOnMarket', id, marketId);

    if (this.isHaveInfluenceOnMarket(id, marketId)) {
      const powerIncreaseMultiplier = this.getNextInfluenceMarketingCost(id, marketId) / this.getCurrentInfluenceMarketingCost(id, marketId);

      const powers = this.getPowerListOnMarket(marketId);

      const index = powers.findIndex(p => p.companyId === id);

      const prevShare = powers[index].share;
      powers[index].share = prevShare * powerIncreaseMultiplier;

      const shares = powers.map(p => p.share).reduce((p, c) => p + c, 0);

      const nextShare = powers[index].share * 100 / shares;

      const income = this.getMarketIncome(id, marketId) * (nextShare / prevShare - 1);

      return Math.floor(income);
    } else if (this.isMarketFree(marketId)) {
      return this.calculateMarketIncome(id, marketId, null, 1);
    } else {
      // market is not free, and we are trying entering it
      const powers = this.getPowerListOnMarket(marketId);

      const newPower = this.getNextInfluenceMarketingCost(id, marketId);

      const shares = powers.map(p => p.power).reduce((p, c) => p + c, 0) + newPower;

      return this.calculateMarketIncome(id, marketId, null, newPower / shares);
    }
  }

  isHaveInfluenceOnMarket(id, marketId) {
    return _markets.find(m => m.companyId === id && m.marketId === marketId);
  }

  isAvailableToLeaveMarket(id, marketId) {
    return this.isHaveInfluenceOnMarket(id, marketId);
  }

  getBaseMarketingInfluence(id, marketId) {
    const record = this.getMarketRecord(id, marketId);

    if (!record) {
      logger.error('no record found in getBaseMarketingInfluence(id, marketId)', id, marketId, _markets);

      return 0;
    }

    const level = record.level;

    return this.getMarketInfo(id, marketId).levels[level];
  }

  getCurrentInfluenceMarketingCost(id, marketId) {
    if (!this.isAvailableToLeaveMarket(id, marketId)) return 0;

    const level = this.getMarketLevelOfCompany(id, marketId);

    return this.getMarketInfo(id, marketId).levels[level];
  }

  getNextInfluenceMarketingCost(id, marketId) {
    if (!this.isCanIncreaseMarketLevel(id, marketId)) return 0;

    const level = this.getMarketLevelOfCompany(id, marketId);

    return this.getMarketInfo(id, marketId).levels[level + 1];
  }

  getMarketLevelOfCompany(id, marketId) {
    const record = _markets.find(m => m.companyId === id && m.marketId === marketId);

    if (record) return record.level;

    return -1;
  }

  getMonthlyMPChange(id) {
    return this.getMonthlyMarketerPoints(id) - this.getMarketingSupportCost(id);
  }

  isMaxLevelReached(id, marketId) {
    const max = this.getMarketInfo(id, marketId).levels.length;
    const current = this.getMarketLevelOfCompany(id, marketId);

    return max === current;
  }

  isFreeMarket(marketId) {
    return _markets.filter(m => m.marketId === marketId).length
  }

  getShareableFeatureIdList(id) {
    return this.getDefaults(id).features.filter((f, fId) => this.isShareableFeature(id, fId)).map((f, fId) => f.id)
  }

  getMarketingAnalysis(id) {
    const markets = this.getMarkets(id);

    return markets.map(m => {
      let cost, enoughMPs, benefitOnLevelUp;

      let isFreeMarket = this.isFreeMarket(m.id);

      const isMaxLevelReached = this.isMaxLevelReached(id, m.id);

      if (isMaxLevelReached) {
        cost = 0;
        enoughMPs = true;
        benefitOnLevelUp = 0;
      } else {
        cost = this.getNextInfluenceMarketingCost(id, m.id) - this.getCurrentInfluenceMarketingCost(id, m.id);
        enoughMPs = this.getMonthlyMPChange(id) >= cost;
        benefitOnLevelUp = this.getIncomeIncreaseIfWeIncreaseInfluenceOnMarket(id, m.id);
      }

      const canIncreaseInfluence = !isMaxLevelReached && enoughMPs;

      let ROI = 0;
      if (cost) {
        ROI = benefitOnLevelUp / cost;
      }

      return {
        canIncreaseInfluence,
        isMaxLevelReached,
        enoughMPs,
        isFreeMarket,
        cost,
        benefitOnLevelUp,
        ROI,
        marketId: m.id
      }
    })
  }

  isCanIncreaseMarketLevel(id, marketId) {
    const max = this.getMarketInfo(id, marketId).levels.length - 1;

    return this.getMarketLevelOfCompany(id, marketId) < max;
  }

  getMarketIncome = (id, marketId, improvement) => {
    if (!this.isHaveInfluenceOnMarket(id, marketId)) return 0;

    const influenceOnMarket = this.getMarketInfluenceOfCompany(id, marketId);

    return this.calculateMarketIncome(id, marketId, improvement, influenceOnMarket);
  };

  getProductIncome(id) {
    const records = _markets
      .filter(m => m.companyId === id);

    if (!records.length) return 0;

    return records
      .map((m, i) => this.getMarketIncome(id, m.marketId, null))
      .reduce((p, c) => p + c, 0);
  }

  getIdea(id) {
    return _products[id].getIdea();
  }

  getMarketingFeatures(id) {
    return _products[id].getMarketingFeatures();
  }

  getSupportPower(id) {
    return _products[id].getSupportPower();
  }

  getEmailPower(id) {
    return _products[id].getEmailPower();
  }

  getMarketingSupportCostPerClientForSupportFeature(id) {
    return _products[id].getMarketingSupportCostPerClientForSupportFeature();
  }

  getProductSupportCost(id) {
    return _products[id].getProductSupportCost();
  }

  getProductExpenses(id) {
    return _products[id].getProductExpenses();
  }

  getName(id) {
    return _products[id].getName();
  }

  getStage(id) {
    return _products[id].getStage();
  }

  getFeatureStatus(id, featureGroup, featureName) {
    return _products[id].getFeatureStatus(featureGroup, featureName);
  }

  getBonusStatus(id, bonusName) {
    return _products[id].getFeatureStatus('bonuses', bonusName);
  }

  getAvailableBonuses(id) {
    return _products[id].getAvailableBonuses();
  }

  getBonuses(id) {
    return Object.keys(_products[id].features.bonuses);
  }

  getBonusesList(id) {
    return _products[id].getBonusesList();
  }

  getMarketRecord(id, marketId) {
    return _markets.find(m => m.marketId === marketId && m.companyId === id);
  }

  isMainMarket(id, marketId) {
    const record = this.getMarketRecord(id, marketId);

    if (!record) return false;

    return record.isMainMarket;
  }

  getClientAnalyticsModifier(id) {
    return _products[id].getClientAnalyticsModifier();
  }

  getProgrammingSupportCostModifier(id) {
    return _products[id].getProgrammingSupportCostModifier();
  }

  getProgrammingSupportCost(id) {
    return _products[id].getProgrammingSupportCost();
  }

  getBaseSupportCost(id = 0) {
    return _products[id].getBaseSupportCost();
  }

  getOurMarketsSupportCostList(id) {
    return _markets
      .filter(m => m.companyId === id)
      .map(m => ({
          cost: this.getCurrentInfluenceMarketingCost(id, m.marketId),
          name: this.getMarketName(id, m.marketId)
        })
      )
  }

  getMarketingSupportCost(id) {
    const baseCost = this.getOurMarketsSupportCostList(id).map(item => item.cost).reduce((p, c) => p + c, 0);

    return Math.ceil(baseCost * (1 - _products[id].getMarketingSupportCost() / 100));
    // return _products[id].getMarketingSupportCost();
  }

  getMarketingFeatureList(id) {
    return _products[id].getMarketingFeatureList();
  };

  getHypothesisAnalyticsFeatures(id) {
    return _products[id].getHypothesisAnalyticsFeatures();
  };

  getPaymentFeatures(id) {
    return _products[id].getPaymentFeatures();
  };

  getImprovementChances(id) {
    return _products[id].getImprovementChances()
  }

  getProductExpensesStructure(id) {
    return _products[id].getProductExpensesStructure();
  }

  getXP(id) {
    return _products[id].getXP();
  }

  getHypothesisPoints(id) {
    return _products[id].getHypothesisPoints();
  }

  getDescriptionOfProduct(id) {
    return _products[id].getDescriptionOfProduct();
  }

  getTestsAmount(id) {
    return _products[id].getTestsAmount();
  }

  getImprovementsAmount(id) {
    return _products[id].getImprovementsAmount();
  }

  getTechnologyComplexityModifier(id) {
    return _products[id].getTechnologyComplexityModifier();
  }

  getBonusesAmount(id) {
    return _products[id].bonuses;
  }

  getNumberOfTechnologiesWhereWeMadeBreakthrough(id) {
    return _products[id].getNumberOfTechnologiesWhereWeMadeBreakthrough();
  }

  getTechnicalDebtModifier(id) {
    return _products[id].getTechnicalDebtModifier();
  }

  idHelper(p, i) {
    return { id: i, p };
  }

  isUpgradeWillResultTechBreakthrough(id, featureId) {
    const current = this.getMainFeatureQualityByFeatureId(id, featureId);
    const max = this.getCurrentMainFeatureDefaultsById(id)[featureId];

    return current + 1000 > max;
  }

  isWeAreRetards(id, featureId) {
    const current = this.getMainFeatureQualityByFeatureId(id, featureId);
    const max = this.getCurrentMainFeatureDefaultsById(id)[featureId];

    return current < 0.6 * max;
  }

  getBonusModifiers(id) {
    return _products[id].getBonusModifiers();
  }

  getBaseFeatureDevelopmentCost(id, featureId) {
    return productDescriptions(this.getIdea(id)).features[featureId].development;
  }

  getMainFeatureUpgradeCost(id, featureId) {
    let modifier = 1;

    logger.shit('write isUpgradeWillResultTechBreakthrough function!!');

    // we are able to make breakthrough
    if (this.isUpgradeWillResultTechBreakthrough(id, featureId)) {
      modifier = 4  - _products[id].getBonusModifiers().techBreakthroughDiscount / 100;
    }

    // we are retards
    if (this.isWeAreRetards(id, featureId)) {
      modifier = 0.25 - _products[id].getBonusModifiers().followerDiscount / 100;
    }

    const specificFeatureModifier = 1 - _products[id].getSpecificFeatureDevelopmentCostModifier(featureId) / 100;

    modifier *= specificFeatureModifier;

    return Math.ceil(this.getBaseFeatureDevelopmentCost(id, featureId) * modifier);
  }

  getLeaderInTech(id, featureId) {
    const leader = _products.map(this.idHelper)
      .filter((obj, i) => obj.p.idea === this.getIdea(id))
      .sort((obj1, obj2) => {
        const p1: Product = obj1.p;
        const p2: Product = obj2.p;

        const f1 = p1.getMainFeatureQualityByFeatureId(featureId);
        const f2 = p2.getMainFeatureQualityByFeatureId(featureId);

        return f2 - f1;
      })[0];

    return {
      id: leader.id,
      name: leader.p.name,
      value: leader.p.getMainFeatureQualityByFeatureId(featureId)
    }
  }

  ceilXPtoThousandValue(value) {
    return Math.ceil(value / 1000) * 1000;
  }

  getCurrentMainFeatureDefaultsById(id) {
    return getCurrentMainFeatureDefaultsById(id);
  }

  isShareableFeature(id, featureId) {
    return productDescriptions(this.getIdea(id)).features[featureId].shareable;
  }

  temporaryMaxFeatureValue(id, featureId) {
    return this.ceilXPtoThousandValue(this.getLeaderInTech(id, featureId).value);
  }

  getUpgradedMaxDefaultFeatureValueList(id) {
    return this.getDefaults(id).features.map((f, featureId) => {
      const base = this.getMainFeatureQualityByFeatureId(id, featureId);

      const leader = (Math.floor(this.getLeaderInTech(id, featureId).value / 1000) + 1) * 1000;

      return leader > base ? leader : base;
    });
  }

  isUpgradingMainFeatureWillResultTechLeadership(id, featureId) {
    const current = this.getMainFeatureQualityByFeatureId(id, featureId);

    const max = this.temporaryMaxFeatureValue(id, featureId);

    return current + 1000 > max;
  }

  getCurrentMainFeatureDefaultsByIdea(idea) {
    return getCurrentMainFeatureDefaultsByIdea(idea);
  }

  getCompetitorsList() {
    logger.shit('getCompetitorsList shows ALL COMPANIES with different ideas! ' +
      'You need an opportunity to toggle between all/same idea companies');

    return _products
      .map((p, i) => ({ p, id: i }))
      .map(obj => {
        const p: Product = obj.p;
        const id = obj.id;

        const rating = this.getRating(id, 0);

        const features = p.features.offer;

        const offer = this.getDefaults(id).features
          .map((f, i) => ({
            name: f.name,
            description: f.shortDescription,
            value: features[i]
          }));

        return {
          id,
          rating,
          style: p.style,
          clients: p.KPI.clients,
          name: p.name,
          features: offer,
          cost: this.getCompanyCost(id),
          company: p,
          income: this.getProductIncome(id),
          expenses: this.getProductExpenses(id)
        }
      });
    // .sort((a, b) => b.cost - a.cost);
  }
}

const store = new ProductStore();

const payload = payloads.productStorePayload;
type PayloadType = payload.type;

Dispatcher.register((p: PayloadType) => {
  if (!p.type) {
    logger.error(`empty type prop in payload ${payload.name}`, p);
    return;
  }

  const id = p.id;

  let change = true;
  switch (p.type) {
    case c.PRODUCT_ACTIONS_SET_PRODUCT_DEFAULTS:
      _products[id].setProductDefaults(PRODUCT_STAGES.PRODUCT_STAGE_NORMAL, p.KPI, p.features, 1999);
      break;

    case c.PRODUCT_ACTIONS_TEST_HYPOTHESIS:
      _products[id].testHypothesis(p);
      break;

    case c.PRODUCT_ACTIONS_SWITCH_STAGE:
      _products[id].switchStage(p.stage);
      break;

    case c.PRODUCT_ACTIONS_IMPROVE_FEATURE:
      _products[id].improveFeature(p);

      logger.shit('rewrite upgradedDefaults updating in Product.js class. ' +
        'You need updating it only on improve Main Feature actions');

      const upgradedDefaults = getCurrentMainFeatureDefaultsById(id);
      const idea = _products[id].getIdea();

      _products
        .filter(p => p.idea === idea)
        .forEach((p) => {
          p.setMainFeatureDefaults(upgradedDefaults);
        });
      break;

    case c.PRODUCT_ACTIONS_IMPROVE_FEATURE_BY_POINTS:
      _products[id].improveFeatureByPoints(p);
      break;

    case c.PRODUCT_ACTIONS_CLIENTS_ADD:
      _products[id].addClients(p);
      break;

    case c.PRODUCT_ACTIONS_CLIENTS_REMOVE:
      _products[id].removeClients(p);
      break;

    case c.PRODUCT_ACTIONS_HYPE_ADD:
      _products[id].addHype(p.hype);
      break;

    case c.PRODUCT_ACTIONS_HYPE_MONTHLY_DECREASE:
      _products[id].loseMonthlyHype(p.hypeDamping);
      break;

    case c.PRODUCT_ACTIONS_MARKETS_INFLUENCE_INCREASE:
      let index = getMarketRecordIndex(p.id, p.marketId);

      if (index >= 0) {
        _markets[index].level++;
      } else {
        _markets.push({ companyId: p.id, marketId: p.marketId, level: 0, partnerId: -1 });
      }
      break;

    case c.PRODUCT_ACTIONS_MARKETS_INFLUENCE_DECREASE:
      index = getMarketRecordIndex(p.id, p.marketId);

      if (index >= 0) {
        clearPartnershipOf(p.id, p.marketId);

        _markets.splice(index, 1)
      }
      break;

    case c.PRODUCT_ACTIONS_MARKETS_SET_AS_MAIN:
      const currentIndex = getCurrentMainMarket(p.id);

      if (currentIndex >= 0) {
        _markets[currentIndex].isMainMarket = false;
      }

      index = getMarketRecordIndex(p.id, p.marketId);
      if (index >= 0) {
        _markets[index].isMainMarket = true;
      }
      break;

    case c.PRODUCT_ACTIONS_MARKETS_PARTNERSHIP_REVOKE:
      let c1 = p.c1;
      let c2 = p.c2;

      clearPartnershipOf(c1, p.marketId);
      clearPartnershipOf(c2, p.marketId);
      break;

    case c.PRODUCT_ACTIONS_MARKETS_PARTNERSHIP_OFFER:
      c1 = p.c1;
      c2 = p.c2;

      const record1 = getMarketRecordIndex(c1, p.marketId);
      const record2 = getMarketRecordIndex(c2, p.marketId);

      clearPartnershipOf(c1, p.marketId);
      clearPartnershipOf(c2, p.marketId);

      _markets[record1].partnerId = c2;
      _markets[record2].partnerId = c1;
      break;

    case c.PRODUCT_ACTIONS_CREATE_COMPETITOR_COMPANY:
      const competitor: Product = p.p;

      competitor.setCompetitorProductDefaults(PRODUCT_STAGES.PRODUCT_STAGE_NORMAL, 0);

      _products.push(competitor);
      break;

    case c.PRODUCT_ACTIONS_COMPANY_BUY:
      logger.debug('buy company store');
      const { buyerId, sellerId } = p;

      const buyer = _products[buyerId];
      const seller = _products[sellerId];

      const difference = companyMerger.merge(buyer, seller);

      _products[buyerId].KPI.clients = difference.clients;
      _products[buyerId].features.offer = difference.features;

      _products.splice(sellerId, 1);
      break;

    case c.PRODUCT_ACTIONS_TECHNOLOGY_RENT:
      _rents.push({
        in: p.acceptor,
        out: p.sender,
        featureId: p.featureId,
        price: p.price,
        until: p.until
      });
      break;

    case c.PRODUCT_ACTIONS_TECHNOLOGY_RENT_REFRESH:
      // it must be reversed in product-actions from max id to min id
      logger.debug(p, 'refresh');
      p.list.forEach((id) => {
        _rents.splice(id, 1);
      });
      break;

    case c.PLAYER_ACTIONS_INCREASE_MONEY:
      _products[p.id || 0]._money += p.amount;
      break;

    case c.PLAYER_ACTIONS_INCREASE_POINTS:
      logger.shit('|| 0 in PLAYER_ACTIONS_INCREASE_POINTS pr store');
      _products[p.id || 0]._points.marketing += p.points.marketing;
      _products[p.id || 0]._points.programming += p.points.programming;
      break;

    case c.PLAYER_ACTIONS_DECREASE_POINTS:
      logger.shit('|| 0 in PLAYER_ACTIONS_DECREASE_POINTS pr store');
      _products[p.id || 0]._points.marketing -= p.mp;
      _products[p.id || 0]._points.programming -= p.pp;
      break;

    case c.PLAYER_ACTIONS_EXPENSES_ADD:
      _expenses.push(p.expense);
      break;

    case c.PLAYER_ACTIONS_EXPENSES_REMOVE:
      _expenses.splice(p.id, 1);
      break;

    case c.PLAYER_ACTIONS_LOANS_TAKE:
      logger.shit('LOAN SIZE MUST BASE ON YOUR INCOME!!!. stores product-store.js');

      const repay = 1.3;
      _products[p.id || 0]._money += p.amount;
      _loan += p.amount * repay;

      _expenses.push({
        type: EXPENSES.EXPENSES_LOAN,
        price: p.amount * repay,
        regularity: 1
      });
      break;

    case c.PLAYER_ACTIONS_LOANS_REPAY:
      let loanSize = _expenses[p.id].price;
      if (loanSize <= _money) {
        _money -= loanSize;
        _loan -= loanSize;

        _expenses.splice(p.id, 1);
      } else {
        change = false;
      }
      break;

    case c.PRODUCT_ACTIONS_BONUSES_ADD:
      _products[p.id].bonuses++;
      break;

    case c.PLAYER_ACTIONS_SET_TASK:
      _team[p.index].task = p.task;
      break;

    case c.PLAYER_ACTIONS_HIRE_WORKER:
      _team.push(p.player);
      _employees.splice(p.i, 1);
      break;

    case c.PLAYER_ACTIONS_FIRE_WORKER:
      _money -= _team[p.i].salary.money;
      _team.splice(p.i, 1);
      break;

    case c.PLAYER_ACTIONS_EMPLOYEE_ADD:
      _employees.push(p.player);
      break;

    case c.PLAYER_ACTIONS_UPDATE_EMPLOYEES:
      _employees = [
        workerGenerator.create(),
        workerGenerator.create(),
        workerGenerator.create(),
        workerGenerator.create(),
        workerGenerator.create(),
        workerGenerator.create(),
        workerGenerator.create(),
        workerGenerator.create(),
        workerGenerator.create()
      ];
      break;

    case c.PLAYER_ACTIONS_EMPLOYEE_REMOVE:
      _employees.splice(p.i, 1);
      break;

    default:
      change = false;
      break;
  }

  if (change) {
    stats.saveAction(p.type, p);
    sessionManager.saveProductStorageData(ProductStore.getStoreData());

    store.emitChange();
  }
});

export default store;


text:
namespace Nop.Core.Plugins
{
    public class OfficialFeedPlugin
    {
        public string Name { get; set; }
        public string Url { get; set; }
        public string PictureUrl { get; set; }
        public string Category { get; set; }
        public string SupportedVersions { get; set; }
        public string Price { get; set; }
    }
}


text:
/*************************************************************************/
/*                                                                       */
/*                Centre for Speech Technology Research                  */
/*                     University of Edinburgh, UK                       */
/*                       Copyright (c) 1996,1997                         */
/*                        All Rights Reserved.                           */
/*                                                                       */
/*  Permission is hereby granted, free of charge, to use and distribute  */
/*  this software and its documentation without restriction, including   */
/*  without limitation the rights to use, copy, modify, merge, publish,  */
/*  distribute, sublicense, and/or sell copies of this work, and to      */
/*  permit persons to whom this work is furnished to do so, subject to   */
/*  the following conditions:                                            */
/*   1. The code must retain the above copyright notice, this list of    */
/*      conditions and the following disclaimer.                         */
/*   2. Any modifications must be clearly marked as such.                */
/*   3. Original authors' names are not deleted.                         */
/*   4. The authors' names are not used to endorse or promote products   */
/*      derived from this software without specific prior written        */
/*      permission.                                                      */
/*                                                                       */
/*  THE UNIVERSITY OF EDINBURGH AND THE CONTRIBUTORS TO THIS WORK        */
/*  DISCLAIM ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING      */
/*  ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT   */
/*  SHALL THE UNIVERSITY OF EDINBURGH NOR THE CONTRIBUTORS BE LIABLE     */
/*  FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES    */
/*  WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN   */
/*  AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,          */
/*  ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF       */
/*  THIS SOFTWARE.                                                       */
/*                                                                       */
/*************************************************************************/
/*                 Authors:  Alan W Black                                */
/*                 Date   :  December 1997                               */
/*-----------------------------------------------------------------------*/
/*  Access to the Ngrammar                                               */
/*                                                                       */
/*=======================================================================*/
#include <cstdio>
#include "festival.h"
#include "festivalP.h"

static LISP ngram_loaded_list = NIL;
static EST_Ngrammar *load_ngram(const EST_String &filename);
static LISP add_ngram(const EST_String &name,EST_Ngrammar *n);

SIOD_REGISTER_CLASS(ngrammar,EST_Ngrammar)

static LISP lisp_load_ngram(LISP name, LISP filename)
{
    EST_Ngrammar *n;

    n = load_ngram(get_c_string(filename));
    add_ngram(get_c_string(name),n);

    return name;
}

static EST_Ngrammar *load_ngram(const EST_String &filename)
{
    EST_Ngrammar *n = new EST_Ngrammar();
    if (n->load(filename) != 0)
    {
	fprintf(stderr,"Ngrammar: failed to read ngrammar from \"%s\"",
		(const char *)filename);
	festival_error();
    }

    return n;
}

static LISP add_ngram(const EST_String &name,EST_Ngrammar *n)
{
    LISP lpair;

    lpair = siod_assoc_str(name,ngram_loaded_list);

    if (ngram_loaded_list == NIL)
    {   // First time round so do a little initialization
	gc_protect(&ngram_loaded_list);
    }

    LISP ng = siod(n);

    if (lpair == NIL)
	ngram_loaded_list =
	    cons(cons(strintern(name),cons(ng,NIL)),ngram_loaded_list);
    else
    {
	cwarn << "Ngrammar: " << name << " recreated" << endl;
	setcar(cdr(lpair),ng);
    }

    return ng;
}

EST_Ngrammar *get_ngram(const EST_String &name,const EST_String &filename)
{
    //  Find ngram named name, returns NULL if none;
    LISP lpair;

    lpair = siod_assoc_str(name,ngram_loaded_list);

    if (lpair == NIL)
    {
	if (filename != EST_String::Empty)
	{
	    EST_Ngrammar *n = load_ngram(filename);
	    add_ngram(name,n);
	    return n;
	}
	else
	{
	    cwarn << "Ngrammar: no ngram named \"" << name << "\"" << endl;
	    return 0;
	}
    }
    else
	return ngrammar(car(cdr(lpair)));
}

void festival_ngram_init()
{
    init_subr_2("ngram.load",lisp_load_ngram,
 "(ngram.load NAME FILENAME)\n\
  Load an ngram from FILENAME and store it named NAME for later access.");

}


text:
@interface AuthCheckInterfaceController()

@end

@implementation AuthCheckInterfaceController

- (void)awakeWithContext:(id)context {
    [super awakeWithContext:context];

    // Configure interface objects here.
}

- (void)willActivate {
    // This method is called when watch view controller is about to be visible to user
    [super willActivate];

	[NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timerJob) userInfo:nil repeats:NO];
}

- (void)didDeactivate {
    // This method is called when watch view controller is no longer visible
    [super didDeactivate];
}

- (void)timerJob {

	if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusNotDetermined) {
		[NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timerJob) userInfo:nil repeats:NO];
	}
	else {
		[self popController];
	}
}

@end


text:
/* MIT License */

/* Below templating is mini-library that enables basic templating abilities */
var templating = function() {
    "use strict";

    function location(cssSelector) {
        return document.querySelector(cssSelector);
    }
    function applyTemplate(templateNode, dataLiteral) {
        var templateHTML = templateNode.innerHTML.toString();
        for (var data in dataLiteral) {
            templateHTML = templateHTML.replace(new RegExp("{{" + data + "}}", "g"), dataLiteral[data]);
        }
        return templateHTML;
    }
    function insertInNode(elementNode, htmlString) {
        elementNode.innerHTML = htmlString;
    }

    return {
        insertInNode: insertInNode,
        applyTemplate: applyTemplate,
        location: location
    };

}();


text:
'use strict';

var Promise  = require('bluebird');
var restling = require('restling');

module.exports = function (db, config) {
    var generateBarcode = require('../../lib/generateBarcode');

    return function (isExt) {
        return function (req, res) {
            var eventId = req.params.eventId;
            if (!req.form.isValid) {
                return Error.emit(res, 400, '400 - Bad Request', req.form.errors);
            }

            var priceWanted;
            var priceWantedExt;
            var newTicketId;

            db.Event
                .find(eventId)
                .then(function (event) {
                    if (!event) {
                        throw new Error.emit(res, 404, '404 - Not Found', 'no event');
                    }

                    if (!event.opened) {
                        throw new Error.emit(res, 404, '404 - Not Found', 'event not opened');
                    }
                })
                .then(function () {
                    return new Promise(function (resolve, reject) {
                        if (isExt) {
                            db.Token
                                .count({
                                    mailCheck: req.form.code,
                                    usermail: req.form.mail
                                })
                                .then(function (count) {
                                    if (count === 0) {
                                        Error.emit(res, 401, '401 - Unauthorized', 'no token');
                                        return reject();
                                    }

                                    return resolve();
                                })
                                .catch(reject);
                        } else {
                            req.form.displayName = req.user.firstname.nameCapitalize() + ' ' + req.user.lastname.nameCapitalize();
                            req.form.mail = req.user.mail;
                            return resolve();
                        }
                    });
                })
                .then(function () {
                    return new Promise(function (resolve, reject) {
                        generateBarcode(resolve, reject, db.Ticket);
                    });
                })
                .then(function (barcode) {
                    return new Promise(function (resolve, reject) {
                        db.SchoolDomain
                            .findAll()
                            .then(function (domains) {
                                var partnerPrice = false;
                                domains.forEach(function (domain) {
                                    var reg = new RegExp('@' + domain.domain + '$', 'i');
                                    if (reg.test(req.form.mail)) {
                                        partnerPrice = true;
                                    }
                                });

                                return resolve([barcode, partnerPrice]);
                            })
                            .catch(reject);
                    });
                })
                .then(function (data) {
                    // data: [barcode, partnerMail]
                    return new Promise(function (resolve, reject) {
                        if (req.user) {
                            if (req.user.inBDE) {
                                db.Price
                                    .find({
                                        where: {
                                            event_id: eventId,
                                            name: { like: '%cotisant en prévente' }
                                        }
                                    })
                                    .then(function (price) {
                                        if (!price) {
                                            return reject();
                                        }

                                        return resolve([price, data[0], 1, 1]);
                                    })
                                    .catch(reject);
                            } else {
                                db.Price
                                    .find({
                                        where: {
                                            event_id: eventId,
                                            name: { like: '%non-cotisant en prévente' }
                                        }
                                    }).then(function (price) {
                                        if (!price) {
                                            return reject();
                                        }

                                        return resolve([price, data[0], 1, 0]);
                                    })
                                    .catch(reject);
                            }
                        } else {
                            if (data[1]) {
                                db.Price
                                    .find({
                                        where: {
                                            event_id: eventId,
                                            name: { like: '%partenaire en prévente' }
                                        }
                                    })
                                    .then(function (price) {
                                        if (!price) {
                                            return reject();
                                        }

                                        return resolve([price, data[0], 0, 0]);
                                    })
                                    .catch(reject);
                            } else {
                                db.Price
                                    .find({
                                        where: {
                                            event_id: eventId,
                                            name: { like: '%extérieur en prévente' }
                                        }
                                    })
                                    .then(function (price) {
                                        if (!price) {
                                            return reject();
                                        }

                                        return resolve([price, data[0], 0, 0]);
                                    })
                                    .catch(reject);
                            }
                        }
                    });
                })
                .then(function (data) {
                    // data [price, barcode, student, contributor]
                    priceWanted = data[0];
                    return db.Ticket.create({
                        username: (req.user) ? req.user.id : 0,
                        displayName: req.form.displayName,
                        birthdate: req.form.birthdate,
                        mail: req.form.mail,
                        student: data[2],
                        contributor: data[3],
                        paid: 0,
                        paid_at: null,
                        paid_with: 'card',
                        barcode: data[1],
                        price_id: data[0].id,
                        event_id: eventId
                    });
                })
                .then(function (newTicket) {
                    newTicketId = newTicket.id;
                    if (req.form.additionalExtTickets) {
                        return new Promise(function (resolve, reject) {
                            db.Price
                                .find({
                                    where: {
                                        event_id: eventId,
                                        name: { like: '%extérieur en prévente' }
                                    }
                                })
                                .then(function (price) {
                                    if (!price) {
                                        Error.emit(res, 404, '404 - Not Found');
                                        return reject();
                                    }

                                    priceWantedExt = price;

                                    return resolve(price);
                                })
                                .catch(reject);
                        });
                    }
                })
                .then(function () {
                    if (req.form.additionalExtTickets && !req.form.isExt) {
                        var additionalExtTickets = req.body.additionalExtTickets;
                        var promises = [];
                        additionalExtTickets.forEach(function () {
                            promises.push(new Promise (function (resolve, reject) {
                                generateBarcode(resolve, reject, db.Ticket);
                            }));
                        });

                        return Promise.all(promises);
                    }
                })
                .then(function (barcodes) {
                    if (req.form.additionalExtTickets && !req.form.isExt) {
                        var additionalExtTickets = req.body.additionalExtTickets;
                        return additionalExtTickets.map(function (additionalExtTicket, i) {
                            return db.Ticket.create({
                                username: (req.user) ? req.user.id : 0,
                                displayName: additionalExtTicket.displayName,
                                birthdate: additionalExtTicket.birthdate,
                                mail: req.form.mail,
                                student: 0,
                                contributor: 0,
                                paid: 0,
                                paid_at: null,
                                paid_with: 'card',
                                barcode: barcodes[i],
                                price_id: priceWantedExt.id,
                                event_id: eventId,
                                mainTicket: newTicketId
                            });
                        });
                    }
                })
                .then(function () {
                    return new Promise(function (resolve, reject) {
                        if (isExt) {
                            db.Token
                                .destroy({
                                    where: {
                                        mailCheck: req.form.code,
                                        usermail: req.form.mail
                                    }
                                })
                                .then(function () {
                                    return resolve();
                                })
                                .catch(reject);
                        }

                        var totalCost = priceWanted.price * 100;
                        if (req.form.additionalExtTickets) {
                            totalCost += req.form.additionalExtTickets.length * (priceWantedExt.price * 100);
                        }

                        return restling.post(config.sherlocks.host + 'pay/' + totalCost, {
                            data: newTicketId,
                            service: config.sherlocks.paymentId
                        });
                    });
                })
                .then(function (sherlocksRes) {
                    return new Promise(function (resolve, reject) {
                        db.Token
                            .create({
                                ticket: newTicketId,
                                sherlocksToken: sherlocksRes.data.token
                            })
                            .then(function () {
                                return resolve(sherlocksRes);
                            })
                            .catch(reject);
                    });
                })
                .then(function (sherlocksRes) {
                    return res
                            .redirect(config.sherlocks.host + 'initiate/' + sherlocksRes.data.id);
                })
                .catch(function (err) {
                    return Error.emit(res, 500, '500 - SQL Server error', err);
                });
        };
    };
};


text:
package msg

import (
	"io"

	"github.com/btcboost/copernicus/core"
)

const (
	HeaderSize       = 80
	AllowedTimeDrift = 2 * 60 * 60
	MaxBlockSize     = 1 * 1000 * 1000
)

type BlockMessage struct {
	Block *core.Block
	Txs   []*TxMessage
}

func (blockMessage *BlockMessage) AddTx(tx *TxMessage) error {
	blockMessage.Txs = append(blockMessage.Txs, tx)
	return nil
}

func (blockMessage *BlockMessage) ClearTxs() {
	blockMessage.Txs = make([]*TxMessage, 0, 2048)
}

func (blockMessage *BlockMessage) BitcoinSerialize(w io.Writer, size uint32) error {
	return nil
}

func (blockMessage *BlockMessage) BitcoinParse(reader io.Reader, size uint32) error {
	return nil
}

func (blockMessage *BlockMessage) Command() string {
	return CommandBlock
}

func (blockMessage *BlockMessage) MaxPayloadLength(size uint32) uint32 {
	return 0
}


text:
/**
 * Provides generic adapters to map datatypes for JPA.
 *
Lang Base Datatype Adapter JPA
 This package contains classes to add support for custom
 * {@link net.sf.mmm.util.lang.api.Datatype}s in Java Persistence API (JPA).
 *
 * @see net.sf.mmm.util.lang.base.datatype.adapter.jpa.AbstractSimpleDatatypeAttributeConverter
 */
package net.sf.mmm.util.lang.base.datatype.adapter.jpa;


text:
.class Lcom/android/internal/widget/ActionBarContextView$2;
.super Ljava/lang/Object;
.source "ActionBarContextView.java"

# interfaces
.implements Landroid/view/View$OnClickListener;

# annotations
.annotation system Ldalvik/annotation/EnclosingMethod;
    value = Lcom/android/internal/widget/ActionBarContextView;->initForMode(Landroid/view/ActionMode;)V
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x0
    name = null
.end annotation

# instance fields
.field final synthetic this$0:Lcom/android/internal/widget/ActionBarContextView;

.field final synthetic val$mode:Landroid/view/ActionMode;

# direct methods
.method constructor <init>(Lcom/android/internal/widget/ActionBarContextView;Landroid/view/ActionMode;)V
    .locals 0
    .parameter
    .parameter

    .prologue
    .line 347
    iput-object p1, p0, Lcom/android/internal/widget/ActionBarContextView$2;->this$0:Lcom/android/internal/widget/ActionBarContextView;

    iput-object p2, p0, Lcom/android/internal/widget/ActionBarContextView$2;->val$mode:Landroid/view/ActionMode;

    invoke-direct/range {p0 .. p0}, Ljava/lang/Object;-><init>()V

    return-void
.end method

# virtual methods
.method public onClick(Landroid/view/View;)V
    .locals 1
    .parameter "v"

    .prologue
    .line 349
    iget-object v0, p0, Lcom/android/internal/widget/ActionBarContextView$2;->val$mode:Landroid/view/ActionMode;

    invoke-virtual {v0}, Landroid/view/ActionMode;->finish()V

    .line 350
    return-void
.end method


text:
'require util/polyfill';

$jscomp.polyfill('String.fromCodePoint', function(orig) {
  if (orig) return orig;

  /**
   * Creates a new string from the given codepoints.
   *
   * <p>Polyfills the static function String.fromCodePoint().
   *
   * @param {...number} var_args
   * @return {string}
   */
  var polyfill = function(var_args) {
    // Note: this is taken from v8's harmony-string.js StringFromCodePoint.
    var result = '';
    for (var i = 0; i < arguments.length; i++) {
      var code = Number(arguments[i]);
      if (code < 0 || code > 0x10FFFF || code !== Math.floor(code)) {
        throw new RangeError('invalid_code_point ' + code);
      }
      if (code <= 0xFFFF) {
        result += String.fromCharCode(code);
      } else {
        code -= 0x10000;
        result += String.fromCharCode((code >>> 10) & 0x3FF | 0xD800);
        result += String.fromCharCode(code & 0x3FF | 0xDC00);
      }
    }
    return result;
  };

  return polyfill;
}, 'es6', 'es3');


text:
namespace ui {

namespace {

HINSTANCE resources_data_dll;

HINSTANCE GetCurrentResourceDLL() {
  if (resources_data_dll)
    return resources_data_dll;
  return GetModuleHandle(NULL);
}

base::FilePath GetResourcesPakFilePath(const std::string& pak_name) {
  base::FilePath path;
  if (PathService::Get(base::DIR_MODULE, &path))
    return path.AppendASCII(pak_name.c_str());

  // Return just the name of the pack file.
  return base::FilePath(base::ASCIIToUTF16(pak_name));
}

}  // namespace

void ResourceBundle::LoadCommonResources() {
  // As a convenience, add the current resource module as a data packs.
  data_packs_.push_back(new ResourceDataDLL(GetCurrentResourceDLL()));

  if (IsScaleFactorSupported(SCALE_FACTOR_100P)) {
    AddDataPackFromPath(
        GetResourcesPakFilePath("chrome_100_percent.pak"),
        SCALE_FACTOR_100P);
  }
  if (IsScaleFactorSupported(SCALE_FACTOR_200P)) {
    DCHECK(gfx::IsHighDPIEnabled());
    AddDataPackFromPath(
        GetResourcesPakFilePath("chrome_200_percent.pak"),
        SCALE_FACTOR_200P);
  }
}

gfx::Image& ResourceBundle::GetNativeImageNamed(int resource_id, ImageRTL rtl) {
  // Flipped image is not used on Windows.
  DCHECK_EQ(rtl, RTL_DISABLED);

  // Windows only uses SkBitmap for gfx::Image, so this is the same as
  // GetImageNamed.
  return GetImageNamed(resource_id);
}

// static
SkBitmap ResourceBundle::PlatformScaleImage(const SkBitmap& image,
                                            float loaded_image_scale,
                                            float desired_bitmap_scale) {
  if (!gfx::IsHighDPIEnabled())
    return image;

  // On Windows we can have multiple device scales like 1/1.25/1.5/2, etc.
  // We only have 1x and 2x data packs. We need to scale the bitmaps
  // accordingly.
  if (loaded_image_scale == desired_bitmap_scale)
    return image;

  SkBitmap scaled_image;
  gfx::Size unscaled_size(image.width(), image.height());
  gfx::Size scaled_size = ToCeiledSize(
      gfx::ScaleSize(unscaled_size,
                      desired_bitmap_scale / loaded_image_scale));
  scaled_image = skia::ImageOperations::Resize(
      image,
      skia::ImageOperations::RESIZE_LANCZOS3,
      scaled_size.width(),
      scaled_size.height());
  DCHECK_EQ(scaled_image.width(), scaled_size.width());
  DCHECK_EQ(scaled_image.height(), scaled_size.height());
  return scaled_image;
}

void SetResourcesDataDLL(HINSTANCE handle) {
  resources_data_dll = handle;
}

HICON LoadThemeIconFromResourcesDataDLL(int icon_id) {
  return ::LoadIcon(GetCurrentResourceDLL(), MAKEINTRESOURCE(icon_id));
}

}  // namespace ui;


text:
package org.wso2.carbon.event.input.adaptor.file.internal.util;

import org.apache.commons.io.input.Tailer;
import org.wso2.carbon.event.input.adaptor.file.internal.listener.FileTailerListener;

public class FileTailerManager {

    private Tailer tailer;
    private FileTailerListener listener;

    public FileTailerManager(Tailer tailer, FileTailerListener listener) {
        super();
        this.tailer = tailer;
        this.listener = listener;
    }

    public Tailer getTailer() {
        return tailer;
    }

    public FileTailerListener getListener() {
        return listener;
    }

}


text:
package org.gingolph.gingmap;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Stream;

import org.tmapi.core.Locator;
import org.tmapi.core.ModelConstraintException;
import org.tmapi.core.Name;
import org.tmapi.core.Topic;
import org.tmapi.core.Variant;

public class NameImpl extends ScopedTopicMapItem<TopicImpl, NameSupport>
    implements Name, Valued, TypedConstruct {

  public NameImpl(TopicMapImpl topicMap, TopicImpl parent) {
    super(topicMap, parent);
  }

  @Override
  protected void notifyOwner() {
    support.setOwner(this);
  }

  @Override
  public String getValue() {
    return support.getValue();
  }

  @Override
  public void setValue(String value) throws ModelConstraintException {
    if (value == null) {
      throw new ModelConstraintException(this, "Null value not allowed");
    }
    String oldValue = support.getValue();
    support.setValue(value);
    getTopicMap().notifyListeners(listener -> listener.onValueChanged(this, value, oldValue));

  }

  @Override
  public Set<Variant> getVariants() {
    List<VariantImpl> variants = support.getVariants();
    return variants == null || variants.isEmpty()? Collections.emptySet() : new UnmodifiableCollectionSet<>(variants);
  }

  public Stream<VariantImpl> variants() {
    List<VariantImpl> variants = support.getVariants();
    return variants == null?Stream.empty():variants.stream();
  }

  @Override
  public Variant createVariant(String value, Topic... scope) throws ModelConstraintException {
    if (scope == null) {
      throw new ModelConstraintException(this, "Null scope not allowed");
    }
    return createVariant(value, Arrays.asList(scope));
  }

  @Override
  public Variant createVariant(String value, Collection<Topic> scope)
      throws ModelConstraintException {
    return createVariant(value, LocatorImpl.XSD_STRING, scope);
  }

  @Override
  public Variant createVariant(Locator value, Topic... scope) throws ModelConstraintException {
    if (scope == null) {
      throw new ModelConstraintException(this, "Null scope not allowed");
    }
    return createVariant(value, Arrays.asList(scope));
  }

  @Override
  public Variant createVariant(Locator value, Collection<Topic> scope)
      throws ModelConstraintException {
    return createVariant(LocatorImpl.XSD_ANY_URI, value, scope);
  }

  @Override
  public Variant createVariant(String value, Locator dataType, Topic... scope)
      throws ModelConstraintException {
    if (scope == null) {
      throw new ModelConstraintException(this, "Null scope not allowed");
    }
    return createVariant(value, dataType, Arrays.asList(scope));
  }

  @Override
  public VariantImpl createVariant(String value, Locator dataType, Collection<Topic> scope)
      throws ModelConstraintException {
    return createVariant(dataType, value, scope);
  }

  private VariantImpl createVariant(Locator datatype, Object value, Collection<Topic> scope)
      throws ModelConstraintException {
    if (scope == null) {
      throw new ModelConstraintException(this, "Null scope not allowed");
    }
    if (scope.isEmpty()) {
      throw new ModelConstraintException(this, "Empty scope not allowed");
    }
    if (this.getScope().containsAll(scope)) {
      throw new ModelConstraintException(this, "Scope is not a superset of parent's scope");
    }
    VariantImpl variant = getTopicMap().createVariant(this, datatype, value);
    support.addVariant(variant);
    // Collection<Topic> parentAndSelfScope = new HashSet<>();
    // parentAndSelfScope.addAll(scope);
    // parentAndSelfScope.addAll(getScope());
    variant.setScope(scope);
    getTopicMap().notifyListeners(listener -> listener.onConstructCreated(variant));
    return variant;
  }

  @Override
  public TopicImpl getType() {
    return support.getType();
  }

  @Override
  public void setType(Topic type) {
    TypedInstanceHelper.setType(this, type, this::doSetType);
  }

  protected final void doSetType(Topic type) {
    support.setType((TopicImpl)type);
  }

  @Override
  public void customRemove() {
    Collection<Variant> variants = new ArrayList<>(getVariants());
    variants.forEach(variant -> variant.remove());

    getParent().removeName(this);
  }

  void removeVariant(VariantImpl variant) {
    support.removeVariant(variant);
  }

  @Override
  public Set<Topic> getScope() {
    return ScopedHelper.getScope(support.getScope());
  }

  protected final void setScope(Collection<Topic> scope) {
    ScopedHelper.setScope(this, scope, getSupport(), getTopicMap().getEquality());
  }

  @Override
  public void addTheme(Topic theme) throws ModelConstraintException {
    ScopedHelper.addTheme(this, theme, getSupport(), getTopicMap().getEquality());
  }

  @Override
  public void removeTheme(Topic theme) {
    ScopedHelper.removeTheme(this, theme, getSupport());
  }

  @Override
  public TopicImpl getReifier() {
    return support.getReifier();
  }

  @Override
  public void setReifier(Topic reifier) throws ModelConstraintException {
    ReifierHelper.setReifier(this, reifier, this::doSetReifier);
  }

  protected void doSetReifier(TopicImpl reifier) {
    support.setReifier(reifier);
  }

  @Override
  protected boolean equalsFromEquality(Object otherObjectOfSameClass) {
    return getTopicMap().getEquality().equals(this, (NameImpl)otherObjectOfSameClass);
  }

  // consistent with equals and avoid too much overhead calculating hashCodes of Type and Scope ... sounds like a reasonable default.
//  @Override
//  public int hashCode() {
//    return Objects.hashCode(getValue());
//  }
//

  @Override
  protected int hashCodeFromEquality() {
    return getTopicMap().getEquality().hashCode(this);
  }

  @Override
  public String toString() {
    return "[value="+getValue()+"], [variants="+getVariants()+"], type="+getType();
  }
}


text:
package org.cyclops.integrateddynamics.core.ingredient;

import org.cyclops.commoncapabilities.api.ingredient.IMixedIngredients;
import org.cyclops.commoncapabilities.api.ingredient.IngredientComponent;
import org.cyclops.commoncapabilities.api.ingredient.MixedIngredientsAdapter;

import java.util.List;
import java.util.Set;

/**
 * A wrapper around ingredients.
 * @author rubensworks
 */
public class WrappedIngredients extends MixedIngredientsAdapter {

    private final IMixedIngredients ingredients;

    public WrappedIngredients(IMixedIngredients ingredients) {
        this.ingredients = ingredients;
    }

    @Override
    public Set<IngredientComponent<?, ?>> getComponents() {
        return ingredients.getComponents();
    }

    @Override
    public <T> List<T> getInstances(IngredientComponent<T, ?> ingredientComponent) {
        return ingredients.getInstances(ingredientComponent);
    }

}


text:
package com.accela.tetrixgame.conn.support.ReflectionSupport;

import java.lang.reflect.Constructor;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import com.accela.tetrixgame.Common;
import com.accela.tetrixgame.conn.support.ObjectPool.ObjectPool;

/**
 *
 * 这个类使用ParameterGenerator来完成使用反射测试一个类的构造函数, 并新建对象的工作。
 *
 * ObjectCreator会自动记住构造函数列表、能够成功新建对像的构造函数,以及 能够成功新建对象的参数列表 //TODO
 * 新加上的缓冲区功能都没有经过详尽的测试 //TODO 未经详尽测试,只是通过HPObjectStreams间接验证过
 */
public class ObjectCreator {
	/**
	 * 用来抽取构造函数
	 */
	private static final ConstructorExtractor constructorExtractor = new ConstructorExtractor();
	/**
	 * 用来记录以前找到的,能够成功新建对象的构造函数。 下次再需要新建用样的对象的时候,就可以直接使用了。
	 */
	private static final Map<Class<?>, Constructor<?>> hitConstructorMap = new ConcurrentHashMap<Class<?>, Constructor<?>>();
	/**
	 * 记录一组可以成功使构造函数新建出对像的参数。 下次再遇到同样的构造函数的时候,就可以直接使用了。
	 */
	private static final Map<Constructor<?>, Object[]> hitParamMap = new ConcurrentHashMap<Constructor<?>, Object[]>();

	private static final CaseObjectCreator caseCreator = new CaseObjectCreator();

	/**
	 * 尽力测试objectClass的构造函数,试图找到一个可以用的构造函数并新建对像。 如果实在找不到,则返回null。
	 *
	 * //TODO 有一个BUG,如果构造函数中的参数类型存在循环,就会使得ObjectCreator卡死 //TODO
	 * 但是这种情况应该很少见,毕竟此时应该有其他构造函数可以使用,它们应该被优先选中
	 */
	public Object createObject(Class<?> objectClass) {
		if (null == objectClass) {
			throw new NullPointerException("objectClass should not be null");
		}

		// 尝试使用CaseObjectCreator创建
		Object caseRet = caseCreator.createInstance(objectClass);
		if (caseRet != null) {
			assert (caseRet.getClass() == objectClass);
			return caseRet;
		}

		// 尝试从对象池中寻找
		Object result = ObjectPool.retrieve(objectClass);
		if (result != null) {
			assert (result.getClass() == objectClass);
			return result;
		}

		// 尝试旧的存储的构造函数
		Constructor<?> oldConstructor = hitConstructorMap.get(objectClass);
		if (oldConstructor != null) {
			Object newInstance = tryConstructor(oldConstructor);

			if (newInstance != null) {
				return newInstance;
			} else {
				// 这种情况不应该出现,因此用assert(false)。但是如果关掉异常,
				// 这里通过后就可以重新用遍历构造函数的方法来尝试,增加健壮性。
				assert (false);
			}
		}

		// 遍历构造函数,依次尝试
		Constructor<?>[] constructors = constructorExtractor
				.getConstructors(objectClass);

		Object newInstance = null;
		for (int i = 0; i < constructors.length; i++) {
			try {
				newInstance = tryConstructor(constructors[i]);
				if (newInstance != null) {
					assert (newInstance.getClass() == objectClass);

					// 记录成功试出结果的构造函数
					hitConstructorMap.put(objectClass, constructors[i]);

					break;
				}
			} catch (Exception ex) {
				ex.printStackTrace();
			}
		}

		return newInstance;
	}

	/**
	 * 用各种参数试探一个构造函数,试图新建对象,如果所有尝试 都失败了,则返回null
	 *
	 * @param constructor
	 * @return
	 */
	private Object tryConstructor(final Constructor<?> constructor) {
		Object result = null;
		constructor.setAccessible(true);

		// 从旧有的记录中尝试能否成功
		Object[] oldParams = hitParamMap.get(constructor);
		if (oldParams != null) {
			try {
				result = constructor.newInstance(oldParams);
				assert (result != null);

				if (result != null) {
					return result;
				}
			} catch (Exception ex) {
				System.err.println("constructor is : " + constructor);
				ex.printStackTrace();
				assert (false);
			}
		}

		// 尝试遍历构造函数的参数的各种可能,来创建新的对象

		Class<?>[] parameterTypes = constructor.getParameterTypes();
		ParameterGenerator[] parameterGenerators = new ParameterGenerator[parameterTypes.length];
		for (int i = 0; i < parameterGenerators.length; i++) {
			parameterGenerators[i] = getParameterGenerator();
		}

		Object[] parameters = new Object[parameterTypes.length];

		int fillingIdx = 0;
		while (fillingIdx >= 0) {
			if (fillingIdx < parameters.length) {
				if (parameterGenerators[fillingIdx].hasNext()) {
					parameters[fillingIdx] = parameterGenerators[fillingIdx]
							.createParameter(parameterTypes[fillingIdx], this);
					fillingIdx++;
				} else {
					parameterGenerators[fillingIdx].reset();
					fillingIdx--;
				}
			} else {
				try {
					result = constructor.newInstance(parameters);
					assert (result != null);

					// 记录成功试出结果的参数
					hitParamMap.put(constructor, parameters);

					break;
				} catch (Exception ex) {
					fillingIdx--;
				}
			}
		}

		for (ParameterGenerator ppg : parameterGenerators) {
			disposeParameterGenerator(ppg);
		}

		return result;
	}

	/**
	 * 与ppgStack配合,取得一个ParameterGenerator。使用这个
	 * 方法来取ParameterGenerator对象才能完成ParameterGenerator 的使用优化。
	 *
	 * @return 一个ParameterStack对象
	 */
	private ParameterGenerator getParameterGenerator() {
		return ParameterGenerator.getParameterGenerator();
	}

	/**
	 * 当用完了一个ParameterGenerator对象后,应该通过这个方法
	 * 来释放,这样才能使ParameterGenererator对象被重复利用。
	 *
	 * @param ppg
	 *            要释放的ParameterGenerator对象
	 */
	private void disposeParameterGenerator(ParameterGenerator ppg) {
		if (null == ppg) {
			throw new NullPointerException("ppg should not be null");
		}

		ParameterGenerator.disposeParameterGenerator(ppg);
	}

}


text:
package main

import (
	"fmt"
	"net/http"
	"sort"
	"strconv"
	"strings"
	"sync"
	"time"

	"github.com/gorilla/mux"
	"github.com/pkg/errors"

	"github.com/lxc/lxd/lxd/cluster"
	"github.com/lxc/lxd/lxd/db"
	"github.com/lxc/lxd/lxd/db/query"
	"github.com/lxc/lxd/lxd/filter"
	"github.com/lxc/lxd/lxd/instance"
	"github.com/lxc/lxd/lxd/instance/instancetype"
	"github.com/lxc/lxd/lxd/response"
	"github.com/lxc/lxd/shared"
	"github.com/lxc/lxd/shared/api"
	"github.com/lxc/lxd/shared/logger"
	"github.com/lxc/lxd/shared/version"
)

// urlInstanceTypeDetect detects what sort of instance type filter is being requested. Either
// explicitly via the instance-type query param or implicitly via the endpoint URL used.
func urlInstanceTypeDetect(r *http.Request) (instancetype.Type, error) {
	reqInstanceType := r.URL.Query().Get("instance-type")
	if strings.HasPrefix(mux.CurrentRoute(r).GetName(), "container") {
		return instancetype.Container, nil
	} else if strings.HasPrefix(mux.CurrentRoute(r).GetName(), "vm") {
		return instancetype.VM, nil
	} else if reqInstanceType != "" {
		instanceType, err := instancetype.New(reqInstanceType)
		if err != nil {
			return instancetype.Any, err
		}
		return instanceType, nil
	}

	return instancetype.Any, nil
}

func containersGet(d *Daemon, r *http.Request) response.Response {
	for i := 0; i < 100; i++ {
		result, err := doContainersGet(d, r)
		if err == nil {
			return response.SyncResponse(true, result)
		}
		if !query.IsRetriableError(err) {
			logger.Debugf("DBERR: containersGet: error %q", err)
			return response.SmartError(err)
		}
		// 100 ms may seem drastic, but we really don't want to thrash
		// perhaps we should use a random amount
		time.Sleep(100 * time.Millisecond)
	}

	logger.Debugf("DBERR: containersGet, db is locked")
	logger.Debugf(logger.GetStack())
	return response.InternalError(fmt.Errorf("DB is locked"))
}

func doContainersGet(d *Daemon, r *http.Request) (interface{}, error) {
	resultString := []string{}
	resultList := []*api.Instance{}
	resultFullList := []*api.InstanceFull{}
	resultMu := sync.Mutex{}

	instanceType, err := urlInstanceTypeDetect(r)
	if err != nil {
		return nil, err
	}

	// Parse the recursion field
	recursionStr := r.FormValue("recursion")

	recursion, err := strconv.Atoi(recursionStr)
	if err != nil {
		recursion = 0
	}

	// Parse filter value
	filterStr := r.FormValue("filter")
	var clauses []filter.Clause
	if filterStr != "" {
		clauses, err = filter.Parse(filterStr)
		if err != nil {
			return nil, errors.Wrap(err, "Invalid filter")
		}
	}

	// Parse the project field
	project := projectParam(r)

	// Get the list and location of all containers
	var result map[string][]string // Containers by node address
	var nodes map[string]string    // Node names by container
	err = d.cluster.Transaction(func(tx *db.ClusterTx) error {
		var err error

		result, err = tx.GetInstanceNamesByNodeAddress(project, instanceType)
		if err != nil {
			return err
		}

		nodes, err = tx.GetInstanceToNodeMap(project, instanceType)
		if err != nil {
			return err
		}

		return nil
	})
	if err != nil {
		return []string{}, err
	}

	// Get the local instances
	nodeCts := map[string]instance.Instance{}
	mustLoadObjects := recursion > 0 || (recursion == 0 && clauses != nil)
	if mustLoadObjects {
		cts, err := instanceLoadNodeProjectAll(d.State(), project, instanceType)
		if err != nil {
			return nil, err
		}

		for _, ct := range cts {
			nodeCts[ct.Name()] = ct
		}
	}

	// Append containers to list and handle errors
	resultListAppend := func(name string, c api.Instance, err error) {
		if err != nil {
			c = api.Instance{
				Name:       name,
				Status:     api.Error.String(),
				StatusCode: api.Error,
				Location:   nodes[name],
			}
		}
		resultMu.Lock()
		resultList = append(resultList, &c)
		resultMu.Unlock()
	}

	resultFullListAppend := func(name string, c api.InstanceFull, err error) {
		if err != nil {
			c = api.InstanceFull{Instance: api.Instance{
				Name:       name,
				Status:     api.Error.String(),
				StatusCode: api.Error,
				Location:   nodes[name],
			}}
		}
		resultMu.Lock()
		resultFullList = append(resultFullList, &c)
		resultMu.Unlock()
	}

	// Get the data
	wg := sync.WaitGroup{}
	for address, containers := range result {
		// If this is an internal request from another cluster node,
		// ignore containers from other nodes, and return only the ones
		// on this node
		if isClusterNotification(r) && address != "" {
			continue
		}

		// Mark containers on unavailable nodes as down
		if mustLoadObjects && address == "0.0.0.0" {
			for _, container := range containers {
				if recursion < 2 {
					resultListAppend(container, api.Instance{}, fmt.Errorf("unavailable"))
				} else {
					resultFullListAppend(container, api.InstanceFull{}, fmt.Errorf("unavailable"))
				}
			}

			continue
		}

		// For recursion requests we need to fetch the state of remote
		// containers from their respective nodes.
		if mustLoadObjects && address != "" && !isClusterNotification(r) {
			wg.Add(1)
			go func(address string, containers []string) {
				defer wg.Done()
				cert := d.endpoints.NetworkCert()

				if recursion == 1 {
					cs, err := doContainersGetFromNode(project, address, cert, instanceType)
					if err != nil {
						for _, name := range containers {
							resultListAppend(name, api.Instance{}, err)
						}

						return
					}

					for _, c := range cs {
						resultListAppend(c.Name, c, nil)
					}

					return
				}

				cs, err := doContainersFullGetFromNode(project, address, cert, instanceType)
				if err != nil {
					for _, name := range containers {
						resultFullListAppend(name, api.InstanceFull{}, err)
					}

					return
				}

				for _, c := range cs {
					resultFullListAppend(c.Name, c, nil)
				}
			}(address, containers)

			continue
		}
		if !mustLoadObjects {
			for _, container := range containers {
				instancePath := "instances"
				if strings.HasPrefix(mux.CurrentRoute(r).GetName(), "container") {
					instancePath = "containers"
				} else if strings.HasPrefix(mux.CurrentRoute(r).GetName(), "vm") {
					instancePath = "virtual-machines"
				}
				url := fmt.Sprintf("/%s/%s/%s", version.APIVersion, instancePath, container)
				resultString = append(resultString, url)
			}
		} else {
			threads := 4
			if len(containers) < threads {
				threads = len(containers)
			}

			queue := make(chan string, threads)

			for i := 0; i < threads; i++ {
				wg.Add(1)

				go func() {
					for {
						container, more := <-queue
						if !more {
							break
						}

						if recursion < 2 {
							c, _, err := nodeCts[container].Render()
							if err != nil {
								resultListAppend(container, api.Instance{}, err)
							} else {
								resultListAppend(container, *c.(*api.Instance), err)
							}

							continue
						}

						c, _, err := nodeCts[container].RenderFull()
						if err != nil {
							resultFullListAppend(container, api.InstanceFull{}, err)
						} else {
							resultFullListAppend(container, *c, err)
						}
					}

					wg.Done()
				}()
			}

			for _, container := range containers {
				queue <- container
			}

			close(queue)
		}
	}
	wg.Wait()

	if recursion == 0 {
		if clauses != nil {
			for _, container := range instance.Filter(resultList, clauses) {
				instancePath := "instances"
				if strings.HasPrefix(mux.CurrentRoute(r).GetName(), "container") {
					instancePath = "containers"
				} else if strings.HasPrefix(mux.CurrentRoute(r).GetName(), "vm") {
					instancePath = "virtual-machines"
				}
				url := fmt.Sprintf("/%s/%s/%s", version.APIVersion, instancePath, container.Name)
				resultString = append(resultString, url)
			}
		}
		return resultString, nil
	}

	if recursion == 1 {
		// Sort the result list by name.
		sort.Slice(resultList, func(i, j int) bool {
			return resultList[i].Name < resultList[j].Name
		})
		if clauses != nil {
			resultList = instance.Filter(resultList, clauses)
		}
		return resultList, nil
	}

	// Sort the result list by name.
	sort.Slice(resultFullList, func(i, j int) bool {
		return resultFullList[i].Name < resultFullList[j].Name
	})

	if clauses != nil {
		resultFullList = instance.FilterFull(resultFullList, clauses)
	}
	return resultFullList, nil
}

// Fetch information about the containers on the given remote node, using the
// rest API and with a timeout of 30 seconds.
func doContainersGetFromNode(project, node string, cert *shared.CertInfo, instanceType instancetype.Type) ([]api.Instance, error) {
	f := func() ([]api.Instance, error) {
		client, err := cluster.Connect(node, cert, true)
		if err != nil {
			return nil, errors.Wrapf(err, "Failed to connect to node %s", node)
		}

		client = client.UseProject(project)

		containers, err := client.GetInstances(api.InstanceType(instanceType.String()))
		if err != nil {
			return nil, errors.Wrapf(err, "Failed to get instances from node %s", node)
		}

		return containers, nil
	}

	timeout := time.After(30 * time.Second)
	done := make(chan struct{})

	var containers []api.Instance
	var err error

	go func() {
		containers, err = f()
		done <- struct{}{}
	}()

	select {
	case <-timeout:
		err = fmt.Errorf("Timeout getting instances from node %s", node)
	case <-done:
	}

	return containers, err
}

func doContainersFullGetFromNode(project, node string, cert *shared.CertInfo, instanceType instancetype.Type) ([]api.InstanceFull, error) {
	f := func() ([]api.InstanceFull, error) {
		client, err := cluster.Connect(node, cert, true)
		if err != nil {
			return nil, errors.Wrapf(err, "Failed to connect to node %s", node)
		}

		client = client.UseProject(project)

		instances, err := client.GetInstancesFull(api.InstanceType(instanceType.String()))
		if err != nil {
			return nil, errors.Wrapf(err, "Failed to get instances from node %s", node)
		}

		return instances, nil
	}

	timeout := time.After(30 * time.Second)
	done := make(chan struct{})

	var instances []api.InstanceFull
	var err error

	go func() {
		instances, err = f()
		done <- struct{}{}
	}()

	select {
	case <-timeout:
		err = fmt.Errorf("Timeout getting instances from node %s", node)
	case <-done:
	}

	return instances, err
}


text:
function [x,itn] = oneProjector(b,d,tau)
% ONEPROJECTOR  Projects b onto the weighted one-norm ball of radius tau
%
%    [X,ITN] = ONEPROJECTOR(B,TAU) returns the orthogonal projection
%    of the vector b onto the one-norm ball of radius tau. The return
%    vector X which solves the problem
%
%            minimize  ||b-x||_2  st  ||x||_1 <= tau.
%               x
%
%    [X,ITN] = ONEPROJECTOR(B,D,TAU) returns the orthogonal
%    projection of the vector b onto the weighted one-norm ball of
%    radius tau, which solves the problem
%
%            minimize  ||b-x||_2  st  || Dx ||_1 <= tau.
%               x
%
%    If D is empty, all weights are set to one, i.e., D = I.
%
%    In both cases, the return value ITN given the number of elements
%    of B that were thresholded.
%
% See also spgl1.

%   oneProjector.m
%   $Id: oneProjector.m 1200 2008-11-21 19:58:28Z mpf $
%
%   ----------------------------------------------------------------------
%   This file is part of SPGL1 (Spectral Projected Gradient for L1).
%
%   Copyright (C) 2007 Ewout van den Berg and Michael P. Friedlander,
%   Department of Computer Science, University of British Columbia, Canada.
%   All rights reserved. E-mail: <{ewout78,mpf}@cs.ubc.ca>.
%
%   SPGL1 is free software; you can redistribute it and/or modify it
%   under the terms of the GNU Lesser General Public License as
%   published by the Free Software Foundation; either version 2.1 of the
%   License, or (at your option) any later version.
%
%   SPGL1 is distributed in the hope that it will be useful, but WITHOUT
%   ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
%   or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General
%   Public License for more details.
%
%   You should have received a copy of the GNU Lesser General Public
%   License along with SPGL1; if not, write to the Free Software
%   Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
%   USA
%   ----------------------------------------------------------------------

% Check arguments
if nargin < 2
  error('The oneProjector function requires at least two parameters');
end
if nargin < 3
  tau = d;
  d   = [];
end

% Check weight vector
if isempty(d), d = 1; end;

if ~isscalar(d) && ( length(b) ~= length(d) )
  error('Vectors b and d must have the same length');
end

% Quick return for the easy cases.
if isscalar(d)  &&  d == 0
   x   = b;
   itn = 0;
   return
end

% Get sign of b and set to absolute values
s = sign(b);
b = abs(b);

% Perform the projection
if isscalar(d)
  [x,itn] = oneProjectorMex(b,tau/d);
else
  d   = abs(d);
  idx = find(d > eps); % Get index of all non-zero entries of d
  x   = b;             % Ensure x_i = b_i for all i not in index set idx
  [x(idx),itn] = oneProjectorMex(b(idx),d(idx),tau);
end

% Restore signs in x
x = x.*s;