text:
package io.fabric8.mq.controller.multiplexer;

import io.fabric8.mq.controller.AsyncExecutors;
import io.fabric8.mq.controller.model.DestinationStatisticsMBean;
import io.fabric8.mq.controller.model.InboundConnection;
import io.fabric8.mq.controller.model.Model;
import io.fabric8.mq.controller.util.LRUCache;
import io.fabric8.mq.controller.util.TransportConnectionStateRegister;
import org.apache.activemq.advisory.AdvisorySupport;
import org.apache.activemq.command.*;
import org.apache.activemq.state.CommandVisitor;
import org.apache.activemq.state.ConsumerState;
import org.apache.activemq.state.ProducerState;
import org.apache.activemq.transport.DefaultTransportListener;
import org.apache.activemq.transport.Transport;
import org.apache.activemq.transport.TransportListener;
import org.apache.activemq.transport.TransportSupport;
import org.apache.activemq.util.ServiceStopper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;

public class MultiplexerInput extends TransportSupport implements CommandVisitor, InboundConnection {
    private static Logger LOG = LoggerFactory.getLogger(MultiplexerInput.class);
    private final Multiplexer multiplexer;
    private final Model model;
    private final String protocol;
    private final String name;
    private final AsyncExecutors asyncExecutors;
    private final TransportConnectionStateRegister multiplexerConnectionStateRegister;
    private final ConnectionId multiplexerConnectionId;
    private final SessionId multiplexerSessionId;
    private final Transport input;
    final private Map<SessionId, SessionId> sessionIdMap = new ConcurrentHashMap<>();
    final private Map<ProducerId, ProducerId> producerIdMap = new ConcurrentHashMap<>();
    final private Map<ConsumerId, ConsumerId> originalConsumerIdKeyMap = new ConcurrentHashMap<>();
    final private Map<ConsumerId, ConsumerId> multiplexerConsumerIdKeyMap = new ConcurrentHashMap<>();
    final private Map<TransactionId, TransactionId> transactionIdMap = new LRUCache<>(10000);
    final private DestinationRegister destinationRegister;
    private ConnectionInfo connectionInfo;
    private AtomicLong inboundMessageCount = new AtomicLong();
    private AtomicLong outboundMessageCount = new AtomicLong();

    MultiplexerInput(Multiplexer multiplexer, String name, String protocol, AsyncExecutors asyncExecutors, TransportConnectionStateRegister transportConnectionStateRegister, Transport input) {
        this.multiplexer = multiplexer;
        this.name = name;
        this.protocol = protocol;
        this.model = multiplexer.getModel();
        this.asyncExecutors = asyncExecutors;
        this.multiplexerConnectionStateRegister = transportConnectionStateRegister;
        this.input = input;
        this.multiplexerConnectionId = multiplexer.getMultiplexerConnectionInfo().getConnectionId();
        this.multiplexerSessionId = multiplexer.getMultiplexerSessionInfo().getSessionId();
        this.destinationRegister = new DestinationRegister(model, this);

    }

    public Transport getInput() {
        return input;
    }

    public ConnectionId getMultiplexerConnectionId() {
        return multiplexerConnectionId;
    }

    public void setTransportListener(TransportListener commandListener) {
        super.setTransportListener(commandListener);
        input.setTransportListener(commandListener);
    }

    public Multiplexer getMultiplexer() {
        return multiplexer;
    }

    @Override
    protected void doStop(ServiceStopper serviceStopper) throws Exception {
        //clear down our ConnectionState
        for (SessionId sessionId : sessionIdMap.values()) {
            removeSession(sessionId);
        }

        multiplexer.removeInput(this);
        if (serviceStopper != null) {
            serviceStopper.stop(input);
        } else {
            input.stop();
        }
        originalConsumerIdKeyMap.clear();
        multiplexerConsumerIdKeyMap.clear();
        sessionIdMap.clear();
        producerIdMap.clear();
        transactionIdMap.clear();
        model.remove(this);

    }

    @Override
    protected void doStart() throws Exception {
        setTransportListener(new DefaultTransportListener() {
            @Override
            public void onCommand(Object command) {
                if (command.getClass() == ShutdownInfo.class) {
                    try {
                        stop();
                    } catch (Exception e) {
                        LOG.debug("Caught exception stopping", e);
                    }
                }

                try {
                    processCommand(command);
                } catch (Throwable error) {
                    onFailure(error);
                }
            }

            @Override
            public void onException(IOException error) {
                onFailure(error);
            }
        });

        this.input.start();
        model.add(this);
    }

    protected void processCommand(Object o) {
        try {
            Command command = (Command) o;
            Response response = command.visit(this);
            if (response != null) {
                //we are processing this locally - not via the Broker
                response.setCorrelationId(command.getCommandId());
                oneway(response);
            }

        } catch (Throwable e) {
            onFailure(e);
        }
    }

    @Override
    public void oneway(Object o) throws IOException {
        input.oneway(o);
    }

    public void oneway(MessageDispatch messageDispatch) throws IOException {
        ConsumerId consumerId = messageDispatch.getConsumerId();
        ConsumerId originalConsumerId = getOriginalConsumerId(consumerId);
        messageDispatch.setConsumerId(originalConsumerId);
        input.oneway(messageDispatch);
        destinationRegister.addMessageOutbound(messageDispatch.getDestination());
        outboundMessageCount.incrementAndGet();
    }

    @Override
    public String getName() {
        return name;
    }

    @Override
    public String getRemoteAddress() {
        return input.getRemoteAddress();
    }

    @Override
    public int getReceiveCounter() {
        return input.getReceiveCounter();
    }

    public void onFailure(Throwable e) {
        if (!isStopping()) {
            LOG.debug("Transport error: {}", e.getMessage(), e);
            try {
                stop();
            } catch (Exception ignore) {
            }
        }
    }

    @Override
    public Response processAddConnection(ConnectionInfo connectionInfo) throws Exception {
        this.connectionInfo = connectionInfo;
        ConnectionInfo copy = connectionInfo.copy();
        copy.setConnectionId(getMultiplexerConnectionId());
        /*
        multiplexer.sendOutAll(this, copy);
        multiplexerConnectionStateRegister.registerConnectionState(copy.getConnectionId(), copy);
        */
        Response response = new Response();
        response.setCorrelationId(connectionInfo.getCommandId());
        return response;
    }

    @Override
    public Response processAddSession(SessionInfo sessionInfo) throws Exception {
        SessionInfo copy = new SessionInfo();
        sessionInfo.copy(copy);
        SessionId originalSessionId = sessionInfo.getSessionId();
        SessionId sessionId = new SessionId(getMultiplexerConnectionId(), multiplexer.getNextSessionId());
        sessionIdMap.put(originalSessionId, sessionId);
        copy.setSessionId(sessionId);
        multiplexer.sendOutAll(this, copy);
        multiplexerConnectionStateRegister.addSession(copy);
        return null;
    }

    @Override
    public Response processAddProducer(ProducerInfo producerInfo) throws Exception {
        ProducerInfo copy = producerInfo.copy();
        SessionId originalSessionId = producerInfo.getProducerId().getParentId();
        SessionId newSessionId = sessionIdMap.get(originalSessionId);
        if (newSessionId == null) {
            newSessionId = new SessionId(getMultiplexerConnectionId(), multiplexer.getNextSessionId());
            sessionIdMap.put(originalSessionId, newSessionId);
        }
        ProducerId producerId = new ProducerId(newSessionId, multiplexer.getNextProducerId());
        copy.setProducerId(producerId);
        producerIdMap.put(producerInfo.getProducerId(), producerId);
        multiplexer.sendOutAll(this, copy);
        multiplexerConnectionStateRegister.addProducer(copy);
        destinationRegister.registerProducer(producerInfo.getDestination());
        return null;
    }

    @Override
    public Response processAddConsumer(ConsumerInfo consumerInfo) throws Exception {
        ConsumerId originalConsumerId = consumerInfo.getConsumerId();
        ConsumerInfo copy = new ConsumerInfo();
        consumerInfo.copy(copy);
        SessionId originalSessionId = consumerInfo.getConsumerId().getParentId();
        SessionId newSessionId = sessionIdMap.get(originalSessionId);
        if (newSessionId == null) {
            //Connection Advisory Consumer sets session id to -1
            if (originalSessionId.getValue() == -1) {
                newSessionId = multiplexerSessionId;
            } else {
                newSessionId = new SessionId(getMultiplexerConnectionId(), multiplexer.getNextSessionId());
            }
            sessionIdMap.put(originalSessionId, newSessionId);
        }
        ConsumerId multiplexConsumerId = new ConsumerId(newSessionId, multiplexer.getNextConsumerId());

        copy.setConsumerId(multiplexConsumerId);
        storeConsumerId(originalConsumerId, multiplexConsumerId);
        multiplexer.registerConsumer(multiplexConsumerId, this);
        multiplexer.sendOutAll(this, copy);
        multiplexerConnectionStateRegister.addConsumer(copy);
        if (!AdvisorySupport.isAdvisoryTopic(consumerInfo.getDestination())) {
            destinationRegister.registerConsumer(consumerInfo.getDestination());
        }
        return null;
    }

    @Override
    public Response processRemoveConnection(ConnectionId connectionId, long l) throws Exception {
        /**
         * The connection is shutting down - and will expect a response.
         * We don't forward these - as the remote Broker will get confused
         * so we sent back a response ourseleves
         */
        if (connectionInfo != null) {
            RemoveInfo removeCommand = connectionInfo.createRemoveCommand();
            removeCommand.setResponseRequired(false);
            removeCommand.setLastDeliveredSequenceId(l);
            /*
            multiplexerConnectionStateRegister.unregisterConnectionState(getMultiplexerConnectionId());

            if (!multiplexer.isStopping() && !multiplexer.isStopped()) {
                multiplexer.sendOutAll(this, removeCommand);
            }
            */
        }

        //clear down our ConnectionState
        for (SessionId sessionId : sessionIdMap.values()) {
            if (multiplexerConnectionStateRegister.removeSession(sessionId) != null) {
                removeSession(sessionId);
            }
        }
        asyncExecutors.execute(new Runnable() {
            public void run() {
                try {
                    Thread.sleep(1000);
                    stop();
                } catch (Throwable e) {
                    LOG.warn("Caught an error trying to stop");
                }
            }
        });
        return new Response();
    }

    @Override
    public Response processRemoveSession(SessionId sessionId, long l) throws Exception {
        SessionId multiplexerSessionId = sessionIdMap.remove(sessionId);
        if (multiplexerSessionId != null) {
            RemoveInfo removeInfo = new RemoveInfo(multiplexerSessionId);
            removeInfo.setLastDeliveredSequenceId(l);
            multiplexerConnectionStateRegister.removeSession(multiplexerSessionId);
            multiplexer.sendOutAll(this, removeInfo);
        }
        return null;
    }

    @Override
    public Response processRemoveProducer(ProducerId producerId) throws Exception {
        ProducerId originalProducerId = producerIdMap.remove(producerId);
        if (originalProducerId != null) {
            RemoveInfo removeInfo = new RemoveInfo(originalProducerId);
            ProducerState state = multiplexerConnectionStateRegister.removeProducer(originalProducerId);
            multiplexer.sendOutAll(this, removeInfo);
            if (state != null && state.getInfo() != null) {
                destinationRegister.unregisterProducer(state.getInfo().getDestination());
            }
        }
        return null;
    }

    @Override
    public Response processRemoveConsumer(ConsumerId consumerId, long l) throws Exception {
        ConsumerId multiplexerConsumerId = removeByOriginal(consumerId);
        multiplexer.unregisterConsumer(multiplexerConsumerId);
        if (multiplexerConsumerId != null) {
            RemoveInfo removeInfo = new RemoveInfo(multiplexerConsumerId);
            removeInfo.setLastDeliveredSequenceId(l);
            ConsumerState state = multiplexerConnectionStateRegister.removeConsumer(multiplexerConsumerId);
            multiplexer.sendOutAll(this, removeInfo);
            if (state != null && state.getInfo() != null) {
                destinationRegister.unregisterConsumer(state.getInfo().getDestination());
            }
        }
        return null;
    }

    @Override
    public Response processAddDestination(DestinationInfo destinationInfo) throws Exception {
        DestinationInfo copy = destinationInfo.copy();
        copy.setConnectionId(getMultiplexerConnectionId());
        multiplexer.sendOut(this, destinationInfo.getDestination(), copy);
        return null;
    }

    @Override
    public Response processRemoveDestination(DestinationInfo destinationInfo) throws Exception {
        DestinationInfo copy = destinationInfo.copy();
        copy.setConnectionId(getMultiplexerConnectionId());
        multiplexer.sendOut(this, destinationInfo.getDestination(), copy);
        return null;
    }

    @Override
    public Response processRemoveSubscription(RemoveSubscriptionInfo removeSubscriptionInfo) throws Exception {
        removeSubscriptionInfo.setConnectionId(getMultiplexerConnectionId());
        multiplexer.sendOutAll(this, removeSubscriptionInfo);
        return null;
    }

    @Override
    public Response processMessage(Message message) throws Exception {

        ProducerId originalProducerId = message.getProducerId();
        ProducerId newProducerId = producerIdMap.get(originalProducerId);
        if (newProducerId != null) {
            ActiveMQDestination destination = message.getDestination();
            Message copy = message.copy();
            copy.setProducerId(newProducerId);
            copy.setTransactionId(getMultiplexTransactionId(message.getOriginalTransactionId()));
            multiplexer.sendOut(this, destination, copy);
            destinationRegister.addMessageInbound(destination);
            inboundMessageCount.incrementAndGet();
        } else {
            LOG.error("Cannot find producerId for " + originalProducerId);
        }
        return null;
    }

    @Override
    public Response processMessageAck(MessageAck messageAck) throws Exception {
        MessageAck copy = new MessageAck();
        messageAck.copy(copy);
        copy.setMessageCount(messageAck.getMessageCount());
        copy.setTransactionId(getMultiplexTransactionId(messageAck.getTransactionId()));
        ConsumerId consumerId = messageAck.getConsumerId();
        ConsumerId multiplexerConsumerId = getMultiplexConsumerId(consumerId);
        if (multiplexerConsumerId != null) {
            copy.setConsumerId(multiplexerConsumerId);
            multiplexer.sendOut(this, copy.getDestination(), copy);
        }

        return null;
    }

    @Override
    public Response processMessagePull(MessagePull messagePull) throws Exception {
        ConsumerId consumerId = messagePull.getConsumerId();
        ConsumerId multiplexerConsumerId = getMultiplexConsumerId(consumerId);
        if (multiplexerConsumerId != null) {
            messagePull.setConsumerId(multiplexerConsumerId);
            multiplexer.sendOut(this, messagePull.getDestination(), messagePull);
        }
        return null;
    }

    @Override
    public Response processBeginTransaction(TransactionInfo transactionInfo) throws Exception {
        transactionInfo.setTransactionId(getMultiplexTransactionId(transactionInfo.getTransactionId()));
        multiplexer.sendOutAll(this, transactionInfo);
        return null;
    }

    @Override
    public Response processPrepareTransaction(TransactionInfo transactionInfo) throws Exception {
        transactionInfo.setTransactionId(getMultiplexTransactionId(transactionInfo.getTransactionId()));
        multiplexer.sendOutAll(this, transactionInfo);
        return null;
    }

    @Override
    public Response processCommitTransactionOnePhase(TransactionInfo transactionInfo) throws Exception {
        transactionInfo.setTransactionId(getMultiplexTransactionId(transactionInfo.getTransactionId()));
        multiplexer.sendOutAll(this, transactionInfo);
        return null;
    }

    @Override
    public Response processCommitTransactionTwoPhase(TransactionInfo transactionInfo) throws Exception {
        transactionInfo.setTransactionId(getMultiplexTransactionId(transactionInfo.getTransactionId()));
        multiplexer.sendOutAll(this, transactionInfo);
        return null;
    }

    @Override
    public Response processRollbackTransaction(TransactionInfo transactionInfo) throws Exception {
        transactionInfo.setTransactionId(getMultiplexTransactionId(transactionInfo.getTransactionId()));
        multiplexer.sendOutAll(this, transactionInfo);
        return null;
    }

    @Override
    public Response processWireFormat(WireFormatInfo wireFormatInfo) throws Exception {
        return null;
    }

    @Override
    public Response processKeepAlive(KeepAliveInfo keepAliveInfo) throws Exception {
        return null;
    }

    @Override
    public Response processShutdown(ShutdownInfo shutdownInfo) throws Exception {
        multiplexer.doAsyncProcess(new Runnable() {
            @Override
            public void run() {
                try {
                    stop();
                } catch (Exception e) {
                    LOG.debug("Caught exception stopping", e);
                }
            }
        });
        return null;
    }

    @Override
    public Response processFlush(FlushCommand flushCommand) throws Exception {
        multiplexer.sendOutAll(this, flushCommand);
        return null;
    }

    @Override
    public Response processBrokerInfo(BrokerInfo brokerInfo) throws Exception {
        multiplexer.sendOutAll(this, brokerInfo);
        return null;
    }

    @Override
    public Response processRecoverTransactions(TransactionInfo transactionInfo) throws Exception {
        transactionInfo.setTransactionId(getMultiplexTransactionId(transactionInfo.getTransactionId()));
        multiplexer.sendOutAll(this, transactionInfo);
        return null;
    }

    @Override
    public Response processForgetTransaction(TransactionInfo transactionInfo) throws Exception {
        transactionInfo.setTransactionId(getAndForgetMultiplexTransactionId(transactionInfo.getTransactionId()));
        multiplexer.sendOutAll(this, transactionInfo);
        return null;
    }

    @Override
    public Response processEndTransaction(TransactionInfo transactionInfo) throws Exception {
        transactionInfo.setTransactionId(getAndForgetMultiplexTransactionId(transactionInfo.getTransactionId()));
        multiplexer.sendOutAll(this, transactionInfo);
        return null;
    }

    @Override
    public Response processMessageDispatchNotification(MessageDispatchNotification messageDispatchNotification) throws Exception {
        multiplexer.sendOutAll(this, messageDispatchNotification);
        return null;
    }

    @Override
    public Response processProducerAck(ProducerAck producerAck) throws Exception {
        multiplexer.sendOutAll(this, producerAck);
        return null;
    }

    @Override
    public Response processMessageDispatch(MessageDispatch messageDispatch) throws Exception {
        multiplexer.sendOutAll(this, messageDispatch);
        return null;
    }

    @Override
    public Response processControlCommand(ControlCommand controlCommand) throws Exception {
        return null;
    }

    @Override
    public Response processConnectionError(ConnectionError connectionError) throws Exception {
        multiplexer.sendOutAll(this, connectionError);
        return null;
    }

    @Override
    public Response processConnectionControl(ConnectionControl connectionControl) throws Exception {
        multiplexer.sendOutAll(this, connectionControl);
        return null;
    }

    @Override
    public Response processConsumerControl(ConsumerControl consumerControl) throws Exception {
        multiplexer.sendOutAll(this, consumerControl);
        return null;
    }

    private TransactionId getMultiplexTransactionId(TransactionId originalId) {
        TransactionId result = originalId;
        if (originalId != null && originalId.isLocalTransaction()) {
            synchronized (transactionIdMap) {
                result = transactionIdMap.get(originalId);
                if (result == null) {
                    long multiplexerTransactionId = multiplexer.getNextTransactionId();
                    result = new LocalTransactionId(getMultiplexerConnectionId(), multiplexerTransactionId);
                    transactionIdMap.put(originalId, result);
                }
            }
        }
        return result;
    }

    private TransactionId getAndForgetMultiplexTransactionId(TransactionId originalId) {
        TransactionId result = originalId;
        if (originalId != null && originalId.isLocalTransaction()) {
            synchronized (transactionIdMap) {
                TransactionId value = transactionIdMap.remove(originalId);
                if (value != null) {
                    result = value;
                }
            }
        }
        return result;
    }

    private void storeConsumerId(ConsumerId original, ConsumerId multiplexer) {
        originalConsumerIdKeyMap.put(original, multiplexer);
        multiplexerConsumerIdKeyMap.put(multiplexer, original);
    }

    private ConsumerId removeByOriginal(ConsumerId original) {
        ConsumerId multiplexerId = originalConsumerIdKeyMap.get(original);
        if (multiplexerId != null) {
            multiplexerConsumerIdKeyMap.remove(multiplexerId);
        }
        return multiplexerId;
    }

    private void removeByMultiplexerId(ConsumerId multiplexerId) {
        ConsumerId originalId = multiplexerConsumerIdKeyMap.remove(multiplexerId);
        if (originalId != null) {
            originalConsumerIdKeyMap.remove(originalId);
        }
    }

    private ConsumerId getMultiplexConsumerId(ConsumerId original) {
        return originalConsumerIdKeyMap.get(original);
    }

    private ConsumerId getOriginalConsumerId(ConsumerId multiplex) {
        return multiplexerConsumerIdKeyMap.get(multiplex);
    }

    private void removeSession(SessionId multiplexerDefinedSessionId) {

        for (ConsumerId multiplexerConsumerId : multiplexerConsumerIdKeyMap.keySet()) {
            if (multiplexerConsumerId.getParentId().equals(multiplexerDefinedSessionId)) {
                removeConsumer(multiplexerConsumerId);
            }
        }
        for (Map.Entry<ProducerId, ProducerId> entry : producerIdMap.entrySet()) {
            if (entry.getValue().getParentId().equals(multiplexerDefinedSessionId)) {
                removeProducer(entry.getValue());
                producerIdMap.remove(entry.getKey());
            }
        }
        if (!multiplexerDefinedSessionId.equals(multiplexerSessionId)) {
            multiplexerConnectionStateRegister.removeSession(multiplexerDefinedSessionId);
            for (Map.Entry<SessionId, SessionId> entry : sessionIdMap.entrySet()) {
                if (entry.getValue().equals(multiplexerDefinedSessionId)) {
                    sessionIdMap.remove(entry.getKey());
                    break;
                }
            }
            RemoveInfo removeInfo = new RemoveInfo(multiplexerDefinedSessionId);
            removeInfo.setLastDeliveredSequenceId(0);
            multiplexer.sendOutAll(this, removeInfo);
        }
    }

    private void removeConsumer(ConsumerId multiplexerConsumerId) {
        if (multiplexerConsumerId != null) {
            removeByMultiplexerId(multiplexerConsumerId);
            if (multiplexerConnectionStateRegister.removeConsumer(multiplexerConsumerId) != null) {
                multiplexer.unregisterConsumer(multiplexerConsumerId);

                RemoveInfo removeInfo = new RemoveInfo(multiplexerConsumerId);
                removeInfo.setLastDeliveredSequenceId(0);
                multiplexer.sendOutAll(this, removeInfo);
            }
        }

    }

    private void removeProducer(ProducerId multiplexerProducerId) {

        if (multiplexerProducerId != null) {
            multiplexerConnectionStateRegister.removeProducer(multiplexerProducerId);
            RemoveInfo removeInfo = new RemoveInfo(multiplexerProducerId);
            multiplexer.sendOutAll(this, removeInfo);
        }
    }

    @Override
    public long getOutboundMessageCount() {
        return outboundMessageCount.get();
    }

    @Override
    public long getInboundMessageCount() {
        return inboundMessageCount.get();
    }

    @Override
    public String getUrl() {
        return input.getRemoteAddress();
    }

    @Override
    public String getProtocol() {
        return protocol;
    }

    @Override
    public List<DestinationStatisticsMBean> getDestinations() {
        return destinationRegister.getDestinations();
    }
}


text:
angular.module('app.routes', [])

.config(function($stateProvider, $urlRouterProvider) {

  // Ionic uses AngularUI Router which uses the concept of states
  // Learn more here: https://github.com/angular-ui/ui-router
  // Set up the various states which the app can be in.
  // Each state's controller can be found in controllers.js
  $stateProvider

  .state('menu.listanoticias', {
    cache: false,
    url: '/listanoticias/:categoria/:idCategoria/:idSubcategoria/:nombreSubcategoria/:fechaSubcategoria/:imagenSubcategoria/',
    views: {
      'side-menu21': {
        templateUrl: 'templates/listanoticias.html',
        controller: 'listaNoticiasCtrl'
      }
    }
  })

  .state('menu.detalle', {
    cache: false,
    url: '/detalle/:idNoticia',
    views: {
      'side-menu21': {
        templateUrl: 'templates/detalle.html',
        controller: 'detalleCtrl'
      }
    }
  })

  .state('menu.main', {
    cache: false,
    url: '/main',
    views: {
      'side-menu21': {
        templateUrl: 'templates/main.html',
        controller: 'mainCtrl'
      }
    }
  })

  .state('menu.subcategoria', {
    url: '/subcategoria/:idCategoria/:nombre/',
    views: {
      'side-menu21': {
        templateUrl: 'templates/subcategoria.html',
        controller: 'subcategoriaCtrl'
      }
    }
  })

  .state('menu', {
    url: '/menu',
    templateUrl: 'templates/menu.html',
    controller: 'menuCtrl'
  })

  .state('login', {
    url: '/login',
    templateUrl: 'templates/login.html',
    controller: 'loginCtrl'
  })

  .state('login-p2', {
    url: '/login-p2',
    templateUrl: 'templates/login-p2.html',
    controller: 'loginCtrl'
  })

$urlRouterProvider.otherwise('/menu/main')

});

redpajama_set_name: RedPajamaGithub


text:
package cz.zcu.kiv.mobile.logger;

import android.accounts.Account;
import android.accounts.AccountManager;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.app.LoaderManager.LoaderCallbacks;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.Loader;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.widget.SimpleCursorAdapter;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.ListView;
import cz.zcu.kiv.mobile.logger.data.database.ProfileTable;
import cz.zcu.kiv.mobile.logger.data.database.exceptions.DatabaseException;
import cz.zcu.kiv.mobile.logger.data.types.AsyncTaskResult;
import cz.zcu.kiv.mobile.logger.data.types.Profile;
import cz.zcu.kiv.mobile.logger.devices.DeviceListActivity;
import cz.zcu.kiv.mobile.logger.profiles.ProfileActivity;
import cz.zcu.kiv.mobile.logger.profiles.ProfileLoader;
import cz.zcu.kiv.mobile.logger.settings.SettingsActivity;
import cz.zcu.kiv.mobile.logger.sync.AuthenticatorService;
import cz.zcu.kiv.mobile.logger.utils.AndroidUtils;

public class MainActivity extends ListActivity implements LoaderCallbacks<AsyncTaskResult<Cursor>>{
  private static final String TAG = MainActivity.class.getSimpleName();

  private static final int LOADER_PROFILES = 1;

  private ProfileTable db;
  private SimpleCursorAdapter profileAdapter;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    db = Application.getInstance().getDatabase().getProfileTable();

    profileAdapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_1, null,
        new String[]{ProfileTable.COLUMN_PROFILE_NAME}, new int[]{android.R.id.text1}, 0);
    setListAdapter(profileAdapter);

    registerForContextMenu(getListView());

    getLoaderManager().initLoader(LOADER_PROFILES, null, this);
  }

  @Override
  protected void onListItemClick(ListView l, View v, int position, long id) {
    Log.d(TAG, "Profile selected: " + position);
    super.onListItemClick(l, v, position, id);

    Profile userProfile;
    try {
      userProfile = db.getProfile(id);
    }
    catch (DatabaseException e) {
      AndroidUtils.toast(this, R.string.profile_load_fail);
      Log.e(TAG, "failed to retrieve profile: ID=" + id);
      return;
    }

    Application.getInstance().setUserProfile(userProfile);

    startActivity(new Intent(this, DeviceListActivity.class));
  }

  @Override
  public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
  }

  @Override
  public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
    super.onCreateContextMenu(menu, v, menuInfo);
    getMenuInflater().inflate(R.menu.main_context, menu);
  }

  @Override
  public boolean onOptionsItemSelected(MenuItem item) {
    Log.d(TAG, "Menu item selected: " + item);
    switch (item.getItemId()) {
      case R.id.action_create_new_profile:
        createNewProfile(null);
        return true;

      case R.id.action_settings:
        startActivity(new Intent(this, SettingsActivity.class));
        return true;

      default:
        return super.onOptionsItemSelected(item);
    }
  }

  @Override
  public boolean onContextItemSelected(MenuItem item) {
    final long profileID = ((AdapterContextMenuInfo) item.getMenuInfo()).id;

    switch (item.getItemId()) {
      case R.id.context_delete:
        new AlertDialog.Builder(this)
          .setTitle(R.string.dialog_delete_profile_title)
          .setMessage(R.string.dialog_delete_profile_message)
          .setPositiveButton(R.string.dialog_delete_positive_button, new OnClickListener() {
              @Override
              public void onClick(DialogInterface dialog, int which) {
                removeProfile(profileID);
                dialog.dismiss();
              }
            })
          .setNegativeButton(R.string.dialog_cancel_button, new OnClickListener() {
              @Override
              public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
              }
            })
          .show();
        return true;

      case R.id.context_edit:
        Intent intent = new Intent(this, ProfileActivity.class);
        intent.putExtra(ProfileActivity.EXTRA_PROFILE_ID, profileID);
        startActivity(intent);
        return true;

      default:
        return super.onContextItemSelected(item);
    }
  }

  public void createNewProfile(View view){
    Log.d(TAG, "New profile creation requested.");
    startActivity(new Intent(this, ProfileActivity.class));
  }

  private void removeProfile(long profileID) {
    try {
      db.deleteProfile(profileID);
    }
    catch (DatabaseException e) {
      Log.e(TAG, "Failed to delete profile: id=" + profileID, e);
      AndroidUtils.toast(MainActivity.this, R.string.profile_delete_fail);
      return;
    }

    Account removeAccount = new Account(String.valueOf(profileID), AuthenticatorService.ACCOUNT_TYPE);
    AccountManager accountManager = (AccountManager) getSystemService(ACCOUNT_SERVICE);
    accountManager.removeAccount(removeAccount, null, null);
  }

  @Override
  public Loader<AsyncTaskResult<Cursor>> onCreateLoader(int id, Bundle args) {
    return new ProfileLoader(this);
  }

  @Override
  public void onLoadFinished(Loader<AsyncTaskResult<Cursor>> loader, AsyncTaskResult<Cursor> data) {
    if(loader.getId() == LOADER_PROFILES) {
      if(data.getError() != null) {
        AndroidUtils.toast(this, R.string.fail_load_profiles);
        Log.e(TAG, "Failed to load profiles.", data.getError());
      }
      else {
        profileAdapter.swapCursor(data.getResult());
      }
    }
  }

  @Override
  public void onLoaderReset(Loader<AsyncTaskResult<Cursor>> data) {
    profileAdapter.swapCursor(null);
  }
}


text:
import { EventEmitter } from 'events';

interface CacheOptions {
    timeout?: number | undefined;
    doesNotRenewTimeout?: boolean | undefined;
    timeoutDisabled?: boolean | undefined;
}

declare class Cache extends EventEmitter {
    keys: string[];
    length: number;

    constructor(options?: number | CacheOptions);

    set(key: string, value: any, timeout?: number): void;
    get(key: string): any;
    remove(key: string): void;
    clean(): void;
}

export = Cache;


text:
/* eslint-disable no-undef */

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

const LOGIN = 'LOGIN'
const LOGIN_SUCCESS = 'LOGIN_SUCCESS'
const LOGOUT = 'LOGOUT'

const state = {
  isLoggedIn: !!localStorage.getItem('token'),
  userId: localStorage.getItem('userId'),
  role: localStorage.getItem('role')
}

const mutations = {
  [LOGIN] (state) {
    state.pending = true
  },
  [LOGIN_SUCCESS] (state, payload) {
    state.isLoggedIn = true
    state.pending = false
  },
  [LOGOUT] (state) {
    state.isLoggedIn = false
  }
}

const actions = {
  login ({ commit }, creds) {
    commit(LOGIN)
    return new Promise(resolve => {
      setTimeout(() => {
        localStorage.setItem('token', 'JWT')
        localStorage.setItem('userId', creds.userId)
        localStorage.setItem('role', creds.role)
        commit(LOGIN_SUCCESS)
        resolve()
      }, 1000)
    })
  },
  logout ({ commit }) {
    localStorage.removeItem('token')
    commit(LOGOUT)
  }
}

const getters = {
  isLoggedIn: state => {
    return state.isLoggedIn
  },
  userId: state => {
    return state.userId
  },
  role: state => {
    return state.role
  }
}

export default new Vuex.Store({
  state,
  mutations,
  actions,
  getters
})


text:
#include "config.h"
#include "ValidationMessage.h"

#include "CSSPropertyNames.h"
#include "CSSStyleSelector.h"
#include "CSSValueKeywords.h"
#include "FormAssociatedElement.h"
#include "HTMLBRElement.h"
#include "HTMLNames.h"
#include "Page.h"
#include "RenderObject.h"
#include "Settings.h"
#include "ShadowRoot.h"
#include "Text.h"
#include <wtf/PassOwnPtr.h>

namespace WebCore {

using namespace HTMLNames;

ALWAYS_INLINE ValidationMessage::ValidationMessage(FormAssociatedElement* element)
    : m_element(element)
{
}

ValidationMessage::~ValidationMessage()
{
    deleteBubbleTree();
}

PassOwnPtr<ValidationMessage> ValidationMessage::create(FormAssociatedElement* element)
{
    return adoptPtr(new ValidationMessage(element));
}

void ValidationMessage::setMessage(const String& message)
{
    // Don't modify the DOM tree in this context.
    // If so, an assertion in Node::isFocusable() fails.
    ASSERT(!message.isEmpty());
    m_message = message;
    if (!m_bubble)
        m_timer.set(new Timer<ValidationMessage>(this, &ValidationMessage::buildBubbleTree));
    else
        m_timer.set(new Timer<ValidationMessage>(this, &ValidationMessage::setMessageDOMAndStartTimer));
    m_timer->startOneShot(0);
}

void ValidationMessage::setMessageDOMAndStartTimer(Timer<ValidationMessage>*)
{
    ASSERT(m_bubbleMessage);
    m_bubbleMessage->removeAllChildren();
    Vector<String> lines;
    m_message.split('\n', lines);
    Document* doc = m_bubbleMessage->document();
    ExceptionCode ec = 0;
    for (unsigned i = 0; i < lines.size(); ++i) {
        if (i) {
            m_bubbleMessage->appendChild(HTMLBRElement::create(doc), ec);
            m_bubbleMessage->appendChild(Text::create(doc, lines[i]), ec);
        } else {
            RefPtr<HTMLElement> bold = HTMLElement::create(bTag, doc);
            bold->setInnerText(lines[i], ec);
            m_bubbleMessage->appendChild(bold.release(), ec);
        }
    }

    int magnification = doc->page() ? doc->page()->settings()->validationMessageTimerMaginification() : -1;
    if (magnification <= 0)
        m_timer.clear();
    else {
        m_timer.set(new Timer<ValidationMessage>(this, &ValidationMessage::deleteBubbleTree));
        m_timer->startOneShot(max(5.0, static_cast<double>(m_message.length()) * magnification / 1000));
    }
}

class ElementWithPseudoId : public HTMLElement {
public:
    static PassRefPtr<HTMLElement> create(Document* doc, const AtomicString& pseudoName)
    {
        return adoptRef(new ElementWithPseudoId(doc, pseudoName));
    }

protected:
    ElementWithPseudoId(Document* doc, const AtomicString& pseudoName)
        : HTMLElement(divTag, doc)
        , m_pseudoName(pseudoName) { };
    virtual const AtomicString& shadowPseudoId() const { return m_pseudoName; }

private:
    AtomicString m_pseudoName;
};

void ValidationMessage::buildBubbleTree(Timer<ValidationMessage>*)
{
    HTMLElement* host = toHTMLElement(m_element);
    Document* doc = host->document();
    m_bubble = ElementWithPseudoId::create(doc, "-webkit-validation-bubble");
    // Need to force position:absolute because RenderMenuList doesn't assume it
    // contains non-absolute or non-fixed renderers as children.
    m_bubble->getInlineStyleDecl()->setProperty(CSSPropertyPosition, CSSValueAbsolute);
    ExceptionCode ec = 0;
    host->ensureShadowRoot()->appendChild(m_bubble.get(), ec);

    RefPtr<HTMLElement> clipper = ElementWithPseudoId::create(doc, "-webkit-validation-bubble-arrow-clipper");
    clipper->appendChild(ElementWithPseudoId::create(doc, "-webkit-validation-bubble-arrow"), ec);
    m_bubble->appendChild(clipper.release(), ec);
    m_bubbleMessage = ElementWithPseudoId::create(doc, "-webkit-validation-bubble-message");
    m_bubble->appendChild(m_bubbleMessage, ec);

    setMessageDOMAndStartTimer();

    // FIXME: Use transition to show the bubble.

    // We don't need to adjust the bubble location. The default position is enough.
}

void ValidationMessage::requestToHideMessage()
{
    // We must not modify the DOM tree in this context by the same reason as setMessage().
    m_timer.set(new Timer<ValidationMessage>(this, &ValidationMessage::deleteBubbleTree));
    m_timer->startOneShot(0);
}

void ValidationMessage::deleteBubbleTree(Timer<ValidationMessage>*)
{
    if (m_bubble) {
        m_bubbleMessage = 0;
        HTMLElement* host = toHTMLElement(m_element);
        ExceptionCode ec;
        host->shadowRoot()->removeChild(m_bubble.get(), ec);
        m_bubble = 0;
    }
    m_message = String();
}

} // namespace WebCore


text:
package v2

import (
	"os"

	"code.cloudfoundry.org/cli/cf/cmd"
	"code.cloudfoundry.org/cli/command"
)

type MarketplaceCommand struct {
	ServicePlanInfo string      `short:"s" description:"Show plan details for a particular service offering"`
	usage           interface{} `usage:"CF_NAME marketplace [-s SERVICE]"`
	relatedCommands interface{} `related_commands:"create-service, services"`
}

func (_ MarketplaceCommand) Setup(config command.Config, ui command.UI) error {
	return nil
}

func (_ MarketplaceCommand) Execute(args []string) error {
	cmd.Main(os.Getenv("CF_TRACE"), os.Args)
	return nil
}


text:
package com.wci.umls.server.jpa.lists;

import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;

import com.wci.umls.server.helpers.ProxyTester;
import com.wci.umls.server.helpers.meta.AttributeNameList;
import com.wci.umls.server.jpa.helpers.meta.AttributeNameListJpa;
import com.wci.umls.server.jpa.meta.AttributeNameJpa;
import com.wci.umls.server.model.meta.AttributeName;

/**
 * Unit testing for {@link AttributeNameList}.
 */
public class AttributeNameListUnitTest extends AbstractListUnit<AttributeName> {

  /** The list1 test fixture . */
  private AttributeNameList list1;

  /** The list2 test fixture . */
  private AttributeNameList list2;

  /** The test fixture o1. */
  private AttributeName o1;

  /** The test fixture o2. */
  private AttributeName o2;

  /**
   * Setup class.
   */
  @BeforeClass
  public static void setupClass() {
    // do nothing
  }

  /**
   * Setup.
   *
   * @throws Exception the exception
   */
  @Before
  public void setup() throws Exception {
    list1 = new AttributeNameListJpa();
    list2 = new AttributeNameListJpa();

    ProxyTester tester = new ProxyTester(new AttributeNameJpa());
    o1 = (AttributeName) tester.createObject(1);
    o2 = (AttributeName) tester.createObject(2);

  }

  /**
   * Test normal use of a list.
   * @throws Exception the exception
   */
  @Test
  public void testNormalUse() throws Exception {
    testNormalUse(list1, list2, o1, o2);
  }

  /**
   * Test degenerate use of a list. Show that the underlying data structure
   * should NOT be manipulated.
   *
   * @throws Exception the exception
   */
  @Test
  public void testDegenerateUse() throws Exception {
    testDegenerateUse(list1, list2, o1, o2);
  }

  /**
   * Test edge cases of a list.
   *
   * @throws Exception the exception
   */
  @Test
  public void testEdgeCases() throws Exception {
    testEdgeCases(list1, list2, o1, o2);
  }

  /**
   * Test XML serialization of a list.
   *
   *
   * @throws Exception the exception
   */
  @Test
  public void testXmlSerialization() throws Exception {
    testXmllSerialization(list1, list2, o1, o2);
  }

  /**
   * Teardown.
   */
  @After
  public void teardown() {
    // do nothing
  }

  /**
   * Teardown class.
   */
  @AfterClass
  public static void teardownClass() {
    // do nothing
  }

}


text:
@interface HCNewFeatureViewController : UIViewController

@end


text:
.class public Lfj;
.super Ljava/lang/Object;
.source "SourceFile"

# interfaces
.implements Ljava/lang/Runnable;

# instance fields
.field final synthetic a:Lcom/tndev/billing/util/IabHelper;

.field private final synthetic b:Z

.field private final synthetic c:Ljava/util/List;

.field private final synthetic d:Landroid/os/Handler;

.field private final synthetic e:Lcom/tndev/billing/util/IabHelper$QueryInventoryFinishedListener;

# direct methods
.method public constructor <init>(Lcom/tndev/billing/util/IabHelper;ZLjava/util/List;Landroid/os/Handler;Lcom/tndev/billing/util/IabHelper$QueryInventoryFinishedListener;)V
    .registers 6
    .parameter
    .parameter
    .parameter
    .parameter
    .parameter

    .prologue
    .line 1
    iput-object p1, p0, Lfj;->a:Lcom/tndev/billing/util/IabHelper;

    iput-boolean p2, p0, Lfj;->b:Z

    iput-object p3, p0, Lfj;->c:Ljava/util/List;

    iput-object p4, p0, Lfj;->d:Landroid/os/Handler;

    iput-object p5, p0, Lfj;->e:Lcom/tndev/billing/util/IabHelper$QueryInventoryFinishedListener;

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

    return-void
.end method

# virtual methods
.method public run()V
    .registers 6

    .prologue
    .line 550
    new-instance v1, Lcom/tndev/billing/util/IabResult;

    const/4 v0, 0x0

    const-string v2, "Inventory refresh successful."

    invoke-direct {v1, v0, v2}, Lcom/tndev/billing/util/IabResult;-><init>(ILjava/lang/String;)V

    .line 551
    const/4 v0, 0x0

    .line 553
    :try_start_9
    iget-object v2, p0, Lfj;->a:Lcom/tndev/billing/util/IabHelper;

    iget-boolean v3, p0, Lfj;->b:Z

    iget-object v4, p0, Lfj;->c:Ljava/util/List;

    invoke-virtual {v2, v3, v4}, Lcom/tndev/billing/util/IabHelper;->queryInventory(ZLjava/util/List;)Lcom/tndev/billing/util/Inventory;
    :try_end_12
    .catch Lcom/tndev/billing/util/IabException; {:try_start_9 .. :try_end_12} :catch_25

    move-result-object v0

    .line 559
    :goto_13
    iget-object v2, p0, Lfj;->a:Lcom/tndev/billing/util/IabHelper;

    invoke-virtual {v2}, Lcom/tndev/billing/util/IabHelper;->a()V

    .line 563
    iget-object v2, p0, Lfj;->d:Landroid/os/Handler;

    new-instance v3, Lfk;

    iget-object v4, p0, Lfj;->e:Lcom/tndev/billing/util/IabHelper$QueryInventoryFinishedListener;

    invoke-direct {v3, p0, v4, v1, v0}, Lfk;-><init>(Lfj;Lcom/tndev/billing/util/IabHelper$QueryInventoryFinishedListener;Lcom/tndev/billing/util/IabResult;Lcom/tndev/billing/util/Inventory;)V

    invoke-virtual {v2, v3}, Landroid/os/Handler;->post(Ljava/lang/Runnable;)Z

    .line 568
    return-void

    .line 555
    :catch_25
    move-exception v1

    .line 556
    invoke-virtual {v1}, Lcom/tndev/billing/util/IabException;->getResult()Lcom/tndev/billing/util/IabResult;

    move-result-object v1

    goto :goto_13
.end method


text:
#ifndef ARM_DEVICE_2019_H
#define ARM_DEVICE_2019_H

#include "../../../common/pwm/servo/servoList.h"

#include "../../../device/device.h"

/**
 * The descriptor for the Arm 2019 device.
 */
DeviceDescriptor* getArm2019DeviceDescriptor(ServoList* servoList);

#endif


text:
This example shows how to add other droplets that are not provisioned by this module to the Swarm cluster using output values.

## Running it

You can try out this example by providing a digitalocean access token and running `terraform apply`. Note that you may need to run `terraform init` first.


text:
package betterwithaddons.interaction.jei.wrapper;

import betterwithaddons.crafting.recipes.SpindleRecipe;
import mezz.jei.api.ingredients.IIngredients;
import mezz.jei.api.recipe.BlankRecipeWrapper;
import net.minecraft.item.ItemStack;

import java.util.List;

/**
 * Created by primetoxinz on 6/29/17.
 */
public class SpindleRecipeWrapper extends BlankRecipeWrapper {
    private SpindleRecipe recipe;

    public SpindleRecipeWrapper(SpindleRecipe recipe) {
        this.recipe = recipe;
    }

    @Override
    public void getIngredients(IIngredients ingredients) {
        ingredients.setInput(ItemStack.class,getInputs());
        ingredients.setOutput(ItemStack.class,getOutputs());
    }

    public List<ItemStack> getInputs() {
        return recipe.getRecipeInputs();
    }

    public List<ItemStack> getOutputs() {
        return recipe.getOutput();
    }
}


text:
package org.apache.uima.lucas.indexer.analysis;

import java.io.IOException;
import java.util.Properties;

import org.apache.lucene.analysis.LowerCaseFilter;
import org.apache.lucene.analysis.TokenFilter;
import org.apache.lucene.analysis.TokenStream;

public class LowerCaseFilterFactory implements TokenFilterFactory {

  public TokenFilter createTokenFilter(TokenStream tokenStream, Properties properties)
          throws IOException {

    return new LowerCaseFilter(tokenStream);
  }

  public void preloadResources(Properties properties) throws IOException {

  }

}


text:
package com.google.android.exoplayer2.text.webvtt;

import android.text.SpannableStringBuilder;
import com.google.android.exoplayer2.C;
import com.google.android.exoplayer2.text.Cue;
import com.google.android.exoplayer2.text.Subtitle;
import com.google.android.exoplayer2.util.Assertions;
import com.google.android.exoplayer2.util.Util;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

/**
 * A representation of a WebVTT subtitle.
 */
/* package */ final class WebvttSubtitle implements Subtitle {

  private final List<WebvttCue> cues;
  private final int numCues;
  private final long[] cueTimesUs;
  private final long[] sortedCueTimesUs;

  /**
   * @param cues A list of the cues in this subtitle.
   */
  public WebvttSubtitle(List<WebvttCue> cues) {
    this.cues = cues;
    numCues = cues.size();
    cueTimesUs = new long[2 * numCues];
    for (int cueIndex = 0; cueIndex < numCues; cueIndex++) {
      WebvttCue cue = cues.get(cueIndex);
      int arrayIndex = cueIndex * 2;
      cueTimesUs[arrayIndex] = cue.startTime;
      cueTimesUs[arrayIndex + 1] = cue.endTime;
    }
    sortedCueTimesUs = Arrays.copyOf(cueTimesUs, cueTimesUs.length);
    Arrays.sort(sortedCueTimesUs);
  }

  @Override
  public int getNextEventTimeIndex(long timeUs) {
    int index = Util.binarySearchCeil(sortedCueTimesUs, timeUs, false, false);
    return index < sortedCueTimesUs.length ? index : C.INDEX_UNSET;
  }

  @Override
  public int getEventTimeCount() {
    return sortedCueTimesUs.length;
  }

  @Override
  public long getEventTime(int index) {
    Assertions.checkArgument(index >= 0);
    Assertions.checkArgument(index < sortedCueTimesUs.length);
    return sortedCueTimesUs[index];
  }

  @Override
  public List<Cue> getCues(long timeUs) {
    ArrayList<Cue> list = null;
    WebvttCue firstNormalCue = null;
    SpannableStringBuilder normalCueTextBuilder = null;

    for (int i = 0; i < numCues; i++) {
      if ((cueTimesUs[i * 2] <= timeUs) && (timeUs < cueTimesUs[i * 2 + 1])) {
        if (list == null) {
          list = new ArrayList<>();
        }
        WebvttCue cue = cues.get(i);
        if (cue.isNormalCue()) {
          // we want to merge all of the normal cues into a single cue to ensure they are drawn
          // correctly (i.e. don't overlap) and to emulate roll-up, but only if there are multiple
          // normal cues, otherwise we can just append the single normal cue
          if (firstNormalCue == null) {
            firstNormalCue = cue;
          } else if (normalCueTextBuilder == null) {
            normalCueTextBuilder = new SpannableStringBuilder();
            normalCueTextBuilder.append(firstNormalCue.text).append("\n").append(cue.text);
          } else {
            normalCueTextBuilder.append("\n").append(cue.text);
          }
        } else {
          list.add(cue);
        }
      }
    }
    if (normalCueTextBuilder != null) {
      // there were multiple normal cues, so create a new cue with all of the text
      list.add(new WebvttCue(normalCueTextBuilder));
    } else if (firstNormalCue != null) {
      // there was only a single normal cue, so just add it to the list
      list.add(firstNormalCue);
    }

    if (list != null) {
      return list;
    } else {
      return Collections.emptyList();
    }
  }

}


text:
"""Support for Baidu speech service."""
import logging

import voluptuous as vol

from homeassistant.components.tts import CONF_LANG, PLATFORM_SCHEMA, Provider
from homeassistant.const import CONF_API_KEY
import homeassistant.helpers.config_validation as cv

_LOGGER = logging.getLogger(__name__)

SUPPORTED_LANGUAGES = ["zh"]
DEFAULT_LANG = "zh"

CONF_APP_ID = "app_id"
CONF_SECRET_KEY = "secret_key"
CONF_SPEED = "speed"
CONF_PITCH = "pitch"
CONF_VOLUME = "volume"
CONF_PERSON = "person"

PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
    {
        vol.Optional(CONF_LANG, default=DEFAULT_LANG): vol.In(SUPPORTED_LANGUAGES),
        vol.Required(CONF_APP_ID): cv.string,
        vol.Required(CONF_API_KEY): cv.string,
        vol.Required(CONF_SECRET_KEY): cv.string,
        vol.Optional(CONF_SPEED, default=5): vol.All(
            vol.Coerce(int), vol.Range(min=0, max=9)
        ),
        vol.Optional(CONF_PITCH, default=5): vol.All(
            vol.Coerce(int), vol.Range(min=0, max=9)
        ),
        vol.Optional(CONF_VOLUME, default=5): vol.All(
            vol.Coerce(int), vol.Range(min=0, max=15)
        ),
        vol.Optional(CONF_PERSON, default=0): vol.All(
            vol.Coerce(int), vol.Range(min=0, max=4)
        ),
    }
)

# Keys are options in the config file, and Values are options
# required by Baidu TTS API.
_OPTIONS = {
    CONF_PERSON: "per",
    CONF_PITCH: "pit",
    CONF_SPEED: "spd",
    CONF_VOLUME: "vol",
}
SUPPORTED_OPTIONS = [CONF_PERSON, CONF_PITCH, CONF_SPEED, CONF_VOLUME]

def get_engine(hass, config):
    """Set up Baidu TTS component."""
    return BaiduTTSProvider(hass, config)

class BaiduTTSProvider(Provider):
    """Baidu TTS speech api provider."""

    def __init__(self, hass, conf):
        """Init Baidu TTS service."""
        self.hass = hass
        self._lang = conf.get(CONF_LANG)
        self._codec = "mp3"
        self.name = "BaiduTTS"

        self._app_data = {
            "appid": conf.get(CONF_APP_ID),
            "apikey": conf.get(CONF_API_KEY),
            "secretkey": conf.get(CONF_SECRET_KEY),
        }

        self._speech_conf_data = {
            _OPTIONS[CONF_PERSON]: conf.get(CONF_PERSON),
            _OPTIONS[CONF_PITCH]: conf.get(CONF_PITCH),
            _OPTIONS[CONF_SPEED]: conf.get(CONF_SPEED),
            _OPTIONS[CONF_VOLUME]: conf.get(CONF_VOLUME),
        }

    @property
    def default_language(self):
        """Return the default language."""
        return self._lang

    @property
    def supported_languages(self):
        """Return a list of supported languages."""
        return SUPPORTED_LANGUAGES

    @property
    def default_options(self):
        """Return a dict including default options."""
        return {
            CONF_PERSON: self._speech_conf_data[_OPTIONS[CONF_PERSON]],
            CONF_PITCH: self._speech_conf_data[_OPTIONS[CONF_PITCH]],
            CONF_SPEED: self._speech_conf_data[_OPTIONS[CONF_SPEED]],
            CONF_VOLUME: self._speech_conf_data[_OPTIONS[CONF_VOLUME]],
        }

    @property
    def supported_options(self):
        """Return a list of supported options."""
        return SUPPORTED_OPTIONS

    def get_tts_audio(self, message, language, options=None):
        """Load TTS from BaiduTTS."""
        from aip import AipSpeech

        aip_speech = AipSpeech(
            self._app_data["appid"],
            self._app_data["apikey"],
            self._app_data["secretkey"],
        )

        if options is None:
            result = aip_speech.synthesis(message, language, 1, self._speech_conf_data)
        else:
            speech_data = self._speech_conf_data.copy()
            for key, value in options.items():
                speech_data[_OPTIONS[key]] = value

            result = aip_speech.synthesis(message, language, 1, speech_data)

        if isinstance(result, dict):
            _LOGGER.error(
                "Baidu TTS error-- err_no:%d; err_msg:%s; err_detail:%s",
                result["err_no"],
                result["err_msg"],
                result["err_detail"],
            )
            return None, None

        return self._codec, result


text: J2OBJC_INTERFACE_TYPE_LITERAL_SOURCE(ImActorModelHttpFileUploadCallback)


text:
import { env, ProgressLocation, version as codeVersion, window } from "vscode";
import { RequestError, ServerErrorNotification, ServerStatusNotification } from "../../shared/analysis_server_types";
import { LogCategory } from "../../shared/enums";
import { Logger } from "../../shared/interfaces";
import { PromiseCompleter } from "../../shared/utils";
import { extensionVersion } from "../../shared/vscode/extension_utils";
import { WorkspaceContext } from "../../shared/workspace";
import { Analytics } from "../analytics";
import { config } from "../config";
import { openLogContents } from "../utils";
import { DasAnalyzerClient } from "./analyzer_das";

const maxErrorReportCount = 3;
const sendFakeErrorAtStartup = false;

let errorCount = 0;

export class AnalyzerStatusReporter {
	private analysisInProgress = false;
	private analyzingPromise?: PromiseCompleter<void>;

	constructor(private readonly logger: Logger, private readonly analyzer: DasAnalyzerClient, private readonly workspaceContext: WorkspaceContext, private readonly analytics: Analytics) {
		// TODO: Should these go in disposables?
		// If so, do we need to worry about server cleaning them up if it disposes first?
		analyzer.registerForServerStatus((n) => this.handleServerStatus(n));
		analyzer.registerForServerError((e: ServerErrorNotification) => this.handleServerError(e));
		analyzer.registerForRequestError((e: RequestError) => this.handleRequestError(e));
		analyzer.registerForServerTerminated(() => this.handleServerTerminated());

		if (sendFakeErrorAtStartup) {
			setTimeout(() => {
				this.handleServerError(
					{
						isFatal: false,
						message: "This is a fake error for testing the error reporting!",
						stackTrace: new Error().stack || "",
					},
					"testError",
				);
			}, 5000);
		}
	}

	private handleServerStatus(status: ServerStatusNotification) {
		if (!status.analysis)
			return;

		this.analysisInProgress = status.analysis.isAnalyzing;

		if (this.analysisInProgress) {
			// Debounce short analysis times.
			setTimeout(() => {
				// When the timeout fires, we need to check analysisInProgress again in case
				// analysis has already finished.
				if (this.analysisInProgress && !this.analyzingPromise) {
					window.withProgress({ location: ProgressLocation.Window, title: "Analyzing…" }, () => {
						if (!this.analyzingPromise) // Re-check, since we don't know how long before this callback is called.
							this.analyzingPromise = new PromiseCompleter();
						return this.analyzingPromise.promise;
					});
				}
			}, 500);
		} else {
			if (this.analyzingPromise) {
				this.analyzingPromise.resolve();
				this.analyzingPromise = undefined;
			}
		}
	}

	private handleServerTerminated() {
		this.analysisInProgress = false;
		if (this.analyzingPromise) {
			this.analyzingPromise.resolve();
			this.analyzingPromise = undefined;
		}
	}

	private handleRequestError(error: RequestError & { method?: string }) {
		// Map this request error to a server error to reuse the shared code.
		this.handleServerError(
			{
				isFatal: false,
				message: error.message,
				stackTrace: error.stackTrace || "",
			},
			error.method,
		);
	}

	private handleServerError(error: ServerErrorNotification, method?: string) {
		// Always log to the console.
		this.logger.error(error.message, LogCategory.Analyzer);
		if (error.stackTrace)
			this.logger.error(error.stackTrace, LogCategory.Analyzer);

		this.analytics.logError(`Analyzer server error${method ? ` (${method})` : ""}`, error.isFatal);

		errorCount++;

		// Offer to report the error.
		if (config.notifyAnalyzerErrors && errorCount <= maxErrorReportCount) {
			const showLog: string = "Show log";
			window.showErrorMessage(`Exception from the Dart analysis server: ${error.message}`, showLog).then((res) => {
				if (res === showLog)
					this.showErrorLog(error, method);
			});
		}
	}

	private showErrorLog(error: ServerErrorNotification, method?: string) {
		const sdkVersion = this.workspaceContext.sdks.dartVersion;
		const flutterSdkVersion = this.workspaceContext.sdks.flutterVersion;

		const analyzerArgs = this.analyzer.getAnalyzerLaunchArgs();

		const data = `
${method ? "### Request\n\nServer was responding to request: `" + method + "`\n" : ""}
### Versions

- ${env.appName} v${codeVersion}
- Dart Code v${extensionVersion}
- ${flutterSdkVersion ? `Flutter SDK v${flutterSdkVersion}` : `Dart SDK v${sdkVersion}`}

### Analyzer Info

The analyzer was launched using the arguments:

${analyzerArgs.map((a) => `- ${a}`).join("\n")}

### Exception${error.isFatal ? " (fatal)" : ""}

${error.message}

${error.stackTrace.trim()}
`;

		openLogContents("md", data);
	}
}


text:
class Users::RegistrationsController < Devise::RegistrationsController
  before_filter :configure_permitted_parameters

  protected

  def configure_permitted_parameters
    devise_parameter_sanitizer.for(:sign_up).push(:username)
    devise_parameter_sanitizer.for(:account_update).push(:username, :current_password, :age, :bio, :gender)
  end
end


text:
package com.cinchapi.concourse.plugin.http;

/**
 * Defines all the actions that can be taken on a response generated by an
 * {@link HttpPlugin}.
 *
 * @author Jeff Nelson
 */
public interface HttpResponse {

    public String body();

    /**
     * Sets the body
     */
    public void body(String body);

    /**
     * Adds not persistent cookie to the response.
     * Can be invoked multiple times to insert more than one cookie.
     *
     * @param name name of the cookie
     * @param value value of the cookie
     */
    public void cookie(String name, String value);

    /**
     * Adds cookie to the response. Can be invoked multiple times to insert more
     * than one cookie.
     *
     * @param name name of the cookie
     * @param value value of the cookie
     * @param maxAge max age of the cookie in seconds (negative for the not
     *            persistent cookie,
     *            zero - deletes the cookie)
     */
    public void cookie(String name, String value, int maxAge);

    /**
     * Adds cookie to the response. Can be invoked multiple times to insert more
     * than one cookie.
     *
     * @param name name of the cookie
     * @param value value of the cookie
     * @param maxAge max age of the cookie in seconds (negative for the not
     *            persistent cookie, zero - deletes the cookie)
     * @param secured if true : cookie will be secured
     *            zero - deletes the cookie)
     */
    public void cookie(String name, String value, int maxAge, boolean secured);

    /**
     * Adds cookie to the response. Can be invoked multiple times to insert more
     * than one cookie.
     *
     * @param path path of the cookie
     * @param name name of the cookie
     * @param value value of the cookie
     * @param maxAge max age of the cookie in seconds (negative for the not
     *            persistent cookie, zero - deletes the cookie)
     * @param secured if true : cookie will be secured
     *            zero - deletes the cookie)
     */
    public void cookie(String path, String name, String value, int maxAge,
            boolean secured);

    /**
     * Adds/Sets a response header
     */
    public void header(String header, String value);

    /**
     * Trigger a browser redirect
     *
     * @param location Where to redirect
     */
    public void redirect(String location);

    /**
     * Trigger a browser redirect with specific http 3XX status code.
     *
     * @param location Where to redirect permanently
     * @param httpStatusCode the http status code
     */
    public void redirect(String location, int httpStatusCode);

    /**
     * Removes the cookie.
     *
     * @param name name of the cookie
     */
    public void removeCookie(String name);

    /**
     * Sets the status code for the response
     */
    public void status(int statusCode);

    /**
     * Sets the content type for the response
     */
    public void type(String contentType);

}


text:
Redesign Project of Frannie's in Hayward, created by Ryan Vu, David Papa, Oscar Gomez, and Rhea Erice.
Photos on landing page in slideshow taken by Ryan, all other photos used from Yelp, stockphotos.
Reviews of Frannie's taken from Yelp.

Index.html brings you to the landing page.
Menu.html brings you to the menu page.
OrderOnline.html brings you to the ordering online page.
All files in the menus folder will bring you to it's respective food.
img folder has the pictures used on the website.

In order to obtain the latest version of this project, clone this project to your GitHub Desktop.
Contact any of the members of this group at the following:
    Ryan Vu rvu@horizon.csueastbay.edu
    Rhea Erice rerice@horizon.csueastbay.edu
    David Papa dapapa1025@hotmail.com
    Oscar Gomez ogomez2@horizon.csueastbay.edu


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

#nullable disable

namespace Microsoft.CodeAnalysis.Operations
{
    /// <summary>
    /// Kinds of arguments.
    /// </summary>
    public enum ArgumentKind
    {
        /// <summary>
        /// Represents unknown argument kind.
        /// </summary>
        None = 0x0,

        /// <summary>
        /// Argument value is explicitly supplied.
        /// </summary>
        Explicit = 0x1,

        /// <summary>
        /// Argument is a param array created by compilers for the matching C# params or VB ParamArray parameter.
        /// Note, the value is a an array creation expression that encapsulates all the elements, if any.
        /// </summary>
        ParamArray = 0x2,

        /// <summary>
        /// Argument is a default value supplied automatically by the compilers.
        /// </summary>
        DefaultValue = 0x3
    }
}


text:
package thingynet.workflow;

import org.jongo.MongoCollection;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import thingynet.Application;
import thingynet.workflow.commands.WorkflowLatency;
import thingynet.workflow.commands.WorkflowLatencyCommand;

import static java.lang.System.currentTimeMillis;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.notNullValue;

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = Application.class)
public class WorkflowLatencyTest {
    private static final long EXPECTED_LATENCY = 1000l;

    @Autowired
    private MongoCollection workflowLogCollection;

    @Autowired
    private WorkflowLatencyCommand command;

    @Before
    public void before() {
        workflowLogCollection.remove();
    }

    @Test
    public void excuteShouldRecordCorrectLatency() throws WorkflowException {
        long count = workflowLogCollection.count();
        assertThat(count, is(0l));

        Workflow workflow = new Workflow(null, null, null, currentTimeMillis(), null);
        workflow.setUpdated(workflow.getStart() + EXPECTED_LATENCY);

        command.execute(workflow);

        Iterable<WorkflowLatency> loads = workflowLogCollection.find().as(WorkflowLatency.class);
        assertThat(loads, notNullValue());
        WorkflowLatency workflowLatency = loads.iterator().next();
        assertThat(workflowLatency, notNullValue());
        assertThat(workflowLatency.getLatency(), is(EXPECTED_LATENCY));
    }

}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">

    <title>Sponsors</title>

    <link href="vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">

    <link href="css/clean-blog.min.css" rel="stylesheet">

    <link href="vendor/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">
    <link href='https://fonts.googleapis.com/css?family=Lora:400,700,400italic,700italic' rel='stylesheet' type='text/css'>
    <link href='https://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800' rel='stylesheet' type='text/css'>

    <link rel="icon" type="image/png" href="/img/brand.png" />

                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                    Toggle navigation
                    Menu
                </button>

                 20th October 2017

                        Home

                        News

                        Venue & Registration

                        CFP

                        Program

                        CTF

                        Sponsors

 Call for Sponsors

				  BSides Luxembourg is looking for sponsors. We would like to
				  provide participants with a great experience and at the same
				  time not to potentially exclude great people by setting the
				  entrance fee at a level which covers the real costs of the event.

				  If you can sponsor our community building initiative, please
				  contact any of the organizers, @BSidesLux
				  or info@bsideslux.lu !

				  Please find the Sponsor Kit document with the details
				  here.

Gold Sponsors

Silver Sponsors

Bronze Sponsors

Capture the Flag Sponsor and Organizer

Copyright © BSides Luxembourg 2017


text:
package ru.job4j.threads;

/**
 * Class Time.
 *
 * @author Ponkin Aleksey
 * @version 1.0.0
 * @since 21.12.2017.
 */
public class Time implements Runnable {
    /**
     * Thread for control.
     */
    private Thread thread;
    /**
     * Maximum execution time.
     */
    private long timeMax;

    /**
     * Constructor class Time.
     * @param runnable class which realise interface Runnable.
     * @param timeMax maximum execution time.
     */
    public Time(Runnable runnable, long timeMax) {
        this.thread = new Thread(runnable);
        this.timeMax = timeMax;
    }

    @Override
    public void run() {
        long stastTime = System.currentTimeMillis();
        thread.start();
        long finishTime = System.currentTimeMillis() - stastTime;
        while (finishTime <= this.timeMax) {
            finishTime = System.currentTimeMillis() - stastTime;
        }
        this.thread.interrupt();
        try {
            thread.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        String text = "Test  simple   text where 25 char";
        Thread threadTemer = new Thread(new Time(new CountChar(text), 10));
        System.out.println("Program to counting the char.");
        threadTemer.start();
        try {
            threadTemer.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("End program.");
        System.out.println("===================================");

        System.out.println();
        System.out.println("Program to counting the char.");
        threadTemer = new Thread(new Time(new CountChar(text), 100));
        threadTemer.start();
        try {
            threadTemer.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("End program.");
        System.out.println("===================================");
    }
}


text:
#!/usr/bin/perl
package Quark::Namespace;
use v5.10;

########################################################################
# Copyright 2014 RCF                                                   #
#                                                                      #
# Licensed under the Apache License, Version 2.0 (the "License");      #
# you may not use this file except in compliance with the License.     #
# You may obtain a copy of the License at                              #
#                                                                      #
#     http://www.apache.org/licenses/LICENSE-2.0                       #
#                                                                      #
# Unless required by applicable law or agreed to in writing,           #
# software distributed under the License is distributed on an          #
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,         #
# either express or implied.                                           #
# See the License for the specific language governing permissions      #
# and limitations under the License.                                   #
########################################################################

# Pragmas
use strict;
use warnings;

use Exporter 'import'; # gives you Exporter's import() method directly
our @EXPORT_OK = qw(make_header make_source);

########################################################################
##                          DEFAULT CPP CODE                          ##
########################################################################

my $COPYRIGHT = << 'COPYRIGHT';
/**********************************************************************/
/* Copyright 2014 RCF                                                 */
/*                                                                    */
/* Licensed under the Apache License, Version 2.0 (the "License");    */
/* you may not use this file except in compliance with the License.   */
/* You may obtain a copy of the License at                            */
/*                                                                    */
/*     http://www.apache.org/licenses/LICENSE-2.0                     */
/*                                                                    */
/* Unless required by applicable law or agreed to in writing,         */
/* software distributed under the License is distributed on an        */
/* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,       */
/* either express or implied.                                         */
/* See the License for the specific language governing permissions    */
/* and limitations under the License.                                 */
/**********************************************************************/
COPYRIGHT

## QUARK HPP ############################################################
my $quark_hpp_init = << "QUARK_HPP_INIT";
$COPYRIGHT
#ifndef HPP_QUARK_DEFINED
#define HPP_QUARK_DEFINED

// Default libraries
#include <string>
#include <unordered_map>

// Libraries
#include "Command.hpp"

// Auto-Generated Libraries
QUARK_HPP_INIT

my $quark_hpp_end = << "QUARK_HPP_END";

// Mapping strings in functions
namespace quark
{
    typedef vm::Prog (*Func_ptr)();
    extern std::unordered_map<std::string,Func_ptr> functions;
}

#endif
QUARK_HPP_END

## QUARK CPP ############################################################
my $quark_cpp_init = << "QUARK_CPP_INIT";
$COPYRIGHT
// Libraries
#include "Quark.hpp"
using namespace quark;

std::unordered_map<std::string,Func_ptr> quark::functions
{
QUARK_CPP_INIT

my $quark_cpp_end = << "QUARK_CPP_END";
};
QUARK_CPP_END

########################################################################
##                    PRINTING NAMESPACE ACCESSORS                    ##
########################################################################

sub make_header
{
    return if scalar @_ != 2;
    my $incdir = shift;
    my $srcdir = shift;

    # Get all .hpp inside $incdir directory
    my @incs = get_includes($incdir);

    # Create a Quark.hpp header file
    open(my $QUARK_HPP, ">", "$incdir/Quark.hpp")
        or die "Unable to open new file $incdir/Quark.hpp";

    select $QUARK_HPP;
    print $quark_hpp_init;

    # Print included files
    map { say "#include \"$_\"" } @incs;

    print $quark_hpp_end;
    select STDOUT;

    close $QUARK_HPP;
}

sub make_source
{
    return if scalar @_ != 2;
    my $incdir = shift;
    my $srcdir = shift;

    # Get all .hpp inside $incdir directory
    my @incs = get_includes($incdir);
    map { s/(.*)\.hpp/$1/ } @incs;

    # Get maximum size of include
    my $max_length = 0;
    map { (length($_) > $max_length) ? ($max_length = length($_)) : () } @incs;

    # Create a Quark.cpp source file
    open(my $QUARK_CPP, ">", "$srcdir/Quark.cpp")
        or die "Unable to open new file $srcdir/Quark.cpp";

    select $QUARK_CPP;
    print $quark_cpp_init;

    # Create map of function names to strings
    for (sort { length($a) <=> length($b) } @incs)
    {
        print " " x 4, "{ ";
        printf "%-*s", $max_length+2, "\"$_\"";     # +2 from \" \"
        print ", ";
        printf "%-*s", $max_length+8, "&upload_$_"; # +8 from &upload_
        say " },";
    }

    print $quark_cpp_end;
    select STDOUT;

    close $QUARK_CPP;
}

sub get_includes
{
    return if scalar @_ != 1;
    my $incdir = shift;

    # Get all .hpp inside $incdir directory
    opendir INCLUDES, $incdir;
    my @incs = grep {
        not /^\./ and not /Quark\.hpp/ and -f "$incdir/$_"
    } readdir INCLUDES;
    closedir INCLUDES;

    return @incs;
}


text:
This is my blog site.
It is based on forking [knitr-jekyll](http://yihui.name/knitr-jekyll)
repo,
which allows R Markdown posts to be compiled
automatically.

All my blog posts are under the
[CC-BY 4.0](http://creativecommons.org/licenses/by/4.0/)
International License.


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
 "http://www.w3.org/TR/html4/loose.dtd">

<title>CURLOPT_SSH_PRIVATE_KEYFILE man page</title>
<meta name="generator" content="roffit">

NAME

CURLOPT_SSH_PRIVATE_KEYFILE - set private key file for SSH auth
SYNOPSIS

#include <curl/curl.h>

CURLcode curl_easy_setopt(CURL *handle, CURLOPT_SSH_PRIVATE_KEYFILE,
                          char *filename);

DESCRIPTION

Pass a char * pointing to a filename for your private key. If not used, libcurl defaults to $HOME/.ssh/id_dsa if the HOME environment variable is set, and just "id_dsa" in the current directory if HOME is not set.

If the file is password-protected, set the password with CURLOPT_KEYPASSWD.
DEFAULT

As explained above
PROTOCOLS

SFTP and SCP
EXAMPLE

TODO
AVAILABILITY

Added in 7.16.1
RETURN VALUE

Returns CURLE_OK if the option is supported, CURLE_UNKNOWN_OPTION if not, or CURLE_OUT_OF_MEMORY if there was insufficient heap space.
SEE ALSO

CURLOPT_SSH_PUBLIC_KEYFILE, CURLOPT_SSH_AUTH_TYPES

 This HTML page was made with roffit.


text:
// ===============================================================================
// PageCommon of SampleCMS
// https://github.com/lozenlin/SampleCMS
//
// PageCommon.cs
//
// ===============================================================================
// Copyright (c) 2017 lozenlin
// Licensed under the MIT License. See LICENSE file in the project root for full license information.
// ===============================================================================

using log4net;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Net;
using System.Security.Principal;
using System.Text;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;

namespace Common.LogicObject
{
    /// <summary>
    /// 網頁的共用元件
    /// </summary>
    public class PageCommon
    {
        /// <summary>
        /// UI 程式(Page, UserControl, HttpHandler)的記錄工具
        /// </summary>
        public ILog LoggerOfUI
        {
            get;
            private set;
        }

        #region qs:=QueryString, se:=Session, vs:=ViewState, co:=Cookie

        /// <summary>
        /// 語言號碼(l或lang,l優先)
        /// </summary>
        public virtual int qsLangNo
        {
            get
            {
                string str = QueryStringToSafeStr("l");
                if (str == null)
                    str = QueryStringToSafeStr("lang");

                int nResult;

                if (str != null)
                    str = str.Trim();

                if (string.IsNullOrEmpty(str))
                {
                    //未指定,抓瀏覽器的
                    string resultCultureName = GetAllowedUserCultureName();

                    nResult = Convert.ToInt32(new LangManager().GetLangNo(resultCultureName));
                }
                else if (int.TryParse(str, out nResult))
                {
                }

                return nResult;
            }
        }

        public string qsCultureNameOfLangNo
        {
            get
            {
                string result = new LangManager().GetCultureName(qsLangNo.ToString());
                return result;
            }
        }

        /// <summary>
        /// 頁碼
        /// </summary>
        public int qsPageCode
        {
            get
            {
                int nResult;
                string str = QueryStringToSafeStr("p");

                if (str != null && int.TryParse(str, out nResult) && nResult >= 1)
                {
                }
                else
                    nResult = 1;

                return nResult;
            }
        }

        /// <summary>
        /// 代碼
        /// </summary>
        public int qsId
        {
            get
            {
                string str = QueryStringToSafeStr("id");
                int nResult = 0;

                if (str != null && int.TryParse(str, out nResult))
                {
                }
                else
                    nResult = 0;

                return nResult;
            }
        }

        /// <summary>
        /// Attach file id
        /// </summary>
        public Guid qsAttId
        {
            get
            {
                string str = QueryStringToSafeStr("attid") ?? "";
                Guid result = Guid.Empty;

                if (str != "" && Guid.TryParse(str, out result))
                {
                }

                return result;
            }
        }

        /// <summary>
        /// Picture id
        /// </summary>
        public Guid qsPicId
        {
            get
            {
                string str = QueryStringToSafeStr("picid") ?? "";
                Guid result = Guid.Empty;

                if (str != "" && Guid.TryParse(str, out result))
                {
                }

                return result;
            }
        }

        /// <summary>
        /// Video id
        /// </summary>
        public Guid qsVidId
        {
            get
            {
                string str = QueryStringToSafeStr("vidid") ?? "";
                Guid result = Guid.Empty;

                if (str != "" && Guid.TryParse(str, out result))
                {
                }

                return result;
            }
        }

        /// <summary>
        /// Token value to preview article page
        /// </summary>
        public string qsPreview
        {
            get
            {
                return QueryStringToSafeStr("preview");
            }
        }

        #endregion

        protected HttpContext context;
        protected StateBag viewState;
        protected ILog logger = null;
        /// <summary>
        /// 讓 QueryStringToSafeStr() 可依照前台、後台去調整過濾方式
        /// </summary>
        protected bool isBackendPage = false;

        #region 工具屬性

        protected HttpServerUtility Server
        {
            get { return context.Server; }
        }

        protected HttpRequest Request
        {
            get { return context.Request; }
        }

        protected HttpResponse Response
        {
            get { return context.Response; }
        }

        protected HttpSessionState Session
        {
            get { return context.Session; }
        }

        protected IPrincipal User
        {
            get { return context.User; }
        }

        protected StateBag ViewState
        {
            get { return viewState; }
        }

        protected System.Web.Caching.Cache Cache
        {
            get { return context.Cache; }
        }

        #endregion

        /// <summary>
        /// 網頁的共用元件
        /// </summary>
        public PageCommon(HttpContext context, StateBag viewState)
        {
            this.context = context;
            this.viewState = viewState;
            logger = LogManager.GetLogger(this.GetType());
            isBackendPage = (this is BackendPageCommon);
        }

        /// <summary>
        /// 初始化 LoggerOfUI
        /// </summary>
        public ILog InitialLoggerOfUI(Type typeUiComponent)
        {
            LoggerOfUI = LogManager.GetLogger(typeUiComponent);

            return LoggerOfUI;
        }

        public string QueryStringToSafeStr(string name)
        {
            string value = Request.QueryString[name];

            if (value == null)
                return null;

            //if (!isBackendPage)
            //return AntiXss.GetSafeHtmlFragment(value);
            return value;
        }

        public string FormToSafeStr(string name)
        {
            string value = Request.Form[name];

            if (value == null)
                return null;

            //if (!isBackendPage)
            //return AntiXss.GetSafeHtmlFragment(value);
            return value;
        }

        public string SessionToSafeStr(string name)
        {
            object obj = Session[name];

            if (obj == null)
                return null;

            string value = Convert.ToString(obj);

            //if (!isBackendPage)
            //return AntiXss.GetSafeHtmlFragment(value);
            return value;
        }

        /// <summary>
        /// 取得客戶端主機位址
        /// </summary>
        /// <remarks>
        /// reference:http://www.dotblogs.com.tw/hunterpo/archive/2011/03/21/21991.aspx
        /// </remarks>
        public string GetClientIP()
        {
            string result = Request.ServerVariables["REMOTE_ADDR"] ?? "";

            if (null != Request.ServerVariables["HTTP_VIA"])
            {
                string forwardIP = Request.ServerVariables["HTTP_X_FORWARDED_FOR"] ?? "";

                if (forwardIP != "" && forwardIP.ToLower() != "unknown")
                    result = forwardIP;
            }

            return result;
        }

        /// <summary>
        /// 取得客戶端主機 IPv4 位址
        /// </summary>
        /// <remarks>
        /// reference:http://www.dotblogs.com.tw/hunterpo/archive/2011/03/21/21991.aspx
        /// </remarks>
        public string GetClientIPv4()
        {
            string result = "";

            foreach (IPAddress ip in Dns.GetHostAddresses(GetClientIP()))
            {
                if (ip.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
                {
                    result = ip.ToString();
                    break;
                }
            }

            return result;
        }

        /// <summary>
        /// 取得客戶端主機 IPv6 位址
        /// </summary>
        /// <remarks>
        /// reference:http://www.dotblogs.com.tw/hunterpo/archive/2011/03/21/21991.aspx
        /// </remarks>
        public string GetClientIPv6()
        {
            string result = "";

            foreach (IPAddress ip in Dns.GetHostAddresses(GetClientIP()))
            {
                if (ip.AddressFamily == System.Net.Sockets.AddressFamily.InterNetworkV6)
                {
                    result = ip.ToString();
                    break;
                }
            }

            return result;
        }

        /// <summary>
        /// 取得本系統允許的瀏覽器指定語系名稱
        /// </summary>
        public string GetAllowedUserCultureName()
        {
            string resultCultureName = "";

            if (Request.UserLanguages != null)
            {
                foreach (string userLang in Request.UserLanguages)
                {
                    string tempCultureName = userLang;

                    if (tempCultureName.Contains(";"))
                        tempCultureName = tempCultureName.Split(';')[0];

                    if (tempCultureName.StartsWith("zh-") || tempCultureName == "zh")
                    {
                        resultCultureName = LangManager.CultureNameZHTW;
                        break;
                    }
                    else if (tempCultureName.StartsWith("en-") || tempCultureName == "en")
                    {
                        resultCultureName = LangManager.CultureNameEN;
                        break;
                    }
                }
            }

            if (resultCultureName == "")
                resultCultureName = LangManager.CultureNameZHTW;

            return resultCultureName;
        }

        /// <summary>
        /// Finds a Control recursively. Note finds the first match and exists
        /// </summary>
        /// <remarks>
        /// reference: http://www.west-wind.com/weblog/posts/2006/Apr/09/ASPNET-20-MasterPages-and-FindControl
        /// </remarks>
        public Control FindControlRecursive(Control Root, string Id)
        {
            if (Root.ID == Id)
                return Root;

            foreach (Control Ctl in Root.Controls)
            {
                Control FoundCtl = FindControlRecursive(Ctl, Id);
                if (FoundCtl != null)
                    return FoundCtl;
            }

            return null;
        }

        /// <summary>
        /// 在傳入的連結後面附加目前的網址參數
        /// </summary>
        public string AppendCurrentQueryString(string linkUrl)
        {
            StringBuilder sbResult = new StringBuilder(linkUrl);
            bool hasPara = linkUrl.IndexOf("?") != -1;
            bool isFirstPara = true;

            foreach (string key in Request.QueryString.AllKeys)
            {
                // add separator
                if (isFirstPara && !hasPara)
                {
                    sbResult.Append("?");
                    isFirstPara = false;
                }
                else
                {
                    sbResult.Append("&");
                }

                sbResult.AppendFormat("{0}={1}", key, Server.UrlEncode(Request.QueryString[key]));
            }

            return sbResult.ToString();
        }

        /// <summary>
        /// 只寄給測試收件人
        /// </summary>
        public bool IsSendToTesterOnly()
        {
            bool bResult = false;
            bool.TryParse(ConfigurationManager.AppSettings["SendToTesterOnly"], out bResult);

            return bResult;
        }

        /// <summary>
        /// display ServiceEmail but send mail by sender
        /// </summary>
        public bool UseSender()
        {
            bool bResult = false;
            bool.TryParse(ConfigurationManager.AppSettings["UseSender"], out bResult);

            return bResult;
        }
    }
}


text:
<?php
namespace Chamilo\Application\Weblcms\Integration\Chamilo\Core\Reporting\Block\Assessment;

use Chamilo\Application\Weblcms\Integration\Chamilo\Core\Tracking\Storage\DataClass\AssessmentAttempt;
use Chamilo\Core\Reporting\ReportingData;
use Chamilo\Core\Repository\Storage\DataClass\ComplexContentObjectItem;
use Chamilo\Libraries\Platform\Session\Request;
use Chamilo\Libraries\Platform\Translation;
use Chamilo\Libraries\Utilities\DatetimeUtilities;

/**
 *
 * @package application.weblcms.php.reporting.blocks Reporting block with the assessment question attempts of one user
 * @author Joris Willems <joris.willems@gmail.com>
 * @author Alexander Van Paemel
 */
class AssessmentQuestionAttemptsUserBlock extends AssessmentBlock
{

    public function count_data()
    {
        $reporting_data = new ReportingData();

        $reporting_data->set_rows($this->get_reporting_data_rows());

        $question_id = Request::get(
            \Chamilo\Application\Weblcms\Tool\Implementation\Reporting\Manager::PARAM_QUESTION);

        $question = \Chamilo\Core\Repository\Storage\DataManager::retrieve_by_id(
            ComplexContentObjectItem::class_name(),
            $question_id);
        $weight = $question->get_weight();

        $question_attempts = $this->get_question_attempts_from_publication_and_question(
            $this->get_publication_id(),
            $question_id,
            $this->get_user_id());

        $counter = 0;

        while ($question_attempt = $question_attempts->next_result())
        {
            $assessment_attempt = $question_attempt->get_optional_property(self::PROPERTY_ASSESSMENT_ATTEMPT);

            $date = $assessment_attempt->get_start_time();
            $date = DatetimeUtilities::format_locale_date(null, $date);

            $reporting_data->add_category($counter);

            // if($assessment_attempt->get_status() == AssessmentAttempt::STATUS_COMPLETED)
            {
                $score = $this->get_score_bar($question_attempt->get_score() / $weight * 100);

                $reporting_data->add_data_category_row(
                    $counter,
                    Translation::get('Details'),
                    $this->get_assessment_result_viewer_link($assessment_attempt->get_id(), $question_attempt->get_id()));
            }

            $reporting_data->add_data_category_row($counter, Translation::get('Date'), $date);
            $reporting_data->add_data_category_row($counter, Translation::get('Score'), $score);
            /*
             * $reporting_data->add_data_category_row( $counter, Translation :: get('Status'),
             * $assessment_attempt->get_status_as_string() );
             */

            $this->add_additional_information_for_attempt(
                $assessment_attempt,
                $question_attempt,
                $counter,
                $reporting_data);

            $counter ++;
        }

        $reporting_data->hide_categories();

        return $reporting_data;
    }

    public function retrieve_data()
    {
        return $this->count_data();
    }

    public function get_views()
    {
        return array(\Chamilo\Core\Reporting\Viewer\Rendition\Block\Type\Html::VIEW_TABLE);
    }

    /**
     * Returns the rows for the reporting data
     *
     * @return string[]
     */
    protected function get_reporting_data_rows()
    {
        return array(Translation::get('Date'), Translation::get('Score'),
            // Translation :: get('Status'),
            Translation::get('Details'));
    }

    /**
     * Adds additional data for the assessment attempt
     *
     * @param AssessmentAttempt $assessment_attempt
     * @param QuestionAttempt $question_attempt
     * @param int $counter
     * @param ReportingData $reporting_data
     */
    protected function add_additional_information_for_attempt($assessment_attempt, $question_attempt, $counter,
        $reporting_data)
    {
    }
}


text:
namespace ash::secure_channel {

class AuthenticatedChannel;

// ConnectionAttempt represents an ongoing attempt to connect to a given device
// over a given medium. Each ConnectionAttempt is comprised of one or
// more PendingConnectionRequests and notifies its delegate when the attempt has
// succeeded or failed.
template <typename FailureDetailType>
class ConnectionAttempt : public PendingConnectionRequestDelegate {
 public:
  // Extracts all of the ClientConnectionParameters owned by |attempt|'s
  // PendingConnectionRequests. This function deletes |attempt| as part of this
  // process to ensure that it is no longer used after extraction is complete.
  static std::vector<std::unique_ptr<ClientConnectionParameters>>
  ExtractClientConnectionParameters(
      std::unique_ptr<ConnectionAttempt<FailureDetailType>> attempt) {
    return attempt->ExtractClientConnectionParameters();
  }

  ConnectionAttempt(const ConnectionAttempt&) = delete;
  ConnectionAttempt& operator=(const ConnectionAttempt&) = delete;

  virtual ~ConnectionAttempt() = default;

  const ConnectionAttemptDetails& connection_attempt_details() const {
    return connection_attempt_details_;
  }

  // Associates |request| with this attempt. If the attempt succeeds, |request|
  // will be notified of success; on failure, |request| will be notified of a
  // connection failure. Returns whether adding the request was successful.
  bool AddPendingConnectionRequest(
      std::unique_ptr<PendingConnectionRequest<FailureDetailType>> request) {
    if (!request) {
      PA_LOG(ERROR) << "ConnectionAttempt::AddPendingConnectionRequest(): "
                    << "Received invalid request.";
      return false;
    }

    if (has_notified_delegate_of_success_) {
      PA_LOG(ERROR) << "ConnectionAttempt::AddPendingConnectionRequest(): "
                    << "Tried to add an additional request,but the attempt had "
                    << "already finished.";
      return false;
    }

    ProcessAddingNewConnectionRequest(std::move(request));
    return true;
  }

 protected:
  ConnectionAttempt(ConnectionAttemptDelegate* delegate,
                    base::Clock* clock,
                    const ConnectionAttemptDetails& connection_attempt_details)
      : delegate_(delegate),
        clock_(clock),
        connection_attempt_details_(connection_attempt_details),
        start_attempt_timestamp_(clock_->Now()) {
    DCHECK(delegate);
  }

  // Derived types should use this function to associate the request with this
  // attempt.
  virtual void ProcessAddingNewConnectionRequest(
      std::unique_ptr<PendingConnectionRequest<FailureDetailType>> request) = 0;

  // Extracts the ClientConnectionParameters from all child
  // PendingConnectionRequests.
  virtual std::vector<std::unique_ptr<ClientConnectionParameters>>
  ExtractClientConnectionParameters() = 0;

  // Derived types can override this function to process the amount of time that
  // this connection attempt has taken to produce a successful connection.
  virtual void ProcessSuccessfulConnectionDuration(
      const base::TimeDelta& duration) {}

  void OnConnectionAttemptSucceeded(
      std::unique_ptr<AuthenticatedChannel> authenticated_channel) {
    if (has_notified_delegate_of_success_) {
      PA_LOG(ERROR) << "ConnectionAttempt::OnConnectionAttemptSucceeded(): "
                    << "Tried to alert delegate of a successful connection, "
                    << "but the attempt had already finished.";
      return;
    }

    has_notified_delegate_of_success_ = true;
    ProcessSuccessfulConnectionDuration(clock_->Now() -
                                        start_attempt_timestamp_);
    delegate_->OnConnectionAttemptSucceeded(
        connection_attempt_details_.GetAssociatedConnectionDetails(),
        std::move(authenticated_channel));
  }

  void OnConnectionAttemptFinishedWithoutConnection() {
    if (has_notified_delegate_of_success_) {
      PA_LOG(ERROR) << "ConnectionAttempt::"
                    << "OnConnectionAttemptFinishedWithoutConnection(): "
                    << "Tried to alert delegate of a failed connection, "
                    << "but the attempt had already finished.";
      return;
    }

    delegate_->OnConnectionAttemptFinishedWithoutConnection(
        connection_attempt_details_);
  }

 private:
  ConnectionAttemptDelegate* delegate_;
  base::Clock* clock_;
  const ConnectionAttemptDetails connection_attempt_details_;
  const base::Time start_attempt_timestamp_;

  bool has_notified_delegate_of_success_ = false;
};

}  // namespace ash::secure_channel

#endif  // ASH_SERVICES_SECURE_CHANNEL_CONNECTION_ATTEMPT_H_