text:
module.exports = {
  "html" : {
    "filters" : "html",
    "profile" : "html",

    "snippets" : {
      "cgh": "",
      "off-canvas-icon" : "",
      "progress-meter" : "",
      "rns" : "\n",
      "rbcharview" : "<meta charset=\"utf-8\">\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n",
      "rbtitle" : "<title>Foundation 5</title>",
      "rbifcss" : "\n",
      "rbnormalize" : "<link rel=\"stylesheet\" href=\"css/normalize.css\">",
      "rbstylesheet" : "<link rel=\"stylesheet\" href=\"css/foundation.css\">",
      "rbappstylesheet" : "\n\n<link rel=\"stylesheet\" href=\"css/app.css\">",
      "rbhead" : "<!doctype html>\n\n\n\n",
      "rbmodernizr" : "\n\n",
      "fjquery": "\n\n\n",
      "fscript": "",
    },
    "abbreviations": {

      "zf-head": "rbhead>(head>rbcharview>rbtitle>rbifcss>rbnormalize>rbstylesheet>rbappstylesheet>rbmodernizr)>{\n\n\n${1:}|}",
      "zf-footer": "fjquery>fscript>{\n\n}",

      "foundation": "zf-head>zf-footer",

      "zf-row" : "
",
      "zf-col" : "
",

      "zf-accordion" : "dl.accordion[data-accordion=data-accordion]>(zf-accordion-active-panel)>(dd*2>(a[href=#panel$@2]{Accordion $@2})>(div#panel$@2.content{Panel $@2 Content}))",
      "zf-accordion-active-panel": "dd>(a[href=#panel$]{Accordion $})>div#panel$.content.active{Panel $ content (this panel has the class active so it will be open at pageload)}",

      "zf-alert" : "{}>div[data-alert=data-alert].alert-box>cgh>{\n}>(a[href=#].close{×})",

      "zf-breadcrumb" : "ul.breadcrumbs>(li*2>a[href=#]{page $})>(li.unavailable>a[href=#]{page 3})>(li.current>a[href=#]{page 4})",

      "zf-button-bar" : "div.button-bar>ul.button-group*2>li*3>a[href=#].button{Button $}",

      "zf-button-group" : "{}>ul.button-group>li*3>a[href=#].button{Button $}",

      "zf-button" : "{\n\n\n\n}>a[href=#].button{Default Button}",

      "zf-clearing" : "ul.clearing-thumbs[data-clearing=data-clearing]>(li>a[href=http://placehold.it/350x150&text=full-image-$]>img[src=http://placehold.it/150x150&text=thumbnail-$])*3",

      "zf-dropdown-button": "{\n\n\n}>(a[href=# data-dropdown=drop].button.dropdown{Dropdown Button})>{
}>ul#drop[data-dropdown-content=dropdown-content].f-dropdown>li*3>a[href=#]{Link $}",

      "zf-full-grid": "zf-row>zf-col.small-12.medium-12.large-12",

      "zf-half-grid": "zf-row>zf-col.small-6.medium-6.large-6*2",

      "zf-offcanvas": "div.off-canvas-wrap[data-offcanvas=data-offcanvas]>div.inner-wrap>(nav.tab-bar>(section.left-small>off-canvas-icon)>{\n}>(section.right.tab-bar-section>h1.title{Foundation}))>{\n\n}>(aside.left-off-canvas-menu>(ul.off-canvas-list>(li>label>{Foundation})>(li>a[href=#]{Link name})))>{\n}>(section.main-section>cgh)>{\n\n}>{\n}>a[href=#].exit-off-canvas",

      "zf-orbit": "ul.example-orbit[data-orbit=example-orbit]>li*5>(div.orbit-caption{image $})>img[src=\"http://placehold.it/1200x450&text=image-$\"]",

      "zf-orbit-content": "ul.example-orbit-content[data-orbit=example-orbit-content]>li[data-orbit-slide=headline-$]*5>div>(h2{Headline $})>(h3{Subheadline})",

      "zf-pagination": "ul.pagination>(li.arrow.unavailable>a[href=#]{«})>(li.current>a[href=#]{$})>((li>a[href=#]{$@2})*3)>(li.unavailable>a[href=#]{…})>((li>a[href=#]{$@12})*2)>(li.arrow>a[href=#]{»})",

      "zf-panel": "div.panel>(h5{This is a callout panel.})>(p{It's a little ostentatious, but useful for important content.})",

      "zf-pricing-table": "ul.pricing-table>(li.title{Standard})>(li.price{\\$99.99})>(li.description{An awesome description})>(li.bullet-item{1 Database})>(li.bullet-item{5GB Storage})>(li.bullet-item{20 Users})>(li.cta-button>a.button[href=#]{Buy now})",

      "zf-progress-bar": "{\n\n\n}>div.progress>progress-meter",

      "zf-quater-grid": "zf-row>zf-col.small-3.medium-3.large-3*4",

      "zf-reveal": "(a[href=# data-reveal-id=myModal]{Click Me For A Modal})>{\n}>(div#myModal.reveal-modal[data-reveal=data-reveal]>(h2{Awesome. I have it})>(p.lead{Your couch. It is mine.})>(p{Im a cool paragraph that lives inside of an even cooler modal. Wins})>(a[href=#].close-reveal-modal>{×}))",

      "zf-sidenav": "ul.side-nav>(li.active>a[href=#]>{Link $})>(li>a[href=#]>{Link $@2})>(li.divider)>(li>a[href=#]>{Link $@3})*2",

      "zf-split-button": "{\n\n\n}>((a[href=#].button.split{Split Button}>span[data-dropdown=drop])>{
})>ul[data-dropdown-content=data-dropdown-content]#drop.f-dropdown>(li>a[href=#]{Link $})*3",

      "zf-subnav": "dl.sub-nav>(dt{Filter})>(dd.active>a[href=#]{All})>(dd>a[href=#]{Active})>(dd>a[href=#]{Pending})>(dd>a[href=#]{Suspended})",

      "zf-tabs": "(dl.tabs[data-tab=data-tab]>(dd.active>a[href=#panel$]>{Tab $})>((dd>a[href=#panel$@2]>{Tab $@2})*3))>div.tabs-content>(div.content.active#panel$>p>(lorem15))>((div.content#panel$@2>p>(lorem15))*3)",

      "zf-third-grid": "zf-row>zf-col.small-4.medium-4.large-4*3",

      "zf-topbar": "nav.top-bar[data-topbar=data-topbar]>(ul.title-area>(li.name>h1>a[href=#]>{Something})>(li.toggle-topbar.menu-icon>a[href=#]>{Menu}))>(section.top-bar-section>rns>(ul.right>(li.active>a[href=#]>{Right Nav Button Active})>(li.has-dropdown>(a[href=#]>{Right Button with Dropdown})>ul.dropdown>(li>a[href=#]>{First link in dropdown})))>(ul.left>li>a[href=#]>{Left Nav Button}))",

      "zf-vertical-tabs": "(dl.tabs.vertical[data-tab=data-tab]>(dd.active>a[href=#panel$a]>{Tab $})>((dd>a[href=#panel$@2a]>{Tab $@2a})*3))>div.tabs-content.vertical>(div.content.active#panel$a>p>(lorem15))>((div.content#panel$@2a>p>(lorem15))*3)",

    }
  }
};


text:
@implementation RMSRightDetailFormCell

+ (UITableViewCellStyle)cellStyle {
    return UITableViewCellStyleValue1;
}

+ (instancetype)cell {
    RMSRightDetailFormCell *cell = [super cell];

    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;

    return cell;
}

- (void)synchronizeView {
    [super synchronizeView];

    self.detailTextLabel.text = [self.value description];
}

@end

redpajama_set_name: RedPajamaGithub


text:
package org.hawkular.alerts.engine.impl;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.annotation.Resource;
import javax.ejb.EJB;
import javax.ejb.Local;
import javax.ejb.Singleton;
import javax.ejb.Startup;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.enterprise.concurrent.ManagedExecutorService;

import org.hawkular.alerts.api.model.condition.CompareCondition;
import org.hawkular.alerts.api.model.condition.Condition;
import org.hawkular.alerts.api.model.condition.ConditionEval;
import org.hawkular.alerts.api.model.dampening.Dampening;
import org.hawkular.alerts.api.model.data.Data;
import org.hawkular.alerts.api.model.event.Alert;
import org.hawkular.alerts.api.model.event.Event;
import org.hawkular.alerts.api.model.trigger.Trigger;
import org.hawkular.alerts.api.services.ActionsService;
import org.hawkular.alerts.api.services.AlertsService;
import org.hawkular.alerts.api.services.DefinitionsService;
import org.hawkular.alerts.engine.impl.AlertsEngineCache.DataEntry;
import org.hawkular.alerts.engine.log.MsgLogger;
import org.hawkular.alerts.engine.service.AlertsEngine;
import org.hawkular.alerts.engine.service.PartitionDataListener;
import org.hawkular.alerts.engine.service.PartitionManager;
import org.hawkular.alerts.engine.service.PartitionManager.Operation;
import org.hawkular.alerts.engine.service.PartitionTriggerListener;
import org.hawkular.alerts.engine.service.RulesEngine;
import org.jboss.logging.Logger;

/**
 * Cassandra implementation for {@link org.hawkular.alerts.api.services.AlertsService}.
 * This implementation processes data asynchronously using a buffer queue.
 *
 * @author Jay Shaughnessy
 * @author Lucas Ponce
 */
@Singleton
@Startup
@Local(AlertsEngine.class)
@TransactionAttribute(value= TransactionAttributeType.NOT_SUPPORTED)
public class AlertsEngineImpl implements AlertsEngine, PartitionTriggerListener, PartitionDataListener {
    private final MsgLogger msgLog = MsgLogger.LOGGER;
    private final Logger log = Logger.getLogger(AlertsEngineImpl.class);

    /*
        ENGINE_DELAY defined in milliseconds
     */
    private static final String ENGINE_DELAY = "hawkular-alerts.engine-delay";

    /*
        ENGINE_PERIOD defined in milliseconds
     */
    private static final String ENGINE_PERIOD = "hawkular-alerts.engine-period";

    private int delay;
    private int period;

    private final List<Data> pendingData;
    private final List<Event> pendingEvents;
    private final List<Alert> alerts;
    private final List<Event> events;
    private final Set<Dampening> pendingTimeouts;
    private final Map<Trigger, List<Set<ConditionEval>>> autoResolvedTriggers;
    private final Set<Trigger> disabledTriggers;
    private final AlertsEngineCache alertsEngineCache;

    private final Timer wakeUpTimer;
    private TimerTask rulesTask;

    @EJB
    RulesEngine rules;

    @EJB
    DefinitionsService definitions;

    @EJB
    ActionsService actions;

    @EJB
    AlertsService alertsService;

    @EJB
    PartitionManager partitionManager;

    @Resource
    private ManagedExecutorService executor;

    boolean distributed = false;

    public AlertsEngineImpl() {
        pendingData = new ArrayList<>();
        pendingEvents = new ArrayList<>();
        alerts = new ArrayList<>();
        events = new ArrayList<>();
        pendingTimeouts = new HashSet<>();
        autoResolvedTriggers = new HashMap<>();
        disabledTriggers = new HashSet<>();
        alertsEngineCache = new AlertsEngineCache();

        wakeUpTimer = new Timer("CassAlertsServiceImpl-Timer");

        delay = new Integer(AlertProperties.getProperty(ENGINE_DELAY, "1000"));
        period = new Integer(AlertProperties.getProperty(ENGINE_PERIOD, "2000"));
    }

    public RulesEngine getRules() {
        return rules;
    }

    public void setRules(RulesEngine rules) {
        this.rules = rules;
    }

    public DefinitionsService getDefinitions() {
        return definitions;
    }

    public void setDefinitions(DefinitionsService definitions) {
        this.definitions = definitions;
    }

    public ActionsService getActions() {
        return actions;
    }

    public void setActions(ActionsService actions) {
        this.actions = actions;
    }

    public AlertsService getAlertsService() {
        return alertsService;
    }

    public void setAlertsService(AlertsService alertsService) {
        this.alertsService = alertsService;
    }

    @PostConstruct
    public void initServices() {
        try {
            distributed = partitionManager.isDistributed();
            if (distributed) {
                log.debug("Registering PartitionManager listeners...");
                partitionManager.registerDataListener(this);
                partitionManager.registerTriggerListener(this);
            }
            executor.submit(() -> {
                /*
                    A reload() operation means that all triggers from the backend should be reloaded into
                    the AlertsEngine memory. In a distributed environment, the node that execute the reload()
                    operation loads the triggers assigned to it and notify other nodes to load rest of the triggers.
                 */
                reload();
            });
        } catch (Throwable t) {
            if (log.isDebugEnabled()) {
                t.printStackTrace();
            }
            msgLog.errorCannotInitializeAlertsService(t.getMessage());
        }
    }

    @PreDestroy
    public void shutdown() {
        rulesTask.cancel();
        wakeUpTimer.cancel();
    }

    public void clear() {
        rulesTask.cancel();

        rules.clear();

        pendingData.clear();
        pendingEvents.clear();
        alerts.clear();
        events.clear();
        pendingTimeouts.clear();
        autoResolvedTriggers.clear();
        disabledTriggers.clear();

        rulesTask = new RulesInvoker();
        wakeUpTimer.schedule(rulesTask, delay, period);
    }

    @Override
    public void reload() {
        log.debug("Start a full reload of the AlertsEngine");
        rules.reset();
        alertsEngineCache.clear();
        if (rulesTask != null) {
            rulesTask.cancel();
        }

        Collection<Trigger> triggers = null;
        try {
            triggers = definitions.getAllTriggers();
        } catch (Exception e) {
            log.debug(e.getMessage(), e);
            msgLog.errorDefinitionsService("Triggers", e.getMessage());
        }

        if (triggers != null && !triggers.isEmpty()) {

            triggers.stream().filter(Trigger::isLoadable).forEach(t -> {
                /*
                    In distributed scenario a reload should delegate into the PartitionManager to load the trigger on
                    the node which belongs
                 */
                if (distributed) {
                    partitionManager.notifyTrigger(Operation.UPDATE, t.getTenantId(), t.getId());
                } else {
                    reloadTrigger(t);
                }
            });
        }

        rules.addGlobal("log", log);
        rules.addGlobal("actions", actions);
        rules.addGlobal("alerts", alerts);
        rules.addGlobal("events", events);
        rules.addGlobal("pendingTimeouts", pendingTimeouts);
        rules.addGlobal("autoResolvedTriggers", autoResolvedTriggers);
        rules.addGlobal("disabledTriggers", disabledTriggers);

        rulesTask = new RulesInvoker();
        wakeUpTimer.schedule(rulesTask, delay, period);
    }

    @Override
    public void addTrigger(final String tenantId, final String triggerId) {
        if (isEmpty(tenantId)) {
            throw new IllegalArgumentException("TenantId must be not null");
        }
        if (isEmpty(triggerId)) {
            throw new IllegalArgumentException("TriggerId must be not null");
        }
        if (distributed) {
            Trigger trigger = null;
            try {
                trigger = definitions.getTrigger(tenantId, triggerId);
                if (log.isDebugEnabled()) {
                    log.debug("addTrigger(" + trigger + ")");
                }
            } catch (Exception e) {
                log.debug(e.getMessage(), e);
                msgLog.errorDefinitionsService("Trigger", e.getMessage());
            }
            if (trigger != null && trigger.isLoadable()) {
                partitionManager.notifyTrigger(Operation.ADD, trigger.getTenantId(), trigger.getId());
            }
        }
    }

    @Override
    public void reloadTrigger(final String tenantId, final String triggerId) {
        if (isEmpty(tenantId)) {
            throw new IllegalArgumentException("TenantId must be not null");
        }
        if (isEmpty(triggerId)) {
            throw new IllegalArgumentException("TriggerId must be not null");
        }

        Trigger trigger = null;
        try {
            trigger = definitions.getTrigger(tenantId, triggerId);
        } catch (Exception e) {
            log.debug(e.getMessage(), e);
            msgLog.errorDefinitionsService("Trigger", e.getMessage());
        }
        if (null == trigger) {
            if (log.isDebugEnabled()) {
                log.debug("Trigger not found for triggerId [" + triggerId + "], removing from rulebase if it exists");
            }
            Trigger doomedTrigger = new Trigger(tenantId, triggerId, "doomed");
            removeTrigger(doomedTrigger);
            return;
        }
        /*
            Non loadable triggers are filtered at this level.
            So in this case we can maintain a generic partition of all triggers on all nodes.
         */
        if (!trigger.isLoadable()) {
            if (log.isDebugEnabled()) {
                log.debug("Skipping reload of trigger [" + trigger.getTenantId() + "/" + trigger.getId() + "]");
            }
            return;
        }
        /*
            In distributed scenario a reload should delegate into the PartitionManager to load the trigger on the node
            which belongs.
         */
        if (distributed) {
            partitionManager.notifyTrigger(Operation.UPDATE, trigger.getTenantId(), trigger.getId());
        } else {
            reloadTrigger(trigger);
        }
    }

    private void reloadTrigger(Trigger trigger) {
        if (null == trigger) {
            throw new IllegalArgumentException("Trigger must be not null");
        }
        if (log.isDebugEnabled()) {
            log.debug("Reloading " + trigger);
        }
        // Look for the Trigger in the rules engine, if it is there then remove everything about it
        removeTrigger(trigger);

        try {
            if (distributed) {
                trigger = definitions.getTrigger(trigger.getTenantId(), trigger.getId());
            }
            if (trigger != null && trigger.isLoadable()) {
                Collection<Condition> conditionSet = definitions.getTriggerConditions(trigger.getTenantId(),
                        trigger.getId(), null);
                Collection<Dampening> dampenings = definitions.getTriggerDampenings(trigger.getTenantId(),
                        trigger.getId(), null);

                /*
                    Caching dataId from conditions.
                 */
                for (Condition c : conditionSet) {
                    DataEntry entry = new DataEntry(c.getTenantId(), c.getTriggerId(), c.getDataId());
                    alertsEngineCache.add(entry);
                    if (Condition.Type.COMPARE == c.getType()) {
                        String data2Id = ((CompareCondition) c).getData2Id();
                        DataEntry entry2 = new DataEntry(c.getTenantId(), c.getTriggerId(), data2Id);
                        alertsEngineCache.add(entry2);
                    }
                }

                rules.addFact(trigger);
                rules.addFacts(conditionSet);
                if (!dampenings.isEmpty()) {
                    rules.addFacts(dampenings);
                }
            }
        } catch (Exception e) {
            log.debug(e.getMessage(), e);
            msgLog.errorDefinitionsService("Conditions/Dampening", e.getMessage());
        }

    }

    @Override
    public Trigger getLoadedTrigger(Trigger trigger) {
        if (null == trigger) {
            throw new IllegalArgumentException("Trigger must be not null");
        }

        Trigger loadedTrigger = null;
        try {
            loadedTrigger = (Trigger)rules.getFact(trigger);

        } catch (Exception e) {
            log.errorf("Failed to get Trigger from engine %s: %s", trigger, e);
        }
        return loadedTrigger;
    }

    @Override
    public void removeTrigger(String tenantId, String triggerId) {
        if (isEmpty(tenantId)) {
            throw new IllegalArgumentException("TenantId must be not null");
        }
        if (isEmpty(triggerId)) {
            throw new IllegalArgumentException("TriggerId must be not null");
        }

        Trigger triggerToRemove = new Trigger(tenantId, triggerId, "trigger-to-remove");
        if (distributed) {
            partitionManager.notifyTrigger(Operation.REMOVE, triggerToRemove.getTenantId(), triggerToRemove.getId());
        } else {
            removeTrigger(triggerToRemove);
        }
    }

    private void removeTrigger(Trigger trigger) {
        if (null != rules.getFact(trigger)) {
            // First remove the related Trigger facts from the engine
            rules.removeFact(trigger);

            // Remove dataId associated from cache
            alertsEngineCache.remove(trigger.getTenantId(), trigger.getId());

            // then remove everything else.
            // We may want to do this with rules, because as is, we need to loop through every Fact in
            // the rules engine doing a relatively slow check.
            final String triggerId = trigger.getId();
            rules.removeFacts(t -> {
                if (t instanceof Dampening) {
                    return ((Dampening)t).getTriggerId().equals(triggerId);
                } else if (t instanceof Condition) {
                    return ((Condition)t).getTriggerId().equals(triggerId);
                }
                return false;
            });
        } else {
            if (log.isDebugEnabled()) {
                log.debug("Trigger not found. Not removed from rulebase " + trigger.toString());
            }
        }
    }

    @Override
    public void sendData(Collection<Data> data) {
        if (data == null) {
            throw new IllegalArgumentException("Data must be not null");
        }
        addPendingData(data);
        if (distributed) {
            partitionManager.notifyData(data);
        }
    }

    @Override
    public void sendData(Data data) {
        sendData(Collections.singleton(data));
    }

    @Override
    public void sendEvent(Event event) {
        sendEvents(Collections.singleton(event));
    }

    @Override
    public void sendEvents(Collection<Event> events) {
        if (events == null) {
            throw new IllegalArgumentException("Events must be not null");
        }
        addPendingEvents(events);
        if (distributed) {
            partitionManager.notifyEvents(events);
        }
    }

    private void addPendingData(Collection<Data> data) {
        ArrayList<Data> filteredData = new ArrayList<>(data);
        for (Iterator<Data> i = filteredData.iterator(); i.hasNext(); ) {
            Data d = i.next();
            if (!alertsEngineCache.isDataIdActive(d.getId())) {
                i.remove();
            }
        }
        synchronized (pendingData) {
            pendingData.addAll(filteredData);
        }
    }

    private void addPendingData(Data data) {
        if (data != null && data.getId() != null && alertsEngineCache.isDataIdActive(data.getId())) {
            synchronized (pendingData) {
                pendingData.add(data);
            }
        }
    }

    private void addPendingEvents(Collection<Event> events) {
        ArrayList<Event> filteredEvents = new ArrayList<>(events);
        for (Iterator<Event> i = filteredEvents.iterator(); i.hasNext(); ) {
            Event e = i.next();
            if (!alertsEngineCache.isDataIdActive(e.getDataId())) {
                i.remove();
            }
        }
        synchronized (pendingEvents) {
            pendingEvents.addAll(filteredEvents);
        }
    }

    private void addPendingEvent(Event event) {
        if (event != null && event.getDataId() != null && alertsEngineCache.isDataIdActive(event.getDataId())) {
            synchronized (pendingEvents) {
                pendingEvents.add(event);
            }
        }
    }

    private synchronized Collection<Data> getAndClearPendingData() {
        Collection<Data> result = new ArrayList<>(pendingData);
        pendingData.clear();
        return result;
    }

    private synchronized Collection<Event> getAndClearPendingEvents() {
        Collection<Event> result = new ArrayList<>(pendingEvents);
        pendingEvents.clear();
        return result;
    }

    private class RulesInvoker extends TimerTask {
        @Override
        public void run() {
            int numTimeouts = checkPendingTimeouts();

            if (!pendingData.isEmpty() || !pendingEvents.isEmpty() || numTimeouts > 0) {
                Collection<Data> newData = getAndClearPendingData();
                Collection<Event> newEvents = getAndClearPendingEvents();

                if (log.isDebugEnabled()) {
                    log.debug("Executing rules engine on " + newData.size() + " datums, "
                            + newEvents.size() + " events and "
                            + numTimeouts +" dampening timeouts.");
                }

                try {
                    if (newData.isEmpty() && newEvents.isEmpty()) {
                        rules.fireNoData();
                    } else {
                        if (!newData.isEmpty()) {
                            rules.addData(newData);
                            newData.clear();
                        }
                        if (!newEvents.isEmpty()) {
                            rules.addEvents(newEvents);
                            newEvents.clear();
                        }
                    }

                    rules.fire();
                    alertsService.addAlerts(alerts);
                    alerts.clear();
                    alertsService.persistEvents(events);
                    if (distributed) {
                        /*
                            Generated events on a node should be notified to other nodes for chained triggers
                         */
                        partitionManager.notifyEvents(events);
                    }
                    events.clear();
                    handleDisabledTriggers();
                    handleAutoResolvedTriggers();

                } catch (Exception e) {
                    e.printStackTrace();
                    if (log.isDebugEnabled()) {
                        log.debug("Error on rules processing: " + e);
                    }
                    msgLog.errorProcessingRules(e.getMessage());
                } finally {
                    alerts.clear();
                    events.clear();
                }
            }
        }

        private int checkPendingTimeouts() {
            if (pendingTimeouts.isEmpty()) {
                return 0;
            }

            long now = System.currentTimeMillis();
            Set<Dampening> timeouts = null;
            for (Dampening d : pendingTimeouts) {
                if (now < d.getTrueEvalsStartTime() + d.getEvalTimeSetting()) {
                    continue;
                }

                d.setSatisfied(true);
                try {
                    if (log.isDebugEnabled()) {
                        log.debug("Dampening Timeout Hit! " + d.toString());
                    }
                    rules.updateFact(d);
                    if (null == timeouts) {
                        timeouts = new HashSet<>();
                    }
                    timeouts.add(d);
                } catch (Exception e) {
                    log.error("Unable to update Dampening Fact on Timeout! " + d.toString(), e);
                }

            }

            if (null == timeouts) {
                return 0;
            }

            pendingTimeouts.removeAll(timeouts);
            return timeouts.size();
        }
    }

    private void handleDisabledTriggers() {
        try {
            for (Trigger t : disabledTriggers) {
                try {
                    definitions.updateTriggerEnablement(t.getTenantId(), t.getId(), false);

                } catch (Exception e) {
                    log.errorf("Failed to persist updated trigger. Could not autoDisable %s", t);
                }
            }
        } finally {
            disabledTriggers.clear();
        }
    }

    private void handleAutoResolvedTriggers() {
        try {
            for (Entry<Trigger, List<Set<ConditionEval>>> entry : autoResolvedTriggers.entrySet()) {
                Trigger t = entry.getKey();
                boolean manualReload = !t.isAutoResolveAlerts();

                // calling resolveAlertsForTrigger will result in a trigger reload (unless it fails),
                // otherwise, manually reload the trigger back into the engine (in firing mode).
                if (t.isAutoResolveAlerts()) {
                    try {
                        alertsService.resolveAlertsForTrigger(t.getTenantId(), t.getId(), "AutoResolve",
                                "Trigger AutoResolve=True", entry.getValue());
                    } catch (Exception e) {
                        manualReload = true;
                        log.errorf("Failed to resolve Alerts. Could not AutoResolve alerts for trigger %s", t);
                    }
                }

                if (manualReload) {
                    try {
                        reloadTrigger(t.getTenantId(), t.getId());
                    } catch (Exception e) {
                        log.errorf("Failed to reload AutoResolved Trigger: %s", t);
                    }
                }
            }
        } finally {
            autoResolvedTriggers.clear();
        }
    }

    /*
        Invoked when a data is added on a different node and this data should be propagated
     */
    @Override
    public void onNewData(Data data) {
        addPendingData(data);
    }

    @Override
    public void onNewData(Collection<Data> data) {
        addPendingData(data);
    }

    /*
        Invoked when an event is added on a different node and this data should be propagated
     */
    @Override
    public void onNewEvent(Event event) {
        addPendingEvent(event);
    }

    @Override
    public void onNewEvents(Collection<Event> events) {
        addPendingEvents(events);
    }

    /*
        This listener method is invoked on distributed scenarios.
        When a trigger is modified, PartitionManager detects which node holds the trigger and send the event.
        Local node is responsible to remove/reload the trigger from AlertsEngine memory.
     */
    @Override
    public void onTriggerChange(Operation operation, String tenantId, String triggerId) {
        if (log.isDebugEnabled()) {
            log.debug("Executing: " + operation + " tenantId: " + tenantId + " triggerId: " + triggerId);
        }
        switch(operation) {
            case ADD:
            case UPDATE:
                Trigger reloadTrigger = new Trigger(tenantId, triggerId, "reload-trigger");
                reloadTrigger(reloadTrigger);
                break;
            case REMOVE:
                Trigger removeTrigger = new Trigger(tenantId, triggerId, "remove-trigger");
                removeTrigger(removeTrigger);
                break;
        }
    }

    /*
        This listener method is invoked on distributed scenarios.
        When topology changes, new nodes added or removed, PartitionManager recalculate global triggers partition.
        On each node, PartitionManager invokes this method to indicate triggers should hold, and the "delta" of
        additions/removals.
        With this delta, the process of remove/reload triggers across cluster is minimized.
     */
    @Override
    public void onPartitionChange(Map<String, List<String>> partition, Map<String, List<String>> removed,
                                            Map<String, List<String>> added) {
        if (!pendingData.isEmpty() || !pendingEvents.isEmpty()) {
            if (!pendingData.isEmpty()) {
                log.warn("Pending Data onPartitionChange: " + pendingData);
            }
            if (!!pendingEvents.isEmpty()) {
                log.warn("Pending Events onPartitionChange: " + pendingData);
            }
        }
        if (log.isDebugEnabled()) {
            log.debug("Executing: PartitionChange ");
            log.debug("Local partition: " + partition);
            log.debug("Removed: " + removed);
            log.debug("Added: " + added);
        }
        /*
            Removing old triggers for this node
         */
        for (Entry<String, List<String>> entry : removed.entrySet()) {
            String tenantId = entry.getKey();
            entry.getValue().stream().forEach(triggerId -> {
                Trigger removeTrigger = new Trigger(tenantId, triggerId, "to-remove-from-alerts-engine");
                removeTrigger(removeTrigger);
            });
        }

        /*
            Reloading new triggers for this node
         */
        for (Entry<String, List<String>> entry : added.entrySet()) {
            String tenantId = entry.getKey();
            entry.getValue().stream().forEach(triggerId -> {
                reloadTrigger(tenantId, triggerId);
            });
        }
    }

    private boolean isEmpty(String s) {
        return null == s || s.trim().isEmpty();
    }

}


text:
<!DOCTYPE HTML>

		<title>Paginator - sap.ui.commons</title>

Test Page for sap.ui.commons.Paginator

Full Paginator - With 110 pages

Event Output:


text:
<?php

/**     \defgroup   geoip      Module GeoIP
 *		\brief      Module to make geoip conversions
 *		\version	$Id: modGeoIPMaxmind.class.php,v 1.5 2010/07/21 11:57:52 eldy Exp $
 */

/**
 *	\file       htdocs/includes/modules/modGeoIPMaxmind.class.php
 *	\ingroup    geoip
 *	\brief      File of geoipmaxmind module descriptor
 */

include_once(DOL_DOCUMENT_ROOT ."/includes/modules/DolibarrModules.class.php");

/**     \class      modGeoIPMaxmind
 *		\brief      Classe de description et activation du module Import
 */
class modGeoIPMaxmind extends DolibarrModules
{

	/**
	 *   \brief      Constructeur. Definit les noms, constantes et boites
	 *   \param      DB      handler d'acces base
	 */
	function modGeoIPMaxmind($DB)
	{
		$this->db = $DB ;
		$this->numero = 2900;

		// Family can be 'crm','financial','hr','projects','products','ecm','technic','other'
		// It is used to group modules in module setup page
		$this->family = "technic";
		// Module label (no space allowed), used if translation string 'ModuleXXXName' not found (where XXX is value of numeric property 'numero' of module)
		$this->name = preg_replace('/^mod/i','',get_class($this));
		// Module description, used if translation string 'ModuleXXXDesc' not found (where XXX is value of numeric property 'numero' of module)
		$this->description = "GeoIP Maxmind conversions capabilities";
		// Possible values for version are: 'development', 'experimental', 'dolibarr' or version
		$this->version = 'dolibarr';
		// Key used in llx_const table to save module status enabled/disabled (where MYMODULE is value of property name of module in uppercase)
		$this->const_name = 'MAIN_MODULE_'.strtoupper($this->name);
		// Where to store the module in setup page (0=common,1=interface,2=others,3=very specific)
		$this->special = 1;
		// Name of image file used for this module.
		// If file is in theme/yourtheme/img directory under name object_pictovalue.png, use this->picto='pictovalue'
		// If file is in module/images directory, use this->picto=DOL_URL_ROOT.'/module/images/file.png'
		$this->picto = 'globe';

		// Data directories to create when module is enabled
		$this->dirs = array("/geoipmaxmind");

		// Config pages
		$this->config_page_url = array("geoipmaxmind.php");

		// D�pendances
		$this->depends = array();
		$this->requiredby = array();
		$this->phpmin = array(4,2,0);
		$this->phpmax = array();
		$this->need_dolibarr_version = array(2,7,-1);	// Minimum version of Dolibarr required by module
		$this->need_javascript_ajax = 1;

		// Constantes
		$this->const = array();

		// Boxes
		$this->boxes = array();

		// Permissions
		$this->rights = array();
		$this->rights_class = 'geoipmaxmind';
		$r=0;
	}

	/**
	 *   \brief      Fonction appelee lors de l'activation du module. Insere en base les constantes, boites, permissions du module.
	 *               Definit egalement les repertoires de donnees a creer pour ce module.
	 */
	function init()
	{
		$sql = array();

		return $this->_init($sql);
	}

	/**
	 *    \brief      Fonction appelee lors de la desactivation d'un module.
	 *                Supprime de la base les constantes, boites et permissions du module.
	 */
	function remove()
	{
		$sql = array();

		return $this->_remove($sql);
	}
}
?>


text:
using System;
using System.Diagnostics;
using System.Globalization;
using System.Runtime.InteropServices;
using System.ComponentModel.Design;
using Microsoft.Win32;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.OLE.Interop;
using Microsoft.VisualStudio.Shell;
using VisualLocalizer.Library.Attributes;
using VisualLocalizer.Editor;
using VisualLocalizer.Library;
using VisualLocalizer.Commands;
using VisualLocalizer.Components;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.TextManager.Interop;
using VisualLocalizer.Gui;
using VisualLocalizer.Settings;
using VisualLocalizer.Library.Components;
using System.IO;

namespace VisualLocalizer {
    /// <summary>
    /// Base class for registration in host VS environment.
    /// </summary>

    [PackageRegistration(UseManagedResourcesOnly = true)]
    [DefaultRegistryRoot("Software\\Microsoft\\VisualStudio\\9.0")]

    // registers product info - name, icon, description (visible in Help/About)
    [InstalledProductRegistration(true, "#110", "#112", "1.0", IconResourceID = 400,LanguageIndependentName="Visual Localizer")]

    // necessary in order to run in hosting environment
    [ProvideLoadKey("Standard", "1.0", "Visual Localizer", "Ondrej Stumpf", 111)]

    // registers menu items
    [ProvideMenuResource(1000, 1)]

    // this GUID tells VS to load the package on startup
    [ProvideAutoLoad("{f1536ef8-92ec-443c-9ed7-fdadf150da82}")]

    // creates "Visual Localizer" output pane in "Output" window
    [ProvideOutputWindow(typeof(VisualLocalizerPackage), typeof(Guids.VisualLocalizerWindowPane), "#110", ClearWithSolution=true,InitiallyInvisible=false)]

    // registers single-view editor of ResX files
    [ProvideEditorFactory(typeof(ResXEditorFactory), 113, TrustLevel = __VSEDITORTRUSTLEVEL.ETL_AlwaysTrusted)]
    [ProvideEditorExtension(typeof(ResXEditorFactory), StringConstants.ResXExtension, 100)]
    [ProvideEditorLogicalView(typeof(ResXEditorFactory), "58F7A940-4755-4382-BCA6-ED89F035491E")]

    // registers tool window displayed on "Batch move to resources" command
    [ProvideToolWindow(typeof(BatchMoveToResourcesToolWindow),MultiInstances=false,
        Style = VsDockStyle.Tabbed, Orientation = ToolWindowOrientation.Bottom, Window = ToolWindowGuids.Outputwindow)]

    // registers tool window displayed on "Batch inline" command
    [ProvideToolWindow(typeof(BatchInlineToolWindow), MultiInstances = false,
        Style = VsDockStyle.Tabbed, Orientation = ToolWindowOrientation.Bottom, Window = ToolWindowGuids.Outputwindow)]

    // registers tool window used by the "Show references" command in ResX editor
    [ProvideToolWindow(typeof(ShowReferencesToolWindow), MultiInstances = false,
        Style = VsDockStyle.Tabbed, Orientation = ToolWindowOrientation.Bottom, Window = ToolWindowGuids.Outputwindow)]

    // registers settings (necessary in order to Import/Export settings work) - contains descriptions and names of nodes
    [ProvideProfile(typeof(GeneralSettingsManager), "VisualLocalizer", "GeneralSettings", 114, 115, false, DescriptionResourceID = 116)]
    [ProvideProfile(typeof(FilterSettingsManager), "VisualLocalizer", "FilterSettings", 117, 118, true, DescriptionResourceID = 119,
        AlternateParent = "VisualLocalizer_GeneralSettings")]
    [ProvideProfile(typeof(EditorSettingsManager), "VisualLocalizer", "Editor", 127, 128, true, DescriptionResourceID = 129,
        AlternateParent = "VisualLocalizer_GeneralSettings")]

    // registers option pages accessible in Tools/Options
    [ProvideOptionPage(typeof(FilterSettingsManager), "VisualLocalizer", "BatchToolWindows", 123, 124, false)]
    [ProvideOptionPage(typeof(EditorSettingsManager), "VisualLocalizer", "Editor", 123, 126, false)]

    [Guid("68c95c48-9295-49a0-a2ed-81da6e651374")]
    public sealed class VisualLocalizerPackage : Package,IVsInstalledProduct
    {
        internal MenuManager menuManager;
        internal EnvDTE80.DTE2 DTE;
        internal EnvDTE.UIHierarchy UIHierarchy;
        internal OleMenuCommandService menuService;

        private static VisualLocalizerPackage instance;

        /// <summary>
        /// Run once on package startup.
        /// </summary>
        protected override void Initialize() {
            instance = this;

            try {
                base.Initialize();

                ActivityLogger.Source = "Visual Localizer";
                VLOutputWindow.VisualLocalizerPane.WriteLine("Visual Localizer is being initialized...");

                InitBaseServices();

                // load settings from registry
                new GeneralSettingsManager().LoadSettingsFromStorage();

                // register handlers for menu items
                menuManager = new MenuManager();

                // register as an editor for ResX files
                RegisterEditorFactory(new ResXEditorFactory());

                VLOutputWindow.VisualLocalizerPane.WriteLine("Initialization completed");
                VLOutputWindow.General.WriteLine("Visual Localizer is up and running");
            } catch (Exception ex) {
                VLOutputWindow.VisualLocalizerPane.WriteException(ex);
                MessageBox.ShowException(ex);
            }
        }

        /// <summary>
        /// Obtains services essential for the package to work properly
        /// </summary>
        private void InitBaseServices() {
            DTE = (EnvDTE80.DTE2)GetService(typeof(EnvDTE.DTE));
            try {
                UIHierarchy = (EnvDTE.UIHierarchy)DTE.Windows.Item(EnvDTE.Constants.vsWindowKindSolutionExplorer).Object;
            } catch {
                UIHierarchy = null;
            }

            menuService = (OleMenuCommandService)GetService(typeof(IMenuCommandService));

            if (DTE == null || menuService == null)
                throw new Exception("Error during initialization of base services.");
        }

        /// <summary>
        /// Returns instance of this package
        /// </summary>
        public static VisualLocalizerPackage Instance {
            get {
                return instance;
            }
        }

        private static VS_VERSION? version = null;

        /// <summary>
        /// Returns version of hosting Visual Studio instance, calculated from registry values
        /// </summary>
        public static VS_VERSION VisualStudioVersion {
            get {
                if (!version.HasValue) {
                    IVsShell shell = (IVsShell)Package.GetGlobalService(typeof(SVsShell));
                    object o;
                    int hr = shell.GetProperty((int)__VSSPROPID2.VSSPROPID_SqmRegistryRoot, out o);
                    Marshal.ThrowExceptionForHR(hr);
                    string registry = o.ToString();

                    if (registry.EndsWith("9.0\\SQM")) {
                        version = VS_VERSION.VS2008;
                    } else if (registry.EndsWith("10.0\\SQM")) {
                        version = VS_VERSION.VS2010;
                    } else if (registry.EndsWith("11.0\\SQM")) {
                        version = VS_VERSION.VS2012;
                    } else if (registry.EndsWith("12.0\\SQM")) {
                        version = VS_VERSION.VS2013;
                    } else if (registry.EndsWith("14.0\\SQM")) {
                        version = VS_VERSION.VS2015;
                    } else {
                        version = VS_VERSION.UNKNOWN;
                    }
                }
                return version.Value;
            }
        }

        #region IVsInstalledProduct

        /// <summary>
        /// Returns ID of resource containing this project's logo displayed in the splash screen
        /// </summary>
        public int IdBmpSplash(out uint pIdBmp) {
            pIdBmp = 400;
            return VSConstants.S_OK;
        }

        /// <summary>
        /// Returns ID of resource containing this project's logo displayed in the about box
        /// </summary>
        public int IdIcoLogoForAboutbox(out uint pIdIco) {
            pIdIco = 400;
            return VSConstants.S_OK;
        }

        /// <summary>
        /// Returns name of this tool, displayed in the splash screen and about box
        /// </summary>
        public int OfficialName(out string pbstrName) {
            pbstrName = "Visual Localizer";
            return VSConstants.S_OK;
        }

        /// <summary>
        /// Returns description displayed in the about box
        /// </summary>
        public int ProductDetails(out string pbstrProductDetails) {
            pbstrProductDetails = "Tool for advanced manipulation with resources.";
            return VSConstants.S_OK;
        }

        /// <summary>
        /// Returns product version
        /// </summary>
        public int ProductID(out string pbstrPID) {
            pbstrPID = "1.3.8";
            return VSConstants.S_OK;
        }

        #endregion
    }

    /// <summary>
    /// Possible versions of Visual Studio
    /// </summary>
    public enum VS_VERSION {
        /// <summary>
        /// Microsoft Visual Studio 2008
        /// </summary>
        VS2008,

        /// <summary>
        /// Microsoft Visual Studio 2010
        /// </summary>
        VS2010,

        /// <summary>
        /// Microsoft Visual Studio 2012
        /// </summary>
        VS2012,

        /// <summary>
        /// Microsoft Visual Studio 2013
        /// </summary>
        VS2013,

        /// <summary>
        /// Microsoft Visual Studio 2015
        /// </summary>
        VS2015,

        /// <summary>
        /// Not possible to determine Visual Studio version
        /// </summary>
        UNKNOWN
    }
}


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

package org.chromium.chrome.browser.preferences.privacy;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

import org.chromium.base.CommandLine;
import org.chromium.base.ContextUtils;
import org.chromium.base.VisibleForTesting;
import org.chromium.chrome.browser.ChromeSwitches;
import org.chromium.chrome.browser.device.DeviceClassManager;
import org.chromium.chrome.browser.physicalweb.PhysicalWeb;
import org.chromium.chrome.browser.preferences.PrefServiceBridge;
import org.chromium.components.minidump_uploader.util.CrashReportingPermissionManager;
import org.chromium.components.minidump_uploader.util.NetworkPermissionUtil;

/**
 * Reads, writes, and migrates preferences related to network usage and privacy.
 */
public class PrivacyPreferencesManager implements CrashReportingPermissionManager{
    static final String DEPRECATED_PREF_CRASH_DUMP_UPLOAD = "crash_dump_upload";
    static final String DEPRECATED_PREF_CRASH_DUMP_UPLOAD_NO_CELLULAR =
            "crash_dump_upload_no_cellular";
    private static final String DEPRECATED_PREF_CELLULAR_EXPERIMENT = "cellular_experiment";

    public static final String PREF_METRICS_REPORTING = "metrics_reporting";
    private static final String PREF_METRICS_IN_SAMPLE = "in_metrics_sample";
    private static final String PREF_NETWORK_PREDICTIONS = "network_predictions";
    private static final String PREF_BANDWIDTH_OLD = "prefetch_bandwidth";
    private static final String PREF_BANDWIDTH_NO_CELLULAR_OLD = "prefetch_bandwidth_no_cellular";
    private static final String ALLOW_PRERENDER_OLD = "allow_prefetch";
    private static final String PREF_PHYSICAL_WEB = "physical_web";
    private static final int PHYSICAL_WEB_OFF = 0;
    private static final int PHYSICAL_WEB_ON = 1;
    private static final int PHYSICAL_WEB_ONBOARDING = 2;

    @SuppressLint("StaticFieldLeak")
    private static PrivacyPreferencesManager sInstance;

    private final Context mContext;
    private final SharedPreferences mSharedPreferences;

    @VisibleForTesting
    PrivacyPreferencesManager(Context context) {
        mContext = context;
        mSharedPreferences = ContextUtils.getAppSharedPreferences();

        migrateUsageAndCrashPreferences();
    }

    public static PrivacyPreferencesManager getInstance() {
        if (sInstance == null) {
            sInstance = new PrivacyPreferencesManager(ContextUtils.getApplicationContext());
        }
        return sInstance;
    }

    public void migrateUsageAndCrashPreferences() {
        SharedPreferences.Editor editor = mSharedPreferences.edit();

        if (mSharedPreferences.contains(DEPRECATED_PREF_CRASH_DUMP_UPLOAD)) {
            String crashDumpNeverUpload = "crash_dump_never_upload";
            setUsageAndCrashReporting(
                    !mSharedPreferences
                             .getString(DEPRECATED_PREF_CRASH_DUMP_UPLOAD, crashDumpNeverUpload)
                             .equals(crashDumpNeverUpload));

            // Remove both this preference and the related one. If the related one is not removed
            // now, later migrations could read from it and clobber the state.
            editor.remove(DEPRECATED_PREF_CRASH_DUMP_UPLOAD);
            if (mSharedPreferences.contains(DEPRECATED_PREF_CRASH_DUMP_UPLOAD_NO_CELLULAR)) {
                editor.remove(DEPRECATED_PREF_CRASH_DUMP_UPLOAD_NO_CELLULAR);
            }
        } else if (mSharedPreferences.contains(DEPRECATED_PREF_CRASH_DUMP_UPLOAD_NO_CELLULAR)) {
            setUsageAndCrashReporting(mSharedPreferences.getBoolean(
                    DEPRECATED_PREF_CRASH_DUMP_UPLOAD_NO_CELLULAR, false));
            editor.remove(DEPRECATED_PREF_CRASH_DUMP_UPLOAD_NO_CELLULAR);
        }

        if (mSharedPreferences.contains(DEPRECATED_PREF_CELLULAR_EXPERIMENT)) {
            editor.remove(DEPRECATED_PREF_CELLULAR_EXPERIMENT);
        }
        editor.apply();
    }

    /**
     * Migrate and delete old preferences.  Note that migration has to happen in Android-specific
     * code because we need to access ALLOW_PRERENDER sharedPreference.
     * TODO(bnc) https://crbug.com/394845. This change is planned for M38. After a year or so, it
     * would be worth considering removing this migration code (also removing accessors in
     * PrefServiceBridge and pref_service_bridge), and reverting to default for users
     * who had set preferences but have not used Chrome for a year. This change would be subject to
     * privacy review.
     */
    public void migrateNetworkPredictionPreferences() {
        PrefServiceBridge prefService = PrefServiceBridge.getInstance();

        // See if PREF_NETWORK_PREDICTIONS is an old boolean value.
        boolean predictionOptionIsBoolean = false;
        try {
            mSharedPreferences.getString(PREF_NETWORK_PREDICTIONS, "");
        } catch (ClassCastException ex) {
            predictionOptionIsBoolean = true;
        }

        // Nothing to do if the user or this migration code has already set the new
        // preference.
        if (!predictionOptionIsBoolean
                && prefService.obsoleteNetworkPredictionOptionsHasUserSetting()) {
            return;
        }

        // Nothing to do if the old preferences are unset.
        if (!predictionOptionIsBoolean
                && !mSharedPreferences.contains(PREF_BANDWIDTH_OLD)
                && !mSharedPreferences.contains(PREF_BANDWIDTH_NO_CELLULAR_OLD)) {
            return;
        }

        // Migrate if the old preferences are at their default values.
        // (Note that for PREF_BANDWIDTH*, if the setting is default, then there is no way to tell
        // whether the user has set it.)
        final String prefBandwidthDefault = BandwidthType.PRERENDER_ON_WIFI.title();
        final String prefBandwidth =
                mSharedPreferences.getString(PREF_BANDWIDTH_OLD, prefBandwidthDefault);
        boolean prefBandwidthNoCellularDefault = true;
        boolean prefBandwidthNoCellular = mSharedPreferences.getBoolean(
                PREF_BANDWIDTH_NO_CELLULAR_OLD, prefBandwidthNoCellularDefault);

        if (!(prefBandwidthDefault.equals(prefBandwidth))
                || (prefBandwidthNoCellular != prefBandwidthNoCellularDefault)) {
            boolean newValue = true;
            // Observe PREF_BANDWIDTH on mobile network capable devices.
            if (isMobileNetworkCapable()) {
                if (mSharedPreferences.contains(PREF_BANDWIDTH_OLD)) {
                    BandwidthType prefetchBandwidthTypePref = BandwidthType.getBandwidthFromTitle(
                            prefBandwidth);
                    if (BandwidthType.NEVER_PRERENDER.equals(prefetchBandwidthTypePref)) {
                        newValue = false;
                    } else if (BandwidthType.PRERENDER_ON_WIFI.equals(prefetchBandwidthTypePref)) {
                        newValue = true;
                    } else if (BandwidthType.ALWAYS_PRERENDER.equals(prefetchBandwidthTypePref)) {
                        newValue = true;
                    }
                }
            // Observe PREF_BANDWIDTH_NO_CELLULAR on devices without mobile network.
            } else {
                if (mSharedPreferences.contains(PREF_BANDWIDTH_NO_CELLULAR_OLD)) {
                    if (prefBandwidthNoCellular) {
                        newValue = true;
                    } else {
                        newValue = false;
                    }
                }
            }
            // Save new value in Chrome PrefService.
            prefService.setNetworkPredictionEnabled(newValue);
        }

        // Delete old sharedPreferences.
        SharedPreferences.Editor sharedPreferencesEditor = mSharedPreferences.edit();
        // Delete PREF_BANDWIDTH and PREF_BANDWIDTH_NO_CELLULAR: just migrated these options.
        if (mSharedPreferences.contains(PREF_BANDWIDTH_OLD)) {
            sharedPreferencesEditor.remove(PREF_BANDWIDTH_OLD);
        }
        if (mSharedPreferences.contains(PREF_BANDWIDTH_NO_CELLULAR_OLD)) {
            sharedPreferencesEditor.remove(PREF_BANDWIDTH_NO_CELLULAR_OLD);
        }
        // Also delete ALLOW_PRERENDER, which was updated based on PREF_BANDWIDTH[_NO_CELLULAR] and
        // network connectivity type, therefore does not carry additional information.
        if (mSharedPreferences.contains(ALLOW_PRERENDER_OLD)) {
            sharedPreferencesEditor.remove(ALLOW_PRERENDER_OLD);
        }
        // Delete bool PREF_NETWORK_PREDICTIONS so that string values can be stored. Note that this
        // SharedPreference carries no information, because it used to be overwritten by
        // kNetworkPredictionEnabled on startup, and now it is overwritten by
        // kNetworkPredictionOptions on startup.
        if (mSharedPreferences.contains(PREF_NETWORK_PREDICTIONS)) {
            sharedPreferencesEditor.remove(PREF_NETWORK_PREDICTIONS);
        }
        sharedPreferencesEditor.apply();
    }

    protected boolean isNetworkAvailable() {
        ConnectivityManager connectivityManager =
                (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
        return (networkInfo != null && networkInfo.isConnected());
    }

    protected boolean isMobileNetworkCapable() {
        ConnectivityManager connectivityManager =
                (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
        // Android telephony team said it is OK to continue using getNetworkInfo() for our purposes.
        // We cannot use ConnectivityManager#getAllNetworks() because that one only reports enabled
        // networks. See crbug.com/532455.
        @SuppressWarnings("deprecation")
        NetworkInfo networkInfo = connectivityManager
                .getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
        return networkInfo != null;
    }

    /**
     * Checks whether prerender should be allowed and updates the preference if it is not set yet.
     * @return Whether prerendering should be allowed.
     */
    public boolean shouldPrerender() {
        if (!DeviceClassManager.enablePrerendering()) return false;
        migrateNetworkPredictionPreferences();
        return PrefServiceBridge.getInstance().canPrefetchAndPrerender();
    }

    /**
     * Sets the usage and crash reporting preference ON or OFF.
     *
     * @param enabled A boolean corresponding whether usage and crash reports uploads are allowed.
     */
    public void setUsageAndCrashReporting(boolean enabled) {
        mSharedPreferences.edit().putBoolean(PREF_METRICS_REPORTING, enabled).apply();
        syncUsageAndCrashReportingPrefs();
    }

    /**
     * Update usage and crash preferences based on Android preferences if possible in case they are
     * out of sync.
     */
    public void syncUsageAndCrashReportingPrefs() {
        if (PrefServiceBridge.isInitialized()) {
            PrefServiceBridge.getInstance().setMetricsReportingEnabled(
                    isUsageAndCrashReportingPermittedByUser());
        }
    }

    /**
     * Sets whether this client is in-sample for usage metrics and crash reporting. See
     * {@link org.chromium.chrome.browser.metrics.UmaUtils#isClientInMetricsSample} for details.
     */
    public void setClientInMetricsSample(boolean inSample) {
        mSharedPreferences.edit().putBoolean(PREF_METRICS_IN_SAMPLE, inSample).apply();
    }

    /**
     * Checks whether this client is in-sample for usage metrics and crash reporting. See
     * {@link org.chromium.chrome.browser.metrics.UmaUtils#isClientInMetricsSample} for details.
     *
     * @returns boolean Whether client is in-sample.
     */
    @Override
    public boolean isClientInMetricsSample() {
        // The default value is true to avoid sampling out crashes that occur before native code has
        // been initialized on first run. We'd rather have some extra crashes than none from that
        // time.
        return mSharedPreferences.getBoolean(PREF_METRICS_IN_SAMPLE, true);
    }

    /**
     * Checks whether uploading of crash dumps is permitted for the available network(s).
     *
     * @return whether uploading crash dumps is permitted.
     */
    @Override
    public boolean isNetworkAvailableForCrashUploads() {
        ConnectivityManager connectivityManager =
                (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
        return NetworkPermissionUtil.isNetworkUnmetered(connectivityManager);
    }

    /**
     * Checks whether uploading of usage metrics and crash dumps is currently permitted, based on
     * user consent only. This doesn't take network condition or experimental state (i.e. disabling
     * upload) into consideration. A crash dump may be retried if this check passes.
     *
     * @return whether the user has consented to reporting usage metrics and crash dumps.
     */
    @Override
    public boolean isUsageAndCrashReportingPermittedByUser() {
        return mSharedPreferences.getBoolean(PREF_METRICS_REPORTING, false);
    }

    /**
     * Check whether the command line switch is used to force uploading if at all possible. Used by
     * test devices to avoid UI manipulation.
     *
     * @return whether uploading should be enabled if at all possible.
     */
    @Override
    public boolean isUploadEnabledForTests() {
        return CommandLine.getInstance().hasSwitch(ChromeSwitches.FORCE_CRASH_DUMP_UPLOAD);
    }

    /**
     * @return Whether uploading usage metrics is currently permitted.
     */
    public boolean isMetricsUploadPermitted() {
        return isNetworkAvailable()
                && (isUsageAndCrashReportingPermittedByUser() || isUploadEnabledForTests());
    }

    /**
     * Sets the Physical Web preference, which enables background scanning for bluetooth beacons
     * and displays a notification when beacons are found.
     *
     * @param enabled A boolean indicating whether to notify on nearby beacons.
     */
    public void setPhysicalWebEnabled(boolean enabled) {
        mSharedPreferences.edit()
            .putInt(PREF_PHYSICAL_WEB, enabled ? PHYSICAL_WEB_ON : PHYSICAL_WEB_OFF)
            .apply();
        PhysicalWeb.updateScans();
    }

    /**
     * Check whether the user is still in the Physical Web onboarding flow.
     *
     * @return boolean {@code true} if onboarding is not yet complete.
     */
    public boolean isPhysicalWebOnboarding() {
        int state = mSharedPreferences.getInt(PREF_PHYSICAL_WEB, PHYSICAL_WEB_ONBOARDING);
        return (state == PHYSICAL_WEB_ONBOARDING);
    }

    /**
     * Check whether Physical Web is configured to notify on nearby beacons.
     *
     * @return boolean {@code true} if the feature is enabled.
     */
    public boolean isPhysicalWebEnabled() {
        int state = mSharedPreferences.getInt(PREF_PHYSICAL_WEB, PHYSICAL_WEB_ONBOARDING);
        return (state == PHYSICAL_WEB_ON);
    }
}


text: __author__ = 'peter.szulman@automic.com'


text:
class RummageableArtefact

  FORMATS_NOT_TO_INDEX = %W(business_support completed_transaction campaign) + Artefact::FORMATS_BY_DEFAULT_OWNING_APP["whitehall"]

  EXCEPTIONAL_SLUGS = %W(
    growthaccelerator
    technology-strategy-board
    enterprise-finance-guarantee
    manufacturing-advisory-service-mas
    research-development-tax-credit-smes
    enterprise-investment-scheme
    seed-enterprise-investment-scheme
    designing-demand
    business-mentoring-support
    start-up-loans
    new-enterprise-allowance
    helping-your-business-grow-internationally
  )

  def initialize(artefact)
    @artefact = artefact
  end

  def logger
    Rails.logger
  end

  def should_be_indexed?
    @artefact.live? && indexable_artefact?
  end

  def self.indexable_artefact?(kind, slug)
    (FORMATS_NOT_TO_INDEX.exclude?(kind) || EXCEPTIONAL_SLUGS.include?(slug))
  end

  def indexable_artefact?
    self.class.indexable_artefact?(@artefact.kind, @artefact.slug)
  end

  def submit
    return unless indexable_artefact?

    @artefact.roles.each do |role|
      search_index = SearchIndex.instance(role.tag_id)
      post(search_index)
    end
  end

  def post(search_index)
    # API requests, if they know about the single registration API, will be
    # providing the indexable_content field to update Rummager. UI requests
    # and requests from apps that don't know about single registration, will
    # not include this field
    if should_amend
      logger.info "Posting amendments to Rummager: #{artefact_link}"
      search_index.amend artefact_link, artefact_hash
    else
      logger.info "Posting document to Rummager: #{artefact_link}"
      search_index.add artefact_hash
    end
  end

  def delete
    logger.info "Deleting item from Rummager: #{artefact_link}"

    @artefact.roles.each do |role|
      search_index = SearchIndex.instance(role.tag_id)
      search_index.delete(artefact_link)
      search_index.commit
    end
  end

  def should_amend
    @artefact.indexable_content.nil?
  end

  def artefact_hash
    # This won't cope with nested values, but we don't have any of those yet
    # When we want to include additional links, this will become an issue
    rummageable_keys = %w{title description format section
      indexable_content boost_phrases organisations additional_links}

    # When amending an artefact, requests with the "link" parameter will be
    # refused, because we can't amend the link within Rummager
    rummageable_keys << "link" unless should_amend

    result = {}

    rummageable_keys.each_with_object(result) do |rummageable_key, hash|
      strip_nils = ["indexable_content", "description"].include? rummageable_key

      # Use the relevant extraction method from this class if it exists
      if respond_to? "artefact_#{rummageable_key}"
        value = __send__ "artefact_#{rummageable_key}"
      elsif @artefact.respond_to? rummageable_key
        value = @artefact.__send__ rummageable_key
      else
        next
      end

      unless (strip_nils && value.nil?)
        hash[rummageable_key] = value
      end
    end
    # travel advice fakes belonging to a section in frontend
    # this code continues the fakery so it'll display in search results
    # as belonging to the correct section
    if @artefact.kind == "travel-advice"
      result['section'] = 'foreign-travel-advice'
    end
    result
  end

  def artefact_section
    section_parts[0]
  end

  def artefact_subsection
    section_parts[1]
  end

  def artefact_format
    @artefact.kind
  end

  def artefact_title
    @artefact.name
  end

  def artefact_link
    "/#{@artefact.slug}"
  end

private
  def section_parts
    section_parts = []
    return section_parts if @artefact.sections.empty?

    if @artefact.primary_section.has_parent?
      section_parts.push(@artefact.primary_section.parent.tag_id)
    end
    section_parts.push(@artefact.primary_section.tag_id.split("/").last)
  end
end


text:
class sdl_mixer;

#endif // include guard


text:
#include <Core/Animation/DualQuaternionSkinning.hpp>

namespace Ra {
namespace Core {
namespace Animation {
void computeDQ( const Pose& pose, const Sparse& weight, DQList& DQ ) {
    CORE_ASSERT( ( pose.size() == size_t( weight.cols() ) ), "pose/weight size mismatch." );
    DQ.clear();
    DQ.resize( weight.rows(),
               DualQuaternion( Quaternion( 0, 0, 0, 0 ), Quaternion( 0, 0, 0, 0 ) ) );

    // Stores the first non-zero quaternion for each vertex.
    std::vector<uint> firstNonZero( weight.rows(), std::numeric_limits<uint>::max() );
    // Contains the converted dual quaternions from the pose
    std::vector<DualQuaternion> poseDQ( pose.size() );

    // Loop through all transforms Tj
    for ( int j = 0; j < weight.outerSize(); ++j )
    {
        poseDQ[j] = DualQuaternion( pose[j] );
        // Count how many vertices are influenced by the given transform
        const int nonZero = weight.col( j ).nonZeros();

        Sparse::InnerIterator it0( weight, j );
#pragma omp parallel for
        // This for loop is here just because OpenMP wants classic for loops.
        // Since we cannot iterate directly through the non-zero elements using the InnerIterator,
        // we initialize an InnerIterator to the first element and then we increase it nz times.
        /*
         * This crappy piece of code was done in order to avoid the critical section
         *           DQ[i] += wq;
         *
         * that was occurring when parallelizing the main for loop.
         *
         * NOTE: this could be definitely improved by using std::thread
         */
        // Loop through all vertices vi who depend on Tj

        for ( int nz = 0; nz < nonZero; ++nz )
        {
            Sparse::InnerIterator itn = it0 + Eigen::Index( nz );
            const uint i              = itn.row();
            const Scalar w            = itn.value();

            firstNonZero[i] = std::min( firstNonZero[i], uint( j ) );
            const Scalar sign =
                Ra::Core::Math::signNZ( poseDQ[j].getQ0().dot( poseDQ[firstNonZero[i]].getQ0() ) );

            const auto wq = poseDQ[j] * w * sign;
            DQ[i] += wq;
        }
    }

    // Normalize all dual quats.
#pragma omp parallel for
    for ( int i = 0; i < int( DQ.size() ); ++i )
    {
        DQ[i].normalize();
    }
}

// alternate naive version, for reference purposes.
// See Kavan , Collins, Zara and O'Sullivan, 2008
void computeDQ_naive( const Pose& pose, const Sparse& weight, DQList& DQ ) {
    CORE_ASSERT( ( pose.size() == size_t( weight.cols() ) ), "pose/weight size mismatch." );
    DQ.clear();
    DQ.resize( weight.rows(),
               DualQuaternion( Quaternion( 0, 0, 0, 0 ), Quaternion( 0, 0, 0, 0 ) ) );
    std::vector<DualQuaternion> poseDQ( pose.size() );

    // 1. Convert all transforms to DQ
#pragma omp parallel for
    for ( int j = 0; j < weight.cols(); ++j )
    {
        poseDQ[j] = DualQuaternion( pose[j] );
    }

    // 2. for all vertices, blend the dual quats.
    for ( int i = 0; i < weight.rows(); ++i )
    {
        int firstNonZero = -1;
        for ( uint j = 0; j < weight.cols(); ++j )
        {
            const Scalar& w = weight.coeff( i, j );
            if ( w == 0 ) { continue; }

            if ( firstNonZero < 0 ) { firstNonZero = j; }

            // Flip the dual quaternion sign according to the dot product with the first non-null
            // dual quat see Algorithm 2 in section 4.1 of the paper.
            Scalar sign =
                Ra::Core::Math::signNZ( poseDQ[j].getQ0().dot( poseDQ[firstNonZero].getQ0() ) );

            DQ[i] += sign * w * poseDQ[j];
        }
    }

    // 3. renormalize all dual quats.
#pragma omp parallel for
    for ( int i = 0; i < int( DQ.size() ); ++i )
    {
        DQ[i].normalize();
    }
}

void dualQuaternionSkinning( const Ra::Core::Vector3Array& input,
                             const DQList& DQ,
                             Ra::Core::Vector3Array& output ) {
    const uint size = input.size();
    CORE_ASSERT( ( size == DQ.size() ), "input/DQ size mismatch." );
    output.resize( size );
#pragma omp parallel for
    for ( int i = 0; i < int( size ); ++i )
    {
        output[i] = DQ[i].transform( input[i] );
    }
}
} // namespace Animation
} // namespace Core
} // namespace Ra


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

#include "chrome/browser/ui/app_list/app_context_menu.h"

#include "chrome/app/chrome_command_ids.h"
#include "chrome/browser/extensions/context_menu_matcher.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/extensions/extension_system.h"
#include "chrome/browser/extensions/extension_uninstall_dialog.h"
#include "chrome/browser/extensions/management_policy.h"
#include "chrome/browser/prefs/incognito_mode_prefs.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/app_list/app_context_menu_delegate.h"
#include "chrome/browser/ui/app_list/app_list_controller_delegate.h"
#include "chrome/browser/ui/browser_navigator.h"
#include "chrome/common/extensions/manifest_url_handler.h"
#include "content/public/common/context_menu_params.h"
#include "grit/chromium_strings.h"
#include "grit/generated_resources.h"
#include "ui/base/l10n/l10n_util.h"

#if defined(USE_ASH)
#include "ash/shell.h"
#endif

using extensions::Extension;

namespace app_list {

namespace {

enum CommandId {
  LAUNCH_NEW = 100,
  TOGGLE_PIN,
  CREATE_SHORTCUTS,
  OPTIONS,
  UNINSTALL,
  DETAILS,
  MENU_NEW_WINDOW,
  MENU_NEW_INCOGNITO_WINDOW,
  // Order matters in LAUNCHER_TYPE_xxxx and must match LaunchType.
  LAUNCH_TYPE_START = 200,
  LAUNCH_TYPE_PINNED_TAB = LAUNCH_TYPE_START,
  LAUNCH_TYPE_REGULAR_TAB,
  LAUNCH_TYPE_FULLSCREEN,
  LAUNCH_TYPE_WINDOW,
  LAUNCH_TYPE_LAST,
};

// ExtensionUninstaller runs the extension uninstall flow. It shows the
// extension uninstall dialog and wait for user to confirm or cancel the
// uninstall.
class ExtensionUninstaller : public ExtensionUninstallDialog::Delegate {
 public:
  ExtensionUninstaller(Profile* profile,
                       const std::string& extension_id,
                       AppListControllerDelegate* controller)
      : profile_(profile),
        app_id_(extension_id),
        controller_(controller) {
  }

  void Run() {
    const Extension* extension =
        extensions::ExtensionSystem::Get(profile_)->extension_service()->
            GetExtensionById(app_id_, true);
    if (!extension) {
      CleanUp();
      return;
    }
    controller_->OnShowExtensionPrompt();
    dialog_.reset(ExtensionUninstallDialog::Create(profile_, NULL, this));
    dialog_->ConfirmUninstall(extension);
  }

 private:
  // Overridden from ExtensionUninstallDialog::Delegate:
  virtual void ExtensionUninstallAccepted() OVERRIDE {
    ExtensionService* service =
        extensions::ExtensionSystem::Get(profile_)->extension_service();
    const Extension* extension = service->GetInstalledExtension(app_id_);
    if (extension) {
      service->UninstallExtension(app_id_,
                                  false, /* external_uninstall*/
                                  NULL);
    }
    controller_->OnCloseExtensionPrompt();
    CleanUp();
  }

  virtual void ExtensionUninstallCanceled() OVERRIDE {
    controller_->OnCloseExtensionPrompt();
    CleanUp();
  }

  void CleanUp() {
    delete this;
  }

  Profile* profile_;
  std::string app_id_;
  AppListControllerDelegate* controller_;
  scoped_ptr<ExtensionUninstallDialog> dialog_;

  DISALLOW_COPY_AND_ASSIGN(ExtensionUninstaller);
};

extensions::ExtensionPrefs::LaunchType GetExtensionLaunchType(
    Profile* profile,
    const Extension* extension) {
  ExtensionService* service =
      extensions::ExtensionSystem::Get(profile)->extension_service();
  return service->extension_prefs()->
      GetLaunchType(extension, extensions::ExtensionPrefs::LAUNCH_DEFAULT);
}

void SetExtensionLaunchType(
    Profile* profile,
    const std::string& extension_id,
    extensions::ExtensionPrefs::LaunchType launch_type) {
  ExtensionService* service =
      extensions::ExtensionSystem::Get(profile)->extension_service();
  service->extension_prefs()->SetLaunchType(extension_id, launch_type);
}

bool MenuItemHasLauncherContext(const extensions::MenuItem* item) {
  return item->contexts().Contains(extensions::MenuItem::LAUNCHER);
}

}  // namespace

AppContextMenu::AppContextMenu(AppContextMenuDelegate* delegate,
                               Profile* profile,
                               const std::string& app_id,
                               AppListControllerDelegate* controller,
                               bool is_platform_app)
    : delegate_(delegate),
      profile_(profile),
      app_id_(app_id),
      controller_(controller),
      is_platform_app_(is_platform_app) {
}

AppContextMenu::~AppContextMenu() {}

ui::MenuModel* AppContextMenu::GetMenuModel() {
  const Extension* extension = GetExtension();
  if (!extension)
    return NULL;

  if (menu_model_.get())
    return menu_model_.get();

  menu_model_.reset(new ui::SimpleMenuModel(this));

  if (app_id_ == extension_misc::kChromeAppId) {
    menu_model_->AddItemWithStringId(
        MENU_NEW_WINDOW,
        IDS_APP_LIST_NEW_WINDOW);
    if (!profile_->IsOffTheRecord()) {
      menu_model_->AddItemWithStringId(
          MENU_NEW_INCOGNITO_WINDOW,
          IDS_APP_LIST_NEW_INCOGNITO_WINDOW);
    }
  } else {
    extension_menu_items_.reset(new extensions::ContextMenuMatcher(
        profile_, this, menu_model_.get(),
        base::Bind(MenuItemHasLauncherContext)));

    if (!is_platform_app_)
      menu_model_->AddItem(LAUNCH_NEW, string16());

    int index = 0;
    extension_menu_items_->AppendExtensionItems(app_id_, string16(),
                                                &index);

    if (controller_->CanPin()) {
      menu_model_->AddSeparator(ui::NORMAL_SEPARATOR);
      menu_model_->AddItemWithStringId(
          TOGGLE_PIN,
          controller_->IsAppPinned(app_id_) ?
              IDS_APP_LIST_CONTEXT_MENU_UNPIN :
              IDS_APP_LIST_CONTEXT_MENU_PIN);
    }

    if (controller_->CanDoCreateShortcutsFlow(is_platform_app_)) {
      menu_model_->AddItemWithStringId(CREATE_SHORTCUTS,
                                       IDS_NEW_TAB_APP_CREATE_SHORTCUT);
    }

    if (!is_platform_app_) {
      menu_model_->AddSeparator(ui::NORMAL_SEPARATOR);
      menu_model_->AddCheckItemWithStringId(
          LAUNCH_TYPE_REGULAR_TAB,
          IDS_APP_CONTEXT_MENU_OPEN_REGULAR);
      menu_model_->AddCheckItemWithStringId(
          LAUNCH_TYPE_PINNED_TAB,
          IDS_APP_CONTEXT_MENU_OPEN_PINNED);
#if defined(USE_ASH)
      if (!ash::Shell::IsForcedMaximizeMode())
#endif
      {
#if defined(OS_MACOSX)
        // Mac does not support standalone web app browser windows or maximize.
        menu_model_->AddCheckItemWithStringId(
            LAUNCH_TYPE_FULLSCREEN,
            IDS_APP_CONTEXT_MENU_OPEN_FULLSCREEN);
#else
        menu_model_->AddCheckItemWithStringId(
            LAUNCH_TYPE_WINDOW,
            IDS_APP_CONTEXT_MENU_OPEN_WINDOW);
        // Even though the launch type is Full Screen it is more accurately
        // described as Maximized in Ash.
        menu_model_->AddCheckItemWithStringId(
            LAUNCH_TYPE_FULLSCREEN,
            IDS_APP_CONTEXT_MENU_OPEN_MAXIMIZED);
#endif
      }
      menu_model_->AddSeparator(ui::NORMAL_SEPARATOR);
      menu_model_->AddItemWithStringId(OPTIONS, IDS_NEW_TAB_APP_OPTIONS);
    }

    menu_model_->AddItemWithStringId(DETAILS, IDS_NEW_TAB_APP_DETAILS);
    menu_model_->AddItemWithStringId(
        UNINSTALL,
        is_platform_app_ ? IDS_APP_LIST_UNINSTALL_ITEM
                         : IDS_EXTENSIONS_UNINSTALL);
  }

  return menu_model_.get();
}

const Extension* AppContextMenu::GetExtension() const {
  const ExtensionService* service =
      extensions::ExtensionSystem::Get(profile_)->extension_service();
  const Extension* extension = service->GetInstalledExtension(app_id_);
  return extension;
}

void AppContextMenu::ShowExtensionOptions() {
  const Extension* extension = GetExtension();
  if (!extension)
    return;

  chrome::NavigateParams params(
      profile_,
      extensions::ManifestURL::GetOptionsPage(extension),
      content::PAGE_TRANSITION_LINK);
  chrome::Navigate(&params);
}

void AppContextMenu::ShowExtensionDetails() {
  const Extension* extension = GetExtension();
  if (!extension)
    return;

  chrome::NavigateParams params(
      profile_,
      extensions::ManifestURL::GetDetailsURL(extension),
      content::PAGE_TRANSITION_LINK);
  chrome::Navigate(&params);
}

void AppContextMenu::StartExtensionUninstall() {
  // ExtensionUninstall deletes itself when done or aborted.
  ExtensionUninstaller* uninstaller = new ExtensionUninstaller(profile_,
                                                               app_id_,
                                                               controller_);
  uninstaller->Run();
}

bool AppContextMenu::IsItemForCommandIdDynamic(int command_id) const {
  return command_id == TOGGLE_PIN || command_id == LAUNCH_NEW;
}

string16 AppContextMenu::GetLabelForCommandId(int command_id) const {
  if (command_id == TOGGLE_PIN) {
    return controller_->IsAppPinned(app_id_) ?
        l10n_util::GetStringUTF16(IDS_APP_LIST_CONTEXT_MENU_UNPIN) :
        l10n_util::GetStringUTF16(IDS_APP_LIST_CONTEXT_MENU_PIN);
  } else if (command_id == LAUNCH_NEW) {
    if (IsCommandIdChecked(LAUNCH_TYPE_PINNED_TAB) ||
        IsCommandIdChecked(LAUNCH_TYPE_REGULAR_TAB)) {
      return l10n_util::GetStringUTF16(IDS_APP_LIST_CONTEXT_MENU_NEW_TAB);
    } else {
      return l10n_util::GetStringUTF16(IDS_APP_LIST_CONTEXT_MENU_NEW_WINDOW);
    }
  } else {
    NOTREACHED();
    return string16();
  }
}

bool AppContextMenu::IsCommandIdChecked(int command_id) const {
  if (command_id >= LAUNCH_TYPE_START && command_id < LAUNCH_TYPE_LAST) {
    return static_cast<int>(GetExtensionLaunchType(profile_, GetExtension())) +
        LAUNCH_TYPE_START == command_id;
  } else if (command_id >= IDC_EXTENSIONS_CONTEXT_CUSTOM_FIRST &&
             command_id <= IDC_EXTENSIONS_CONTEXT_CUSTOM_LAST) {
    return extension_menu_items_->IsCommandIdChecked(command_id);
  }
  return false;
}

bool AppContextMenu::IsCommandIdEnabled(int command_id) const {
  if (command_id == TOGGLE_PIN) {
    return controller_->CanPin();
  } else if (command_id == OPTIONS) {
    const ExtensionService* service =
        extensions::ExtensionSystem::Get(profile_)->extension_service();
    const Extension* extension = GetExtension();
    return service->IsExtensionEnabledForLauncher(app_id_) &&
           extension &&
           !extensions::ManifestURL::GetOptionsPage(extension).is_empty();
  } else if (command_id == UNINSTALL) {
    const Extension* extension = GetExtension();
    const extensions::ManagementPolicy* policy =
        extensions::ExtensionSystem::Get(profile_)->management_policy();
    return extension &&
           policy->UserMayModifySettings(extension, NULL);
  } else if (command_id == DETAILS) {
    const Extension* extension = GetExtension();
    return extension && extension->from_webstore();
  } else if (command_id >= IDC_EXTENSIONS_CONTEXT_CUSTOM_FIRST &&
             command_id <= IDC_EXTENSIONS_CONTEXT_CUSTOM_LAST) {
    return extension_menu_items_->IsCommandIdEnabled(command_id);
  } else if (command_id == MENU_NEW_WINDOW) {
    // "Normal" windows are not allowed when incognito is enforced.
    return IncognitoModePrefs::GetAvailability(profile_->GetPrefs()) !=
        IncognitoModePrefs::FORCED;
  } else if (command_id == MENU_NEW_INCOGNITO_WINDOW) {
    // Incognito windows are not allowed when incognito is disabled.
    return IncognitoModePrefs::GetAvailability(profile_->GetPrefs()) !=
        IncognitoModePrefs::DISABLED;
  }
  return true;
}

bool AppContextMenu::GetAcceleratorForCommandId(
    int command_id,
    ui::Accelerator* acclelrator) {
  return false;
}

void AppContextMenu::ExecuteCommand(int command_id, int event_flags) {
  if (command_id == LAUNCH_NEW) {
    delegate_->ExecuteLaunchCommand(event_flags);
  } else if (command_id == TOGGLE_PIN && controller_->CanPin()) {
    if (controller_->IsAppPinned(app_id_))
      controller_->UnpinApp(app_id_);
    else
      controller_->PinApp(app_id_);
  } else if (command_id == CREATE_SHORTCUTS) {
    controller_->DoCreateShortcutsFlow(profile_, app_id_);
  } else if (command_id >= LAUNCH_TYPE_START &&
             command_id < LAUNCH_TYPE_LAST) {
    SetExtensionLaunchType(profile_,
                           app_id_,
                           static_cast<extensions::ExtensionPrefs::LaunchType>(
                               command_id - LAUNCH_TYPE_START));
  } else if (command_id == OPTIONS) {
    ShowExtensionOptions();
  } else if (command_id == UNINSTALL) {
    StartExtensionUninstall();
  } else if (command_id == DETAILS) {
    ShowExtensionDetails();
  } else if (command_id >= IDC_EXTENSIONS_CONTEXT_CUSTOM_FIRST &&
             command_id <= IDC_EXTENSIONS_CONTEXT_CUSTOM_LAST) {
    extension_menu_items_->ExecuteCommand(command_id, NULL,
                                          content::ContextMenuParams());
  } else if (command_id == MENU_NEW_WINDOW) {
    controller_->CreateNewWindow(profile_, false);
  } else if (command_id == MENU_NEW_INCOGNITO_WINDOW) {
    controller_->CreateNewWindow(profile_, true);
  }
}

}  // namespace app_list


text:
package gowrapmx4j

import "testing"

func TestMetricSet(t *testing.T) {

	//func NewMX4JMetric(hname, objname, format, attr string) MX4JMetric {
	mm := NewMX4JMetric("NodeStatus", "org.apache.cassandra.net:type=FailureDetector", "map", "SimpleStates")
	RegistrySet(mm, nil)

	if len(registry) != 1 {
		t.Errorf("Registry was not updated")
	}

	metrics := RegistryGetAll()
	if len(metrics) != 1 {
		t.Errorf("Not all metrics returned")
	}
}

func TestMultiMetricSet(t *testing.T) {

	//func NewMX4JMetric(hname, objname, format, attr string) MX4JMetric {
	mm := NewMX4JMetric("NodeStatus", "org.apache.cassandra.net:type=FailureDetector", "map", "SimpleStates")
	RegistrySet(mm, nil)
	RegistrySet(mm, nil)
	RegistrySet(mm, nil)
	RegistrySet(mm, nil)

	if len(registry) != 1 {
		t.Errorf("Registry was not updated")
	}

	metrics := RegistryGetAll()
	if len(metrics) != 1 {
		t.Errorf("Not all metrics returned")
	}
	RegistrySet(mm, nil)
	RegistrySet(mm, nil)

	metrics = RegistryGetAll()
	if len(metrics) != 1 {
		t.Errorf("Not all metrics returned")
	}
}

func TestMultiMetricGet(t *testing.T) {

	//func NewMX4JMetric(hname, objname, format, attr string) MX4JMetric {
	mm := NewMX4JMetric("NodeStatus", "org.apache.cassandra.net:type=FailureDetector", "map", "SimpleStates")
	RegistrySet(mm, nil)

	hname := "NodeStatus"
	m := RegistryGet(hname)
	/*
		if m == nil {
			t.Errorf("%s not found in registry", hname)
		}
	*/
	//fmt.Printf("%#v\n", m)
	if m.HumanName != hname {
		t.Errorf("Wrong retristry metric returned")
	}
}


text:
import * as Preact from '#preact';
import {
  Alignment,
  Axis,
  Orientation,
  getDimension,
  getOffsetPosition,
  getScrollEnd,
} from './dimensions';
import {Arrow} from './arrow';
import {CarouselContext} from './carousel-context';
import {ContainWrapper} from '#preact/component';
import {Scroller} from './scroller';
import {WithAmpContext} from '#preact/context';
import {forwardRef, toChildArray} from '#preact/compat';
import {isRTL} from '#core/dom';
import {sequentialIdGenerator} from '#core/data-structures/id-generator';
import {toWin} from '#core/window';
import {
  cloneElement,
  useCallback,
  useContext,
  useEffect,
  useImperativeHandle,
  useLayoutEffect,
  useMemo,
  useRef,
  useState,
} from '#preact';
import {useStyles} from './component.jss';
import {mod} from '#core/math';

/**
 * @enum {string}
 */
const Controls = {
  ALWAYS: 'always',
  NEVER: 'never',
  AUTO: 'auto',
};

/**
 * @enum {string}
 */
const Interaction = {
  GENERIC: 0,
  FOCUS: 1,
  MOUSE: 2,
  TOUCH: 3,
  NONE: 4,
};

/**
 * @enum {string}
 */
const Direction = {
  LTR: 'ltr',
  RTL: 'rtl',
  AUTO: 'auto',
};

const MIN_AUTO_ADVANCE_INTERVAL = 1000;

const generateCarouselKey = sequentialIdGenerator();

/**
 * @param {!BaseCarouselDef.Props} props
 * @param {{current: ?BaseCarouselDef.CarouselApi}} ref
 * @return {PreactDef.Renderable}
 */
function BentoBaseCarouselWithRef(
  {
    advanceCount = 1,
    arrowPrevAs,
    arrowNextAs,
    autoAdvance: shouldAutoAdvance = false,
    autoAdvanceCount = 1,
    autoAdvanceInterval: customAutoAdvanceInterval = MIN_AUTO_ADVANCE_INTERVAL,
    autoAdvanceLoops = Number.POSITIVE_INFINITY,
    children,
    controls = Controls.AUTO,
    defaultSlide = 0,
    dir = Direction.AUTO,
    lightbox = false,
    loop,
    mixedLength = false,
    onClick,
    onFocus,
    onMouseEnter,
    onSlideChange,
    onTouchStart,
    orientation = Orientation.HORIZONTAL,
    outsetArrows = false,
    snap = true,
    snapAlign = Alignment.START,
    snapBy = 1,
    visibleCount = 1,
    _thumbnails = false,
    ...rest
  },
  ref
) {
  const classes = useStyles();
  const childrenArray = useMemo(() => toChildArray(children), [children]);
  const {length} = childrenArray;
  const carouselContext = useContext(CarouselContext);
  const [currentSlideState, setCurrentSlideState] = useState(
    Math.min(Math.max(defaultSlide, 0), length)
  );
  const globalCurrentSlide = carouselContext.currentSlide ?? currentSlideState;
  const setGlobalCurrentSlide =
    carouselContext.setCurrentSlide ?? setCurrentSlideState;
  const currentSlide = _thumbnails ? currentSlideState : globalCurrentSlide;
  const setCurrentSlide = _thumbnails
    ? setCurrentSlideState
    : setGlobalCurrentSlide;
  const currentSlideRef = useRef(currentSlide);
  const axis = orientation == Orientation.HORIZONTAL ? Axis.X : Axis.Y;
  const [id] = useState(generateCarouselKey);

  useLayoutEffect(() => {
    // noop if !_thumbnails || !carouselContext.
    setCurrentSlide(globalCurrentSlide);
  }, [globalCurrentSlide, setCurrentSlide]);

  const {setSlides, slides} = carouselContext;

  const scrollRef = useRef(null);
  const containRef = useRef(null);
  const contentRef = useRef(null);

  const autoAdvanceTimesRef = useRef(0);
  const autoAdvanceInterval = useMemo(
    () => Math.max(customAutoAdvanceInterval, MIN_AUTO_ADVANCE_INTERVAL),
    [customAutoAdvanceInterval]
  );

  const autoAdvance = useCallback(() => {
    if (
      autoAdvanceTimesRef.current + visibleCount / length >= autoAdvanceLoops ||
      interaction.current !== Interaction.NONE
    ) {
      return false;
    }
    if (loop || currentSlideRef.current + visibleCount < length) {
      scrollRef.current.advance(autoAdvanceCount); // Advance forward by specified count
      // Count autoadvance loops as proportions of the carousel we have advanced through.
      autoAdvanceTimesRef.current += autoAdvanceCount / length;
    } else {
      scrollRef.current.advance(-currentSlideRef.current); // Advance in reverse to first slide
      autoAdvanceTimesRef.current = Math.ceil(autoAdvanceTimesRef.current);
    }
    return true;
  }, [autoAdvanceCount, autoAdvanceLoops, length, loop, visibleCount]);
  const next = useCallback(() => scrollRef.current.next(), []);
  const prev = useCallback(() => scrollRef.current.prev(), []);

  useEffect(() => {
    if (!shouldAutoAdvance || !containRef.current) {
      return;
    }
    const win = toWin(containRef.current.ownerDocument.defaultView);
    const interval = win.setInterval(() => {
      const autoAdvanced = autoAdvance();
      if (!autoAdvanced) {
        win.clearInterval(interval);
      }
    }, autoAdvanceInterval);
    return () => win.clearInterval(interval);
  }, [autoAdvance, autoAdvanceInterval, shouldAutoAdvance]);

  const setRestingIndex = useCallback(
    (index) => {
      if (length <= 0 || isNaN(index)) {
        return;
      }
      index = loop
        ? mod(index, length)
        : Math.min(Math.max(index, 0), length - 1);
      setCurrentSlide(index);
      if (currentSlideRef.current !== index) {
        currentSlideRef.current = index;
        if (onSlideChange) {
          onSlideChange(index);
        }
      }
    },
    [length, loop, setCurrentSlide, onSlideChange]
  );

  useImperativeHandle(
    ref,
    () =>
      /** @type {!BaseCarouselDef.CarouselApi} */ ({
        goToSlide: (index) => {
          interaction.current = Interaction.GENERIC;
          setRestingIndex(index);
        },
        next: () => {
          interaction.current = Interaction.GENERIC;
          next();
        },
        prev: () => {
          interaction.current = Interaction.GENERIC;
          prev();
        },
        get root() {
          return containRef.current;
        },
        get node() {
          return contentRef.current;
        },
      }),
    [next, prev, setRestingIndex]
  );

  useEffect(() => {
    // For now, do not update slides if they are the same length as before.
    // Otherwise this causes an infinite loop when updating the AMP Context.
    if (!_thumbnails && slides && slides.length !== childrenArray.length) {
      setSlides(childrenArray);
    }
  }, [_thumbnails, childrenArray, setSlides, slides]);

  const disableForDir = (dir) => {
    if (loop) {
      // Arrows always available when looping.
      return false;
    }
    if (currentSlide + dir < 0) {
      // Can no longer advance backwards.
      return true;
    }
    if (currentSlide + visibleCount + dir > length) {
      // Can no longer advance forwards.
      return true;
    }
    if (mixedLength && dir > 0) {
      // Measure container to see if we have reached the end.
      if (!scrollRef.current) {
        return false;
      }
      const container = scrollRef.current.node;
      if (!container || !container.children.length) {
        return false;
      }
      const scrollEnd = getScrollEnd(axis, container);
      const scrollStart = getOffsetPosition(
        axis,
        container.children[currentSlide]
      );
      const {length} = getDimension(axis, container);
      if (length !== scrollEnd && length + scrollStart >= scrollEnd) {
        // Can no longer scroll forwards.
        return true;
      }
    }
    return false;
  };

  const interaction = useRef(Interaction.NONE);
  const hideControls = useMemo(() => {
    if (controls === Controls.ALWAYS || outsetArrows) {
      return false;
    }
    if (controls === Controls.NEVER) {
      return true;
    }
    return interaction.current === Interaction.TOUCH;
  }, [controls, outsetArrows]);

  const [rtl, setRtl] = useState(dir === Direction.RTL);
  useLayoutEffect(() => {
    if (!containRef.current || dir !== Direction.AUTO) {
      return;
    }
    const doc = containRef.current.ownerDocument;
    if (!doc) {
      return;
    }
    setRtl(isRTL(doc));
  }, [dir, setRtl]);

  return (
    <ContainWrapper
      size={true}
      layout={true}
      paint={true}
      contentStyle={{
        display: 'flex',
        direction: rtl ? Direction.RTL : Direction.LTR,
      }}
      ref={containRef}
      onFocus={(e) => {
        if (onFocus) {
          onFocus(e);
        }
        interaction.current = Interaction.FOCUS;
      }}
      onMouseEnter={(e) => {
        if (onMouseEnter) {
          onMouseEnter(e);
        }
        interaction.current = Interaction.MOUSE;
      }}
      onTouchStart={(e) => {
        if (onTouchStart) {
          onTouchStart(e);
        }
        interaction.current = Interaction.TOUCH;
      }}
      tabIndex="0"
      wrapperClassName={classes.carousel}
      contentRef={contentRef}
      {...rest}
    >
      {!hideControls && (
        <Arrow
          advance={prev}
          as={arrowPrevAs}
          by={-advanceCount}
          disabled={disableForDir(-1)}
          outsetArrows={outsetArrows}
          rtl={rtl}
        />
      )}
      <Scroller
        advanceCount={advanceCount}
        alignment={snapAlign}
        axis={axis}
        lightboxGroup={lightbox && 'carousel' + id}
        loop={loop}
        mixedLength={mixedLength}
        onClick={onClick}
        restingIndex={currentSlide}
        setRestingIndex={setRestingIndex}
        snap={snap}
        snapBy={snapBy}
        ref={scrollRef}
        visibleCount={mixedLength ? 1 : visibleCount}
        _thumbnails={_thumbnails}
      >
        {childrenArray.map((child, index) => {
          const {alt, 'aria-label': ariaLabel} = child.props;
          return (
            <WithAmpContext
              caption={alt || ariaLabel}
              key={index}
              renderable={index == currentSlide}
              playable={index == currentSlide}
            >
              {cloneElement(child, {...child.props, thumbnailSrc: undefined})}
            </WithAmpContext>
          );
        })}
      </Scroller>
      {!hideControls && (
        <Arrow
          advance={next}
          by={advanceCount}
          as={arrowNextAs}
          disabled={disableForDir(1)}
          outsetArrows={outsetArrows}
          rtl={rtl}
        />
      )}
    </ContainWrapper>
  );
}

const BentoBaseCarousel = forwardRef(BentoBaseCarouselWithRef);
BentoBaseCarousel.displayName = 'BentoBaseCarousel'; // Make findable for tests.
export {BentoBaseCarousel};