text:
<?php

namespace Box\Tests\Mod\Staff\Api;

class GuestTest extends \BBTestCase
{
    /**
     * @var \Box\Mod\Staff\Api\Guest
     */
    protected $api = null;

    public function setup()
    {
        $this->api= new \Box\Mod\Staff\Api\Guest();
    }

    public function testgetDi()
    {
        $di = new \Box_Di();
        $this->api->setDi($di);
        $getDi = $this->api->getDi();
        $this->assertEquals($di, $getDi);
    }

    public function testCreate()
    {
        $adminId = 1;

        $apiMock = $this->getMockBuilder('\Box\Mod\Staff\Api\Guest')
            ->setMethods(array('login'))
            ->getMock();
        $apiMock->expects($this->atLeastOnce())
            ->method('login');

        $serviceMock = $this->getMockBuilder('\Box\Mod\Staff\Service')->getMock();
        $serviceMock->expects($this->atLeastOnce())
            ->method('createAdmin')
            ->will($this->returnValue($adminId));

        $validatorMock = $this->getMockBuilder('\Box_Validate')->getMock();
        $validatorMock->expects($this->atLeastOnce())
            ->method('checkRequiredParamsForArray');

        $dbMock = $this->getMockBuilder('\Box_Database')->getMock();
        $dbMock->expects($this->atLeastOnce())
            ->method('findOne')
            ->will($this->returnValue(array()));

        $di = new \Box_Di();
        $di['db'] = $dbMock;
        $di['validator'] = $validatorMock;

        $apiMock->setDi($di);
        $apiMock->setService($serviceMock);

        $data = array(
            'email' => 'example@boxbilling.com',
            'password' => 'EasyToGuess',
        );
        $result = $apiMock->create($data);
        $this->assertTrue($result);
    }

    public function testCreate_Exception()
    {
        $dbMock = $this->getMockBuilder('\Box_Database')->getMock();
        $dbMock->expects($this->atLeastOnce())
            ->method('findOne')
            ->will($this->returnValue(array(array())));

        $di = new \Box_Di();
        $di['db'] = $dbMock;

        $this->api->setDi($di);

        $data = array(
            'email' => 'example@boxbilling.com',
            'password' => 'EasyToGuess',
        );

        $this->setExpectedException('\Box_Exception', 'Administrator account already exists', 55);
        $this->api->create($data);
    }

    /**
     * @expectedException \Box_Exception
     */
    public function testLoginWithoutEmail()
    {
        $guestApi = new \Box\Mod\Staff\Api\Guest();

        $di = new \Box_Di();
        $di['validator'] = new \Box_Validate();

        $guestApi->setDi($di);
        $guestApi->login(array());
    }

    /**
     * @expectedException \Box_Exception
     */
    public function testLoginWithoutPassword()
    {
        $guestApi = new \Box\Mod\Staff\Api\Guest();

        $di = new \Box_Di();
        $di['validator'] = new \Box_Validate();

        $guestApi->setDi($di);
        $guestApi->login(array('email'=>'email@domain.com'));
    }

    public function testSuccessfulLogin()
    {
        $modMock = $this->getMockBuilder('Box_Mod')
            ->disableOriginalConstructor()
            ->getMock();
        $modMock->expects($this->atLeastOnce())
            ->method('getConfig')
            ->will($this->returnValue(array()));

        $serviceMock = $this->getMockBuilder('\Box\Mod\Staff\Service')
            ->getMock();
        $serviceMock->expects($this->atLeastOnce())
            ->method('login')
            ->will($this->returnValue(array()));

        $validatorMock = $this->getMockBuilder('\Box_Validate')->getMock();
        $validatorMock->expects($this->atLeastOnce())
            ->method('checkRequiredParamsForArray');

        $di = new \Box_Di();
        $di['validator'] = $validatorMock;

        $guestApi = new \Box\Mod\Staff\Api\Guest();
        $guestApi->setMod($modMock);
        $guestApi->setService($serviceMock);
        $guestApi->setDi($di);
        $result = $guestApi->login(array('email'=>'email@domain.com', 'password'=>'pass'));
        $this->assertInternalType('array', $result);
    }

    public function testLoginCheckIpException()
    {
        $modMock = $this->getMockBuilder('\Box_Mod')
            ->disableOriginalConstructor()
            ->getMock();
        $configArr = array(
            'allowed_ips' => '1.1.1.1'.PHP_EOL.'2.2.2.2',
            'check_ip' => true,
        );
        $modMock->expects($this->atLeastOnce())
            ->method('getConfig')
            ->will($this->returnValue($configArr));

        $validatorMock = $this->getMockBuilder('\Box_Validate')->getMock();
        $validatorMock->expects($this->atLeastOnce())
            ->method('checkRequiredParamsForArray');

        $di = new \Box_Di();
        $di['validator'] = $validatorMock;

        $guestApi = new \Box\Mod\Staff\Api\Guest();
        $guestApi->setMod($modMock);
        $guestApi->setDi($di);
        $ip = '192.168.0.1';
        $guestApi->setIp($ip);

        $this->setExpectedException('\Box_Exception', sprintf('You are not allowed to login to admin area from %s address', $ip), 403);

        $data = array(
            'email'    => 'email@domain.com',
            'password' => 'pass',
        );
        $guestApi->login($data);
    }
}

redpajama_set_name: RedPajamaGithub


text:
'use strict';

/* global require, console */

var express = require('express'),
    router = express.Router();

module.exports = router;


text:
/* From ppp_instance.idl modified Wed Jan  4 06:11:56 2012. */

#ifndef PPAPI_C_PPP_INSTANCE_H_
#define PPAPI_C_PPP_INSTANCE_H_

#include "ppapi/c/pp_bool.h"
#include "ppapi/c/pp_instance.h"
#include "ppapi/c/pp_macros.h"
#include "ppapi/c/pp_point.h"
#include "ppapi/c/pp_rect.h"
#include "ppapi/c/pp_resource.h"
#include "ppapi/c/pp_size.h"
#include "ppapi/c/pp_stdint.h"

#define PPP_INSTANCE_INTERFACE_1_0 "PPP_Instance;1.0"
#define PPP_INSTANCE_INTERFACE_1_1 "PPP_Instance;1.1"
#define PPP_INSTANCE_INTERFACE PPP_INSTANCE_INTERFACE_1_1

/**
 * @file
 * This file defines the PPP_Instance structure - a series of
 * pointers to methods that you must implement in your module.
 */

/**
 * @addtogroup Interfaces
 * @{
 */
/**
 * The PPP_Instance interface contains pointers to a series of
 * functions that you must implement in your module. These functions can be
 * trivial (simply return the default return value) unless you want your module
 * to handle events such as change of focus or input events (keyboard/mouse)
 * events.
 */
struct PPP_Instance_1_1 {
  /**
   * DidCreate() is a creation handler that is called when a new instance is
   * created. This function is called for each instantiation on the page,
   * corresponding to one \<embed\> tag on the page.
   *
   * Generally you would handle this call by initializing the information
   * your module associates with an instance and creating a mapping from the
   * given PP_Instance handle to this data. The
   * PP_Instance handle will be used in subsequent calls to
   * identify which instance the call pertains to.
   *
   * It's possible for more than one instance to be created in a single module.
   * This means that you may get more than one OnCreate without an
   * OnDestroy in between, and should be prepared to maintain
   * multiple states associated with each instance.
   *
   * If this function reports a failure (by returning PP_FALSE),
   * the instance will be deleted.
   *
   * @param[in] instance A new PP_Instance identifying one
   * instance of a module. This is an opaque handle.
   *
   * @param[in] argc The number of arguments contained in argn
   * and argv.
   *
   * @param[in] argn An array of argument names.  These argument names are
   * supplied in the \<embed\> tag, for example:
   * \<embed id="nacl_module" dimensions="2"\> will produce two
   * argument names: "id" and "dimensions."
   *
   * @param[in] argv An array of argument values.  These are the values of the
   * arguments listed in the \<embed\> tag, for example
   * \<embed id="nacl_module" dimensions="2"\> will produce two
   * argument values: "nacl_module" and "2".  The indices of these values match
   * the indices of the corresponding names in argn.
   *
   * @return PP_TRUE on success or PP_FALSE on
   * failure.
   */
  PP_Bool (*DidCreate)(PP_Instance instance,
                       uint32_t argc,
                       const char* argn[],
                       const char* argv[]);
  /**
   * DidDestroy() is an instance destruction handler. This function is called
   * in many cases (see below) when a module instance is destroyed. It will be
   * called even if DidCreate() returned failure.
   *
   * Generally you will handle this call by deallocating the tracking
   * information and the PP_Instance mapping you created in the
   * DidCreate() call. You can also free resources associated with this
   * instance but this isn't required; all resources associated with the deleted
   * instance will be automatically freed when this function returns.
   *
   * The instance identifier will still be valid during this call, so the module
   * can perform cleanup-related tasks. Once this function returns, the
   * PP_Instance handle will be invalid. This means that you can't
   * do any asynchronous operations like network requests, file writes or
   * messaging from this function since they will be immediately canceled.
   *
   * Note: This function will always be skipped on untrusted
   * (Native Client) implementations. This function may be skipped on trusted
   * implementations in certain circumstances when Chrome does "fast shutdown"
   * of a web page. Fast shutdown will happen in some cases when all module
   * instances are being deleted, and no cleanup functions will be called.
   * The module will just be unloaded and the process terminated.
   *
   * @param[in] instance A PP_Instance identifying one instance
   * of a module.
   */
  void (*DidDestroy)(PP_Instance instance);
  /**
   * DidChangeView() is called when the position, size, or other view
   * attributes of the instance has changed.
   */
  void (*DidChangeView)(PP_Instance instance, PP_Resource view_resource);
  /**
   * DidChangeFocus() is called when an instance has gained or lost focus.
   * Having focus means that keyboard events will be sent to the instance.
   * An instance's default condition is that it will not have focus.
   *
   * Note:Clicks on instances will give focus only if you
   * handle the click event. Return true from
   * HandleInputEvent in PPP_InputEvent (or use
   * unfiltered events) to signal that the click event was handled. Otherwise,
   * the browser will bubble the event and give focus to the element on the page
   * that actually did end up consuming it. If you're not getting focus, check
   * to make sure you're returning true from the mouse click in
   * HandleInputEvent.
   *
   * @param[in] instance A PP_Instance identifying the instance
   * receiving the input event.
   *
   * @param[in] has_focus Indicates the new focused state of the instance.
   */
  void (*DidChangeFocus)(PP_Instance instance, PP_Bool has_focus);
  /**
   * HandleDocumentLoad() is called after initialize for a full-frame
   * module that was instantiated based on the MIME type of a DOMWindow
   * navigation. This situation only applies to modules that are pre-registered
   * to handle certain MIME types. If you haven't specifically registered to
   * handle a MIME type or aren't positive this applies to you, your
   * implementation of this function can just return PP_FALSE.
   *
   * The given url_loader corresponds to a
   * PPB_URLLoader instance that is already opened. Its response
   * headers may be queried using PPB_URLLoader::GetResponseInfo.
   * The reference count for the URL loader is not incremented automatically on
   * behalf of the module. You need to increment the reference count yourself
   * if you are going to keep a reference to it.
   *
   * This method returns PP_FALSE if the module cannot handle the
   * data. In response to this method, the module should call
   * ReadResponseBody() to read the incoming data.
   *
   * @param[in] instance A PP_Instance identifying the instance
   * that should do the load.
   *
   * @param[in] url_loader An open PPB_URLLoader instance.
   *
   * @return PP_TRUE if the data was handled,
   * PP_FALSE otherwise.
   */
  PP_Bool (*HandleDocumentLoad)(PP_Instance instance, PP_Resource url_loader);
};

typedef struct PPP_Instance_1_1 PPP_Instance;

struct PPP_Instance_1_0 {
  PP_Bool (*DidCreate)(PP_Instance instance,
                       uint32_t argc,
                       const char* argn[],
                       const char* argv[]);
  void (*DidDestroy)(PP_Instance instance);
  void (*DidChangeView)(PP_Instance instance,
                        const struct PP_Rect* position,
                        const struct PP_Rect* clip);
  void (*DidChangeFocus)(PP_Instance instance, PP_Bool has_focus);
  PP_Bool (*HandleDocumentLoad)(PP_Instance instance, PP_Resource url_loader);
};
/**
 * @}
 */

#endif  /* PPAPI_C_PPP_INSTANCE_H_ */


text:
package org.quartzpowered.network.pipeline;

import javax.crypto.SecretKey;

public interface HandlerFactory {
    public EncryptionHandler createEncryptionHandler(SecretKey sharedSecret);
}


text:
class NewMovieColumns < ActiveRecord::Migration
  def self.up
    add_column :movies, :budget, :string, :limit => 32, :default => "0", :null => false
    add_column :movies, :revenue, :string, :limit => 32, :default => "0", :null => false
  end

  def self.down
  end
end


text:
#include <stdlib.h>

#include "../../../Dependencies/FoundationIO/libFoundationIO/include/BitIO.h"
#include "../../../Dependencies/FoundationIO/libFoundationIO/include/Math.h"
#include "../../../Dependencies/FoundationIO/libFoundationIO/include/Log.h"
#include "../../../Dependencies/FoundationIO/libFoundationIO/include/ContainerIO.h"

#include "../../include/libPCM.h"
#include "../../include/Private/libPCMTypes.h"
#include "../../include/Private/Image/BMPCommon.h"

#ifdef __cplusplus
extern "C" {
#endif

    static uint64_t BMPGetRowSize(const uint16_t BitsPerPixel, const uint32_t ImageWidth) {
        return floor((BitsPerPixel * ImageWidth + 31) / 32) * 4; // floor((4 * 1024 + 31) / 32) * 4
    }

    static uint64_t BMPGetPixelArraySize(const uint64_t RowSize, const int32_t ImageHeight) { // 5568, 3712, there's 54 extra bytes in the PixelArray...
        return RowSize * ImageHeight;
    }

    static uint8_t BMPDecompressRLE8(uint8_t Count, uint8_t Pixel) {
        /*
         End of Scanline Marker: 0
         End of File Marker: 1
         RLE8 Delta: 2; Contains a vertical and horizontal coordinate for the value
         There are 2 modes, absolute and RLE
         The first byte is the run length, the second byte is the value; special values as defined above have a run length of 0.
         */
        return 0;
    }

    static uint8_t BMPDecompressRLE4(uint8_t Count, uint8_t Pixels) {
        /*
         End of Scanline Marker: 0
         End of File Marker: 1
         RLE8 Delta: 2; Contains a vertical and horizontal coordinate for the value
         There are 2 modes, absolute and RLE
         The first byte is the run length, the second byte is the value; special values as defined above have a run length of 0.
         */
        return 0;
    }

    static void BMPParsePalette(PCMFile *PCM, BitBuffer *BitB) {

    }

    void BMPParseMetadata(PCMFile *PCM, BitBuffer *BitB) {
        BitBuffer_Skip(BitB, 16);                           // Skip BM
        uint32_t DIBSize                                    = 0UL;
        PCM->FileSize                                       = ReadBits(LSByteFirst, LSBitFirst, BitB, 32); // 1049654
        BitBuffer_Skip(BitB, 32);                           // 2 16 bit Reserved fields
        PCM->Pic->BMPPixelOffset                            = ReadBits(LSByteFirst, LSBitFirst, BitB, 32); // 1078
        if (PCM->Pic->BMPPixelOffset > 14) { // DIB Header
            DIBSize                                         = ReadBits(LSByteFirst, LSBitFirst, BitB, 32); // 40
            if (DIBSize >= 40) {
                PCM->Pic->Width                             = ReadBits(LSByteFirst, LSBitFirst, BitB, 32); // 1024
                int32_t Height                              = ReadBits(LSByteFirst, LSBitFirst, BitB, 32); // 1024
                if (Height < 0) {
                    PCM->Pic->ImageIsTopDown                = Yes;
                } else {
                    PCM->Pic->ImageIsTopDown                = No;
                }
                PCM->Pic->Height                            = Absolute(Height);
            } else if (DIBSize == 12) {
                PCM->Pic->Width                             = ReadBits(LSByteFirst, LSBitFirst, BitB, 16);
                int16_t Height                              = ReadBits(LSByteFirst, LSBitFirst, BitB, 16);
                if (Height < 0) {
                    PCM->Pic->ImageIsTopDown                = Yes;
                } else {
                    PCM->Pic->ImageIsTopDown                = No;
                }
                PCM->Pic->Height                            = Absolute(Height);
            }
            BitBuffer_Skip(BitB, 16);                       // NumPlanes, always 1
            PCM->BitDepth                                   = ReadBits(LSByteFirst, LSBitFirst, BitB, 16); // 8
            PCM->Pic->BMPCompressionType                    = ReadBits(LSByteFirst, LSBitFirst, BitB, 32); // 0
            PCM->Pic->NumBytesUsedBySamples                 = ReadBits(LSByteFirst, LSBitFirst, BitB, 32); // 16
            PCM->Pic->BMPWidthPixelsPerMeter                = ReadBits(LSByteFirst, LSBitFirst, BitB, 32); // 3780
            PCM->Pic->BMPHeightPixelsPerMeter               = ReadBits(LSByteFirst, LSBitFirst, BitB, 32); // 3780
            PCM->Pic->BMPColorsIndexed                      = ReadBits(LSByteFirst, LSBitFirst, BitB, 32); // 0
            PCM->Pic->BMPIndexColorsUsed                    = ReadBits(LSByteFirst, LSBitFirst, BitB, 32); // 0
            if (DIBSize >= 56) {
                PCM->Pic->BMPColorSpaceType                 = ReadBits(LSByteFirst, LSBitFirst, BitB, 32); // 0000FF00 aka 16,711,680
                if (DIBSize >= 108) {
                    PCM->Pic->BMPXYZCoordinates[0]          = ReadBits(LSByteFirst, LSBitFirst, BitB, 32); // 65280
                    PCM->Pic->BMPXYZCoordinates[1]          = ReadBits(LSByteFirst, LSBitFirst, BitB, 32); // 256
                    PCM->Pic->BMPXYZCoordinates[2]          = ReadBits(LSByteFirst, LSBitFirst, BitB, 32); // 4,278,190,080
                    PCM->Pic->BMPRedGamma                   = ReadBits(LSByteFirst, LSBitFirst, BitB, 32); // 1,934,772,034
                    PCM->Pic->BMPGreenGamma                 = ReadBits(LSByteFirst, LSBitFirst, BitB, 32); // 687,194,752
                    PCM->Pic->BMPBlueGamma                  = ReadBits(LSByteFirst, LSBitFirst, BitB, 32); // 354,334,816
                    if (DIBSize >= 124) {
                        PCM->Pic->BMPICCIntent              = ReadBits(LSByteFirst, LSBitFirst, BitB, 32); // 32,212,256
                        PCM->Pic->BMPICCPayload             = ReadBits(LSByteFirst, LSBitFirst, BitB, 32); // 322,122,560
                        PCM->Pic->BMPICCPayloadSize         = ReadBits(LSByteFirst, LSBitFirst, BitB, 32); // 644,245,120
                        BitBuffer_Skip(BitB, 32); // More Reserved data.
                        // Ok so when the Height is positive, the image is upside down, the bottom of the image is at the top of the file.
                    }
                }
            }
            BitBuffer_Skip(BitB, DIBSize - BitBuffer_GetPosition(BitB)); // Skip the remaining bits.
        } else if (DIBSize == 40 && (PCM->Pic->BMPCompressionType == BMP_BitFields || PCM->Pic->BMPCompressionType == BMP_RGBABitFields)) {
            PCM->Pic->BMPRedMask                            = ReadBits(LSByteFirst, MSBitFirst, BitB, PCM->BitDepth);
            PCM->Pic->BMPGreenMask                          = ReadBits(LSByteFirst, LSBitFirst, BitB, PCM->BitDepth);
            PCM->Pic->BMPBlueMask                           = ReadBits(MSByteFirst, LSBitFirst, BitB, PCM->BitDepth);
            if (PCM->Pic->BMPCompressionType == BMP_RGBABitFields) {
                PCM->Pic->BMPAlphaMask                      = ReadBits(MSByteFirst, LSBitFirst, BitB, PCM->BitDepth);
            }
        } else {
            BitBuffer_Skip(BitB, Bits2Bytes((PCM->Pic->BMPPixelOffset - 14) - DIBSize, false));
        }
    }

    uint16_t ***BMPExtractImage(PCMFile *PCM, BitBuffer *BitB) { // We need to convert the pixels to the Runtime Byte and Bit order.
        uint16_t ***ExtractedImage                  = calloc(PCM->Pic->Width * PCM->Pic->Height * PCM->NumChannels, sizeof(uint16_t**));
        if (PCM != NULL && BitB != NULL && ExtractedImage != NULL) {
            if (PCM->Pic->ImageIsTopDown == Yes) {
                // Read from the bottom to the top.
                for (uint32_t HeightLine = 0; HeightLine < PCM->Pic->Height; HeightLine++) {
                    for (uint32_t WidthLine = 0; WidthLine < PCM->Pic->Width; WidthLine++) {
                        for (uint16_t Channel = 0; Channel < PCM->NumChannels; Channel++) { // Ok, this works when the bit depth is 8 bits per pixel, but what about 1 bit images, or palettized ones?
                            if (PCM->Pic->BMPCompressionType == BMP_RGB) {
                                ExtractedImage[HeightLine][WidthLine][Channel] = ReadBits(LSByteFirst, LSBitFirst, BitB, PCM->BitDepth);
                            } else if (PCM->Pic->BMPCompressionType == BMP_RLE_8Bit) {
                                uint8_t Count       = ReadBits(LSByteFirst, LSBitFirst, BitB, 8);
                                uint8_t PixelIndex  = ReadBits(LSByteFirst, LSBitFirst, BitB, 8);
                            } else if (PCM->Pic->BMPCompressionType == BMP_RLE_4Bit) {
                                uint8_t Count       = ReadBits(LSByteFirst, LSBitFirst, BitB, 8);
                                uint8_t NibblePixel = ReadBits(LSByteFirst, LSBitFirst, BitB, 8);
                            } else if (PCM->Pic->BMPCompressionType == BMP_BitFields) {
                                if (Channel == 0) {
                                    ExtractedImage[HeightLine][WidthLine][0] = ReadBits(LSByteFirst, LSBitFirst, BitB, PCM->Pic->BMPRedMask);
                                } else if (Channel == 1) {
                                    ExtractedImage[HeightLine][WidthLine][1] = ReadBits(LSByteFirst, LSBitFirst, BitB, PCM->Pic->BMPGreenMask);
                                } else if (Channel == 2) {
                                    ExtractedImage[HeightLine][WidthLine][2] = ReadBits(LSByteFirst, LSBitFirst, BitB, PCM->Pic->BMPBlueMask);
                                }
                            } else if (PCM->Pic->BMPCompressionType == BMP_RGBABitFields) {
                                if (Channel == 0) {
                                    ExtractedImage[HeightLine][WidthLine][0] = ReadBits(LSByteFirst, LSBitFirst, BitB, PCM->Pic->BMPRedMask);
                                } else if (Channel == 1) {
                                    ExtractedImage[HeightLine][WidthLine][1] = ReadBits(LSByteFirst, LSBitFirst, BitB, PCM->Pic->BMPGreenMask);
                                } else if (Channel == 2) {
                                    ExtractedImage[HeightLine][WidthLine][2] = ReadBits(LSByteFirst, LSBitFirst, BitB, PCM->Pic->BMPBlueMask);
                                } else if (Channel == 3) {
                                    ExtractedImage[HeightLine][WidthLine][3] = ReadBits(LSByteFirst, LSBitFirst, BitB, PCM->Pic->BMPAlphaMask);
                                }
                            } else if (PCM->Pic->BMPCompressionType == BMP_JPEG) {
                                Log(Log_ERROR, __func__, U8("BMP Compression Type is JPEG, there's nothing we can do since JPEG is a lossy format"));
                            } else if (PCM->Pic->BMPCompressionType == BMP_PNG) {
                                Log(Log_ERROR, __func__, U8("BMP Compression Type is PNG, decode it to uncompressed BMP"));
                            } else if (PCM->Pic->BMPCompressionType == BMP_CMYK || PCM->Pic->BMPCompressionType == BMP_CMYK_RLE_8Bit || PCM->Pic->BMPCompressionType == BMP_CMYK_RLE_4Bit) {
                                Log(Log_ERROR, __func__, U8("CMYK Images are unsupported"));
                            }
                        }
                    }
                }
            } else {
                // Read from the bottom to the top.
                for (uint32_t HeightLine = Absolute(PCM->Pic->Height); HeightLine > 0; HeightLine--) {
                    for (uint32_t WidthLine = 0; WidthLine < PCM->Pic->Width; WidthLine++) {
                        for (uint16_t Channel = 0; Channel < PCM->NumChannels; Channel++) { // Ok, this works when the bit depth is 8 bits per pixel, but what about 1 bit images, or palettized ones?
                            if (PCM->Pic->BMPCompressionType == BMP_RGB) {
                                ExtractedImage[HeightLine][WidthLine][Channel] = ReadBits(LSByteFirst, LSBitFirst, BitB, PCM->BitDepth);
                            } else if (PCM->Pic->BMPCompressionType == BMP_RLE_8Bit) {
                                uint8_t Count       = ReadBits(LSByteFirst, LSBitFirst, BitB, 8);
                                uint8_t PixelIndex  = ReadBits(LSByteFirst, LSBitFirst, BitB, 8);
                                // Look up PixelIndex in the Palette, set Count pixels to that value
                                PCM->Pic->BMPPalette[PixelIndex]; // TODO: Finish the palette lookup
                            } else if (PCM->Pic->BMPCompressionType == BMP_RLE_4Bit) {
                                uint8_t Count       = ReadBits(LSByteFirst, LSBitFirst, BitB, 8);
                                uint8_t NibblePixel = ReadBits(LSByteFirst, LSBitFirst, BitB, 8);
                            } else if (PCM->Pic->BMPCompressionType == BMP_BitFields) {
                                if (Channel == 0) {
                                    ExtractedImage[HeightLine][WidthLine][0] = ReadBits(LSByteFirst, LSBitFirst, BitB, PCM->Pic->BMPRedMask);
                                } else if (Channel == 1) {
                                    ExtractedImage[HeightLine][WidthLine][1] = ReadBits(LSByteFirst, LSBitFirst, BitB, PCM->Pic->BMPGreenMask);
                                } else if (Channel == 2) {
                                    ExtractedImage[HeightLine][WidthLine][2] = ReadBits(LSByteFirst, LSBitFirst, BitB, PCM->Pic->BMPBlueMask);
                                }
                            } else if (PCM->Pic->BMPCompressionType == BMP_RGBABitFields) {
                                if (Channel == 0) {
                                    ExtractedImage[HeightLine][WidthLine][0] = ReadBits(LSByteFirst, LSBitFirst, BitB, PCM->Pic->BMPRedMask);
                                } else if (Channel == 1) {
                                    ExtractedImage[HeightLine][WidthLine][1] = ReadBits(LSByteFirst, LSBitFirst, BitB, PCM->Pic->BMPGreenMask);
                                } else if (Channel == 2) {
                                    ExtractedImage[HeightLine][WidthLine][2] = ReadBits(LSByteFirst, LSBitFirst, BitB, PCM->Pic->BMPBlueMask);
                                } else if (Channel == 3) {
                                    ExtractedImage[HeightLine][WidthLine][3] = ReadBits(LSByteFirst, LSBitFirst, BitB, PCM->Pic->BMPAlphaMask);
                                }
                            } else if (PCM->Pic->BMPCompressionType == BMP_JPEG) {
                                Log(Log_ERROR, __func__, U8("BMP Compression Type is JPEG, there's nothing we can do since JPEG is a lossy format"));
                            } else if (PCM->Pic->BMPCompressionType == BMP_PNG) {
                                Log(Log_ERROR, __func__, U8("BMP Compression Type is PNG, decode it to uncompressed BMP"));
                            } else if (PCM->Pic->BMPCompressionType == BMP_CMYK || PCM->Pic->BMPCompressionType == BMP_CMYK_RLE_8Bit || PCM->Pic->BMPCompressionType == BMP_CMYK_RLE_4Bit) {
                                Log(Log_ERROR, __func__, U8("CMYK Images are unsupported"));
                            }
                        }
                    }
                }
            }
            if (PCM->Pic->BMPColorsIndexed > 0) {
                // The image is palettized, so we need to go ahead and map the pixel bits to the actual colors.
            }
        } else if (PCM == NULL) {
            Log(Log_ERROR, __func__, U8("PCM Pointer is NULL"));
        } else if (BitB == NULL) {
            Log(Log_ERROR, __func__, U8("BitB Pointer is NULL"));
        } else if (ExtractedImage == NULL) {
            Log(Log_ERROR, __func__, U8("Couldn't allocate enough memory to decode the image"));
        }

        return ExtractedImage;
    }

    Container *BMPExtractImage2(PCMFile *PCM, BitBuffer *BitB) {
        Container *Container = NULL;
        uint8_t   *Pixels8   = NULL;
        uint16_t  *Pixels16  = NULL;

        if (PCM != NULL && BitB != NULL) {
            if (PCM->BitDepth <= 8) {
                Pixels8        = calloc(PCM->Pic->Width * PCM->Pic->Height * PCM->NumChannels, sizeof(uint8_t));
                Container      = Container_Init(PCM->NumChannels, PCM->Pic->Width * PCM->Pic->Height, UInteger8Array);
                Container_Attach(Container, Pixels8);
            } else if (PCM->BitDepth <= 16) {
                Pixels16       = calloc(PCM->Pic->Width * PCM->Pic->Height * PCM->NumChannels, sizeof(uint16_t));
                Container      = Container_Init(PCM->NumChannels, PCM->Pic->Width * PCM->Pic->Height, UInteger16Array);
                Container_Attach(Container, Pixels16);
            }

            if (PCM->Pic->ImageIsTopDown == Yes) {
                // Read from the bottom to the top.
                for (uint32_t HeightLine = 0; HeightLine < PCM->Pic->Height; HeightLine++) {
                    for (uint32_t WidthLine = 0; WidthLine < PCM->Pic->Width; WidthLine++) {
                        for (uint16_t Channel = 0; Channel < PCM->NumChannels; Channel++) { // Ok, this works when the bit depth is 8 bits per pixel, but what about 1 bit images, or palettized ones?
                            if (PCM->BitDepth <= 8) {
                                Pixels8[HeightLine * WidthLine * Channel]  = ReadBits(LSByteFirst, LSBitFirst, BitB, PCM->BitDepth);
                            } else if (PCM->BitDepth <= 16) {
                                Pixels16[HeightLine * WidthLine * Channel] = ReadBits(LSByteFirst, LSBitFirst, BitB, PCM->BitDepth);
                            }
                        }
                    }
                }
            } else {
                // Read from the bottom to the top.
                for (uint32_t HeightLine = Absolute(PCM->Pic->Height); HeightLine > 0; HeightLine--) {
                    for (uint32_t WidthLine = 0; WidthLine < PCM->Pic->Width; WidthLine++) {
                        for (uint16_t Channel = 0; Channel < PCM->NumChannels; Channel++) { // Ok, this works when the bit depth is 8 bits per pixel, but what about 1 bit images, or palettized ones?
                            if (PCM->BitDepth <= 8) {
                                Pixels8[HeightLine * WidthLine * Channel]  = ReadBits(LSByteFirst, LSBitFirst, BitB, PCM->BitDepth);
                            } else if (PCM->BitDepth <= 16) {
                                Pixels16[HeightLine * WidthLine * Channel] = ReadBits(LSByteFirst, LSBitFirst, BitB, PCM->BitDepth);
                            }
                            if (PCM->Pic->BMPColorsIndexed == Yes) {
                                // Look up Pixels8[HeightLine * WidthLine * Channel] in the index.
                                PCM->Pic->BMPColorsIndexed;
                            }
                        }
                    }
                }
            }
            if (PCM->Pic->BMPColorsIndexed > 0) {
                // The image is palettized, so we need to go ahead and map the pixel bits to the actual colors.
                // Basically just look up the value
            }
        }
        return Container;
    }

#ifdef __cplusplus
}
#endif


text:
export var rAF = (function() {
    return window.requestAnimationFrame ||
           window.webkitRequestAnimationFrame ||
           window.mozRequestAnimationFrame;
})();

export default rAF;

export var cancelRAF = (function() {
    return window.cancelAnimationFrame ||
           window.cancelRequestAnimationFrame ||
           window.webkitCancelRequestAnimationFrame ||
           window.mozCancelRequestAnimationFrame;
})();


text:
use libc::{c_char, c_int, c_void};
use pyport::Py_ssize_t;
use object::*;
use methodobject::PyMethodDef;

#[cfg_attr(windows, link(name="pythonXY"))] extern "C" {
    pub static mut PyModule_Type: PyTypeObject;
}

#[inline(always)]
pub unsafe fn PyModule_Check(op : *mut PyObject) -> c_int {
    PyObject_TypeCheck(op, &mut PyModule_Type)
}

#[inline(always)]
pub unsafe fn PyModule_CheckExact(op : *mut PyObject) -> c_int {
    (Py_TYPE(op) == &mut PyModule_Type) as c_int
}

#[cfg_attr(windows, link(name="pythonXY"))] extern "C" {
    pub fn PyModule_NewObject(name: *mut PyObject) -> *mut PyObject;
    pub fn PyModule_New(name: *const c_char) -> *mut PyObject;
    pub fn PyModule_GetDict(arg1: *mut PyObject) -> *mut PyObject;
    pub fn PyModule_GetNameObject(arg1: *mut PyObject) -> *mut PyObject;
    pub fn PyModule_GetName(arg1: *mut PyObject) -> *const c_char;
    pub fn PyModule_GetFilename(arg1: *mut PyObject) -> *const c_char;
    pub fn PyModule_GetFilenameObject(arg1: *mut PyObject) -> *mut PyObject;
    pub fn PyModule_GetDef(arg1: *mut PyObject) -> *mut PyModuleDef;
    pub fn PyModule_GetState(arg1: *mut PyObject) -> *mut c_void;

    #[cfg(Py_3_5)]
    pub fn PyModuleDef_Init(arg1: *mut PyModuleDef) -> *mut PyObject;
    #[cfg(Py_3_5)]
    pub static mut PyModuleDef_Type: PyTypeObject;
}

#[repr(C)]
#[derive(Copy)]
pub struct PyModuleDef_Base {
    pub ob_base: PyObject,
    pub m_init: Option<extern "C" fn() -> *mut PyObject>,
    pub m_index: Py_ssize_t,
    pub m_copy: *mut PyObject,
}
impl Clone for PyModuleDef_Base {
    fn clone(&self) -> PyModuleDef_Base { *self }
}

pub const PyModuleDef_HEAD_INIT: PyModuleDef_Base = PyModuleDef_Base {
    ob_base: PyObject_HEAD_INIT,
    m_init: None,
    m_index: 0,
    m_copy: 0 as *mut PyObject
};

#[repr(C)]
#[derive(Copy)]
#[cfg(Py_3_5)]
pub struct PyModuleDef_Slot {
    pub slot: c_int,
    pub value: *mut c_void,
}
#[cfg(Py_3_5)]
impl Clone for PyModuleDef_Slot {
    fn clone(&self) -> PyModuleDef_Slot { *self }
}

#[cfg(Py_3_5)]
pub const Py_mod_create : c_int = 1;
#[cfg(Py_3_5)]
pub const Py_mod_exec : c_int = 2;

#[repr(C)]
#[derive(Copy)]
pub struct PyModuleDef {
    pub m_base: PyModuleDef_Base,
    pub m_name: *const c_char,
    pub m_doc: *const c_char,
    pub m_size: Py_ssize_t,
    pub m_methods: *mut PyMethodDef,
    #[cfg(not(Py_3_5))]
    pub m_reload: Option<inquiry>,
    #[cfg(Py_3_5)]
    pub m_slots: *mut PyModuleDef_Slot,
    pub m_traverse: Option<traverseproc>,
    pub m_clear: Option<inquiry>,
    pub m_free: Option<freefunc>,
}
impl Clone for PyModuleDef {
    fn clone(&self) -> PyModuleDef { *self }
}

#[cfg(not(Py_3_5))]
pub const PyModuleDef_INIT: PyModuleDef = PyModuleDef {
    m_base: PyModuleDef_HEAD_INIT,
    m_name: 0 as *const _,
    m_doc: 0 as *const _,
    m_size: 0,
    m_methods: 0 as *mut _,
    m_reload: None,
    m_traverse: None,
    m_clear: None,
    m_free: None
};

#[cfg(Py_3_5)]
pub const PyModuleDef_INIT: PyModuleDef = PyModuleDef {
    m_base: PyModuleDef_HEAD_INIT,
    m_name: 0 as *const _,
    m_doc: 0 as *const _,
    m_size: 0,
    m_methods: 0 as *mut _,
    m_slots: 0 as *mut _,
    m_traverse: None,
    m_clear: None,
    m_free: None
};


text:
from cno import EDA
from cno import SIF
from cno.testing import getdata
import tempfile

filename = getdata("test_simple.eda")
sifname = getdata("test_simple.sif")

def test_eda():
    e = EDA(filename, verbose=True)
    s1 = e.export2sif()
    s2 = SIF(sifname)
    assert s1 == s2

    try:
        e = EDA("dummy")
        assert False
    except:
        assert True

def test_eda_format():
    # test eda with header (used in HPN-Dream8 challenge
    fh = tempfile.NamedTemporaryFile(delete=False)
    fh.write(b"EdgeScore\n")
    fh.write(b"A (1) B = 0.5\n")
    fh.close()
    e = EDA(fh.name)
    fh.delete = True
    fh.close()

    # test bad data sets

    fh = tempfile.NamedTemporaryFile(delete=False)
    fh.write(b"A (1) B = 0.5\n")
    fh.write(b"\n") # should be skipped without errors
    fh.write(b"A B = 0.5\n") # should raise an erro
    fh.close()
    try:
        e = EDA(fh.name)
        assert False
    except:
        assert True
    fh.delete = True
    fh.close()


text:
namespace AMD
{
///////////////////////////////////////////////////////////////////////////////
class VulkanComputeSample
{
public:
    VulkanComputeSample(const VulkanComputeSample&) = delete;
    VulkanComputeSample& operator= (const VulkanComputeSample&) = delete;

    VulkanComputeSample();
    virtual ~VulkanComputeSample();

    void Run();
    struct ImportTable;

protected:
    VkInstance instance_ = VK_NULL_HANDLE;
    VkDevice device_ = VK_NULL_HANDLE;
    VkPhysicalDevice physicalDevice_ = VK_NULL_HANDLE;
    VkQueue queue_ = VK_NULL_HANDLE;

    std::unique_ptr<ImportTable> importTable_;

    int queueFamilyIndex_ = -1;

private:
    VkCommandPool commandPool_;
    VkCommandBuffer commandBuffer_;

#ifdef _DEBUG
    VkDebugReportCallbackEXT debugCallback_;
#endif
};
}   // namespace AMD

#endif


text:
const _queue: Promise<void>[] = [];

// A global queue of functions that will execute one after the other. The function must return a promise.
// fn is either a blocking function or a function that returns a promise
export function queueAction(fn: () => Promise<any>) {
  let promise = _queue.length ? _queue[_queue.length - 1] : Promise.resolve();
  // Execute fn regardless of the result of the existing promise. We
  // don't use finally here because finally can't modify the return value.
  promise = promise
    .then(
      (..._args) => fn(),
      (..._args) => fn()
    )
    .then(
      (value) => {
        _queue.shift();
        return value;
      },
      (e) => {
        _queue.shift();
        throw e;
      }
    );
  _queue.push(promise);

  return promise;
}

// Wrap a function to produce a function that will be queued when invoked
export function queuedAction<T extends any[], K>(
  fn: (...args: T) => Promise<K>,
  context?
): (...args: T) => Promise<any> {
  return (...args: T) => queueAction(() => fn.apply(context, args));
}


text:
module Frenetic.NetCore.Semantics
  ( evalProgram
  , Id (..)
  , Act (..)
  , Pol (..)
  , In (..)
  , Out (..)
  , Callback (..)
  , Callbacks
  , callbackDelayStream
  , callbackInterval
  , evalPol
  , evalAct
  , desugarPolicy
  , synthRestrictPol
  , isForward
  , isGetPacket
  , isQuery
  , matchPkt
  , actOnMatch
  , preimgOfAct
  , seqAct
  , outToMicroflowAction
  )  where

import Prelude hiding (pred)
import Nettle.OpenFlow.Match
import Nettle.OpenFlow.Packet (BufferID)
import Nettle.IPv4.IPAddress
import Frenetic.NetCore.Reduce (isEmptyPredicate)
import Frenetic.Pattern
import Frenetic.Common
import Frenetic.Topo (Switch,Port,Loc)
import Frenetic.NetCore.Types
import Frenetic.NetCore.Short
import qualified Data.ByteString.Lazy as BS
import Control.Monad.State
import qualified Data.Map as M

import Data.Generics

{-# LANGUAGE DeriveDataTypeable #-}

type Id = Int

data Prog
  = ProgPol Pol
  | ProgLetQueue Switch Port Word16 (Queue -> Prog)
  | ProgUnion Prog Prog

data Pol
  = PolEmpty
  | PolProcessIn Predicate [Act]
  | PolUnion Pol Pol
  | PolRestrict Pol Predicate
  | PolGenPacket Id
  -- | PolSeq Pol Pol
  deriving (Show, Eq, Data, Typeable)

data Act
  = ActFwd PseudoPort Modification
  | ActQueryPktCounter Id Int
  | ActQueryByteCounter Id Int
  | ActGetPkt Id
  | ActMonSwitch Id
  deriving (Show, Eq, Data, Typeable)

data In
  = InPkt Loc Packet (Maybe BufferID)
  | InGenPkt Id Switch PseudoPort Packet ByteString
  | InCounters Id Switch Predicate Integer {- packets -} Integer {- bytes -}
  | InSwitchEvt SwitchEvent
  deriving (Show, Eq, Data, Typeable)

data Out
  = OutPkt Switch PseudoPort Packet (Either BufferID ByteString)
  | OutIncrPktCounter Id
  | OutIncrByteCounter Id Integer
  | OutUpdPktCounter Id Switch Predicate Integer
  | OutUpdByteCounter Id Switch Predicate Integer
  | OutGetPkt Id Loc Packet
  | OutNothing
  | OutSwitchEvt Id SwitchEvent
  deriving (Show, Eq, Data, Typeable)

data Callback
  = CallbackByteCounter Int ((Switch, Integer) -> IO ())
  | CallbackPktCounter Int ((Switch, Integer) -> IO ())
  | CallbackGetPkt ((Loc, Packet) -> IO ())
  | CallbackMonSwitch (SwitchEvent -> IO ())

instance Show Callback where
  show (CallbackByteCounter n _) = "CallbackByteCounter " ++ show n
  show (CallbackPktCounter n _) = "CallbackPktCounter " ++ show n
  show (CallbackGetPkt _) = "CallbackGetPkt"
  show (CallbackMonSwitch _) = "CallbackMonSwitch"

type Callbacks = Map Id Callback

outToMicroflowAction (OutPkt _ pt _ (Left _)) = Just (ActFwd pt unmodified)
outToMicroflowAction (OutGetPkt x _ _) = Just (ActGetPkt x)
outToMicroflowAction _ = Nothing

seqAct :: Act -> Act -> Maybe Act
seqAct (ActFwd p mods1) (ActFwd InPort mods2) = Just (ActFwd p mods3)
  where mods3 = Modification
                  (modifyDlSrc mods2 `ifLeft` modifyDlSrc mods1)
                  (modifyDlDst mods2 `ifLeft` modifyDlDst mods1)
                  (modifyDlVlan mods2 `ifLeft` modifyDlVlan mods1)
                  (modifyDlVlanPcp mods2 `ifLeft` modifyDlVlanPcp mods1)
                  (modifyNwSrc mods2 `ifLeft` modifyNwSrc mods1)
                  (modifyNwDst mods2 `ifLeft` modifyNwDst mods1)
                  (modifyNwTos mods2 `ifLeft` modifyNwTos mods1)
                  (modifyTpSrc mods2 `ifLeft` modifyTpSrc mods1)
                  (modifyTpDst mods2 `ifLeft` modifyTpDst mods1)

seqAct (ActFwd _ mods1) (ActFwd p mods2) = Just (ActFwd p mods3)
  where mods3 = Modification
                  (modifyDlSrc mods2 `ifLeft` modifyDlSrc mods1)
                  (modifyDlDst mods2 `ifLeft` modifyDlDst mods1)
                  (modifyDlVlan mods2 `ifLeft` modifyDlVlan mods1)
                  (modifyDlVlanPcp mods2 `ifLeft` modifyDlVlanPcp mods1)
                  (modifyNwSrc mods2 `ifLeft` modifyNwSrc mods1)
                  (modifyNwDst mods2 `ifLeft` modifyNwDst mods1)
                  (modifyNwTos mods2 `ifLeft` modifyNwTos mods1)
                  (modifyTpSrc mods2 `ifLeft` modifyTpSrc mods1)
                  (modifyTpDst mods2 `ifLeft` modifyTpDst mods1)
seqAct _ _ = Nothing

outToIn :: Out -> Maybe In
-- TODO(arjun): pol1;pol2 doesn't work if pol1 emits to a pseudoport?
outToIn (OutPkt sw (Physical pt) pk (Left buf)) =
  Just (InPkt (Loc sw pt) pk (Just buf))
-- TODO(arjun): perhaps Out should carry the channel ID
-- outToIn (OutPkt sw pt pk (Right bytes)) = Just (InGenPkt ??? sw pt pk bytes)
outToIn _ = Nothing

isGetPacket (ActGetPkt{}) = True
isGetPacket _ = False

isForward :: Act -> Bool
isForward (ActFwd _ _) = True
isForward _ = False

isQuery :: Act -> Bool
isQuery act = case act of
  ActQueryPktCounter {} -> True
  ActQueryByteCounter {} -> True
  ActGetPkt {} -> True
  ActFwd {} -> False
  ActMonSwitch {} -> True

-- |Restricts the policy's domain to 'pred'. Does not eliminate
-- 'Restrict' expressions, but does restrict their restrictions.
synthRestrictPol :: Pol -> Predicate -> Pol
synthRestrictPol pol pred = case pol of
  PolEmpty -> PolEmpty
  PolProcessIn pred' acts ->
    PolProcessIn (And pred' pred) acts
  PolUnion pol1 pol2 ->
    PolUnion (synthRestrictPol pol1 pred) (synthRestrictPol pol2 pred)
  -- PolSeq pol1 pol2 ->
  --   PolSeq (synthRestrictPol pol1 pred) pol2 -- No need to restrict pol2!
  PolRestrict (PolGenPacket chan) pred' ->
    PolRestrict (PolGenPacket chan) (And pred pred')
  PolRestrict pol pred' ->
    PolRestrict pol (And pred pred')
  PolGenPacket chan ->
    PolRestrict (PolGenPacket chan) pred

inPacket :: In -> Maybe Packet
inPacket (InPkt _ pkt _) = Just pkt
inPacket (InGenPkt _ _ _ pkt _) = Just pkt
inPacket (InCounters _ _ _ _ _) = Nothing
inPacket (InSwitchEvt _) = Nothing

evalPol = pol
evalAct = action

pol :: Pol -> In -> [Out]
pol PolEmpty _ = []
pol (PolUnion p1 p2) inp = pol p1 inp ++ pol p2 inp
pol (PolProcessIn pr acts) inp =
  if pred pr inp then map (\a -> action a inp) acts else []
pol (PolRestrict p pr) inp =
  if pred pr inp then pol p inp else []
pol (PolGenPacket x) inp = case inp of
  InGenPkt y sw pt pkt raw ->
    if x == y then [OutPkt sw pt pkt (Right raw)] else []
  otherwise -> []
-- pol (PolSeq p1 p2) inp = concatMap (pol p2) (mapMaybe outToIn (pol p1 inp))

action :: Act -> In -> Out
action (ActFwd pt mods) (InPkt (Loc sw _) hdrs maybePkt) = case maybePkt of
  Just pkt -> OutPkt sw pt hdrs (Left pkt)
  Nothing -> OutNothing
action (ActFwd _ _) (InGenPkt _ _ _ _ _) = OutNothing
action (ActFwd _ _) (InCounters _ _ _ _ _) = OutNothing
action (ActFwd _ _) (InSwitchEvt _) = OutNothing
action (ActQueryPktCounter x _) (InCounters y sw pred numPkts _) =
  if x == y then
    OutUpdPktCounter x sw pred numPkts
  else
    OutNothing
action (ActQueryPktCounter _ _) (InPkt _ _ _) = OutNothing
action (ActQueryPktCounter x _) (InGenPkt _ _ _ _ _) = OutIncrPktCounter x
action (ActQueryPktCounter _ _) (InSwitchEvt _) = OutNothing
action (ActQueryByteCounter x _) (InCounters y sw pred _ numBytes) =
  if x == y then
    OutUpdByteCounter x sw pred numBytes
  else
    OutNothing
action (ActQueryByteCounter _ _) (InPkt _ _ _) = OutNothing
action (ActQueryByteCounter x _) (InGenPkt _ _ _ _ pkt) =
  OutIncrByteCounter x (fromIntegral (BS.length pkt))
action (ActQueryByteCounter _ _) (InSwitchEvt _) = OutNothing
action (ActGetPkt x) (InPkt loc hdrs _) = OutGetPkt x loc hdrs
action (ActGetPkt _) (InGenPkt _ _ _ _ _) = OutNothing
action (ActGetPkt _) (InCounters _ _ _ _ _) = OutNothing
action (ActGetPkt _) (InSwitchEvt _) = OutNothing
action (ActMonSwitch x) (InSwitchEvt evt) = OutSwitchEvt x evt
action (ActMonSwitch _) (InPkt _ _ _) = OutNothing
action (ActMonSwitch _) (InGenPkt _ _ _ _ _) = OutNothing
action (ActMonSwitch _) (InCounters _ _ _ _ _) = OutNothing

ifLeft :: Maybe a -> Maybe a -> Maybe a
ifLeft (Just x) _ = Just x
ifLeft Nothing y = y

eqIfJust :: Eq a => Maybe a -> Maybe a -> Maybe (Maybe a)
eqIfJust (Just x) (Just y) = if x == y then Just Nothing else Nothing
eqIfJust (Just x) Nothing = Just Nothing
eqIfJust Nothing rhs = Just rhs

eqIfJustIP :: Maybe IPAddress
           -> IPAddressPrefix
           -> Maybe IPAddressPrefix
eqIfJustIP (Just x) y =
  if x `elemOfPrefix` y then Just (IPAddressPrefix (IPAddress 0) 0) else Nothing
eqIfJustIP Nothing rhs = Just rhs

preimgOfAct :: Act -> Match -> Maybe Match
preimgOfAct (ActFwd (Physical pt) (Modification{..})) (Match{..}) = do
  inPort <- eqIfJust (Just pt) inPort
  srcEthAddress <- eqIfJust modifyDlSrc srcEthAddress
  dstEthAddress <- eqIfJust modifyDlDst dstEthAddress
  let unvlan Nothing = 0xffff
      unvlan (Just v) = v
  vLANID <- eqIfJust (fmap unvlan modifyDlVlan) vLANID
  vLANPriority <- eqIfJust modifyDlVlanPcp vLANPriority
  ipTypeOfService <- eqIfJust modifyNwTos ipTypeOfService
  srcIPAddress <- eqIfJustIP modifyNwSrc srcIPAddress
  dstIPAddress <- eqIfJustIP modifyNwDst dstIPAddress
  srcTransportPort <- eqIfJust modifyTpSrc srcTransportPort
  dstTransportPort <- eqIfJust modifyTpDst dstTransportPort
  return $ Match inPort srcEthAddress dstEthAddress vLANID vLANPriority
                 ethFrameType ipTypeOfService matchIPProtocol srcIPAddress
                 dstIPAddress srcTransportPort dstTransportPort
preimgOfAct (ActFwd InPort (Modification{..})) (Match{..}) = do
  srcEthAddress <- eqIfJust modifyDlSrc srcEthAddress
  dstEthAddress <- eqIfJust modifyDlDst dstEthAddress
  let unvlan Nothing = 0xffff
      unvlan (Just v) = v
  vLANID <- eqIfJust (fmap unvlan modifyDlVlan) vLANID
  vLANPriority <- eqIfJust modifyDlVlanPcp vLANPriority
  ipTypeOfService <- eqIfJust modifyNwTos ipTypeOfService
  srcIPAddress <- eqIfJustIP modifyNwSrc srcIPAddress
  dstIPAddress <- eqIfJustIP modifyNwDst dstIPAddress
  srcTransportPort <- eqIfJust modifyTpSrc srcTransportPort
  dstTransportPort <- eqIfJust modifyTpDst dstTransportPort
  return $ Match Nothing srcEthAddress dstEthAddress vLANID vLANPriority
                 ethFrameType ipTypeOfService matchIPProtocol srcIPAddress
                 dstIPAddress srcTransportPort dstTransportPort
preimgOfAct _ _ = Nothing

actOnMatch :: Act -> Match -> Maybe Match
actOnMatch (ActFwd (Physical pt) (Modification{..})) (Match{..}) =
  Just $ Match (Just pt)
           (modifyDlSrc `ifLeft` srcEthAddress)
           (modifyDlDst `ifLeft` dstEthAddress)
           (case modifyDlVlan of
              Just Nothing -> Just 0xffff
              Just (Just vlan) -> Just vlan
              Nothing -> vLANID)
           (modifyDlVlanPcp `ifLeft` vLANPriority)
           ethFrameType
           (modifyNwTos `ifLeft` ipTypeOfService)
           matchIPProtocol
           (case modifyNwSrc of
              Just ip -> IPAddressPrefix ip 32
              Nothing -> srcIPAddress)
           (case modifyNwDst of
              Just ip -> IPAddressPrefix ip 32
              Nothing -> dstIPAddress)
           (modifyTpSrc `ifLeft` srcTransportPort)
           (modifyTpDst `ifLeft` dstTransportPort)
actOnMatch (ActFwd AllPorts _) _ = Nothing
actOnMatch (ActFwd InPort _) _ = Nothing -- TODO(mjr): Not sure what this func is...
actOnMatch (ActFwd (ToQueue _) _) _ = Nothing -- TODO(arjun): easy IMO
actOnMatch (ActQueryPktCounter _ _) _ = Nothing
actOnMatch (ActQueryByteCounter _ _) _ = Nothing
actOnMatch (ActGetPkt _) _ = Nothing
actOnMatch (ActMonSwitch _) _ = Nothing

-- |When a packet-specific predicate is applied to a non-packet input, we
-- produce this default value.
nonPktDefault = False

counterMatches :: In -> Predicate -> Bool
counterMatches (InCounters _ _ pred _ _) pred' =
  isEmptyPredicate (And pred (Not pred'))
counterMatches _ _ = False

-- |'pktHeaderIs inPkt sel v' tests if the input packet's header is 'v'. If
-- 'inPkt' is not a packet, but some other type of input, 'pktHeaderIs' returns
-- 'False'.
pktHeaderIs :: Eq a => In -> (Packet -> a) -> a -> Bool
pktHeaderIs inp sel v = case inPacket inp of
  Just pkt -> sel pkt == v
  Nothing -> nonPktDefault

-- |Use 'tpPktHeaderIs' it match OpenFlow headers that only meaningful for
-- certain types of packets (e.g., TCP ports and IP protocol.)
tpPktHeaderIs :: Eq a => In -> (Packet -> Maybe a) -> a -> Bool
tpPktHeaderIs inp sel v = case inPacket inp of
  Just pkt -> case sel pkt of
    Nothing -> False
    Just v' -> v' == v
  Nothing -> nonPktDefault

pred :: Predicate -> In -> Bool
pred Any _ = True
pred None _ = False
pred (Or pr1 pr2) inp = pred pr1 inp || pred pr2 inp
pred (And pr1 pr2) inp = pred pr1 inp && pred pr2 inp
pred (Not pr) inp = not (pred pr inp)
pred (DlSrc eth) inp =
  pktHeaderIs inp pktDlSrc eth || counterMatches inp (DlSrc eth)
pred (DlDst eth) inp =
  pktHeaderIs inp pktDlDst eth || counterMatches inp (DlDst eth)
pred (DlTyp typ) inp =
  pktHeaderIs inp pktDlTyp typ || counterMatches inp (DlTyp typ)
pred (DlVlan vlan) inp =
  pktHeaderIs inp pktDlVlan vlan || counterMatches inp (DlVlan vlan)
pred (DlVlanPcp pcp) inp =
  pktHeaderIs inp pktDlVlanPcp pcp || counterMatches inp (DlVlanPcp pcp)
pred (NwSrc (IPAddressPrefix prefix len)) inp = case inPacket inp of
  Just Packet{..} -> case pktNwSrc of
    Nothing -> len == 0
    Just ip -> ip `elemOfPrefix` (IPAddressPrefix prefix len)
  Nothing -> nonPktDefault
pred (NwDst (IPAddressPrefix prefix len)) inp = case inPacket inp of
  Just Packet{..} -> case pktNwDst of
    Nothing -> len == 0
    Just ip -> ip `elemOfPrefix` (IPAddressPrefix prefix len)
  Nothing -> nonPktDefault
pred (NwProto proto) inp =
  pktHeaderIs inp pktNwProto proto || counterMatches inp (NwProto proto)
pred (TpSrcPort pt) inp =
  tpPktHeaderIs inp pktTpSrc pt || counterMatches inp (TpSrcPort pt)
pred (TpDstPort pt) inp =
  tpPktHeaderIs inp pktTpDst pt || counterMatches inp (TpDstPort pt)
pred (NwTos tos) inp =
  pktHeaderIs inp pktNwTos tos || counterMatches inp (NwTos tos)
pred (Switch sw) inp = case inp of
  InPkt (Loc sw' _) _ _ -> sw' == sw
  InGenPkt _ sw' _ _ _ -> sw' == sw
  InSwitchEvt (SwitchConnected sw' _) -> sw == sw'
  InSwitchEvt (SwitchDisconnected sw') -> sw == sw'
  InSwitchEvt (PortEvent sw' _ _ _) -> sw == sw'
  InCounters _ _ pred _ _ -> isEmptyPredicate (And pred (Not (Switch sw)))
pred (IngressPort pt) inp = case inp of
  InPkt (Loc _ pt') _ _ -> pt == pt'
  InGenPkt _ _ pt' _ _ -> case pt' of
    Physical p -> p == pt
    otherwise -> False
  InSwitchEvt (PortEvent _ pt' _ _) -> pt == pt'
  InSwitchEvt (SwitchConnected _ _) -> nonPktDefault
  InSwitchEvt (SwitchDisconnected _) -> nonPktDefault
  InCounters _ _ pred _ _ -> isEmptyPredicate (And pred (Not (IngressPort pt)))

callbackInterval :: Callback -> Maybe Int
callbackInterval (CallbackByteCounter n _) = Just n
callbackInterval (CallbackPktCounter n _) = Just n
callbackInterval (CallbackGetPkt _) = Nothing
callbackInterval (CallbackMonSwitch _) = Nothing

insDelayStream :: Int
               -> a
               -> [Either a Int]
               -> [Either a Int]
insDelayStream delay evt [] = [Right delay, Left evt]
insDelayStream delay evt (Right delay' : rest) =
  let delay'' = delay - delay'
    in if delay'' > 0 then
         (Right delay') : (insDelayStream delay'' evt rest)
       else if delay'' == 0 then
         (Right delay) : (Left evt) : rest
       else {- delay'' < 0 -}
         (Right delay) : (Left evt) : (Right (delay' - delay)) : rest
insDelayStream delay evt (Left evt' : rest) =
  (Left evt') : (insDelayStream delay evt rest)

-- |Returns an infinite stream of callbacks and delays. The controller should
-- invoke callbacks with the current counter or pause for the delay.
--
-- The delay is in millseconds. (Note that 'threadDelay' takes a
-- nanosecond argument.)
callbackDelayStream :: Callbacks -> [Either (Id, Callback) Int]
callbackDelayStream callbacks = loop initial
  where loop :: [Either (Int, Id, Callback) Int] -> [Either (Id, Callback) Int]
        loop [] = []
        loop (Right delay : future) = (Right delay) : (loop future)
        loop (Left evt@(delay, x, cb) : future) =
          let future' = insDelayStream delay evt future
            in (Left (x, cb)) : (loop future')
        select :: (Id, Callback) -> Maybe (Int, Id, Callback)
        select (x, cb) = case callbackInterval cb of
          Nothing -> Nothing
          Just delay -> Just (delay, x, cb)
        initial :: [Either (Int, Id, Callback) Int]
        initial = foldr (\evt@(delay, _,_) acc -> insDelayStream delay evt acc)
                        []
                        (mapMaybe select (M.toList callbacks))

type DSState = (Id, Map Id Callback, [(Id, Chan (Loc, ByteString))])

type DS a = State DSState a

newCallback :: Callback -> DS Id
newCallback cb = do
  (x, cbs, gens) <- get
  put (x+1, M.insert x cb cbs, gens)
  return x

newGenPacket :: Chan (Loc, ByteString) -> DS Id
newGenPacket chan = do
  (x, cbs, gens) <- get
  put (x+1, cbs, (x,chan):gens)
  return x

dsPolicy ::  Policy -> DS Pol
dsPolicy PoBottom = return PolEmpty
dsPolicy (PoBasic pred actions) = do
  actions' <- mapM dsAction actions
  return (PolProcessIn pred actions')
dsPolicy (PoUnion pol1 pol2) = do
  pol1' <- dsPolicy pol1
  pol2' <- dsPolicy pol2
  return (PolUnion pol1' pol2')
dsPolicy (Restrict pol pred) = do
  pol' <- dsPolicy pol
  return (PolRestrict pol' pred)
dsPolicy (SendPackets chan) = do
  x <- newGenPacket chan
  return (PolGenPacket x)
dsPolicy (Sequence pol1 pol2) = do
  pol1' <- dsPolicy pol1
  pol2' <- dsPolicy pol2
  return (unionClean $ deSeq pol1' pol2')

unionClean (PolUnion PolEmpty a) = unionClean a
unionClean (PolUnion a PolEmpty) = unionClean a
unionClean (PolUnion a b) = PolUnion (unionClean a) (unionClean b)
unionClean (PolRestrict a pred) = PolRestrict (unionClean a) pred
unionClean a = a

deSeq (PolUnion p1 p2) p3 = PolUnion (deSeq p1 p3) (deSeq p2 p3)
deSeq (PolRestrict p1 pred) p3 = PolRestrict (deSeq p1 p3) pred
deSeq (PolGenPacket id) _ = PolGenPacket id
deSeq PolEmpty _ = PolEmpty
deSeq (PolProcessIn pred acts) pol = (foldl PolUnion PolEmpty) $ map (deSeq1 pred pol) acts

rightIfJust Nothing a = a
rightIfJust a Nothing = a
rightIfJust _ b = b

-- This may not handle the semantics of 'stripVlan' correctly
unionModR Modification{..} (Modification
                            modifyDlSrc1
                            modifyDlDst1
                            (Just Nothing)
                            modifyDlVlanPcp1
                            modifyNwSrc1
                            modifyNwDst1
                            modifyNwTos1
                            modifyTpSrc1
                            modifyTpDst1)
  =
  Modification (modifyDlSrc `rightIfJust` modifyDlSrc1)
               (modifyDlDst `rightIfJust` modifyDlDst1)
               (Just Nothing)
               Nothing
               (modifyNwSrc `rightIfJust` modifyNwSrc1)
               (modifyNwDst `rightIfJust` modifyNwDst1)
               (modifyNwTos `rightIfJust` modifyNwTos1)
               (modifyTpSrc `rightIfJust` modifyTpSrc1)
               (modifyTpDst `rightIfJust` modifyTpDst1)

unionModR Modification{..} (Modification
                            modifyDlSrc1
                            modifyDlDst1
                            modifyDlVlan1
                            modifyDlVlanPcp1
                            modifyNwSrc1
                            modifyNwDst1
                            modifyNwTos1
                            modifyTpSrc1
                            modifyTpDst1)
  =
  Modification (modifyDlSrc `rightIfJust` modifyDlSrc1)
               (modifyDlDst `rightIfJust` modifyDlDst1)
               (modifyDlVlan `rightIfJust` modifyDlVlan1)
               (modifyDlVlanPcp `rightIfJust` modifyDlVlanPcp1)
               (modifyNwSrc `rightIfJust` modifyNwSrc1)
               (modifyNwDst `rightIfJust` modifyNwDst1)
               (modifyNwTos `rightIfJust` modifyNwTos1)
               (modifyTpSrc `rightIfJust` modifyTpSrc1)
               (modifyTpDst `rightIfJust` modifyTpDst1)

deSeq1 pred pol act = PolRestrict (transformPol pol act) pred

transformPol (PolUnion p1 p2) a = PolUnion (transformPol p1 a) (transformPol p2 a)
transformPol (PolProcessIn pred acts) act = PolProcessIn (transformPred pred act) (map (transformAct act) acts)

transformAct (ActFwd pOld modOld) (ActFwd InPort modNew) = ActFwd pOld (modOld `unionModR` modNew)
transformAct (ActFwd pOld modOld) (ActFwd pNew modNew) = ActFwd pNew (modOld `unionModR` modNew)
-- transformAct a b = error "Don't know how to sequences actions " ++ (show a) ++ " " ++ (show b)

transformPred (And p1 p2) act = And (transformPred p1 act) (transformPred p2 act)
transformPred (Or p1 p2) act = Or (transformPred p1 act) (transformPred p2 act)
transformPred (Not p) act = Not (transformPred p act)
transformPred (DlSrc val) (ActFwd p Modification{..}) = (deletePred val modifyDlSrc DlSrc)
transformPred (DlDst val) (ActFwd p Modification{..}) = (deletePred val modifyDlDst DlDst)
transformPred (DlTyp val) (ActFwd p Modification{..}) = DlTyp val
transformPred (DlVlan val) (ActFwd p Modification{..}) = (deletePred val modifyDlVlan DlVlan)
transformPred (DlVlanPcp val) (ActFwd p Modification{..}) = (deletePred val modifyDlVlanPcp DlVlanPcp)
{- Need to handle IP prefix matching over set ip addresses. Avoiding for now -}
-- transformPred (NwSrc val) (ActFwd p Modification{..}) = (deletePred val modifyNwSrc NwSrc)
-- transformPred (NwDst val) (ActFwd p Modification{..}) = (deletePred val modifyNwDst NwDst)
transformPred (NwProto val) (ActFwd p Modification{..}) = NwProto val
transformPred (NwTos val) (ActFwd p Modification{..}) = (deletePred val modifyNwTos NwTos)
transformPred (TpSrcPort val) (ActFwd p Modification{..}) = (deletePred val modifyTpSrc TpSrcPort)
transformPred (TpDstPort val) (ActFwd p Modification{..}) = (deletePred val modifyTpDst TpDstPort)
transformPred (IngressPort val) (ActFwd (Physical p) Modification{..}) = (deletePred val (Just p) IngressPort)
transformPred (IngressPort val) (ActFwd InPort Modification{..}) = IngressPort val
transformPred (Switch val) (ActFwd p Modification{..}) = Switch val
transformPred Any act = Any
transformPred None act = None

deletePred a (Just b) field = if (a == b) then Any else None
deletePred a Nothing field = field a

-- getModVal Modification{..} DlSrc = modifyDlSrc
-- getModVal Modification{..} DlDst = modifyDlDst
-- getModVal Modification{..} DlVlan = modifyDlVlan
-- getModVal Modification{..} DlVlanPcp = modifyDlVlanPcp
-- getModVal Modification{..} NwSrc = modifyNwSrc
-- getModVal Modification{..} NwDst = modifyNwDst
-- getModVal Modification{..} NwTos = modifyNwTos
-- getModVal Modification{..} TpSrcPort = modifyTpSrc
-- getModVal Modification{..} TpDstPort = modifyTpDst
-- getModVal _ _ = Nothing

dsAction :: Action -> DS Act
dsAction (Forward pt mods) =
  return (ActFwd pt mods)
dsAction (CountPackets _ interval cb) = do
  x <- newCallback (CallbackPktCounter interval cb)
  return (ActQueryPktCounter x interval)
dsAction (CountBytes _ interval cb) = do
  x <- newCallback (CallbackByteCounter interval cb)
  return (ActQueryByteCounter x interval)
dsAction (GetPacket _ cb) = do
  x <- newCallback (CallbackGetPkt cb)
  return (ActGetPkt x)
dsAction (MonitorSwitch cb) = do
  x <- newCallback (CallbackMonSwitch cb)
  return (ActMonSwitch x)

desugarPolicy :: Policy
              -> (Callbacks,
                  [(Id, Chan (Loc, ByteString))],
                  Pol)
desugarPolicy pol = (cbs, gens, pol')
  where (pol', (_, cbs, gens)) = runState (dsPolicy pol) (0, M.empty, [])

evalProgram :: Program
            -> (Map Switch [Queue], Policy)
evalProgram prog = (M.fromListWith (++) queues, pol)
  where (qMap, pol) = eval M.empty prog
        queues = concatMap (\((sw, _), (_, qs)) -> zip [sw ..] (map (:[]) qs))
                           -- I assume nobody is reading this code.
                           (M.toList qMap)
        eval qMap prog = case prog of
          Policy pol -> (qMap, pol)
          ProgramUnion prog1 prog2 ->
            let (qMap', pol1) = eval qMap prog1
                (qMap'', pol2) = eval qMap' prog2
              in (qMap'', pol1 `mappend` pol2)
          WithQueue sw pt rate fn -> case M.lookup (sw,pt) qMap of
            Nothing ->
              let q = Queue sw pt 1 rate
                in eval (M.insert (sw,pt) (1, [q]) qMap) (fn q)
            Just (n, qs) ->
              let q = Queue sw pt (n+1) rate
                in eval (M.insert (sw,pt) (n+1, q : qs) qMap) (fn q)

matchHdr :: Eq a => a -> Maybe a -> Bool
matchHdr _ Nothing = True
matchHdr v (Just v') = v == v'

matchNwHdr :: Eq a => Maybe a -> Maybe a -> Bool
matchNwHdr _ Nothing = True
matchNwHdr Nothing (Just _) = False
matchNwHdr (Just v) (Just v') = v == v'

matchPkt :: Match -> Port -> Packet -> Bool
matchPkt (Match {..}) pktInPort (Packet{..}) =
  pktInPort `matchHdr` inPort &&
  pktDlSrc `matchHdr` srcEthAddress &&
  pktDlDst `matchHdr` dstEthAddress &&
  pktDlVlan' `matchHdr` vLANID &&
  pktDlVlanPcp `matchHdr` vLANPriority &&
  pktDlTyp `matchHdr` ethFrameType &&
  pktNwProto `matchHdr` matchIPProtocol &&
  pktNwTos `matchHdr` ipTypeOfService &&
  pktNwSrc `matchIP` srcIPAddress &&
  pktNwDst `matchIP` dstIPAddress &&
  pktTpSrc `matchNwHdr` srcTransportPort &&
  pktTpDst `matchNwHdr` dstTransportPort
    where pktDlVlan' = case pktDlVlan of
            Just v -> v
            Nothing -> 0xffff
          matchIP Nothing (IPAddressPrefix _ 0) = True
          matchIP Nothing (IPAddressPrefix _ _) = False
          matchIP (Just ip) prefix = elemOfPrefix ip prefix


text:
<!doctype html>
<!--
@license
Copyright (c) 2015 The Polymer Project Authors. All rights reserved.
This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt
The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt
The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt
Code distributed by Google as part of the polymer project is also
subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt
-->
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, minimum-scale=1.0, initial-scale=1.0, user-scalable=yes">

    <script src="../../../../webcomponentsjs/webcomponents-lite.js"></script>
    <script src="../../../../web-component-tester/browser.js"></script>

    <!-- Step 1: import the element to test -->
    <link rel="import" href="../../../app/polymer-ui/elements/settings-view.html">
  </head>
  <body>

    <!-- You can use the document as a place to set up your fixtures. -->
    <test-fixture id="my-fixture">
      <template is="dom-template">
        <settings-view></settings-view>
      </template>
    </test-fixture>

    <script>
      // This is ugly, but it's unclear how to inject functionality the way we
      // want without different suites
      suite('<settings-view> 1', function() {
        let path = 'some path';
        let dirId = 'abc123';
        let port = 9876;
        let instanceName = 'my awesome cache';
        let domainName = 'mylaptop.local';

        // stamp them somehow.
        let setPathSpy = sinon.spy();
        let setDirSpy = sinon.spy();
        let setPortSpy = sinon.spy();
        let setNameSpy = sinon.spy();
        let setHostNameSpy = sinon.spy();
        let setCoalescenceDigestSpy = sinon.spy();
        let setCoalescenceBloomSpy = sinon.spy();

        let settingsModuleSpy = {
          setAbsPath: setPathSpy,
          setInstanceName: setNameSpy,
          setBaseDirId: setDirSpy,
          setServerPort: setPortSpy,
          setHostName: setHostNameSpy,
          setCoalescenceDigest: setCoalescenceDigestSpy,
          setCoalescenceBloom: setCoalescenceBloomSpy,
          getAbsPath: sinon.stub(),
          getInstanceName: sinon.stub(),
          getBaseDirId: sinon.stub(),
          getServerPort: sinon.stub(),
          getHostName: sinon.stub(),
        };

        let myEl;
        // In the app require() is provided by the browser-ified script. In the
        // tests we are stubbing out its functionality using the
        // getSettingsModule().
        window.require = function() {
          return settingsModuleSpy;
        };

        test('save settings calls save functions with values', function() {
          myEl = fixture('my-fixture');
          myEl.getSettingsModule = sinon.stub().returns(settingsModuleSpy)

          var saveEl = myEl.$.savebutton;

          myEl.$$('#abs-path-input').value = path;
          myEl.$$('#instance-name-input').value = instanceName;
          myEl.$$('#server-port-input').value = port;
          myEl.$$('#domain-name-input').value = domainName;
          myEl.$$('#coalescence-strategy').selected = 'digest';

          saveEl.click();

          assert.equal(setPathSpy.calledOnce, true);
          assert.equal(setPortSpy.calledOnce, true);
          assert.equal(setNameSpy.calledOnce, true);
          assert.equal(setHostNameSpy.calledOnce, true);
          assert.equal(setPathSpy.args[0][0], path);
          assert.equal(setPortSpy.args[0][0], port);
          assert.equal(setNameSpy.args[0][0], instanceName);
          assert.equal(setHostNameSpy.args[0][0], domainName);
          assert.equal(setCoalescenceDigestSpy.callCount, 1);
          assert.equal(setCoalescenceBloomSpy.callCount, 0);

        });
      });

      suite('<settings-view> 2', function() {
        let path = 'a nice path';
        let entryPath = 'the entry path';
        let dirId = '987zyx';
        let port = 1234;
        let instanceName = 'Matt\'s cache';
        let domainName = 'hello.local';
        let coalescenceStrategy = 'bloom';

        let settingsModuleSpy = {
          getAbsPath: sinon.stub().returns(path),
          getInstanceName: sinon.stub().returns(instanceName),
          getBaseDirPath: sinon.stub().returns(entryPath),
          getServerPort: sinon.stub().returns(port),
          getHostName: sinon.stub().returns(domainName),
          getCoalescenceStrategy: sinon.stub().returns(coalescenceStrategy),
        };

        window.require = function() {
          console.log('require() no-op in setup');
          return settingsModuleSpy;
        };

        test('starts initialized with values from settings', function() {
          myEl = fixture('my-fixture');
          myEl.getSettingsModule = sinon.stub.returns(settingsModuleSpy);

          assert.equal(
            myEl.$$('#base-dir-label').textContent,
            entryPath
          );
          assert.equal(
            myEl.$$('#instance-name-input').value,
            instanceName
          );
          assert.equal(
            myEl.$$('#server-port-input').value,
            port
          );
          assert.equal(
            myEl.$$('#abs-path-input').value,
            path
          );
          assert.equal(
            myEl.$$('#domain-name-input').value,
            domainName
          );
          assert.equal(
            myEl.$$('#coalescence-strategy').selected,
            coalescenceStrategy
          );
        });

      });
    </script>

  </body>
</html>


text:
package synergynet3.apps.numbernet.network;

import java.util.Collection;
import java.util.Map;
import java.util.Map.Entry;

import synergynet3.apps.numbernet.controller.numbernettable.CalculatorCollectionManager;
import synergynet3.apps.numbernet.ui.calculator.Calculator;
import synergynet3.cluster.sharedmemory.DistributedPropertyChangedAction;
import synergynet3.web.apps.numbernet.comms.table.NumberNetStudentTableClusteredData;
import synergynet3.web.apps.numbernet.shared.CalculatorKey;

import com.hazelcast.core.Member;

/**
 * The Class CalculatorKeySynchronizer.
 */
public class CalculatorKeySynchronizer
{

	/** The calculator collection manager. */
	private CalculatorCollectionManager calculatorCollectionManager;

	/** The student table data cluster. */
	private NumberNetStudentTableClusteredData studentTableDataCluster;

	/**
	 * Instantiates a new calculator key synchronizer.
	 *
	 * @param calculatorCollectionManager
	 *            the calculator collection manager
	 * @param studentTableDataCluster
	 *            the student table data cluster
	 */
	public CalculatorKeySynchronizer(CalculatorCollectionManager calculatorCollectionManager, NumberNetStudentTableClusteredData studentTableDataCluster)
	{
		this.calculatorCollectionManager = calculatorCollectionManager;
		this.studentTableDataCluster = studentTableDataCluster;
	}

	/**
	 * Start.
	 */
	public void start()
	{
		this.studentTableDataCluster.getCalculatorKeyStateMap().registerChangeListener(new DistributedPropertyChangedAction<Map<CalculatorKey, Boolean>>()
		{
			@Override
			public void distributedPropertyDidChange(Member m, Map<CalculatorKey, Boolean> oldValue, Map<CalculatorKey, Boolean> newValue)
			{
				updateAllCalculatorsSetKeyStateWithValue(newValue);
			}
		});
	}

	/**
	 * Update calculator set key state with value.
	 *
	 * @param calc
	 *            the calc
	 * @param itemKey
	 *            the item key
	 * @param state
	 *            the state
	 */
	private void updateCalculatorSetKeyStateWithValue(Calculator calc, CalculatorKey itemKey, Boolean state)
	{
		calc.setKeyVisible(itemKey.getStringRepresentation(), state);
	}

	/**
	 * Update all calculators set key state with value.
	 *
	 * @param keyMap
	 *            the key map
	 */
	protected void updateAllCalculatorsSetKeyStateWithValue(Map<CalculatorKey, Boolean> keyMap)
	{
		Collection<String> users = calculatorCollectionManager.getUsersWhoHaveCalculators();
		for (String user : users)
		{
			Calculator calc = calculatorCollectionManager.getCalculatorForUser(user);
			for (Entry<CalculatorKey, Boolean> entry : keyMap.entrySet())
			{
				updateCalculatorSetKeyStateWithValue(calc, entry.getKey(), entry.getValue());
			}
		}

	}

}


text:
from rest_framework import serializers
from django.contrib.auth.models import User
from donor.models import Profile, Request, Message

class RequestSerializer(serializers.HyperlinkedModelSerializer):

    class Meta:
        model = Request
        fields = ('id', 'creator', 'category', 'grouping', 'name', 'description', 'start', 'end', 'email', 'phone')

class UserSerializer(serializers.HyperlinkedModelSerializer):
    request_set = RequestSerializer(many=True)
    class Meta:
        model = User
        fields = ('id', 'email', 'username', 'date_joined', 'request_set')

class ProfileSerializer(serializers.HyperlinkedModelSerializer):

    class Meta:
        model = Profile
        fields = ('id', 'user', 'category', 'informationNumber', 'address', 'phone')

class MessageSerializer(serializers.HyperlinkedModelSerializer):

    class Meta:
        model = Message
        fields = ('id', 'sender', 'recipient', 'text', 'created')


text:
package org.apache.hyracks.algebricks.tests.pushruntime;

import java.io.IOException;

import org.apache.hyracks.algebricks.runtime.base.IUnnestingEvaluator;
import org.apache.hyracks.algebricks.runtime.base.IUnnestingEvaluatorFactory;
import org.apache.hyracks.api.context.IHyracksTaskContext;
import org.apache.hyracks.api.exceptions.HyracksDataException;
import org.apache.hyracks.data.std.api.IPointable;
import org.apache.hyracks.data.std.util.ArrayBackedValueStorage;
import org.apache.hyracks.dataflow.common.data.accessors.IFrameTupleReference;

public class IntArrayUnnester implements IUnnestingEvaluatorFactory {

    private int[] x;

    public IntArrayUnnester(int[] x) {
        this.x = x;
    }

    private static final long serialVersionUID = 1L;

    @Override
    public IUnnestingEvaluator createUnnestingEvaluator(IHyracksTaskContext ctx) throws HyracksDataException {
        final ArrayBackedValueStorage abvs = new ArrayBackedValueStorage();
        return new IUnnestingEvaluator() {

            private int pos;

            @Override
            public void init(IFrameTupleReference tuple) throws HyracksDataException {
                pos = 0;
            }

            @Override
            public boolean step(IPointable result) throws HyracksDataException {
                try {
                    if (pos < x.length) {
                        // Writes one byte to distinguish between null
                        // values and end of sequence.
                        abvs.reset();
                        abvs.getDataOutput().writeInt(x[pos]);
                        result.set(abvs);
                        ++pos;
                        return true;
                    } else {
                        return false;
                    }

                } catch (IOException e) {
                    throw new HyracksDataException(e);
                }
            }

        };

    }

}