text:
package sqmf.impl;

import com.google.common.util.concurrent.Futures;
import edu.uci.ics.jung.algorithms.shortestpath.DijkstraShortestPath;
import org.jgrapht.GraphPath;
import org.jgrapht.alg.shortestpath.KShortestPaths;
import org.opendaylight.controller.md.sal.binding.api.DataBroker;
import org.opendaylight.controller.sal.binding.api.BindingAwareBroker;
import org.opendaylight.controller.sal.binding.api.NotificationProviderService;
import org.opendaylight.controller.sal.binding.api.RpcProviderRegistry;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.sqmf.rev141210.SqmfService;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.sqmf.rev141210.StartMonitoringLinksInput;
import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NodeId;
import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Link;
import org.opendaylight.yangtools.yang.common.RpcResult;
import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.awt.*;
import java.util.*;
import java.util.List;
import java.util.concurrent.Future;
//import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.sqmf.rev141210.StartFailoverInput;
//import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.sqmf.rev141210.StartFailoverInput;

/**
 * The core class of the implementation.
 *
 * @author Marievi Xezonaki
 */
public class SqmfImplementation implements SqmfService {

    private static final Logger LOG = LoggerFactory.getLogger(SqmfImplementation.class);

    private static HashMap<String, Integer> inputPorts = new HashMap<>();
    private static HashMap<String, Integer> outputPorts = new HashMap<>();
    private static HashMap<String, Integer> failoverPorts = new HashMap<>();
    private static DataBroker db;
    private static String srcMacForDelayMeasuring = "00:00:00:00:00:03";
    public static String srcNode = null;
    public static String dstNode = null;
    private static RpcProviderRegistry rpcProviderRegistry;
    private NotificationProviderService notificationService;
    public static GraphPath<Integer, DomainLink> mainGraphWalk = null, failoverGraphWalk = null;
    public static double QoEThreshold;
    private static Timer timer;
    private static MonitorLinksTask monitorLinksTask;
    public static boolean fastFailover = false;
    public static String applicationType = "";
    private String videoAbsolutePath;
    private int videoCase = 0;
    private static HashMap<String, Integer> inputPortsFailover = new HashMap<>();
    private static HashMap<String, Integer> outputPortsFailover = new HashMap<>();
    private DijkstraShortestPath<NodeId, Link> shortestPath = null;
    private BindingAwareBroker.ProviderContext session;

    /**
     * The constructor method.
     *
     */
    public SqmfImplementation(BindingAwareBroker.ProviderContext session, DataBroker db, RpcProviderRegistry rpcProviderRegistry, NotificationProviderService notificationService) {
        this.db = db;
        this.session = session;
        this.rpcProviderRegistry = rpcProviderRegistry;
        this.notificationService = notificationService;
    }

    /**
     * The method which starts monitoring the packet loss and delay of links, when the user asks it.
     *
     * @param input     The input of the RPC, containing the source node, the destination node, the QoE threshold and the application type (VoIP or video).
     */
    @Override
    public Future<RpcResult<Void>> startMonitoringLinks(StartMonitoringLinksInput input) {

        //read user input
        if (input != null){
            if (input.getSrcNode() != null && input.getDstNode() != null && input.getQoEThreshold() != null && input.getApplication() != null){
                srcNode = input.getSrcNode();
                dstNode = input.getDstNode();
                try {
                    Float QoE = Float.parseFloat(input.getQoEThreshold());
                    QoEThreshold = QoE.doubleValue();
                }
                catch (NumberFormatException e){
                    LOG.info("Wrong number format for QoE threshold, try again.");
                    return Futures.immediateFuture(RpcResultBuilder.<Void>success().build());
                }
                applicationType = input.getApplication().getName();
            }
        }
        else{
            LOG.info("A field of the input is empty, try again.");
            return Futures.immediateFuture(RpcResultBuilder.<Void>success().build());
        }

        // if the application type is video, launch a file chooser to select a video file to be streamed
        if (applicationType.equals(UDPVideo.getName())){
            FileDialog dialog = new FileDialog((Frame)null, "Select File to Open");
            dialog.setMode(FileDialog.LOAD);
            dialog.setVisible(true);
            videoAbsolutePath = dialog.getDirectory() + dialog.getFile();
            videoCase = findVideoCase(videoAbsolutePath);
            if (videoCase == 0){
                LOG.info("Video required specifications not met, choose another video.");
                return Futures.immediateFuture(RpcResultBuilder.<Void>success().build());
            }
        }

        //first, add rules to ingress and egress nodes to forward their packets to controller
        if (NetworkGraph.getInstance().getGraphNodes() != null && NetworkGraph.getInstance().getGraphLinks() != null) {
            Hashtable<String, DomainNode> domainNodes = NetworkGraph.getInstance().getDomainNodes();
            DomainNode sourceNode = domainNodes.get(srcNode);
            DomainNode destNode = domainNodes.get(dstNode);

            //check if the given switches are edge switches, therefore connected to hosts
            if (!checkIfEdgeSwitches(sourceNode, destNode)){
                LOG.info("Not edge switches given, returning...");
                return Futures.immediateFuture(RpcResultBuilder.<Void>success().build());
            }

            List<GraphPath<Integer, DomainLink>> possiblePaths = createPaths(NetworkGraph.getInstance(), sourceNode.getNodeID(), destNode.getNodeID());
            if (possiblePaths.size() > 1) {
                GraphPath<Integer, DomainLink> mainPath = possiblePaths.get(0);
                GraphPath<Integer, DomainLink> failoverPath = possiblePaths.get(1);

                //determine main and failover path
                mainGraphWalk = mainPath;
                failoverGraphWalk = failoverPath;
                findPorts(mainGraphWalk, sourceNode, destNode);

                //register packet processing listener
                PacketProcessing packetProcessingListener = new PacketProcessing(srcNode, dstNode, srcMacForDelayMeasuring);
                if (notificationService != null) {
                    notificationService.registerNotificationListener(packetProcessingListener);
                }
                SwitchConfigurator switchConfigurator = new SwitchConfigurator(db);
                //configure ingress and egress switches to send their packets to controller (for packet loss monitoring)
                switchConfigurator.configureIngressAndEgressForMonitoring(srcNode, dstNode, inputPorts, outputPorts);
                /* then, add rules to all nodes of both main and failover path to forward packets
                   with specific MAC to controller (for delay monitoring) */
                switchConfigurator.configureNodesForDelayMonitoring(mainGraphWalk.getEdgeList(), srcMacForDelayMeasuring);
                switchConfigurator.configureNodesForDelayMonitoring(failoverGraphWalk.getEdgeList(), srcMacForDelayMeasuring);
                switchConfigurator.configureNodesForUDPTrafficForwarding(mainGraphWalk.getEdgeList(), inputPorts, outputPorts);
            }
        }
        else{
            return Futures.immediateFuture(RpcResultBuilder.<Void>success().build());
        }

        //finally, start monitoring links
        timer = new Timer();
        monitorLinksTask = new MonitorLinksTask(db, rpcProviderRegistry, srcMacForDelayMeasuring, videoAbsolutePath, UDPVideo.getVideoFPS(videoAbsolutePath), videoCase);
        timer.schedule(monitorLinksTask, 0, 5000);

        return Futures.immediateFuture(RpcResultBuilder.<Void>success().build());
    }

    /**
     * The method which initializes the failover procedure.
     *
     * @param videoAbsolutePath     The video's absolute path in the file system.
     * @return                      An integer denoting the video characteristics case.
     */
    public int findVideoCase(String videoAbsolutePath){

        //check what category video belongs to
        int keyFrame = UDPVideo.getKeyFrame(videoAbsolutePath);
        System.out.println("The video has key frame: " + keyFrame);
        String codec = UDPVideo.getVideoCodec(videoAbsolutePath);
        System.out.println("The video has codec: " + codec);
        String format = UDPVideo.getVideoFormat(videoAbsolutePath);
        System.out.println("The video has format: " + format);

        if ((keyFrame == -1) || (codec == null) || (format == null)){
            return 0;
        }
        if ((keyFrame == 1) && codec.equals("h264") && format.equals("640x480")){
            return 5;
        }
        if ((keyFrame == 1) && codec.equals("mpeg4") && format.equals("640x480")){
            return 4;
        }
        if ((keyFrame == 1) && codec.equals("mpeg2") && format.equals("640x480")){
            return 3;
        }
        if ((keyFrame == 1) && codec.equals("mpeg4") && format.equals("160x120")){
            return 2;
        }
        if ((keyFrame == 1) && codec.equals("mpeg4") && format.equals("320x240")){
            return 1;
        }
        return 0;
    }

    /**
     * The method which changes the main with the failover path in case the QoE threshold is not met. This way,
     * packets start being forwarded to the failover path for better QoE.
     *
     */
    public static void changePath(){

        GraphPath<Integer, DomainLink> temp = mainGraphWalk;
        mainGraphWalk = failoverGraphWalk;
        failoverGraphWalk = temp;

        MonitorLinksTask.isFailover = true;

        if (NetworkGraph.getInstance().getGraphNodes() != null && NetworkGraph.getInstance().getGraphLinks() != null) {
            Hashtable<String, DomainNode> domainNodes = NetworkGraph.getInstance().getDomainNodes();
            findPorts(mainGraphWalk, domainNodes.get(srcNode), domainNodes.get(dstNode));
            SwitchConfigurator switchConfigurator = new SwitchConfigurator(db);
            switchConfigurator.configureIngressAndEgressForMonitoring(srcNode, dstNode, inputPorts, outputPorts);
            switchConfigurator.configureNodesForUDPTrafficForwarding(mainGraphWalk.getEdgeList(), inputPorts, outputPorts);
        }

    }

    /**
     * The method which stops the timer task monitoring the links.
     *
     */
    @Override
    public Future<RpcResult<Void>> stopMonitoringLinks() {
        System.out.println("Stopping the monitoring of links.");
        if (monitorLinksTask != null) {
            monitorLinksTask.cancel();
        }
        if (timer != null) {
            timer.cancel();
            timer.purge();
        }

        return Futures.immediateFuture(RpcResultBuilder.<Void>success().build());
    }

    /**
     * The method which checks if both given nodes are edge nodes.
     *
     * @param sourceNode    The source node given by the user.
     * @param destNode      The destination node given by the user.
     * @return              It returns true if both given nodes are edge nodes and false if either of them is not.
     */
    private boolean checkIfEdgeSwitches(DomainNode sourceNode, DomainNode destNode){
        List<Link> graphLinks = NetworkGraph.getInstance().getGraphLinks();
        Boolean isSourceEdge = false, isDestEdge = false;

        System.out.println("Source " + sourceNode.getODLNodeID() + " dest " + destNode.getODLNodeID());
        //check if graph links containing "host" also contain the source or destination node
        for (Link graphLink : graphLinks){
            System.out.println(graphLink.getLinkId().getValue());
            if (graphLink.getLinkId().getValue().contains("host")){
                if (graphLink.getLinkId().getValue().contains(destNode.getODLNodeID())){
                    isDestEdge = true;
                }
                else if (graphLink.getLinkId().getValue().contains(sourceNode.getODLNodeID())){
                    isSourceEdge = true;
                }
            }
        }
        if (isDestEdge && isSourceEdge) {
            return true;
        }
        else{
            return false;
        }
    }

    /**
     * The method which creates the two shortest paths between the two given nodes.
     *
     * @param graph         The network graph.
     * @param sourceNode    The source node given by the user.
     * @param destNode      The destination node given by the user.
     * @return              It returns a list of the created paths.
     */
    private static List<GraphPath<Integer, DomainLink>> createPaths(NetworkGraph graph, Integer sourceNode, Integer destNode) {
        //find all possible paths between source and destination
        if (graph != null) {
            KShortestPaths kPaths = new KShortestPaths<>(graph, 2);
            List<GraphPath<Integer, DomainLink>> graphPaths = kPaths.getPaths(sourceNode, destNode);
            return graphPaths;
        } else {
            System.out.println("Graph was null.");
            return null;
        }
    }

    /**
     * The method which determines the input port for the ingress path node (source) and the output port for the egress
     * path node (destination).
     *
     * @param sourceNode    The source node given by the user.
     * @param destNode      The destination node given by the user.
     * @return
     */
    private static void findPortsForIngressAndEgressNodes(DomainNode sourceNode, DomainNode destNode){
        List<Link> graphLinks = NetworkGraph.getInstance().getGraphLinks();

        //examine all links of the graph and find the ones connecting a host to a switch
        for (Link graphLink : graphLinks){
            if (graphLink.getLinkId().getValue().contains("host")){
                if (graphLink.getLinkId().getValue().contains(destNode.getODLNodeID())){
                    String[] firstSplit = graphLink.getLinkId().getValue().split("\\/");
                    if (firstSplit[0].contains("openflow")) {
                        String[] secondSplit = firstSplit[0].split("openflow:");
                        outputPorts.put(destNode.getODLNodeID(), Integer.parseInt(secondSplit[1].split(":")[1]));
                    }
                    else if (firstSplit[1].contains("openflow")){
                        String[] secondSplit = firstSplit[1].split("openflow:");
                        outputPorts.put(destNode.getODLNodeID(), Integer.parseInt(secondSplit[1].split(":")[1]));
                    }
                }
                else if (graphLink.getLinkId().getValue().contains(sourceNode.getODLNodeID())){
                    String[] firstSplit = graphLink.getLinkId().getValue().split("\\/");
                    if (firstSplit[0].contains("openflow")) {
                        String[] secondSplit = firstSplit[0].split("openflow:");
                        inputPorts.put(sourceNode.getODLNodeID(), Integer.parseInt(secondSplit[1].split(":")[1]));
                    }
                    else if (firstSplit[1].contains("openflow")){
                        String[] secondSplit = firstSplit[1].split("openflow:");
                        inputPorts.put(sourceNode.getODLNodeID(), Integer.parseInt(secondSplit[1].split(":")[1]));
                    }
                }
            }
        }
    }

    /**
     * The method which determines the input and output ports for the core nodes of the main path, as well as the input port
     * for the egress (destination) switch and the output port for the ingress (source) switch.
     *
     * @param path          The path which will be analyzed to find its nodes' input, output and failover ports.
     * @param sourceNode    The source node given by the user.
     * @param destNode      The destination node given by the user.
     * @return
     */
    public static void findPorts(GraphPath<Integer, DomainLink> path, DomainNode sourceNode, DomainNode destNode) {
        //find in and out ports for nodes of main path
        for (DomainLink link : path.getEdgeList()) {
            inputPorts.put(link.getLink().getDestination().getDestNode().getValue(), Integer.parseInt(link.getLink().getDestination().getDestTp().getValue().split(":")[2]));
            outputPorts.put(link.getLink().getSource().getSourceNode().getValue(), Integer.parseInt(link.getLink().getSource().getSourceTp().getValue().split(":")[2]));
            failoverPorts.put(link.getLink().getDestination().getDestNode().getValue(), inputPorts.get(link.getLink().getDestination().getDestNode().getValue()));
        }
        //find in port for ingress node and out port for egress node, for main path
        if (!inputPorts.containsKey(sourceNode.getODLNodeID()) || !outputPorts.containsKey(destNode.getODLNodeID())) {
            findPortsForIngressAndEgressNodes(sourceNode, destNode);
        }
    }

    // --------------------------------------   FAST FAILOVER METHODS ---------------------------------------
    /**
     * The method which initializes the failover procedure.
     *
     * @param input     The user input, defining the two nodes between which a path will be established for traffic transmission.
     * @return          It returns a void future result.
     */
/*    @Override
    public Future<RpcResult<Void>> startFailover(StartFailoverInput input) {
        fastFailover = true;
        LOG.info("Configuring switches for resilience.");

        if (input.getSrcNode() != null && input.getDstNode() != null) {
            srcNode = input.getSrcNode();
            dstNode = input.getDstNode();
        }
        Hashtable<String, DomainNode> domainNodes = NetworkGraph.getInstance().getDomainNodes();
        DomainNode sourceNode = domainNodes.get(srcNode);
        DomainNode destNode = domainNodes.get(dstNode);

        //check if the given switches are edge switches, therefore connected to hosts
        if (!checkIfEdgeSwitches(sourceNode, destNode)){
            LOG.info("Not edge switches given, returning...");
            return Futures.immediateFuture(RpcResultBuilder.<Void>success().build());
        }

        //create the two best paths (minimum number of hops) between the given switches
        List<GraphPath<Integer, DomainLink>> possiblePaths = createPaths(NetworkGraph.getInstance(), sourceNode.getNodeID(), destNode.getNodeID());
        if (possiblePaths.size() < 2){
            LOG.info("There is no backup path between given switches, resilience cannot be achieved. Returning...");
            return Futures.immediateFuture(RpcResultBuilder.<Void>success().build());
        }
        //configure the switches of the main path beforehand
        implementFailover();

        return Futures.immediateFuture(RpcResultBuilder.<Void>success().build());

    }*/

    /**
     * The method which implements the resilience. For each node of the main path, finds an alternative port (to send
     * the packet back to the ingress switch in case of a link failure) and configures the nodes before traffic generation.
     */
  /*  public static void implementFailover(){
        if (NetworkGraph.getInstance().getGraphNodes() != null && NetworkGraph.getInstance().getGraphLinks() != null) {
            Hashtable<String, DomainNode> domainNodes = NetworkGraph.getInstance().getDomainNodes();
            DomainNode sourceNode = domainNodes.get(srcNode);
            DomainNode destNode = domainNodes.get(dstNode);

            List<GraphPath<Integer, DomainLink>> possiblePaths = createPaths(NetworkGraph.getInstance(), sourceNode.getNodeID(), destNode.getNodeID());
            //if there are two paths available, the first will be the main path and the second the backup path
            if (possiblePaths.size() > 1){
                GraphPath<Integer, DomainLink> mainPath = possiblePaths.get(0);
                GraphPath<Integer, DomainLink> failoverPath = possiblePaths.get(1);

                //find ports for nodes of main path
                findPorts(mainPath, sourceNode, destNode);

                //find failover ports for nodes of main path
                for (DomainLink link : mainPath.getEdgeList()){
                    failoverPorts.put(link.getLink().getDestination().getDestNode().getValue(), inputPorts.get(link.getLink().getDestination().getDestNode().getValue()));
                }
                failoverPorts.put(sourceNode.getODLNodeID(), Integer.parseInt(failoverPath.getEdgeList().get(0).getLink().getSource().getSourceTp().getValue().split(":")[2]));

                //find in and out ports for nodes of failover path
                for (DomainLink link : failoverPath.getEdgeList()){
                    inputPortsFailover.put(link.getLink().getDestination().getDestNode().getValue(), Integer.parseInt(link.getLink().getDestination().getDestTp().getValue().split(":")[2]));
                    outputPortsFailover.put(link.getLink().getSource().getSourceNode().getValue(), Integer.parseInt(link.getLink().getSource().getSourceTp().getValue().split(":")[2]));

                }
                inputPortsFailover.put(sourceNode.getODLNodeID(), inputPorts.get(sourceNode.getODLNodeID()));
                outputPortsFailover.put(destNode.getODLNodeID(), outputPorts.get(destNode.getODLNodeID()));

                //configure the switches of both main and failover path
                SwitchConfigurator switchConfigurator = new SwitchConfigurator(db);
                switchConfigurator.configureIngress(sourceNode, inputPorts.get(sourceNode.getODLNodeID()), outputPorts.get(sourceNode.getODLNodeID()), failoverPorts.get(sourceNode.getODLNodeID()));
                switchConfigurator.configureCoreAndEgress(mainPath.getEdgeList(), inputPorts, outputPorts, failoverPorts);
            }
        }
    }*/

    /**
     * The method which gets all links from MD-SAL.
     *
     * @param db        The data broker.
     * @return          The links list.
     */
   /* public static List<Link> getAllLinks(DataBroker db) {
        List<Link> linkList = new ArrayList<>();

        try {
            TopologyId topoId = new TopologyId("flow:1");
            InstanceIdentifier<Topology> nodesIid = InstanceIdentifier.builder(NetworkTopology.class).child(Topology.class, new TopologyKey(topoId)).toInstance();
            ReadOnlyTransaction nodesTransaction = db.newReadOnlyTransaction();
            CheckedFuture<com.google.common.base.Optional<Topology>, ReadFailedException> nodesFuture = nodesTransaction
                    .read(LogicalDatastoreType.OPERATIONAL, nodesIid);
            com.google.common.base.Optional<Topology> nodesOptional = nodesFuture.checkedGet();

            if (nodesOptional != null && nodesOptional.isPresent())
                linkList = nodesOptional.get().getLink();

            return linkList;
        } catch (Exception e) {

            LOG.info("Node Fetching Failed");

            return linkList;
        }
    }*/

    /**
     * The method which gets all nodes from MD-SAL.
     *
     * @param db        The data broker.
     * @return          The nodes list.
     */
   /* public static List<org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node> getNodes(DataBroker db) throws ReadFailedException {
        List<org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node> nodeList = new ArrayList<>();
        InstanceIdentifier<Nodes> nodesIid = InstanceIdentifier.builder(
                Nodes.class).build();
        ReadOnlyTransaction nodesTransaction = db.newReadOnlyTransaction();
        CheckedFuture<com.google.common.base.Optional<Nodes>, ReadFailedException> nodesFuture = nodesTransaction
                .read(LogicalDatastoreType.OPERATIONAL, nodesIid);
        com.google.common.base.Optional<Nodes> nodesOptional = nodesFuture.checkedGet();

        if (nodesOptional != null && nodesOptional.isPresent()) {
            nodeList = nodesOptional.get().getNode();
        }
        return nodeList;
    }*/

}


text:
layout: post
microblog: true
audio:
photo:
date: 2018-10-27 19:14:52 -0700
guid: http://curt.micro.blog/2018/10/28/in-the-trump.html
---
"In the Trump era, people who should be shunned are embraced…" —[Karen Tumulty](https://apple.news/AZlRLRLkgQSi_w1EYHslqaw)

redpajama_set_name: RedPajamaGithub


text:
class COMPMainMenu {
  constructor() {
    this.mainMenu = document.querySelector('.main-menu');
    this.topbar = document.querySelector('.main-menu__topbar');
    this.openButton = document.getElementById('main-menu__open-button');
    this.sidebar = document.querySelector('.main-menu__sidebar');
    this.sidebarContainer = document.querySelector('.main-menu__sidebar__container');
    this.closeButton = document.getElementById('main-menu__close-button');

    this.isTouching = false;
    this.touchStart;
    this.touchCurrent;

    this.showSidebar = this.showSidebar.bind(this);
    this.hideSidebar = this.hideSidebar.bind(this);

    this.transitionend = this.transitionend.bind(this);
    this.stopPropagation = this.stopPropagation.bind(this);

    this.touchstart = this.touchstart.bind(this);
    this.touchmove = this.touchmove.bind(this);
    this.touchend = this.touchend.bind(this);
    this.update = this.update.bind(this);

    this.events();
  }
  events() {
    this.openButton.addEventListener('click', this.showSidebar);
    this.closeButton.addEventListener('click', this.hideSidebar);
    this.sidebarContainer.addEventListener('animationEnd', this.transitionend);

    this.sidebar.addEventListener('click', this.hideSidebar)
    this.sidebarContainer.addEventListener('click', this.stopPropagation);

    document.addEventListener('touchstart', this.touchstart);
    document.addEventListener('touchmove', this.touchmove);
    document.addEventListener('touchend', this.touchend);
  }
  showSidebar() {
    this.sidebarContainer.style.willChange = 'transform';

    this.sidebar.classList.remove('--desable');
    this.sidebar.classList.add('--active');
    this.sidebarContainer.classList.remove('--desable');
    this.sidebarContainer.classList.add('--active');

  }
  hideSidebar() {
    this.sidebarContainer.style.willChange = 'transform';

    this.sidebar.classList.remove('--active');
    this.sidebar.classList.add('--desable');
    this.sidebarContainer.classList.remove('--active');
    this.sidebarContainer.classList.add('--desable');

  }

  touchstart(evt) {
    if(!this.sidebar.classList.contains('--active')) {
      return;
    }
    this.isTouching = true;
    this.touchStart = evt.targetTouches[0].pageX;
    this.touchCurrent = this.touchStart;

  }
  touchmove() {
    if(!this.isTouching) {
      return;
    }
    this.touchStart = evt.targetTouches[0].pageX;

  }
  touchend() {
    if(!this.isTouching) {
      return;
    }
    this.isTouching = false;

  }

  transitionend() {
    this.sidebarContainer.style.willChange = '';

  }
  stopPropagation(evt) {
    evt.stopPropagation();

  }

  update() {

  }
}

$(function () {
  new COMPMainMenu();
})


text:
<?php

declare(strict_types=1);

namespace Nelmio\Alice\FixtureBuilder\Denormalizer\FlagParser\Chainable;

use Nelmio\Alice\Definition\FlagBag;
use Nelmio\Alice\FixtureBuilder\Denormalizer\FlagParser\ChainableFlagParserInterface;
use Nelmio\Alice\NotCallableTrait;

class FakeChainableFlagParser implements ChainableFlagParserInterface
{
    use NotCallableTrait;

    /**
     * @inheritdoc
     */
    public function canParse(string $element): bool
    {
        $this->__call(__FUNCTION__, func_get_args());
    }

    /**
     * @inheritdoc
     */
    public function parse(string $element): FlagBag
    {
        $this->__call(__FUNCTION__, func_get_args());
    }
}


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

<TITLE>
Uses of Class soot.jimple.parser.node.PLocalName (Soot API)
</TITLE>

<META NAME="date" CONTENT="2012-01-22">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Uses of Class
soot.jimple.parser.node.PLocalName

Packages that use PLocalName

soot.jimple.parser.node

Uses of PLocalName in soot.jimple.parser.node

Subclasses of PLocalName in soot.jimple.parser.node

 class
ALocalName

Methods in soot.jimple.parser.node that return PLocalName

 PLocalName
ASingleLocalNameList.getLocalName()

 PLocalName
ANonstaticInvokeExpr.getLocalName()

 PLocalName
AMultiLocalNameList.getLocalName()

 PLocalName
ALocalVariable.getLocalName()

 PLocalName
ALocalImmediate.getLocalName()

 PLocalName
ALocalFieldRef.getLocalName()

 PLocalName
AIdentityStatement.getLocalName()

 PLocalName
AIdentityNoTypeStatement.getLocalName()

Methods in soot.jimple.parser.node with parameters of type PLocalName

 void
ASingleLocalNameList.setLocalName(PLocalName node)

 void
ANonstaticInvokeExpr.setLocalName(PLocalName node)

 void
AMultiLocalNameList.setLocalName(PLocalName node)

 void
ALocalVariable.setLocalName(PLocalName node)

 void
ALocalImmediate.setLocalName(PLocalName node)

 void
ALocalFieldRef.setLocalName(PLocalName node)

 void
AIdentityStatement.setLocalName(PLocalName node)

 void
AIdentityNoTypeStatement.setLocalName(PLocalName node)

Constructors in soot.jimple.parser.node with parameters of type PLocalName

AIdentityNoTypeStatement(PLocalName _localName_,
                         TColonEquals _colonEquals_,
                         TAtIdentifier _atIdentifier_,
                         TSemicolon _semicolon_)

AIdentityStatement(PLocalName _localName_,
                   TColonEquals _colonEquals_,
                   TAtIdentifier _atIdentifier_,
                   PType _type_,
                   TSemicolon _semicolon_)

ALocalFieldRef(PLocalName _localName_,
               TDot _dot_,
               PFieldSignature _fieldSignature_)

ALocalImmediate(PLocalName _localName_)

ALocalVariable(PLocalName _localName_)

AMultiLocalNameList(PLocalName _localName_,
                    TComma _comma_,
                    PLocalNameList _localNameList_)

ANonstaticInvokeExpr(PNonstaticInvoke _nonstaticInvoke_,
                     PLocalName _localName_,
                     TDot _dot_,
                     PMethodSignature _methodSignature_,
                     TLParen _lParen_,
                     PArgList _argList_,
                     TRParen _rParen_)

ASingleLocalNameList(PLocalName _localName_)

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<title>R: Vignettes and other documentation</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" type="text/css" href="/doc/html/R.css" />

 Vignettes and other documentation

Vignettes from package 'magrittr'

<col style="width: 22%;" />
<col style="width:  2%;" />
<col style="width: 50%;" />
<col style="width:  8%;" />
<col style="width:  8%;" />
<col style="width:  8%;" />

magrittr::magrittr
	Introducing magrittr
HTML
source
R code


text:
import rospy
import cv
import cv2
import time
import subprocess
import numpy
import threading
from std_msgs.msg import *
from sensor_msgs.msg import *
from geometry_msgs.msg import *
from cv_bridge import *
from deformable_astar.msg import *
from deformable_astar.srv import *
from transformation_helper import *
from xtf.xtf import *
from grc import *

class bcolors:
    HEADER = '\033[95m'
    OKBLUE = '\033[94m'
    OKGREEN = '\033[92m'
    WARNING = '\033[93m'
    QUESTION = '\033[90m'
    FAIL = '\033[91m'
    CYAN = '\033[96m'
    BOLD = '\033[1m'
    ENDC = '\033[0m'

class SDFClient:

    def __init__(self, sdf_topic, centers_topic, sdf_threshold, gradient_multiplier):
        rospy.init_node('sdf_client')
        # Set the dimensions of the environment
        # Horizontal (Y) is 0.55m (55cm)
        # Each cell is 5mm x 5mm, so we have 110.0 horizontal cells
        self.horz_cells = 110.0
        # Vertical (X) is o.402m (40.2cm)
        # Each cell is 5mm x 5mm, so we have 80.4 vertical cells
        self.vert_cells = 80.4
        # Set the offset between the upper left checkerboard center and the origin cell of the environment
        # Horizontal (Y) is 1cm
        self.origin_horz_cell_offset = -2.5
        # Vertical (X) is 1cm
        self.origin_vert_cell_offset = -0.5
        self.sdf_threshold = sdf_threshold
        self.gradient_multiplier = gradient_multiplier
        self.sdf_request_srv = rospy.Service("sdf_query", SDFQuery, self.sdf_request_cb)
        self.grc_request_srv = rospy.Service("grc_query", GRCQuery, self.grc_request_cb)
        self.bridge = CvBridge()
        self.controller = GradientRejectionController()
        self.sdf_lock = threading.Lock()
        self.latest_sdf = None
        self.latest_centers = None
        cv.NamedWindow("Status")
        # Load the trajectory file
        parser = XTFParser()
        self.path = parser.ParseTraj("/home/calderpg/Dropbox/Classes/AI/Project/code/TestEnv2.xtf")
        self.sdf_sub = rospy.Subscriber(sdf_topic, Image, self.sdf_cb)
        self.centers_sub = rospy.Subscriber(centers_topic, Int32MultiArray, self.centers_cb)
        while not rospy.is_shutdown():
            rospy.spin()

    def grc_request_cb(self, request):
        # Lock the SDF representation
        with self.sdf_lock:
            if (self.latest_sdf == None or self.latest_centers == None):
                rospy.logerr("Unable to complete request as no SDF or centers have been received")
                response = GRCQueryResponse()
                response.corrected_target.x = request.current_target.x
                response.corrected_target.y = request.current_target.y
                response.corrected_target.z = request.current_target.z
                return response
            else:
                sdf = self.latest_sdf
                centers = self.latest_centers
        # Call the gradient computation
        [rendered_image, current_gradient, originH, originV, horz_pixels_per_cell, vert_pixels_per_cell, robot_voxels] = self.compute_current_gradient(sdf, centers, [request.current_state.x, request.current_state.y, request.current_state.z])
        # Draw the current 'target' state (center only)
        idealtargetcenterH = int(round(originH + (request.current_target.y * horz_pixels_per_cell)))
        idealtargetcenterV = int(round(originV + (request.current_target.x * vert_pixels_per_cell)))
        cv.Circle(rendered_image, (idealtargetcenterH,idealtargetcenterV), 3, (0,0,255), thickness=-1)
        # Draw the next 'target' state (center only)
        nexttargetcenterH = int(round(originH + (request.next_target.y * horz_pixels_per_cell)))
        nexttargetcenterV = int(round(originV + (request.next_target.x * vert_pixels_per_cell)))
        cv.Circle(rendered_image, (nexttargetcenterH,nexttargetcenterV), 3, (255,0,255), thickness=-1)
        # Compute the GRC corrections for the corrected target state
        # We're going to deal with translation and rotation separately here
        # First, let's handle translation
        current_ideal_np = numpy.array([request.current_ideal.x, request.current_ideal.y])
        current_state_np = numpy.array([request.current_state.x, request.current_state.y])
        current_target_np = numpy.array([request.current_target.x, request.current_target.y])
        next_target_np = numpy.array([request.next_target.x, request.next_target.y])
        current_translation_gradient = numpy.array([current_gradient[0], current_gradient[1]])
        # Send the various states+gradient to the GRC controller
        corrected_target_translation_np = self.controller.compute_new_target(current_ideal_np, current_state_np, current_target_np, next_target_np, current_translation_gradient, request.grc_control)
        # Second, let's handle rotation
        current_ideal_rotation = request.current_ideal.z
        current_state_rotation = request.current_state.z
        current_target_rotation = request.current_target.z
        next_target_rotation = request.next_target.z
        current_rotation_gradient = float(current_gradient[2])
        # If the current rotation gradient is above bound, cap it to 0.1
        rotation_gradient_bound = 0.1
        if (current_rotation_gradient > rotation_gradient_bound):
            current_rotation_gradient = rotation_gradient_bound
        elif (current_rotation_gradient < -rotation_gradient_bound):
            current_rotation_gradient = -rotation_gradient_bound
        print "Current rotation gradient " + str(current_rotation_gradient) + " (bounded)"
        # Simply add the current rotation gradient to the target rotation
        corrected_target_rotation = current_target_rotation + current_rotation_gradient
        # Now that we're done, bring translation and rotation back together
        corrected_target = [float(corrected_target_translation_np[0]), float(corrected_target_translation_np[1]), corrected_target_rotation]
        # Draw the corrected target state
        # First, the target center
        targetcenterH = int(round(originH + (corrected_target[1] * horz_pixels_per_cell)))
        targetcenterV = int(round(originV + (corrected_target[0] * vert_pixels_per_cell)))
        cv.Circle(rendered_image, (targetcenterH,targetcenterV), 3, (0,127,255), thickness=-1)
        # Transform each of the points in the robot into environment (x,y) locations
        target_environment_cells = []
        for (rbx, rby) in robot_voxels:
            [ex, ey] = self.transform(corrected_target[0], corrected_target[1], corrected_target[2], rbx, rby)
            target_environment_cells.append([ex, ey])
        # Convert the environment cells to pixels and draw
        for (ex, ey) in target_environment_cells:
            eH = int(round(originH + (ey * horz_pixels_per_cell)))
            eV = int(round(originV + (ex * vert_pixels_per_cell)))
            cv.Circle(rendered_image, (eH,eV), 3, (0,127,255))
        # Final steps
        # Resize the image to double size
        rendered_image_full_size = cv.CreateMat(1080, 1920, cv.CV_8UC3)
        cv.Resize(rendered_image, rendered_image_full_size)
        #cv.ShowImage("Status", sdf_false_color)
        cv.ShowImage("Status", rendered_image_full_size)
        # This is how you get OpenCV to actually draw the window
        # (otherwise, it never has time to process)
        cv.WaitKey(3)
        # Return the response
        response = GRCQueryResponse()
        response.corrected_target.x = corrected_target[0]
        response.corrected_target.y = corrected_target[1]
        response.corrected_target.z = corrected_target[2]
        return response

    def compute_current_gradient(self, current_sdf, current_corners, current_position):
        # Make the basic false-color SDF image for visualization
        sdf_false_color = cv.CreateMat(current_sdf.rows, current_sdf.cols, cv.CV_8UC3)
        max_distance = 100
        for i in xrange(current_sdf.rows):
            for j in xrange(current_sdf.cols):
                [posdist, negdist] = current_sdf[i, j]
                if negdist == 0.0:
                    blue_channel = 0
                    green_channel = 0
                    red_channel = int(64.0 + (64.0 * (posdist / max_distance)))
                    sdf_false_color[i, j] = [blue_channel, green_channel, red_channel]
                elif posdist == 0.0:
                    blue_channel = int(64.0 + (64.0 * (negdist / max_distance)))
                    green_channel = 0
                    red_channel = 0
                    sdf_false_color[i, j] = [blue_channel, green_channel, red_channel]
                else:
                    print "SDF image channels 1 and 2 not correctly separated"
        # Compute pixels/environment cell
        horz_pixels = ((current_corners[1][0] - current_corners[0][0]) + (current_corners[2][0] - current_corners[3][0])) / 2.0
        vert_pixels = ((current_corners[3][1] - current_corners[0][1]) + (current_corners[2][1] - current_corners[1][1])) / 2.0
        horz_pixels_per_cell = horz_pixels / self.horz_cells
        vert_pixels_per_cell = vert_pixels / self.vert_cells
        # Draw origin point
        originH = int(round(current_corners[0][0] + (self.origin_horz_cell_offset * horz_pixels_per_cell)))
        originV = int(round(current_corners[0][1] + (self.origin_vert_cell_offset * vert_pixels_per_cell)))
        originpoint1 = (originH - 5, originV - 5)
        originpoint2 = (originH + 5, originV + 5)
        cv.Rectangle(sdf_false_color, originpoint1, originpoint2, (255, 0, 255), thickness=-1)
        # Draw a calibration marker in the center of the image
        cal_centerH = int(round(current_corners[0][0] + ((self.horz_cells * 0.5) * horz_pixels_per_cell)))
        cal_centerV = int(round(current_corners[0][1] + ((self.vert_cells * 0.5) * vert_pixels_per_cell)))
        cal_centerpoint1 = (cal_centerH - 10, cal_centerV - 10)
        cal_centerpoint2 = (cal_centerH + 10, cal_centerV + 10)
        cv.Rectangle(sdf_false_color, cal_centerpoint1, cal_centerpoint2, (255, 255, 255), thickness=2)
        # Draw markers over the locations of the corner checkerboards
        ulccpoint1 = (current_corners[0][0] - 10, current_corners[0][1] - 10)
        ulccpoint2 = (current_corners[0][0] + 10, current_corners[0][1] + 10)
        cv.Rectangle(sdf_false_color, ulccpoint1, ulccpoint2, (0, 255, 255), thickness=2)
        urccpoint1 = (current_corners[1][0] - 10, current_corners[1][1] - 10)
        urccpoint2 = (current_corners[1][0] + 10, current_corners[1][1] + 10)
        cv.Rectangle(sdf_false_color, urccpoint1, urccpoint2, (0, 255, 255), thickness=2)
        lrccpoint1 = (current_corners[3][0] - 10, current_corners[3][1] - 10)
        lrccpoint2 = (current_corners[3][0] + 10, current_corners[3][1] + 10)
        cv.Rectangle(sdf_false_color, lrccpoint1, lrccpoint2, (0, 255, 255), thickness=2)
        llccpoint1 = (current_corners[2][0] - 10, current_corners[2][1] - 10)
        llccpoint2 = (current_corners[2][0] + 10, current_corners[2][1] + 10)
        cv.Rectangle(sdf_false_color, llccpoint1, llccpoint2, (0, 255, 255), thickness=2)
        # Draw markers where we *expected* the checkerboards to be!
        cal_ulcc_H = int(round(current_corners[0][0]))
        cal_ulcc_V = int(round(current_corners[0][1]))
        eulccpoint1 = (cal_ulcc_H - 10, cal_ulcc_V - 10)
        eulccpoint2 = (cal_ulcc_H + 10, cal_ulcc_V + 10)
        cv.Rectangle(sdf_false_color, eulccpoint1, eulccpoint2, (255, 255, 255), thickness=2)
        cal_urcc_H = int(round(current_corners[0][0] + (self.horz_cells * horz_pixels_per_cell)))
        cal_urcc_V = int(round(current_corners[0][1]))
        eurccpoint1 = (cal_urcc_H - 10, cal_urcc_V - 10)
        eurccpoint2 = (cal_urcc_H + 10, cal_urcc_V + 10)
        cv.Rectangle(sdf_false_color, eurccpoint1, eurccpoint2, (255, 255, 255), thickness=2)
        cal_llcc_H = int(round(current_corners[0][0]))
        cal_llcc_V = int(round(current_corners[0][1] + (self.vert_cells * vert_pixels_per_cell)))
        ellccpoint1 = (cal_llcc_H - 10, cal_llcc_V - 10)
        ellccpoint2 = (cal_llcc_H + 10, cal_llcc_V + 10)
        cv.Rectangle(sdf_false_color, ellccpoint1, ellccpoint2, (255, 255, 255), thickness=2)
        cal_lrcc_H = int(round(current_corners[0][0] + (self.horz_cells * horz_pixels_per_cell)))
        cal_lrcc_V = int(round(current_corners[0][1] + (self.vert_cells * vert_pixels_per_cell)))
        elrccpoint1 = (cal_lrcc_H - 10, cal_lrcc_V - 10)
        elrccpoint2 = (cal_lrcc_H + 10, cal_lrcc_V + 10)
        cv.Rectangle(sdf_false_color, elrccpoint1, elrccpoint2, (255, 255, 255), thickness=2)
        # Draw start point
        [startCellX, startCellY, startRotate] = self.path.trajectory[0].position_desired
        startH = int(round(originH + (startCellY * horz_pixels_per_cell)))
        startV = int(round(originV + (startCellX * vert_pixels_per_cell)))
        startpoint1 = (startH - 5, startV - 5)
        startpoint2 = (startH + 5, startV + 5)
        cv.Rectangle(sdf_false_color, startpoint1, startpoint2, (255, 0, 0), thickness=-1)
        # Draw goal point
        [goalCellX, goalCellY, goalRotate] = self.path.trajectory[-1].position_desired
        goalH = int(round(originH + (goalCellY * horz_pixels_per_cell)))
        goalV = int(round(originV + (goalCellX * vert_pixels_per_cell)))
        goalpoint1 = (goalH - 5, goalV - 5)
        goalpoint2 = (goalH + 5, goalV + 5)
        cv.Rectangle(sdf_false_color, goalpoint1, goalpoint2, (0, 255, 0), thickness=-1)
        # Render the trajectory centers atop the image
        for index in xrange(1, len(self.path.trajectory) - 1):
            [cellX, cellY, rotation] = self.path.trajectory[index].position_desired
            stateH = int(round(originH + (cellY * horz_pixels_per_cell)))
            stateV = int(round(originV + (cellX * vert_pixels_per_cell)))
            point1 = (stateH - 2, stateV - 2)
            point2 = (stateH + 2, stateV + 2)
            cv.Rectangle(sdf_false_color, point1, point2, (0, 127, 0))
        # Draw the requested state
        # Draw the current center point
        centerH = int(round(originH + (current_position[1] * horz_pixels_per_cell)))
        centerV = int(round(originV + (current_position[0] * vert_pixels_per_cell)))
        cv.Circle(sdf_false_color, (centerH, centerV), 3, (0, 255, 255), thickness=-1)
        # Make the list of all points in the robot
        cx = 11
        cy = 4
        robot_voxels = []
        for xr in xrange(16):
            for yr in xrange(16):
                if (xr < 8) and (yr >= 8):
                    pass
                else:
                    rx = xr - cx
                    if rx >= 0.0:
                        rx -= 0.5
                    elif rx <= -0.0:
                        rx += 0.5
                    ry = yr - cy
                    if ry >= 0.0:
                        ry -= 0.5
                    elif ry <= -0.0:
                        ry += 0.5
                    robot_voxels.append([rx, ry])
        # Transform each of the points in the robot into environment (x,y) locations
        environment_cells = []
        for (rbx, rby) in robot_voxels:
            [ex, ey] = self.transform(current_position[0], current_position[1], current_position[2], rbx, rby)
            environment_cells.append([ex, ey])
        print "Robot voxels: ", robot_voxels
        print "Environment cells: ", environment_cells
        # Convert the environment cells to pixels
        pixel_points = []
        for (ex, ey) in environment_cells:
            eH = int(round(originH + (ey * horz_pixels_per_cell)))
            eV = int(round(originV + (ex * vert_pixels_per_cell)))
            pixel_points.append([eH, eV])
            #cv.Circle(sdf_false_color, (eH,eV), 3, (0,127,127))
        print "Pixel points: ", pixel_points
        ################################################################################################################
        # Compute the gradient for each point
        gradients = []
        for (eH, eV) in pixel_points:
            if (eH >= 1) and (eH < (current_sdf.cols - 1)):
                if (eV >= 1) and (eV < (current_sdf.rows - 1)):
                    gHorz = (self.query_sdf(current_sdf, eV, eH + 1) - self.query_sdf(current_sdf, eV, eH - 1)) * 0.5
                    gVert = (self.query_sdf(current_sdf, eV + 1, eH) - self.query_sdf(current_sdf, eV - 1, eH)) * 0.5
                    # Convert values from SDF into cells, not pixels
                    gHorz = gHorz / horz_pixels_per_cell
                    gVert = gVert / vert_pixels_per_cell
                    sdf_val = self.query_sdf(current_sdf, eV, eH)
                    if sdf_val >= self.sdf_threshold:
                        gHorz = 0.0
                        gVert = 0.0
                    else:
                        dist_to_threshold = abs(self.sdf_threshold - sdf_val)
                        gHorz = gHorz * self.gradient_multiplier * dist_to_threshold
                        gVert = gVert * self.gradient_multiplier * dist_to_threshold
                    gradients.append([gVert, gHorz])
                    # Draw the gradient
                    cv.Circle(sdf_false_color, (eH,eV), 1, (127,127,0))
                    cv.Line(sdf_false_color, (eH,eV), (int(round(eH + 5 * gHorz)), int(round(eV + 5 * gVert))), (100,100,100))
                else:
                    rospy.logwarn("eV " + str(eV) + " outside bounds")
                    gradients.append([0.0, 0.0])
            else:
                rospy.logwarn("eH " + str(eH) + " outside bounds")
                gradients.append([0.0, 0.0])
        # Combine the gradients together
        # Loop through to build the Jacobian (J) and end-effector gradient (Xdot) matrices
        # since Xdot = J * Qdot
        J_raw = []
        Xdot_raw = []
        for index in xrange(len(gradients)):
            gradient = gradients[index]
            Xdot_raw += gradient
            # Compute the Jacobian at the current state
            d = math.sqrt((robot_voxels[index][0] * vert_pixels_per_cell) ** 2 + (robot_voxels[index][1] * horz_pixels_per_cell) ** 2)
            d2 = math.sqrt((robot_voxels[index][0]) ** 2 + (robot_voxels[index][1]) ** 2)
            if (abs(gradient[0]) > 0.0 or abs(gradient[1]) > 0.0):
                pass #print "d value: ", d
            # Compute the current derivatives for rotation
            px = environment_cells[index][0] - current_position[0]
            py = environment_cells[index][1] - current_position[1]
            angle = math.atan2(py, px)
            pprimex = d2 * cos(0.1 + angle)
            pprimey = d2 * sin(0.1 + angle)
            deltapx = (pprimex - px) / 0.1
            deltapy = (pprimey - py) / 0.1
            #print "d2:", d2
            #print "angle:", angle
            #print "dpx:", deltapx
            #print "dpy:", deltapy
            J_raw.append([1.0, 0.0, deltapx])
            J_raw.append([0.0, 1.0, deltapy])
            #J_raw.append([1.0, 0.0, -d * sin(angle)])
            #J_raw.append([0.0, 1.0, d * cos(angle)])
            #J_raw.append([1.0, 0.0, d * -sin(1.0)]) # 2.0 inflates the rotation effect to decrease rotation gradient
            #J_raw.append([0.0, 1.0, d * cos(1.0)]) # same here
        # Draw the last point
        #cv.Circle(sdf_false_color, (int(round(originH + (environment_cells[-1][1] * horz_pixels_per_cell))), int(round(originV + (environment_cells[-1][0] * vert_pixels_per_cell)))), 3, (255,255,255))
        J = numpy.array(J_raw)
        Xdot = numpy.array(Xdot_raw)
        #print "Xdot", Xdot
        #print "J", J
        # 'Invert' the Jacobian so we can do Qdot = J+ * Xdot
        Jpinv = numpy.linalg.pinv(J)
        #Jpinv = numpy.transpose(J)
        #print "J+", Jpinv
        # Compute Qdot
        Qdot = numpy.dot(Jpinv, Xdot)
        print "Current gradient is " + str(Qdot) + " (unbounded)"
        ################################################################################################################
        # Draw the complete (x,y) gradient
        cv.Line(sdf_false_color, (centerH,centerV), (int(round(centerH + (10 * Qdot[1]))), int(round(centerV + (10 * Qdot[0])))), (0,255,255))
        return [sdf_false_color, Qdot, originH, originV, horz_pixels_per_cell, vert_pixels_per_cell, robot_voxels]

if __name__ == '__main__':
    print bcolors.HEADER + bcolors.BOLD + "[SDF CLIENT] Starting the SDF client..." + bcolors.ENDC
    #Get the parameters from the server
    sdf_topic = rospy.get_param("~sdf_topic", "test_camera/sdf_raw")
    centers_topic = rospy.get_param("~centers_topic", "test_camera/centers")
    #Print the starting parameters to the screen
    print bcolors.HEADER + bcolors.BOLD + "[SDF CLIENT] Starting with SDF topic: /" + sdf_topic + bcolors.ENDC
    print bcolors.HEADER + bcolors.BOLD + "[SDF CLIENT] Starting with centers topic: /" + centers_topic + bcolors.ENDC
    sdf_threshold = 20.0
    gradient_multiplier = 5.0
    SDFClient(sdf_topic, centers_topic, sdf_threshold, gradient_multiplier)


text:
<?php
	//Add Friends Template
	//Generate a random number for the search input name fields, so that the browser will not remember any previous entries.
	$rand = md5(rand(0, time()));
	if ($this->rand_key != ''){
		$last_search = $_POST['search_friends_'.$this->rand_key];
	} else {
		$last_search = $_POST['search_friends_'.$rand];
	}
?>

<?php echo _AT('search_for_friends'); ?>

		<form action="<?php echo url_rewrite(AT_SOCIAL_BASENAME.'groups/list.php');?>" method="POST" id="search_friends_form">
			<?php echo _AT('search'); ?>
			<input type="text" size="60" name="search_friends_<?php echo $rand;?>" id="search_friends" value="<?php echo $last_search; ?>" onkeyup="showResults(this.value, 'livesearch', '<?php echo AT_SOCIAL_BASENAME; ?>groups/list.php')"/>
			<input type="submit" name="search" value="<?php echo _AT('search'); ?>">
			<input type="hidden" name="rand_key" value="<?php echo $rand; ?>" />
			<input type="hidden" name="id" value="<?php echo $this->grp_obj->getID(); ?>" />

		</form>

<?php echo _AT('connections'); ?>

	<?php
	if (!empty($this->grp_members)):
		echo "
"._AT('there_are_entries', sizeof($this->grp_members))."
";
		foreach ($this->grp_members as $id=>$person_obj):
	?>

		<?php if($_SESSION['member_id']==$this->grp_obj->getUser()): ?>

<a href="<?php echo AT_SOCIAL_BASENAME;?>groups/list.php?remove=yes<?php echo SEP;?>id=<?php echo $this->grp_obj->getID(); ?><?php echo SEP;?>member_id=<?php echo $person_obj->getID(); ?>"><img src="<?php echo $_base_href.AT_SOCIAL_BASENAME; ?>images/b_drop.png" alt="<?php echo _AT('remove_group_member'); ?>" title="<?php echo _AT('remove_group_member'); ?>" border="0"/>

		<?php endif; ?>

<?php echo printSocialProfileImg($person_obj->getID()); ?>

				<?php
					$profile = $person_obj->getDetails();
					echo printSocialName($person_obj->getID()) . '
';
					echo $profile['country'] . ' ' . $profile['province'] . '
';
				?>

	<?php
		endforeach;
	endif;
	?>


text:
const path = require('path');
const ProgressPlugin = require('webpack/lib/ProgressPlugin');
const ProvidePlugin = require('webpack/lib/ProvidePlugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const autoprefixer = require('autoprefixer');
const postcssUrl = require('postcss-url');

const { NoEmitOnErrorsPlugin, LoaderOptionsPlugin } = require('webpack');
const { GlobCopyWebpackPlugin, BaseHrefWebpackPlugin } = require('@angular/cli/plugins/webpack');
const { CommonsChunkPlugin } = require('webpack').optimize;
const { AotPlugin } = require('@ngtools/webpack');

const nodeModules = path.join(process.cwd(), 'node_modules');
const entryPoints = ["inline","polyfills","sw-register","styles","vendor","main"];
const baseHref = "";
const deployUrl = "";

switch(process.env.NODE_ENV) {
  default:
    ENVIRONMENT = 'environments/environment.dev.ts';
    break;
  case "production":
    ENVIRONMENT = 'environments/environment.prod.ts';
    break;
  case "cordova":
    ENVIRONMENT = 'environments/environment.cordova.ts';
    break;
}

module.exports = {
  "devtool": "source-map",
  "resolve": {
    "extensions": [
      ".ts",
      ".js"
    ],
    "modules": [
      "./node_modules"
    ]
  },
  "resolveLoader": {
    "modules": [
      "./node_modules"
    ]
  },
  "entry": {
    "main": [
      "./src/main.ts"
    ],
    "polyfills": [
      "./src/polyfills.ts"
    ],
    "styles": [
      "./src/styles.css"
    ]
  },
  "output": {
    "path": path.join(process.cwd(), "cordova/www"),//dist
    "filename": "[name].bundle.js",
    "chunkFilename": "[id].chunk.js"
  },
  "module": {
    "rules": [
			{
				"test": /\.(pug|jade)$/,
				"use": ["raw-loader", "pug-html-loader"]

			},
      {
        "enforce": "pre",
        "test": /\.js$/,
        "loader": "source-map-loader",
        "exclude": [
          /\/node_modules\//
        ]
      },
      {
        "test": /\.json$/,
        "loader": "json-loader"
      },
      {
        "test": /\.html$/,
        "loader": "raw-loader"
      },
      {
        "test": /\.(eot|svg)$/,
        "loader": "file-loader?name=[name].[hash:20].[ext]"
      },
      {
        "test": /\.(jpg|png|gif|otf|ttf|woff|woff2|cur|ani)$/,
        "loader": "url-loader?name=[name].[hash:20].[ext]&limit=10000"
      },
      {
        "exclude": [
          path.join(process.cwd(), "src/styles.css")
        ],
        "test": /\.css$/,
        "loaders": [
          "exports-loader?module.exports.toString()",
          "css-loader?{\"sourceMap\":false,\"importLoaders\":1}",
          "postcss-loader"
        ]
      },
      {
        "exclude": [
          path.join(process.cwd(), "src/styles.css")
        ],
        "test": /\.scss$|\.sass$/,
        "loaders": [
          "exports-loader?module.exports.toString()",
          "css-loader?{\"sourceMap\":false,\"importLoaders\":1}",
          "postcss-loader",
          "sass-loader"
        ]
      },
      {
        "exclude": [
          path.join(process.cwd(), "src/styles.css")
        ],
        "test": /\.less$/,
        "loaders": [
          "exports-loader?module.exports.toString()",
          "css-loader?{\"sourceMap\":false,\"importLoaders\":1}",
          "postcss-loader",
          "less-loader"
        ]
      },
      {
        "exclude": [
          path.join(process.cwd(), "src/styles.css")
        ],
        "test": /\.styl$/,
        "loaders": [
          "exports-loader?module.exports.toString()",
          "css-loader?{\"sourceMap\":false,\"importLoaders\":1}",
          "postcss-loader",
          "stylus-loader?{\"sourceMap\":false,\"paths\":[]}"
        ]
      },
      {
        "include": [
          path.join(process.cwd(), "src/styles.css")
        ],
        "test": /\.css$/,
        "loaders": ExtractTextPlugin.extract({
          "use": [
            "css-loader?{\"sourceMap\":false,\"importLoaders\":1}",
            "postcss-loader"
          ],
          "fallback": "style-loader",
          "publicPath": ""
        })
      },
      {
        "include": [
          path.join(process.cwd(), "src/styles.css")
        ],
        "test": /\.scss$|\.sass$/,
        "loaders": ExtractTextPlugin.extract({
          "use": [
            "css-loader?{\"sourceMap\":false,\"importLoaders\":1}",
            "postcss-loader",
            "sass-loader"
          ],
          "fallback": "style-loader",
          "publicPath": ""
        })
      },
      {
        "include": [
          path.join(process.cwd(), "src/styles.css")
        ],
        "test": /\.less$/,
         "loaders": ExtractTextPlugin.extract({
          "use": [
            "css-loader?{\"sourceMap\":false,\"importLoaders\":1}",
            "postcss-loader",
            "less-loader"
          ],
          "fallback": "style-loader",
          "publicPath": ""
        })
      },
      {
        "include": [
          path.join(process.cwd(), "src/styles.css")
        ],
        "test": /\.styl$/,
        "loaders": ExtractTextPlugin.extract({
          "use": [
            "css-loader?{\"sourceMap\":false,\"importLoaders\":1}",
            "postcss-loader",
            "stylus-loader?{\"sourceMap\":false,\"paths\":[]}"
          ],
          "fallback": "style-loader",
          "publicPath": ""
        })
      },
      {
        "test": /\.ts$/,
        "loader": "@ngtools/webpack"
      }
    ]
  },
  "plugins": [
    new NoEmitOnErrorsPlugin(),
    new GlobCopyWebpackPlugin({
      "patterns": [
        "assets",
        "favicon.ico"
      ],
      "globOptions": {
        "cwd": "/home/abrown28/Projects/WorkoutPro/src",
        "dot": true,
        "ignore": "**/.gitkeep"
      }
    }),
    new ProgressPlugin(),
    new HtmlWebpackPlugin({
      "template": "./src/index.html",
      "filename": "./index.html",
      "hash": false,
      "inject": true,
      "compile": true,
      "favicon": false,
      "minify": false,
      "cache": true,
      "showErrors": true,
      "chunks": "all",
      "excludeChunks": [],
      "title": "Webpack App",
      "xhtml": true,
      "chunksSortMode": function sort(left, right) {
        let leftIndex = entryPoints.indexOf(left.names[0]);
        let rightindex = entryPoints.indexOf(right.names[0]);
        if (leftIndex > rightindex) {
            return 1;
        }
        else if (leftIndex < rightindex) {
            return -1;
        }
        else {
            return 0;
        }
      }
    }),
    new BaseHrefWebpackPlugin({}),
    new CommonsChunkPlugin({
      "name": "inline",
      "minChunks": null
    }),
    new CommonsChunkPlugin({
      "name": "vendor",
      "minChunks": (module) => module.resource && module.resource.startsWith(nodeModules),
      "chunks": [
        "main"
      ]
    }),
    new ExtractTextPlugin({
      "filename": "[name].bundle.css",
      "disable": true
    }),
    new LoaderOptionsPlugin({
      "sourceMap": false,
      "options": {
        "postcss": [
          autoprefixer(),
          postcssUrl({"url": (URL) => {
            // Only convert root relative URLs, which CSS-Loader won't process into require().
            if (!URL.startsWith('/') || URL.startsWith('//')) {
                return URL;
            }
            if (deployUrl.match(/:\/\//)) {
                // If deployUrl contains a scheme, ignore baseHref use deployUrl as is.
                return `${deployUrl.replace(/\/$/, '')}${URL}`;
            }
            else if (baseHref.match(/:\/\//)) {
                // If baseHref contains a scheme, include it as is.
                return baseHref.replace(/\/$/, '') +
                    `/${deployUrl}/${URL}`.replace(/\/\/+/g, '/');
            }
            else {
                // Join together base-href, deploy-url and the original URL.
                // Also dedupe multiple slashes into single ones.
                return `/${baseHref}/${deployUrl}/${URL}`.replace(/\/\/+/g, '/');
            }
        }})
        ],
        "sassLoader": {
          "sourceMap": false,
          "includePaths": []
        },
        "lessLoader": {
          "sourceMap": false
        },
        "context": ""
      }
    }),
    new AotPlugin({
      "mainPath": "main.ts",
      "hostReplacementPaths": {
        "environments/environment.ts": ENVIRONMENT
      },
      "exclude": [],
      "tsConfigPath": "src/tsconfig.app.json",
      "skipCodeGeneration": true
    }),
    new ProvidePlugin({
      $: "jquery",
      jQuery: "jquery",
      "window.jQuery": "jquery",
      Tether: "tether",
      "window.Tether": "tether",
      Tooltip: "exports?Tooltip!bootstrap/js/dist/tooltip",
      Alert: "exports?Alert!bootstrap/js/dist/alert",
      Button: "exports?Button!bootstrap/js/dist/button",
      Carousel: "exports?Carousel!bootstrap/js/dist/carousel",
      Collapse: "exports?Collapse!bootstrap/js/dist/collapse",
      Dropdown: "exports?Dropdown!bootstrap/js/dist/dropdown",
      Modal: "exports?Modal!bootstrap/js/dist/modal",
      Popover: "exports?Popover!bootstrap/js/dist/popover",
      Scrollspy: "exports?Scrollspy!bootstrap/js/dist/scrollspy",
      Tab: "exports?Tab!bootstrap/js/dist/tab",
      Tooltip: "exports?Tooltip!bootstrap/js/dist/tooltip",
      Util: "exports?Util!bootstrap/js/dist/util",
    }),
  ],
  "node": {
    "fs": "empty",
    "global": true,
    "crypto": "empty",
    "tls": "empty",
    "net": "empty",
    "process": true,
    "module": false,
    "clearImmediate": false,
    "setImmediate": false
  }
};


text:
package com.fsck.k9.mail.internet;

import com.fsck.k9.mail.BodyPart;
import com.fsck.k9.mail.MessagingException;
import com.fsck.k9.mail.Multipart;

import java.io.*;
import java.util.Locale;
import java.util.Random;

public class MimeMultipart extends Multipart {
    private byte[] mPreamble;
    private byte[] mEpilogue;

    private String mContentType;

    private final String mBoundary;

    public MimeMultipart() throws MessagingException {
        mBoundary = generateBoundary();
        setSubType("mixed");
    }

    public MimeMultipart(String contentType) throws MessagingException {
        this.mContentType = contentType;
        try {
            mBoundary = MimeUtility.getHeaderParameter(contentType, "boundary");
            if (mBoundary == null) {
                throw new MessagingException("MultiPart does not contain boundary: " + contentType);
            }
        } catch (Exception e) {
            throw new MessagingException(
                "Invalid MultiPart Content-Type; must contain subtype and boundary. ("
                + contentType + ")", e);
        }
    }

    public String generateBoundary() {
        Random random = new Random();
        StringBuilder sb = new StringBuilder();
        sb.append("----");
        for (int i = 0; i < 30; i++) {
            sb.append(Integer.toString(random.nextInt(36), 36));
        }
        return sb.toString().toUpperCase(Locale.US);
    }

    public void setPreamble(byte[] preamble) {
        this.mPreamble = preamble;
    }

    public void setEpilogue(byte[] epilogue) {
        mEpilogue = epilogue;
    }

    @Override
    public String getContentType() {
        return mContentType;
    }

    public void setSubType(String subType) {
        mContentType = String.format("multipart/%s; boundary=\"%s\"", subType, mBoundary);
    }

    @Override
    public void writeTo(OutputStream out) throws IOException, MessagingException {
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out), 1024);

        if (mPreamble != null) {
            out.write(mPreamble);
            writer.write("\r\n");
        }

        if (getBodyParts().isEmpty()) {
            writer.write("--");
            writer.write(mBoundary);
            writer.write("\r\n");
        } else {
            for (BodyPart bodyPart : getBodyParts()) {
                writer.write("--");
                writer.write(mBoundary);
                writer.write("\r\n");
                writer.flush();
                bodyPart.writeTo(out);
                writer.write("\r\n");
            }
        }

        writer.write("--");
        writer.write(mBoundary);
        writer.write("--\r\n");
        writer.flush();
        if (mEpilogue != null) {
            out.write(mEpilogue);
        }
    }

    @Override
    public InputStream getInputStream() throws MessagingException {
        return null;
    }

    @Override
    public void setUsing7bitTransport() throws MessagingException {
        for (BodyPart part : getBodyParts()) {
            part.setUsing7bitTransport();
        }
    }
}


text:
namespace Rcpp{
namespace sugar{

template <int RTYPE, bool NA, typename T>
class Rep_each : public Rcpp::VectorBase< RTYPE ,NA, Rep_each<RTYPE,NA,T> > {
public:
	typedef typename Rcpp::VectorBase<RTYPE,NA,T> VEC_TYPE ;
	typedef typename Rcpp::traits::storage_type<RTYPE>::type STORAGE ;

        Rep_each( const VEC_TYPE& object_, R_xlen_t times_ ) :
		object(object_), times(times_), n(object.size()) {}

        inline STORAGE operator[]( R_xlen_t i ) const {
		return object[ i / times ] ;
	}
        inline R_xlen_t size() const { return n * times ; }

private:
	const VEC_TYPE& object ;
        R_xlen_t times, n ;
} ;

} // sugar

template <int RTYPE, bool NA, typename T>
inline sugar::Rep_each<RTYPE,NA,T> rep_each( const VectorBase<RTYPE,NA,T>& t, R_xlen_t times ){
	return sugar::Rep_each<RTYPE,NA,T>( t, times ) ;
}

} // Rcpp
#endif


text:
package raptor.chess;

import raptor.chess.pgn.PgnHeader;

/**
 * An implementation of a bughouse game. This approach involves linking two
 * bughouse games together. And setting the others droppable piece counts as
 * pieces are captured.
 *
 *
 * NOTE: the xoring for the zobrist is broken. It would need to be fixed to rely
 * on that for a computer program. Also this wont work for bgpn without some
 * changes.
 */
public class BughouseGame extends CrazyhouseGame {

	protected BughouseGame otherBoard;

	public BughouseGame() {
		super();
		setHeader(PgnHeader.Variant, Variant.bughouse.name());
	}

	// Leave this here. It will be needed when bgpn is implemented.
	/**
	 * Decrements the drop count of the other game.
	 */
	// @Override
	// protected void decrementDropCount(int color, int piece) {
	// piece = piece & PROMOTED_MASK;
	// if (otherBoard != null) {
	// otherBoard.dropCounts[color][piece] = otherBoard.dropCounts[color][piece]
	// - 1;
	// }
	// }
	/**
	 * @param ignoreHashes
	 *            Whether to include copying hash tables.
	 * @return An deep clone copy of this Game object.
	 */
	@Override
	public BughouseGame deepCopy(boolean ignoreHashes) {
		BughouseGame result = new BughouseGame();
		overwrite(result, ignoreHashes);
		return result;
	}

	public BughouseGame getOtherBoard() {
		return otherBoard;
	}

	// Leave this here. It will be needed when bgpn is implemented.
	/**
	 * Increments the drop count of the other game.
	 */
	// @Override
	// protected void incrementDropCount(int color, int piece) {
	// if ((piece & PROMOTED_MASK) != 0) {
	// piece = PAWN;
	// } else {
	// if (otherBoard != null) {
	// otherBoard.dropCounts[color][piece] = otherBoard.dropCounts[color][piece]
	// + 1;
	// }
	// }
	// }
	public void setOtherBoard(BughouseGame bughouseGame) {
		otherBoard = bughouseGame;
	}

}


text:
<?php

/*
 * This file is part of Mongator.
 *
 * (c) Máximo Cuadros <maximo@yunait.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Mongator\Tests;

use Mongator\Query\Result;

class ResultTest extends TestCase
{
    public function testConstructFromArrayObject()
    {
        $ao = new \ArrayObject(range(0,19));
        $result = new Result($ao);

        $valid = range(0,19);
        foreach ($result as $key => $value) {
            $this->assertSame($key, $value);
            $this->assertSame($valid[$key], $value);
        }

        $result->rewind();
        $this->assertSame(0, $result->current());
        $this->assertSame(0, $result->key());

        $this->assertSame(20, $result->count());
    }

    public function testConstructFromMongoCursor()
    {
        $articles = $this->createArticlesRaw(10);

        $query = new \Model\ArticleQuery($this->mongator->getRepository('Model\Article'));

        $result = $query->limit(2)->createCursor();
        $this->assertInstanceOf('MongoCursor', $result->getIterator());

        $i = 0;
        foreach ($result as $key => $value) {
            $this->assertSame('Article' . $i++, $value['title']);
            $this->assertSame($key, (string) $value['_id']);
        }

        $this->assertSame(10, $result->count());
    }

    public function testSetCountInteger()
    {
        $ao = new \ArrayObject(range(0,19));
        $result = new Result($ao);

        $result->setCount(50);
        $this->assertSame(50, $result->count());
    }

    public function testSetCountClosure()
    {
        $ao = new \ArrayObject(range(0,19));
        $result = new Result($ao);

        $result->setCount(function() { return 100; });
        $this->assertSame(100, $result->count());
    }

    public function testSerialize()
    {
        $ao = new \ArrayObject(range(0,2));
        $result = new Result($ao);

        $result->setCount(50);

        $expected = 'C:21:"Mongator\Query\Result":64:{a:2:{s:5:"count";i:50;s:4:"data";a:3:{i:0;i:0;i:1;i:1;i:2;i:2;}}}';
        $this->assertSame($expected, serialize($result));
    }

    public function testUnSerialize()
    {
        $ao = new \ArrayObject(range(0,2));
        $expected = new Result($ao);

        $expected->setCount(50);

        $string = 'C:21:"Mongator\Query\Result":64:{a:2:{s:5:"count";i:50;s:4:"data";a:3:{i:0;i:0;i:1;i:1;i:2;i:2;}}}';
        $this->assertEquals($expected, unserialize($string));
    }
}


text:
<?php
namespace Codeception\Command\Shared;

use Symfony\Component\Console\Formatter\OutputFormatterStyle;
use Symfony\Component\Console\Output\OutputInterface;

trait Style
{
    public function addStyles(OutputInterface $output)
    {
        $style = new OutputFormatterStyle('white', 'green', ['bold']);
        $output->getFormatter()->setStyle('notice', $style);
        $style = new OutputFormatterStyle(null, null, ['bold']);
        $output->getFormatter()->setStyle('bold', $style);
        $style = new OutputFormatterStyle(null, 'yellow', ['bold']);
        $output->getFormatter()->setStyle('warning', $style);
    }
}


text:
<?php

use yii\helpers\Html;
use yii\widgets\ActiveForm;

/* @var $this yii\web\View */
/* @var $model backend\models\OutTrunkgroupManipulationSearch */
/* @var $form yii\widgets\ActiveForm */
$id = isset($_GET['id'])?$_GET['id']:"";
?>

    <?php $form = ActiveForm::begin([
        'action' => ['index'],
        'id' => $model->formName(),
    ]); ?>

    <?= $form->field($model, 'type')->dropDownList([0=>'Source Number',1 =>'Dest Number'],['prompt'=>'Select Type']) ?>

    <?= $form->field($model, 'search_string') ?>

    <?= $form->field($model, 'replace_string')?>

        <?= $form->field($model, 'out_trunkgroup_id')->textInput(['value'=>$id]) ?>

        <?= Html::submitButton('Search', ['class' => 'btn btn-primary-budi']) ?>
        <?= Html::resetButton('Reset', ['class' => 'btn btn-default']) ?>

    <?php ActiveForm::end(); ?>


text:
from oslo_log import log
from webob import Request
from eventlet.green import socket
from sys import maxint
from time import time

#from swift.common.swob import Request
#from swift.common.utils import get_logger, TRUE_VALUES, split_path

class Informant(object):
    """
    Informant Middleware used for sending events to statsd
    """
    def __init__(self, app, conf, *args, **kwargs):
        self.app = app
        self.logger = log.getLogger('informant')
        self.statsd_host = conf.get('statsd_host', '127.0.0.1')
        self.statsd_port = int(conf.get('statsd_port', '8125'))
        self.statsd_addr = (self.statsd_host, self.statsd_port)
        self.statsd_sample_rate = float(conf.get('statsd_sample_rate', '.5'))
        self.valid_methods = conf.get('valid_http_methods',
                                      'GET,HEAD,POST,PUT,DELETE,COPY')
        self.valid_methods = [s.strip().upper() for s in
                              self.valid_methods.split(',') if s.strip()]
        self.metric_name_prepend = conf.get('metric_name_prepend', '')
        self.metric_name_component = conf.get('metric_name_component', '')
        self.actual_rate = 0.0
        self.counter = 0
        self.monitored = 0

    def _send_events(self, payloads, combined_events=False):
        """Fire the udp events to statsd"""
        try:
            udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
            for payload in payloads:
                udp_socket.sendto(payload, self.statsd_addr)
        except Exception:
            self.logger.exception(_("Error sending statsd event"))

    def _send_sampled_event(self):
        """"
        Track the sample rate and checks to see if this is a request
        that should be sent to statsd.

        :returns: True if the event should be sent to statsd
        """
        send_sample = False
        self.counter += 1
        if self.actual_rate < self.statsd_sample_rate:
            self.monitored += 1
            send_sample = True
        self.actual_rate = float(self.monitored) / float(self.counter)
        if self.counter >= maxint or self.monitored >= maxint:
            self.counter = 0
            self.monitored = 0
        return send_sample

    def statsd_event(self, env, req):
        """generate a statsd event for this request"""
        try:
            if self._send_sampled_event():
                request_method = req.method.upper()
                if request_method not in self.valid_methods:
                    request_method = "BAD_METHOD"
                if 'informant.status' in env:
                    self.logger.exception(env['informant.status'])
                    status_int = env['informant.status']
                    response = getattr(req, 'response', None)
                    if getattr(req, 'client_disconnect', False) or \
                            getattr(response, 'client_disconnect', False):
                        status_int = 499
                else:
                    #start_response never got called for some reason, likely
                    #because something else blew up but we don't know for sure.
                    status_int = 599
                if 'informant.start_time' in env:
                    self.logger.exception(env['informant.start_time'])
                    duration = (time() - env['informant.start_time']) * 1000
                else:
                    duration = 0
                transferred = getattr(req, 'bytes_transferred', 0)
                if transferred is '-' or transferred is 0:
                    transferred = getattr(response, 'bytes_transferred', 0)
                if transferred is '-':
                    transferred = 0

                # Check if we have a NOVA boot request so we can plot it seperately
                if req.path.endswith('/servers') and request_method == 'POST':
                    self.logger.exception('Nova boot request')
                    request_method = 'NOVA_BOOT'

                metric_name = "%s.%s.%s" % (self.metric_name_component, request_method,
                                            status_int)
                counter = "%s%s:1|c|@%s" % (self.metric_name_prepend,
                                            metric_name,
                                            self.statsd_sample_rate)
                timer = "%s%s:%d|ms|@%s" % (self.metric_name_prepend,
                                            metric_name, duration,
                                            self.statsd_sample_rate)
                tfer = "%stfer.%s:%s|c|@%s" % (self.metric_name_prepend,
                                               metric_name, transferred,
                                               self.statsd_sample_rate)
                self._send_events([counter, timer, tfer], self.combined_events)
        except Exception:
            try:
                self.logger.exception(_("Encountered error in statsd_event"))
            except Exception:
                pass

    def __call__(self, env, start_response):

        def _start_response(status, headers, exc_info=None):
            """start_response wrapper to add request status to env"""
            env['informant.status'] = int(status.split(' ', 1)[0])
            start_response(status, headers, exc_info)

        req = Request(env)
        try:
            if 'eventlet.posthooks' in env:
                env['informant.start_time'] = time()
                env['eventlet.posthooks'].append(
                    (self.statsd_event, (req,), {}))
            return self.app(env, _start_response)
        except Exception:
            self.logger.exception('WSGI EXCEPTION:')
            _start_response('500 Internal Server Error',
                            [('Content-Length', '0')])
            return []

def filter_factory(global_conf, **local_conf):
    conf = global_conf.copy()
    conf.update(local_conf)

    def informant_filter(app):
        return Informant(app, conf)
    return informant_filter


text:
import numpy as np
from numpy.lib.stride_tricks import as_strided
from paramz.transformations import Transformation, _lim_val, epsilon

def get_conv_1D(arr, win):
    assert win>0
    arr = arr.copy()
    if win==1:
        return arr
    else:
        return as_strided(arr, shape=(arr.shape[0]-win+1,win)+arr.shape[1:], strides=(arr.strides[0],)+arr.strides)

class LogexpInv(Transformation):
    def f(self, x):
        return np.where(x>_lim_val, x, np.log(np.exp(x+1e-20) - 1.))
    def finv(self, f):
        return np.where(f>_lim_val, f, np.log1p(np.exp(np.clip(f, -_lim_val, _lim_val)))) + epsilon
    def gradfactor(self, f, df):
        return np.einsum('i,i->i', df, np.where(f>_lim_val, 1., 1. - np.exp(-f)))
    def initialize(self, f):
        if np.any(f < 0.):
            print("Warning: changing parameters to satisfy constraints")
        return np.abs(f)
    def log_jacobian(self, model_param):
        return np.where(model_param>_lim_val, model_param, np.log(np.exp(model_param+1e-20) - 1.)) - model_param
    def log_jacobian_grad(self, model_param):
        return 1./(np.exp(model_param)-1.)
    def __str__(self):
        return '+ve'

def comp_mapping(X, Y):
    from GPy.core.parameterization.variational import VariationalPosterior
    X = X.mean.values if isinstance(X, VariationalPosterior) else X
    Y = Y.mean.values if isinstance(Y, VariationalPosterior) else Y
    from scipy.linalg import lstsq
    W = lstsq(X,Y)[0]
    return W


text:
.. currentmodule:: network

class LoRa
==========

This class provides a driver for the LoRa network processor in the **LoPy**. Below is an example demonstrating LoRaWAN Activation by Personalisation usage::

    from network import LoRa
    import socket
    import binascii
    import struct

    # Initialize LoRa in LORAWAN mode.
    lora = LoRa(mode=LoRa.LORAWAN)

    # create an ABP authentication params
    dev_addr = struct.unpack(">l", binascii.unhexlify('00 00 00 05'.replace(' ','')))[0]
    nwk_swkey = binascii.unhexlify('2B 7E 15 16 28 AE D2 A6 AB F7 15 88 09 CF 4F 3C'.replace(' ',''))
    app_swkey = binascii.unhexlify('2B 7E 15 16 28 AE D2 A6 AB F7 15 88 09 CF 4F 3C'.replace(' ',''))

    # join a network using ABP (Activation By Personalization)
    lora.join(activation=LoRa.ABP, auth=(dev_addr, nwk_swkey, app_swkey))

    # create a LoRa socket
    s = socket.socket(socket.AF_LORA, socket.SOCK_RAW)

    # set the LoRaWAN data rate
    s.setsockopt(socket.SOL_LORA, socket.SO_DR, 5)

    # make the socket non-blocking
    s.setblocking(False)

    # send some data
    s.send(bytes([0x01, 0x02, 0x03]))

    # get any data received...
    data = s.recv(64)
    print(data)

.. warning::
  Please ensure that there is an **antenna connected** to your device before sending/receiving LoRa messages as inproper use (e.g. without an antenna), may damage the device.

Additional examples
-------------------

For various other complete LoRa examples, check here for :ref:`additional examples<lora_examples>`.

Constructors
------------

.. class:: LoRa(id=0, ...)

   Create and configure a LoRa object. See ``init`` for params of configuration. ::

        lora = LoRa(mode=LoRa.LORAWAN)

Methods
-------

.. method:: lora.init(mode, \*, frequency=868000000, tx_power=14, bandwidth=LoRa.868000000, sf=7, preamble=8, coding_rate=LoRa.CODING_4_5, power_mode=LoRa.ALWAYS_ON, tx_iq=false, rx_iq=false, adr=false, public=true, tx_retries=1, device_class=LoRa.CLASS_A)

   This method is used to set the LoRa subsystem configuration and to specific raw LoRa or LoRaWAN.

   The arguments are:

     - ``mode`` can be either ``LoRa.LORA`` or ``LoRa.LORAWAN``.
     - ``frequency`` accepts values between 863000000 and 870000000 in the 868 band, or between 902000000 and 928000000 in the 915 band.
     - ``tx_power`` is the transmit power in dBm. It accepts between 2 and 14 for the 868 band, and between 5 and 20 in the 915 band.
     - ``bandwidth`` is the channel bandwidth in KHz. In the 868 band the accepted values are ``LoRa.BW_125KHZ`` and ``LoRa.BW_250KHZ``. In the 915 band the accepted values are ``LoRa.BW_125KHZ`` and ``LoRa.BW_500KHZ``.
     - ``sf`` sets the desired spreading factor. Accepts values between 7 and 12.
     - ``preamble`` configures the number of pre-amble symbols. The default value is 8.
     - ``coding_rate`` can take the following values: ``LoRa.CODING_4_5``, ``LoRa.CODING_4_6``,
       ``LoRa.CODING_4_7`` or ``LoRa.CODING_4_8``.
     - ``power_mode`` can be either ``LoRa.ALWAYS_ON``, ``LoRa.TX_ONLY`` or ``LoRa.SLEEP``. In ``ALWAYS_ON`` mode, the radio is always listening for incoming packets whenever a transmission is not taking place. In ``TX_ONLY`` the radio goes to sleep as soon as the transmission completes. In ``SLEEP`` mode the radio is sent to sleep permanently and won't accept any commands until the power mode is changed.
     - ``tx_iq`` enables TX IQ inversion.
     - ``rx_iq`` enables RX IQ inversion.
     - ``adr`` enables Adaptive Data Rate.
     - ``public`` selects between the public and private sync word.
     - ``tx_retries`` sets the number of TX retries in ``LoRa.LORAWAN`` mode.
     - ``device_class`` sets the LoRaWAN device class. Can be either ``LoRa.CLASS_A`` or ``LoRa.CLASS_C``.

    .. note::

       In ``LoRa.LORAWAN`` mode, only ``adr``, ``public``, ``tx_retries`` and ``device_class`` are used. All the other
       params will be ignored as they are handled by the LoRaWAN stack directly. On the other hand, in ``LoRa.LORA`` mode
       from those 3 arguments, only the ``public`` one is important in order to program the sync word. In ``LoRa.LORA`` mode ``adr``,
       ``tx_retries`` and ``device_class`` are ignored since they are only relevant to the LoRaWAN stack.

   For example, you can do::

      # initialize in raw LoRa mode
      lora.init(mode=LoRa.LORA, tx_power=14, sf=12)

   or::

      # initialize in LoRaWAN mode
      lora.init(mode=LoRa.LORAWAN)

.. method:: lora.join(activation, auth, \*, timeout=None)

    Join a LoRaWAN network. The parameters are:

      - ``activation``: can be either ``LoRa.OTAA`` or ``LoRa.ABP``.
      - ``auth``: is a tuple with the authentication data.

    In the case of ``LoRa.OTAA`` the authentication tuple is: ``(app_eui, app_key)``. Example::

          from network import LoRa
          import socket
          import time
          import binascii

          # Initialize LoRa in LORAWAN mode.
          lora = LoRa(mode=LoRa.LORAWAN)

          # create an OTAA authentication parameters
          app_eui = binascii.unhexlify('AD A4 DA E3 AC 12 67 6B'.replace(' ',''))
          app_key = binascii.unhexlify('11 B0 28 2A 18 9B 75 B0 B4 D2 D8 C7 FA 38 54 8B'.replace(' ',''))

          # join a network using OTAA (Over the Air Activation)
          lora.join(activation=LoRa.OTAA, auth=(app_eui, app_key), timeout=0)

          # wait until the module has joined the network
          while not lora.has_joined():
              time.sleep(2.5)
              print('Not yet joined...')

    In the case of ``LoRa.ABP`` the authentication tuple is: ``(dev_addr, nwk_swkey, app_swkey)``. Example::

          from network import LoRa
          import socket
          import binascii
          import struct

          # Initialize LoRa in LORAWAN mode.
          lora = LoRa(mode=LoRa.LORAWAN)

          # create an ABP authentication params
          dev_addr = struct.unpack(">l", binascii.unhexlify('00 00 00 05'.replace(' ','')))[0]
          nwk_swkey = binascii.unhexlify('2B 7E 15 16 28 AE D2 A6 AB F7 15 88 09 CF 4F 3C'.replace(' ',''))
          app_swkey = binascii.unhexlify('2B 7E 15 16 28 AE D2 A6 AB F7 15 88 09 CF 4F 3C'.replace(' ',''))

          # join a network using ABP (Activation By Personalization)
          lora.join(activation=LoRa.ABP, auth=(dev_addr, nwk_swkey, app_swkey))

.. method:: lora.bandwidth([bandwidth])

    Get or set the bandwidth in raw LoRa mode (``LoRa.LORA``). Can be either ``LoRa.BW_125KHZ`` ``(0)``, ``LoRa.BW_250KHZ`` ``(1)`` or ``LoRa.BW_500KHZ`` ``(2)``.::

		# get raw LoRa Bandwidth
		lora.bandwidth()

		# set raw LoRa Bandwidth
		lora.bandwidth(LoRa.BW_125KHZ)

.. method:: lora.frequency([frequency])

    Get or set the frequency in raw LoRa mode (``LoRa.LORA``). The allowed range is between 863000000 and 870000000 Hz for the 868 MHz band version or between 902000000 and 928000000 Hz for the 915 MHz band version.::

		# get raw LoRa Frequency
		lora.frequency()

		# set raw LoRa Frequency
		lora.frequency(868000000)

.. method:: lora.coding_rate([coding_rate])

    Get or set the coding rate in raw LoRa mode (``LoRa.LORA``). The allowed values are: ``LoRa.CODING_4_5`` ``(0)``, ``LoRa.CODING_4_6`` ``(1)``, ``LoRa.CODING_4_7`` ``(2)`` and ``LoRa.CODING_4_8`` ``(3)``. ::

		# get raw LoRa Coding Rate
		lora.coding_rate()

		# set raw LoRa Coding Rate
		lora.coding_rate(LoRa.CODING_4_5)

.. method:: lora.preamble([preamble])

    Get or set the number of preamble symbols in raw LoRa mode (``LoRa.LORA``).::

		# get raw LoRa preamble symbols
		lora.preamble()

		# set raw LoRa preamble symbols
		lora.preamble(LoRa.CODING_4_5)

.. method:: lora.sf([sf])

    Get or set the spreading factor value in raw LoRa mode (``LoRa.LORA``). The minimmum value is 7 and the maximum is 12.::

		# get raw LoRa spread factor value
		lora.sf()

		# set raw LoRa spread factor value
		lora.sf(7)

.. method:: lora.power_mode([power_mode])

    Get or set the power mode in raw LoRa mode (``LoRa.LORA``). The accepted values are: ``LoRa.ALWAYS_ON``, ``LoRa.TX_ONLY`` and ``LoRa.SLEEP``.::

.. method:: lora.stats()

    Return a named tuple with usefel information from the last received LoRa or LoRaWAN packet. The named tuple has the following form:

    ``(rx_timestamp, rssi, snr, sftx, sfrx, sftx, tx_trials)``

    Example: ::

        lora.stats()

    Where:

       - ``rx_timestamp`` is an internat timestamp of the last received packet with microseconds presicion.
       - ``rssi`` holds the received signal strength in dBm.
       - ``snr`` contains the signal to noise ratio id dB.
       - ``sfrx`` tells the data rate (in the case of ``LORAWAN`` mode) or the spreading factor (in the case of ``LORA`` mode) of the last packet received.
       - ``sftx`` tells the data rate (in the case of ``LORAWAN`` mode) or the spreading factor (in the case of ``LORA`` mode) of the last packet transmitted.
       - ``tx_trials`` is the number of tx attempts of the last transmitted packet (only relevant for ``LORAWAN`` confirmed packets).

.. method:: lora.has_joined()

    Returns ``True`` if a LoRaWAN network has been joined. ``False`` otherwise.::

		lora.has_joined()

.. method:: lora.add_channel(index, \*, frequency, dr_min, dr_max)

    Add a LoRaWAN channel on the specified index. If there's already a channel with that index it will be replaced with the new one.

    The arguments are:

      - ``index``: Index of the channel to add. Accepts values between **0 and 15 for EU** and between **0 and 71 for US**.
      - ``frequency``: Center frequency in Hz of the channel.
      - ``dr_min``: Minimum data rate of the channel (0-7).
      - ``dr_max``: Maximum data rate of the channel (0-7).

	Examples: ::

		lora.add_channel(index=0, frequency=868000000, dr_min=5, dr_max=6)

.. method:: lora.remove_channel(index)

     Removes the channel from the specified index. On the 868MHz band the channels 0 to 2 cannot be removed, they can only be replaced by other channels using the ``lora.add_channel`` method. A way to remove all channels except for one is to add the same channel, 3 times on indexes 0, 1 and 2. An example can be seen below: ::

		 lora.remove_channel()

     On the 915MHz band there are no restrictions around this.

.. method:: lora.mac()

   Returns a byte object with the 8-Byte MAC address of the LoRa radio.::

	   lora.mac()

.. method:: lora.callback(trigger, handler=None, arg=None)

   Specify a callback handler for the LoRa radio. The trigger types are ``LoRa.RX_PACKET_EVENT``, ``LoRa.TX_PACKET_EVENT`` and ``LoRa.TX_FAILED_EVENT``

   The ``LoRa.RX_PACKET_EVENT` event is raised for every received packet.
   The ``LoRa.TX_PACKET_EVENT`` event is raised as soon as the packet transmisison cycle ends. In the case of non-confirmed transmissions, this will occur at the end of the
   receive windows, but, in the case of confirmed transmissions, this event will only be raised if the **ack** is received. If the **ack** is not received ``LoRa.TX_FAILED_EVENT``
   will be raised after the number of ``tx_retries`` configured have been performed.

   An example of how this callback functions can be seen the in method :ref:`lora.events() <lora_events>`.

.. method:: lora.ischannel_free(rssi_threshold)

    This method is used to check for radio activity on the current LoRa channel, and if the rssi of the measured activity is lower than the `rssi_threshold` given, the return value will
    be ``True``, otherwise ``False``. Example::

        lora.ischannel_free(-100)

.. method:: lora.set_battery_level(level)

    Set the battery level value that will be sent when the LoRaWAN MAC command that retrieves the battery level is received. This command is sent by the network and handled
    automatically by the LoRaWAN stack. Value should be in percentage, from 0 to 100. Values larger than 100 will be clipped.::

        lora.set_battery_level(75)

.. _lora_events:

.. method:: lora.events()

   This method returns a value with bits sets (if any) indicating the events that have triggered the callback. Please note that
   by calling this function the internal events registry is cleared automatically, therefore calling it immediately for a second time
   will most likely return a value of 0.

   Example::

        def lora_cb(lora):
            events = lora.events()
            if events & LoRa.RX_PACKET_EVENT:
                print('Lora packet received')
            if events & LoRa.TX_PACKET_EVENT:
                print('Lora packet sent')

        lora.callback(trigger=(LoRa.RX_PACKET_EVENT | LoRa.TX_PACKET_EVENT), handler=lora_cb)

Constants
---------

.. data:: LoRa.LORA
          LoRa.LORAWAN

    LoRa stack mode

.. data:: LoRa.OTAA
          LoRa.ABP

    LoRaWAN join procedure

.. data:: LoRa.ALWAYS_ON
          LoRa.TX_ONLY
          LoRa.SLEEP

    Raw LoRa power mode

.. data:: LoRa.BW_125KHZ
          LoRa.BW_250KHZ
          LoRa.BW_500KHZ

    Raw LoRa bandwidth

.. data:: LoRa.CODING_4_5
          LoRa.CODING_4_6
          LoRa.CODING_4_7
          LoRa.CODING_4_8

    Raw LoRa coding rate

.. data:: LoRa.RX_PACKET_EVENT
          LoRa.TX_PACKET_EVENT
          LoRa.TX_FAILED_EVENT

    Callback trigger types (may be ORed)

.. data:: LoRa.CLASS_A
          LoRa.CLASS_C

    LoRaWAN device class

Working with LoRa and LoRaWAN sockets
-------------------------------------

LoRa sockets are created in the following way::

   import socket
   s = socket.socket(socket.AF_LORA, socket.SOCK_RAW)

And they **must** be created after initializing the LoRa network card.

LoRa sockets support the following standard methods from the :class:`socket <.socket>` module:

.. method:: socket.close()

   Usage: ``s.close()``

.. method:: socket.bind(port_number)

   Usage: ``s.bind(1)``

   .. note::

      The ``.bind()`` method is only applicable when the radio is configured in ``LoRa.LORAWAN`` mode.

.. method:: socket.send(bytes)

   Usage: ``s.send(bytes([1, 2, 3]))`` or: ``s.send('Hello')``

.. method:: socket.recv(bufsize)

   Usage: ``s.recv(128)``

.. method:: socket.setsockopt(level, optname, value)

   Set the value of the given socket option. The needed symbolic constants are defined in the
   socket module (SO_* etc.). In the case of LoRa the values are always integers. Examples::

      # configuring the data rate
      s.setsockopt(socket.SOL_LORA, socket.SO_DR, 5)

      # selecting non-confirmed type of messages
      s.setsockopt(socket.SOL_LORA, socket.SO_CONFIRMED, False)

      # selecting confirmed type of messages
      s.setsockopt(socket.SOL_LORA, socket.SO_CONFIRMED, True)

   .. note::

      Socket options are only applicable when the LoRa radio is used in ``LoRa.LORAWAN`` mode.
      When using the radio in ``LoRa.LORA`` mode, use the class methods to change the spreading
      factor, bandwidth and coding rate to the desired values.

.. method:: socket.settimeout(value)

   Sets the socket timeout value in seconds. Accepts floating point values.

   Usage: ``s.settimeout(5.5)``

.. method:: socket.setblocking(flag)

   Usage: ``s.setblocking(True)``


text:
<?xml version="1.0" encoding="UTF-8"?>
<constraint-mapping xmlns="http://symfony.com/schema/dic/constraint-mapping"
                    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                    xsi:schemaLocation="http://symfony.com/schema/dic/constraint-mapping
        http://symfony.com/schema/dic/constraint-mapping/constraint-mapping-1.0.xsd">

    <class name="AppBundle\Models\UserSignUp">
        <property name="firstName">
            <constraint name="NotBlank" />
            <constraint name="Length">
                <option name="min">1</option>
            </constraint>
        </property>
        <property name="lastName">
            <constraint name="NotBlank" />
            <constraint name="Length">
                <option name="min">1</option>
            </constraint>
        </property>
        <property name="email">
            <constraint name="Email" />
        </property>
        <property name="plainTextPassword">
            <constraint name="Length">
                <option name="min">8</option>
            </constraint>
            <constraint name="Regex">
                <option name="pattern">/^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,}$/</option>
                <option name="message">user_sign_up.form.password.policy.error_message</option>
            </constraint>
        </property>
    </class>
</constraint-mapping>