text:
from AlgorithmImports import *
from Portfolio.MinimumVariancePortfolioOptimizer import MinimumVariancePortfolioOptimizer

### <summary>
### Provides an implementation of Mean-Variance portfolio optimization based on modern portfolio theory.
### The default model uses the MinimumVariancePortfolioOptimizer that accepts a 63-row matrix of 1-day returns.
### </summary>
class MeanVarianceOptimizationPortfolioConstructionModel(PortfolioConstructionModel):
    def __init__(self,
                 rebalance = Resolution.Daily,
                 portfolioBias = PortfolioBias.LongShort,
                 lookback = 1,
                 period = 63,
                 resolution = Resolution.Daily,
                 targetReturn = 0.02,
                 optimizer = None):
        """Initialize the model
        Args:
            rebalance: Rebalancing parameter. If it is a timedelta, date rules or Resolution, it will be converted into a function.
                              If None will be ignored.
                              The function returns the next expected rebalance time for a given algorithm UTC DateTime.
                              The function returns null if unknown, in which case the function will be called again in the
                              next loop. Returning current time will trigger rebalance.
            portfolioBias: Specifies the bias of the portfolio (Short, Long/Short, Long)
            lookback(int): Historical return lookback period
            period(int): The time interval of history price to calculate the weight
            resolution: The resolution of the history price
            optimizer(class): Method used to compute the portfolio weights"""
        super().__init__()
        self.lookback = lookback
        self.period = period
        self.resolution = resolution
        self.portfolioBias = portfolioBias
        self.sign = lambda x: -1 if x < 0 else (1 if x > 0 else 0)

        lower = 0 if portfolioBias == PortfolioBias.Long else -1
        upper = 0 if portfolioBias == PortfolioBias.Short else 1
        self.optimizer = MinimumVariancePortfolioOptimizer(lower, upper, targetReturn) if optimizer is None else optimizer

        self.symbolDataBySymbol = {}

        # If the argument is an instance of Resolution or Timedelta
        # Redefine rebalancingFunc
        rebalancingFunc = rebalance
        if isinstance(rebalance, int):
            rebalance = Extensions.ToTimeSpan(rebalance)
        if isinstance(rebalance, timedelta):
            rebalancingFunc = lambda dt: dt + rebalance
        if rebalancingFunc:
            self.SetRebalancingFunc(rebalancingFunc)

    def ShouldCreateTargetForInsight(self, insight):
        if len(PortfolioConstructionModel.FilterInvalidInsightMagnitude(self.Algorithm, [insight])) == 0:
            return False

        symbolData = self.symbolDataBySymbol.get(insight.Symbol)
        if insight.Magnitude is None:
            self.algorithm.SetRunTimeError(ArgumentNullException('MeanVarianceOptimizationPortfolioConstructionModel does not accept \'None\' as Insight.Magnitude. Please checkout the selected Alpha Model specifications.'))
            return False
        symbolData.Add(self.Algorithm.Time, insight.Magnitude)

        return True

    def DetermineTargetPercent(self, activeInsights):
        """
         Will determine the target percent for each insight
        Args:
        Returns:
        """
        targets = {}

        # If we have no insights just return an empty target list
        if len(activeInsights) == 0:
            return targets

        symbols = [insight.Symbol for insight in activeInsights]

        # Create a dictionary keyed by the symbols in the insights with an pandas.Series as value to create a data frame
        returns = { str(symbol) : data.Return for symbol, data in self.symbolDataBySymbol.items() if symbol in symbols }
        returns = pd.DataFrame(returns)

        # The portfolio optimizer finds the optional weights for the given data
        weights = self.optimizer.Optimize(returns)
        weights = pd.Series(weights, index = returns.columns)

        # Create portfolio targets from the specified insights
        for insight in activeInsights:
            weight = weights[str(insight.Symbol)]

            # don't trust the optimizer
            if self.portfolioBias != PortfolioBias.LongShort and self.sign(weight) != self.portfolioBias:
                weight = 0
            targets[insight] = weight

        return targets

    def OnSecuritiesChanged(self, algorithm, changes):
        '''Event fired each time the we add/remove securities from the data feed
        Args:
            algorithm: The algorithm instance that experienced the change in securities
            changes: The security additions and removals from the algorithm'''

        # clean up data for removed securities
        super().OnSecuritiesChanged(algorithm, changes)
        for removed in changes.RemovedSecurities:
            symbolData = self.symbolDataBySymbol.pop(removed.Symbol, None)
            symbolData.Reset()

        # initialize data for added securities
        symbols = [ x.Symbol for x in changes.AddedSecurities ]
        history = algorithm.History(symbols, self.lookback * self.period, self.resolution)
        if history.empty: return

        tickers = history.index.levels[0]
        for ticker in tickers:
            symbol = SymbolCache.GetSymbol(ticker)

            if symbol not in self.symbolDataBySymbol:
                symbolData = self.MeanVarianceSymbolData(symbol, self.lookback, self.period)
                symbolData.WarmUpIndicators(history.loc[ticker])
                self.symbolDataBySymbol[symbol] = symbolData

    class MeanVarianceSymbolData:
        '''Contains data specific to a symbol required by this model'''
        def __init__(self, symbol, lookback, period):
            self.symbol = symbol
            self.roc = RateOfChange(f'{symbol}.ROC({lookback})', lookback)
            self.roc.Updated += self.OnRateOfChangeUpdated
            self.window = RollingWindow[IndicatorDataPoint](period)

        def Reset(self):
            self.roc.Updated -= self.OnRateOfChangeUpdated
            self.roc.Reset()
            self.window.Reset()

        def WarmUpIndicators(self, history):
            for tuple in history.itertuples():
                self.roc.Update(tuple.Index, tuple.close)

        def OnRateOfChangeUpdated(self, roc, value):
            if roc.IsReady:
                self.window.Add(value)

        def Add(self, time, value):
            item = IndicatorDataPoint(self.symbol, time, value)
            self.window.Add(item)

        @property
        def Return(self):
            return pd.Series(
                data = [(1 + float(x.Value))**252 - 1 for x in self.window],
                index = [x.EndTime for x in self.window])

        @property
        def IsReady(self):
            return self.window.IsReady

        def __str__(self, **kwargs):
            return '{}: {:.2%}'.format(self.roc.Name, (1 + self.window[0])**252 - 1)


text:
namespace MassTransit.AmazonSqsTransport.Configuration.Configurators
{
    using System;
    using Amazon;
    using Amazon.SimpleNotificationService;
    using Amazon.SQS;

    public class ConfigurationHostSettings :
        AmazonSqsHostSettings
    {
        readonly Lazy<Uri> _hostAddress;

        public ConfigurationHostSettings()
        {
            _hostAddress = new Lazy<Uri>(FormatHostAddress);
        }

        public RegionEndpoint Region { get; set; }
        public string AccessKey { get; set; }
        public string SecretKey { get; set; }

        public AmazonSQSConfig AmazonSqsConfig { get; set; }

        public AmazonSimpleNotificationServiceConfig AmazonSnsConfig { get; set; }

        public Uri HostAddress => _hostAddress.Value;

        public IConnection CreateConnection()
        {
            return new Connection(AccessKey, SecretKey, Region, AmazonSqsConfig, AmazonSnsConfig);
        }

        Uri FormatHostAddress()
        {
            var builder = new UriBuilder
            {
                Scheme = "amazonsqs",
                Host = Region.SystemName,
                Path = "/"
            };

            return builder.Uri;
        }

        public override string ToString()
        {
            return new UriBuilder
            {
                Scheme = "https",
                Host = Region.SystemName
            }.Uri.ToString();
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
export WASABI_SERVER=http://localhost:8080/api/v1
# NOTE: CHANGE THIS TO BE YOUR LOGIN
export WASABI_LOGIN=admin:admin
export APP_NAME=MyStore
export EXP_NAME=TestBuyButtonColor

echo Creating experiment $EXP_NAME in new application $APP_NAME
curl -u ${WASABI_LOGIN} -H "Content-Type: application/json" -d "{\"applicationName\":\"${APP_NAME}\",\"label\":\"${EXP_NAME}\",\"samplingPercent\":1,\"startTime\":\"2016-04-27T00:00:00-0700\",\"endTime\":\"2017-08-19T00:00:00-0700\",\"description\":\"Experiment to test effect of different color Buy buttons.\"}" "${WASABI_SERVER}/experiments/?createNewApplication=true"
echo Created experiment, getting ID

# Get the experiment ID, needed in later API calls
export EXPERIMENT_ID=$(curl -u ${WASABI_LOGIN} ${WASABI_SERVER}/applications/${APP_NAME}/experiments/${EXP_NAME} | python -mjson.tool | sed -n 's/^.*id\".*\"\(.*\)\".*/\1/p')
echo Experiment ID: ${EXPERIMENT_ID}

# Create buckets
curl -u ${WASABI_LOGIN} -H "Content-Type: application/json" -d "{\"label\":\"Control\",\"allocationPercent\":0.3334,\"description\":\"Show the default button color, white.\",\"isControl\":true}" \
    "${WASABI_SERVER}/experiments/${EXPERIMENT_ID}/buckets"
echo Created bucket Control
curl -u ${WASABI_LOGIN} -H "Content-Type: application/json" -d "{\"label\":\"BlueButton\",\"allocationPercent\":0.3333,\"description\":\"Show a blue Buy button.\",\"isControl\":false}" \
    "${WASABI_SERVER}/experiments/${EXPERIMENT_ID}/buckets"
echo Created bucket BlueButton
curl -u ${WASABI_LOGIN} -H "Content-Type: application/json" -d "{\"label\":\"GreenButton\",\"allocationPercent\":0.3333,\"description\":\"Show a green Buy button.\",\"isControl\":false}" \
    "${WASABI_SERVER}/experiments/${EXPERIMENT_ID}/buckets"
echo Created bucket GreenButton

echo Starting experiment
curl -u ${WASABI_LOGIN} -X PUT -H "Content-Type: application/json" -d '{"state":"RUNNING"}' "${WASABI_SERVER}/experiments/${EXPERIMENT_ID}"
echo Experiment started


text:
package org.apache.solr.cloud;

import static java.util.Collections.singletonList;

import com.codahale.metrics.Counter;
import com.codahale.metrics.Metric;
import com.codahale.metrics.MetricRegistry;
import java.io.IOException;
import java.lang.invoke.MethodHandles;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.request.UpdateRequest;
import org.apache.solr.cloud.ZkTestServer.LimitViolationAction;
import org.apache.solr.common.SolrInputDocument;
import org.apache.solr.common.cloud.Replica;
import org.apache.solr.common.cloud.ZkStateReader;
import org.apache.solr.common.params.ModifiableSolrParams;
import org.apache.solr.common.util.TimeSource;
import org.apache.solr.core.CoreContainer;
import org.apache.solr.metrics.SolrMetricManager;
import org.apache.solr.util.TimeOut;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Test PeerSync when a node restarts and documents are indexed when node was down.
 *
 * <p>This test is modeled after SyncSliceTest
 */
public class PeerSyncReplicationTest extends AbstractFullDistribZkTestBase {

  private static final Logger log = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());

  private boolean success = false;
  int docId = 0;

  List<CloudJettyRunner> nodesDown = new ArrayList<>();

  @Override
  public void distribTearDown() throws Exception {
    if (!success) {
      printLayoutOnTearDown = true;
    }
    System.clearProperty("distribUpdateSoTimeout");
    System.clearProperty("solr.directoryFactory");
    System.clearProperty("solr.ulog.numRecordsToKeep");
    System.clearProperty("tests.zk.violationReportAction");
    super.distribTearDown();
  }

  public PeerSyncReplicationTest() {
    super();
    sliceCount = 1;
    fixShardCount(3);
  }

  @Override
  protected String getCloudSolrConfig() {
    return "solrconfig-tlog.xml";
  }

  @Override
  public void distribSetUp() throws Exception {
    // set socket timeout small, so replica won't be put into LIR state when they restart
    System.setProperty("distribUpdateSoTimeout", "3000");
    // tlog gets deleted after node restarts if we use CachingDirectoryFactory.
    // make sure that tlog stays intact after we restart a node
    System.setProperty("solr.directoryFactory", "solr.StandardDirectoryFactory");
    System.setProperty("solr.ulog.numRecordsToKeep", "1000");
    System.setProperty("tests.zk.violationReportAction", LimitViolationAction.IGNORE.toString());
    super.distribSetUp();
  }

  @Test
  // commented 2-Aug-2018 @BadApple(bugUrl="https://issues.apache.org/jira/browse/SOLR-12028")
  public void test() throws Exception {
    handle.clear();
    handle.put("timestamp", SKIPVAL);

    waitForThingsToLevelOut(30, TimeUnit.SECONDS);

    del("*:*");

    // index enough docs and commit to establish frame of reference for PeerSync
    for (int i = 0; i < 100; i++) {
      indexDoc(id, docId, i1, 50, tlong, 50, t1, "document number " + docId++);
    }
    commit();
    waitForThingsToLevelOut(30, TimeUnit.SECONDS);

    try {
      checkShardConsistency(false, true);

      long cloudClientDocs = cloudClient.query(new SolrQuery("*:*")).getResults().getNumFound();
      assertEquals(docId, cloudClientDocs);

      CloudJettyRunner initialLeaderJetty = shardToLeaderJetty.get("shard1");
      List<CloudJettyRunner> otherJetties = getOtherAvailableJetties(initialLeaderJetty);
      CloudJettyRunner neverLeader = otherJetties.get(otherJetties.size() - 1);
      otherJetties.remove(neverLeader);

      // first shutdown a node that will never be a leader
      forceNodeFailures(singletonList(neverLeader));

      // node failure and recovery via PeerSync
      log.info("Forcing PeerSync");
      CloudJettyRunner nodePeerSynced = forceNodeFailureAndDoPeerSync(false);

      // add a few more docs
      indexDoc(id, docId, i1, 50, tlong, 50, t1, "document number " + docId++);
      indexDoc(id, docId, i1, 50, tlong, 50, t1, "document number " + docId++);
      commit();

      cloudClientDocs = cloudClient.query(new SolrQuery("*:*")).getResults().getNumFound();
      assertEquals(docId, cloudClientDocs);

      // now shutdown all other nodes except for 'nodeShutDownForFailure'
      otherJetties.remove(nodePeerSynced);
      forceNodeFailures(otherJetties);
      waitForThingsToLevelOut(30, TimeUnit.SECONDS);
      checkShardConsistency(false, true);

      // now shutdown the original leader
      log.info("Now shutting down initial leader");
      forceNodeFailures(singletonList(initialLeaderJetty));
      log.info("Updating mappings from zk");
      waitForNewLeader(
          cloudClient,
          "shard1",
          (Replica) initialLeaderJetty.client.info,
          new TimeOut(15, TimeUnit.SECONDS, TimeSource.NANO_TIME));
      updateMappingsFromZk(jettys, clients, true);
      assertEquals(
          "PeerSynced node did not become leader",
          nodePeerSynced,
          shardToLeaderJetty.get("shard1"));

      // bring up node that was down all along, and let it PeerSync from the node that was forced to
      // PeerSync
      bringUpDeadNodeAndEnsureNoReplication(neverLeader, false);
      waitTillNodesActive();

      checkShardConsistency(false, true);

      // bring back all the nodes including initial leader
      // (commented as reports Maximum concurrent create/delete watches above limit violation and
      // reports thread leaks)
      /*for(int i = 0 ; i < nodesDown.size(); i++) {
        bringUpDeadNodeAndEnsureNoReplication(shardToLeaderJetty.get("shard1"), neverLeader, false);
      }
      checkShardConsistency(false, true);*/

      // make sure leader has not changed after bringing initial leader back
      assertEquals(nodePeerSynced, shardToLeaderJetty.get("shard1"));

      // assert metrics
      SolrMetricManager manager = nodePeerSynced.jetty.getCoreContainer().getMetricManager();
      MetricRegistry registry = null;
      for (String name : manager.registryNames()) {
        if (name.startsWith("solr.core.collection1")) {
          registry = manager.registry(name);
          break;
        }
      }
      assertNotNull(registry);
      Map<String, Metric> metrics = registry.getMetrics();
      assertTrue(
          "REPLICATION.peerSync.time present", metrics.containsKey("REPLICATION.peerSync.time"));
      assertTrue(
          "REPLICATION.peerSync.errors present",
          metrics.containsKey("REPLICATION.peerSync.errors"));

      Counter counter = (Counter) metrics.get("REPLICATION.peerSync.errors");
      assertEquals(0L, counter.getCount());
      success = true;
    } finally {
      System.clearProperty("solr.disableFingerprint");
    }
  }

  class IndexInBackGround extends Thread {
    private int numDocs;
    private CloudJettyRunner runner;

    public IndexInBackGround(int numDocs, CloudJettyRunner nodeToBringUp) {
      super(getClassName());
      this.numDocs = numDocs;
      this.runner = nodeToBringUp;
    }

    @Override
    public void run() {
      try {
        // If we don't wait for cores get loaded, the leader may put this replica into LIR state
        waitForCoreLoading();
        for (int i = 0; i < numDocs; i++) {
          indexDoc(id, docId, i1, 50, tlong, 50, t1, "document number " + docId);
          docId++;
          // slow down adds, to get documents indexed while in PeerSync
          Thread.sleep(100);
        }
      } catch (Exception e) {
        log.error("Error indexing doc in background", e);
        // Throwing an error here will kill the thread
      }
    }

    private void waitForCoreLoading() throws InterruptedException {
      while (true) {
        if (runner.jetty.getCoreContainer() != null) {
          CoreContainer cc = runner.jetty.getCoreContainer();
          cc.waitForLoadingCoresToFinish(20000);
          break;
        }
        Thread.sleep(100);
      }
    }
  }

  private void forceNodeFailures(List<CloudJettyRunner> replicasToShutDown) throws Exception {
    for (CloudJettyRunner replicaToShutDown : replicasToShutDown) {
      replicaToShutDown.jetty.stop();
    }

    int totalDown = 0;

    Set<CloudJettyRunner> jetties = new HashSet<>();
    jetties.addAll(shardToJetty.get("shard1"));

    if (replicasToShutDown != null) {
      jetties.removeAll(replicasToShutDown);
      totalDown += replicasToShutDown.size();
    }

    jetties.removeAll(nodesDown);
    totalDown += nodesDown.size();

    assertEquals(getShardCount() - totalDown, jetties.size());

    nodesDown.addAll(replicasToShutDown);
  }

  private CloudJettyRunner forceNodeFailureAndDoPeerSync(boolean disableFingerprint)
      throws Exception {
    // kill non leader - new leader could have all the docs or be missing one
    CloudJettyRunner leaderJetty = shardToLeaderJetty.get("shard1");

    List<CloudJettyRunner> nonLeaderJetties = getOtherAvailableJetties(leaderJetty);
    CloudJettyRunner replicaToShutDown =
        nonLeaderJetties.get(random().nextInt(nonLeaderJetties.size())); // random non leader node

    forceNodeFailures(Arrays.asList(replicaToShutDown));

    // two docs need to be synced back when replica restarts
    indexDoc(id, docId, i1, 50, tlong, 50, t1, "document number " + docId++);
    indexDoc(id, docId, i1, 50, tlong, 50, t1, "document number " + docId++);
    commit();

    bringUpDeadNodeAndEnsureNoReplication(replicaToShutDown, disableFingerprint);

    return replicaToShutDown;
  }

  private void bringUpDeadNodeAndEnsureNoReplication(
      CloudJettyRunner nodeToBringUp, boolean disableFingerprint) throws Exception {
    // disable fingerprint check if needed
    System.setProperty("solr.disableFingerprint", String.valueOf(disableFingerprint));
    // we wait a little while, so socket between leader -> replica will be timeout
    Thread.sleep(3000);
    IndexInBackGround iib = new IndexInBackGround(50, nodeToBringUp);
    iib.start();

    // bring back dead node and ensure it recovers
    nodeToBringUp.jetty.start();

    nodesDown.remove(nodeToBringUp);

    waitTillNodesActive();
    waitForThingsToLevelOut(30, TimeUnit.SECONDS);

    Set<CloudJettyRunner> jetties = new HashSet<>();
    jetties.addAll(shardToJetty.get("shard1"));
    jetties.removeAll(nodesDown);
    assertEquals(getShardCount() - nodesDown.size(), jetties.size());

    waitForThingsToLevelOut(30, TimeUnit.SECONDS);

    iib.join();

    cloudClient.commit();

    checkShardConsistency(false, false);

    long cloudClientDocs = cloudClient.query(new SolrQuery("*:*")).getResults().getNumFound();
    assertEquals(docId, cloudClientDocs);

    // if there was no replication, we should not have replication.properties file
    String replicationProperties =
        nodeToBringUp.jetty.getSolrHome()
            + "/cores/"
            + DEFAULT_TEST_COLLECTION_NAME
            + "/data/replication.properties";
    assertTrue(
        "PeerSync failed. Had to fail back to replication",
        Files.notExists(Paths.get(replicationProperties)));
  }

  private void waitTillNodesActive() throws Exception {
    ZkStateReader zkStateReader = ZkStateReader.from(cloudClient);
    zkStateReader.waitForState(
        "collection1",
        3,
        TimeUnit.MINUTES,
        (n, c) -> {
          Collection<String> nodesDownNames =
              nodesDown.stream().map(runner -> runner.coreNodeName).collect(Collectors.toList());
          Collection<Replica> replicas = c.getSlice("shard1").getReplicas();
          return replicas.stream()
              .filter(r -> !nodesDownNames.contains(r.getName()))
              .allMatch(r -> r.getState() == Replica.State.ACTIVE && n.contains(r.getNodeName()));
        });
  }

  private List<CloudJettyRunner> getOtherAvailableJetties(CloudJettyRunner leader) {
    List<CloudJettyRunner> candidates = new ArrayList<>();
    candidates.addAll(shardToJetty.get("shard1"));

    if (leader != null) {
      candidates.remove(leader);
    }

    candidates.removeAll(nodesDown);

    return candidates;
  }

  protected void indexDoc(Object... fields) throws IOException, SolrServerException {
    SolrInputDocument doc = new SolrInputDocument();

    addFields(doc, fields);
    addFields(doc, "rnd_s", RandomStringUtils.random(random().nextInt(100) + 100));

    UpdateRequest ureq = new UpdateRequest();
    ureq.add(doc);
    ModifiableSolrParams params = new ModifiableSolrParams();
    ureq.setParams(params);
    ureq.process(cloudClient);
  }

  // skip the randoms - they can deadlock...
  @Override
  protected void indexr(Object... fields) throws Exception {
    SolrInputDocument doc = new SolrInputDocument();
    addFields(doc, fields);
    addFields(doc, "rnd_b", true);
    indexDoc(doc);
  }
}


text:
import Control.Monad

import Prelude
import System.IO
import Text.PrettyPrint

import           Benchmark.Types
import qualified Benchmark.Blake2b.CPortable     as Blake2bCP
import qualified Benchmark.Blake2b.CHandWritten  as Blake2bCHW

import qualified Benchmark.Blake2s.CHandWritten  as Blake2sCHW

import qualified Benchmark.ChaCha20.CPortable    as ChaCha20CP
import qualified Benchmark.ChaCha20.CHandWritten as ChaCha20CHW

import qualified Benchmark.Poly1305.CPortable    as Poly1305CP

import qualified Benchmark.Sha256.CPortable      as Sha256CP
import qualified Benchmark.Sha256.CHandWritten   as Sha256CHW

import qualified Benchmark.Sha512.CPortable      as Sha512CP
import qualified Benchmark.Sha512.CHandWritten   as Sha512CHW

import qualified Benchmark.CSPRG.CPortable       as CSPRGCP

main :: IO ()
main = do
  hSetEncoding stdout utf8
  putStrLn $ render header
  mapM_ printBench [ Blake2bCP.bench
                   , Blake2bCHW.bench

                   , Blake2sCHW.bench

                   , Poly1305CP.bench

                   , CSPRGCP.bench

                   , ChaCha20CP.bench
                   , ChaCha20CHW.bench

                   , Sha256CP.bench
                   , Sha256CHW.bench

                   , Sha512CP.bench
                   , Sha512CHW.bench
                   ]

  where printBench = runRaazBench >=> pure . render >=> putStrLn


text:
import Immutable, {List, Map} from 'immutable';
import flatten from 'lodash/flatten';
import filter from 'lodash/filter';
import get from 'lodash/fp/get';

export function createPathObjects(state, path) {
  const setPath = [];
  return path.slice(0, -1).reduce((state, key) => {
    const isArr = Array.isArray(key);
    setPath.push(isArr ? key[0] : key);
    return state.updateIn(setPath, x => x == null ? isArr ? List() : Map() : x);
  }, state);
}

export function update (state, { op, path, value }) {
  state = createPathObjects(state, path);
  path = flatten(path);
  if (value && op !== 'remove' && typeof value === 'object') {
    value = Immutable.fromJS(value);
  }
  switch(op) {
    case 'replace':
      return state.setIn(path, value);
    case 'add':
      return state.updateIn(path, xs => (xs == null ? new List([value]) : xs.push(value)));
    case 'remove':
      return value == null
        ? state.deleteIn(path)
        : state.updateIn(path, List(), xs => xs.delete(xs.indexOf(value)));
    default:
      return state;
  }
}

export function buildPatchFromEvent(evt, { path, isArray }) {
  let { type, value, checked } = evt.target;
  const op = 'replace';
  switch(type) {
    case 'checkbox':
      return isArray
        ? { path, op: checked ? 'add' : 'remove', value }
        : { path, op, value: checked };
    case 'select-multiple':
      return { path, op, value: filter(evt.target.options, 'selected').map(o => o.value) };
    case 'number':
      return { path, op, value: parseFloat(value, 10) };
    case 'file':
      return { path, op, value: evt.target.files };
    default:
      return { path, op, value };
  }
}

export const buildPath = function() {
  const PATH_ARRAY_RE = /\[([\d]*)\]/;

  return function buildPath(name, delimiter) {
    return name.split(delimiter).reduce((path, key) => {
      let match = PATH_ARRAY_RE.exec(key);
      path.push(match ? [ key.slice(0, match.index) ] : key);
      if (match && match[1]) {
        path.push(match[1]);
      }
      return path;
    }, []);
  };

}();

export function getValue({ parent, isArray, valuePath }, toJS) {
  let value;
  const ctx = get('value')(parent.state) || get('value')(parent.props) || Map();
  if (typeof ctx === 'object' && typeof ctx.getIn === 'function') {
    value = ctx.getIn(valuePath) || value;
  }
  return toJS && typeof value === 'object' && typeof value.toJS === 'function'
    ? value.toJS()
    : value == null
      ? isArray ? List() : ''
      : value;
}


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.

package com.azure.resourcemanager.loganalytics.generated;

import com.azure.core.util.Context;

/** Samples for Tables ListByWorkspace. */
public final class TablesListByWorkspaceSamples {
    /*
     * x-ms-original-file: specification/operationalinsights/resource-manager/Microsoft.OperationalInsights/preview/2021-12-01-preview/examples/TablesList.json
     */
    /**
     * Sample code: TablesListByWorkspace.
     *
     * @param manager Entry point to LogAnalyticsManager.
     */
    public static void tablesListByWorkspace(com.azure.resourcemanager.loganalytics.LogAnalyticsManager manager) {
        manager.tables().listByWorkspace("oiautorest6685", "oiautorest6685", Context.NONE);
    }
}


text:
<?php

namespace Torchbox\Thankq\Api;

class doMembershipGet
{

    /**
     * @var esitWSdoMembershipGetArgument $doMembershipGetArgument
     */
    protected $doMembershipGetArgument = null;

    /**
     * @param esitWSdoMembershipGetArgument $doMembershipGetArgument
     */
    public function __construct($doMembershipGetArgument)
    {
      $this->doMembershipGetArgument = $doMembershipGetArgument;
    }

    /**
     * @return esitWSdoMembershipGetArgument
     */
    public function getDoMembershipGetArgument()
    {
      return $this->doMembershipGetArgument;
    }

    /**
     * @param esitWSdoMembershipGetArgument $doMembershipGetArgument
     * @return \Torchbox\Thankq\Api\doMembershipGet
     */
    public function setDoMembershipGetArgument($doMembershipGetArgument)
    {
      $this->doMembershipGetArgument = $doMembershipGetArgument;
      return $this;
    }

}


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/np__settings_container"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:gravity="center_horizontal"
    android:orientation="vertical" >

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/np__transparent_background" >

        <include
            android:id="@+id/np__settings_action_bar_layout"
            layout="@layout/np__layout_dialog_action_bar" />
        <LinearLayout
            android:layout_width="@dimen/np__settings_button_width"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:layout_marginBottom="@dimen/np__settings_button_buttom_margin"
            android:layout_centerHorizontal="true"
            android:orientation="vertical" >

            <com.nextpeer.android.open.ui.NPButton
                android:id="@+id/np__settings_about_button"
                style="@style/NP__.Settings.Button"
                android:layout_width="match_parent"
                android:layout_height="@dimen/np__settings_button_height"
                android:layout_marginBottom="@dimen/np__settings_button_buttom_margin"
                android:padding="@dimen/np__settings_button_padding"
                android:text="@string/np__application_name"
                app:np__button_color="@color/np__palette_orange" />

            <com.nextpeer.android.open.ui.NPButton
                android:id="@+id/np__settings_feedback_button"
                style="@style/NP__.Settings.Button"
                android:layout_width="match_parent"
                android:layout_height="@dimen/np__settings_button_height"
                android:layout_marginBottom="@dimen/np__settings_button_buttom_margin"
                android:padding="@dimen/np__settings_button_padding"
                android:text="@string/np__application_name"
                app:np__button_color="@color/np__palette_yellow" />

            <com.nextpeer.android.open.ui.NPButton
                android:id="@+id/np__settings_signout_button"
                style="@style/NP__.Settings.Button"
                android:layout_width="match_parent"
                android:layout_height="@dimen/np__settings_button_height"
                android:layout_marginBottom="@dimen/np__settings_button_buttom_margin"
                android:text="@string/np__application_name"
                app:np__button_color="@color/np__palette_dark_blue" />
        </LinearLayout>
    </RelativeLayout>

</RelativeLayout>


text:
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Text;
using System.Windows.Forms;

namespace stCoreUI
{
	public class FlatGroupBox : ContainerControl
	{
		private int W;
		private int H;
		private bool _ShowText = true;

		[Category("Colors")]
		public Color BaseColor
		{
			get { return _BaseColor; }
			set { _BaseColor = value; }
		}

		public bool ShowText
		{
			get { return _ShowText; }
			set { _ShowText = value; }
		}

		private Color _BaseColor = Color.FromArgb(60, 70, 73);
		private Color _TextColor = Helpers.FlatColor;

		public FlatGroupBox()
		{
			SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.UserPaint | ControlStyles.ResizeRedraw | ControlStyles.OptimizedDoubleBuffer | ControlStyles.SupportsTransparentBackColor, true);
			DoubleBuffered = true;
			BackColor = Color.Transparent;
			Size = new Size(240, 180);
			Font = new Font("Segoe UI", 10);
		}

		protected override void OnPaint(PaintEventArgs e)
		{
			this.UpdateColors();

			Bitmap B = new Bitmap(Width, Height);
			Graphics G = Graphics.FromImage(B);
			W = Width - 1;
			H = Height - 1;

			GraphicsPath GP = new GraphicsPath();
			GraphicsPath GP2 = new GraphicsPath();
			GraphicsPath GP3 = new GraphicsPath();
			Rectangle Base = new Rectangle(8, 8, W - 16, H - 16);

			var _with7 = G;
			_with7.SmoothingMode = SmoothingMode.HighQuality;
			_with7.PixelOffsetMode = PixelOffsetMode.HighQuality;
			_with7.TextRenderingHint = TextRenderingHint.ClearTypeGridFit;
			_with7.Clear(BackColor);

			//-- Base
			GP = Helpers.RoundRec(Base, 8);
			_with7.FillPath(new SolidBrush(_BaseColor), GP);

			//-- Arrows
			GP2 = Helpers.DrawArrow(28, 2, false);
			_with7.FillPath(new SolidBrush(_BaseColor), GP2);
			GP3 = Helpers.DrawArrow(28, 8, true);
			_with7.FillPath(new SolidBrush(Color.FromArgb(60, 70, 73)), GP3);

			//-- if ShowText
			if (ShowText)
			{
				_with7.DrawString(Text, Font, new SolidBrush(_TextColor), new Rectangle(16, 16, W, H), Helpers.NearSF);
			}

			base.OnPaint(e);
			G.Dispose();
			e.Graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
			e.Graphics.DrawImageUnscaled(B, 0, 0);
			B.Dispose();
		}

		private void UpdateColors()
		{
			FlatColors colors = Helpers.GetColors(this);

			_TextColor = colors.Flat;
		}
	}
}


text:
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="ConfigTests.cs" company="Bartek Flejterski">
//   The MIT License (MIT)
//
//   Copyright (c) 2014 Bartek Flejterski
//
//   Permission is hereby granted, free of charge, to any person obtaining a copy
//   of this software and associated documentation files (the "Software"), to deal
//   in the Software without restriction, including without limitation the rights
//   to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//   copies of the Software, and to permit persons to whom the Software is
//   furnished to do so, subject to the following conditions:
//
//   The above copyright notice and this permission notice shall be included in
//   all copies or substantial portions of the Software.
//
//   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//   IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//   FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//   AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//   LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//   OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//   THE SOFTWARE.
// </copyright>
// <summary>
//   The config tests.
// </summary>
// --------------------------------------------------------------------------------------------------------------------
namespace Utils.Test
{
    using System.Collections.Generic;

    using Microsoft.VisualStudio.TestTools.UnitTesting;

    using NFluent;

    /// <summary>
    ///     The config tests.
    /// </summary>
    [TestClass]
    public class ConfigTests
    {
        #region Public Methods and Operators

        /// <summary>
        ///     The read all keys test.
        /// </summary>
        [TestMethod]
        public void ReadAllKeysTest()
        {
            IEnumerable<string> allKeys = Config.AllKeys;
            Check.That(allKeys).ContainsExactly(new[] { "int", "double", "string" });
        }

        /// <summary>
        ///     The read double test.
        /// </summary>
        [TestMethod]
        public void ReadDoubleTest()
        {
            var result = Config.ReadKey<double>("double");
            Check.That(result).IsEqualTo(2.5);
        }

        /// <summary>
        ///     The test method 1.
        /// </summary>
        [TestMethod]
        public void ReadIntTest()
        {
            var result = Config.ReadKey<int>("int");
            Check.That(result).IsEqualTo(7);
        }

        /// <summary>
        ///     The read key with non existing converter type test.
        /// </summary>
        [TestMethod]
        [ExpectedException(typeof(PoochyUtilsException))]
        public void ReadKeyWithNonExistingConverterTypeTest()
        {
            Config.ReadKey<NonExistingConverterType>("string");
        }

        /// <summary>
        ///     The read not existing key test.
        /// </summary>
        [TestMethod]
        [ExpectedException(typeof(PoochyUtilsException))]
        public void ReadNotExistingKeyTest()
        {
            Config.ReadKey<string>("notExistingKey");
        }

        /// <summary>
        ///     The read string test.
        /// </summary>
        [TestMethod]
        public void ReadStringTest()
        {
            var result = Config.ReadKey<string>("string");
            Check.That(result).IsEqualTo("test");
        }

        #endregion
    }

    /// <summary>
    ///     The non existing converter type class - used interally for testing.
    /// </summary>
    internal class NonExistingConverterType
    {
    }
}


text:
// Copyright (c) 2015-2020, Saritasa. All rights reserved.
// Licensed under the BSD license. See LICENSE file in the project root for full license information.

using System;
using System.Collections.Generic;
using System.Net.Mail;
using System.IO;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;

namespace Saritasa.Tools.Emails.Interceptors
{
    /// <summary>
    /// Saves emails into specified folder in .eml format.
    /// </summary>
    public class SaveToFileEmailsInterceptor : IEmailInterceptor
    {
        /// <summary>
        /// Directory to save emails.
        /// </summary>
        public string Directory { get; }

        /// <summary>
        /// Save only sent emails.
        /// </summary>
        public bool AfterSend { get; }

        private static readonly object @lock = new object();

        /// <summary>
        /// Constructor.
        /// </summary>
        /// <param name="directory">Directory to save emails.</param>
        /// <param name="afterSend">Save only sent emails.</param>
        public SaveToFileEmailsInterceptor(string directory, bool afterSend = false)
        {
            if (string.IsNullOrEmpty(directory))
            {
                throw new ArgumentNullException(nameof(directory));
            }
            Directory = directory;
            AfterSend = afterSend;
        }

        private void Save(MailMessage message)
        {
            // Sometimes we have emails sending at the same second, add postfix in that case.
            lock (@lock)
            {
                var path = Path.Combine(Directory, $"{DateTime.Now:yyyyMMdd-hhmmss}.msg");
                for (int i = 0; File.Exists(path); i++)
                {
                    path = Path.Combine(Directory, $"{DateTime.Now:yyyyMMdd-hhmmss}-{i:000}.msg");
                }
                SaveMailMessage(message, path);
            }
        }

        #region IEmailInterceptor implementation

        /// <inheritdoc />
        public Task SendingAsync(MailMessage mailMessage, IDictionary<string, object> data, ref bool cancel,
            CancellationToken cancellationToken)
        {
            if (!AfterSend)
            {
                Save(mailMessage);
            }
            return Task.CompletedTask;
        }

        /// <inheritdoc />
        public Task SentAsync(MailMessage mailMessage, IDictionary<string, object> data,
            CancellationToken cancellationToken)
        {
            if (AfterSend)
            {
                Save(mailMessage);
            }
            return Task.CompletedTask;
        }

        #endregion

        /// <summary>
        /// Saves the specified message to disk.
        /// </summary>
        /// <param name="message">The message.</param>
        /// <param name="fileName">Name of the file.</param>
        private static void SaveMailMessage(MailMessage message, string fileName)
        {
            var assembly = typeof(SmtpClient).Assembly;
            var mailWriterType = assembly.GetType("System.Net.Mail.MailWriter");

            using (var fileStream = new FileStream(fileName, FileMode.Create))
            {
                // Get reflection info for MailWriter constructor.
                var mailWriterConstructor =
                    mailWriterType.GetConstructor(
                        BindingFlags.Instance | BindingFlags.NonPublic,
                        null,
                        new[] { typeof(Stream) },
                        null);

                // Construct MailWriter object with our FileStream.
                var mailWriter = mailWriterConstructor.Invoke(new object[] { fileStream });

                // Get reflection info for Send() method on MailMessage.
                var sendMethod =
                    typeof(MailMessage).GetMethod(
                        "Send",
                        BindingFlags.Instance | BindingFlags.NonPublic);

                // Call method passing in MailWriter.
                if (sendMethod.GetParameters().Length == 2)
                {
                    sendMethod.Invoke(
                        message,
                        BindingFlags.Instance | BindingFlags.NonPublic,
                        null,
                        new[] { mailWriter, true },
                        null);
                }
                else
                {
                    sendMethod.Invoke(
                        message,
                        BindingFlags.Instance | BindingFlags.NonPublic,
                        null,
                        new[] { mailWriter, true, true },
                        null);
                }

                // Finally get reflection info for Close() method on our MailWriter.
                var closeMethod =
                    mailWriter.GetType().GetMethod(
                        "Close",
                        BindingFlags.Instance | BindingFlags.NonPublic);

                // Call close method.
                closeMethod.Invoke(
                    mailWriter,
                    BindingFlags.Instance | BindingFlags.NonPublic,
                    null,
                    new object[] { },
                    null);
            }
        }
    }
}


text:
using System.Collections.Generic;

namespace LightBDD.Core.Metadata
{
    /// <summary>
    /// Interface describing feature metadata.
    /// </summary>
    public interface IFeatureInfo : IMetadataInfo
    {
        /// <summary>
        /// Returns feature name.
        /// </summary>
        //TODO: remove in 4.x
        new INameInfo Name { get; }
        /// <summary>
        /// Returns feature labels or empty collection if none provided.
        /// </summary>
        IEnumerable<string> Labels { get; }
        /// <summary>
        /// Returns feature description or <c>null</c> if none provided.
        /// </summary>
        string Description { get; }
    }
}


text:
namespace asar {

namespace {

// The global instance of ArchiveMap, will be destroyed on exit.
typedef std::map<base::FilePath, Archive*> ArchiveMap;
//static base::LazyInstance<ArchiveMap> g_archive_map = LAZY_INSTANCE_INITIALIZER;
static ArchiveMap* g_archive_map = nullptr;

const base::FilePath::CharType kAsarExtension[] = FILE_PATH_LITERAL(".asar");

}  // namespace

Archive* GetOrCreateAsarArchive(const base::FilePath& path) {
    if (!g_archive_map)
        g_archive_map = new ArchiveMap();
    ArchiveMap& archive_map = *g_archive_map;
    ArchiveMap::iterator it = archive_map.find(path);
    if (it == archive_map.end()) {
        Archive* archive(new Archive(path));
        if (!archive->Init()) {
            delete archive;
            return nullptr;
        }
        archive_map[path] = archive;
    }
    return archive_map[path];
}

bool GetAsarArchivePath(const base::FilePath& full_path,
    base::FilePath* asar_path,
    base::FilePath* relative_path) {
    base::FilePath iter = full_path;
    while (true) {
        base::FilePath dirname = iter.DirName();
        if (iter.MatchesExtension(kAsarExtension))
            break;
        else if (iter == dirname)
            return false;
        iter = dirname;
    }

    base::FilePath tail;
    if (!iter.AppendRelativePath(full_path, &tail))
        return false;

    *asar_path = iter;
    *relative_path = tail;
    return true;
}

bool ReadFileToString(const wchar_t* path, std::string* buffer) {
    HANDLE hFile = ::CreateFileW(path, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
    if (INVALID_HANDLE_VALUE == hFile)
        return false;

    DWORD fileSizeHigh;
    const DWORD bufferSize = ::GetFileSize(hFile, &fileSizeHigh);

    DWORD numberOfBytesRead = 0;
    buffer->resize(bufferSize);
    BOOL b = ::ReadFile(hFile, &buffer->at(0), bufferSize, &numberOfBytesRead, nullptr);
    ::CloseHandle(hFile);
    return !!b;
}

bool ReadFileToString(const base::FilePath& path, std::string* contents) {
    base::FilePath asar_path, relative_path;
    if (!GetAsarArchivePath(path, &asar_path, &relative_path))
        return ReadFileToString(path.AsUTF16Unsafe().c_str(), contents);

    Archive* archive = GetOrCreateAsarArchive(asar_path);
    if (!archive)
        return false;

    Archive::FileInfo info;
    if (!archive->GetFileInfo(relative_path, &info))
        return false;

    if (info.unpacked) {
        base::FilePath real_path;
        // For unpacked file it will return the real path instead of doing the copy.
        archive->CopyFileOut(relative_path, &real_path);
        return ReadFileToString(real_path, contents);
    }

    base::File src(asar_path, base::File::FLAG_OPEN | base::File::FLAG_READ);
    if (!src.IsValid())
        return false;

    contents->resize(info.size);
    return static_cast<int>(info.size) == src.Read(info.offset, const_cast<char*>(contents->data()), contents->size());
}

}  // namespace asar


text:
import { async, ComponentFixture, TestBed } from '@angular/core/testing';

import { UserWidgetComponent } from './user-widget.component';

describe('UserWidgetComponent', () => {
  let component: UserWidgetComponent;
  let fixture: ComponentFixture<UserWidgetComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ UserWidgetComponent ]
    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(UserWidgetComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });
});


text: Dos2unix for windows


text:
struct ViewHostMsg_UpdateRect_Params;

namespace content {

class OverscrollWindowDelegate;
class OverscrollNavigationOverlayTest;
class ScopedLayerClippingSetting;

// When a history navigation is triggered at the end of an overscroll
// navigation, it is necessary to show the history-screenshot until the page is
// done navigating and painting. This class accomplishes this by calling the
// navigation and creating, showing and destroying the screenshot window on top
// of the page until the page has completed loading and painting. When the
// overscroll completes, this screenshot window is returned by
// OnOverscrollComplete and |window_| is set to own it.
// There are two overscroll cases, for the first one the main window is the web
// contents window. At this stage, |window_| is null. The second case is
// triggered if the user overscrolls after |window_| is set, before the page
// finishes loading. When this happens, |window_| is the main window.
class CONTENT_EXPORT OverscrollNavigationOverlay
    : public WebContentsObserver,
      public OverscrollWindowAnimation::Delegate {
 public:
  // Note that this enum is used to back an UMA histogram, so it should be
  // treated as append-only.
  enum NavigationDirection { NONE, FORWARD, BACK, NAVIGATION_COUNT };

  OverscrollNavigationOverlay(WebContentsImpl* web_contents,
                              aura::Window* web_contents_window);

  ~OverscrollNavigationOverlay() override;

  // Returns a pointer to the relay delegate we own.
  OverscrollControllerDelegate* relay_delegate() { return owa_.get(); }

 private:
  class ScopedLayerClippingSetting;

  friend class OverscrollNavigationOverlayTest;
  FRIEND_TEST_ALL_PREFIXES(OverscrollNavigationOverlayTest, WithScreenshot);
  FRIEND_TEST_ALL_PREFIXES(OverscrollNavigationOverlayTest, WithoutScreenshot);
  FRIEND_TEST_ALL_PREFIXES(OverscrollNavigationOverlayTest, CannotNavigate);
  FRIEND_TEST_ALL_PREFIXES(OverscrollNavigationOverlayTest, CancelNavigation);
  FRIEND_TEST_ALL_PREFIXES(OverscrollNavigationOverlayTest,
                           CancelAfterSuccessfulNavigation);
  FRIEND_TEST_ALL_PREFIXES(OverscrollNavigationOverlayTest, OverlayWindowSwap);

  // Resets state and starts observing |web_contents_| for page load/paint
  // updates. This function makes sure that the screenshot window is stacked
  // on top, so that it hides the content window behind it, and destroys the
  // screenshot window when the page is done loading/painting.
  // This should be called immediately after initiating the navigation,
  // otherwise the overlay may be dismissed prematurely.
  void StartObserving();

  // Stop observing the page and start the final overlay fade-out animation if
  // there's no active overscroll window animation.
  void StopObservingIfDone();

  // Creates a window that shows a history-screenshot and is stacked relative to
  // the current overscroll |direction_| with the given |bounds|.
  scoped_ptr<aura::Window> CreateOverlayWindow(const gfx::Rect& bounds);

  // Returns an image with the history-screenshot for the previous or next page,
  // according to the given |direction|.
  const gfx::Image GetImageForDirection(NavigationDirection direction) const;

  // Overridden from OverscrollWindowAnimation::Delegate:
  scoped_ptr<aura::Window> CreateFrontWindow(const gfx::Rect& bounds) override;
  scoped_ptr<aura::Window> CreateBackWindow(const gfx::Rect& bounds) override;
  aura::Window* GetMainWindow() const override;
  void OnOverscrollCompleting() override;
  void OnOverscrollCompleted(scoped_ptr<aura::Window> window) override;
  void OnOverscrollCancelled() override;

  // Overridden from WebContentsObserver:
  void DidFirstVisuallyNonEmptyPaint() override;
  void DidStopLoading() override;

  // The current overscroll direction.
  NavigationDirection direction_;

  // The web contents that are being navigated.
  WebContentsImpl* web_contents_;

  // The overlay window that shows a screenshot during an overscroll gesture and
  // handles overscroll events during the second overscroll case.
  scoped_ptr<aura::Window> window_;

  bool loading_complete_;
  bool received_paint_update_;

  // URL of the NavigationEntry we are navigating to. This is needed to
  // filter on WebContentsObserver callbacks and is used to dismiss the overlay
  // when the relevant page loads and paints.
  GURL pending_entry_url_;

  // Manages the overscroll animations.
  scoped_ptr<OverscrollWindowAnimation> owa_;

  // The window that hosts the web contents.
  aura::Window* web_contents_window_;

  // Scoped clipping settings for the contents layer and its parent.
  scoped_ptr<ScopedLayerClippingSetting> contents_layer_settings_;
  scoped_ptr<ScopedLayerClippingSetting> contents_layer_parent_settings_;

  DISALLOW_COPY_AND_ASSIGN(OverscrollNavigationOverlay);
};

}  // namespace content

#endif  // CONTENT_BROWSER_WEB_CONTENTS_AURA_OVERSCROLL_NAVIGATION_OVERLAY_H_


text:
concatenate file globs, watching for changes

This module is just like the `cat` command, but with watching!

[![build status](https://secure.travis-ci.org/substack/catw.png)](http://travis-ci.org/substack/catw)

# example

``` js
#!/usr/bin/env node

var catw = require('catw');
var fs = require('fs');

catw('*.txt', function (stream) {
    var w = stream.pipe(fs.createWriteStream('/tmp/bundle.txt'));
    w.on('close', function () { console.log('wrote to /tmp/bundle.txt') });
});
```

If we run the program in a directory with files `a.txt` and `b.txt`, the
`bundle.txt` output will be both files concatenated together (in string-order by
filename):

```
beep
boop
```

If we edit `a.txt` to be `"BEEP"` instead of `"beep"`, the `bundle.txt` is now:

```
BEEP
boop
```

and then if we add a third file `c.txt` with the contents `"!!!"`, the output is
now:

```
BEEP
boop
!!!
```

We can even delete files. If we delete `b.txt`, the output is now:

```
BEEP
!!!
```

If we add a new file called `bloop.txt` with contents `"BLOOP"`, the
`bundle.txt` output is now:

```
BEEP
BLOOP
!!!
```

because the glob expansions of directories are sorted before concatenating.

# usage

There is a command-line `catw` command that ships with this package.

```
usage: catw {OPTIONS} [FILES...] -o OUTFILE

  If FILES is "-", read from stdin.
  If there is no OUTFILE, write to stdout and exit without watching.

  OPTIONS:

    -w, --watch      Watch for changes.
                     Default: true except when writing to stdout.

    -c, --command    Execute a transform command for file before concatenating.
                     The env var $FILE will be set for each file path.

    -t, --transform  Transform each file using a module.

    -v, --verbose    Print the number of bytes written whenever a file changes.

    -h, --help       Print this help message.

Make sure to escape the globs that you want `catw` to watch so your shell won't
expand them.
```

# methods

``` js
var catw = require('catw')
```

## var cat = catw(patterns, opts={}, cb)

Create a new `cat` to concatenate `patterns`, an array of strings or a single
string and watch each of the `patterns` for changes: new files, deleted files,
and file updates.

It `opts.watch` is `false`, don't watch for changes, only concatenate once.

You can pass in a `opts.transform(file)` function that returns a transform
stream to modify file contents before the contents are written to the bundle.

If specified, `cb(stream)` sets up a listener on the `'stream'` event.

## cat.close()

Stop listening for updates to the `patterns`.

# events

## cat.on('stream', function (stream) {})

Each time a file matched by a pattern changes or there is a new or deleted file
matched by a pattern, this event fires with a `stream` that will output the
concatenated file contents.

# install

To get the module, with [npm](https://npmjs.org) do:

```
npm install catw
```

and to get the `catw` command do:

```
npm install -g catw
```

# test

With [npm](https://npmjs.org) do:

```
npm test
```

# license

MIT


text:
@interface WYVCExampleViewController : UIViewController

@end


text:
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt

#include <linux/hardirq.h>
#include <linux/slab.h>
#include <linux/export.h>

#include "libertas_tf.h"

static const struct channel_range channel_ranges[] = {
	{ LBTF_REGDOMAIN_US,		1, 12 },
	{ LBTF_REGDOMAIN_CA,		1, 12 },
	{ LBTF_REGDOMAIN_EU,		1, 14 },
	{ LBTF_REGDOMAIN_JP,		1, 14 },
	{ LBTF_REGDOMAIN_SP,		1, 14 },
	{ LBTF_REGDOMAIN_FR,		1, 14 },
};

static u16 lbtf_region_code_to_index[MRVDRV_MAX_REGION_CODE] =
{
	LBTF_REGDOMAIN_US, LBTF_REGDOMAIN_CA, LBTF_REGDOMAIN_EU,
	LBTF_REGDOMAIN_SP, LBTF_REGDOMAIN_FR, LBTF_REGDOMAIN_JP,
};

static struct cmd_ctrl_node *lbtf_get_cmd_ctrl_node(struct lbtf_private *priv);

/**
 *  lbtf_cmd_copyback - Simple callback that copies response back into command
 *
 *  @priv	A pointer to struct lbtf_private structure
 *  @extra	A pointer to the original command structure for which
 *		'resp' is a response
 *  @resp	A pointer to the command response
 *
 *  Returns: 0 on success, error on failure
 */
int lbtf_cmd_copyback(struct lbtf_private *priv, unsigned long extra,
		     struct cmd_header *resp)
{
	struct cmd_header *buf = (void *)extra;
	uint16_t copy_len;

	copy_len = min(le16_to_cpu(buf->size), le16_to_cpu(resp->size));
	memcpy(buf, resp, copy_len);
	return 0;
}
EXPORT_SYMBOL_GPL(lbtf_cmd_copyback);

#define CHAN_TO_IDX(chan) ((chan) - 1)

static void lbtf_geo_init(struct lbtf_private *priv)
{
	const struct channel_range *range = channel_ranges;
	u8 ch;
	int i;

	for (i = 0; i < ARRAY_SIZE(channel_ranges); i++)
		if (channel_ranges[i].regdomain == priv->regioncode) {
			range = &channel_ranges[i];
			break;
		}

	for (ch = priv->range.start; ch < priv->range.end; ch++)
		priv->channels[CHAN_TO_IDX(ch)].flags = 0;
}

/**
 *  lbtf_update_hw_spec: Updates the hardware details.
 *
 *  @priv    	A pointer to struct lbtf_private structure
 *
 *  Returns: 0 on success, error on failure
 */
int lbtf_update_hw_spec(struct lbtf_private *priv)
{
	struct cmd_ds_get_hw_spec cmd;
	int ret = -1;
	u32 i;

	lbtf_deb_enter(LBTF_DEB_CMD);

	memset(&cmd, 0, sizeof(cmd));
	cmd.hdr.size = cpu_to_le16(sizeof(cmd));
	memcpy(cmd.permanentaddr, priv->current_addr, ETH_ALEN);
	ret = lbtf_cmd_with_response(priv, CMD_GET_HW_SPEC, &cmd);
	if (ret)
		goto out;

	priv->fwcapinfo = le32_to_cpu(cmd.fwcapinfo);

	/* The firmware release is in an interesting format: the patch
	 * level is in the most significant nibble ... so fix that: */
	priv->fwrelease = le32_to_cpu(cmd.fwrelease);
	priv->fwrelease = (priv->fwrelease << 8) |
		(priv->fwrelease >> 24 & 0xff);

	printk(KERN_INFO "libertastf: %pM, fw %u.%u.%up%u, cap 0x%08x\n",
		cmd.permanentaddr,
		priv->fwrelease >> 24 & 0xff,
		priv->fwrelease >> 16 & 0xff,
		priv->fwrelease >>  8 & 0xff,
		priv->fwrelease       & 0xff,
		priv->fwcapinfo);
	lbtf_deb_cmd("GET_HW_SPEC: hardware interface 0x%x, hardware spec 0x%04x\n",
		    cmd.hwifversion, cmd.version);

	/* Clamp region code to 8-bit since FW spec indicates that it should
	 * only ever be 8-bit, even though the field size is 16-bit.  Some
	 * firmware returns non-zero high 8 bits here.
	 */
	priv->regioncode = le16_to_cpu(cmd.regioncode) & 0xFF;

	for (i = 0; i < MRVDRV_MAX_REGION_CODE; i++) {
		/* use the region code to search for the index */
		if (priv->regioncode == lbtf_region_code_to_index[i])
			break;
	}

	/* if it's unidentified region code, use the default (USA) */
	if (i >= MRVDRV_MAX_REGION_CODE) {
		priv->regioncode = 0x10;
		pr_info("unidentified region code; using the default (USA)\n");
	}

	if (priv->current_addr[0] == 0xff)
		memmove(priv->current_addr, cmd.permanentaddr, ETH_ALEN);

	SET_IEEE80211_PERM_ADDR(priv->hw, priv->current_addr);

	lbtf_geo_init(priv);
out:
	lbtf_deb_leave(LBTF_DEB_CMD);
	return ret;
}

/**
 *  lbtf_set_channel: Set the radio channel
 *
 *  @priv	A pointer to struct lbtf_private structure
 *  @channel	The desired channel, or 0 to clear a locked channel
 *
 *  Returns: 0 on success, error on failure
 */
int lbtf_set_channel(struct lbtf_private *priv, u8 channel)
{
	int ret = 0;
	struct cmd_ds_802_11_rf_channel cmd;

	lbtf_deb_enter(LBTF_DEB_CMD);

	cmd.hdr.size = cpu_to_le16(sizeof(cmd));
	cmd.action = cpu_to_le16(CMD_OPT_802_11_RF_CHANNEL_SET);
	cmd.channel = cpu_to_le16(channel);

	ret = lbtf_cmd_with_response(priv, CMD_802_11_RF_CHANNEL, &cmd);
	lbtf_deb_leave_args(LBTF_DEB_CMD, "ret %d", ret);
	return ret;
}

int lbtf_beacon_set(struct lbtf_private *priv, struct sk_buff *beacon)
{
	struct cmd_ds_802_11_beacon_set cmd;
	int size;

	lbtf_deb_enter(LBTF_DEB_CMD);

	if (beacon->len > MRVL_MAX_BCN_SIZE) {
		lbtf_deb_leave_args(LBTF_DEB_CMD, "ret %d", -1);
		return -1;
	}
	size =  sizeof(cmd) - sizeof(cmd.beacon) + beacon->len;
	cmd.hdr.size = cpu_to_le16(size);
	cmd.len = cpu_to_le16(beacon->len);
	memcpy(cmd.beacon, (u8 *) beacon->data, beacon->len);

	lbtf_cmd_async(priv, CMD_802_11_BEACON_SET, &cmd.hdr, size);

	lbtf_deb_leave_args(LBTF_DEB_CMD, "ret %d", 0);
	return 0;
}

int lbtf_beacon_ctrl(struct lbtf_private *priv, bool beacon_enable,
		     int beacon_int)
{
	struct cmd_ds_802_11_beacon_control cmd;
	lbtf_deb_enter(LBTF_DEB_CMD);

	cmd.hdr.size = cpu_to_le16(sizeof(cmd));
	cmd.action = cpu_to_le16(CMD_ACT_SET);
	cmd.beacon_enable = cpu_to_le16(beacon_enable);
	cmd.beacon_period = cpu_to_le16(beacon_int);

	lbtf_cmd_async(priv, CMD_802_11_BEACON_CTRL, &cmd.hdr, sizeof(cmd));

	lbtf_deb_leave(LBTF_DEB_CMD);
	return 0;
}

static void lbtf_queue_cmd(struct lbtf_private *priv,
			  struct cmd_ctrl_node *cmdnode)
{
	unsigned long flags;
	lbtf_deb_enter(LBTF_DEB_HOST);

	if (!cmdnode) {
		lbtf_deb_host("QUEUE_CMD: cmdnode is NULL\n");
		goto qcmd_done;
	}

	if (!cmdnode->cmdbuf->size) {
		lbtf_deb_host("DNLD_CMD: cmd size is zero\n");
		goto qcmd_done;
	}

	cmdnode->result = 0;
	spin_lock_irqsave(&priv->driver_lock, flags);
	list_add_tail(&cmdnode->list, &priv->cmdpendingq);
	spin_unlock_irqrestore(&priv->driver_lock, flags);

	lbtf_deb_host("QUEUE_CMD: inserted command 0x%04x into cmdpendingq\n",
		     le16_to_cpu(cmdnode->cmdbuf->command));

qcmd_done:
	lbtf_deb_leave(LBTF_DEB_HOST);
}

static void lbtf_submit_command(struct lbtf_private *priv,
			       struct cmd_ctrl_node *cmdnode)
{
	unsigned long flags;
	struct cmd_header *cmd;
	uint16_t cmdsize;
	uint16_t command;
	int timeo = 5 * HZ;
	int ret;

	lbtf_deb_enter(LBTF_DEB_HOST);

	cmd = cmdnode->cmdbuf;

	spin_lock_irqsave(&priv->driver_lock, flags);
	priv->cur_cmd = cmdnode;
	cmdsize = le16_to_cpu(cmd->size);
	command = le16_to_cpu(cmd->command);

	lbtf_deb_cmd("DNLD_CMD: command 0x%04x, seq %d, size %d\n",
		     command, le16_to_cpu(cmd->seqnum), cmdsize);
	lbtf_deb_hex(LBTF_DEB_CMD, "DNLD_CMD", (void *) cmdnode->cmdbuf, cmdsize);

	ret = priv->hw_host_to_card(priv, MVMS_CMD, (u8 *) cmd, cmdsize);
	spin_unlock_irqrestore(&priv->driver_lock, flags);

	if (ret) {
		pr_info("DNLD_CMD: hw_host_to_card failed: %d\n", ret);
		/* Let the timer kick in and retry, and potentially reset
		   the whole thing if the condition persists */
		timeo = HZ;
	}

	/* Setup the timer after transmit command */
	mod_timer(&priv->command_timer, jiffies + timeo);

	lbtf_deb_leave(LBTF_DEB_HOST);
}

/**
 *  This function inserts command node to cmdfreeq
 *  after cleans it. Requires priv->driver_lock held.
 */
static void __lbtf_cleanup_and_insert_cmd(struct lbtf_private *priv,
					 struct cmd_ctrl_node *cmdnode)
{
	lbtf_deb_enter(LBTF_DEB_HOST);

	if (!cmdnode)
		goto cl_ins_out;

	cmdnode->callback = NULL;
	cmdnode->callback_arg = 0;

	memset(cmdnode->cmdbuf, 0, LBS_CMD_BUFFER_SIZE);

	list_add_tail(&cmdnode->list, &priv->cmdfreeq);

cl_ins_out:
	lbtf_deb_leave(LBTF_DEB_HOST);
}

static void lbtf_cleanup_and_insert_cmd(struct lbtf_private *priv,
	struct cmd_ctrl_node *ptempcmd)
{
	unsigned long flags;

	spin_lock_irqsave(&priv->driver_lock, flags);
	__lbtf_cleanup_and_insert_cmd(priv, ptempcmd);
	spin_unlock_irqrestore(&priv->driver_lock, flags);
}

void lbtf_complete_command(struct lbtf_private *priv, struct cmd_ctrl_node *cmd,
			  int result)
{
	cmd->result = result;
	cmd->cmdwaitqwoken = 1;
	wake_up_interruptible(&cmd->cmdwait_q);

	if (!cmd->callback)
		__lbtf_cleanup_and_insert_cmd(priv, cmd);
	priv->cur_cmd = NULL;
}

int lbtf_cmd_set_mac_multicast_addr(struct lbtf_private *priv)
{
	struct cmd_ds_mac_multicast_addr cmd;

	lbtf_deb_enter(LBTF_DEB_CMD);

	cmd.hdr.size = cpu_to_le16(sizeof(cmd));
	cmd.action = cpu_to_le16(CMD_ACT_SET);

	cmd.nr_of_adrs = cpu_to_le16((u16) priv->nr_of_multicastmacaddr);

	lbtf_deb_cmd("MULTICAST_ADR: setting %d addresses\n", cmd.nr_of_adrs);

	memcpy(cmd.maclist, priv->multicastlist,
	       priv->nr_of_multicastmacaddr * ETH_ALEN);

	lbtf_cmd_async(priv, CMD_MAC_MULTICAST_ADR, &cmd.hdr, sizeof(cmd));

	lbtf_deb_leave(LBTF_DEB_CMD);
	return 0;
}

void lbtf_set_mode(struct lbtf_private *priv, enum lbtf_mode mode)
{
	struct cmd_ds_set_mode cmd;
	lbtf_deb_enter(LBTF_DEB_WEXT);

	cmd.hdr.size = cpu_to_le16(sizeof(cmd));
	cmd.mode = cpu_to_le16(mode);
	lbtf_deb_wext("Switching to mode: 0x%x\n", mode);
	lbtf_cmd_async(priv, CMD_802_11_SET_MODE, &cmd.hdr, sizeof(cmd));

	lbtf_deb_leave(LBTF_DEB_WEXT);
}

void lbtf_set_bssid(struct lbtf_private *priv, bool activate, const u8 *bssid)
{
	struct cmd_ds_set_bssid cmd;
	lbtf_deb_enter(LBTF_DEB_CMD);

	cmd.hdr.size = cpu_to_le16(sizeof(cmd));
	cmd.activate = activate ? 1 : 0;
	if (activate)
		memcpy(cmd.bssid, bssid, ETH_ALEN);

	lbtf_cmd_async(priv, CMD_802_11_SET_BSSID, &cmd.hdr, sizeof(cmd));
	lbtf_deb_leave(LBTF_DEB_CMD);
}

int lbtf_set_mac_address(struct lbtf_private *priv, uint8_t *mac_addr)
{
	struct cmd_ds_802_11_mac_address cmd;
	lbtf_deb_enter(LBTF_DEB_CMD);

	cmd.hdr.size = cpu_to_le16(sizeof(cmd));
	cmd.action = cpu_to_le16(CMD_ACT_SET);

	memcpy(cmd.macadd, mac_addr, ETH_ALEN);

	lbtf_cmd_async(priv, CMD_802_11_MAC_ADDRESS, &cmd.hdr, sizeof(cmd));
	lbtf_deb_leave(LBTF_DEB_CMD);
	return 0;
}

int lbtf_set_radio_control(struct lbtf_private *priv)
{
	int ret = 0;
	struct cmd_ds_802_11_radio_control cmd;

	lbtf_deb_enter(LBTF_DEB_CMD);

	cmd.hdr.size = cpu_to_le16(sizeof(cmd));
	cmd.action = cpu_to_le16(CMD_ACT_SET);

	switch (priv->preamble) {
	case CMD_TYPE_SHORT_PREAMBLE:
		cmd.control = cpu_to_le16(SET_SHORT_PREAMBLE);
		break;

	case CMD_TYPE_LONG_PREAMBLE:
		cmd.control = cpu_to_le16(SET_LONG_PREAMBLE);
		break;

	case CMD_TYPE_AUTO_PREAMBLE:
	default:
		cmd.control = cpu_to_le16(SET_AUTO_PREAMBLE);
		break;
	}

	if (priv->radioon)
		cmd.control |= cpu_to_le16(TURN_ON_RF);
	else
		cmd.control &= cpu_to_le16(~TURN_ON_RF);

	lbtf_deb_cmd("RADIO_SET: radio %d, preamble %d\n", priv->radioon,
		    priv->preamble);

	ret = lbtf_cmd_with_response(priv, CMD_802_11_RADIO_CONTROL, &cmd);

	lbtf_deb_leave_args(LBTF_DEB_CMD, "ret %d", ret);
	return ret;
}

void lbtf_set_mac_control(struct lbtf_private *priv)
{
	struct cmd_ds_mac_control cmd;
	lbtf_deb_enter(LBTF_DEB_CMD);

	cmd.hdr.size = cpu_to_le16(sizeof(cmd));
	cmd.action = cpu_to_le16(priv->mac_control);
	cmd.reserved = 0;

	lbtf_cmd_async(priv, CMD_MAC_CONTROL,
		&cmd.hdr, sizeof(cmd));

	lbtf_deb_leave(LBTF_DEB_CMD);
}

/**
 *  lbtf_allocate_cmd_buffer - Allocates cmd buffer, links it to free cmd queue
 *
 *  @priv	A pointer to struct lbtf_private structure
 *
 *  Returns: 0 on success.
 */
int lbtf_allocate_cmd_buffer(struct lbtf_private *priv)
{
	int ret = 0;
	u32 bufsize;
	u32 i;
	struct cmd_ctrl_node *cmdarray;

	lbtf_deb_enter(LBTF_DEB_HOST);

	/* Allocate and initialize the command array */
	bufsize = sizeof(struct cmd_ctrl_node) * LBS_NUM_CMD_BUFFERS;
	cmdarray = kzalloc(bufsize, GFP_KERNEL);
	if (!cmdarray) {
		lbtf_deb_host("ALLOC_CMD_BUF: tempcmd_array is NULL\n");
		ret = -1;
		goto done;
	}
	priv->cmd_array = cmdarray;

	/* Allocate and initialize each command buffer in the command array */
	for (i = 0; i < LBS_NUM_CMD_BUFFERS; i++) {
		cmdarray[i].cmdbuf = kzalloc(LBS_CMD_BUFFER_SIZE, GFP_KERNEL);
		if (!cmdarray[i].cmdbuf) {
			lbtf_deb_host("ALLOC_CMD_BUF: ptempvirtualaddr is NULL\n");
			ret = -1;
			goto done;
		}
	}

	for (i = 0; i < LBS_NUM_CMD_BUFFERS; i++) {
		init_waitqueue_head(&cmdarray[i].cmdwait_q);
		lbtf_cleanup_and_insert_cmd(priv, &cmdarray[i]);
	}

	ret = 0;

done:
	lbtf_deb_leave_args(LBTF_DEB_HOST, "ret %d", ret);
	return ret;
}

/**
 *  lbtf_free_cmd_buffer - Frees the cmd buffer.
 *
 *  @priv	A pointer to struct lbtf_private structure
 *
 *  Returns: 0
 */
int lbtf_free_cmd_buffer(struct lbtf_private *priv)
{
	struct cmd_ctrl_node *cmdarray;
	unsigned int i;

	lbtf_deb_enter(LBTF_DEB_HOST);

	/* need to check if cmd array is allocated or not */
	if (priv->cmd_array == NULL) {
		lbtf_deb_host("FREE_CMD_BUF: cmd_array is NULL\n");
		goto done;
	}

	cmdarray = priv->cmd_array;

	/* Release shared memory buffers */
	for (i = 0; i < LBS_NUM_CMD_BUFFERS; i++) {
		kfree(cmdarray[i].cmdbuf);
		cmdarray[i].cmdbuf = NULL;
	}

	/* Release cmd_ctrl_node */
	kfree(priv->cmd_array);
	priv->cmd_array = NULL;

done:
	lbtf_deb_leave(LBTF_DEB_HOST);
	return 0;
}

/**
 *  lbtf_get_cmd_ctrl_node - Gets free cmd node from free cmd queue.
 *
 *  @priv		A pointer to struct lbtf_private structure
 *
 *  Returns: pointer to a struct cmd_ctrl_node or NULL if none available.
 */
static struct cmd_ctrl_node *lbtf_get_cmd_ctrl_node(struct lbtf_private *priv)
{
	struct cmd_ctrl_node *tempnode;
	unsigned long flags;

	lbtf_deb_enter(LBTF_DEB_HOST);

	if (!priv)
		return NULL;

	spin_lock_irqsave(&priv->driver_lock, flags);

	if (!list_empty(&priv->cmdfreeq)) {
		tempnode = list_first_entry(&priv->cmdfreeq,
					    struct cmd_ctrl_node, list);
		list_del(&tempnode->list);
	} else {
		lbtf_deb_host("GET_CMD_NODE: cmd_ctrl_node is not available\n");
		tempnode = NULL;
	}

	spin_unlock_irqrestore(&priv->driver_lock, flags);

	lbtf_deb_leave(LBTF_DEB_HOST);
	return tempnode;
}

/**
 *  lbtf_execute_next_command: execute next command in cmd pending queue.
 *
 *  @priv     A pointer to struct lbtf_private structure
 *
 *  Returns: 0 on success.
 */
int lbtf_execute_next_command(struct lbtf_private *priv)
{
	struct cmd_ctrl_node *cmdnode = NULL;
	struct cmd_header *cmd;
	unsigned long flags;
	int ret = 0;

	/* Debug group is lbtf_deb_THREAD and not lbtf_deb_HOST, because the
	 * only caller to us is lbtf_thread() and we get even when a
	 * data packet is received */
	lbtf_deb_enter(LBTF_DEB_THREAD);

	spin_lock_irqsave(&priv->driver_lock, flags);

	if (priv->cur_cmd) {
		pr_alert("EXEC_NEXT_CMD: already processing command!\n");
		spin_unlock_irqrestore(&priv->driver_lock, flags);
		ret = -1;
		goto done;
	}

	if (!list_empty(&priv->cmdpendingq)) {
		cmdnode = list_first_entry(&priv->cmdpendingq,
					   struct cmd_ctrl_node, list);
	}

	if (cmdnode) {
		cmd = cmdnode->cmdbuf;

		list_del(&cmdnode->list);
		lbtf_deb_host("EXEC_NEXT_CMD: sending command 0x%04x\n",
			    le16_to_cpu(cmd->command));
		spin_unlock_irqrestore(&priv->driver_lock, flags);
		lbtf_submit_command(priv, cmdnode);
	} else
		spin_unlock_irqrestore(&priv->driver_lock, flags);

	ret = 0;
done:
	lbtf_deb_leave(LBTF_DEB_THREAD);
	return ret;
}

static struct cmd_ctrl_node *__lbtf_cmd_async(struct lbtf_private *priv,
	uint16_t command, struct cmd_header *in_cmd, int in_cmd_size,
	int (*callback)(struct lbtf_private *, unsigned long,
			struct cmd_header *),
	unsigned long callback_arg)
{
	struct cmd_ctrl_node *cmdnode;

	lbtf_deb_enter(LBTF_DEB_HOST);

	if (priv->surpriseremoved) {
		lbtf_deb_host("PREP_CMD: card removed\n");
		cmdnode = ERR_PTR(-ENOENT);
		goto done;
	}

	cmdnode = lbtf_get_cmd_ctrl_node(priv);
	if (cmdnode == NULL) {
		lbtf_deb_host("PREP_CMD: cmdnode is NULL\n");

		/* Wake up main thread to execute next command */
		queue_work(lbtf_wq, &priv->cmd_work);
		cmdnode = ERR_PTR(-ENOBUFS);
		goto done;
	}

	cmdnode->callback = callback;
	cmdnode->callback_arg = callback_arg;

	/* Copy the incoming command to the buffer */
	memcpy(cmdnode->cmdbuf, in_cmd, in_cmd_size);

	/* Set sequence number, clean result, move to buffer */
	priv->seqnum++;
	cmdnode->cmdbuf->command = cpu_to_le16(command);
	cmdnode->cmdbuf->size    = cpu_to_le16(in_cmd_size);
	cmdnode->cmdbuf->seqnum  = cpu_to_le16(priv->seqnum);
	cmdnode->cmdbuf->result  = 0;

	lbtf_deb_host("PREP_CMD: command 0x%04x\n", command);

	cmdnode->cmdwaitqwoken = 0;
	lbtf_queue_cmd(priv, cmdnode);
	queue_work(lbtf_wq, &priv->cmd_work);

 done:
	lbtf_deb_leave_args(LBTF_DEB_HOST, "ret %p", cmdnode);
	return cmdnode;
}

void lbtf_cmd_async(struct lbtf_private *priv, uint16_t command,
	struct cmd_header *in_cmd, int in_cmd_size)
{
	lbtf_deb_enter(LBTF_DEB_CMD);
	__lbtf_cmd_async(priv, command, in_cmd, in_cmd_size, NULL, 0);
	lbtf_deb_leave(LBTF_DEB_CMD);
}

int __lbtf_cmd(struct lbtf_private *priv, uint16_t command,
	      struct cmd_header *in_cmd, int in_cmd_size,
	      int (*callback)(struct lbtf_private *,
			      unsigned long, struct cmd_header *),
	      unsigned long callback_arg)
{
	struct cmd_ctrl_node *cmdnode;
	unsigned long flags;
	int ret = 0;

	lbtf_deb_enter(LBTF_DEB_HOST);

	cmdnode = __lbtf_cmd_async(priv, command, in_cmd, in_cmd_size,
				  callback, callback_arg);
	if (IS_ERR(cmdnode)) {
		ret = PTR_ERR(cmdnode);
		goto done;
	}

	might_sleep();
	ret = wait_event_interruptible(cmdnode->cmdwait_q,
				       cmdnode->cmdwaitqwoken);
	if (ret) {
		pr_info("PREP_CMD: command 0x%04x interrupted by signal: %d\n",
			    command, ret);
		goto done;
	}

	spin_lock_irqsave(&priv->driver_lock, flags);
	ret = cmdnode->result;
	if (ret)
		pr_info("PREP_CMD: command 0x%04x failed: %d\n",
			    command, ret);

	__lbtf_cleanup_and_insert_cmd(priv, cmdnode);
	spin_unlock_irqrestore(&priv->driver_lock, flags);

done:
	lbtf_deb_leave_args(LBTF_DEB_HOST, "ret %d", ret);
	return ret;
}
EXPORT_SYMBOL_GPL(__lbtf_cmd);

/* Call holding driver_lock */
void lbtf_cmd_response_rx(struct lbtf_private *priv)
{
	priv->cmd_response_rxed = 1;
	queue_work(lbtf_wq, &priv->cmd_work);
}
EXPORT_SYMBOL_GPL(lbtf_cmd_response_rx);

int lbtf_process_rx_command(struct lbtf_private *priv)
{
	uint16_t respcmd, curcmd;
	struct cmd_header *resp;
	int ret = 0;
	unsigned long flags;
	uint16_t result;

	lbtf_deb_enter(LBTF_DEB_CMD);

	mutex_lock(&priv->lock);
	spin_lock_irqsave(&priv->driver_lock, flags);

	if (!priv->cur_cmd) {
		ret = -1;
		spin_unlock_irqrestore(&priv->driver_lock, flags);
		goto done;
	}

	resp = (void *)priv->cmd_resp_buff;
	curcmd = le16_to_cpu(priv->cur_cmd->cmdbuf->command);
	respcmd = le16_to_cpu(resp->command);
	result = le16_to_cpu(resp->result);

	if (net_ratelimit())
		pr_info("libertastf: cmd response 0x%04x, seq %d, size %d\n",
			respcmd, le16_to_cpu(resp->seqnum),
			le16_to_cpu(resp->size));

	if (resp->seqnum != priv->cur_cmd->cmdbuf->seqnum) {
		spin_unlock_irqrestore(&priv->driver_lock, flags);
		ret = -1;
		goto done;
	}
	if (respcmd != CMD_RET(curcmd)) {
		spin_unlock_irqrestore(&priv->driver_lock, flags);
		ret = -1;
		goto done;
	}

	if (resp->result == cpu_to_le16(0x0004)) {
		/* 0x0004 means -EAGAIN. Drop the response, let it time out
		   and be resubmitted */
		spin_unlock_irqrestore(&priv->driver_lock, flags);
		ret = -1;
		goto done;
	}

	/* Now we got response from FW, cancel the command timer */
	del_timer(&priv->command_timer);
	priv->cmd_timed_out = 0;
	if (priv->nr_retries)
		priv->nr_retries = 0;

	/* If the command is not successful, cleanup and return failure */
	if ((result != 0 || !(respcmd & 0x8000))) {
		/*
		 * Handling errors here
		 */
		switch (respcmd) {
		case CMD_RET(CMD_GET_HW_SPEC):
		case CMD_RET(CMD_802_11_RESET):
			pr_info("libertastf: reset failed\n");
			break;

		}
		lbtf_complete_command(priv, priv->cur_cmd, result);
		spin_unlock_irqrestore(&priv->driver_lock, flags);

		ret = -1;
		goto done;
	}

	spin_unlock_irqrestore(&priv->driver_lock, flags);

	if (priv->cur_cmd && priv->cur_cmd->callback) {
		ret = priv->cur_cmd->callback(priv, priv->cur_cmd->callback_arg,
				resp);
	}
	spin_lock_irqsave(&priv->driver_lock, flags);

	if (priv->cur_cmd) {
		/* Clean up and Put current command back to cmdfreeq */
		lbtf_complete_command(priv, priv->cur_cmd, result);
	}
	spin_unlock_irqrestore(&priv->driver_lock, flags);

done:
	mutex_unlock(&priv->lock);
	lbtf_deb_leave_args(LBTF_DEB_CMD, "ret %d", ret);
	return ret;
}


text:
#ifndef NANAIRO_PINHOLE_CAMERA_HPP
#define NANAIRO_PINHOLE_CAMERA_HPP

// Standard C++ library
#include <array>
// Zisc
#include "zisc/utility.hpp"
// Nanairo
#include "camera_model.hpp"
#include "NanairoCore/nanairo_core_config.hpp"
#include "NanairoCore/Geometry/point.hpp"
#include "NanairoCore/Geometry/vector.hpp"
#include "NanairoCore/Setting/setting_node_base.hpp"

namespace nanairo {

// Forward declaration
class PathState;
class Ray;
class SampledDirection;
class Sampler;

//! \addtogroup Core
//! \{

/*!
 \details
 No detailed.
 */
class PinholeCamera : public CameraModel
{
 public:
  class FilmShape
  {
   public:
    //! Initialize the film
    FilmShape(const Point3& c) noexcept;

    //! Return the center point of the film
    Point3 center() const noexcept;

    //! Return the film axises
    const std::array<Vector3, 2>& edge() const noexcept;

    //! Initialize the film shape
    void initialize(const Float aspect_ratio,
                    const Float angle_of_view) noexcept;

    //! Return the normal of the film
    const Vector3& normal() const noexcept;

    //! Set the center of the film
    void setCenter(const Point3& c) noexcept;

    //! Return the surface area of the front side of the film
    Float surfaceArea() const noexcept;

    //! Test ray-film intersection
    bool testIntersection(const Ray& ray, Point2* st) const noexcept;

    //! Apply affine transformation
    void transform(const Matrix4x4& matrix) noexcept;

    //! Return the vertex0 of the film
    const Point3& vertex0() const noexcept;

   private:
    //! Calculate the normal vector
    Vector3 calcNormal(const Vector3& e1, const Vector3& e2) const noexcept;

    Float surface_area_;
    Point3 vertex0_; //!< The left bottom point of the film
    std::array<Vector3, 2> edge_;
    Vector3 normal_;
  };

  //! Create a pinhole camera
  PinholeCamera(const SettingNodeBase* settings) noexcept;

  //! Return the angle of view
  Float angleOfView() const noexcept;

  //! Calculate the pdf
  Float calcPdf(const Vector3& vout) const noexcept override;

  //! Calculate the pixel location of the film
  bool calcPixelLocation(const Vector3& ray_direction,
                         Index2d* index) const noexcept override;

  //! Calculate the radiance
  Float calcRadiance(const Vector3& vout) const noexcept override;

  //! Calculate the radiance and pdf
  std::array<Float, 2> calcRadianceAndPdf(const Vector3& vout)
      const noexcept override;

  //! Return the film shape
  const FilmShape& filmShape() const noexcept;

  //! Return the normal of the pinhole camera
  Vector3 getNormal(const Index2d& index) const noexcept override;

  //! Return the camera position
  const Point3& position() const noexcept override;

  //! Sample ray direction
  SampledDirection sampleDirection(const Index2d& index) const noexcept override;

  //! Return the sampled lens point
  const Point3& sampledLensPoint() const noexcept override;

  //! Sample pinhole point
  void sampleLensPoint(Sampler& sampler,
                       const PathState& path_state) noexcept override;

  //! Apply affine transformation
  void transform(const Matrix4x4& matrix) noexcept override;

  //! Return the pinhole camera type
  CameraType type() const noexcept override;

  //! Return the x axis vector of the camera coordinate
  Vector3 xAxis() const noexcept override;

  //! Return the y axis vector of the camera coordinate
  Vector3 yAxis() const noexcept override;

  //! Return the z axis vector of the camera coordinate
  Vector3 zAxis() const noexcept override;

 private:
  //! Calculate the inverse pdf
  Float calcInversePdf(const Float cos_theta) const noexcept;

  //! Initialize the film shape
  void initFilmShape() noexcept override;

  //! Initialize
  void initialize(const SettingNodeBase* settings) noexcept;

  Point3 pinhole_position_; //!< The position of pinhole
  FilmShape film_shape_;
  Float angle_of_view_;
};

//! \} Core

} // namespace nanairo

#include "pinhole_camera-inl.hpp"

#endif // NANAIRO_PINHOLE_CAMERA_HPP


text:
package com.esri.gpt.catalog.schema;
import com.esri.gpt.framework.util.Val;
import com.esri.gpt.framework.xml.DomUtil;
import javax.faces.component.UIComponent;
import javax.faces.component.html.HtmlInputTextarea;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;

/**
 * Input text area component associated with a metadata parameter.
 *

 * The component is configured from a node with a schema configuration
 * XML document.
 *

 * Example:

 *
<parameter key="abstract">
 *
<input type="textArea" cols="60" rows="8"/>
 *
</parameter>
 */
public class InputTextArea extends InputText {

// class variables =============================================================

// instance variables ==========================================================
private int _cols;
private int _rows;

// constructors ================================================================

/** Default constructor. */
public InputTextArea() {
  this(null);
}

/**
 * Construct by duplicating an existing object.
 * @param objectToDuplicate the object to duplicate
 */
public InputTextArea(InputTextArea objectToDuplicate) {
  super(objectToDuplicate);
  if (objectToDuplicate == null) {
    setCols(getDefaultCols());
    setRows(getDefaultRows());
  } else {
    setCols(objectToDuplicate.getCols());
    setRows(objectToDuplicate.getRows());
  }
}

// properties ==================================================================

/**
 * Gets the default number of columns (60).
 * @return the default number of columns
 */
public int getDefaultCols() {
  return 60;
}

/**
 * Gets the default max length (4000).
 * @return the default max length
 */
@Override
public int getDefaultMaxlength() {
  return 4000;
}

/**
 * Gets the default number of rows (8).
 * @return the number of rows
 */
public int getDefaultRows() {
  return 8;
}

/**
 * Gets the number of columns in the text area component.
 * @return the number of columns
 */
public int getCols() {
  return _cols;
}
/**
 * Sets the number of columns in the text area component.
 * @param size the number of columns
 */
public void setCols(int size) {
  _cols = (size < 1) ? getDefaultCols() : size;
}

/**
 * Gets the number of rows in the text area component.
 * @return the number of rows
 */
public int getRows() {
  return _rows;
}
/**
 * Sets the number of rows in the text area component.
 * @param size the number of rows
 */
public void setRows(int size) {
  _rows = (size < 1) ? getDefaultRows() : size;
}

// methods =====================================================================

/**
 * Configures the object based upon a node loaded from a
 * schema configuration XML.
 *
The super.configure method should be invoked prior to any
 * sub-class configuration.
 *

 * The following attributes are configured:
 *
cols rows
 * @param context the configuration context
 * @param node the configuration node
 * @param attributes the attributes of the configuration node
 */
@Override
public void configure(CfgContext context, Node node, NamedNodeMap attributes) {
  super.configure(context,node,attributes);
  setCols(Val.chkInt(DomUtil.getAttributeValue(attributes,"cols"),-1));
  setRows(Val.chkInt(DomUtil.getAttributeValue(attributes,"rows"),-1));
}

/**
 * Produces a deep clone of the object.
 *
The duplication constructor is invoked.
 *
return new InputTextArea(this);
 */
@Override
public InputTextArea duplicate() {
  return new InputTextArea(this);
}

/**
 * Appends property information for the component to a StringBuffer.
 *
The method is intended to support "FINEST" logging.
 *
super.echo should be invoked prior appending any local information.
 * @param sb the StringBuffer to use when appending information
 */
@Override
public void echo(StringBuffer sb) {
  super.echo(sb);
  sb.append(" cols=\"").append(getCols()).append("\"");
  sb.append(" rows=\"").append(getRows()).append("\"");
}

/**
 * Makes a Faces HtmlInputTextarea component for a parameter.
 * @param context the UI context
 * @param section the parent section
 * @param parameter the associated parameter
 * @return the UI component
 */
@Override
public UIComponent makeInputComponent(UiContext context,
                                      Section section,
                                      Parameter parameter) {

  // make the component
  HtmlInputTextarea component = new HtmlInputTextarea();
  component.setId(getFacesId());
  component.setCols(getCols());
  component.setRows(getRows());
  component.setDisabled(!getEditable());
  component.setOnchange(getOnChange());
  component.setOnclick(getOnClick());
  setComponentValue(context,component,parameter);
  return applyHint(context,component);
}

}


text:
const severitiesByKey = {
	error: 'error'
};
const validator = function (opts = {}) {
	const {
		rules = [],
		value
	} = opts;
	const results = {
		isValid: true,
		message: null
	};

	if (rules && rules.length) {
		const failedRule = rules.find(obj => {
			const {test, forced} = obj;

			if (forced === true) {
				return true;
			}

			if (typeof test === 'function') {
				return test(value);
			} else if (test) {
				return test.test(value);
			}

			return false;
		});

		if (failedRule) {
			results.isValid = false;
			results.message = failedRule.message;
			results.severity = failedRule.severity || severitiesByKey.error;
		}
	}

	return results;
};

export {
	severitiesByKey,
	validator
};


text:
package net.drewke.tdme.engine.fileio.models;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;

import net.drewke.tdme.engine.model.Face;
import net.drewke.tdme.engine.model.FacesEntity;
import net.drewke.tdme.engine.model.Group;
import net.drewke.tdme.engine.model.Material;
import net.drewke.tdme.engine.model.Model;
import net.drewke.tdme.engine.model.Model.UpVector;
import net.drewke.tdme.engine.model.ModelHelper;
import net.drewke.tdme.engine.model.RotationOrder;
import net.drewke.tdme.engine.model.TextureCoordinate;
import net.drewke.tdme.math.Vector3;
import net.drewke.tdme.os.FileSystem;
import net.drewke.tdme.utils.ArrayList;
import net.drewke.tdme.utils.HashMap;

/**
 * Wavefront object reader
 * @author andreas.drewke
 * @version $Id$
 */
public final class WFObjReader {

	/**
	 * Reads a wave front object file
	 * @param path name
	 * @param file name
	 * @return model
	 * @throws IOException
	 * @throws ModelIOException
	 */
	public static Model read(String pathName, String fileName) throws IOException, ModelFileIOException {
		// create object
		Model model = new Model(pathName + File.separator + fileName, fileName, UpVector.Y_UP, RotationOrder.XYZ, null);

		ArrayList<Vector3> vertices = new ArrayList<Vector3>();
		ArrayList<TextureCoordinate> textureCoordinates = new ArrayList<TextureCoordinate>();

		HashMap<String, Material> materials = model.getMaterials();
		HashMap<String, Group> subGroups = model.getSubGroups();
		HashMap<String, Group> groups = model.getGroups();

		// current group
		Group group = null;

		// model vertices -> group vertices mapping
		HashMap<Integer, Integer> modelGroupVerticesMapping = null;
		// model texture coordinates -> group texture coordinates mapping
		HashMap<Integer, Integer> modelGroupTextureCoordinatesMapping = null;

		// current group data
		ArrayList<Face> groupFacesEntityFaces = null;
		ArrayList<Vector3> groupVertices = null;
		ArrayList<Vector3> groupNormals = null;
		ArrayList<TextureCoordinate> groupTextureCoordinates = null;

		// current group's faces entity
		ArrayList<FacesEntity> groupFacesEntities = null;
		FacesEntity groupFacesEntity = null;

		//
		DataInputStream inputStream = new DataInputStream(FileSystem.getInstance().getInputStream(pathName, fileName));
		BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));

		//
		try {
			//
			String line;
			while ((line = reader.readLine()) != null) {
				line = line.trim();

				// skip on comments
				if (line.startsWith("#")) {
					continue;
				}

				// determine index of first ' ' which will separate command from arguments
				int commandEndIdx = line.indexOf(' ');
				if (commandEndIdx == -1) commandEndIdx = line.length();

				// determine command
				String command = line.substring(0, commandEndIdx).trim().toLowerCase();

				// determine arguments if any exist
				String arguments = command.length() + 1 > line.length()?"":line.substring(command.length() + 1);

				// parse
				if (command.equals("mtllib")) {
					String materialFileName = arguments;
					materials = WFObjReader.readMaterials(pathName, materialFileName);
				} else
				if (command.equals("v")) {
					StringTokenizer t = new StringTokenizer(arguments, " ");
					float x = Float.parseFloat(t.nextToken());
					float y = Float.parseFloat(t.nextToken());
					float z = Float.parseFloat(t.nextToken());
					// add vertex
					vertices.add(new Vector3(x, y, z));
				} else
				if (command.equals("vt")) {
					StringTokenizer t = new StringTokenizer(arguments, " ");
					float u = Float.parseFloat(t.nextToken());
					float v = Float.parseFloat(t.nextToken());
					textureCoordinates.add(new TextureCoordinate(u, v));
				} else
				if (command.equals("f")) {
					StringTokenizer t2;
					StringTokenizer t = new StringTokenizer(arguments, " ");
					int v0 = -1;
					int v1 = -1;
					int v2 = -1;
					int vt0 = -1;
					int vt1 = -1;
					int vt2 = -1;

					// parse vertex index 0, vertex texture index 0
					t2 = new StringTokenizer(t.nextToken(), "/");
					v0 = Integer.parseInt(t2.nextToken()) - 1;
					if (t2.hasMoreTokens()) {
						vt0 = Integer.parseInt(t2.nextToken()) - 1;
					}
					// parse vertex index 1, vertex texture index 1
					t2 = new StringTokenizer(t.nextToken(), "/");
					v1 = Integer.parseInt(t2.nextToken()) - 1;
					if (t2.hasMoreTokens()) {
						vt1 = Integer.parseInt(t2.nextToken()) - 1;
					}
					// parse vertex index 2, vertex texture index 2
					t2 = new StringTokenizer(t.nextToken(), "/");
					v2 = Integer.parseInt(t2.nextToken()) - 1;
					if (t2.hasMoreTokens()) {
						vt2 = Integer.parseInt(t2.nextToken()) - 1;
					}

					// check if triangulated
					if (t.hasMoreTokens()) {
						throw new ModelFileIOException("We only support triangulated meshes");
					}

					Integer mappedVertex = null;

					// map v0 to group
					mappedVertex = modelGroupVerticesMapping.get(v0);
					if (mappedVertex == null) {
						groupVertices.add(vertices.get(v0).clone());
						v0 = groupVertices.size() - 1;
					} else {
						v0 = mappedVertex.intValue();
					}

					// map v1 to group
					mappedVertex = modelGroupVerticesMapping.get(v1);
					if (mappedVertex == null) {
						groupVertices.add(vertices.get(v1).clone());
						v1 = groupVertices.size() - 1;
					} else {
						v1 = mappedVertex.intValue();
					}

					// map v2 to group
					mappedVertex = modelGroupVerticesMapping.get(v2);
					if (mappedVertex == null) {
						groupVertices.add(vertices.get(v2).clone());
						v2 = groupVertices.size() - 1;
					} else {
						v2 = mappedVertex.intValue();
					}

					//
					Integer mappedTextureCoordinate = null;

					// map vt0 to group
					mappedTextureCoordinate = modelGroupTextureCoordinatesMapping.get(vt0);
					if (mappedTextureCoordinate == null) {
						groupTextureCoordinates.add(textureCoordinates.get(vt0).clone());
						vt0 = groupTextureCoordinates.size() - 1;
					} else {
						vt0 = mappedTextureCoordinate.intValue();
					}

					// map vt1 to group
					mappedTextureCoordinate = modelGroupTextureCoordinatesMapping.get(vt1);
					if (mappedTextureCoordinate == null) {
						groupTextureCoordinates.add(textureCoordinates.get(vt1).clone());
						vt1 = groupTextureCoordinates.size() - 1;
					} else {
						vt1 = mappedTextureCoordinate.intValue();
					}

					// map vt2 to group
					mappedTextureCoordinate = modelGroupTextureCoordinatesMapping.get(vt2);
					if (mappedTextureCoordinate == null) {
						groupTextureCoordinates.add(textureCoordinates.get(vt2).clone());
						vt2 = groupTextureCoordinates.size() - 1;
					} else {
						vt2 = mappedTextureCoordinate.intValue();
					}

					// compute vertex normal
					Vector3[] faceVertexNormals = ModelHelper.computeNormals(new Vector3[] {groupVertices.get(v0), groupVertices.get(v1), groupVertices.get(v2)});

					// store group normals
					int n0 = groupNormals.size();
					groupNormals.add(faceVertexNormals[0]);
					int n1 = groupNormals.size();
					groupNormals.add(faceVertexNormals[1]);
					int n2 = groupNormals.size();
					groupNormals.add(faceVertexNormals[2]);

					// create face with vertex indices
					//	we only support triangulated faces
					Face face = new Face(group, v0, v1, v2, n0, n1, n2);
					if (vt0 != -1 && vt1 != -1 && vt2 != -1) {
						// set optional texture coordinate index
						face.setTextureCoordinateIndices(vt0, vt1, vt2);
					}
					groupFacesEntityFaces.add(face);
				} else
				if (command.equals("g")) {
					if (group != null) {
						// current faces entity
						if (groupFacesEntityFaces.isEmpty() == false) {
							groupFacesEntity.setFaces(groupFacesEntityFaces);
							groupFacesEntities.add(groupFacesEntity);
						}

						// group
						group.setVertices(groupVertices);
						group.setNormals(groupNormals);
						group.setTextureCoordinates(groupTextureCoordinates);
						group.setFacesEntities(groupFacesEntities);
						group.determineFeatures();
					}
					StringTokenizer t = new StringTokenizer(arguments, " ");
					String name = t.nextToken();
					groupVertices = new ArrayList<Vector3>();
					groupNormals = new ArrayList<Vector3>();
					groupTextureCoordinates = new ArrayList<TextureCoordinate>();
					groupFacesEntityFaces = new ArrayList<Face>();
					group = new Group(
						model,
						null,
						name,
						name
					);
					groupFacesEntity = new FacesEntity(group, name);
					groupFacesEntities = new ArrayList<FacesEntity>();
					modelGroupVerticesMapping = new HashMap<Integer, Integer>();
					modelGroupTextureCoordinatesMapping = new HashMap<Integer, Integer>();
					subGroups.put(name, group);
					groups.put(name, group);
				} else
				if (command.equals("usemtl")) {
					if (group != null) {
						// current faces entity
						if (groupFacesEntityFaces.isEmpty() == false) {
							groupFacesEntity.setFaces(groupFacesEntityFaces);
							groupFacesEntities.add(groupFacesEntity);
						}

						// set up new one
						groupFacesEntity = new FacesEntity(group, "#" + groupFacesEntities.size());
						groupFacesEntityFaces = new ArrayList<Face>();
					}
					groupFacesEntity.setMaterial(materials.get(arguments));
				} else {
					// not supported
				}

			}

			// finish last group
			if (group != null) {
				// current faces entity
				if (groupFacesEntityFaces.isEmpty() == false) {
					groupFacesEntity.setFaces(groupFacesEntityFaces);
					groupFacesEntities.add(groupFacesEntity);
				}

				// group
				group.setVertices(groupVertices);
				group.setNormals(groupNormals);
				group.setTextureCoordinates(groupTextureCoordinates);
				group.setFacesEntities(groupFacesEntities);
				group.determineFeatures();
			}
		} finally {
			// close resouces
			reader.close();
			inputStream.close();
		}

		// prepare for indexed rendering
		ModelHelper.prepareForIndexedRendering(model);

		//
		return model;
	}

	/**
	 * Reads a wavefront object material library
	 * @param path name
	 * @param file name
	 * @return
	 */
	private static HashMap<String, Material> readMaterials(String pathName, String fileName) throws IOException {
		HashMap<String, Material> materials = new HashMap<String, Material>();
		Material current = null;
		//
		DataInputStream inputStream = new DataInputStream(FileSystem.getInstance().getInputStream(pathName, fileName));
		BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
		String line;
		float alpha = 1.0f;
		while ((line = reader.readLine()) != null) {
			line = line.trim();

			// skip on comments
			if (line.startsWith("#")) {
				continue;
			}

			// determine index of first ' ' which will separate command from arguments
			int commandEndIdx = line.indexOf(' ');
			if (commandEndIdx == -1) commandEndIdx = line.length();

			// determine command
			String command = line.substring(0, commandEndIdx).trim().toLowerCase();

			// determine arguments if any exist
			String arguments = command.length() + 1 > line.length()?"":line.substring(command.length() + 1);

			// parse
			if (command.equals("newmtl")) {
				String name = arguments;
				current = new Material(name);
				materials.put(name, current);
			} else
			if (command.equals("map_ka")) {
				current.setDiffuseTexture(pathName, arguments);
			} else
			if (command.equals("map_kd")) {
				current.setDiffuseTexture(pathName, arguments);
			} else
			if (command.equals("ka")) {
				StringTokenizer t = new StringTokenizer(arguments, " ");
				current.getAmbientColor().set(
					Float.parseFloat(t.nextToken()),
					Float.parseFloat(t.nextToken()),
					Float.parseFloat(t.nextToken()),
					alpha
				);
			} else
			if (command.equals("kd")) {
				StringTokenizer t = new StringTokenizer(arguments, " ");
				current.getDiffuseColor().set(
					Float.parseFloat(t.nextToken()),
					Float.parseFloat(t.nextToken()),
					Float.parseFloat(t.nextToken()),
					alpha
				);
			} else
			if (command.equals("ks")) {
				StringTokenizer t = new StringTokenizer(arguments, " ");
				current.getSpecularColor().set(
					Float.parseFloat(t.nextToken()),
					Float.parseFloat(t.nextToken()),
					Float.parseFloat(t.nextToken()),
					alpha
				);
			} else
			if (command.equals("tr")) {
				alpha = Float.parseFloat(arguments);
				current.getAmbientColor().setAlpha(alpha);
				current.getDiffuseColor().setAlpha(alpha);
				current.getSpecularColor().setAlpha(alpha);
				current.getEmissionColor().setAlpha(alpha);
			} else
			if (command.equals("d")) {
				alpha = Float.parseFloat(arguments);
				current.getAmbientColor().setAlpha(alpha);
				current.getDiffuseColor().setAlpha(alpha);
				current.getSpecularColor().setAlpha(alpha);
				current.getEmissionColor().setAlpha(alpha);
			}
		}

		// Close the input stream
		inputStream.close();

		//
		return materials;
	}

}