text:
GraphAnnotator = function(imageURL, options) {
  options = options || {};
  this.graph = options.graph || {nodes: [{}, {}], edges: [{index: [0, 1]}]};
  this.lineWidth = options.lineWidth || 3;
  this.nodeColor = options.nodeColor || [0, 255, 255];
  this.edgeColor = options.edgeColor || [0, 255, 255];
  this.nodeDiameter = options.nodeDiameter || 3;
  this.hitDistance = options.hitDistance || 10;
  this._initializeContainer(options);
  this._initializeLayers(imageURL, function() {
    if (options.onchange)
      this._initializeEvents(options);
    this._renderGraph();
    if (options.onload)
      options.onload.call(this);
  });
};

// Set node attributes.
//
// The first argument is an index of the node. When omitted, attributes are
// set to all nodes.
//
// Example
//
//     annotator.setNodeAttributes({color: [255, 255, 0]});
//     annotator.setNodeAttributes(2, {color: [255, 255, 0]});
//
// There are three attributes.
//
// * `color` - RGB values in a 3-element integer array.
// * `lineWidth` - Width of the line.
// * `diameter` - Diameter of the node.
//
GraphAnnotator.prototype.setNodeAttributes = function(index, attributes) {
  var start = 0,
      end = this.graph.nodes.length;
  if (attributes === undefined)
    attributes = index;
  else if (index !== null) {
    start = index;
    end = index + 1;
  }
  for (var i = start; i < end; ++i)
    for (var key in attributes)
      this.graph.nodes[i][key] = attributes[key];
  this._renderGraph();
  return this;
};

// Set edge attributes.
//
// The first argument is an index of the edge. When omitted, attributes are
// set to all edges.
//
// Example
//
//     annotator.setEdgeAttributes({color: [255, 255, 0]});
//     annotator.setEdgeAttributes(2, {color: [255, 255, 0]});
//
// There are two attributes.
//
// * `color` - RGB values in a 3-element integer array.
// * `lineWidth` - Width of the line.
//
GraphAnnotator.prototype.setEdgeAttributes = function(index, attributes) {
  var start = 0,
      end = this.graph.nodes.length;
  if (attributes === undefined)
    attributes = index;
  else {
    start = index;
    end = index + 1;
  }
  for (var i = start; i < end; ++i)
    for (var key in attributes)
      this.edges[i][key] = attributes[key];
  this._renderGraph();
  return this;
};

// Get the next node to annotate.
//
// Return an index of next node to annotate. When finished, return null.
//
GraphAnnotator.prototype.getNextNode = function() {
  return this._findNode(null);
};

// Get the current graph.
//
// After annotation is completed, each node gets position field filled.
// Use getNextNode() to check whether if there is a pending node to
// annotate.
//
GraphAnnotator.prototype.getGraph = function() {
  return this.graph;
};

// Private methods.

// Initialize a container.
GraphAnnotator.prototype._initializeContainer = function(options) {
  if (options.container)
    this.container = options.container;
  else {
    this.container = document.createElement('div');
    document.body.appendChild(this.container);
  }
  this.container.style.display = 'inline-block';
  this.container.style.position = 'relative';
  this.container.innerHTML = '';
};

// Create layer elements.
GraphAnnotator.prototype._initializeLayers = function(imageURL, callback) {
  var _this = this;
  this.image = new Image();
  this.image.src = imageURL;
  this.container.appendChild(this.image);
  this.image.onload = function(event) {
    _this.canvas = document.createElement('canvas');
    _this.canvas.width = event.target.width;
    _this.canvas.height = event.target.height;
    _this.canvas.style.position = 'absolute';
    _this.canvas.style.left = '0px';
    _this.canvas.style.top = '0px';
    _this.canvas.style.cursor = 'pointer';
    _this.container.appendChild(_this.canvas);
    _this.canvas.oncontextmenu = function() { return false; };
    callback.call(_this);
  };
};

// Set up events.
GraphAnnotator.prototype._initializeEvents = function(options) {
  var _this = this,
      mousestatus = false,
      currentNode = null;
  this.canvas.addEventListener('mousedown', function(event) {
    if (mousestatus === false) {
      mousestatus = true;
      currentNode = _this._findNode(_this._getPosition(event));
      _this._updateNode(event, currentNode);
      if (options.onselect && currentNode !== null)
        options.onselect.call(_this, currentNode);
      document.onselectstart = function() { return false; };
    }
  });
  this.canvas.addEventListener('mousemove', function(event) {
    if (mousestatus === true)
      _this._updateNode(event, currentNode);
  });
  window.addEventListener('mouseup', function(event) {
    if (mousestatus === true) {
      _this._updateNode(event, currentNode);
      mousestatus = false;
      document.onselectstart = function() { return true; };
      options.onchange.call(_this, currentNode);
      currentNode = null;
    }
  });
};

// Find and update the current node.
GraphAnnotator.prototype._findNode = function(position) {
  var candidate = null,
      i;
  if (position) {
    // Find the nearest node.
    var minDistance = Infinity;
    for (i = 0; i < this.graph.nodes.length; ++i) {
      if (this.graph.nodes[i].position !== undefined) {
        var nodePosition = this.graph.nodes[i].position,
            distance = Math.sqrt(
            Math.pow(nodePosition[0] - position[0], 2) +
            Math.pow(nodePosition[1] - position[1], 2));
        if (distance <= this.hitDistance && distance <= minDistance) {
          minDistance = distance;
          candidate = i;
        }
      }
    }
  }
  if (candidate === null) {
    // Find the unfinished node.
    for (i = 0; i < this.graph.nodes.length; ++i) {
      if (this.graph.nodes[i].position === undefined) {
        candidate = i;
        break;
      }
    }
  }
  return candidate;
};

// Render a graph.
GraphAnnotator.prototype._renderGraph = function() {
  // Get a format RGB string.
  function formatRGB(rgb) {
    if (typeof rgb === 'object' && rgb.length === 3)
      return 'rgb(' + rgb[0] + ',' + rgb[1] + ',' + rgb[2] + ')';
    else
      return rgb;
  }
  var context,
      i;
  this.canvas.width = this.image.width;
  context = this.canvas.getContext('2d');
  for (i = 0; i < this.graph.edges.length; ++i) {
    var edge = this.graph.edges[i],
        node1 = this.graph.nodes[edge.index[0]],
        node2 = this.graph.nodes[edge.index[1]];
    if (node1.position === undefined || node2.position === undefined)
      continue;
    context.lineWidth = edge.lineWidth || this.lineWidth;
    context.strokeStyle = formatRGB(edge.color || this.edgeColor);
    context.beginPath();
    context.moveTo(node1.position[0], node1.position[1]);
    context.lineTo(node2.position[0], node2.position[1]);
    context.closePath();
    context.stroke();
  }
  for (i = 0; i < this.graph.nodes.length; ++i) {
    var node = this.graph.nodes[i];
    if (node.position) {
      context.lineWidth = node.lineWidth || this.lineWidth;
      context.strokeStyle = formatRGB(node.color || this.nodeColor);
      context.beginPath();
      context.arc(node.position[0],
                  node.position[1],
                  node.diameter || this.nodeDiameter,
                  0,
                  Math.PI*2,
                  false);
      context.closePath();
      context.stroke();
    }
  }
};

// Get a mouse position.
GraphAnnotator.prototype._getPosition = function(event) {
  var x = event.pageX - this.container.offsetLeft + this.container.scrollLeft,
      y = event.pageY - this.container.offsetTop + this.container.scrollTop;
  x = Math.max(Math.min(x, this.canvas.width - 1), 0);
  y = Math.max(Math.min(y, this.canvas.height - 1), 0);
  return [x, y];
};

// Update a node.
GraphAnnotator.prototype._updateNode = function(event, currentNode) {
  if (currentNode !== null) {
    this.graph.nodes[currentNode].position = this._getPosition(event);
    this._renderGraph();
  }
};


text:
#include <linux/init.h>
#include <linux/interrupt.h>
#include <linux/delay.h>
#include <linux/platform_device.h>
#include <linux/err.h>
#include <linux/io.h>
#include <linux/spi/spi.h>
#include <linux/spi/orion_spi.h>
#include <linux/module.h>
#include <asm/unaligned.h>

#define DRIVER_NAME			"orion_spi"

#define ORION_NUM_CHIPSELECTS		1 /* only one slave is supported*/
#define ORION_SPI_WAIT_RDY_MAX_LOOP	2000 /* in usec */

#define ORION_SPI_IF_CTRL_REG		0x00
#define ORION_SPI_IF_CONFIG_REG		0x04
#define ORION_SPI_DATA_OUT_REG		0x08
#define ORION_SPI_DATA_IN_REG		0x0c
#define ORION_SPI_INT_CAUSE_REG		0x10

#define ORION_SPI_IF_8_16_BIT_MODE	(1 << 5)
#define ORION_SPI_CLK_PRESCALE_MASK	0x1F

struct orion_spi {
	struct work_struct	work;

	/* Lock access to transfer list.	*/
	spinlock_t		lock;

	struct list_head	msg_queue;
	struct spi_master	*master;
	void __iomem		*base;
	unsigned int		max_speed;
	unsigned int		min_speed;
	struct orion_spi_info	*spi_info;
};

static struct workqueue_struct *orion_spi_wq;

static inline void __iomem *spi_reg(struct orion_spi *orion_spi, u32 reg)
{
	return orion_spi->base + reg;
}

static inline void
orion_spi_setbits(struct orion_spi *orion_spi, u32 reg, u32 mask)
{
	void __iomem *reg_addr = spi_reg(orion_spi, reg);
	u32 val;

	val = readl(reg_addr);
	val |= mask;
	writel(val, reg_addr);
}

static inline void
orion_spi_clrbits(struct orion_spi *orion_spi, u32 reg, u32 mask)
{
	void __iomem *reg_addr = spi_reg(orion_spi, reg);
	u32 val;

	val = readl(reg_addr);
	val &= ~mask;
	writel(val, reg_addr);
}

static int orion_spi_set_transfer_size(struct orion_spi *orion_spi, int size)
{
	if (size == 16) {
		orion_spi_setbits(orion_spi, ORION_SPI_IF_CONFIG_REG,
				  ORION_SPI_IF_8_16_BIT_MODE);
	} else if (size == 8) {
		orion_spi_clrbits(orion_spi, ORION_SPI_IF_CONFIG_REG,
				  ORION_SPI_IF_8_16_BIT_MODE);
	} else {
		pr_debug("Bad bits per word value %d (only 8 or 16 are "
			 "allowed).\n", size);
		return -EINVAL;
	}

	return 0;
}

static int orion_spi_baudrate_set(struct spi_device *spi, unsigned int speed)
{
	u32 tclk_hz;
	u32 rate;
	u32 prescale;
	u32 reg;
	struct orion_spi *orion_spi;

	orion_spi = spi_master_get_devdata(spi->master);

	tclk_hz = orion_spi->spi_info->tclk;

	/*
	 * the supported rates are: 4,6,8...30
	 * round up as we look for equal or less speed
	 */
	rate = DIV_ROUND_UP(tclk_hz, speed);
	rate = roundup(rate, 2);

	/* check if requested speed is too small */
	if (rate > 30)
		return -EINVAL;

	if (rate < 4)
		rate = 4;

	/* Convert the rate to SPI clock divisor value.	*/
	prescale = 0x10 + rate/2;

	reg = readl(spi_reg(orion_spi, ORION_SPI_IF_CONFIG_REG));
	reg = ((reg & ~ORION_SPI_CLK_PRESCALE_MASK) | prescale);
	writel(reg, spi_reg(orion_spi, ORION_SPI_IF_CONFIG_REG));

	return 0;
}

/*
 * called only when no transfer is active on the bus
 */
static int
orion_spi_setup_transfer(struct spi_device *spi, struct spi_transfer *t)
{
	struct orion_spi *orion_spi;
	unsigned int speed = spi->max_speed_hz;
	unsigned int bits_per_word = spi->bits_per_word;
	int	rc;

	orion_spi = spi_master_get_devdata(spi->master);

	if ((t != NULL) && t->speed_hz)
		speed = t->speed_hz;

	if ((t != NULL) && t->bits_per_word)
		bits_per_word = t->bits_per_word;

	rc = orion_spi_baudrate_set(spi, speed);
	if (rc)
		return rc;

	return orion_spi_set_transfer_size(orion_spi, bits_per_word);
}

static void orion_spi_set_cs(struct orion_spi *orion_spi, int enable)
{
	if (enable)
		orion_spi_setbits(orion_spi, ORION_SPI_IF_CTRL_REG, 0x1);
	else
		orion_spi_clrbits(orion_spi, ORION_SPI_IF_CTRL_REG, 0x1);
}

static inline int orion_spi_wait_till_ready(struct orion_spi *orion_spi)
{
	int i;

	for (i = 0; i < ORION_SPI_WAIT_RDY_MAX_LOOP; i++) {
		if (readl(spi_reg(orion_spi, ORION_SPI_INT_CAUSE_REG)))
			return 1;
		else
			udelay(1);
	}

	return -1;
}

static inline int
orion_spi_write_read_8bit(struct spi_device *spi,
			  const u8 **tx_buf, u8 **rx_buf)
{
	void __iomem *tx_reg, *rx_reg, *int_reg;
	struct orion_spi *orion_spi;

	orion_spi = spi_master_get_devdata(spi->master);
	tx_reg = spi_reg(orion_spi, ORION_SPI_DATA_OUT_REG);
	rx_reg = spi_reg(orion_spi, ORION_SPI_DATA_IN_REG);
	int_reg = spi_reg(orion_spi, ORION_SPI_INT_CAUSE_REG);

	/* clear the interrupt cause register */
	writel(0x0, int_reg);

	if (tx_buf && *tx_buf)
		writel(*(*tx_buf)++, tx_reg);
	else
		writel(0, tx_reg);

	if (orion_spi_wait_till_ready(orion_spi) < 0) {
		dev_err(&spi->dev, "TXS timed out\n");
		return -1;
	}

	if (rx_buf && *rx_buf)
		*(*rx_buf)++ = readl(rx_reg);

	return 1;
}

static inline int
orion_spi_write_read_16bit(struct spi_device *spi,
			   const u16 **tx_buf, u16 **rx_buf)
{
	void __iomem *tx_reg, *rx_reg, *int_reg;
	struct orion_spi *orion_spi;

	orion_spi = spi_master_get_devdata(spi->master);
	tx_reg = spi_reg(orion_spi, ORION_SPI_DATA_OUT_REG);
	rx_reg = spi_reg(orion_spi, ORION_SPI_DATA_IN_REG);
	int_reg = spi_reg(orion_spi, ORION_SPI_INT_CAUSE_REG);

	/* clear the interrupt cause register */
	writel(0x0, int_reg);

	if (tx_buf && *tx_buf)
		writel(__cpu_to_le16(get_unaligned((*tx_buf)++)), tx_reg);
	else
		writel(0, tx_reg);

	if (orion_spi_wait_till_ready(orion_spi) < 0) {
		dev_err(&spi->dev, "TXS timed out\n");
		return -1;
	}

	if (rx_buf && *rx_buf)
		put_unaligned(__le16_to_cpu(readl(rx_reg)), (*rx_buf)++);

	return 1;
}

static unsigned int
orion_spi_write_read(struct spi_device *spi, struct spi_transfer *xfer)
{
	struct orion_spi *orion_spi;
	unsigned int count;
	int word_len;

	orion_spi = spi_master_get_devdata(spi->master);
	word_len = spi->bits_per_word;
	count = xfer->len;

	if (word_len == 8) {
		const u8 *tx = xfer->tx_buf;
		u8 *rx = xfer->rx_buf;

		do {
			if (orion_spi_write_read_8bit(spi, &tx, &rx) < 0)
				goto out;
			count--;
		} while (count);
	} else if (word_len == 16) {
		const u16 *tx = xfer->tx_buf;
		u16 *rx = xfer->rx_buf;

		do {
			if (orion_spi_write_read_16bit(spi, &tx, &rx) < 0)
				goto out;
			count -= 2;
		} while (count);
	}

out:
	return xfer->len - count;
}

static void orion_spi_work(struct work_struct *work)
{
	struct orion_spi *orion_spi =
		container_of(work, struct orion_spi, work);

	spin_lock_irq(&orion_spi->lock);
	while (!list_empty(&orion_spi->msg_queue)) {
		struct spi_message *m;
		struct spi_device *spi;
		struct spi_transfer *t = NULL;
		int par_override = 0;
		int status = 0;
		int cs_active = 0;

		m = container_of(orion_spi->msg_queue.next, struct spi_message,
				 queue);

		list_del_init(&m->queue);
		spin_unlock_irq(&orion_spi->lock);

		spi = m->spi;

		/* Load defaults */
		status = orion_spi_setup_transfer(spi, NULL);

		if (status < 0)
			goto msg_done;

		list_for_each_entry(t, &m->transfers, transfer_list) {
			if (par_override || t->speed_hz || t->bits_per_word) {
				par_override = 1;
				status = orion_spi_setup_transfer(spi, t);
				if (status < 0)
					break;
				if (!t->speed_hz && !t->bits_per_word)
					par_override = 0;
			}

			if (!cs_active) {
				orion_spi_set_cs(orion_spi, 1);
				cs_active = 1;
			}

			if (t->len)
				m->actual_length +=
					orion_spi_write_read(spi, t);

			if (t->delay_usecs)
				udelay(t->delay_usecs);

			if (t->cs_change) {
				orion_spi_set_cs(orion_spi, 0);
				cs_active = 0;
			}
		}

msg_done:
		if (cs_active)
			orion_spi_set_cs(orion_spi, 0);

		m->status = status;
		m->complete(m->context);

		spin_lock_irq(&orion_spi->lock);
	}

	spin_unlock_irq(&orion_spi->lock);
}

static int __init orion_spi_reset(struct orion_spi *orion_spi)
{
	/* Verify that the CS is deasserted */
	orion_spi_set_cs(orion_spi, 0);

	return 0;
}

static int orion_spi_setup(struct spi_device *spi)
{
	struct orion_spi *orion_spi;

	orion_spi = spi_master_get_devdata(spi->master);

	/* Fix ac timing if required.   */
	if (orion_spi->spi_info->enable_clock_fix)
		orion_spi_setbits(orion_spi, ORION_SPI_IF_CONFIG_REG,
				  (1 << 14));

	if ((spi->max_speed_hz == 0)
			|| (spi->max_speed_hz > orion_spi->max_speed))
		spi->max_speed_hz = orion_spi->max_speed;

	if (spi->max_speed_hz < orion_spi->min_speed) {
		dev_err(&spi->dev, "setup: requested speed too low %d Hz\n",
			spi->max_speed_hz);
		return -EINVAL;
	}

	/*
	 * baudrate & width will be set orion_spi_setup_transfer
	 */
	return 0;
}

static int orion_spi_transfer(struct spi_device *spi, struct spi_message *m)
{
	struct orion_spi *orion_spi;
	struct spi_transfer *t = NULL;
	unsigned long flags;

	m->actual_length = 0;
	m->status = 0;

	/* reject invalid messages and transfers */
	if (list_empty(&m->transfers) || !m->complete)
		return -EINVAL;

	orion_spi = spi_master_get_devdata(spi->master);

	list_for_each_entry(t, &m->transfers, transfer_list) {
		unsigned int bits_per_word = spi->bits_per_word;

		if (t->tx_buf == NULL && t->rx_buf == NULL && t->len) {
			dev_err(&spi->dev,
				"message rejected : "
				"invalid transfer data buffers\n");
			goto msg_rejected;
		}

		if (t->bits_per_word)
			bits_per_word = t->bits_per_word;

		if ((bits_per_word != 8) && (bits_per_word != 16)) {
			dev_err(&spi->dev,
				"message rejected : "
				"invalid transfer bits_per_word (%d bits)\n",
				bits_per_word);
			goto msg_rejected;
		}
		/*make sure buffer length is even when working in 16 bit mode*/
		if ((t->bits_per_word == 16) && (t->len & 1)) {
			dev_err(&spi->dev,
				"message rejected : "
				"odd data length (%d) while in 16 bit mode\n",
				t->len);
			goto msg_rejected;
		}

		if (t->speed_hz && t->speed_hz < orion_spi->min_speed) {
			dev_err(&spi->dev,
				"message rejected : "
				"device min speed (%d Hz) exceeds "
				"required transfer speed (%d Hz)\n",
				orion_spi->min_speed, t->speed_hz);
			goto msg_rejected;
		}
	}

	spin_lock_irqsave(&orion_spi->lock, flags);
	list_add_tail(&m->queue, &orion_spi->msg_queue);
	queue_work(orion_spi_wq, &orion_spi->work);
	spin_unlock_irqrestore(&orion_spi->lock, flags);

	return 0;
msg_rejected:
	/* Message rejected and not queued */
	m->status = -EINVAL;
	if (m->complete)
		m->complete(m->context);
	return -EINVAL;
}

static int __init orion_spi_probe(struct platform_device *pdev)
{
	struct spi_master *master;
	struct orion_spi *spi;
	struct resource *r;
	struct orion_spi_info *spi_info;
	int status = 0;

	spi_info = pdev->dev.platform_data;

	master = spi_alloc_master(&pdev->dev, sizeof *spi);
	if (master == NULL) {
		dev_dbg(&pdev->dev, "master allocation failed\n");
		return -ENOMEM;
	}

	if (pdev->id != -1)
		master->bus_num = pdev->id;

	/* we support only mode 0, and no options */
	master->mode_bits = 0;

	master->setup = orion_spi_setup;
	master->transfer = orion_spi_transfer;
	master->num_chipselect = ORION_NUM_CHIPSELECTS;

	dev_set_drvdata(&pdev->dev, master);

	spi = spi_master_get_devdata(master);
	spi->master = master;
	spi->spi_info = spi_info;

	spi->max_speed = DIV_ROUND_UP(spi_info->tclk, 4);
	spi->min_speed = DIV_ROUND_UP(spi_info->tclk, 30);

	r = platform_get_resource(pdev, IORESOURCE_MEM, 0);
	if (r == NULL) {
		status = -ENODEV;
		goto out;
	}

	if (!request_mem_region(r->start, resource_size(r),
				dev_name(&pdev->dev))) {
		status = -EBUSY;
		goto out;
	}
	spi->base = ioremap(r->start, SZ_1K);

	INIT_WORK(&spi->work, orion_spi_work);

	spin_lock_init(&spi->lock);
	INIT_LIST_HEAD(&spi->msg_queue);

	if (orion_spi_reset(spi) < 0)
		goto out_rel_mem;

	status = spi_register_master(master);
	if (status < 0)
		goto out_rel_mem;

	return status;

out_rel_mem:
	release_mem_region(r->start, resource_size(r));

out:
	spi_master_put(master);
	return status;
}

static int __exit orion_spi_remove(struct platform_device *pdev)
{
	struct spi_master *master;
	struct orion_spi *spi;
	struct resource *r;

	master = dev_get_drvdata(&pdev->dev);
	spi = spi_master_get_devdata(master);

	cancel_work_sync(&spi->work);

	r = platform_get_resource(pdev, IORESOURCE_MEM, 0);
	release_mem_region(r->start, resource_size(r));

	spi_unregister_master(master);

	return 0;
}

MODULE_ALIAS("platform:" DRIVER_NAME);

static struct platform_driver orion_spi_driver = {
	.driver = {
		.name	= DRIVER_NAME,
		.owner	= THIS_MODULE,
	},
	.remove		= __exit_p(orion_spi_remove),
};

static int __init orion_spi_init(void)
{
	orion_spi_wq = create_singlethread_workqueue(
				orion_spi_driver.driver.name);
	if (orion_spi_wq == NULL)
		return -ENOMEM;

	return platform_driver_probe(&orion_spi_driver, orion_spi_probe);
}
module_init(orion_spi_init);

static void __exit orion_spi_exit(void)
{
	flush_workqueue(orion_spi_wq);
	platform_driver_unregister(&orion_spi_driver);

	destroy_workqueue(orion_spi_wq);
}
module_exit(orion_spi_exit);

MODULE_DESCRIPTION("Orion SPI driver");
MODULE_AUTHOR("Shadi Ammouri <shadi@marvell.com>");
MODULE_LICENSE("GPL");

redpajama_set_name: RedPajamaGithub


text:
var express = require("express");
var router = express.Router();

router.route("/")
  .get(function(req, res, next) {
    return res.render("chat")
  });

module.exports = router;


text:
+++
title = "Daniel Maher"
twitter = "phrawzty"
linkedin = ""
website = "https://dark.ca/"
image = "daniel-maher.jpg"
type = "speaker"
linktitle = ["daniel-maher"]
+++

Dan is a veteran of the dotcom bubble, and has been variously a system administrator, university lecturer, start-up founder, and day labourer. As a member of the Devopsdays Core team, he has had the privilege of speaking and keynoting at events around the world. Today, he is a Developer Advocate at Datadog, a role that mixes two of his great passions: measuring things, and talking about measuring things.


text:
@interface TestTambourineInstrument : AKInstrument
@end

@interface TestTambourineNote : AKNote
@property AKNoteProperty *intensity;
@property AKNoteProperty *dampingFactor;
@property AKNoteProperty *mainResonantFrequency;
- (instancetype)initWithIntensity:(int)intensity
                    dampingFactor:(float)dampingFactor
            mainResonantFrequency:(float)mainResonantFrequency;
@end

@implementation TestTambourineInstrument

- (instancetype)init
{
    self = [super init];
    if (self) {
        TestTambourineNote *note = [[TestTambourineNote alloc] init];
        AKTambourine *tambourine = [AKTambourine tambourine];
        tambourine.intensity = note.intensity;
        tambourine.dampingFactor = note.dampingFactor;
        tambourine.mainResonantFrequency = note.mainResonantFrequency;
        [self setAudioOutput:tambourine];
    }
    return self;
}

@end

@implementation TestTambourineNote

- (instancetype)init
{
    self = [super init];
    if (self) {
        _intensity = [self createPropertyWithValue:1 minimum:0 maximum:1000];
        _dampingFactor = [self createPropertyWithValue:0 minimum:0 maximum:1];
        _mainResonantFrequency = [self createPropertyWithValue:0 minimum:0 maximum:20000];
    }
    return self;
}

- (instancetype)initWithIntensity:(int)intensity
                    dampingFactor:(float)dampingFactor
            mainResonantFrequency:(float)mainResonantFrequency
{
    self = [self init];
    if (self) {
        _intensity.value = (float)intensity;
        _dampingFactor.value = dampingFactor;
        _mainResonantFrequency.value = mainResonantFrequency;
    }
    return self;
}
@end

@interface AKTambourineTests : AKTestCase
@end

@implementation AKTambourineTests

- (void)testTambourine
{
    // Set up performance
    TestTambourineInstrument *testInstrument = [[TestTambourineInstrument alloc] init];
    [AKOrchestra addInstrument:testInstrument];

    AKPhrase *phrase = [AKPhrase phrase];

    for (int i = 0; i < 20; i++) {
        TestTambourineNote *note = [[TestTambourineNote alloc] initWithIntensity:25+(i+1)*20
                                                                   dampingFactor:1.0-((float)i/20)
                                                           mainResonantFrequency:200*(float)i];
        note.duration.value = 0.5;
        [phrase addNote:note atTime:(float)i*0.5];
    }

    [testInstrument playPhrase:phrase];

    // Check output
    XCTAssertEqualObjects([self md5ForOutputWithDuration:testDuration], @"8c88f6eb00209fc63946052854d5f09c");
}

- (void)testPresetClosedTambourine
{
    AKInstrument *testInstrument = [AKInstrument instrument];
    [testInstrument setAudioOutput:[AKTambourine presetClosedTambourine]];
    [AKOrchestra addInstrument:testInstrument];
    [testInstrument play];

    XCTAssertEqualObjects([self md5ForOutputWithDuration:1.0],
                          @"82e5675e159055f279d71692569c5267");
}

- (void)testPresetOpenTambourine
{
    AKInstrument *testInstrument = [AKInstrument instrument];
    [testInstrument setAudioOutput:[AKTambourine presetOpenTambourine]];
    [AKOrchestra addInstrument:testInstrument];
    [testInstrument play];

    XCTAssertEqualObjects([self md5ForOutputWithDuration:1.0],
                          @"1fa2680fb57c3757a64f4ec8ab140201");
}

@end


text:
import OpenGL.GL as GL
import os.path as path
from .programs import *

__all__ = [
    'ShaderCompileError',
    'ShaderProgramData',
]

class ShaderCompileError(Exception):
    pass

class ShaderProgramData(object):

    def __init__(self, shader_base_dir):
        # type: (str) -> None
        self._base_dir = shader_base_dir
        self._fragshaders = {}
        self._frag_uniforms = {}
        self._vertshaders = {}
        self._vert_uniforms = {}
        self._geomshaders = {}
        self._geom_uniforms = {}
        self._shaderprograms = {}
        self._uniforms = {}

    def _extract_uniforms(self, lines):
        uniforms = []
        for line in lines:   # type: str
            s = line.lstrip(' ')
            if s.startswith('uniform'):
                uniform = s.split()[-1].rstrip(';')
                if uniform not in uniforms:
                    uniforms.append(uniform)
        return tuple(uniforms)

    def compile_fragment_shaders(self, **kwargs):
        # type: (...) -> None
        for frag_shader_name in kwargs:
            shader_file = kwargs[frag_shader_name]
            self.compile_fragment_shader(frag_shader_name, shader_file=shader_file)

    def compile_fragment_shader(self, frag_shader_name, **kwargs):
        # type: (str, ...) -> None
        if 'shader_file' in kwargs:
            fname = path.join(self._base_dir, kwargs.get('shader_file'))
            with open(fname) as fsh:
                lines = fsh.readlines()
                fragment_code = "\n".join(lines)
        elif 'shader_location' in kwargs:
            fname = kwargs['shader_location']
            with open(fname) as fsh:
                lines = fsh.readlines()
                fragment_code = "\n".join(lines)
        elif 'shader_code' in kwargs:
            fragment_code = kwargs.get('shader_code')
        else:
            raise ValueError("'shader_file' or 'shader_code' keyword argument expected.")

        self._frag_uniforms[frag_shader_name] = self._extract_uniforms(fragment_code.split('\n'))

        fragment_id = GL.glCreateShader(GL.GL_FRAGMENT_SHADER)
        GL.glShaderSource(fragment_id, fragment_code)
        GL.glCompileShader(fragment_id)

        if not GL.glGetShaderiv(fragment_id, GL.GL_COMPILE_STATUS):
            raise ShaderCompileError(GL.glGetShaderInfoLog(fragment_id))

        self._fragshaders[frag_shader_name] = fragment_id

    def compile_vertex_shaders(self, **kwargs):
        # type: (...) -> None
        for vert_shader_name in kwargs:
            shader_file = kwargs[vert_shader_name]
            self.compile_vertex_shader(vert_shader_name, shader_file=shader_file)

    def compile_vertex_shader(self, vert_shader_name, **kwargs):
        # type: (str, ...) -> None
        if 'shader_file' in kwargs:
            fname = path.join(self._base_dir, kwargs.get('shader_file'))
            with open(fname) as vsh:
                vertex_code = "\n".join(vsh.readlines())
        elif 'shader_location' in kwargs:
            fname = kwargs['shader_location']
            with open(fname) as vsh:
                lines = vsh.readlines()
                vertex_code = "\n".join(lines)
        elif 'shader_code' in kwargs:
            vertex_code = kwargs.get('shader_code')
        else:
            raise ValueError("'shader_file' or 'shader_code' keyword argument expected.")

        self._vert_uniforms[vert_shader_name] = self._extract_uniforms(vertex_code.split('\n'))

        vertex_id = GL.glCreateShader(GL.GL_VERTEX_SHADER)
        GL.glShaderSource(vertex_id, vertex_code)
        GL.glCompileShader(vertex_id)

        if not GL.glGetShaderiv(vertex_id, GL.GL_COMPILE_STATUS):
            raise ShaderCompileError(GL.glGetShaderInfoLog(vertex_id))

        self._vertshaders[vert_shader_name] = vertex_id

    def compile_geometry_shaders(self, **kwargs):
        # type: (...) -> None
        for geom_shader_name in kwargs:
            shader_file = kwargs[geom_shader_name]
            self.compile_geometry_shader(geom_shader_name, shader_file=shader_file)

    def compile_geometry_shader(self, geom_shader_name, **kwargs):
        # type: (str, ...) -> None
        if 'shader_file' in kwargs:
            fname = path.join(self._base_dir, kwargs.get('shader_file'))
            with open(fname) as gsh:
                geometry_code = "\n".join(gsh.readlines())
        elif 'shader_location' in kwargs:
            fname = kwargs['shader_location']
            with open(fname) as gsh:
                lines = gsh.readlines()
                geometry_code = "\n".join(lines)
        elif 'shader_code' in kwargs:
            geometry_code = kwargs.get('shader_code')
        else:
            raise ValueError("'shader_file' or 'shader_code' keyword argument expected.")

        self._geom_uniforms[geom_shader_name] = self._extract_uniforms(geometry_code.split('\n'))

        geometry_id = GL.glCreateShader(GL.GL_VERTEX_SHADER)
        GL.glShaderSource(geometry_id, geometry_code)
        GL.glCompileShader(geometry_id)

        if not GL.glGetShaderiv(geometry_id, GL.GL_COMPILE_STATUS):
            raise ShaderCompileError(GL.glGetShaderInfoLog(geometry_id))

        self._geomshaders[geom_shader_name] = geometry_id

    def link(self, program_name, **shaders):
        # type: (...) -> None
        vertex_id = self._vertshaders.get(shaders.get('vertex'))
        fragment_id = self._fragshaders.get(shaders.get('fragment'))
        geometry_id = self._geomshaders.get(shaders.get('geometry'))

        program = GL.glCreateProgram()

        if vertex_id is not None:
            GL.glAttachShader(program, vertex_id)
        if geometry_id is not None:
            GL.glAttachShader(program, geometry_id)
        if fragment_id is not None:
            GL.glAttachShader(program, fragment_id)

        GL.glLinkProgram(program)
        if not GL.glGetProgramiv(program, GL.GL_LINK_STATUS):
            message = GL.glGetProgramInfoLog(program).decode(errors='ignore')
            raise RuntimeError("ShaderProgramErrorMessage: '{}'".format(message))

        uniforms = ()
        if vertex_id is not None:
            GL.glDetachShader(program, vertex_id)
            uniforms += self._vert_uniforms[shaders['vertex']]
        if geometry_id is not None:
            GL.glDetachShader(program, geometry_id)
            uniforms += self._geom_uniforms[shaders['geometry']]
        if fragment_id is not None:
            GL.glDetachShader(program, fragment_id)
            uniforms += self._frag_uniforms[shaders['fragment']]

        self._shaderprograms[program_name] = program
        self._uniforms[program_name] = uniforms

    def build(self, program_name, *uniforms):
        # type: (str, ...) -> ShaderProgram
        if program_name not in self._shaderprograms:
            raise ValueError("'{}' not found.".format(program_name))
        if len(uniforms) == 0:
            uniforms = self._uniforms[program_name]
        return ShaderProgram(self._shaderprograms[program_name], *uniforms)


text:
static NSString * const kMisfitAppUrlScheme = @"shine-internal://";
static NSString * const kMisfitDeveloperPortalDomain = @"https://build.int.misfit.com";
#else
static NSString * const kMisfitAppUrlScheme = @"shine://";
static NSString * const kMisfitDeveloperPortalDomain = @"https://build.misfit.com";
#endif

static NSString * const kMisfitCloudAPIToken = @"__misfit_cloud_api_token";

static NSString * const kMisfitAppID = @"__misfit_cloud_app_id";

static NSString * const kMisfitAppSecret = @"__misfit_cloud_app_secret";

@interface MFCSession ()

@property (nonatomic, readwrite) BOOL isConnected;

@property (nonatomic, strong) MFCCompletion connectCompletion;

@end

@implementation MFCSession

+ (MFCSession *) sharedInstance
{
    static MFCSession *_sharedInstance;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _sharedInstance = [[MFCSession alloc] init];
        _sharedInstance.appId = [[NSUserDefaults standardUserDefaults] valueForKey:kMisfitAppID];
        _sharedInstance.appSecret = [[NSUserDefaults standardUserDefaults] valueForKey:kMisfitAppSecret];
        _sharedInstance.token = [[NSUserDefaults standardUserDefaults] valueForKey:kMisfitCloudAPIToken];
    });
    return _sharedInstance;
}

- (void) setToken:(NSString *) token
{
    //TODO: check parameters here.

    _token = token;

    if(token){
        _isConnected = YES;
    }else{
        _isConnected = NO;
    }

    [[NSUserDefaults standardUserDefaults] setObject:self.token forKey:kMisfitCloudAPIToken];

    [[NSUserDefaults standardUserDefaults] synchronize];

    [[MFCAPIClient sharedClient] setDefaultHeader:@"Authorization"
                                        withValue:[NSString stringWithFormat:@"Bearer %@", token]];

    [[MFCAPIClient sharedClient] setDefaultHeader:@"Content-Type"
                                        withValue:@"application/json"];
}

- (void) setAppId:(NSString *)appId
{
    _appId  = appId;
    [[NSUserDefaults standardUserDefaults] setValue:self.appId forKey:kMisfitAppID];
}

- (void) setAppSecret:(NSString *)appSecret
{
    _appSecret  = appSecret;
    [[NSUserDefaults standardUserDefaults] setValue:self.appSecret forKey:kMisfitAppSecret];
}

-(void) connectWithAppId:(NSString *) appId
               appSecret:(NSString *) appSecret
            responseType:(NSString *) responseType
              completion:(MFCCompletion) completion
{
    BOOL canOpenApp = [[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:kMisfitAppUrlScheme]];

    self.appId = appId;
    self.appSecret = appSecret;
    self.connectCompletion = completion;

    if(canOpenApp){

        //get hash of app secret. not used yet
        //NSString * appSecretMD5 = [appSecret MD5String];
        NSString * redirectURL = [NSString stringWithFormat:@"%@authorize?response_type=token&app_id=%@&secret_hash=%@",
                                  kMisfitAppUrlScheme,
                                  self.appId,
                                  self.appId];//for compatibility

        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:redirectURL]];

    }else{
        //[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"itms-apps://itunes.apple.com/app/shine/id564157241"]];
        NSString * redirectURL = [NSString stringWithFormat:@"%@/oauth/authorize?response_type=token&app_id=%@&secret_hash=%@",
                                  kMisfitDeveloperPortalDomain,
                                  appId,
                                  appId];//for compatibility

        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:redirectURL]];
    }
}

- (void) disconnectWithCompletion:(MFCCompletion) completion
{
    if(self.appId){
        [[MFCAPIClient sharedClient] sendRequestToMisfitRelativePath:[NSString stringWithFormat:@"/oauth/revoke/%@",self.appId]
                                                          httpMethod:@"POST"
                                                          parameters:@{}
                                                             success:^(id responseObject) {

                                                                 [self reset];

                                                                 completion(responseObject,nil);
                                                             } failure:^(MFCError * error) {

                                                                 [self reset];
                                                                 completion(nil,error);
                                                             }];
    }else{
        completion(nil,[MFCError businessErrorForbidden]);
    }
}

- (void) reset
{
    self.isConnected = NO;
    //self.appId = nil;
    //self.appSecret = nil;
    self.token = nil;
    //[[NSUserDefaults standardUserDefaults] removeObjectForKey:kMisfitAppID];
    //[[NSUserDefaults standardUserDefaults] removeObjectForKey:kMisfitAppSecret];
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:kMisfitCloudAPIToken];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

- (BOOL) handleOpenURL:(NSURL *) url
{
    NSDictionary * params = [url queryItems];
    //URL: mfc-misfittest://authorize#access_token=[token]
    //OR: mfc-misfittest://authorize?error=cancel

    NSString * errorCode = [params objectForKey:@"error"];

    if((errorCode) && (![errorCode isEqualToString:@""])){
        if (self.connectCompletion) {
            if([errorCode isEqualToString:@"cancel"]){
                self.connectCompletion(nil, [MFCError businessErrorUserCanceled]);
            }else{
                self.connectCompletion(nil, [MFCError businessErrorForbidden]);
            }
        }
        return NO;
    }
    NSDictionary * fragParams = [url fragmentItems];
    NSString * token = [fragParams objectForKey:@"access_token"];

    self.token = token;
    self.isConnected = YES;

    [[NSUserDefaults standardUserDefaults] setValue:self.appSecret forKey:kMisfitAppSecret];
    [[NSUserDefaults standardUserDefaults] setObject:self.token forKey:kMisfitCloudAPIToken];

    [[NSUserDefaults standardUserDefaults] synchronize];

    [[MFCAPIClient sharedClient] setDefaultHeader:@"Authorization"
                                        withValue:[NSString stringWithFormat:@"Bearer %@", token]];

    [self handleDidBecomeActive];

    if (self.connectCompletion) {
        self.connectCompletion(fragParams, nil);
    }

    [self finishLogin];

    return YES;
}

- (BOOL) canHandleOpenUrl:(NSURL *) url
{
    if(!self.appId){
        return NO;
    }
    NSString * redirectBackFromMisfitAppSchema = [[NSString stringWithFormat:@"mfc-%@", self.appId] lowercaseString];
    return [[url.scheme lowercaseString] isEqualToString:redirectBackFromMisfitAppSchema];
}

- (void)handleDidBecomeActive
{
    if (self.isConnected) {
        //maintain the http request queue?
    }
}

- (BOOL) isMisfitAppInstalled
{
    return [[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:kMisfitAppUrlScheme]];
}

- (void) finishLogin
{
    self.connectCompletion = nil;
}

- (void) getProfileWithCompletion:(MFCCompletion) completion
{
    [[MFCAPIClient sharedClient] sendRequestToMisfitRelativePath:@"user/me/profile"
                                                      httpMethod:@"GET"
                                                      parameters:@{}
                                                         success:^(id responseObject) {
                                                             completion(responseObject,nil);
                                                         } failure:^(MFCError * error) {
                                                             completion(nil,error);
                                                         }];
}
- (void) getProfileStatisticsWithCompletion:(MFCCompletion) completion
{
    [[MFCAPIClient sharedClient] sendRequestToMisfitRelativePath:@"user/me/profile/statistics"
                                                      httpMethod:@"GET"
                                                      parameters:@{}
                                                         success:^(id responseObject) {
                                                             completion(responseObject,nil);
                                                         } failure:^(MFCError * error) {
                                                             completion(nil,error);
                                                         }];
}
- (void) getSettingWithCompletion:(MFCCompletion) completion
{
    [[MFCAPIClient sharedClient] sendRequestToMisfitRelativePath:@"user/me/profile/settings"
                                                      httpMethod:@"GET"
                                                      parameters:@{}
                                                         success:^(id responseObject) {
                                                             completion(responseObject,nil);
                                                         } failure:^(MFCError * error) {
                                                             completion(nil,error);
                                                         }];
}
- (void) getDeviceWithCompletion:(MFCCompletion) completion
{
    [[MFCAPIClient sharedClient] sendRequestToMisfitRelativePath:@"user/me/device/list"
                                                      httpMethod:@"GET"
                                                      parameters:@{}
                                                         success:^(id responseObject) {
                                                             completion(responseObject,nil);
                                                         } failure:^(MFCError * error) {
                                                             completion(nil,error);
                                                         }];
}

- (void) getActivitySummaryWithCompletionByDate:(NSDate *)date range:(MFCQuerySummaryRange)range completion:(MFCCompletion) completion
{
    [[MFCAPIClient sharedClient] sendRequestToMisfitRelativePath:@"user/me/activity/summary"
                                                      httpMethod:@"GET"
                                                      parameters:@{@"date":[self getDateStr:date],
                                                                   @"period":[self getRangeStringByType:range]}
                                                         success:^(id responseObject) {
                                                             completion(responseObject,nil);
                                                         } failure:^(MFCError * error) {
                                                             completion(nil,error);
                                                         }];
}

- (void) getActivityGraphWithCompletionByDate:(NSDate *)date completion:(MFCCompletion) completion
{
    [[MFCAPIClient sharedClient] sendRequestToMisfitRelativePath:@"user/me/activity/graph"
                                                      httpMethod:@"GET"
                                                      parameters:@{@"date":[self getDateStr:date]}
                                                         success:^(id responseObject) {
                                                             completion(responseObject,nil);
                                                         } failure:^(MFCError * error) {
                                                             completion(nil,error);
                                                         }];
}

- (void) getActivityDetailWithCompletionByDate:(NSDate *)date completion:(MFCCompletion) completion
{
    [[MFCAPIClient sharedClient] sendRequestToMisfitRelativePath:@"user/me/activity"
                                                      httpMethod:@"GET"
                                                      parameters:@{@"date":[self getDateStr:date]}
                                                         success:^(id responseObject) {
                                                             completion(responseObject,nil);
                                                         } failure:^(MFCError * error) {
                                                             completion(nil,error);
                                                         }];
}
- (void) getSleepSummaryWithCompletionByDate:(NSDate *)date range:(MFCQuerySummaryRange)range completion:(MFCCompletion) completion
{
    [[MFCAPIClient sharedClient] sendRequestToMisfitRelativePath:@"user/me/sleep/summary"
                                                      httpMethod:@"GET"
                                                      parameters:@{@"date":[self getDateStr:date],
                                                                   @"period":[self getRangeStringByType:range]}
                                                         success:^(id responseObject) {
                                                             completion(responseObject,nil);
                                                         } failure:^(MFCError * error) {
                                                             completion(nil,error);
                                                         }];

}
- (void) getSleepDetailWithCompletionByDate:(NSDate *)date completion:(MFCCompletion) completion
{
    [[MFCAPIClient sharedClient] sendRequestToMisfitRelativePath:@"user/me/sleep"
                                                      httpMethod:@"GET"
                                                      parameters:@{@"date": [self getDateStr:date]}
                                                         success:^(id responseObject) {
                                                             completion(responseObject,nil);
                                                         } failure:^(MFCError * error) {
                                                             completion(nil,error);
                                                         }];
}
- (void) getWeightSummaryWithCompletionByDate:(NSDate *)date range:(MFCQuerySummaryRange)range completion:(MFCCompletion) completion
{
    [[MFCAPIClient sharedClient] sendRequestToMisfitRelativePath:@"user/me/weight/summary"
                                                      httpMethod:@"GET"
                                                      parameters:@{@"date":[self getDateStr:date],
                                                                   @"period":[self getRangeStringByType:range]}
                                                         success:^(id responseObject) {
                                                             completion(responseObject,nil);
                                                         } failure:^(MFCError * error) {
                                                             completion(nil,error);
                                                         }];

}

- (NSString*)getDateStr:(NSDate*)date
{
    NSDateFormatter* fmt = [[NSDateFormatter alloc] init];
    fmt.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en"];
    fmt.dateFormat = @"yyyy-MM-dd";
    NSString* dateString = [fmt stringFromDate:date];
    MFSLogInfo(@"%@", dateString);
    return dateString;
}
- (NSString*)getRangeStringByType:(MFCQuerySummaryRange)range
{
    switch (range) {
        case MFCQuerySummaryRangeWeek:
            return @"week";
        case MFCQuerySummaryRangeMonth:
            return @"month";
        default:
            return @"week";
    }
}

@end


text:
"""Tests for mobilenet_v2."""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import copy
import tensorflow as tf
from nets.mobilenet import conv_blocks as ops
from nets.mobilenet import mobilenet
from nets.mobilenet import mobilenet_v2

slim = tf.contrib.slim

def find_ops(optype):
  """Find ops of a given type in graphdef or a graph.

  Args:
    optype: operation type (e.g. Conv2D)
  Returns:
     List of operations.
  """
  gd = tf.get_default_graph()
  return [var for var in gd.get_operations() if var.type == optype]

class MobilenetV2Test(tf.test.TestCase):

  def setUp(self):
    tf.reset_default_graph()

  def testCreation(self):
    spec = dict(mobilenet_v2.V2_DEF)
    _, ep = mobilenet.mobilenet(
        tf.placeholder(tf.float32, (10, 224, 224, 16)), conv_defs=spec)
    num_convs = len(find_ops('Conv2D'))

    # This is mostly a sanity test. No deep reason for these particular
    # constants.
    #
    # All but first 2 and last one have  two convolutions, and there is one
    # extra conv that is not in the spec. (logits)
    self.assertEqual(num_convs, len(spec['spec']) * 2 - 2)
    # Check that depthwise are exposed.
    for i in range(2, 17):
      self.assertIn('layer_%d/depthwise_output' % i, ep)

  def testCreationNoClasses(self):
    spec = copy.deepcopy(mobilenet_v2.V2_DEF)
    net, ep = mobilenet.mobilenet(
        tf.placeholder(tf.float32, (10, 224, 224, 16)), conv_defs=spec,
        num_classes=None)
    self.assertIs(net, ep['global_pool'])

  def testImageSizes(self):
    for input_size, output_size in [(224, 7), (192, 6), (160, 5),
                                    (128, 4), (96, 3)]:
      tf.reset_default_graph()
      _, ep = mobilenet_v2.mobilenet(
          tf.placeholder(tf.float32, (10, input_size, input_size, 3)))

      self.assertEqual(ep['layer_18/output'].get_shape().as_list()[1:3],
                       [output_size] * 2)

  def testWithSplits(self):
    spec = copy.deepcopy(mobilenet_v2.V2_DEF)
    spec['overrides'] = {
        (ops.expanded_conv,): dict(split_expansion=2),
    }
    _, _ = mobilenet.mobilenet(
        tf.placeholder(tf.float32, (10, 224, 224, 16)), conv_defs=spec)
    num_convs = len(find_ops('Conv2D'))
    # All but 3 op has 3 conv operatore, the remainign 3 have one
    # and there is one unaccounted.
    self.assertEqual(num_convs, len(spec['spec']) * 3 - 5)

  def testWithOutputStride8(self):
    out, _ = mobilenet.mobilenet_base(
        tf.placeholder(tf.float32, (10, 224, 224, 16)),
        conv_defs=mobilenet_v2.V2_DEF,
        output_stride=8,
        scope='MobilenetV2')
    self.assertEqual(out.get_shape().as_list()[1:3], [28, 28])

  def testDivisibleBy(self):
    tf.reset_default_graph()
    mobilenet_v2.mobilenet(
        tf.placeholder(tf.float32, (10, 224, 224, 16)),
        conv_defs=mobilenet_v2.V2_DEF,
        divisible_by=16,
        min_depth=32)
    s = [op.outputs[0].get_shape().as_list()[-1] for op in find_ops('Conv2D')]
    s = set(s)
    self.assertSameElements([32, 64, 96, 160, 192, 320, 384, 576, 960, 1280,
                             1001], s)

  def testDivisibleByWithArgScope(self):
    tf.reset_default_graph()
    # Verifies that depth_multiplier arg scope actually works
    # if no default min_depth is provided.
    with slim.arg_scope((mobilenet.depth_multiplier,), min_depth=32):
      mobilenet_v2.mobilenet(
          tf.placeholder(tf.float32, (10, 224, 224, 2)),
          conv_defs=mobilenet_v2.V2_DEF, depth_multiplier=0.1)
      s = [op.outputs[0].get_shape().as_list()[-1] for op in find_ops('Conv2D')]
      s = set(s)
      self.assertSameElements(s, [32, 192, 128, 1001])

  def testFineGrained(self):
    tf.reset_default_graph()
    # Verifies that depth_multiplier arg scope actually works
    # if no default min_depth is provided.

    mobilenet_v2.mobilenet(
        tf.placeholder(tf.float32, (10, 224, 224, 2)),
        conv_defs=mobilenet_v2.V2_DEF, depth_multiplier=0.01,
        finegrain_classification_mode=True)
    s = [op.outputs[0].get_shape().as_list()[-1] for op in find_ops('Conv2D')]
    s = set(s)
    # All convolutions will be 8->48, except for the last one.
    self.assertSameElements(s, [8, 48, 1001, 1280])

  def testMobilenetBase(self):
    tf.reset_default_graph()
    # Verifies that mobilenet_base returns pre-pooling layer.
    with slim.arg_scope((mobilenet.depth_multiplier,), min_depth=32):
      net, _ = mobilenet_v2.mobilenet_base(
          tf.placeholder(tf.float32, (10, 224, 224, 16)),
          conv_defs=mobilenet_v2.V2_DEF, depth_multiplier=0.1)
      self.assertEqual(net.get_shape().as_list(), [10, 7, 7, 128])

  def testWithOutputStride16(self):
    tf.reset_default_graph()
    out, _ = mobilenet.mobilenet_base(
        tf.placeholder(tf.float32, (10, 224, 224, 16)),
        conv_defs=mobilenet_v2.V2_DEF,
        output_stride=16)
    self.assertEqual(out.get_shape().as_list()[1:3], [14, 14])

  def testMultiplier(self):
    op = mobilenet.op
    new_def = copy.deepcopy(mobilenet_v2.V2_DEF)

    def inverse_multiplier(output_params, multiplier):
      output_params['num_outputs'] /= multiplier

    new_def['spec'][0] = op(
        slim.conv2d,
        kernel_size=(3, 3),
        multiplier_func=inverse_multiplier,
        num_outputs=16)
    _ = mobilenet_v2.mobilenet_base(
        tf.placeholder(tf.float32, (10, 224, 224, 16)),
        conv_defs=new_def, depth_multiplier=0.1)
    s = [op.outputs[0].get_shape().as_list()[-1] for op in find_ops('Conv2D')]
    # Expect first layer to be 160 (16 / 0.1), and other layers
    # their max(original size * 0.1, 8)
    self.assertEqual([160, 8, 48, 8, 48], s[:5])

  def testWithOutputStride8AndExplicitPadding(self):
    tf.reset_default_graph()
    out, _ = mobilenet.mobilenet_base(
        tf.placeholder(tf.float32, (10, 224, 224, 16)),
        conv_defs=mobilenet_v2.V2_DEF,
        output_stride=8,
        use_explicit_padding=True,
        scope='MobilenetV2')
    self.assertEqual(out.get_shape().as_list()[1:3], [28, 28])

  def testWithOutputStride16AndExplicitPadding(self):
    tf.reset_default_graph()
    out, _ = mobilenet.mobilenet_base(
        tf.placeholder(tf.float32, (10, 224, 224, 16)),
        conv_defs=mobilenet_v2.V2_DEF,
        output_stride=16,
        use_explicit_padding=True)
    self.assertEqual(out.get_shape().as_list()[1:3], [14, 14])

  def testBatchNormScopeDoesNotHaveIsTrainingWhenItsSetToNone(self):
    sc = mobilenet.training_scope(is_training=None)
    self.assertNotIn('is_training', sc[slim.arg_scope_func_key(
        slim.batch_norm)])

  def testBatchNormScopeDoesHasIsTrainingWhenItsNotNone(self):
    sc = mobilenet.training_scope(is_training=False)
    self.assertIn('is_training', sc[slim.arg_scope_func_key(slim.batch_norm)])
    sc = mobilenet.training_scope(is_training=True)
    self.assertIn('is_training', sc[slim.arg_scope_func_key(slim.batch_norm)])
    sc = mobilenet.training_scope()
    self.assertIn('is_training', sc[slim.arg_scope_func_key(slim.batch_norm)])

if __name__ == '__main__':
  tf.test.main()


text:
namespace $ {

	export function $mol_data_instance< Instance extends new ( ... args : any[] )=> any >( Instance : Instance ) {

		return $mol_data_setup( ( val : InstanceType< Instance > ) => {

			if( val as object instanceof Instance ) return val

			return $mol_fail( new $mol_data_error( `${ val } is not a ${ Instance.name }` ) )

		} , Instance )

	}

}


text:
(function($) {

// function to retrieve GET params
$.urlParam = function(name){
	var results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(window.location.href);
    if (results != null) {
	    return results[1] || 0;
    }
    else {
        return 0;
    }
}

/*---------------------------------------------------------
  Setup, Layout, and Status Functions
---------------------------------------------------------*/

var capabilities = new Array('select', 'download', 'rename', 'delete');

// Get localized messages from file
// through culture var or from URL
if($.urlParam('langCode') != 0 && file_exists (ofmBase + '/scripts/languages/'  + $.urlParam('langCode') + '.js')) culture = $.urlParam('langCode');
var lg = [];
$.ajax({
  url: ofmBase + '/scripts/languages/'  + culture + '.js',
  async: false,
  dataType: 'json',
  success: function (json) {
    lg = json;
  }
});

// Options for alert, prompt, and confirm dialogues.
$.prompt.setDefaults({
    overlayspeed: 'fast',
    show: 'fadeIn',
    opacity: 0.4
});

// Forces columns to fill the layout vertically.
// Called on initial page load and on resize.
var setDimensions = function(){
	var newH = $(window).height() - $('#uploader').height() - 30;
	$('#splitter, #filetree, #fileinfo, .vsplitbar').height(newH);
}

// Display Min Path
var displayPath = function (path) {
    if (showFullPath == false) {
        // if a "displayPathDecorator" function is defined, use it to decorate path
        return 'function' === (typeof displayPathDecorator)
                ? displayPathDecorator(path)
                : path.replace(fileRoot, "/");
    }
    else {
        return path;
    }
}

// Set the view buttons state
var setViewButtonsFor = function(viewMode) {
    if (viewMode == 'grid') {
        $('#grid').addClass('ON');
        $('#list').removeClass('ON');
    }
    else {
        $('#list').addClass('ON');
        $('#grid').removeClass('ON');
    }
}

// Test if a given url exists
function file_exists (url) {
    // http://kevin.vanzonneveld.net
    // +   original by: Enrique Gonzalez
    // +      input by: Jani Hartikainen
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // %        note 1: This function uses XmlHttpRequest and cannot retrieve resource from different domain.
    // %        note 1: Synchronous so may lock up browser, mainly here for study purposes.
    // *     example 1: file_exists('http://kevin.vanzonneveld.net/pj_test_supportfile_1.htm');
    // *     returns 1: '123'
    var req = this.window.ActiveXObject ? new ActiveXObject("Microsoft.XMLHTTP") : new XMLHttpRequest();
    if (!req) {
        throw new Error('XMLHttpRequest not supported');
    }

    // HEAD Results are usually shorter (faster) than GET
    req.open('HEAD', url, false);
    req.send(null);
    if (req.status == 200) {
        return true;
    }

    return false;
}

// preg_replace
// Code from : http://xuxu.fr/2006/05/20/preg-replace-javascript/
var preg_replace = function(array_pattern, array_pattern_replace, str)  {
	var new_str = String (str);
		for (i=0; i<array_pattern.length; i++) {
			var reg_exp= RegExp(array_pattern[i], "g");
			var val_to_replace = array_pattern_replace[i];
			new_str = new_str.replace (reg_exp, val_to_replace);
		}
		return new_str;
	}

// cleanString (), on the same model as server side (connector)
// cleanString
var cleanString = function(str) {
    // This break internationalization
    /*
	var cleaned = "";
	var p_search  = 	new Array("Š", "š", "Đ", "đ", "Ž", "ž", "Č", "č", "Ć", "ć", "À",
						"Á", "Â", "Ã", "Ä", "Å", "Æ", "Ç", "È", "É", "Ê", "Ë", "Ì", "Í", "Î", "Ï",
						"Ñ", "Ò", "Ó", "Ô", "Õ", "Ö", "Ő", "Ø", "Ù", "Ú", "Û", "Ü", "Ý", "Þ", "ß",
						"à", "á", "â", "ã", "ä", "å", "æ", "ç", "è", "é", "ê", "ë", "ì",  "í",
						"î", "ï", "ð", "ñ", "ò", "ó", "ô", "õ", "ö", "ő", "ø", "ù", "ú", "û", "ý",
						"ý", "þ", "ÿ", "Ŕ", "ŕ", " ", "'", "/"
						);
	var p_replace = 	new Array("S", "s", "Dj", "dj", "Z", "z", "C", "c", "C", "c", "A",
						"A", "A", "A", "A", "A", "A", "C", "E", "E", "E", "E", "I", "I", "I", "I",
						"N", "O", "O", "O", "O", "O", "O", "O", "U", "U", "U", "U", "Y", "B", "Ss",
						"a", "a", "a", "a", "a", "a", "a", "c", "e", "e", "e", "e", "i", "i",
						"i", "i", "o", "n", "o", "o", "o", "o", "o", "o", "o", "u", "u", "u", "y",
						"y", "b", "y", "R", "r", "_", "_", ""
					);

	cleaned = preg_replace(p_search, p_replace, str);
	cleaned = cleaned.replace(/[^_a-zA-Z0-9]/g, "");
	cleaned = cleaned.replace(/[_]+/g, "_");
	return cleaned;
	*/

    return str;
}

// nameFormat (), separate filename from extension before calling cleanString()
// nameFormat
var nameFormat = function(input) {
	filename = '';
	if(input.lastIndexOf('.') != -1) {
		filename  = cleanString(input.substr(0, input.lastIndexOf('.')));
		filename += '.' + input.split('.').pop();
	} else {
		filename = cleanString(input);
	}
	return filename;
}

// Handle Error. Freeze interactive buttons and display
// error message. Also called when auth() function return false (Code == "-1")
var handleError = function(errMsg) {
	$('#fileinfo').html('
' + errMsg+ '
');
	$('#newfile').attr("disabled", "disabled");
	$('#upload').attr("disabled", "disabled");
	$('#newfolder').attr("disabled", "disabled");
}

// Test if Data structure has the 'cap' capability
// 'cap' is one of 'select', 'rename', 'delete', 'download'
function has_capability(data, cap) {
	if (data['File Type'] == 'dir' && cap == 'download') return false;
	if (typeof(data['Capabilities']) == "undefined") return true;
	else return $.inArray(cap, data['Capabilities']) > -1;
}

// from http://phpjs.org/functions/basename:360
var basename = function(path, suffix) {
    var b = path.replace(/^.*[\/\\]/g, '');

    if (typeof(suffix) == 'string' && b.substr(b.length-suffix.length) == suffix) {
        b = b.substr(0, b.length-suffix.length);
    }

    return b;
}

// Sets the folder status, upload, and new folder functions
// to the path specified. Called on initial page load and
// whenever a new directory is selected.
var setUploader = function(path){
	$('#currentpath').val(path);
	$('#uploader h1').text(lg.current_folder + displayPath(path));

	$('#newfolder').unbind().click(function(){
		var foldername =  lg.default_foldername;
		var msg = lg.prompt_foldername + ' : <input id="fname" name="fname" type="text" value="' + foldername + '" />';

		var getFolderName = function(v, m){
			if(v != 1) return false;
			var fname = m.children('#fname').val();

			if(fname != ''){
				foldername = cleanString(fname);
				var d = new Date(); // to prevent IE cache issues
				$.getJSON(fileConnector + '?mode=addfolder&path=' + $('#currentpath').val() + '&name=' + foldername + '&space=' + space + '&type=' + type + '&time=' + d.getMilliseconds(), function(result){
					if(result['Code'] == 0){
						addFolder(result['Parent'], result['Name']);
						getFolderInfo(result['Parent']);
					} else {
						$.prompt(result['Error']);
					}
				});
			} else {
				$.prompt(lg.no_foldername);
			}
		}
		var btns = {};
		btns[lg.create_folder] = true;
		btns[lg.cancel] = false;
		$.prompt(msg, {
			callback: getFolderName,
			buttons: btns
		});
	});
}

// Binds specific actions to the toolbar in detail views.
// Called when detail views are loaded.
var bindToolbar = function(data){
	// this little bit is purely cosmetic
	$('#fileinfo').find('button').wrapInner('');

	if (!has_capability(data, 'select')) {
		$('#fileinfo').find('button#select').hide();
	} else {
		$('#fileinfo').find('button#select').click(function(){
			selectItem(data);
		}).show();
	}

	if (!has_capability(data, 'rename')) {
		$('#fileinfo').find('button#rename').hide();
	} else {
		$('#fileinfo').find('button#rename').click(function(){
			var newName = renameItem(data);
			if(newName.length) $('#fileinfo > h1').text(newName);
		}).show();
	}

	if (!has_capability(data, 'delete')) {
		$('#fileinfo').find('button#delete').hide();
	} else {
		$('#fileinfo').find('button#delete').click(function(){
			if(deleteItem(data)) $('#fileinfo').html('
' + lg.select_from_left + '
');
		}).show();
	}

	if (!has_capability(data, 'download')) {
		$('#fileinfo').find('button#download').hide();
	} else {
		$('#fileinfo').find('button#download').click(function(){
			window.location = fileConnector + '?mode=download&path=' + encodeURIComponent(data['Path']) + '&space=' + space + '&type=' + type;
		}).show();
	}
}

// Converts bytes to kb, mb, or gb as needed for display.
var formatBytes = function(bytes){
	var n = parseFloat(bytes);
	var d = parseFloat(1024);
	var c = 0;
	var u = [lg.bytes,lg.kb,lg.mb,lg.gb];

	while(true){
		if(n < d){
			n = Math.round(n * 100) / 100;
			return n + u[c];
		} else {
			n /= d;
			c += 1;
		}
	}
}

/*---------------------------------------------------------
  Item Actions
---------------------------------------------------------*/

// Calls the SetUrl function for FCKEditor compatibility,
// passes file path, dimensions, and alt text back to the
// opening window. Triggered by clicking the "Select"
// button in detail views or choosing the "Select"
// contextual menu option in list views.
// NOTE: closes the window when finished.
var selectItem = function(data){
	if(window.opener){
	 	if(window.tinyMCEPopup){
        	// use TinyMCE > 3.0 integration method
            var win = tinyMCEPopup.getWindowArg("window");
			win.document.getElementById(tinyMCEPopup.getWindowArg("input")).value = data['Path'];
            if (typeof(win.ImageDialog) != "undefined") {
				// Update image dimensions
            	if (win.ImageDialog.getImageData)
                 	win.ImageDialog.getImageData();

                // Preview if necessary
                if (win.ImageDialog.showPreviewImage)
					win.ImageDialog.showPreviewImage(data['Path']);
			}
			tinyMCEPopup.close();
			return;
		}
		if($.urlParam('CKEditor')){
			// use CKEditor 3.0 integration method
			window.opener.CKEDITOR.tools.callFunction($.urlParam('CKEditorFuncNum'), webRoot + data['Path']);
		}
        else {
            try {
                window.opener.ckeditorFileBrowserItemSelected(webRoot + data['Path']);
            }
            catch (e) {
                // $.prompt(lg.fck_select_integration + ' -> ' + webRoot + data['Path']);
                // Ignored
            }
        }

		window.close();
	} else {
        $.prompt(lg.fck_select_integration + ' -> ' + webRoot + data['Path']);
	}
}

// Renames the current item and returns the new name.
// Called by clicking the "Rename" button in detail views
// or choosing the "Rename" contextual menu option in
// list views.
var renameItem = function(data){
	var finalName = '';
	var msg = lg.new_filename + ' : <input id="rname" name="rname" type="text" value="' + data['Filename'] + '" />';

	var getNewName = function(v, m){
		if(v != 1) return false;
		rname = m.children('#rname').val();

		if(rname != ''){
			var givenName = nameFormat(rname);
			var oldPath = data['Path'];

			var connectString = fileConnector + '?mode=rename&old=' + data['Path'] + '&new=' + encodeURIComponent(givenName) + '&space=' + space + '&type=' + type;

			$.ajax({
				type: 'GET',
				url: connectString,
				dataType: 'json',
				async: false,
				success: function(result){
					if(result['Code'] == 0){
						var newPath = result['New Path'];
						var newName = result['New Name'];

						updateNode(oldPath, newPath, newName);

						var title = $("#preview h1").attr("title");

						if (typeof title !="undefined" && title == oldPath) {
							$('#preview h1').text(newName);
						}

						if($('#fileinfo').data('view') == 'grid'){
							$('#fileinfo img[alt="' + oldPath + '"]').parent().next('p').text(newName);
							$('#fileinfo img[alt="' + oldPath + '"]').attr('alt', newPath);
						} else {
							$('#fileinfo td[title="' + oldPath + '"]').text(newName);
							$('#fileinfo td[title="' + oldPath + '"]').attr('title', newPath);
						}

						$.prompt(lg.successful_rename);
					} else {
						$.prompt(result['Error']);
					}

					finalName = result['New Name'];
				}
			});
		}
	}
	var btns = {};
	btns[lg.rename] = true;
	btns[lg.cancel] = false;
	$.prompt(msg, {
		callback: getNewName,
		buttons: btns
	});

	return finalName;
}

// Prompts for confirmation, then deletes the current item.
// Called by clicking the "Delete" button in detail views
// or choosing the "Delete contextual menu item in list views.
var deleteItem = function(data){
	var isDeleted = false;
	var msg = lg.confirmation_delete;

	var doDelete = function(v, m){
		if(v != 1) return false;
		var connectString = fileConnector + '?mode=delete&path=' + encodeURIComponent(data['Path']) + '&space=' + space + '&type=' + type;

		$.ajax({
			type: 'GET',
			url: connectString,
			dataType: 'json',
			async: false,
			success: function(result){
				if(result['Code'] == 0){
					removeNode(result['Path']);
					var rootpath = result['Path'].substring(0, result['Path'].length-1); // removing the last slash
					rootpath = rootpath.substr(0, rootpath.lastIndexOf('/') + 1);
					$('#uploader h1').text(lg.current_folder + displayPath(rootpath));
					isDeleted = true;
					$.prompt(lg.successful_delete);
				} else {
					isDeleted = false;
					$.prompt(result['Error']);
				}
			}
		});
	}
	var btns = {};
	btns[lg.yes] = true;
	btns[lg.no] = false;
	$.prompt(msg, {
		callback: doDelete,
		buttons: btns
	});

	return isDeleted;
}

/*---------------------------------------------------------
  Functions to Update the File Tree
---------------------------------------------------------*/

// Adds a new node as the first item beneath the specified
// parent node. Called after a successful file upload.
var addNode = function(path, name){
	var ext = name.substr(name.lastIndexOf('.') + 1);
	var thisNode = $('#filetree').find('a[rel="' + path + '"]');
	var parentNode = thisNode.parent();
	var newNode = '
' + name + '
';

	if(!parentNode.find('ul').size()) parentNode.append('

');
	parentNode.find('ul').prepend(newNode);
	thisNode.click().click();

	getFolderInfo(path);

	$.prompt(lg.successful_added_file);
}

// Updates the specified node with a new name. Called after
// a successful rename operation.
var updateNode = function(oldPath, newPath, newName){
	var thisNode = $('#filetree').find('a[rel="' + oldPath + '"]');
	var parentNode = thisNode.parent().parent().prev('a');
	thisNode.attr('rel', newPath).text(newName);
	parentNode.click().click();

}

// Removes the specified node. Called after a successful
// delete operation.
var removeNode = function(path){
    $('#filetree')
        .find('a[rel="' + path + '"]')
        .parent()
        .fadeOut('slow', function(){
            $(this).remove();
        });
    // grid case
    if($('#fileinfo').data('view') == 'grid'){
        $('#contents img[alt="' + path + '"]').parent().parent()
            .fadeOut('slow', function(){
                $(this).remove();
        });
    }
    // list case
    else {
        $('table#contents')
            .find('td[title="' + path + '"]')
            .parent()
            .fadeOut('slow', function(){
                $(this).remove();
        });
    }
    // remove fileinfo when item to remove is currently selected
    if ($('#preview').length) {
    	getFolderInfo(path.substr(0, path.lastIndexOf('/') + 1));
	}
}

// Adds a new folder as the first item beneath the
// specified parent node. Called after a new folder is
// successfully created.
var addFolder = function(parent, name){
	var newNode = '
' + name + '

';
	var parentNode = $('#filetree').find('a[rel="' + parent + '"]');
	if(parent != fileRoot){
		parentNode.next('ul').prepend(newNode).prev('a').click().click();
	} else {
		$('#filetree > ul').prepend(newNode);
		$('#filetree').find('li a[rel="' + parent + name + '/"]').click(function(){
				getFolderInfo(parent + name + '/');
			}).each(function() {
				$(this).contextMenu(
					{ menu: getContextMenuOptions($(this)) },
					function(action, el, pos){
						var path = $(el).attr('rel');
						setMenus(action, path);
					});
				}
			);
	}

	$.prompt(lg.successful_added_folder);
}

/*---------------------------------------------------------
  Functions to Retrieve File and Folder Details
---------------------------------------------------------*/

// Decides whether to retrieve file or folder info based on
// the path provided.
var getDetailView = function(path){
	if(path.lastIndexOf('/') == path.length - 1){
		getFolderInfo(path);
		$('#filetree').find('a[rel="' + path + '"]').click();
	} else {
		getFileInfo(path);
	}
}

function getContextMenuOptions(elem) {
	var optionsID = elem.attr('class').replace(/ /g, '_');
	if (optionsID == "") return 'itemOptions';
	if (!($('#' + optionsID).length)) {
		// Create a clone to itemOptions with menus specific to this element
		var newOptions = $('#itemOptions').clone().attr('id', optionsID);
		if (!elem.hasClass('cap_select')) $('.select', newOptions).remove();
		if (!elem.hasClass('cap_download')) $('.download', newOptions).remove();
		if (!elem.hasClass('cap_rename')) $('.rename', newOptions).remove();
		if (!elem.hasClass('cap_delete')) $('.delete', newOptions).remove();
		$('#itemOptions').after(newOptions);
	}
	return optionsID;
}

// Binds contextual menus to items in list and grid views.
var setMenus = function(action, path){
	var d = new Date(); // to prevent IE cache issues
	$.getJSON(fileConnector + '?mode=getinfo&path=' + path + '&space=' + space + '&type=' + type + '&time=' + d.getMilliseconds(), function(data){
        var item;
		if($('#fileinfo').data('view') == 'grid'){
			item = $('#fileinfo').find('img[alt="' + data['Path'] + '"]').parent();
		} else {
			item = $('#fileinfo').find('td[title="' + data['Path'] + '"]').parent();
		}

		switch(action){
			case 'select':
				selectItem(data);
				break;

			case 'download':
				window.location = fileConnector + '?mode=download&path=' + data['Path'] + '&space=' + space + '&type=' + type;
				break;

			case 'rename':
				var newName = renameItem(data);
				break;

			case 'delete':
				deleteItem(data);
				break;
		}
	});
}

// Retrieves information about the specified file as a JSON
// object and uses that data to populate a template for
// detail views. Binds the toolbar for that detail view to
// enable specific actions. Called whenever an item is
// clicked in the file tree or list views.
var getFileInfo = function(file){
	// Update location for status, upload, & new folder functions.
	var currentpath = file.substr(0, file.lastIndexOf('/') + 1);
	setUploader(currentpath);

	// Include the template.
	var template = '

';
	template += '<form id="toolbar">';
	if(window.opener != null) template += '<button id="select" name="select" type="button" value="Select">' + lg.select + '</button>';
	template += '<button id="download" name="download" type="button" value="Download">' + lg.download + '</button>';
	if(browseOnly != true) template += '<button id="rename" name="rename" type="button" value="Rename">' + lg.rename + '</button>';
	if(browseOnly != true) template += '<button id="delete" name="delete" type="button" value="Delete">' + lg.del + '</button>';
	template += '<button id="parentfolder">' + lg.parentfolder + '</button>';
	template += '</form>';

	$('#fileinfo').html(template);
	$('#parentfolder').click(function() {getFolderInfo(currentpath);});

	// Retrieve the data & populate the template.
	var d = new Date(); // to prevent IE cache issues
	$.getJSON(fileConnector + '?mode=getinfo&path=' + encodeURIComponent(file) + '&space=' + space + '&type=' + type + '&time=' + d.getMilliseconds(), function(data){
		if(data['Code'] == 0){
			$('#fileinfo').find('h1').text(data['Filename']).attr('title', file);
			$('#fileinfo').find('img').attr('src',data['Preview']);

			var properties = '';

			if(data['Properties']['Width'] && data['Properties']['Width'] != '') properties += '
' + lg.dimensions + '

' + data['Properties']['Width'] + 'x' + data['Properties']['Height'] + '
';
			if(data['Properties']['Date Created'] && data['Properties']['Date Created'] != '') properties += '
' + lg.created + '

' + data['Properties']['Date Created'] + '
';
			if(data['Properties']['Date Modified'] && data['Properties']['Date Modified'] != '') properties += '
' + lg.modified + '

' + data['Properties']['Date Modified'] + '
';
			if(data['Properties']['Size'] || parseInt(data['Properties']['Size'])==0) properties += '
' + lg.size + '

' + formatBytes(data['Properties']['Size']) + '
';

			$('#fileinfo').find('dl').html(properties);

			// Bind toolbar functions.
			bindToolbar(data);
		} else {
			$.prompt(data['Error']);
		}
	});
}

// Retrieves data for all items within the given folder and
// creates a list view. Binds contextual menu options.
// TODO: consider stylesheet switching to switch between grid
// and list views with sorting options.
var getFolderInfo = function(path){
	// Update location for status, upload, & new folder functions.
	setUploader(path);

	// Display an activity indicator.
	$('#fileinfo').html('');

	// Retrieve the data and generate the markup.
	var d = new Date(); // to prevent IE cache issues
	var url = fileConnector + '?path=' + encodeURIComponent(path) + '&mode=getfolder&showThumbs=' + showThumbs + '&space=' + space + '&type=' + type + '&time=' + d.getMilliseconds();
	$.getJSON(url, function(data){
		var result = '';

		// Is there any error or user is unauthorized?
		if(data.Code=='-1') {
			handleError(data.Error);
			return;
		};

		if(data){
			if($('#fileinfo').data('view') == 'grid'){
				result += '
';

				for(key in data){
					var props = data[key]['Properties'];
					var cap_classes = "";
					for (cap in capabilities) {
						if (has_capability(data[key], capabilities[cap])) {
							cap_classes += " cap_" + capabilities[cap];
						}
					}

					var scaledWidth = 64;
					var actualWidth = props['Width'];
					if(actualWidth > 1 && actualWidth < scaledWidth) scaledWidth = actualWidth;

					result += '

' + data[key]['Filename'] + '
';
					if(props['Width'] && props['Width'] != '') result += '' + props['Width'] + 'x' + props['Height'] + '';
					if(props['Size'] && props['Size'] != '') result += '' + props['Size'] + '';
					if(props['Date Created'] && props['Date Created'] != '') result += '' + props['Date Created'] + '';
					if(props['Date Modified'] && props['Date Modified'] != '') result += '' + props['Date Modified'] + '';
					result += '
';
				}

				result += '
';
			} else {
				result += '
';
				result += '

' + lg.name + '	' + lg.dimensions + '	' + lg.size + '	' + lg.modified + '

';
				result += '
';

				for(key in data){
					var path = data[key]['Path'];
					var props = data[key]['Properties'];
                    var cap_classes = "";
					for (cap in capabilities) {
						if (has_capability(data[key], capabilities[cap])) {
							cap_classes += " cap_" + capabilities[cap];
						}
					}
					result += '
';
					result += '' + data[key]['Filename'] + '	';

					if(props['Width'] && props['Width'] != ''){
						result += ('' + props['Width'] + 'x' + props['Height'] + '	');
					} else {
						result += '	';
					}

					if(props['Size'] && props['Size'] != ''){
						result += '' + formatBytes(props['Size']) + '	';
					} else {
						result += '	';
					}

					if(props['Date Modified'] && props['Date Modified'] != ''){
						result += '' + props['Date Modified'] + '	';
					} else {
						result += '	';
					}

					result += '
';
				}

				result += '
';
				result += '
';
			}
		} else {
			result += '
' + lg.could_not_retrieve_folder + '
';
		}

		// Add the new markup to the DOM.
		$('#fileinfo').html(result);

		// Bind click events to create detail views and add
		// contextual menu options.
		if($('#fileinfo').data('view') == 'grid'){
			$('#fileinfo').find('#contents li').click(function(){
				var path = $(this).find('img').attr('alt');
				getDetailView(path);
			}).each(function() {
				$(this).contextMenu(
					{ menu: getContextMenuOptions($(this)) },
					function(action, el, pos){
						var path = $(el).find('img').attr('alt');
						setMenus(action, path);
					}
				);
			});
		} else {
			$('#fileinfo').find('td:first-child').each(function(){
				var path = $(this).attr('title');
				var treenode = $('#filetree').find('a[rel="' + path + '"]').parent();
				$(this).css('background-image', treenode.css('background-image'));
			});

			$('#fileinfo tbody tr').click(function(){
				var path = $('td:first-child', this).attr('title');
				getDetailView(path);
			}).each(function() {
				$(this).contextMenu(
					{ menu: getContextMenuOptions($(this)) },
					function(action, el, pos){
						var path = $('td:first-child', el).attr('title');
						setMenus(action, path);
					}
				);
			});

			$('#fileinfo').find('table').tablesorter({
				textExtraction: function(node){
					if($(node).find('abbr').size()){
						return $(node).find('abbr').attr('title');
					} else {
						return node.innerHTML;
					}
				}
			});
		}
	});
}

// Retrieve data (file/folder listing) for jqueryFileTree and pass the data back
// to the callback function in jqueryFileTree
var populateFileTree = function(path, callback){
	var d = new Date(); // to prevent IE cache issues
    var url = fileConnector + '?path=' + encodeURIComponent(path) + '&mode=getfolder&showThumbs=' + showThumbs + '&space=' + space + '&type=' + type + '&time=' + d.getMilliseconds();
	$.getJSON(url, function(data) {
		var result = '';
		// Is there any error or user is unauthorized?
		if(data.Code=='-1') {
			handleError(data.Error);
			return;
		};

		if(data) {
			result += "
";
			for(key in data) {
				var cap_classes = "";
				for (cap in capabilities) {
					if (has_capability(data[key], capabilities[cap])) {
						cap_classes += " cap_" + capabilities[cap];
					}
				}
				if (data[key]['File Type'] == 'dir') {
					result += "
" + data[key]['Filename'] + "
";
				} else {
					result += "
" + data[key]['Filename'] + "
";
				}
			}
			result += "
";
		} else {
			result += '
' + lg.could_not_retrieve_folder + '
';
		}
		callback(result);
	});
}

/*---------------------------------------------------------
  Initialization
---------------------------------------------------------*/

$(function(){
	if($.urlParam('expandedFolder') != 0) {
		expandedFolder = $.urlParam('expandedFolder');
		fullexpandedFolder = fileRoot + expandedFolder;
	} else {
		expandedFolder = '';
		fullexpandedFolder = null;
	}
	// Adjust layout.
	setDimensions();
	$(window).resize(setDimensions);

	// we finalize the FileManager UI initialization
	// with localized text if necessary
	if(autoload == true) {
		$('#upload').append(lg.upload);
		$('#newfolder').append(lg.new_folder);
		$('#grid').attr('title', lg.grid_view);
		$('#list').attr('title', lg.list_view);
		$('#fileinfo h1').append(lg.select_from_left);
		$('#itemOptions a[href$="#select"]').append(lg.select);
		$('#itemOptions a[href$="#download"]').append(lg.download);
		$('#itemOptions a[href$="#rename"]').append(lg.rename);
		$('#itemOptions a[href$="#delete"]').append(lg.del);
	}

	// Provides support for adjustible columns.
	$('#splitter').splitter({
		sizeLeft: 200
	});

	// cosmetic tweak for buttons
	$('button').wrapInner('');

	// Set initial view state.
	$('#fileinfo').data('view', defaultViewMode);
    setViewButtonsFor(defaultViewMode);

	$('#home').click(function(){
        var currentViewMode = $('#fileinfo').data('view');
		$('#fileinfo').data('view', currentViewMode);
		$('#filetree>ul>li.expanded>a').trigger('click');
		getFolderInfo(fileRoot);
	});

	// Set buttons to switch between grid and list views.
	$('#grid').click(function(){
        setViewButtonsFor('grid');
		$('#fileinfo').data('view', 'grid');
		getFolderInfo($('#currentpath').val());
	});

	$('#list').click(function(){
        setViewButtonsFor('list');
		$('#fileinfo').data('view', 'list');
		getFolderInfo($('#currentpath').val());
	});

	// Provide initial values for upload form, status, etc.
	setUploader(fileRoot);

	$('#uploader').attr('action', fileConnector + '?space=' + space + '&type=' + type);

	$('#uploader').ajaxForm({
		target: '#uploadresponse',
		beforeSubmit: function(arr, form, options) {
			$('#upload').attr('disabled', true);
			$('#upload span').addClass('loading').text(lg.loading_data);
			if ($.urlParam('type').toString().toLowerCase() == 'images') {
				// Test if uploaded file extension is in valid image extensions
				var newfileSplitted = $('#newfile', form).val().toLowerCase().split('.');
				for (key in imagesExt) {
					if (imagesExt[key] == newfileSplitted[newfileSplitted.length-1]) {
						return true;
					}
				}
				$.prompt(lg.UPLOAD_IMAGES_ONLY);
				return false;
			}
		},
		success: function(result){
			var data = jQuery.parseJSON($('#uploadresponse').find('textarea').text());

			if(data['Code'] == 0){
				addNode(data['Path'], data['Name']);
			} else {
				$.prompt(data['Error']);
			}
			$('#upload').removeAttr('disabled');
			$('#upload span').removeClass('loading').text(lg.upload);

			// clear data in browse input
      $("#newfile").replaceWith('<input id="newfile" type="file" name="newfile">');
		}
	});

	// Creates file tree.
    $('#filetree').fileTree({
		root: fileRoot,
		datafunc: populateFileTree,
		multiFolder: false,
		folderCallback: function(path){ getFolderInfo(path); },
		expandedFolder: fullexpandedFolder,
		after: function(data){
			$('#filetree').find('li a').each(function() {
				$(this).contextMenu(
					{ menu: getContextMenuOptions($(this)) },
					function(action, el, pos){
						var path = $(el).attr('rel');
						setMenus(action, path);
					}
				)
			});
		}
	}, function(file){
		getFileInfo(file);
	});
	// Disable select function if no window.opener
	if(window.opener == null) $('#itemOptions a[href$="#select"]').remove();
	// Keep only browseOnly features if needed
	if(browseOnly == true) {
		$('#newfile').remove();
		$('#upload').remove();
		$('#newfolder').remove();
		$('#toolbar').remove('#rename');
		$('.contextMenu .rename').remove();
		$('.contextMenu .delete').remove();
	}
    getDetailView(fileRoot + expandedFolder);
});

})(jQuery);


text:
package com.gudong.appkit.utils;

import android.content.Context;
import android.support.v4.app.FragmentManager;

import com.afollestad.materialdialogs.MaterialDialog;
import com.afollestad.materialdialogs.ThemeSingleton;
import com.gudong.appkit.R;
import com.gudong.appkit.ui.fragment.CustomWebViewDialog;

/**
 * tool for dialog
 * Created by mao on 7/19/15.
 */
public class DialogUtil {
    /**
     * show a dialog which it contain one point message only
     * @param context context
     */
    public static void showSinglePointDialog(Context context, String message){
        new MaterialDialog.Builder(context)
                .title(context.getString(R.string.title_point))
                .content(message)
                .positiveText(context.getString(R.string.dialog_confirm))
                .show();
    }

    public static void showCusotomDialogFillInWebView(Context context, FragmentManager fragmentManager, String dialogTitle, String htmlFileName, String tag) {
        int accentColor = ThemeSingleton.get().widgetColor;
        if (accentColor == 0)
            accentColor = context.getResources().getColor(R.color.colorAccent);

        CustomWebViewDialog.create(dialogTitle, htmlFileName, accentColor)
                .show(fragmentManager, tag);
    }
}


text:
package com.cloudcomputing.dimayor.utils;

import endpoints.repackaged.com.google.gson.Gson;

public class JsonUtil {

	public static String toJson(Object object) {
		return new Gson().toJson(object);
	}

	public static <T> T jsonToObject(String json, Class<T> objClass) {
		return new Gson().fromJson(json, objClass);
	}

}


text:
module ActiveRecord
  module Type
    module OracleEnhanced
      class Integer < ActiveModel::Type::Integer # :nodoc:
        private
          def max_value
            ("9" * 38).to_i
          end
      end
    end
  end
end


text:
package com.intel.analytics.bigdl.nn

import com.intel.analytics.bigdl.tensor.Tensor
import com.intel.analytics.bigdl.utils.{T, Table}
import com.intel.analytics.bigdl.utils.serializer.ModuleSerializationTest
import org.scalatest.{FlatSpec, Matchers}

import scala.util.Random

@com.intel.analytics.bigdl.tags.Parallel
class CAddTableSpec extends FlatSpec with Matchers {
  "CAddTable" should "be correct when input is scalar" in {
    val module = CAddTable[Float]()
    val scalar = Tensor[Float](Array(2.0f), Array[Int]())
    val tensor = Tensor[Float](T(1, 2, 3))
    module.forward(T(scalar, tensor)) should be(Tensor[Float](T(3, 4, 5)))
    val grads = module.backward(T(scalar, tensor), Tensor[Float](T(1, 2, 3)))
    grads[Tensor[Float]](1).value() should be(6)
    grads[Tensor[Float]](2) should be(Tensor[Float](T(1, 2, 3)))
  }

  "CAddTable" should "be correct when input is scalar exchange order" in {
    val module = CAddTable[Float]()
    val scalar = Tensor[Float](Array(2.0f), Array[Int]())
    val tensor = Tensor[Float](T(1, 2, 3))
    module.forward(T(tensor, scalar)) should be(Tensor[Float](T(3, 4, 5)))
    val grads = module.backward(T(tensor, scalar), Tensor[Float](T(1, 2, 3)))
    grads[Tensor[Float]](1) should be(Tensor[Float](T(1, 2, 3)))
    grads[Tensor[Float]](2).value() should be(6)
  }
}

class CAddTableSerialTest extends ModuleSerializationTest {
  override def test(): Unit = {
    val input1 = Tensor[Float](5, 5).apply1(e => Random.nextFloat())
    val input2 = Tensor[Float](5, 5).apply1(e => Random.nextFloat())
    var input = new Table()
    input(1.toFloat) = input1
    input(2.toFloat) = input2
    val caddTable = CAddTable[Float](false).setName("caddTable")
    runSerializationTest(caddTable, input)
  }
}


text:
{
  var e = document.createEvent("HTMLEvents");
  e.initEvent(
    inType,
    dictionary.bubbles === false ? false : true,
    dictionary.cancelable === false ? false : true,
    dictionary.detail
  );
  return e;
}


text:
class CQPixmap;

class CQThumbnailCanvas : public QWidget {
 public:
  enum BgMode {
    BGCOLOR,
    CHECKERBOARD
  };

 public:
  CQThumbnailCanvas(CQPixmap *pixmap);

 private:
  void paintEvent(QPaintEvent *);

 private:
  CQPixmap *pixmap_;
  BgMode    bgMode_;
};

#endif


text:
using UnityEngine;
using System.Collections;

public class TurnStats {

	public int MovesLeft { get; set; }
	public int AttacksLeft { get; set; }
	public AITurnPlan AITurnPlan { get; set; }
	CombatantStats combatantStats = null;

	public TurnStats() {
		MovesLeft = 0;
		AttacksLeft = 0;
		this.AITurnPlan = null;
	}

	public void Reset(CombatantStats stats) {
		this.combatantStats = stats;
		this.MovesLeft = stats.MovesPerTurn;
		this.AttacksLeft = stats.AttacksPerTurn;
		this.AITurnPlan = null;
	}

	public bool CanDoSomething() {
		if (MovesLeft > 0 || AttacksLeft > 0) {
			return true;
		}
		return false;
	}

	public bool CanMove() {
		return MovesLeft > 0;
	}

	public bool CanAttack() {
		return AttacksLeft > 0;
	}

	public void ConsumeMovement() {
		this.MovesLeft = this.MovesLeft - 1;
	}

	public void ConsumeAttack() {
		this.AttacksLeft = this.AttacksLeft - 1;
	}

	public bool HasDoneAnything() {
		if (this.MovesLeft == combatantStats.MovesPerTurn &&
		    this.AttacksLeft == combatantStats.AttacksPerTurn) {
			return false;
		}
		return true;
	}

	public void EndTurn() {
		MovesLeft = 0;
		AttacksLeft = 0;
	}

	public bool HasAITurnPlan() {
		return this.AITurnPlan != null;
	}

	public string ToString() {
		return "Atks: " + AttacksLeft + " Moves: " + MovesLeft;
	}

}


text:
/*!
\ingroup PkgPolynomialConcepts
\cgalConcept

This `AdaptableFunctor` provides several operators
to construct objects of type `PolynomialTraits_d::Polynomial_d`.

\cgalRefines `AdaptableFunctor`
\cgalRefines `CopyConstructible`
\cgalRefines `DefaultConstructible`

\sa `Polynomial_d`
\sa `PolynomialTraits_d`

*/

class PolynomialTraits_d::ConstructPolynomial {
public:

/// \name Types
/// @{

/*!

*/
typedef PolynomialTraits_d::Polynomial_d result_type;

/// @}

/// \name Operations
/// @{

/*!
Construct the zero polynomial.
*/
result_type operator()();

/*!
Construct the constant polynomial equal to \f$ i\f$.
*/
result_type operator()(int i);

/*!
Construct the constant polynomial equal to \f$ a\f$.
*/
result_type operator()
(PolynomialTraits_d::Innermost_coefficient_type a);

/*!
Construct the polynomial equal to \f$ a\f$.
*/
result_type operator()
(PolynomialTraits_d::Coefficient_type a);

/*!
\pre The value type of `InputIterator` is `PolynomialTraits_d::Coefficient_type`.

The operator constructs the a polynomial from the iterator range,
with respect to the outermost variable, \f$ x_{d-1}\f$.

The range starts with the coefficient for \f$ x_{d-1}^0\f$.

In case the range is empty, the zero polynomial is constructed.

*/
template < class InputIterator >
result_type operator()(InputIterator begin, InputIterator end);

/*!

Constructs a `Polynomial_d` from a given iterator range of
`std::pair<CGAL::Exponent_vector, PolynomialTraits_d::Innermost_coefficient_type>`.

The optional parameter `is_sorted` indicates whether the given iterator range is
already sorted.

\pre The value type of `InputIterator` is `std::pair<CGAL::Exponent_vector, PolynomialTraits_d::Innermost_coefficient_type>`.
\pre Each `CGAL::Exponent_vector` must have size \f$ d\f$.
\pre All appearing `CGAL::Exponent_vector`s are different.

*/
template < class InputIterator >
result_type operator()(InputIterator begin, InputIterator end, bool is_sorted= false);

/// @}

}; /* end PolynomialTraits_d::ConstructPolynomial */


text:
define({
  "_widgetLabel": "Gráfico",
  "executeChartTip": "Haz clic en una de las siguientes tareas para ejecutar el gráfico.",
  "invalidConfig": "Configuración no válida.",
  "noneChartTip": "No se ha configurado ninguna tarea de gráfico para este widget.",
  "chartParams": "Opciones",
  "charts": "GRÁFICOS",
  "apply": "APLICAR",
  "useSpatialFilter": "Usar filtro espacial para limitar las entidades",
  "useCurrentMapExtent": "Solo entidades que intersequen el área de mapa actual",
  "drawGraphicOnMap": "Solo entidades que intersequen un área definida por el usuario",
  "chartResults": "Resultados del gráfico",
  "clearResults": "Borrar resultados",
  "noPermissionsMsg": "No tienes permisos para acceder a este servicio.",
  "specifySpatialFilterMsg": "Especifica un filtro espacial para esta tarea.",
  "queryError": "Error de la consulta.",
  "noResults": "Ninguna entidad encontrada.",
  "category": "Categoría",
  "count": "Recuento",
  "label": "Etiqueta",
  "horizontalAxis": "Eje horizontal",
  "verticalAxis": "Eje vertical",
  "dataLabels": "Etiquetas de datos",
  "color": "Color",
  "colorful": "Multicolor",
  "monochromatic": "Monocromático",
  "tasks": "Tareas",
  "results": "Resultados",
  "applySpatialFilterToLimitResults": "Aplicar un filtro espacial para limitar los resultados",
  "useCurrentExtentTip": "Parcial o totalmente dentro de la extensión de mapa actual",
  "useDrawGraphicTip": "Parcial o totalmente dentro de la forma dibujada en el mapa",
  "useFeaturesTip": "En función de sus ubicaciones con respecto a las entidades de otra capa",
  "noSpatialLimitTip": "No limitar espacialmente los resultados",
  "applySearchDistance": "Aplicar una distancia de búsqueda",
  "spatialRelationship": "Relación espacial",
  "relatedLayer": "Capa relacionada",
  "clear": "Borrar",
  "bufferDistance": "Distancia de zona de influencia",
  "miles": "Millas",
  "kilometers": "Kilómetros",
  "feet": "Pies",
  "meters": "Metros",
  "yards": "Yardas",
  "nauticalMiles": "Millas náuticas",
  "back": "Atrás",
  "execute": "Aplicar",
  "backCharts": "Volver a gráficos",
  "backOptions": "Volver a opciones",
  "clearCharts": "Borrar todos los gráficos"
});