text:
package net.floodlightcontroller.loadbalancer;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Comparator;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.openflow.protocol.OFFlowMod;
import org.openflow.protocol.OFMatch;
import org.openflow.protocol.OFMessage;
import org.openflow.protocol.OFOXMFieldType;
import org.openflow.protocol.OFPacketIn;
import org.openflow.protocol.OFPacketOut;
import org.openflow.protocol.OFPort;
import org.openflow.protocol.OFGroup;
import org.openflow.protocol.OFType;
import org.openflow.protocol.action.OFAction;
import org.openflow.protocol.instruction.OFInstruction;
import org.openflow.protocol.instruction.OFInstructionApplyActions;
import org.openflow.protocol.action.OFActionSetField;
import org.openflow.protocol.action.OFActionSetQueue;
import org.openflow.protocol.action.OFActionOutput;
import org.openflow.protocol.action.OFActionPopVLAN;
import org.openflow.util.HexString;
import org.openflow.util.U16;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import net.floodlightcontroller.core.FloodlightContext;
import net.floodlightcontroller.core.IFloodlightProviderService;
import net.floodlightcontroller.core.IOFMessageListener;
import net.floodlightcontroller.core.IOFSwitch;
import net.floodlightcontroller.core.module.FloodlightModuleContext;
import net.floodlightcontroller.core.module.FloodlightModuleException;
import net.floodlightcontroller.core.module.IFloodlightModule;
import net.floodlightcontroller.core.module.IFloodlightService;
import net.floodlightcontroller.counter.ICounterStoreService;
import net.floodlightcontroller.devicemanager.IDevice;
import net.floodlightcontroller.devicemanager.IDeviceService;
import net.floodlightcontroller.devicemanager.SwitchPort;
import net.floodlightcontroller.packet.ARP;
import net.floodlightcontroller.packet.Ethernet;
import net.floodlightcontroller.packet.ICMP;
import net.floodlightcontroller.packet.IPacket;
import net.floodlightcontroller.packet.IPv4;
import net.floodlightcontroller.packet.TCP;
import net.floodlightcontroller.packet.UDP;
import net.floodlightcontroller.restserver.IRestApiService;
import net.floodlightcontroller.routing.IRoutingService;
import net.floodlightcontroller.routing.Route;
import net.floodlightcontroller.staticflowentry.IStaticFlowEntryPusherService;
import net.floodlightcontroller.topology.ITopologyService;
import net.floodlightcontroller.topology.NodePortTuple;
import net.floodlightcontroller.util.MACAddress;
import net.floodlightcontroller.util.OFMessageDamper;

/**
 * A simple load balancer module for ping, tcp, and udp flows. This module is accessed
 * via a REST API defined close to the OpenStack Quantum LBaaS (Load-balancer-as-a-Service)
 * v1.0 API proposal. Since the proposal has not been final, no efforts have yet been
 * made to confirm compatibility at this time.
 *
 * Limitations:
 * - client records and static flows not purged after use, will exhaust switch flow tables over time
 * - round robin policy among servers based on connections, not traffic volume
 * - health monitoring feature not implemented yet
 *
 * @author kcwang
 */
public class LoadBalancer implements IFloodlightModule,
    ILoadBalancerService, IOFMessageListener {

    protected static Logger log = LoggerFactory.getLogger(LoadBalancer.class);

    // Our dependencies
    protected IFloodlightProviderService floodlightProvider;
    protected IRestApiService restApi;

    protected ICounterStoreService counterStore;
    protected OFMessageDamper messageDamper;
    protected IDeviceService deviceManager;
    protected IRoutingService routingEngine;
    protected ITopologyService topology;
    protected IStaticFlowEntryPusherService sfp;

    protected HashMap<String, LBVip> vips;
    protected HashMap<String, LBPool> pools;
    protected HashMap<String, LBMember> members;
    protected HashMap<Integer, String> vipIpToId;
    protected HashMap<Integer, MACAddress> vipIpToMac;
    protected HashMap<Integer, String> memberIpToId;
    protected HashMap<IPClient, LBMember> clientToMember;

    //Copied from Forwarding with message damper routine for pushing proxy Arp
    protected static int OFMESSAGE_DAMPER_CAPACITY = 10000; // ms.
    protected static int OFMESSAGE_DAMPER_TIMEOUT = 250; // ms
    protected static String LB_ETHER_TYPE = "0x800";
    protected static int LB_PRIORITY = 32768;

    // Comparator for sorting by SwitchCluster
    public Comparator<SwitchPort> clusterIdComparator =
            new Comparator<SwitchPort>() {
                @Override
                public int compare(SwitchPort d1, SwitchPort d2) {
                    Long d1ClusterId =
                            topology.getL2DomainId(d1.getSwitchDPID());
                    Long d2ClusterId =
                            topology.getL2DomainId(d2.getSwitchDPID());
                    return d1ClusterId.compareTo(d2ClusterId);
                }
            };

    // data structure for storing connected
    public class IPClient {
        int ipAddress;
        byte nw_proto;
        short srcPort; // tcp/udp src port. icmp type (OFMatch convention)
        short targetPort; // tcp/udp dst port, icmp code (OFMatch convention)

        public IPClient() {
            ipAddress = 0;
            nw_proto = 0;
            srcPort = -1;
            targetPort = -1;
        }
    }

    @Override
    public String getName() {
        return "loadbalancer";
    }

    @Override
    public boolean isCallbackOrderingPrereq(OFType type, String name) {
        return (type.equals(OFType.PACKET_IN) &&
                (name.equals("topology") ||
                 name.equals("devicemanager") ||
                 name.equals("virtualizer")));
    }

    @Override
    public boolean isCallbackOrderingPostreq(OFType type, String name) {
        return (type.equals(OFType.PACKET_IN) && name.equals("forwarding"));
   }

    @Override
    public net.floodlightcontroller.core.IListener.Command
            receive(IOFSwitch sw, OFMessage msg, FloodlightContext cntx) {
        switch (msg.getType()) {
            case PACKET_IN:
                return processPacketIn(sw, (OFPacketIn)msg, cntx);
            default:
                break;
        }
        log.warn("Received unexpected message {}", msg);
        return Command.CONTINUE;
    }

    private net.floodlightcontroller.core.IListener.Command
            processPacketIn(IOFSwitch sw, OFPacketIn pi,
                            FloodlightContext cntx) {

        Ethernet eth = IFloodlightProviderService.bcStore.get(cntx,
                                                              IFloodlightProviderService.CONTEXT_PI_PAYLOAD);
        IPacket pkt = eth.getPayload();

        if (eth.isBroadcast() || eth.isMulticast()) {
            // handle ARP for VIP
            if (pkt instanceof ARP) {
                // retrieve arp to determine target IP address
                ARP arpRequest = (ARP) eth.getPayload();

                int targetProtocolAddress = IPv4.toIPv4Address(arpRequest
                                                               .getTargetProtocolAddress());

                if (vipIpToId.containsKey(targetProtocolAddress)) {
                    String vipId = vipIpToId.get(targetProtocolAddress);
                    vipProxyArpReply(sw, pi, cntx, vipId);
                    return Command.STOP;
                }
            }
        } else {
            // currently only load balance IPv4 packets - no-op for other traffic
            if (pkt instanceof IPv4) {
                IPv4 ip_pkt = (IPv4) pkt;

                // If match Vip and port, check pool and choose member
                int destIpAddress = ip_pkt.getDestinationAddress();

                if (vipIpToId.containsKey(destIpAddress)){
                    IPClient client = new IPClient();
                    client.ipAddress = ip_pkt.getSourceAddress();
                    client.nw_proto = ip_pkt.getProtocol();
                    if (ip_pkt.getPayload() instanceof TCP) {
                        TCP tcp_pkt = (TCP) ip_pkt.getPayload();
                        client.srcPort = tcp_pkt.getSourcePort();
                        client.targetPort = tcp_pkt.getDestinationPort();
                    }
                    if (ip_pkt.getPayload() instanceof UDP) {
                        UDP udp_pkt = (UDP) ip_pkt.getPayload();
                        client.srcPort = udp_pkt.getSourcePort();
                        client.targetPort = udp_pkt.getDestinationPort();
                    }
                    if (ip_pkt.getPayload() instanceof ICMP) {
                        client.srcPort = 8;
                        client.targetPort = 0;
                    }

                    LBVip vip = vips.get(vipIpToId.get(destIpAddress));
                    LBPool pool = pools.get(vip.pickPool(client));
                    LBMember member = members.get(pool.pickMember(client));

                    // for chosen member, check device manager and find and push routes, in both directions
                    pushBidirectionalVipRoutes(sw, pi, cntx, client, member);

                    // packet out based on table rule
                    pushPacket(pkt, sw, pi.getBufferId(), pi.getInPort(), OFPort.OFPP_TABLE.getValue(),
                                cntx, true);

                    return Command.STOP;
                }
            }
        }
        // bypass non-load-balanced traffic for normal processing (forwarding)
        return Command.CONTINUE;
    }

    /**
     * used to send proxy Arp for load balanced service requests
     * @param IOFSwitch sw
     * @param OFPacketIn pi
     * @param FloodlightContext cntx
     * @param String vipId
     */

    protected void vipProxyArpReply(IOFSwitch sw, OFPacketIn pi, FloodlightContext cntx, String vipId) {
        log.debug("vipProxyArpReply");

        Ethernet eth = IFloodlightProviderService.bcStore.get(cntx,
                                                              IFloodlightProviderService.CONTEXT_PI_PAYLOAD);

        // retrieve original arp to determine host configured gw IP address
        if (! (eth.getPayload() instanceof ARP))
            return;
        ARP arpRequest = (ARP) eth.getPayload();

        // have to do proxy arp reply since at this point we cannot determine the requesting application type
        byte[] vipProxyMacBytes = vips.get(vipId).proxyMac.toBytes();

        // generate proxy ARP reply
        IPacket arpReply = new Ethernet()
            .setSourceMACAddress(vipProxyMacBytes)
            .setDestinationMACAddress(eth.getSourceMACAddress())
            .setEtherType(Ethernet.TYPE_ARP)
            .setVlanID(eth.getVlanID())
            .setPriorityCode(eth.getPriorityCode())
            .setPayload(
                new ARP()
                .setHardwareType(ARP.HW_TYPE_ETHERNET)
                .setProtocolType(ARP.PROTO_TYPE_IP)
                .setHardwareAddressLength((byte) 6)
                .setProtocolAddressLength((byte) 4)
                .setOpCode(ARP.OP_REPLY)
                .setSenderHardwareAddress(vipProxyMacBytes)
                .setSenderProtocolAddress(
                        arpRequest.getTargetProtocolAddress())
                .setTargetHardwareAddress(
                        eth.getSourceMACAddress())
                .setTargetProtocolAddress(
                        arpRequest.getSenderProtocolAddress()));

        // push ARP reply out
        pushPacket(arpReply, sw, OFPacketOut.BUFFER_ID_NONE, OFPort.OFPP_ANY.getValue(),
                   pi.getInPort(), cntx, true);
        log.debug("proxy ARP reply pushed as {}", IPv4.fromIPv4Address(vips.get(vipId).address));

        return;
    }

    /**
     * used to push any packet - borrowed routine from Forwarding
     *
     * @param OFPacketIn pi
     * @param IOFSwitch sw
     * @param int bufferId
     * @param int inPort
     * @param int outPort
     * @param FloodlightContext cntx
     * @param boolean flush
     */
    public void pushPacket(IPacket packet,
                           IOFSwitch sw,
                           int bufferId,
                           int inPort,
                           int outPort,
                           FloodlightContext cntx,
                           boolean flush) {
        if (log.isTraceEnabled()) {
            log.trace("PacketOut srcSwitch={} inPort={} outPort={}",
                      new Object[] {sw, inPort, outPort});
        }

        OFPacketOut po =
                (OFPacketOut) floodlightProvider.getOFMessageFactory()
                                                .getMessage(OFType.PACKET_OUT);

        // set actions
        List<OFAction> actions = new ArrayList<OFAction>();
        actions.add(new OFActionOutput(outPort, (short) 0xffff));

        po.setActions(actions);

        // set buffer_id, in_port
        po.setBufferId(bufferId);
        po.setInPort(inPort);

        // set data - only if buffer_id == -1
        if (po.getBufferId() == OFPacketOut.BUFFER_ID_NONE) {
            if (packet == null) {
                log.error("BufferId is not set and packet data is null. " +
                          "Cannot send packetOut. " +
                        "srcSwitch={} inPort={} outPort={}",
                        new Object[] {sw, inPort, outPort});
                return;
            }
            byte[] packetData = packet.serialize();
            po.setPacketData(packetData);
        }

        try {
            counterStore.updatePktOutFMCounterStoreLocal(sw, po);
            messageDamper.write(sw, po, cntx, flush);
        } catch (IOException e) {
            log.error("Failure writing packet out", e);
        }
    }

    /**
     * used to find and push in-bound and out-bound routes using StaticFlowEntryPusher
     * @param IOFSwitch sw
     * @param OFPacketIn pi
     * @param FloodlightContext cntx
     * @param IPClient client
     * @param LBMember member
     */
    protected void pushBidirectionalVipRoutes(IOFSwitch sw, OFPacketIn pi, FloodlightContext cntx, IPClient client, LBMember member) {

        // borrowed code from Forwarding to retrieve src and dst device entities
        // Check if we have the location of the destination
        IDevice srcDevice = null;
        IDevice dstDevice = null;

        // retrieve all known devices
        Collection<? extends IDevice> allDevices = deviceManager
                .getAllDevices();

        for (IDevice d : allDevices) {
            for (int j = 0; j < d.getIPv4Addresses().length; j++) {
                    if (srcDevice == null && client.ipAddress == d.getIPv4Addresses()[j])
                        srcDevice = d;
                    if (dstDevice == null && member.address == d.getIPv4Addresses()[j]) {
                        dstDevice = d;
                        member.macString = dstDevice.getMACAddressString();
                    }
                    if (srcDevice != null && dstDevice != null)
                        break;
            }
        }

        // srcDevice and/or dstDevice is null, no route can be pushed
        if (srcDevice == null || dstDevice == null) return;

        Long srcIsland = topology.getL2DomainId(sw.getId());

        if (srcIsland == null) {
            log.debug("No openflow island found for source {}/{}",
                      sw.getStringId(), pi.getInPort());
            return;
        }

        // Validate that we have a destination known on the same island
        // Validate that the source and destination are not on the same switchport
        boolean on_same_island = false;
        boolean on_same_if = false;
        for (SwitchPort dstDap : dstDevice.getAttachmentPoints()) {
            long dstSwDpid = dstDap.getSwitchDPID();
            Long dstIsland = topology.getL2DomainId(dstSwDpid);
            if ((dstIsland != null) && dstIsland.equals(srcIsland)) {
                on_same_island = true;
                if ((sw.getId() == dstSwDpid) &&
                        (pi.getInPort() == dstDap.getPort())) {
                    on_same_if = true;
                }
                break;
            }
        }

        if (!on_same_island) {
            // Flood since we don't know the dst device
            if (log.isTraceEnabled()) {
                log.trace("No first hop island found for destination " +
                        "device {}, Action = flooding", dstDevice);
            }
            return;
        }

        if (on_same_if) {
            if (log.isTraceEnabled()) {
                log.trace("Both source and destination are on the same " +
                        "switch/port {}/{}, Action = NOP",
                        sw.toString(), pi.getInPort());
            }
            return;
        }

        // Install all the routes where both src and dst have attachment
        // points.  Since the lists are stored in sorted order we can
        // traverse the attachment points in O(m+n) time
        SwitchPort[] srcDaps = srcDevice.getAttachmentPoints();
        Arrays.sort(srcDaps, clusterIdComparator);
        SwitchPort[] dstDaps = dstDevice.getAttachmentPoints();
        Arrays.sort(dstDaps, clusterIdComparator);

        int iSrcDaps = 0, iDstDaps = 0;

        // following Forwarding's same routing routine, retrieve both in-bound and out-bound routes for
        // all clusters.
        while ((iSrcDaps < srcDaps.length) && (iDstDaps < dstDaps.length)) {
            SwitchPort srcDap = srcDaps[iSrcDaps];
            SwitchPort dstDap = dstDaps[iDstDaps];
            Long srcCluster =
                    topology.getL2DomainId(srcDap.getSwitchDPID());
            Long dstCluster =
                    topology.getL2DomainId(dstDap.getSwitchDPID());

            int srcVsDest = srcCluster.compareTo(dstCluster);
            if (srcVsDest == 0) {
                if (!srcDap.equals(dstDap) &&
                        (srcCluster != null) &&
                        (dstCluster != null)) {
                    Route routeIn =
                            routingEngine.getRoute(srcDap.getSwitchDPID(),
                                                   (short)srcDap.getPort(),
                                                   dstDap.getSwitchDPID(),
                                                   (short)dstDap.getPort(), 0);
                    Route routeOut =
                            routingEngine.getRoute(dstDap.getSwitchDPID(),
                                                   (short)dstDap.getPort(),
                                                   srcDap.getSwitchDPID(),
                                                   (short)srcDap.getPort(), 0);

                    // use static flow entry pusher to push flow mod along in and out path
                    // in: match src client (ip, port), rewrite dest from vip ip/port to member ip/port, forward
                    // out: match dest client (ip, port), rewrite src from member ip/port to vip ip/port, forward

                    if (routeIn != null) {
                        pushStaticVipRoute(true, routeIn, client, member, sw.getId());
                    }

                    if (routeOut != null) {
                        pushStaticVipRoute(false, routeOut, client, member, sw.getId());
                    }

                }
                iSrcDaps++;
                iDstDaps++;
            } else if (srcVsDest < 0) {
                iSrcDaps++;
            } else {
                iDstDaps++;
            }
        }
        return;
    }

    /**
     * used to push given route using static flow entry pusher
     * @param boolean inBound
     * @param Route route
     * @param IPClient client
     * @param LBMember member
     * @param long pinSwitch
     */
    public void pushStaticVipRoute(boolean inBound, Route route, IPClient client, LBMember member, long pinSwitch) {
        List<NodePortTuple> path = route.getPath();
        if (path.size()>0) {
           for (int i = 0; i < path.size(); i+=2) {

               long sw = path.get(i).getNodeId();
               String swString = HexString.toHexString(path.get(i).getNodeId());
               String entryName;
               String matchString = null;
               String actionString = null;

               OFFlowMod fm = (OFFlowMod) floodlightProvider.getOFMessageFactory()
                       .getMessage(OFType.FLOW_MOD);

               fm.setIdleTimeout((short) 0);   // infinite
               fm.setHardTimeout((short) 0);   // infinite
               fm.setBufferId(OFPacketOut.BUFFER_ID_NONE);
               fm.setCommand((byte) 0);
               fm.setFlags((short) 0);
               fm.setOutPort(OFPort.OFPP_ANY.getValue());
               fm.setOutGroup(OFGroup.OFPG_ANY.getValue());
               fm.setCookie((long) 0);
               fm.setPriority(Short.MAX_VALUE);

               if (inBound) {
                   entryName = "inbound-vip-"+ member.vipId+"-client-"+client.ipAddress+"-port-"+client.targetPort
                           +"-srcswitch-"+path.get(0).getNodeId()+"-sw-"+sw;
                   matchString = "nw_src="+IPv4.fromIPv4Address(client.ipAddress)+","
                               + "nw_proto="+String.valueOf(client.nw_proto)+","
                               + "tp_src="+String.valueOf(client.srcPort & 0xffff)+","
                               + "dl_type="+LB_ETHER_TYPE+","
                               + "in_port="+String.valueOf(path.get(i).getPortId());

                   if (sw == pinSwitch) {
                       actionString = "set-dst-ip="+IPv4.fromIPv4Address(member.address)+","
                                + "set-dst-mac="+member.macString+","
                                + "output="+path.get(i+1).getPortId();
                   } else {
                       actionString =
                               "output="+path.get(i+1).getPortId();
                   }
               } else {
                   entryName = "outbound-vip-"+ member.vipId+"-client-"+client.ipAddress+"-port-"+client.targetPort
                           +"-srcswitch-"+path.get(0).getNodeId()+"-sw-"+sw;
                   matchString = "nw_dst="+IPv4.fromIPv4Address(client.ipAddress)+","
                               + "nw_proto="+String.valueOf(client.nw_proto)+","
                               + "tp_dst="+String.valueOf(client.srcPort & 0xffff)+","
                               + "dl_type="+LB_ETHER_TYPE+","
                               + "in_port="+String.valueOf(path.get(i).getPortId());

                   if (sw == pinSwitch) {
                       actionString = "set-src-ip="+IPv4.fromIPv4Address(vips.get(member.vipId).address)+","
                               + "set-src-mac="+vips.get(member.vipId).proxyMac.toString()+","
                               + "output="+path.get(i+1).getPortId();
                   } else {
                       actionString = "output="+path.get(i+1).getPortId();
                   }

               }

               parseActionString(fm, actionString, log);

               fm.setPriority(U16.t(LB_PRIORITY));

               OFMatch ofMatch = new OFMatch();
               try {
                   ofMatch.fromString(matchString);
               } catch (IllegalArgumentException e) {
                   log.debug("ignoring flow entry {} on switch {} with illegal OFMatch() key: "
                                     + matchString, entryName, swString);
               }

               fm.setMatch(ofMatch);
               sfp.addFlow(entryName, fm, swString);

           }
        }
        return;
    }

    @Override
    public Collection<LBVip> listVips() {
        return vips.values();
    }

    @Override
    public Collection<LBVip> listVip(String vipId) {
        Collection<LBVip> result = new HashSet<LBVip>();
        result.add(vips.get(vipId));
        return result;
    }

    @Override
    public LBVip createVip(LBVip vip) {
        if (vip == null)
            vip = new LBVip();

        vips.put(vip.id, vip);
        vipIpToId.put(vip.address, vip.id);
        vipIpToMac.put(vip.address, vip.proxyMac);

        return vip;
    }

    @Override
    public LBVip updateVip(LBVip vip) {
        vips.put(vip.id, vip);
        return vip;
    }

    @Override
    public int removeVip(String vipId) {
        if(vips.containsKey(vipId)){
            vips.remove(vipId);
            return 0;
        } else {
            return -1;
        }
    }

    @Override
    public Collection<LBPool> listPools() {
        return pools.values();
    }

    @Override
    public Collection<LBPool> listPool(String poolId) {
        Collection<LBPool> result = new HashSet<LBPool>();
        result.add(pools.get(poolId));
        return result;
    }

    @Override
    public LBPool createPool(LBPool pool) {
        if (pool==null)
            pool = new LBPool();

        pools.put(pool.id, pool);
        if (pool.vipId != null && vips.containsKey(pool.vipId))
            vips.get(pool.vipId).pools.add(pool.id);
        else {
            log.error("specified vip-id must exist");
            pool.vipId = null;
            pools.put(pool.id, pool);
        }
        return pool;
    }

    @Override
    public LBPool updatePool(LBPool pool) {
        pools.put(pool.id, pool);
        return null;
    }

    @Override
    public int removePool(String poolId) {
        LBPool pool;
        if(pools!=null){
            pool = pools.get(poolId);
            if (pool.vipId != null)
                vips.get(pool.vipId).pools.remove(poolId);
            pools.remove(poolId);
            return 0;
        } else {
            return -1;
        }
    }

    @Override
    public Collection<LBMember> listMembers() {
        return members.values();
    }

    @Override
    public Collection<LBMember> listMember(String memberId) {
        Collection<LBMember> result = new HashSet<LBMember>();
        result.add(members.get(memberId));
        return result;
        }

    @Override
    public Collection<LBMember> listMembersByPool(String poolId) {
        Collection<LBMember> result = new HashSet<LBMember>();

        if(pools.containsKey(poolId)) {
            ArrayList<String> memberIds = pools.get(poolId).members;
            for (int i=0; i<memberIds.size(); i++)
                result.add(members.get(memberIds.get(i)));
        }
        return result;
    }

    @Override
    public LBMember createMember(LBMember member) {
        if (member == null)
            member = new LBMember();

        members.put(member.id, member);
        memberIpToId.put(member.address, member.id);

        if (member.poolId != null && pools.get(member.poolId) != null) {
            member.vipId = pools.get(member.poolId).vipId;
            if (!pools.get(member.poolId).members.contains(member.id))
                pools.get(member.poolId).members.add(member.id);
        } else
            log.error("member must be specified with non-null pool_id");

        return member;
    }

    @Override
    public LBMember updateMember(LBMember member) {
        members.put(member.id, member);
        return member;
    }

    @Override
    public int removeMember(String memberId) {
        LBMember member;
        member = members.get(memberId);

        if(member != null){
            if (member.poolId != null)
                pools.get(member.poolId).members.remove(memberId);
            members.remove(memberId);
            return 0;
        } else {
            return -1;
        }
    }

    @Override
    public Collection<LBMonitor> listMonitors() {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public Collection<LBMonitor> listMonitor(String monitorId) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public LBMonitor createMonitor(LBMonitor monitor) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public LBMonitor updateMonitor(LBMonitor monitor) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public int removeMonitor(String monitorId) {
        // TODO Auto-generated method stub
        return 0;
    }

    @Override
    public Collection<Class<? extends IFloodlightService>>
            getModuleServices() {
        Collection<Class<? extends IFloodlightService>> l =
                new ArrayList<Class<? extends IFloodlightService>>();
        l.add(ILoadBalancerService.class);
        return l;
   }

    @Override
    public Map<Class<? extends IFloodlightService>, IFloodlightService>
            getServiceImpls() {
        Map<Class<? extends IFloodlightService>, IFloodlightService> m =
                new HashMap<Class<? extends IFloodlightService>,
                    IFloodlightService>();
        m.put(ILoadBalancerService.class, this);
        return m;
    }

    @Override
    public Collection<Class<? extends IFloodlightService>>
            getModuleDependencies() {
        Collection<Class<? extends IFloodlightService>> l =
                new ArrayList<Class<? extends IFloodlightService>>();
        l.add(IFloodlightProviderService.class);
        l.add(IRestApiService.class);
        l.add(ICounterStoreService.class);
        l.add(IDeviceService.class);
        l.add(ITopologyService.class);
        l.add(IRoutingService.class);
        l.add(IStaticFlowEntryPusherService.class);

        return l;
    }

    @Override
    public void init(FloodlightModuleContext context)
                                                 throws FloodlightModuleException {
        floodlightProvider = context.getServiceImpl(IFloodlightProviderService.class);
        restApi = context.getServiceImpl(IRestApiService.class);
        counterStore = context.getServiceImpl(ICounterStoreService.class);
        deviceManager = context.getServiceImpl(IDeviceService.class);
        routingEngine = context.getServiceImpl(IRoutingService.class);
        topology = context.getServiceImpl(ITopologyService.class);
        sfp = context.getServiceImpl(IStaticFlowEntryPusherService.class);

        messageDamper = new OFMessageDamper(OFMESSAGE_DAMPER_CAPACITY,
                                            EnumSet.of(OFType.FLOW_MOD),
                                            OFMESSAGE_DAMPER_TIMEOUT);

        vips = new HashMap<String, LBVip>();
        pools = new HashMap<String, LBPool>();
        members = new HashMap<String, LBMember>();
        vipIpToId = new HashMap<Integer, String>();
        vipIpToMac = new HashMap<Integer, MACAddress>();
        memberIpToId = new HashMap<Integer, String>();
    }

    @Override
    public void startUp(FloodlightModuleContext context) {
        floodlightProvider.addOFMessageListener(OFType.PACKET_IN, this);
        restApi.addRestletRoutable(new LoadBalancerWebRoutable());
    }

    /**
     * Parses OFFlowMod actions from strings.
     * @param flowMod The OFFlowMod to set the actions for
     * @param actionstr The string containing all the actions
     * @param log A logger to log for errors.
     */
    public static void parseActionString(OFFlowMod flowMod, String actionstr, Logger log) {
        List<OFAction> actions = new LinkedList<OFAction>();
        List<OFInstruction> instructions = new LinkedList<OFInstruction>();
        if (actionstr != null) {
            actionstr = actionstr.toLowerCase();
            for (String subaction : actionstr.split(",")) {
                String action = subaction.split("[=:]")[0];
                OFAction subaction_struct = null;

                if (action.equals("output")) {
                    subaction_struct = decode_output(subaction, log);
                }
                else if (action.equals("set-queue")) {
                    subaction_struct = decode_set_queue(subaction, log);
                }
                else if (action.equals("strip-vlan")) {
                    subaction_struct = decode_strip_vlan(subaction, log);
                }
                else if (action.equals("set-vlan-id")) {
                    subaction_struct = decode_set_vlan_id(subaction, log);
                }
                else if (action.equals("set-vlan-priority")) {
                    subaction_struct = decode_set_vlan_priority(subaction, log);
                }
                else if (action.equals("set-src-mac")) {
                    subaction_struct = decode_set_src_mac(subaction, log);
                }
                else if (action.equals("set-dst-mac")) {
                    subaction_struct = decode_set_dst_mac(subaction, log);
                }
                else if (action.equals("set-tos-bits")) {
                    subaction_struct = decode_set_tos_bits(subaction, log);
                }
                else if (action.equals("set-src-ip")) {
                    subaction_struct = decode_set_src_ip(subaction, log);
                }
                else if (action.equals("set-dst-ip")) {
                    subaction_struct = decode_set_dst_ip(subaction, log);
                }
                /* In OF1.3, there is no action for generalized TP_SRC, TP_DST.
                 * It is specific to TCP, UDP, SCTP
                 */
                else if (action.equals("set-tcp-sport")) {
                    subaction_struct = decode_set_tcp_sport(subaction, log);
                }
                else if (action.equals("set-tcp-dport")) {
                    subaction_struct = decode_set_tcp_dport(subaction, log);
                }
                else if (action.equals("set-udp-sport")) {
                    subaction_struct = decode_set_udp_sport(subaction, log);
                }
                else if (action.equals("set-udp-dport")) {
                    subaction_struct = decode_set_udp_dport(subaction, log);
                }
                else {
                    log.error("Unexpected action '{}', '{}'", action, subaction);
                }

                if (subaction_struct != null) {
                    actions.add(subaction_struct);
                }
            }
        }
        log.debug("action {}", actions);
        instructions.add(new OFInstructionApplyActions().setActions(actions));
        flowMod.setInstructions(instructions);
    }

    private static OFAction decode_output(String subaction, Logger log) {
    	OFActionOutput sa = null;
        Matcher n;

        n = Pattern.compile("output=(?:((?:0x)?\\d+)|(all)|(controller)|(local)|(ingress-port)|(normal)|(flood))").matcher(subaction);
        if (n.matches()) {
            sa = new OFActionOutput();
            sa.setMaxLength(Short.MAX_VALUE);
            int port = OFPort.OFPP_ANY.getValue();
            if (n.group(1) != null) {
                try {
                    port = get_short(n.group(1));
                }
                catch (NumberFormatException e) {
                    log.debug("Invalid port in: '{}' (error ignored)", subaction);
                    return null;
                }
            }
            else if (n.group(2) != null)
                port = OFPort.OFPP_ALL.getValue();
            else if (n.group(3) != null)
                port = OFPort.OFPP_CONTROLLER.getValue();
            else if (n.group(4) != null)
                port = OFPort.OFPP_LOCAL.getValue();
            else if (n.group(5) != null)
                port = OFPort.OFPP_IN_PORT.getValue();
            else if (n.group(6) != null)
                port = OFPort.OFPP_NORMAL.getValue();
            else if (n.group(7) != null)
                port = OFPort.OFPP_FLOOD.getValue();
            sa.setPort(port);
            log.debug("action {}", sa);
        }
        else {
            log.error("Invalid subaction: '{}'", subaction);
            return null;
        }

        return sa;
    }

    private static OFAction decode_set_queue(String subaction, Logger log) {
        OFAction sa = null;
        Matcher n;

        n = Pattern.compile("set-queue=(?:((?:0x)?\\d+)\\:((?:0x)?\\d+))").matcher(subaction);
        if (n.matches()) {
            int queueid = 0;
            if (n.group(1) != null) {
                try {
                    queueid = get_int(n.group(1));
                }
                catch (NumberFormatException e) {
                    log.debug("Invalid queue-id in: '{}' (error ignored)", subaction);
                    return null;
               }
            }

            sa = new OFActionSetQueue().setQueueId(queueid);
            log.debug("action {}", sa);
        }
        else {
            log.debug("Invalid action: '{}'", subaction);
            return null;
        }

        return sa;
    }

    private static OFAction decode_strip_vlan(String subaction, Logger log) {
        OFAction sa = null;
        Matcher n = Pattern.compile("strip-vlan").matcher(subaction);

        if (n.matches()) {
            sa = new OFActionPopVLAN();
            log.debug("action {}", sa);
        }
        else {
            log.debug("Invalid action: '{}'", subaction);
            return null;
        }

        return sa;
    }

    private static OFAction decode_set_vlan_id(String subaction, Logger log) {
        OFAction sa = null;
        Matcher n = Pattern.compile("set-vlan-id=((?:0x)?\\d+)").matcher(subaction);

        if (n.matches()) {
            if (n.group(1) != null) {
                try {
                    short vlanid = get_short(n.group(1));
                    sa = new OFActionSetField(OFOXMFieldType.VLAN_VID, vlanid);
                    log.debug("action {}", sa);
                }
                catch (NumberFormatException e) {
                    log.debug("Invalid VLAN in: {} (error ignored)", subaction);
                    return null;
                }
            }
        }
        else {
            log.debug("Invalid action: '{}'", subaction);
            return null;
        }

        return sa;
    }

    private static OFAction decode_set_vlan_priority(String subaction, Logger log) {
        OFAction sa = null;
        Matcher n = Pattern.compile("set-vlan-priority=((?:0x)?\\d+)").matcher(subaction);

        if (n.matches()) {
            if (n.group(1) != null) {
                try {
                    byte prior = get_byte(n.group(1));
                    sa = new OFActionSetField(OFOXMFieldType.ETH_SRC, prior);
                    log.debug("  action {}", sa);
                }
                catch (NumberFormatException e) {
                    log.debug("Invalid VLAN priority in: {} (error ignored)", subaction);
                    return null;
                }
            }
        }
        else {
            log.debug("Invalid action: '{}'", subaction);
            return null;
        }

        return sa;
    }

    private static OFAction decode_set_src_mac(String subaction, Logger log) {
    	OFActionSetField sa = null;
        Matcher n = Pattern.compile("set-src-mac=(?:(\\p{XDigit}+)\\:(\\p{XDigit}+)\\:(\\p{XDigit}+)\\:(\\p{XDigit}+)\\:(\\p{XDigit}+)\\:(\\p{XDigit}+))").matcher(subaction);

        if (n.matches()) {
            byte[] macaddr = get_mac_addr(n, subaction, log);
            if (macaddr != null) {
                sa = new OFActionSetField(OFOXMFieldType.ETH_SRC, macaddr);
                log.debug("action {}", sa);
            }
        }
        else {
            log.debug("Invalid action: '{}'", subaction);
            return null;
        }

        return sa;
    }

    private static OFAction decode_set_dst_mac(String subaction, Logger log) {
        OFActionSetField sa = null;
        Matcher n = Pattern.compile("set-dst-mac=(?:(\\p{XDigit}+)\\:(\\p{XDigit}+)\\:(\\p{XDigit}+)\\:(\\p{XDigit}+)\\:(\\p{XDigit}+)\\:(\\p{XDigit}+))").matcher(subaction);

        if (n.matches()) {
            byte[] macaddr = get_mac_addr(n, subaction, log);
            if (macaddr != null) {
                sa = new OFActionSetField(OFOXMFieldType.ETH_DST, macaddr);
                log.debug("  action {}", sa);
            }
        }
        else {
            log.debug("Invalid action: '{}'", subaction);
            return null;
        }

        return sa;
    }

    private static OFAction decode_set_tos_bits(String subaction, Logger log) {
    	OFActionSetField sa = null;
        Matcher n = Pattern.compile("set-tos-bits=((?:0x)?\\d+)").matcher(subaction);

        if (n.matches()) {
            if (n.group(1) != null) {
                try {
                    byte tosbits = get_byte(n.group(1));
                    sa = new OFActionSetField(OFOXMFieldType.IP_DSCP, tosbits);
                    log.debug("action {}", sa);
                }
                catch (NumberFormatException e) {
                    log.debug("Invalid dst-port in: {} (error ignored)", subaction);
                    return null;
                }
            }
        }
        else {
            log.debug("Invalid action: '{}'", subaction);
            return null;
        }

        return sa;
    }

    private static OFAction decode_set_src_ip(String subaction, Logger log) {
    	OFActionSetField sa = null;
        Matcher n = Pattern.compile("set-src-ip=(?:(\\d+)\\.(\\d+)\\.(\\d+)\\.(\\d+))").matcher(subaction);

        if (n.matches()) {
            int ipaddr = get_ip_addr(n, subaction, log);
            sa = new OFActionSetField(OFOXMFieldType.IPV4_SRC, ipaddr);
            log.debug("action {}", sa);
        }
        else {
            log.debug("Invalid action: '{}'", subaction);
            return null;
        }

        return sa;
    }

    private static OFAction decode_set_dst_ip(String subaction, Logger log) {
        OFActionSetField sa = null;
        Matcher n = Pattern.compile("set-dst-ip=(?:(\\d+)\\.(\\d+)\\.(\\d+)\\.(\\d+))").matcher(subaction);

        if (n.matches()) {
            int ipaddr = get_ip_addr(n, subaction, log);
            sa = new OFActionSetField(OFOXMFieldType.IPV4_DST, ipaddr);
            log.debug("action {}", sa);
        }
        else {
            log.debug("Invalid action: '{}'", subaction);
            return null;
        }

        return sa;
    }

    private static OFAction decode_set_tcp_sport(String subaction, Logger log) {
        OFActionSetField sa = null;
        Matcher n = Pattern.compile("set-tcp-sport=((?:0x)?\\d+)").matcher(subaction);

        if (n.matches()) {
            if (n.group(1) != null) {
                try {
                    int portnum = get_short(n.group(1));
                    sa = new OFActionSetField(OFOXMFieldType.TCP_SRC, portnum);
                    log.debug("action {}", sa);
                }
                catch (NumberFormatException e) {
                    log.debug("Invalid tcp-sport in: {} (error ignored)", subaction);
                    return null;
                }
            }
        }
        else {
            log.debug("Invalid action: '{}'", subaction);
            return null;
        }

        return sa;
    }

    private static OFAction decode_set_tcp_dport(String subaction, Logger log) {
        OFActionSetField sa = null;
        Matcher n = Pattern.compile("set-tcp-dport=((?:0x)?\\d+)").matcher(subaction);

        if (n.matches()) {
            if (n.group(1) != null) {
                try {
                    int portnum = get_short(n.group(1));
                    sa = new OFActionSetField(OFOXMFieldType.TCP_DST, portnum);
                    log.debug("action {}", sa);
                }
                catch (NumberFormatException e) {
                    log.debug("Invalid tcp-sport in: {} (error ignored)", subaction);
                    return null;
                }
            }
        }
        else {
            log.debug("Invalid action: '{}'", subaction);
            return null;
        }

        return sa;
    }

    private static OFAction decode_set_udp_sport(String subaction, Logger log) {
        OFActionSetField sa = null;
        Matcher n = Pattern.compile("set-udp-sport=((?:0x)?\\d+)").matcher(subaction);

        if (n.matches()) {
            if (n.group(1) != null) {
                try {
                    int portnum = get_short(n.group(1));
                    sa = new OFActionSetField(OFOXMFieldType.UDP_SRC, portnum);
                    log.debug("action {}", sa);
                }
                catch (NumberFormatException e) {
                    log.debug("Invalid udp-sport in: {} (error ignored)", subaction);
                    return null;
                }
            }
        }
        else {
            log.debug("Invalid action: '{}'", subaction);
            return null;
        }

        return sa;
    }

    private static OFAction decode_set_udp_dport(String subaction, Logger log) {
        OFActionSetField sa = null;
        Matcher n = Pattern.compile("set-udp-dport=((?:0x)?\\d+)").matcher(subaction);

        if (n.matches()) {
            if (n.group(1) != null) {
                try {
                    int portnum = get_short(n.group(1));
                    sa = new OFActionSetField(OFOXMFieldType.UDP_DST, portnum);
                    log.debug("action {}", sa);
                }
                catch (NumberFormatException e) {
                    log.debug("Invalid tcp-sport in: {} (error ignored)", subaction);
                    return null;
                }
            }
        }
        else {
            log.debug("Invalid action: '{}'", subaction);
            return null;
        }

        return sa;
    }

    private static byte[] get_mac_addr(Matcher n, String subaction, Logger log) {
        byte[] macaddr = new byte[6];

        for (int i=0; i<6; i++) {
            if (n.group(i+1) != null) {
                try {
                    macaddr[i] = get_byte("0x" + n.group(i+1));
                }
                catch (NumberFormatException e) {
                    log.debug("Invalid src-mac in: '{}' (error ignored)", subaction);
                    return null;
                }
            }
            else {
                log.debug("Invalid src-mac in: '{}' (null, error ignored)", subaction);
                return null;
            }
        }

        return macaddr;
    }

    private static int get_ip_addr(Matcher n, String subaction, Logger log) {
        int ipaddr = 0;

        for (int i=0; i<4; i++) {
            if (n.group(i+1) != null) {
                try {
                    ipaddr = ipaddr<<8;
                    ipaddr = ipaddr | get_int(n.group(i+1));
                }
                catch (NumberFormatException e) {
                    log.debug("Invalid src-ip in: '{}' (error ignored)", subaction);
                    return 0;
                }
            }
            else {
                log.debug("Invalid src-ip in: '{}' (null, error ignored)", subaction);
                return 0;
            }
        }

        return ipaddr;
    }

    // Parse int as decimal, hex (start with 0x or #) or octal (starts with 0)
    private static int get_int(String str) {
        return Integer.decode(str);
    }

    // Parse short as decimal, hex (start with 0x or #) or octal (starts with 0)
    private static short get_short(String str) {
        return (short)(int)Integer.decode(str);
    }

    // Parse byte as decimal, hex (start with 0x or #) or octal (starts with 0)
    private static byte get_byte(String str) {
        return Integer.decode(str).byteValue();
    }

}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <item name="torchview_margin_right" type="dimen">16dp</item>
    <item name="torchview_margin_bottom" type="dimen">16dp</item>
    <item name="torchview_margin_left" type="dimen">16dp</item>
    <item name="torchview_padding_right" type="dimen">8dp</item>
    <item name="torchview_padding_bottom" type="dimen">4dp</item>
    <item name="torchview_padding_left" type="dimen">8dp</item>
    <item name="torchview_padding_top" type="dimen">4dp</item>

    <item name="torch_message_padding_horizontal" type="dimen">8dp</item>
    <item name="torch_message_padding_vertical" type="dimen">4dp</item>
</resources>

redpajama_set_name: RedPajamaGithub


text:
'use strict';

/* global jQuery, $ */

var Backbone = require('backbone');
Backbone.$ = jQuery;

var List = require('./views/combinations');
var Header = require('./views/header');
var Input = require('./views/input');

var data = require('./data');
var Combinations = require('./collections/combinations');
var combinations = new Combinations(data);

new List({
  el: $('.list'),
  collection: combinations
});
new Header({
  el: $('.header')
});
new Input({
  el: $('.search'),
  collection: combinations
});


text:
require "simple_blog/engine"

module SimpleBlog

  # Blog
  mattr_accessor :blog_name
  @@blog_name = 'Simple Blog'
  mattr_accessor :blog_description

  # Posts
  mattr_accessor :author_user_class
  mattr_accessor :author_user_class_display_field
  mattr_accessor :author_user_class_biography_field
  mattr_accessor :author_user_class_avatar_method
  mattr_accessor :author_scope
  @@author_scope = 'all'

  # Comments
  mattr_accessor :enable_comments
  @@enable_comments = true

  mattr_accessor :commenter_user_class
  mattr_accessor :commenter_user_class_display_field

  mattr_accessor :only_allow_users_to_comment
  @@only_allow_users_to_comment = true

  mattr_accessor :current_user_method

  mattr_accessor :refreshed_time

end


text:
import numpy as np
import pytest

from contourpy import ContourGenerator, FillType, LineType, ZInterp, contour_generator, max_threads

from . import util_test

@pytest.fixture
def xyz_3x3_as_lists():
    x = [[0, 1, 2], [0, 1, 2], [0, 1, 2]]
    y = [[0, 0, 0], [1, 1, 1], [2, 2, 2]]
    z = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
    return x, y, z

@pytest.fixture
def xyz_2x3_as_lists():  # shape (2, 3)
    x = [[0, 1, 2], [0, 1, 2]]
    y = [[0, 0, 0], [1, 1, 1]]
    z = [[0, 1, 2], [3, 4, 5]]
    return x, y, z

@pytest.fixture
def xyz_7x5_as_arrays():  # shape (7, 5)
    x, y = np.meshgrid([0, 1, 2, 3, 4], [0, 1, 2, 3, 4, 5, 6])
    z = x + y
    return x, y, z

@pytest.mark.parametrize("name", util_test.all_names())
@pytest.mark.parametrize("z", ([1], [[[1]]]))
def test_ndim_z(xyz_3x3_as_lists, name, z):
    x, y, _ = xyz_3x3_as_lists
    with pytest.raises(TypeError):
        contour_generator(x, y, z, name=name)

@pytest.mark.parametrize("name", util_test.all_names())
@pytest.mark.parametrize("all_xyz", ([[1]], [[1], [2]], [[1, 2]]))
def test_z_shape_too_small(all_xyz, name):
    with pytest.raises(TypeError):
        contour_generator(all_xyz, all_xyz, all_xyz, name=name)

@pytest.mark.parametrize("name", util_test.all_names())
@pytest.mark.parametrize("wrong_ndim", (None, [1], [[[1]]]))
def test_diff_ndim_xy(xyz_3x3_as_lists, name, wrong_ndim):
    x, y, z = xyz_3x3_as_lists
    with pytest.raises(TypeError):
        contour_generator(wrong_ndim, y, z, name=name)
    with pytest.raises(TypeError):
        contour_generator(x, wrong_ndim, z, name=name)

@pytest.mark.parametrize("name", util_test.all_names())
def test_xy_None(xyz_3x3_as_lists, name):
    _, _, z = xyz_3x3_as_lists
    contour_generator(None, None, z, name=name)

@pytest.mark.parametrize("name", util_test.all_names())
def test_xy_not_specified(xyz_3x3_as_lists, name):
    _, _, z = xyz_3x3_as_lists
    contour_generator(z=z, name=name)

@pytest.mark.parametrize("name", util_test.all_names())
def test_xy_1d(name):
    z = [[0, 1, 2], [3, 4, 5]]
    contour_generator([0, 1, 2], [0, 1], z, name=name)
    with pytest.raises(TypeError):
        contour_generator([0, 1], [0, 1], z, name=name)
    with pytest.raises(TypeError):
        contour_generator([0, 1, 2, 3], [0, 1], z, name=name)
    with pytest.raises(TypeError):
        contour_generator([0, 1, 2], [0], z, name=name)
    with pytest.raises(TypeError):
        contour_generator([0, 1, 2], [0, 1, 2], z, name=name)

@pytest.mark.parametrize("name", util_test.all_names())
def test_xy_ndim_more_than_2(name):
    z = [[0, 1, 2], [3, 4, 5]]
    msg = "Inputs x and y must be None, 1D or 2D, not 3D"
    with pytest.raises(TypeError, match=msg):
        contour_generator([[[1]]], [[[2]]], z, name=name)

@pytest.mark.parametrize("name", util_test.all_names())
@pytest.mark.parametrize("diff_shape", ([[1, 2, 3, 4], [5, 6, 7, 8]], [[1, 2], [3, 4], [5, 6]]))
def test_xyz_diff_shapes(xyz_3x3_as_lists, name, diff_shape):
    x, y, z = xyz_3x3_as_lists
    with pytest.raises(TypeError):
        contour_generator(diff_shape, y, z, name=name)
    with pytest.raises(TypeError):
        contour_generator(x, diff_shape, z, name=name)
    with pytest.raises(TypeError):
        contour_generator(x, y, diff_shape, name=name)

@pytest.mark.parametrize("name", util_test.corner_mask_names())
def test_corner_mask(xyz_3x3_as_lists, name):
    x, y, z = xyz_3x3_as_lists
    for corner_mask in [False, True]:
        cont_gen = contour_generator(x, y, z, name=name, corner_mask=corner_mask)
        assert cont_gen.corner_mask == corner_mask

def test_corner_mask_not_supported(xyz_3x3_as_lists):
    name = "mpl2005"
    x, y, z = xyz_3x3_as_lists
    msg = f"{name} contour generator does not support corner_mask=True"
    with pytest.raises(ValueError, match=msg):
        contour_generator(x, y, z, name=name, corner_mask=True)

@pytest.mark.parametrize('name', util_test.all_names())
def test_chunk_size_negative(xyz_3x3_as_lists, name):
    x, y, z = xyz_3x3_as_lists
    msg = "chunk_size cannot be negative"
    with pytest.raises(ValueError, match=msg):
        contour_generator(x, y, z, name=name, chunk_size=-1)
    with pytest.raises(ValueError, match=msg):
        contour_generator(x, y, z, name=name, chunk_size=(-1, 0))
    with pytest.raises(ValueError, match=msg):
        contour_generator(x, y, z, name=name, chunk_size=(0, -1))

@pytest.mark.parametrize("name", util_test.all_names())
@pytest.mark.parametrize("chunk_size", np.arange(9))
def test_chunk_size_1d(xyz_7x5_as_arrays, name, chunk_size):
    x, y, z = xyz_7x5_as_arrays
    ny, nx = z.shape
    cont_gen = contour_generator(x, y, z, name=name, chunk_size=chunk_size)
    ret_y_chunk_size, ret_x_chunk_size = cont_gen.chunk_size
    ret_y_chunk_count, ret_x_chunk_count = cont_gen.chunk_count
    if chunk_size == 0:
        assert ret_x_chunk_size == nx-1
        assert ret_y_chunk_size == ny-1
    else:
        assert ret_x_chunk_size == min(chunk_size, nx-1)
        assert ret_y_chunk_size == min(chunk_size, ny-1)
    assert ret_y_chunk_count*ret_y_chunk_size >= ny-1
    assert (ret_y_chunk_count-1)*ret_y_chunk_size < ny-1
    assert ret_x_chunk_count*ret_x_chunk_size >= nx-1
    assert (ret_x_chunk_count-1)*ret_x_chunk_size < nx-1

@pytest.mark.parametrize("name", util_test.all_names())
@pytest.mark.parametrize("x_chunk_size", np.arange(9))
@pytest.mark.parametrize("y_chunk_size", np.arange(9))
def test_chunk_size_2d(xyz_7x5_as_arrays, name, x_chunk_size, y_chunk_size):
    x, y, z = xyz_7x5_as_arrays
    ny, nx = z.shape
    cont_gen = contour_generator(x, y, z, name=name, chunk_size=(y_chunk_size, x_chunk_size))
    ret_y_chunk_size, ret_x_chunk_size = cont_gen.chunk_size
    ret_y_chunk_count, ret_x_chunk_count = cont_gen.chunk_count
    if x_chunk_size == 0:
        assert ret_x_chunk_size == nx-1
    else:
        assert ret_x_chunk_size == min(x_chunk_size, nx-1)
    if y_chunk_size == 0:
        assert ret_y_chunk_size == ny-1
    else:
        assert ret_y_chunk_size == min(y_chunk_size, ny-1)
    assert ret_y_chunk_count*ret_y_chunk_size >= ny-1
    assert (ret_y_chunk_count-1)*ret_y_chunk_size < ny-1
    assert ret_x_chunk_count*ret_x_chunk_size >= nx-1
    assert (ret_x_chunk_count-1)*ret_x_chunk_size < nx-1

def test_chunk_size_and_count(xyz_7x5_as_arrays):
    x, y, z = xyz_7x5_as_arrays
    name = "serial"
    msg = "Only one of chunk_size, chunk_count and total_chunk_count should be set"
    with pytest.raises(ValueError, match=msg):
        contour_generator(x, y, z, name=name, chunk_size=1, chunk_count=1)
    with pytest.raises(ValueError, match=msg):
        contour_generator(x, y, z, name=name, chunk_size=1, total_chunk_count=1)
    with pytest.raises(ValueError, match=msg):
        contour_generator(x, y, z, name=name, chunk_count=1, total_chunk_count=1)

@pytest.mark.parametrize("name", util_test.all_names())
@pytest.mark.parametrize(
    "chunk_count, ret_chunk_count",
    [[0, (1, 1)], [1, (1, 1)], [2, (2, 2)], [3, (3, 2)], [4, (3, 4)], [9, (6, 4)]],
)
def test_chunk_count_1d(xyz_7x5_as_arrays, name, chunk_count, ret_chunk_count):
    x, y, z = xyz_7x5_as_arrays
    ny, nx = z.shape
    cont_gen = contour_generator(x, y, z, name=name, chunk_count=chunk_count)
    ret_y_chunk_size, ret_x_chunk_size = cont_gen.chunk_size
    assert cont_gen.chunk_count == ret_chunk_count
    ret_y_chunk_count, ret_x_chunk_count = ret_chunk_count
    assert ret_y_chunk_count*ret_y_chunk_size >= ny-1
    assert (ret_y_chunk_count-1)*ret_y_chunk_size < ny-1
    assert ret_x_chunk_count*ret_x_chunk_size >= nx-1
    assert (ret_x_chunk_count-1)*ret_x_chunk_size < nx-1

@pytest.mark.parametrize("name", util_test.all_names())
@pytest.mark.parametrize(
    "chunk_count, ret_chunk_count",
    [[(0, 1), (1, 1)], [(1, 0), (1, 1)], [(2, 3), (2, 2)], [(3, 2), (3, 2)], [(1, 9), (1, 4)],
     [(9, 1), (6, 1)]],
)
def test_chunk_count_2d(xyz_7x5_as_arrays, name, chunk_count, ret_chunk_count):
    x, y, z = xyz_7x5_as_arrays
    ny, nx = z.shape
    cont_gen = contour_generator(x, y, z, name=name, chunk_count=chunk_count)
    ret_y_chunk_size, ret_x_chunk_size = cont_gen.chunk_size
    assert cont_gen.chunk_count == ret_chunk_count
    ret_y_chunk_count, ret_x_chunk_count = ret_chunk_count
    assert ret_y_chunk_count*ret_y_chunk_size >= ny-1
    assert (ret_y_chunk_count-1)*ret_y_chunk_size < ny-1
    assert ret_x_chunk_count*ret_x_chunk_size >= nx-1
    assert (ret_x_chunk_count-1)*ret_x_chunk_size < nx-1

@pytest.mark.parametrize("name", util_test.all_names())
@pytest.mark.parametrize(
    "total_chunk_count, ret_chunk_count",
    [[0, (1, 1)], [1, (1, 1)], [2, (2, 1)], [3, (3, 1)], [4, (2, 2)], [6, (3, 2)], [9, (3, 2)],
     [25, (6, 4)]],
)
def test_total_chunk_count(xyz_7x5_as_arrays, name, total_chunk_count, ret_chunk_count):
    x, y, z = xyz_7x5_as_arrays
    ny, nx = z.shape
    cont_gen = contour_generator(x, y, z, name=name, total_chunk_count=total_chunk_count)
    ret_y_chunk_size, ret_x_chunk_size = cont_gen.chunk_size
    assert cont_gen.chunk_count == ret_chunk_count
    ret_y_chunk_count, ret_x_chunk_count = ret_chunk_count
    assert ret_y_chunk_count*ret_y_chunk_size >= ny-1
    assert (ret_y_chunk_count-1)*ret_y_chunk_size < ny-1
    assert ret_x_chunk_count*ret_x_chunk_size >= nx-1
    assert (ret_x_chunk_count-1)*ret_x_chunk_size < nx-1

def test_name_invalid(xyz_3x3_as_lists):
    x, y, z = xyz_3x3_as_lists
    name = "some invalid name"
    msg = f"Unrecognised contour generator name: {name}"
    with pytest.raises(ValueError, match=msg):
        _ = contour_generator(x, y, z, name=name)

@pytest.mark.parametrize("name", ["mpl2005", "mpl2014"])
@pytest.mark.parametrize(
    "line_type", [LineType.Separate, LineType.ChunkCombinedCode, LineType.ChunkCombinedOffset])
def test_line_type_not_supported(xyz_3x3_as_lists, name, line_type):
    x, y, z = xyz_3x3_as_lists
    msg = f"{name} contour generator does not support line_type {line_type}"
    with pytest.raises(ValueError, match=msg):
        contour_generator(x, y, z, name=name, line_type=line_type)

@pytest.mark.parametrize("name", ["mpl2005", "mpl2014"])
@pytest.mark.parametrize("fill_type", [
    FillType.OuterOffset, FillType.ChunkCombinedCode, FillType.ChunkCombinedOffset,
    FillType.ChunkCombinedCodeOffset, FillType.ChunkCombinedOffsetOffset])
def test_fill_type_not_supported(xyz_3x3_as_lists, name, fill_type):
    x, y, z = xyz_3x3_as_lists
    msg = f"{name} contour generator does not support fill_type {fill_type}"
    with pytest.raises(ValueError, match=msg):
        contour_generator(x, y, z, name=name, fill_type=fill_type)

@pytest.mark.parametrize("name", util_test.all_names())
def test_properties(xyz_3x3_as_lists, name):
    # Test that each ContourGenerator class implements all the required properties.
    x, y, z = xyz_3x3_as_lists
    cont_gen = contour_generator(x, y, z, name=name)
    _, _ = cont_gen.chunk_count
    _, _ = cont_gen.chunk_size
    _ = cont_gen.corner_mask
    _ = cont_gen.fill_type
    _ = cont_gen.line_type
    _ = cont_gen.quad_as_tri
    _ = cont_gen.thread_count
    _ = cont_gen.z_interp

@pytest.mark.parametrize("name", util_test.quad_as_tri_names())
def test_quad_as_tri(xyz_3x3_as_lists, name):
    x, y, z = xyz_3x3_as_lists
    for quad_as_tri in [False, True]:
        cont_gen = contour_generator(x, y, z, name=name, quad_as_tri=quad_as_tri)
        assert cont_gen.quad_as_tri == quad_as_tri

def test_quad_as_tri_not_supported(xyz_3x3_as_lists):
    x, y, z = xyz_3x3_as_lists
    name = "mpl2005"
    msg = f"{name} contour generator does not support quad_as_tri=True"
    with pytest.raises(ValueError, match=msg):
        contour_generator(x, y, z, name=name, quad_as_tri=True)

@pytest.mark.parametrize("chunk_size", [0, 1, 2])
@pytest.mark.parametrize("thread_count", [0, 1, 2])
def test_thread_count(xyz_7x5_as_arrays, chunk_size, thread_count):
    name = "threaded"
    x, y, z = xyz_7x5_as_arrays
    cont_gen = contour_generator(
        x, y, z, name=name, chunk_size=chunk_size, thread_count=thread_count)
    ret_thread_count = cont_gen.thread_count
    ret_chunk_count = np.prod(cont_gen.chunk_count)
    max_thread_count = max_threads()
    if chunk_size == 0:
        assert ret_chunk_count == 1
        assert ret_thread_count == 1
    elif thread_count == 0:
        assert ret_thread_count == min(max_thread_count, ret_chunk_count)
    else:
        assert ret_thread_count == min(max_thread_count, ret_chunk_count, ret_thread_count)

@pytest.mark.parametrize("name", util_test.all_names(exclude="threaded"))
def test_thread_count_not_supported(xyz_3x3_as_lists, name):
    x, y, z = xyz_3x3_as_lists
    thread_count = 2
    msg = f"{name} contour generator does not support thread_count {thread_count}"
    with pytest.raises(ValueError, match=msg):
        contour_generator(x, y, z, name=name, thread_count=thread_count)

def test_enums_as_strings(xyz_3x3_as_lists):
    x, y, z = xyz_3x3_as_lists
    cg = contour_generator(
        x, y, z, line_type="SeparateCode", fill_type="ChunkCombinedCodeOffset", z_interp="Log")
    assert cg.line_type == LineType.SeparateCode
    assert cg.fill_type == FillType.ChunkCombinedCodeOffset
    assert cg.z_interp == ZInterp.Log

@pytest.mark.parametrize("name", util_test.all_names())
def test_is_contour_generator(name, xyz_3x3_as_lists):
    x, y, z = xyz_3x3_as_lists
    cg = contour_generator(x, y, z, name=name)
    assert isinstance(cg, ContourGenerator)

@pytest.mark.parametrize("name", util_test.all_names())
def test_z_interp_none_to_linear(name, xyz_3x3_as_lists):
    x, y, z = xyz_3x3_as_lists
    cg = contour_generator(x, y, z, name=name, z_interp=None)
    assert cg.z_interp == ZInterp.Linear

@pytest.mark.parametrize("name", ["mpl2005", "mpl2014"])
def test_z_interp_not_supported(name, xyz_3x3_as_lists):
    x, y, z = xyz_3x3_as_lists
    msg = f"{name} contour generator does not support z_interp ZInterp.Log"
    with pytest.raises(ValueError, match=msg):
        contour_generator(x, y, z, name=name, z_interp=ZInterp.Log)


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

using Microsoft.IdentityModel.Clients.ActiveDirectory;
using Microsoft.Rest.Azure.Authentication;
using System.Security;
using System.Threading.Tasks;

namespace Microsoft.Azure.Commands.Common.Authentication
{
    /// <summary>
    /// Interface to the keystore for authentication
    /// </summary>
    internal sealed class KeyStoreApplicationCredentialProvider : IApplicationAuthenticationProvider
    {
        private string _tenantId;

        /// <summary>
        /// Create a credential provider
        /// </summary>
        /// <param name="tenant"></param>
        public KeyStoreApplicationCredentialProvider(string tenant)
        {
            this._tenantId = tenant;
        }

        /// <summary>
        /// Authenticate using the secret for the specified client from the key store
        /// </summary>
        /// <param name="clientId">The active directory client id for the application.</param>
        /// <param name="audience">The intended audience for authentication</param>
        /// <param name="context">The AD AuthenticationContext to use</param>
        /// <returns></returns>
        public async Task<AuthenticationResult> AuthenticateAsync(string clientId, string audience, AuthenticationContext context)
        {
            var task = new Task<SecureString>(() =>
            {
                return ServicePrincipalKeyStore.GetKey(clientId, _tenantId);
            });
            task.Start();
            var key = await task.ConfigureAwait(false);

            return await context.AcquireTokenAsync(audience, new ClientCredential(clientId, key));
        }
    }
}


text:
import tensorflow as tf
import numpy as np

from elbow import ConditionalDistribution

from elbow.parameterization import unconstrained, unconstrained_zeros, positive_exp, simplex_constrained, unit_interval, unconstrained_small, unconstrained_scale
from elbow.transforms import Logit, Simplex, Exp, TransformedDistribution, Normalize

from elbow.util.dists import multivariate_gaussian_log_density, multivariate_gaussian_entropy, gaussian_entropy, gaussian_log_density, bernoulli_entropy, bernoulli_log_density
from elbow.util.misc import concrete_shape

class NoisyRandomProjection(ConditionalDistribution):
    """
    Projects an input matrix Z through a random linear projection W,
    sampled from W ~ N(0, 1), marginalizing out the projection.
    This is 'dual PCA' (ordinarily in PCA we marginalize out the inputs Z
    and solve for W).
    """

    def __init__(self, Z, mu=None, std=None,  **kwargs):
        super(NoisyRandomProjection, self).__init__(Z=Z, mu=mu, std=std, **kwargs)

    def inputs(self):
        return {"Z": unconstrained, "mu": unconstrained, "std": positive_exp}

    def _compute_shape(self, Z_shape, mu_shape, std_shape):
        raise Exception("RandomProjection requires an explicitly specified shape")

    def _sample(self, Z, mu, std):
        n, d_output = self.shape
        d_latent = concrete_shape(Z.get_shape())[1]
        W = tf.random_normal(shape=(d_output, d_latent), dtype=self.dtype)
        eps = tf.random_normal(shape=self.shape, dtype=self.dtype)
        return tf.matmul(Z, tf.transpose(W)) + mu + eps*std

    def _logp(self, result, Z, mu, std):
        n, d_output = self.shape

        cov = tf.matmul(Z, tf.transpose(Z)) + tf.diag(tf.ones(n,)*std)
        L = tf.cholesky(cov)
        r = result - mu
        out_cols = tf.unpack(r, axis=1)
        lps = [multivariate_gaussian_log_density(col, mu=0., L=L) for col in out_cols]
        return tf.reduce_sum(tf.pack(lps))

    def _entropy(self, Z, mu, std):
        n, d_output = self.shape
        cov = tf.matmul(Z, tf.transpose(Z)) + tf.diag(tf.ones(n,)*std)
        L = tf.cholesky(cov)
        return d_output * multivariate_gaussian_entropy(L=L)

class InverseProjection(ConditionalDistribution):
    """
    Define an 'inference network' performing exact posterior inference
    in PCA. Given high-dimensional observations X and a projection matrix W,
    computes the (analytic) multivariate Gaussian posterior on the
    latent variables X, assuming a standard Gaussian prior.

    Note that when constructing this RV as a variational model, the inputs
    should be the *variational models* of X and W (q_X and q_W) rather than
    X and W themselves.
    """

    def __init__(self, X, W, mu=None, std=None, **kwargs):
        super(InverseProjection, self).__init__(X=X, W=W, mu=mu, std=std, **kwargs)

    def inputs(self):
        return {"X": None, "W": None, "mu": unconstrained, "std": positive_exp}

    def _build_inverse_projection(self, X, W, mu, std):
        n, d_latent = self.shape
        variance = tf.square(std)

        M = tf.matmul(tf.transpose(W), W) + tf.diag(tf.ones((d_latent))*variance)
        L = tf.cholesky(M)

        # pred_Z = M^-1 W' r' as per (6) in tipping & bishop JRSS
        # https://www.microsoft.com/en-us/research/wp-content/uploads/2016/02/bishop-ppca-jrss.pdf
        r = X-mu
        WTr = tf.transpose(tf.matmul(r, W)) # W' (t - mu)
        tmp = tf.matrix_triangular_solve(L, WTr, lower=True)
        pred_z = tf.transpose(tf.matrix_triangular_solve(tf.transpose(L), tmp, lower=False))

        return pred_z, L, std

    def _sample_and_entropy(self, **input_samples):
        # more efficient to re-use the same network for sampled value and entropy
        pred_z, L, std = self._build_inverse_projection(**input_samples)
        eps = tf.random_normal(shape=self.shape)
        unit_entropy = multivariate_gaussian_entropy(L_prec=L/std)

        self.canonical_pred = pred_z
        self.canonical_L = L

        n, d_latent = self.shape
        sample = pred_z + tf.transpose(tf.matrix_triangular_solve(tf.transpose(L/std), tf.transpose(eps), lower=False))
        entropy = n*unit_entropy
        return sample, entropy

    def _sample(self, X, W, mu, std):
        pred_z, L, std = self._build_inverse_projection(X, W, mu, std)
        eps = tf.random_normal(shape=self.shape)

        # sample from N(pred_z, M^-1 * std**2)
        # where LL' = M
        return pred_z + tf.transpose(tf.matrix_triangular_solve(tf.transpose(L/std), tf.transpose(eps), lower=False))

    def _entropy(self, X, W, mu, std):
        n, d_latent = self.shape
        pred_z, L, std = self._build_inverse_projection(X, W, mu, std)
        unit_entropy = multivariate_gaussian_entropy(L_prec=L/std)
        return n*unit_entropy

    def _logp(self, result, X, W, mu, std):
        pred_z, L, std = self._build_inverse_projection(X, W, mu, std)

        rows = tf.unpack(result - pred_z)
        lps = [multivariate_gaussian_log_density(r, mu=0, L_prec=L/std) for r in rows]
        return tf.reduce_sum(tf.pack(lps))

class MeanFieldLinearGaussian(ConditionalDistribution):

    def __init__(self, X, W=None, mu=None, std=None, **kwargs):
        self.X_shape = concrete_shape(Z.get_shape())[1] if isinstance(X, tf.Tensor) else X.shape
        super(MeanFieldLinearGaussian, self).__init__(X=X, W=W, mu=mu, std=std, **kwargs)

    def inputs(self):
        return {"X": None, "W": unconstrained, "mu": unconstrained_zeros, "std": positive_exp}

    def _compute_shape(self, X_shape, W_shape, mu_shape, std_shape):
        n, d = X_shape
        m, d = W_shape
        return (n, m)

    def _input_shape(self, param, **kwargs):
        assert(self.shape is not None)
        n, m = self.shape
        n2, d = self.X_shape
        assert(n==n2)
        if param=="W":
            return (m, d)
        elif param=="mu":
            return (m,)
        elif param=="std":
            return (m,)
        else:
            raise Exception("unknown param %s" % param)

    def _sample(self, X, W, mu, std):

        # X: n x d
        # W: m x d
        # Z: n x m
        proj = tf.matmul(X, tf.transpose(W)) + mu
        eps = tf.random_normal(shape=self.shape)
        sampled = proj + eps*std
        return sampled

    def _entropy(self, X, W, mu, std):
        n, m = self.shape
        return n*gaussian_entropy(stddev=std)

    def _logp(self, result, X, W, mu, std):
        proj = tf.matmul(X, tf.transpose(W)) + mu
        return gaussian_log_density(result, mu=proj, stddev=std)

    def derived_parameters(self, X, W, mu, std, **kwargs):
        proj = tf.matmul(X, tf.transpose(W)) + mu
        return {"mean": proj}

class MeanFieldBernoulli(ConditionalDistribution):

    def __init__(self, X, W=None, b=None, **kwargs):
        self.X_shape = concrete_shape(Z.get_shape())[1] if isinstance(X, tf.Tensor) else X.shape
        self.scale = 10.0
        super(MeanFieldBernoulli, self).__init__(X=X, W=W, b=b, **kwargs)

    def inputs(self):
        return {"X": None, "W": unconstrained, "b": unconstrained_small}

    def _compute_shape(self, X_shape, W_shape, mu_shape, std_shape):
        n, d = X_shape
        m, d = W_shape
        return (n, m)

    def _input_shape(self, param, **kwargs):
        assert(self.shape is not None)
        n, m = self.shape
        n2, d = self.X_shape
        assert(n==n2)
        if param=="W":
            return (m, d)
        elif param=="b":
            return (m,)
        else:
            raise Exception("unknown param %s" % param)

    def _sample(self, X, W, b):

        # X: n x d
        # W: m x d
        # Z: n x m
        proj = tf.matmul(X, tf.transpose(W)) + b
        probs = Logit.transform(proj / self.scale)

        unif = tf.random_uniform(shape=self.shape, dtype=tf.float32)
        return tf.cast(unif < probs, self.dtype)

    def _entropy(self, X, W, b):
        n, m = self.shape
        proj = tf.matmul(X, tf.transpose(W)) + b
        probs = Logit.transform(proj / self.scale)
        return tf.reduce_sum(bernoulli_entropy(probs))

    def _logp(self, result, X, W, b):
        proj = tf.matmul(X, tf.transpose(W)) + b
        probs = Logit.transform(proj / self.scale)
        lps = bernoulli_log_density(result, probs)
        return tf.reduce_sum(lps)

    def derived_parameters(self, X, W, b, **kwargs):
        proj = tf.matmul(X, tf.transpose(W)) + b
        probs = Logit.transform(proj / self.scale)
        return {"p": probs}


text:
package me.stevenkin.boomvc.http;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public interface Const {

    String DEFAULT_SERVER_PORT = "8000";
    String DEFAULT_SERVER_ADDRESS = "0.0.0.0";
    String LOCAL_IP_ADDRESS = "127.0.0.1";
    String CONTENT_TYPE_HTML = "text/html; charset=UTF-8";
    String CONTENT_TYPE_JSON = "application/json; charset=UTF-8";
    String CONTENT_TYPE_TEXT = "text/plain; charset=UTF-8";
    String HTTP_DATE_FORMAT = "EEE, dd MMM yyyy HH:mm:ss zzz";
    String INTERNAL_SERVER_ERROR_HTML = "<!DOCTYPE html>\n" +
            "\n" +
            "\n" +
            "    <meta charset=\"UTF-8\">\n" +
            "    <title>error</title>\n" +
            "\n" +
            "\n" +
            "
500 Internal Server Error

\n" +
            "\n" +
            "";
    String NOT_FOUND_ERROR_HTML = "<!DOCTYPE html>\n" +
            "\n" +
            "\n" +
            "    <meta charset=\"UTF-8\">\n" +
            "    <title>error</title>\n" +
            "\n" +
            "\n" +
            "
404 Not Found

\n" +
            "\n" +
            "";
    String DEFAULT_THREAD_NAME = "boom_thread_2333_";
    String DEFAULT_BANNER_PATH = "/banner.txt";
    List<String> DEFAULT_STATICS = new ArrayList<>(
            Arrays.asList("/favicon.ico", "/robots.txt", "/static", "/upload"));

    String PROP_NAME0 = "classpath:app.properties";
    String PROP_NAME = "classpath:application.properties";
    String DEFAULT_SCAN_PACKAGE = "me.stevenkin.boomvc";

    String REDIRECT_PREFIX = "redirect:";

    // Env key
    String ENV_KEY_APP_NAME = "app.name";
    String ENV_KEY_APP_THREAD_NAME = "app.thread-name";
    String ENV_KEY_BANNER_PATH = "app.banner-path";
    String ENV_KEY_CONTEXT_PATH = "app.context-path";
    String ENV_KEY_GZIP_ENABLE = "http.gzip.enable";
    String ENV_KEY_CORS_ENABLE = "http.cors.enable";
    String ENV_KEY_SESSION_KEY = "http.session.key";
    String ENV_KEY_SESSION_TIMEOUT = "http.session.timeout";
    String ENV_KEY_HTTP_CACHE_TIMEOUT = "http.cache.timeout";
    String ENV_KEY_HTTP_REQUEST_COST = "http.request.cost";
    String ENV_KEY_PAGE_404 = "mvc.view.404";
    String ENV_KEY_PAGE_500 = "mvc.view.500";
    String ENV_KEY_STATIC_DIRS = "mvc.statics";
    String ENV_KEY_STATIC_LIST = "mvc.statics.show-list";
    String ENV_KEY_IOC_PACKAGES = "mvc.ioc.packages";
    String ENV_KEY_TEMPLATE_PATH = "mvc.template.path";
    String ENV_KEY_SERVER_ADDRESS = "server.address";
    String ENV_KEY_SERVER_PORT = "server.port";
    String ENV_KEY_SERVER_ACCEPT_THREAD_COUNT = "server.accept-thread.count";
    String ENV_KEY_SERVER_IO_THREAD_COUNT = "server.io-thread.count";

    int DEFAULT_SO_BACKLOG = 1024;
    int DEFAULT_ACCEPT_THREAD_COUNT = 1;
    int DEFAULT_IO_THREAD_COUNT = 1;
    //int DEFAULT_IO_THREAD_COUNT = Runtime.getRuntime().availableProcessors();

    String NEW_LINE = "\r\n";

    String BANNER_TEXT = NEW_LINE +
            " ____" + NEW_LINE +
            "| __ )  ___   ___  _ __ ___" + NEW_LINE +
            "|  _ \\ / _ \\ / _ \\| '_ ` _ \\" + NEW_LINE +
            "| |_) | (_) | (_) | | | | | |" + NEW_LINE +
            "|____/ \\___/ \\___/|_| |_| |_|";

}


text:
<?php

	class StatusEmployee
	{
		public $id_status;
		public $name_status;
		public $description_status;
	}
?>


text:
#import "NSObject.h"

@interface XCRefactoringTransformationSpecificLogic : NSObject
{
}

+ (Class)classForTransformKey:(id)arg1;
- (BOOL)allowOnlyObjectiveCCompilationUnits:(id)arg1;
- (BOOL)getClass:(Class *)arg1 declaration:(id *)arg2 fromASTNode:(id)arg3 mainThreadArguments:(id)arg4 error:(id *)arg5;
- (id)localizedSnapshotTitle:(id)arg1;
- (id)localizedStringFrom:(id)arg1;
- (BOOL)mainThreadArgumentsAreAvailable:(id)arg1 error:(id *)arg2;
- (BOOL)modifyAllFiles:(id)arg1 mainThreadArguments:(id)arg2 error:(id *)arg3;
- (BOOL)modifyFileChangeSets:(id)arg1 parseThreadArguments:(id)arg2 error:(id *)arg3;
- (BOOL)modifyProblems:(id)arg1 parseThreadArguments:(id)arg2 error:(id *)arg3;
- (BOOL)parseUnsavedFiles:(id)arg1;
- (id)postInitialFileInfo:(id)arg1 newSelectionLineInfo:(struct _XCRefactoringLineInfo *)arg2 error:(id *)arg3;
- (id)preliminaryRelatedNames:(id)arg1;
- (id)setUpInfo:(id)arg1;
- (id)transformParamDict:(id)arg1;
- (BOOL)userInputIsAvailable:(id)arg1 error:(id *)arg2;

@end


text:
package monocle.std

@deprecated("instances have been move to typeclass companion object", since = "1.4.0")
object tuple4

@deprecated("instances have been move to typeclass companion object", since = "1.4.0")
trait Tuple4Optics


text:
package org.kodejava.example.lang;

public class UniqueArray {
    /**
     * Return true if number num is appeared only once in the
     * array num is unique.
     */
    public static boolean isUnique(int[] array, int num) {
        for (int i = 0; i < array.length; i++) {
            if (array[i] == num) {
                return false;
            }
        }
        return true;
    }

    /**
     * Convert the given array to an array with unique values
     * without duplicates and returns it.
     */
    public static int[] toUniqueArray(int[] array) {
        int[] temp = new int[array.length];
        for (int i = 0; i < temp.length; i++) {
            temp[i] = -1; // in case u have value of 0 in the array
        }

        int counter = 0;
        for (int i = 0; i < array.length; i++) {
            if (isUnique(temp, array[i]))
                temp[counter++] = array[i];
        }

        int[] uniqueArray = new int[counter];
        System.arraycopy(temp, 0, uniqueArray, 0, uniqueArray.length);
        return uniqueArray;
    }

    /**
     * Print given array
     */
    public static void printArray(int[] array) {
        for (int i = 0; i < array.length; i++) {
            System.out.print(array[i] + " ");
        }

        System.out.println("");
    }

    public static void main(String[] args) {
        int[] array = {1, 1, 2, 3, 4, 1, 4, 7, 9, 7};
        printArray(array);
        printArray(toUniqueArray(array));
    }
}


text:
package com.fasterxml.jackson.jr.stree;

import java.util.Arrays;

import com.fasterxml.jackson.core.*;
import com.fasterxml.jackson.jr.ob.JSON;

import junit.framework.TestCase;

public abstract class JacksonJrTreeTestBase extends TestCase
{
    protected final JsonFactory _factory = new JsonFactory();

    protected void assertToken(JsonToken expToken, JsonToken actToken)
    {
        if (actToken != expToken) {
            fail("Expected token "+expToken+", current token "+actToken);
        }
    }

    protected void assertToken(JsonToken expToken, JsonParser p)
    {
        assertToken(expToken, p.currentToken());
    }

    protected void verifyException(Throwable e, String... matches)
    {
        String msg = e.getMessage();
        String lmsg = (msg == null) ? "" : msg.toLowerCase();
        for (String match : matches) {
            String lmatch = match.toLowerCase();
            if (lmsg.indexOf(lmatch) >= 0) {
                return;
            }
        }
        fail("Expected an exception with one of substrings ("+Arrays.asList(matches)+"): got one with message \""+msg+"\"");
    }

    protected String q(String str) {
        return "\"" + str + "\"";
    }

    protected String a2q(String json) {
        return json.replace("'", "\"");
    }

    protected JSON jsonWithTreeCodec() {
        return JSON.builder()
                // 13-Feb-2020, tatu: There are 2 different ways actually..
//            .treeCodec(new JacksonJrsTreeCodec())
                .register(new JrSimpleTreeExtension())
            .build();
    }
}


text:
import express from 'express';
import { CosmosPluginConfig, PlatformType } from 'react-cosmos-plugin';
import { CosmosConfig } from 'react-cosmos-shared2/cosmosConfig';
import resolveFrom from 'resolve-from';
import { getDevPlaygroundHtml } from '../shared/playgroundHtml';
import { getStaticPath } from '../shared/static';

export function createApp(
  platformType: PlatformType,
  cosmosConfig: CosmosConfig,
  pluginConfigs: CosmosPluginConfig[]
): express.Express {
  const app = express();

  const playgroundHtml = getDevPlaygroundHtml(
    platformType,
    cosmosConfig,
    pluginConfigs
  );
  app.get('/', (req: express.Request, res: express.Response) => {
    res.send(playgroundHtml);
  });

  app.get(
    '/_plugin/:scriptPath',
    (req: express.Request, res: express.Response) => {
      const { scriptPath } = req.params;
      if (!scriptPath) {
        res.sendStatus(404);
        return;
      }

      // TODO: Restrict which scripts can be opened based on plugin configs
      const cleanPath = `./${decodeURIComponent(scriptPath)}`;
      const absolutePath = resolveFrom.silent(cosmosConfig.rootDir, cleanPath);
      if (!absolutePath) {
        res.sendStatus(404);
        return;
      }

      res.sendFile(absolutePath);
    }
  );

  app.get('/_playground.js', (req: express.Request, res: express.Response) => {
    res.sendFile(require.resolve('react-cosmos-playground2/dist'));
  });

  app.get('/_cosmos.ico', (req: express.Request, res: express.Response) => {
    res.sendFile(getStaticPath('favicon.ico'));
  });

  return app;
}


text:
package br.mp.mpt.prt8.severino.entity;

import static br.mp.mpt.prt8.severino.mediator.intervalodatas.ValidarIntervalo.MENSAGEM_DATA_FUTURA;
import static br.mp.mpt.prt8.severino.mediator.intervalodatas.ValidarIntervalo.VALIDACAO_DATA_ENTRADA;
import static br.mp.mpt.prt8.severino.mediator.intervalodatas.ValidarIntervalo.VALIDACAO_INTERVALO_ENTRADA_SAIDA;
import static br.mp.mpt.prt8.severino.mediator.intervalodatas.ValidarIntervalo.isDataEntradaValida;
import static br.mp.mpt.prt8.severino.mediator.intervalodatas.ValidarIntervalo.isIntervaloEntradaSaidaValido;
import static javax.persistence.FetchType.LAZY;

import java.time.LocalDate;
import java.util.Date;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.Transient;
import javax.validation.Valid;
import javax.validation.constraints.AssertFalse;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Past;
import javax.validation.constraints.Size;
import javax.validation.groups.ConvertGroup;
import javax.validation.groups.Default;

import org.springframework.data.jpa.datatables.mapping.DataTablesOutput;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.format.annotation.DateTimeFormat.ISO;

import com.fasterxml.jackson.annotation.JsonView;

import br.mp.mpt.prt8.severino.utils.Constantes;
import br.mp.mpt.prt8.severino.utils.DateUtils;
import br.mp.mpt.prt8.severino.validators.SelecionarVeiculo;
import br.mp.mpt.prt8.severino.validators.SelecionarVisita;

/**
 * The persistent class for the acesso_garagem database table.
 *
 */
@Entity
@Table(name = "acesso_garagem")
public class AcessoGaragem extends AbstractEntityIntervaloData<Integer> {
	private static final long serialVersionUID = -8836753558231868937L;

	@Id
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	@Column(name = "id_acesso_garagem", unique = true, nullable = false)
	@JsonView(DataTablesOutput.View.class)
	private Integer id;

	@Column(length = 400)
	@Size(max = 400)
	private String anotacao;

	@Column(name = "data_hora_cadastro", nullable = false, updatable = false)
	@Temporal(TemporalType.TIMESTAMP)
	@DateTimeFormat(iso = ISO.DATE_TIME)
	private Date dataHoraCadastro;

	@Temporal(TemporalType.TIMESTAMP)
	@Column(nullable = false)
	@DateTimeFormat(pattern = Constantes.DATE_TIME_FORMAT)
	@JsonView(DataTablesOutput.View.class)
	@Past(message = MENSAGEM_DATA_FUTURA)
	private Date entrada;

	@Temporal(TemporalType.TIMESTAMP)
	@Past(message = MENSAGEM_DATA_FUTURA)
	@DateTimeFormat(pattern = Constantes.DATE_TIME_FORMAT)
	@JsonView(DataTablesOutput.View.class)
	private Date saida;

	// uni-directional many-to-one association to Motorista
	@ManyToOne(fetch = FetchType.LAZY)
	@JoinColumn(name = "id_motorista")
	@JsonView(DataTablesOutput.View.class)
	private Motorista motorista;

	// uni-directional many-to-one association to Veiculo
	@ManyToOne(fetch = FetchType.LAZY)
	@JoinColumn(name = "placa", nullable = false)
	@Valid
	@NotNull
	@ConvertGroup(from = Default.class, to = SelecionarVeiculo.class)
	private Veiculo veiculo;

	// uni-directional many-to-one association to Usuario
	@ManyToOne(fetch = FetchType.LAZY)
	@JoinColumn(name = "id_usuario", nullable = false, updatable = false)
	private Usuario usuario;

	// uni-directional many-to-one association to Visita
	@ManyToOne(fetch = FetchType.LAZY)
	@JoinColumn(name = "id_visita")
	@NotNull(groups = SelecionarVisita.class)
	@Valid
	private Visita visita;

	@ManyToOne(fetch = LAZY)
	@JoinColumn(name = "id_local", nullable = false, updatable = false)
	private Local local;

	@Transient
	private boolean usuarioVisitante;

	@AssertFalse(message = VALIDACAO_DATA_ENTRADA)
	public boolean isValidacaoDataEntrada() {
		return isDataEntradaValida(this);
	}

	@AssertFalse(message = VALIDACAO_INTERVALO_ENTRADA_SAIDA)
	public boolean isValidacaoIntervaloEntradaSaida() {
		return isIntervaloEntradaSaidaValido(this);
	}

	@Transient
	public LocalDate getEntradaAsLocalDate() {
		return DateUtils.toLocalDate(getEntrada());
	}

	@Override
	public Integer getId() {
		return this.id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	public String getAnotacao() {
		return this.anotacao;
	}

	public void setAnotacao(String anotacao) {
		this.anotacao = anotacao;
	}

	public Date getDataHoraCadastro() {
		return this.dataHoraCadastro;
	}

	@Override
	public void setDataHoraCadastro(Date dataHoraCadastro) {
		this.dataHoraCadastro = dataHoraCadastro;
	}

	@Override
	public Date getEntrada() {
		return this.entrada;
	}

	@Override
	public void setEntrada(Date entrada) {
		this.entrada = entrada;
	}

	@Override
	public Date getSaida() {
		return this.saida;
	}

	@Override
	public void setSaida(Date saida) {
		this.saida = saida;
	}

	public Motorista getMotorista() {
		return this.motorista;
	}

	public void setMotorista(Motorista motorista) {
		this.motorista = motorista;
	}

	public Veiculo getVeiculo() {
		return this.veiculo;
	}

	public void setVeiculo(Veiculo veiculo) {
		this.veiculo = veiculo;
	}

	public Usuario getUsuario() {
		return this.usuario;
	}

	@Override
	public void setUsuario(Usuario usuario) {
		this.usuario = usuario;
	}

	public Visita getVisita() {
		return this.visita;
	}

	public void setVisita(Visita visita) {
		this.visita = visita;
	}

	/**
	 * @return the usuarioVisitante
	 */
	public boolean isUsuarioVisitante() {
		if (getMotorista() != null) {
			return usuarioVisitante = false;
		}
		if (getVisita() != null) {
			return usuarioVisitante = true;
		}
		return usuarioVisitante;
	}

	/**
	 * @param usuarioVisitante
	 *            the usuarioVisitante to set
	 */
	public void setUsuarioVisitante(boolean usuarioVisitante) {
		this.usuarioVisitante = usuarioVisitante;
	}

	public Local getLocal() {
		return local;
	}

	@Override
	public void setLocal(Local local) {
		this.local = local;
	}

}


text:
<?php
namespace Payum\Klarna\Invoice\Action;

use Payum\Core\Action\PaymentAwareAction;
use Payum\Core\Bridge\Spl\ArrayObject;
use Payum\Core\Exception\RequestNotSupportedException;
use Payum\Core\Request\Authorize;
use Payum\Core\Request\Capture;
use Payum\Klarna\Invoice\Request\Api\Activate;

class CaptureAction extends PaymentAwareAction
{
    /**
     * {@inheritDoc}
     *
     * @param Capture $request
     */
    public function execute($request)
    {
        RequestNotSupportedException::assertSupports($this, $request);

        $details = ArrayObject::ensureArrayObject($request->getModel());

        if (false == $details['rno']) {
            $this->payment->execute(new Authorize($details));
        }

        if ($details['rno'] && false == $details['invoice_number']) {
            $this->payment->execute(new Activate($details));
        }
    }

    /**
     * {@inheritDoc}
     */
    public function supports($request)
    {
        return
            $request instanceof Capture &&
            $request->getModel() instanceof \ArrayAccess
        ;
    }
}


text:
PROCEED="yes"
REINSTALL=0
grep enchant-1.6.0 /list-$CHRISTENED"-"$SURNAME > /dev/null && ((\!$?)) &&\
    REINSTALL=1 && echo "Previous installation detected, proceed?" && read PROCEED
[ $PROCEED = "yes" ] || [ $PROCEED = "y" ] || exit 0
# Download:
wget http://www.abisource.com/downloads/enchant/1.6.0/enchant-1.6.0.tar.gz
# FTP/alt Download:
#wget ftp://ftp.netbsd.org/pub/pkgsrc/distfiles/enchant-1.6.0.tar.gz
#
# md5sum:
echo "de11011aff801dc61042828041fb59c7 enchant-1.6.0.tar.gz" | md5sum -c ;\
    ( exit ${PIPESTATUS[0]} )
#
tar -xvf enchant-1.6.0.tar.gz
cd enchant-1.6.0
./configure --prefix=/usr --disable-static
make
#
as_root make install
#
# link in aspell
as_root ln -svfn ../../lib/aspell /usr/share/enchant/aspell
#
# test it!
cat > /tmp/test-enchant.txt << "EOF"
Tel me more abot linux
Ther ar so many commads
EOF
enchant -d en_US -l /tmp/test-enchant.txt
enchant -d en_US -a /tmp/test-enchant.txt
rm /tmp/test-enchant.txt
# You will see a list of the misspelled words followed by a list
#+of alternatives for them
#
cd ..
as_root rm -rf enchant-1.6.0
#
# Add to installed list for this computer:
echo "enchant-1.6.0" >> /list-$CHRISTENED"-"$SURNAME
#
###################################################


text:
require 'racc'
require 'racc/parser'
require 'racc/grammarfileparser'
require 'racc/parserfilegenerator'
require 'racc/logfilegenerator'


text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>forms_validation</title>

    <form id="test_form" action="cgi-bin/registration.pl">

            Име
            <input type="text" id="name"

                title="Името може да съдържа само букви, '.', '_' и '-'"
                name="ime"
                >

            Възраст
            <input type="number" id="age" min="16" max="100" step="1" />

            Мобилен
            <input type="tel" id="tel" pattern="\+359 [\d ]{2,8}" />

            E-mail
            <input type="email" id="email" name="email">

            E-mail отново
            <input type="email" id="email2" name="email2" onblur="verify_email(this)" >

            Парола
            <input type="password" id="password" name="password">

            Повторете паролата
            <input type="password" id="password2" name="password2">

            Снимка
( < 50KB )
            <input type="file" id="avatar" maxlength="12">

            Любим цвят
            <input type="color" id="color" maxlength="12" >
            <input type="range" size="2" name="satisfaction" min="1" max="5" value="3">

            <button type="submit" value="Submit">Въведи</button>
            <button type="reset" value="Reset">Изчисти</button>

    </form>