text:
"""Trains the MNIST network using preloaded data stored in a variable.

Run using bazel:

bazel run --config opt \
    <...>/tensorflow/examples/how_tos/reading_data:fully_connected_preloaded_var

or, if installed via pip:

cd tensorflow/examples/how_tos/reading_data
python fully_connected_preloaded_var.py
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import argparse
import sys
import time

import tensorflow as tf

from tensorflow.examples.tutorials.mnist import input_data
from tensorflow.examples.tutorials.mnist import mnist

# Basic model parameters as external flags.
FLAGS = None

def run_training():
  """Train MNIST for a number of epochs."""
  # Get the sets of images and labels for training, validation, and
  # test on MNIST.
  data_sets = input_data.read_data_sets(FLAGS.train_dir, FLAGS.fake_data)

  # Tell TensorFlow that the model will be built into the default Graph.
  with tf.Graph().as_default():
    with tf.name_scope('input'):
      # Input data
      images_initializer = tf.placeholder(
          dtype=data_sets.train.images.dtype,
          shape=data_sets.train.images.shape)
      labels_initializer = tf.placeholder(
          dtype=data_sets.train.labels.dtype,
          shape=data_sets.train.labels.shape)
      input_images = tf.Variable(
          images_initializer, trainable=False, collections=[])
      input_labels = tf.Variable(
          labels_initializer, trainable=False, collections=[])

      image, label = tf.train.slice_input_producer(
          [input_images, input_labels], num_epochs=FLAGS.num_epochs)
      label = tf.cast(label, tf.int32)
      images, labels = tf.train.batch(
          [image, label], batch_size=FLAGS.batch_size)

    # Build a Graph that computes predictions from the inference model.
    logits = mnist.inference(images, FLAGS.hidden1, FLAGS.hidden2)

    # Add to the Graph the Ops for loss calculation.
    loss = mnist.loss(logits, labels)

    # Add to the Graph the Ops that calculate and apply gradients.
    train_op = mnist.training(loss, FLAGS.learning_rate)

    # Add the Op to compare the logits to the labels during evaluation.
    eval_correct = mnist.evaluation(logits, labels)

    # Build the summary operation based on the TF collection of Summaries.
    summary_op = tf.summary.merge_all()

    # Create a saver for writing training checkpoints.
    saver = tf.train.Saver()

    # Create the op for initializing variables.
    init_op = tf.group(tf.global_variables_initializer(),
                       tf.local_variables_initializer())

    # Create a session for running Ops on the Graph.
    sess = tf.Session()

    # Run the Op to initialize the variables.
    sess.run(init_op)
    sess.run(input_images.initializer,
             feed_dict={images_initializer: data_sets.train.images})
    sess.run(input_labels.initializer,
             feed_dict={labels_initializer: data_sets.train.labels})

    # Instantiate a SummaryWriter to output summaries and the Graph.
    summary_writer = tf.summary.FileWriter(FLAGS.train_dir, sess.graph)

    # Start input enqueue threads.
    coord = tf.train.Coordinator()
    threads = tf.train.start_queue_runners(sess=sess, coord=coord)

    # And then after everything is built, start the training loop.
    try:
      step = 0
      while not coord.should_stop():
        start_time = time.time()

        # Run one step of the model.
        _, loss_value = sess.run([train_op, loss])

        duration = time.time() - start_time

        # Write the summaries and print an overview fairly often.
        if step % 100 == 0:
          # Print status to stdout.
          print('Step %d: loss = %.2f (%.3f sec)' % (step, loss_value,
                                                     duration))
          # Update the events file.
          summary_str = sess.run(summary_op)
          summary_writer.add_summary(summary_str, step)
          step += 1

        # Save a checkpoint periodically.
        if (step + 1) % 1000 == 0:
          print('Saving')
          saver.save(sess, FLAGS.train_dir, global_step=step)

        step += 1
    except tf.errors.OutOfRangeError:
      print('Saving')
      saver.save(sess, FLAGS.train_dir, global_step=step)
      print('Done training for %d epochs, %d steps.' % (FLAGS.num_epochs, step))
    finally:
      # When done, ask the threads to stop.
      coord.request_stop()

    # Wait for threads to finish.
    coord.join(threads)
    sess.close()

def main(_):
  run_training()

if __name__ == '__main__':
  parser = argparse.ArgumentParser()
  parser.add_argument(
      '--learning_rate',
      type=float,
      default=0.01,
      help='Initial learning rate.'
  )
  parser.add_argument(
      '--num_epochs',
      type=int,
      default=2,
      help='Number of epochs to run trainer.'
  )
  parser.add_argument(
      '--hidden1',
      type=int,
      default=128,
      help='Number of units in hidden layer 1.'
  )
  parser.add_argument(
      '--hidden2',
      type=int,
      default=32,
      help='Number of units in hidden layer 2.'
  )
  parser.add_argument(
      '--batch_size',
      type=int,
      default=100,
      help='Batch size.  Must divide evenly into the dataset sizes.'
  )
  parser.add_argument(
      '--train_dir',
      type=str,
      default='/tmp/data',
      help='Directory to put the training data.'
  )
  parser.add_argument(
      '--fake_data',
      default=False,
      help='If true, uses fake data for unit testing.',
      action='store_true'
  )
  FLAGS, unparsed = parser.parse_known_args()
  tf.app.run(main=main, argv=[sys.argv[0]] + unparsed)

redpajama_set_name: RedPajamaGithub


text:
import { Button } from "palette"
import { ButtonProps } from "palette"

export const CTAButton: React.FC<ButtonProps> = (props) => <Button block haptic {...props} />


text:
define(function(require) {
  /*
    DEPENDENCIES
   */

  var BaseDialog = require('utils/dialogs/dialog');
  var TemplateHTML = require('hbs!./quotas/html');
  var Locale = require('utils/locale');
  var QuotaDefaults = require('utils/quotas/quota-defaults');
  var QuotaWidgets = require('utils/quotas/quota-widgets');

  /*
    CONSTANTS
   */

  var DIALOG_ID = require('./quotas/dialogId');
  var TAB_ID = require('../tabId');
  var RESOURCE = "Group";
  var XML_ROOT = "GROUP";

  /*
    CONSTRUCTOR
   */

  function Dialog() {
    this.dialogId = DIALOG_ID;

    this.element = undefined;

    BaseDialog.call(this);
  }

  Dialog.DIALOG_ID = DIALOG_ID;
  Dialog.prototype = Object.create(BaseDialog.prototype);
  Dialog.prototype.constructor = Dialog;
  Dialog.prototype.html = _html;
  Dialog.prototype.onShow = _onShow;
  Dialog.prototype.setup = _setup;
  Dialog.prototype.setParams = _setParams;

  return Dialog;

  /*
    FUNCTION DEFINITIONS
   */

  function _html() {
    return TemplateHTML({
      'dialogId': this.dialogId,
      'quotasHTML': QuotaWidgets.dialogHTML()
    });
  }

  function _setup(context) {
    var that = this;

    QuotaWidgets.setupQuotasDialog(context);

    return false;
  }

  /**
   * @param {object} params
   *        - params.element : group object, or empty object {}
   */
  function _setParams(params) {
    this.element = params.element;
  }

  function _onShow(context) {
    QuotaWidgets.populateQuotasDialog(
      this.element,
      QuotaDefaults.getDefaultQuotas(RESOURCE),
      context);

    return false;
  }
});


text:
ul.concern {list-style-type: none; width:80%;}
ul.concern li {background: #909090; padding-bottom:20px; padding-left:10px}
ul.observation  { width:80%;list-style-type: none;}
ul.observation li {background: #CFD4E6; margin-bottom: 0px; padding-bottom:0px;}
ul.observation li.fail {background: red}
ul.observation li.pass {background: lime}


text:
layout: post
author: M Haidar Hanif
title: "Metro Group's Future Store Initiative: The Review"
date: 2014-03-16 06:00:00 +0700
comments: false
categories:
- Commerce
- HCI
- Technology
- Review
keywords: hci, human, computer, interaction, commerce, store, big data, technology, review
---

Innovation Background
=====================

Innovative technology in human-computer interaction world has also come and rapidly changing on how people do business. One of the significant change is in technology shop, convenience store, or retail industry. That is, a huge chance in making huge change in order to develop it better and have the advantage of it.

{% img center http://www.weiterleitung.metrogroup.de/metrogroup_logo.gif 'METRO GROUP Logo' %}
One of the most popular or viral concept and implementation is [Future Store Initiative](http://future-store.org) by Metro Group. Metro Group (Metro AG) is a German global diversified retail company and wholesale/cash and carry group based in Düsseldorf. We can compare them with [Carrefour](http://carrefour.com), another popular retail company.

{% blockquote Future Store Initiative, METRO GROUP %}
The METRO GROUP Future Store Initiative is a joint project including more than 75 partners from the retailing and consumer goods, IT and service sectors. Together, the initiative's partners are driving forward the modernization process in the retailing sector. Each company brings something different to the project, depending on its sector and area of expertise: some make innovative technology available while others test the technology in practice. On top of that, all partners offer their expertise on managing processes more efficiently and improving services in the retailing sector. The METRO GROUP Future Store Initiative has succeeded in pooling the expertise of all its partners and using this knowledge to develop ground-breaking concepts. That makes the initiative a unique project.
{% endblockquote %}

The future store is a new concepts hands on technology shop or super/hypermarket category. Its core idea may resolve new challenges that bridge between electronic commerce and ordinary dailyy life shopping. Because these days, retail industry is undergoing massive changes. So some more factors and aspects have the important role to make it better for businesses and customers. There must be also a cooperation between retail, consumer goods, information technology, service sector, and others. Some huge number of partners are taking part in developing and testing its innovative technologies and real-world concepts. Partners with various companies such as MetSAP, Intel, IBM, Cisco Systems, Fujitsu, and others to make it so.

What Future Store Initiative offers? What if every good technology combined together to make the ultimate commerce and retail system? We may discuss more on the realistic side rather than conceptual side.

<!-- more -->

Let's watch the presentational and actual videos. Or for actual readers, there's a white paper titled ["Welcome to the Future Store" (PDF)](http://chainlinkresearch.com/parallaxview/whitepapers/Welcome_to_the_future_store.pdf).

{% youtube bV-4phC2rvU %}
-- [Metro Future Stores (jogundosekun on YouTube)](http://youtu.be/bV-4phC2rvU)

{% youtube rZzls3VH678 %}
-- [real,- Future Store (Saksanjutut on YouTube)](http://youtu.be/rZzls3VH678)

A Virtual Tour of the Future Store
==================================

{% img http://www.wanzl.com/uploads/pics/Real_erfolgsgeschichte_FutureStore_540_web_01.jpg 730 'real,- Future Store front building' %}
-- [The real,- Future Store in Tönisvorst (Wanzl)](http://wanzl.com/en_DE/company/success-stories/real-de.html)

(Yes, "real,-" rather than "Real" it is.)

This is where that advance and real implementation of ubiquitous computing mostly takes place, the advanced computing concept where computing is actually everywhere and anywhere, in contrast to desktop computing. Because it occurs with any device, location, and format. Further than that, it also takes place in customer's home.

Unfortunately, since early 2013, the Future Store Initiative has already closed. So it was mostly only tested as an experiment. So the rest is just history. Anyway, let's see what they have designed, developed, and achieved.

Future (Things)
---------------

Let's take a journey in the future of retailing. Notice that these technologies work together simultaneously.

### Mobile Shopping Assistant (MSA)

{% img http://newsimg.bbc.co.uk/media/images/40163000/jpg/_40163605_psa203m.jpg 'MSA or PSA in Tablet PC' %}
Or Personal Shopping Assistant (PSA) is the convenient, user-friendly computer on the shopping cart.

What it can do and we get?

- Greets the customer by name.
- Displays information and prices when the customer scans the product barcode over the built-in reading device.
- Provides information about special offers and promotions.
- Directs the customer to the products he needs.
- Keeps a running total of the shopping bill.
- Makes check-out much faster, as the customer has already scanned their purchases while shopping.
- The data transfer process triggered from the PSA to the checkout counter automatically.
- The receipt is printed out and the customer then pays.
- No need to take goods out of the shopping cart and no queue.

So in short, it's smarter to shop and reduces waiting time. In addition, the customers need a Loyalty Card to use it.

According to the technical specifications from numerous partner services, it has:

- XGA pressure-sensitive touchscreen.
- Built-in EAN barcode scanner.
- Long battery life.
- Operating system with special application software by Multichannel Retail.
- Communicates with the store's central data server via the internal WLAN network.
- Central data server applications, based on database.

### Electronic Advertising Displays (EAD)

{% img http://photos1.blogger.com/blogger/6167/2089/320/FSI-Technologien_AdvertisingDisplays.jpg 'EAD in action' %}
A dynamic display that reliable and always up-to-date. They help customers find their way around the store and latest special offers, also provide detailed information through videos or animations. They are centrally managed over the network through an internal wireless LAN connection. There's a chance that if it's presented like this, it could be more interesting.

### Information Terminals

{% img http://newsimg.bbc.co.uk/media/images/40163000/jpg/_40163603_infoterminal203m.jpg 'Information Terminals' %}
Or infoterminals. Like a computerized catalogs. They provide a wealth and details of information about all the products, even the manufacturing process, ingredients, and selling price. Also with additional useful household and health tips, such as recipes and tips. And obviously where to find  them.

### Electronic Price Labels

{% img http://spectrum.ieee.org/images/apr04/images/0404nsuperf2.jpg 'Electronic Price Labels' %}
Officially called Electronic Shelf Labeling (ESL) System with digital LC displays, communicate through a separate wireless network using Communication Base Stations (CBS). So they're a far better accurate and always updated price labels. No this is one of the most useful and convenient way to put a price label.

### Intelligent Scales

{% img http://newsimg.bbc.co.uk/media/images/40163000/jpg/_40163597_scale203m.jpg "IBM's Veggie Vision: Intelligent Scales" %}
Automatically recognizes what type of food (fruit or vegetable) is being weighed, also look for the product symbol. So just place the product on the scale, then a label is automatically printed out. They're linked to the electronic point of sale (EPOS) controller via the store's wireless network.

### Self Checkout

{% img https://m1.behance.net/rendition/modules/4124267/disp/dcf80744ab7bfa2ab69c471b1717e4ea.jpg 360 'FastLane checkout' %}
{% img http://kantarretailiq.eu/Content/Render/508012.jpeg 360 'Self checkout' %}
[FastLane checkout branding by Mark Magnusson](https://www.behance.net/gallery/Future-Store-Initiative/707414)
and
[Self checkout system](http://kantarretailiq.eu/Conversation/ConversationDetails.aspx?id=508014)

Simply swipe each item over the scanner and place it in a shopping bag. Then just pay with two payment options:

- Cash: bills or coins using the special cash terminal
- Card: debit/credit card at the payment terminal.

The details of each transaction to the store's central POS controller, which transfers the sales data to the central Merchandise Management System (MMS).

### Personal Digital Assistant (PDA)

{% img http://plstorebrands.com/images/plmag/pli_fall2003/features/1b.jpg Employee's PDA %}
Not to be confused with MSA or PSA, of course. It's for the store employees. So they can communicate more flexibly and efficiently, access the merchandise management system, check stock levels anytime, examine each shelf to monitor expiration dates, and much more. Also yes, it's equipped with an RFID reader.

### Smart Shelves

{% img http://newsimg.bbc.co.uk/media/images/40163000/jpg/_40163601_gilette_rfidbox203.jpg "Smart shelves with radio tags" %}
{% img http://economists-pick-research.hktdc.com/resources/MI_Portal/Article/imn/2004/02/38561/retail089r.jpg %}
The name explains themselves.

### Radio-Frequency Identification (RFID)

RFID, RFID Reader, RFID transponder, RFID everywhere, and much more RFIDs. Almost all the above technologies and products use RFID. How it works in the context of Future Store? [Read more in their site](http://www.future-store.org/internet/site/ts_fsi/node/140064/Len/index.html). More into how it works can be [read in HowStuffWorks](http://electronics.howstuffworks.com/gadgets/high-tech-gadgets/rfid.htm).

Its areas of application includes:

- Product Transport: for METRO Group Distribution Logistics (MDL)
- Warehouse Dispatch
- Product Delivery
- Storage in the Backstore
- Transporting the Goods into the Store

### More (Things)

There are absolutely much more features beyond those.

{% img http://kantarretailiq.eu/Content/Render/508013.jpeg 225 300 'Roger the Robot' %}
{% img http://kantarretailiq.eu/Content/Render/508013.jpeg 225 300 'Roger the Robot' %}
{% img http://kantarretailiq.eu/Content/Render/508013.jpeg 225 300 'Roger the Robot' %}

- Robots. Yes, interesting.

{% img http://www.spychips.com/metro/images/payback-card-large.jpg 250 %}
-- [METRO's Loyalty Card](http://www.spychips.com/metro/scandal-payback.html)

- Loyalty card with hidden RFID tag.
- Wireless Information Highway.
- Barcode.
- Electronic Product Code (EPC).
- (Serialized) Global Trade Item Number (S/GTIN).
- Smart Freezer.
- Logistic Unit.

Interface
---------

Please noted that it was developed, released or opened at circa 2003. So the interface may more represents the functional aspect with Web 2.0 design. This is the enhanced version of most common UI in the store.

{% img https://m1.behance.net/rendition/modules/4124263/disp/5d2dc9cf66926d500bc4523d041ff0cf.jpg 730 Common Future Store UI %}
-- [Future Store UI by Mark Magnusson](https://www.behance.net/gallery/Future-Store-Initiative/707414)

Conclusion
==========

In human-computer interaction aspect, there're a lot of things connected together and going on here. The system mostly use ubiquitous computing to manage, set, arrange, and control all the equipment and tools, where human (customers, employees, and managers) who also interact more with the technology itself  experience the better shopping and retailing process.

The combination of various innovative technology and services is truly a crucial factor for trade. It proven to increase efficiency in logistics and in warehouse management, whilst at the same time, giving an individual service and advanced special shopping experience for the customer.
{% pullquote left %}
{" So it still depends on consumer's taste and understanding. "}
{% endpullquote %}
It may actually help and boost customer with shopping experience. It's easier and faster to scan, list, buy, and deliver goods that actually needed. Business happy. Customer happy. But in the other hand, if it mismatched with the user's behavior, the experience could actually break. That's why the actual implementation must meet or fulfill the exact specifications and requirements. Objectively speaking, still, any advancement in innovation and technology is essentially good and useful.

# <abbr title="Too Long; Didn't Read">TL;DR</abbr>

The innovation and technology of futuristic store from Metro Group in the ubiquitous cloud computing era.

Additional Links
================

- [Future Store – Wikipedia](https://de.wikipedia.org/wiki/Future_Store)
- [real,- Future Store | Super/hypermarket in Tönisvorst (DE)](http://retail-square.com/shops/real-future-store)
- [Store of the Week: Real](http://kantarretailiq.eu/Conversation/ConversationDetails.aspx?id=508014)
- [Success stories - Real (DE)](http://wanzl.com/en_DE/company/success-stories/real-de.html)
- [spychips | Scandal: The RFID Tag Hidden in METRO's Loyalty Card](http://www.spychips.com/metro/scandal-payback.html)
- [The future of shopping by Tim Weber](http://news.bbc.co.uk/2/hi/3712261.stm)
- [Supermarket's Futuristic Outlet by John Blau](http://spectrum.ieee.org/computing/embedded-systems/supermarkets-futuristic-outlet)
- [BBC News - Is this the supermarket of the future?](http://bbc.co.uk/news/business-12310809)
- [Retailing in the 21st Century: Current and Future Trends](http://books.google.co.id/books?id=rM9cJVWiceYC)
- [Future Store Initiative Design by Mark Magnusson](https://www.behance.net/gallery/Future-Store-Initiative/707414)


text:
<?php

/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for an application.
| It's a breeze. Simply tell Laravel the URIs it should respond to
| and give it the controller to call when that URI is requested.
|
*/

Route::get('/', function () {
    return redirect('/home');
});

/*
|--------------------------------------------------------------------------
| API routes
|--------------------------------------------------------------------------
*/

Route::group(['prefix' => 'api', 'namespace' => 'API'], function () {
    Route::group(['prefix' => 'v1'], function () {
        require config('infyom.laravel_generator.path.api_routes');
    });
});

Route::auth();

Route::get('/home', 'HomeController@index');


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

function moduleDidLoad() {
  common.hideModule();
}

// Called by the common.js module.
function domContentLoaded(name, tc, config, width, height) {
  navigator.webkitPersistentStorage.requestQuota(1024 * 1024,
      function(bytes) {
        common.updateStatus(
            'Allocated ' + bytes + ' bytes of persistant storage.');
        common.createNaClModule(name, tc, config, width, height);
        common.attachDefaultListeners();
      },
      function(e) { alert('Failed to allocate space') });
}

// Called by the common.js module.
function attachListeners() {
  var radioEls = document.querySelectorAll('input[type="radio"]');
  for (var i = 0; i < radioEls.length; ++i) {
    radioEls[i].addEventListener('click', onRadioClicked);
  }

  document.getElementById('fopenExecute').addEventListener('click', fopen);
  document.getElementById('fcloseExecute').addEventListener('click', fclose);
  document.getElementById('freadExecute').addEventListener('click', fread);
  document.getElementById('fwriteExecute').addEventListener('click', fwrite);
  document.getElementById('fseekExecute').addEventListener('click', fseek);
  document.getElementById('statExecute').addEventListener('click', stat);
}

function onRadioClicked(e) {
  var divId = this.id.slice(5);  // skip "radio"
  var functionEls = document.querySelectorAll('.function');
  for (var i = 0; i < functionEls.length; ++i) {
    var visible = functionEls[i].id === divId;
    if (functionEls[i].id === divId)
      functionEls[i].removeAttribute('hidden');
    else
      functionEls[i].setAttribute('hidden');
  }
}

function addFilenameToSelectElements(filehandle, filename) {
  var text = '[' + filehandle + '] ' + filename;
  var selectEls = document.querySelectorAll('select.file-handle');
  for (var i = 0; i < selectEls.length; ++i) {
    var optionEl = document.createElement('option');
    optionEl.setAttribute('value', filehandle);
    optionEl.appendChild(document.createTextNode(text));
    selectEls[i].appendChild(optionEl);
  }
}

function removeFilenameFromSelectElements(filehandle) {
  var optionEls = document.querySelectorAll('select.file-handle > option');
  for (var i = 0; i < optionEls.length; ++i) {
    var optionEl = optionEls[i];
    if (optionEl.value == filehandle) {
      var selectEl = optionEl.parentNode;
      selectEl.removeChild(optionEl);
    }
  }
}

var filehandle_map = {};

function fopen(e) {
  var filename = document.getElementById('fopenFilename').value;
  var access = document.getElementById('fopenMode').value;
  nacl_module.postMessage(makeCall('fopen', filename, access));
}

function fopenResult(filename, filehandle) {
  filehandle_map[filehandle] = filename;

  addFilenameToSelectElements(filehandle, filename);
  common.logMessage('File ' + filename + ' opened successfully.\n');
}

function fclose(e) {
  var filehandle = document.getElementById('fcloseHandle').value;
  nacl_module.postMessage(makeCall('fclose', filehandle));
}

function fcloseResult(filehandle) {
  var filename = filehandle_map[filehandle];
  removeFilenameFromSelectElements(filehandle, filename);
  common.logMessage('File ' + filename + ' closed successfully.\n');
}

function fread(e) {
  var filehandle = document.getElementById('freadHandle').value;
  var numBytes = document.getElementById('freadBytes').value;
  nacl_module.postMessage(makeCall('fread', filehandle, numBytes));
}

function freadResult(filehandle, data) {
  var filename = filehandle_map[filehandle];
  common.logMessage('Read "' + data + '" from file ' + filename + '.\n');
}

function fwrite(e) {
  var filehandle = document.getElementById('fwriteHandle').value;
  var data = document.getElementById('fwriteData').value;
  nacl_module.postMessage(makeCall('fwrite', filehandle, data));
}

function fwriteResult(filehandle, bytes_written) {
  var filename = filehandle_map[filehandle];
  common.logMessage('Wrote ' + bytes_written + ' bytes to file ' + filename +
      '.\n');
}

function fseek(e) {
  var filehandle = document.getElementById('fseekHandle').value;
  var offset = document.getElementById('fseekOffset').value;
  var whence = document.getElementById('fseekWhence').value;
  nacl_module.postMessage(makeCall('fseek', filehandle, offset, whence));
}

function fseekResult(filehandle, filepos) {
  var filename = filehandle_map[filehandle];
  common.logMessage('Seeked to location ' + filepos + ' in file ' + filename +
      '.\n');
}

function stat(e) {
  var filename = document.getElementById('statFilename').value;
  nacl_module.postMessage(makeCall('stat', filename));
}

function statResult(filename, size) {
  common.logMessage('File ' + filename + ' has size ' + size + '.\n');
}

/**
 * Return true when |s| starts with the string |prefix|.
 *
 * @param {string} s The string to search.
 * @param {string} prefix The prefix to search for in |s|.
 * @return {boolean} Whether |s| starts with |prefix|.
 */
function startsWith(s, prefix) {
  // indexOf would search the entire string, lastIndexOf(p, 0) only checks at
  // the first index. See: http://stackoverflow.com/a/4579228
  return s.lastIndexOf(prefix, 0) === 0;
}

function makeCall(func) {
  var message = func;
  for (var i = 1; i < arguments.length; ++i) {
    message += '\1' + arguments[i];
  }

  return message;
}

// Called by the common.js module.
function handleMessage(message_event) {
  var msg = message_event.data;
  if (startsWith(msg, 'Error:')) {
    common.logMessage(msg + '\n');
  } else {
    // Result from a function call.
    var params = msg.split('\1');
    var funcName = params[0];
    var funcResultName = funcName + 'Result';
    var resultFunc = window[funcResultName];

    if (!resultFunc) {
      common.logMessage('Error: Bad message received from NaCl module.\n');
      return;
    }

    resultFunc.apply(null, params.slice(1));
  }
}


text:
'use strict';

const _ = require('lodash');
const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser');
const Promise = require('bluebird');
const request = require('request');
const xpath = require('xpath');
const Dom = require('xmldom').DOMParser;

const app = express();
app.use(cors());
app.use(bodyParser.json({ type: 'application/json' }));

const jsonParser = bodyParser.json();

function makeRequest (httpVerb, requestedUrl, config) {
  const headers = (_.isUndefined(config)) ? { 'Content-Type': 'application/json' } : config.headers;
  const options = { method: httpVerb, uri: requestedUrl, headers };

  return new Promise((resolve, reject) => {
    request(options, (error, response, body) => {
      if (error) { return reject(error); }
      response.payload = body;
      return resolve(response);
    });
  }).catch(() => { /* foda-se */ });
}

const root = express.Router();

root.post('/xpath', jsonParser, (req, res) => {
  if (!req.body) return res.sendStatus(400);
  makeRequest('GET', req.body.url.toString('utf-8')).then((response) => {
    if (response.statusCode === 200) {
      const payload = response.payload.toString();
      const doc = new Dom().parseFromString(payload);
      var value = xpath.select(req.body.xpath, doc)
      if (value !== undefined && value.length !== 0)
        value = value[0].nodeValue;
      res.json({ xpathResult: value });
    }
  });
});

app.use('/', root);

app.listen(8080, () => {
  console.log('server listening on port 8080');
});


text:
if [[ -z $1 ]]
 then read -p "Enter docker container name:" container
else
  container=$1
fi

if [[ -z "$container" ]]
  then echo "Invalid container name"
  exit
fi

docker stop ${container} && docker rm ${container}


text:
/**
 * Autogenerated by Thrift Compiler (0.14.1)
 *
 * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
 *  @generated
 */
package org.apache.hadoop.hive.metastore.api;

@SuppressWarnings({"cast", "rawtypes", "serial", "unchecked", "unused"})
@javax.annotation.Generated(value = "Autogenerated by Thrift Compiler (0.14.1)")
@org.apache.hadoop.classification.InterfaceAudience.Public @org.apache.hadoop.classification.InterfaceStability.Stable public class ReplicationMetrics implements org.apache.thrift.TBase<ReplicationMetrics, ReplicationMetrics._Fields>, java.io.Serializable, Cloneable, Comparable<ReplicationMetrics> {
  private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("ReplicationMetrics");

  private static final org.apache.thrift.protocol.TField SCHEDULED_EXECUTION_ID_FIELD_DESC = new org.apache.thrift.protocol.TField("scheduledExecutionId", org.apache.thrift.protocol.TType.I64, (short)1);
  private static final org.apache.thrift.protocol.TField POLICY_FIELD_DESC = new org.apache.thrift.protocol.TField("policy", org.apache.thrift.protocol.TType.STRING, (short)2);
  private static final org.apache.thrift.protocol.TField DUMP_EXECUTION_ID_FIELD_DESC = new org.apache.thrift.protocol.TField("dumpExecutionId", org.apache.thrift.protocol.TType.I64, (short)3);
  private static final org.apache.thrift.protocol.TField METADATA_FIELD_DESC = new org.apache.thrift.protocol.TField("metadata", org.apache.thrift.protocol.TType.STRING, (short)4);
  private static final org.apache.thrift.protocol.TField PROGRESS_FIELD_DESC = new org.apache.thrift.protocol.TField("progress", org.apache.thrift.protocol.TType.STRING, (short)5);

  private static final org.apache.thrift.scheme.SchemeFactory STANDARD_SCHEME_FACTORY = new ReplicationMetricsStandardSchemeFactory();
  private static final org.apache.thrift.scheme.SchemeFactory TUPLE_SCHEME_FACTORY = new ReplicationMetricsTupleSchemeFactory();

  private long scheduledExecutionId; // required
  private @org.apache.thrift.annotation.Nullable java.lang.String policy; // required
  private long dumpExecutionId; // required
  private @org.apache.thrift.annotation.Nullable java.lang.String metadata; // optional
  private @org.apache.thrift.annotation.Nullable java.lang.String progress; // optional

  /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */
  public enum _Fields implements org.apache.thrift.TFieldIdEnum {
    SCHEDULED_EXECUTION_ID((short)1, "scheduledExecutionId"),
    POLICY((short)2, "policy"),
    DUMP_EXECUTION_ID((short)3, "dumpExecutionId"),
    METADATA((short)4, "metadata"),
    PROGRESS((short)5, "progress");

    private static final java.util.Map<java.lang.String, _Fields> byName = new java.util.HashMap<java.lang.String, _Fields>();

    static {
      for (_Fields field : java.util.EnumSet.allOf(_Fields.class)) {
        byName.put(field.getFieldName(), field);
      }
    }

    /**
     * Find the _Fields constant that matches fieldId, or null if its not found.
     */
    @org.apache.thrift.annotation.Nullable
    public static _Fields findByThriftId(int fieldId) {
      switch(fieldId) {
        case 1: // SCHEDULED_EXECUTION_ID
          return SCHEDULED_EXECUTION_ID;
        case 2: // POLICY
          return POLICY;
        case 3: // DUMP_EXECUTION_ID
          return DUMP_EXECUTION_ID;
        case 4: // METADATA
          return METADATA;
        case 5: // PROGRESS
          return PROGRESS;
        default:
          return null;
      }
    }

    /**
     * Find the _Fields constant that matches fieldId, throwing an exception
     * if it is not found.
     */
    public static _Fields findByThriftIdOrThrow(int fieldId) {
      _Fields fields = findByThriftId(fieldId);
      if (fields == null) throw new java.lang.IllegalArgumentException("Field " + fieldId + " doesn't exist!");
      return fields;
    }

    /**
     * Find the _Fields constant that matches name, or null if its not found.
     */
    @org.apache.thrift.annotation.Nullable
    public static _Fields findByName(java.lang.String name) {
      return byName.get(name);
    }

    private final short _thriftId;
    private final java.lang.String _fieldName;

    _Fields(short thriftId, java.lang.String fieldName) {
      _thriftId = thriftId;
      _fieldName = fieldName;
    }

    public short getThriftFieldId() {
      return _thriftId;
    }

    public java.lang.String getFieldName() {
      return _fieldName;
    }
  }

  // isset id assignments
  private static final int __SCHEDULEDEXECUTIONID_ISSET_ID = 0;
  private static final int __DUMPEXECUTIONID_ISSET_ID = 1;
  private byte __isset_bitfield = 0;
  private static final _Fields optionals[] = {_Fields.METADATA,_Fields.PROGRESS};
  public static final java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap;
  static {
    java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new java.util.EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class);
    tmpMap.put(_Fields.SCHEDULED_EXECUTION_ID, new org.apache.thrift.meta_data.FieldMetaData("scheduledExecutionId", org.apache.thrift.TFieldRequirementType.REQUIRED,
        new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.I64)));
    tmpMap.put(_Fields.POLICY, new org.apache.thrift.meta_data.FieldMetaData("policy", org.apache.thrift.TFieldRequirementType.REQUIRED,
        new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING)));
    tmpMap.put(_Fields.DUMP_EXECUTION_ID, new org.apache.thrift.meta_data.FieldMetaData("dumpExecutionId", org.apache.thrift.TFieldRequirementType.REQUIRED,
        new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.I64)));
    tmpMap.put(_Fields.METADATA, new org.apache.thrift.meta_data.FieldMetaData("metadata", org.apache.thrift.TFieldRequirementType.OPTIONAL,
        new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING)));
    tmpMap.put(_Fields.PROGRESS, new org.apache.thrift.meta_data.FieldMetaData("progress", org.apache.thrift.TFieldRequirementType.OPTIONAL,
        new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING)));
    metaDataMap = java.util.Collections.unmodifiableMap(tmpMap);
    org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(ReplicationMetrics.class, metaDataMap);
  }

  public ReplicationMetrics() {
  }

  public ReplicationMetrics(
    long scheduledExecutionId,
    java.lang.String policy,
    long dumpExecutionId)
  {
    this();
    this.scheduledExecutionId = scheduledExecutionId;
    setScheduledExecutionIdIsSet(true);
    this.policy = policy;
    this.dumpExecutionId = dumpExecutionId;
    setDumpExecutionIdIsSet(true);
  }

  /**
   * Performs a deep copy on <i>other</i>.
   */
  public ReplicationMetrics(ReplicationMetrics other) {
    __isset_bitfield = other.__isset_bitfield;
    this.scheduledExecutionId = other.scheduledExecutionId;
    if (other.isSetPolicy()) {
      this.policy = other.policy;
    }
    this.dumpExecutionId = other.dumpExecutionId;
    if (other.isSetMetadata()) {
      this.metadata = other.metadata;
    }
    if (other.isSetProgress()) {
      this.progress = other.progress;
    }
  }

  public ReplicationMetrics deepCopy() {
    return new ReplicationMetrics(this);
  }

  @Override
  public void clear() {
    setScheduledExecutionIdIsSet(false);
    this.scheduledExecutionId = 0;
    this.policy = null;
    setDumpExecutionIdIsSet(false);
    this.dumpExecutionId = 0;
    this.metadata = null;
    this.progress = null;
  }

  public long getScheduledExecutionId() {
    return this.scheduledExecutionId;
  }

  public void setScheduledExecutionId(long scheduledExecutionId) {
    this.scheduledExecutionId = scheduledExecutionId;
    setScheduledExecutionIdIsSet(true);
  }

  public void unsetScheduledExecutionId() {
    __isset_bitfield = org.apache.thrift.EncodingUtils.clearBit(__isset_bitfield, __SCHEDULEDEXECUTIONID_ISSET_ID);
  }

  /** Returns true if field scheduledExecutionId is set (has been assigned a value) and false otherwise */
  public boolean isSetScheduledExecutionId() {
    return org.apache.thrift.EncodingUtils.testBit(__isset_bitfield, __SCHEDULEDEXECUTIONID_ISSET_ID);
  }

  public void setScheduledExecutionIdIsSet(boolean value) {
    __isset_bitfield = org.apache.thrift.EncodingUtils.setBit(__isset_bitfield, __SCHEDULEDEXECUTIONID_ISSET_ID, value);
  }

  @org.apache.thrift.annotation.Nullable
  public java.lang.String getPolicy() {
    return this.policy;
  }

  public void setPolicy(@org.apache.thrift.annotation.Nullable java.lang.String policy) {
    this.policy = policy;
  }

  public void unsetPolicy() {
    this.policy = null;
  }

  /** Returns true if field policy is set (has been assigned a value) and false otherwise */
  public boolean isSetPolicy() {
    return this.policy != null;
  }

  public void setPolicyIsSet(boolean value) {
    if (!value) {
      this.policy = null;
    }
  }

  public long getDumpExecutionId() {
    return this.dumpExecutionId;
  }

  public void setDumpExecutionId(long dumpExecutionId) {
    this.dumpExecutionId = dumpExecutionId;
    setDumpExecutionIdIsSet(true);
  }

  public void unsetDumpExecutionId() {
    __isset_bitfield = org.apache.thrift.EncodingUtils.clearBit(__isset_bitfield, __DUMPEXECUTIONID_ISSET_ID);
  }

  /** Returns true if field dumpExecutionId is set (has been assigned a value) and false otherwise */
  public boolean isSetDumpExecutionId() {
    return org.apache.thrift.EncodingUtils.testBit(__isset_bitfield, __DUMPEXECUTIONID_ISSET_ID);
  }

  public void setDumpExecutionIdIsSet(boolean value) {
    __isset_bitfield = org.apache.thrift.EncodingUtils.setBit(__isset_bitfield, __DUMPEXECUTIONID_ISSET_ID, value);
  }

  @org.apache.thrift.annotation.Nullable
  public java.lang.String getMetadata() {
    return this.metadata;
  }

  public void setMetadata(@org.apache.thrift.annotation.Nullable java.lang.String metadata) {
    this.metadata = metadata;
  }

  public void unsetMetadata() {
    this.metadata = null;
  }

  /** Returns true if field metadata is set (has been assigned a value) and false otherwise */
  public boolean isSetMetadata() {
    return this.metadata != null;
  }

  public void setMetadataIsSet(boolean value) {
    if (!value) {
      this.metadata = null;
    }
  }

  @org.apache.thrift.annotation.Nullable
  public java.lang.String getProgress() {
    return this.progress;
  }

  public void setProgress(@org.apache.thrift.annotation.Nullable java.lang.String progress) {
    this.progress = progress;
  }

  public void unsetProgress() {
    this.progress = null;
  }

  /** Returns true if field progress is set (has been assigned a value) and false otherwise */
  public boolean isSetProgress() {
    return this.progress != null;
  }

  public void setProgressIsSet(boolean value) {
    if (!value) {
      this.progress = null;
    }
  }

  public void setFieldValue(_Fields field, @org.apache.thrift.annotation.Nullable java.lang.Object value) {
    switch (field) {
    case SCHEDULED_EXECUTION_ID:
      if (value == null) {
        unsetScheduledExecutionId();
      } else {
        setScheduledExecutionId((java.lang.Long)value);
      }
      break;

    case POLICY:
      if (value == null) {
        unsetPolicy();
      } else {
        setPolicy((java.lang.String)value);
      }
      break;

    case DUMP_EXECUTION_ID:
      if (value == null) {
        unsetDumpExecutionId();
      } else {
        setDumpExecutionId((java.lang.Long)value);
      }
      break;

    case METADATA:
      if (value == null) {
        unsetMetadata();
      } else {
        setMetadata((java.lang.String)value);
      }
      break;

    case PROGRESS:
      if (value == null) {
        unsetProgress();
      } else {
        setProgress((java.lang.String)value);
      }
      break;

    }
  }

  @org.apache.thrift.annotation.Nullable
  public java.lang.Object getFieldValue(_Fields field) {
    switch (field) {
    case SCHEDULED_EXECUTION_ID:
      return getScheduledExecutionId();

    case POLICY:
      return getPolicy();

    case DUMP_EXECUTION_ID:
      return getDumpExecutionId();

    case METADATA:
      return getMetadata();

    case PROGRESS:
      return getProgress();

    }
    throw new java.lang.IllegalStateException();
  }

  /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */
  public boolean isSet(_Fields field) {
    if (field == null) {
      throw new java.lang.IllegalArgumentException();
    }

    switch (field) {
    case SCHEDULED_EXECUTION_ID:
      return isSetScheduledExecutionId();
    case POLICY:
      return isSetPolicy();
    case DUMP_EXECUTION_ID:
      return isSetDumpExecutionId();
    case METADATA:
      return isSetMetadata();
    case PROGRESS:
      return isSetProgress();
    }
    throw new java.lang.IllegalStateException();
  }

  @Override
  public boolean equals(java.lang.Object that) {
    if (that instanceof ReplicationMetrics)
      return this.equals((ReplicationMetrics)that);
    return false;
  }

  public boolean equals(ReplicationMetrics that) {
    if (that == null)
      return false;
    if (this == that)
      return true;

    boolean this_present_scheduledExecutionId = true;
    boolean that_present_scheduledExecutionId = true;
    if (this_present_scheduledExecutionId || that_present_scheduledExecutionId) {
      if (!(this_present_scheduledExecutionId && that_present_scheduledExecutionId))
        return false;
      if (this.scheduledExecutionId != that.scheduledExecutionId)
        return false;
    }

    boolean this_present_policy = true && this.isSetPolicy();
    boolean that_present_policy = true && that.isSetPolicy();
    if (this_present_policy || that_present_policy) {
      if (!(this_present_policy && that_present_policy))
        return false;
      if (!this.policy.equals(that.policy))
        return false;
    }

    boolean this_present_dumpExecutionId = true;
    boolean that_present_dumpExecutionId = true;
    if (this_present_dumpExecutionId || that_present_dumpExecutionId) {
      if (!(this_present_dumpExecutionId && that_present_dumpExecutionId))
        return false;
      if (this.dumpExecutionId != that.dumpExecutionId)
        return false;
    }

    boolean this_present_metadata = true && this.isSetMetadata();
    boolean that_present_metadata = true && that.isSetMetadata();
    if (this_present_metadata || that_present_metadata) {
      if (!(this_present_metadata && that_present_metadata))
        return false;
      if (!this.metadata.equals(that.metadata))
        return false;
    }

    boolean this_present_progress = true && this.isSetProgress();
    boolean that_present_progress = true && that.isSetProgress();
    if (this_present_progress || that_present_progress) {
      if (!(this_present_progress && that_present_progress))
        return false;
      if (!this.progress.equals(that.progress))
        return false;
    }

    return true;
  }

  @Override
  public int hashCode() {
    int hashCode = 1;

    hashCode = hashCode * 8191 + org.apache.thrift.TBaseHelper.hashCode(scheduledExecutionId);

    hashCode = hashCode * 8191 + ((isSetPolicy()) ? 131071 : 524287);
    if (isSetPolicy())
      hashCode = hashCode * 8191 + policy.hashCode();

    hashCode = hashCode * 8191 + org.apache.thrift.TBaseHelper.hashCode(dumpExecutionId);

    hashCode = hashCode * 8191 + ((isSetMetadata()) ? 131071 : 524287);
    if (isSetMetadata())
      hashCode = hashCode * 8191 + metadata.hashCode();

    hashCode = hashCode * 8191 + ((isSetProgress()) ? 131071 : 524287);
    if (isSetProgress())
      hashCode = hashCode * 8191 + progress.hashCode();

    return hashCode;
  }

  @Override
  public int compareTo(ReplicationMetrics other) {
    if (!getClass().equals(other.getClass())) {
      return getClass().getName().compareTo(other.getClass().getName());
    }

    int lastComparison = 0;

    lastComparison = java.lang.Boolean.compare(isSetScheduledExecutionId(), other.isSetScheduledExecutionId());
    if (lastComparison != 0) {
      return lastComparison;
    }
    if (isSetScheduledExecutionId()) {
      lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.scheduledExecutionId, other.scheduledExecutionId);
      if (lastComparison != 0) {
        return lastComparison;
      }
    }
    lastComparison = java.lang.Boolean.compare(isSetPolicy(), other.isSetPolicy());
    if (lastComparison != 0) {
      return lastComparison;
    }
    if (isSetPolicy()) {
      lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.policy, other.policy);
      if (lastComparison != 0) {
        return lastComparison;
      }
    }
    lastComparison = java.lang.Boolean.compare(isSetDumpExecutionId(), other.isSetDumpExecutionId());
    if (lastComparison != 0) {
      return lastComparison;
    }
    if (isSetDumpExecutionId()) {
      lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.dumpExecutionId, other.dumpExecutionId);
      if (lastComparison != 0) {
        return lastComparison;
      }
    }
    lastComparison = java.lang.Boolean.compare(isSetMetadata(), other.isSetMetadata());
    if (lastComparison != 0) {
      return lastComparison;
    }
    if (isSetMetadata()) {
      lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.metadata, other.metadata);
      if (lastComparison != 0) {
        return lastComparison;
      }
    }
    lastComparison = java.lang.Boolean.compare(isSetProgress(), other.isSetProgress());
    if (lastComparison != 0) {
      return lastComparison;
    }
    if (isSetProgress()) {
      lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.progress, other.progress);
      if (lastComparison != 0) {
        return lastComparison;
      }
    }
    return 0;
  }

  @org.apache.thrift.annotation.Nullable
  public _Fields fieldForId(int fieldId) {
    return _Fields.findByThriftId(fieldId);
  }

  public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException {
    scheme(iprot).read(iprot, this);
  }

  public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException {
    scheme(oprot).write(oprot, this);
  }

  @Override
  public java.lang.String toString() {
    java.lang.StringBuilder sb = new java.lang.StringBuilder("ReplicationMetrics(");
    boolean first = true;

    sb.append("scheduledExecutionId:");
    sb.append(this.scheduledExecutionId);
    first = false;
    if (!first) sb.append(", ");
    sb.append("policy:");
    if (this.policy == null) {
      sb.append("null");
    } else {
      sb.append(this.policy);
    }
    first = false;
    if (!first) sb.append(", ");
    sb.append("dumpExecutionId:");
    sb.append(this.dumpExecutionId);
    first = false;
    if (isSetMetadata()) {
      if (!first) sb.append(", ");
      sb.append("metadata:");
      if (this.metadata == null) {
        sb.append("null");
      } else {
        sb.append(this.metadata);
      }
      first = false;
    }
    if (isSetProgress()) {
      if (!first) sb.append(", ");
      sb.append("progress:");
      if (this.progress == null) {
        sb.append("null");
      } else {
        sb.append(this.progress);
      }
      first = false;
    }
    sb.append(")");
    return sb.toString();
  }

  public void validate() throws org.apache.thrift.TException {
    // check for required fields
    if (!isSetScheduledExecutionId()) {
      throw new org.apache.thrift.protocol.TProtocolException("Required field 'scheduledExecutionId' is unset! Struct:" + toString());
    }

    if (!isSetPolicy()) {
      throw new org.apache.thrift.protocol.TProtocolException("Required field 'policy' is unset! Struct:" + toString());
    }

    if (!isSetDumpExecutionId()) {
      throw new org.apache.thrift.protocol.TProtocolException("Required field 'dumpExecutionId' is unset! Struct:" + toString());
    }

    // check for sub-struct validity
  }

  private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException {
    try {
      write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out)));
    } catch (org.apache.thrift.TException te) {
      throw new java.io.IOException(te);
    }
  }

  private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, java.lang.ClassNotFoundException {
    try {
      // it doesn't seem like you should have to do this, but java serialization is wacky, and doesn't call the default constructor.
      __isset_bitfield = 0;
      read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in)));
    } catch (org.apache.thrift.TException te) {
      throw new java.io.IOException(te);
    }
  }

  private static class ReplicationMetricsStandardSchemeFactory implements org.apache.thrift.scheme.SchemeFactory {
    public ReplicationMetricsStandardScheme getScheme() {
      return new ReplicationMetricsStandardScheme();
    }
  }

  private static class ReplicationMetricsStandardScheme extends org.apache.thrift.scheme.StandardScheme<ReplicationMetrics> {

    public void read(org.apache.thrift.protocol.TProtocol iprot, ReplicationMetrics struct) throws org.apache.thrift.TException {
      org.apache.thrift.protocol.TField schemeField;
      iprot.readStructBegin();
      while (true)
      {
        schemeField = iprot.readFieldBegin();
        if (schemeField.type == org.apache.thrift.protocol.TType.STOP) {
          break;
        }
        switch (schemeField.id) {
          case 1: // SCHEDULED_EXECUTION_ID
            if (schemeField.type == org.apache.thrift.protocol.TType.I64) {
              struct.scheduledExecutionId = iprot.readI64();
              struct.setScheduledExecutionIdIsSet(true);
            } else {
              org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
            }
            break;
          case 2: // POLICY
            if (schemeField.type == org.apache.thrift.protocol.TType.STRING) {
              struct.policy = iprot.readString();
              struct.setPolicyIsSet(true);
            } else {
              org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
            }
            break;
          case 3: // DUMP_EXECUTION_ID
            if (schemeField.type == org.apache.thrift.protocol.TType.I64) {
              struct.dumpExecutionId = iprot.readI64();
              struct.setDumpExecutionIdIsSet(true);
            } else {
              org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
            }
            break;
          case 4: // METADATA
            if (schemeField.type == org.apache.thrift.protocol.TType.STRING) {
              struct.metadata = iprot.readString();
              struct.setMetadataIsSet(true);
            } else {
              org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
            }
            break;
          case 5: // PROGRESS
            if (schemeField.type == org.apache.thrift.protocol.TType.STRING) {
              struct.progress = iprot.readString();
              struct.setProgressIsSet(true);
            } else {
              org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
            }
            break;
          default:
            org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
        }
        iprot.readFieldEnd();
      }
      iprot.readStructEnd();
      struct.validate();
    }

    public void write(org.apache.thrift.protocol.TProtocol oprot, ReplicationMetrics struct) throws org.apache.thrift.TException {
      struct.validate();

      oprot.writeStructBegin(STRUCT_DESC);
      oprot.writeFieldBegin(SCHEDULED_EXECUTION_ID_FIELD_DESC);
      oprot.writeI64(struct.scheduledExecutionId);
      oprot.writeFieldEnd();
      if (struct.policy != null) {
        oprot.writeFieldBegin(POLICY_FIELD_DESC);
        oprot.writeString(struct.policy);
        oprot.writeFieldEnd();
      }
      oprot.writeFieldBegin(DUMP_EXECUTION_ID_FIELD_DESC);
      oprot.writeI64(struct.dumpExecutionId);
      oprot.writeFieldEnd();
      if (struct.metadata != null) {
        if (struct.isSetMetadata()) {
          oprot.writeFieldBegin(METADATA_FIELD_DESC);
          oprot.writeString(struct.metadata);
          oprot.writeFieldEnd();
        }
      }
      if (struct.progress != null) {
        if (struct.isSetProgress()) {
          oprot.writeFieldBegin(PROGRESS_FIELD_DESC);
          oprot.writeString(struct.progress);
          oprot.writeFieldEnd();
        }
      }
      oprot.writeFieldStop();
      oprot.writeStructEnd();
    }

  }

  private static class ReplicationMetricsTupleSchemeFactory implements org.apache.thrift.scheme.SchemeFactory {
    public ReplicationMetricsTupleScheme getScheme() {
      return new ReplicationMetricsTupleScheme();
    }
  }

  private static class ReplicationMetricsTupleScheme extends org.apache.thrift.scheme.TupleScheme<ReplicationMetrics> {

    @Override
    public void write(org.apache.thrift.protocol.TProtocol prot, ReplicationMetrics struct) throws org.apache.thrift.TException {
      org.apache.thrift.protocol.TTupleProtocol oprot = (org.apache.thrift.protocol.TTupleProtocol) prot;
      oprot.writeI64(struct.scheduledExecutionId);
      oprot.writeString(struct.policy);
      oprot.writeI64(struct.dumpExecutionId);
      java.util.BitSet optionals = new java.util.BitSet();
      if (struct.isSetMetadata()) {
        optionals.set(0);
      }
      if (struct.isSetProgress()) {
        optionals.set(1);
      }
      oprot.writeBitSet(optionals, 2);
      if (struct.isSetMetadata()) {
        oprot.writeString(struct.metadata);
      }
      if (struct.isSetProgress()) {
        oprot.writeString(struct.progress);
      }
    }

    @Override
    public void read(org.apache.thrift.protocol.TProtocol prot, ReplicationMetrics struct) throws org.apache.thrift.TException {
      org.apache.thrift.protocol.TTupleProtocol iprot = (org.apache.thrift.protocol.TTupleProtocol) prot;
      struct.scheduledExecutionId = iprot.readI64();
      struct.setScheduledExecutionIdIsSet(true);
      struct.policy = iprot.readString();
      struct.setPolicyIsSet(true);
      struct.dumpExecutionId = iprot.readI64();
      struct.setDumpExecutionIdIsSet(true);
      java.util.BitSet incoming = iprot.readBitSet(2);
      if (incoming.get(0)) {
        struct.metadata = iprot.readString();
        struct.setMetadataIsSet(true);
      }
      if (incoming.get(1)) {
        struct.progress = iprot.readString();
        struct.setProgressIsSet(true);
      }
    }
  }

  private static <S extends org.apache.thrift.scheme.IScheme> S scheme(org.apache.thrift.protocol.TProtocol proto) {
    return (org.apache.thrift.scheme.StandardScheme.class.equals(proto.getScheme()) ? STANDARD_SCHEME_FACTORY : TUPLE_SCHEME_FACTORY).getScheme();
  }
}


text:
package org.analogweb.core;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;

import org.analogweb.InvocationArguments;
import org.analogweb.InvocationMetadata;
import org.analogweb.MediaType;
import org.analogweb.RequestContext;
import org.analogweb.RequestValueResolver;
import org.analogweb.RequestValueResolvers;
import org.analogweb.TypeMapperContext;
import org.analogweb.annotation.RequestFormats;
import org.analogweb.annotation.Resolver;
import org.analogweb.util.AnnotationUtils;
import org.analogweb.util.ArrayUtils;

/**
 * @author snowgoose
 */
public class ConsumesMediaTypeVerifier extends AbstractApplicationProcessor {

	@Override
	public Object prepareInvoke(InvocationArguments args,
			InvocationMetadata metadata, RequestContext context,
			TypeMapperContext converters, RequestValueResolvers resolvers) {
		if (context.getRequestMethod().equalsIgnoreCase("GET")) {
			return NO_INTERRUPTION;
		}
		Method method = metadata.resolveMethod();
		if (method == null) {
			return NO_INTERRUPTION;
		}
		Annotation[] ann = method.getAnnotations();
		RequestFormats formats = AnnotationUtils.findAnnotation(
				RequestFormats.class, ann);
		MediaType contentType = context.getContentType();
		if (contentType == null) {
			throw new UnsupportedMediaTypeException(metadata.getDefinedPath());
		}
		String[] expectMimes;
		if (formats == null
				|| ArrayUtils.isEmpty(expectMimes = formats.value())) {
			if (mediaTypeUnsupported(contentType, method, resolvers)) {
				throw new UnsupportedMediaTypeException(
						metadata.getDefinedPath());
			}
		} else {
			for (String expectMime : expectMimes) {
				if (contentType.isCompatible(MediaTypes.valueOf(expectMime))) {
					return super.prepareInvoke(args, metadata, context,
							converters, resolvers);
				}
			}
			throw new UnsupportedMediaTypeException(metadata.getDefinedPath());
		}
		return super.prepareInvoke(args, metadata, context, converters,
				resolvers);
	}

	private boolean mediaTypeUnsupported(MediaType contentType, Method method,
			RequestValueResolvers handlers) {
		Annotation[][] parameterAnn = method.getParameterAnnotations();
		for (Annotation[] pa : parameterAnn) {
			Resolver by = AnnotationUtils.findAnnotation(Resolver.class, pa);
			if (by != null) {
				RequestValueResolver ha = handlers.findRequestValueResolver(by
						.value());
				if (ha instanceof SpecificMediaTypeRequestValueResolver
						&& ((SpecificMediaTypeRequestValueResolver) ha)
								.supports(contentType) == false) {
					return true;
				}
			}
		}
		return false;
	}

	@Override
	public int getPrecedence() {
		return 1;
	}
}


text:
package org.ovirt.mobile.movirt.ui.auth.connectionsettings;

import android.os.Parcel;
import android.os.Parcelable;

public class LoginInfo implements Parcelable {
    public String endpoint;
    public String username;
    public String password;
    public boolean adminPrivileges;

    public LoginInfo(String endpoint, String username, String password, boolean adminPrivileges) {
        this.endpoint = endpoint;
        this.username = username;
        this.password = password;
        this.adminPrivileges = adminPrivileges;
    }

    public LoginInfo(Parcel parcel) {
        this.endpoint = parcel.readString();
        this.username = parcel.readString();
        this.password = parcel.readString();
        this.adminPrivileges = parcel.readInt() != 0;
    }

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeString(endpoint);
        dest.writeString(username);
        dest.writeString(password);
        dest.writeInt(adminPrivileges ? 1 : 0);
    }

    public static final Creator<LoginInfo> CREATOR = new Creator<LoginInfo>() {
        public LoginInfo createFromParcel(Parcel source) {
            return new LoginInfo(source);
        }

        public LoginInfo[] newArray(int size) {
            return new LoginInfo[size];
        }
    };
}


text:
#ifndef SEC_PROT_H_
#define SEC_PROT_H_

/*
 * Interface between KMP API and key management security protocols. Interface
 * provides abstraction for different security protocols for KMP API module.
 *
 * For security protocols it provides access to network, timing, callback
 * security keys and network address services.
 *
 */

typedef enum {
    SEC_RESULT_OK = 0,
    SEC_RESULT_ERR_NO_MEM = -1,
    SEC_RESULT_ERR_TX_NO_ACK = -2,
    SEC_RESULT_ERR_UNSPEC = -3,
    SEC_RESULT_TIMEOUT = -4,
    SEC_RESULT_ERROR = -5,
    SEC_RESULT_CONF_ERROR = -6
} sec_prot_result_e;

typedef enum {
    SEC_STATE_INIT = 0,
    SEC_STATE_CREATE_REQ,
    SEC_STATE_CREATE_RESP,
    SEC_STATE_CREATE_IND,
    SEC_STATE_FINISH,
    SEC_STATE_FINISHED,
    SEC_STATE_FIRST
} sec_prot_state_e;

typedef enum {
    SEC_PROT_TYPE_EAP_TLS = 0,
    SEC_PROT_TYPE_TLS
} sec_prot_type_e;

typedef enum {
    SEC_PROT_TX_OK = 0,                       // Successful
    SEC_PROT_TX_ERR_TX_NO_ACK = -1,           // No acknowledge was received
    SEC_PROT_TX_ERR_UNSPEC = -2,              // Other reason
} sec_prot_tx_status_e;

/**
 * sec_prot_create_request KMP-CREATE.request to security protocol
 *
 * \param prot protocol
 * \param sec_keys security keys
 *
 */
typedef void sec_prot_create_request(sec_prot_t *prot, sec_prot_keys_t *sec_keys);

/**
 * sec_prot_create_response KMP-CREATE.response from security protocol
 *
 * \param prot protocol
 * \param result result
 *
 */
typedef void sec_prot_create_response(sec_prot_t *prot, sec_prot_result_e result);

/**
 * sec_prot_create_confirm KMP-CREATE.confirm from security protocol
 *
 * \param prot protocol
 * \param result result
 *
 */
typedef void sec_prot_create_confirm(sec_prot_t *prot, sec_prot_result_e result);

/**
 * sec_prot_create_indication KMP-CREATE.indication from security protocol
 *
 * \param prot protocol
 *
 */
typedef void sec_prot_create_indication(sec_prot_t *prot);

/**
 * sec_prot_finished_indication KMP-FINISHED.indication from security protocol
 *
 * \param prot protocol
 * \param result result
 * \param sec_keys security keys
 *
 */
typedef void sec_prot_finished_indication(sec_prot_t *prot, sec_prot_result_e result, sec_prot_keys_t *sec_keys);

/**
 * sec_prot_finished Security protocol has finished and is ready for delete
 *
 * \param prot protocol
 *
 */
typedef void sec_prot_finished(sec_prot_t *prot);

/**
 * sec_prot_finished_send Security protocol finished send
 *
 * \param prot protocol
 *
 */
typedef void sec_prot_finished_send(sec_prot_t *prot);

/**
 * sec_prot_receive receive a message
 *
 * \param prot protocol
 * \param pdu pdu
 * \param size pdu size
 *
 * \return < 0 failure
 * \return >= 0 success
 *
 */
typedef int8_t sec_prot_receive(sec_prot_t *prot, void *pdu, uint16_t size);

/**
 * sec_prot_send send a message
 *
 * \param prot protocol
 * \param pdu pdu
 * \param size pdu size
 *
 * \return < 0 failure
 * \return >= 0 success
 *
 */
typedef int8_t sec_prot_send(sec_prot_t *prot, void *pdu, uint16_t size);

/**
 * sec_prot_tx_status_ind tx status indication
 *
 * \param prot protocol
 * \param tx_status tx status
 *
 * \return < 0 failure
 * \return >= 0 success
 *
 */
typedef int8_t sec_prot_tx_status_ind(sec_prot_t *prot, sec_prot_tx_status_e tx_status);

/**
 * sec_prot_delete delete the protocol data
 *
 * \param prot protocol
 *
 */
typedef void sec_prot_delete(sec_prot_t *prot);

/**
 * sec_prot_state_machine protocol state machine
 *
 * \param prot protocol
 *
 */
typedef void sec_prot_state_machine(sec_prot_t *prot);

/**
 * sec_prot_state_machine_call call protocol state machine
 *
 * \param prot protocol
 *
 */
typedef void sec_prot_state_machine_call(sec_prot_t *prot);

/**
 * sec_prot_timer_start start timer
 *
 * \param prot protocol
 *
 */
typedef void sec_prot_timer_start(sec_prot_t *prot);

/**
 * sec_prot_timer_stop stop timer
 *
 * \param prot protocol
 *
 */
typedef void sec_prot_timer_stop(sec_prot_t *prot);

/**
 * sec_prot_timer_timeout timer timeout
 *
 * \param prot protocol
 * \param ticks timer ticks
 *
 */
typedef void sec_prot_timer_timeout(sec_prot_t *prot, uint16_t ticks);

/**
 * sec_prot_eui64_addr_get gets EUI-64 addresses
 *
 * \param prot protocol
 * \param local_eui64 local EUI-64
 * \param remote_eui64 remote EUI-64
 *
 */
typedef void sec_prot_eui64_addr_get(sec_prot_t *prot, uint8_t *local_eui64, uint8_t *remote_eui64);

/**
 * sec_prot_by_type_get gets security protocol
 *
 * \param prot protocol
 * \param type security protocol type
 *
 * \return security protocol or NULL
 *
 */
typedef sec_prot_t *sec_prot_by_type_get(sec_prot_t *prot, uint8_t type);

/**
 * sec_prot_receive_disable disables receiving of messages
 *
 * \param prot protocol
 *
 * \return security protocol or NULL
 *
 */
typedef void sec_prot_receive_disable(sec_prot_t *prot);

typedef struct sec_prot_int_data_s sec_prot_int_data_t;

// Security protocol data
struct sec_prot_s {
    sec_prot_create_request       *create_req;           /**< Create request */
    sec_prot_create_response      *create_resp;          /**< Create response */

    sec_prot_create_confirm       *create_conf;          /**< Create confirm */
    sec_prot_create_indication    *create_ind;           /**< Create indication */
    sec_prot_finished_indication  *finished_ind;         /**< Finished indication */
    sec_prot_finished             *finished;             /**< Finished i.e. ready to be deleted */
    sec_prot_finished_send        *finished_send;        /**< Send finished */

    sec_prot_send                 *send;                 /**< Protocol send */
    sec_prot_receive              *receive;              /**< Protocol receive */
    sec_prot_tx_status_ind        *tx_status_ind;        /**< TX status indication */

    sec_prot_delete               *delete;               /**< Protocol delete */

    sec_prot_state_machine_call   *state_machine_call;   /**< Call state machine */
    sec_prot_state_machine        *state_machine;        /**< Protocol state machine */

    sec_prot_timer_start          *timer_start;          /**< Start timer */
    sec_prot_timer_stop           *timer_stop;           /**< Stop timer */
    sec_prot_timer_timeout        *timer_timeout;        /**< Timer timeout */

    sec_prot_eui64_addr_get       *addr_get;             /**< Gets EUI-64 addresses */
    sec_prot_by_type_get          *type_get;             /**< Gets security protocol by type */
    sec_prot_receive_disable      *receive_disable;      /**< Disable receiving of messages */

    sec_prot_keys_t               *sec_keys;             /**< Security keys storage pointer */
    uint8_t                       header_size;           /**< Header size */
    sec_prot_int_data_t           *data;                 /**< Protocol internal data */
};

#endif /* SEC_PROT_H_ */


text:
{% each %}
  {% if type != "enum" %}
#include "../include/{{ filename }}.h"
  {% endif %}
{% endeach %}

extern "C" void init(Handle<v8::Object> target) {
  NanScope();

  Wrapper::InitializeComponent(target);
  {%each%}
    {% if type != "enum" %}
  {{ cppClassName }}::InitializeComponent(target);
    {% endif %}
  {%endeach%}
}

NODE_MODULE(nodegit, init)


text:
import endpoints
import os
import werkzeug

not_found_app = werkzeug.exceptions.NotFound()

url_map = werkzeug.routing.Map([
    werkzeug.routing.Rule('/', endpoint='index.html'),
])

static_path = endpoints.settings.static_path

def application(environ, start_response):
    adapter = url_map.bind_to_environ(environ)
    try:
        endpoint, values = adapter.match()
    except:
        return not_found_app(environ, start_response)
    else:
        file_path = os.path.join(static_path, endpoint)
        f = open(file_path)
        response = werkzeug.wrappers.Response(werkzeug.wsgi.wrap_file(environ, f), mimetype="text/html")
        return response(environ, start_response)

application = werkzeug.wsgi.SharedDataMiddleware(application, dict([endpoints.static_endpoint]))
application = werkzeug.wsgi.DispatcherMiddleware(application, endpoints.wsgi_endpoints)


text:
#ifndef LIST_H
#define LIST_H

/*
 * Comparision functions for searching list.
 */

typedef LONG (FNLISTCOMPARE)(PVOID, PVOID);
typedef FNLISTCOMPARE *PFNLISTCOMPARE;

/*
 * Create or destroy a list.
 */

extern PVOID ShrGenericListNew(PFNLISTCOMPARE pfnCompare);
extern PVOID ShrExactStringListNew(void);
extern PVOID ShrStringListNew(void);
extern PVOID ShrValueListNew(void);

extern BOOL ShrListFree(PVOID pListParm);

/*
 * Add an item to a list.
 */

extern BOOL ShrListAddLast(PVOID pListParm, PVOID pValue);
extern BOOL ShrListAddFirst(PVOID pListParm, PVOID pValue);
extern BOOL ShrListAddBefore
    (PVOID pListParm, PVOID pValue, PVOID pBeforeValue);
extern BOOL ShrListAddAfter
    (PVOID pListParm, PVOID pValue, PVOID pAfterValue);

/*
 * Remove an item from list.
 */

extern BOOL ShrListRemove(PVOID pListParm, PVOID pValue);
extern PVOID ShrListRemoveFirst(PVOID pListParm);
extern BOOL ShrListRemoveAll(PVOID pListParm);

/*
 * Enumerate items in a list.
 */

extern PVOID ShrListBeginEnum(PVOID pListParm);
extern BOOL ShrListEndEnum(PVOID pListParm, PVOID pListEnum);
extern BOOL ShrListNext
    (PVOID pListParm, PVOID pListEnum, PVOID *ppValue);

/*
 * List statistics.
 */

extern ULONG ShrListCount(PVOID pListParm);

/*
 * Membership.
 */

extern BOOL ShrListIncludes(PVOID pListParm, PVOID pValue);

#endif


text:
<widget id='http://tizen.org/test/wrt-rtbin-tizen-tests' xmlns='http://www.w3.org/ns/widgets' xmlns:tizen='http://tizen.org/ns/widgets'>
  <access origin="*"/>
  <icon src="icon.png" height="117" width="117"/>
  <name>wrt-rtbin-tizen-tests</name>
  <tizen:application id="ypbwwcontm.wrtrtbinautotizentests" package="ypbwwcontm" required_version="2.2"/>
  <tizen:setting screen-orientation="landscape"/>
</widget>


text:
package org.springframework.social.facebook.api.impl.json;

import java.io.IOException;
import java.util.Collections;
import java.util.List;

import org.springframework.social.facebook.api.Comment;
import org.springframework.social.facebook.api.ListAndCount;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

class CommentListAndCountDeserializer extends JsonDeserializer<ListAndCount<Comment>> {

	@SuppressWarnings("unchecked")
	@Override
	public ListAndCount<Comment> deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException {
		ObjectMapper mapper = new ObjectMapper();
		mapper.registerModule(new FacebookModule());
		jp.setCodec(mapper);
		if(jp.hasCurrentToken()) {
			JsonNode commentsNode = jp.readValueAs(JsonNode.class);
			JsonNode dataNode = commentsNode.get("data");
			List<Comment> commentsList = dataNode != null ?
					(List<Comment>) mapper.reader(new TypeReference<List<Comment>>() {}).readValue(dataNode) :
					Collections.<Comment>emptyList();
			return new ListAndCount<Comment>(commentsList, commentsList.size());
		}

		return null;
	}
}


text:
const {sortBy} = require('../../Array');

const AbilityContext = require('../AbilityContext.js');
const BaseStep = require('./basestep.js');
const GameKeywords = require('../gamekeywords.js');

const challengeKeywords = ['insight', 'intimidate', 'pillage', 'renown'];

class KeywordWindow extends BaseStep {
    constructor(game, challenge) {
        super(game);
        this.challenge = challenge;
        this.winnerCardsWithContext = challenge.getWinnerCards().map(card => {
            return { card: card, context: new AbilityContext({ player: this.challenge.winner, game: this.game, challenge: this.challenge, source: card }) };
        });
        this.firstPlayer = game.getFirstPlayer();
        this.remainingKeywords = challengeKeywords;
    }

    continue() {
        if(!this.challenge.winner) {
            return true;
        }

        if(this.firstPlayer.keywordSettings.chooseOrder && this.remainingKeywords.length > 1) {
            this.promptForKeywordOrder();
            return false;
        }

        this.processRemainingInAutomaticOrder();

        return true;
    }

    promptForKeywordOrder() {
        let buttons = this.remainingKeywords.map(keyword => {
            return { text: GameKeywords[keyword].title, arg: keyword, method: 'chooseKeyword' };
        });
        this.game.promptWithMenu(this.firstPlayer, this, {
            activePrompt: {
                menuTitle: 'Choose keyword order',
                buttons: [
                    { text: 'Automatic', arg: 'automatic', method: 'chooseKeyword' }
                ].concat(sortBy(buttons, button => button.title))
            },
            waitingPromptTitle: 'Waiting for first player to choose keyword order'
        });
    }

    chooseKeyword(player, keyword) {
        if(keyword === 'automatic') {
            this.processRemainingInAutomaticOrder();
            return true;
        }

        this.applyKeyword(keyword);
        this.remainingKeywords = this.remainingKeywords.filter(k => k !== keyword);
        return true;
    }

    processRemainingInAutomaticOrder() {
        while(this.remainingKeywords.length !== 0) {
            let keyword = this.remainingKeywords[0];
            this.applyKeyword(keyword);
            this.remainingKeywords = this.remainingKeywords.slice(1);
        }
    }

    applyKeyword(keyword) {
        let ability = GameKeywords[keyword];
        let participantsWithKeyword = this.getParticipantsForKeyword(keyword, ability);

        if(participantsWithKeyword.length === 0) {
            return;
        }

        if(this.challenge.winner.keywordSettings.chooseCards) {
            let cards = participantsWithKeyword.map(participant => participant.card);
            this.game.promptForSelect(this.challenge.winner, {
                mode: 'unlimited',
                ordered: true,
                activePromptTitle: 'Select ' + keyword + ' cards',
                cardCondition: card => cards.includes(card),
                onSelect: (player, selectedCards) => {
                    let finalParticipants = selectedCards.map(card => participantsWithKeyword.find(participant => participant.card === card));

                    this.resolveAbility(ability, finalParticipants);
                    this.game.checkWinCondition(this.challenge.winner);

                    return true;
                }
            });
        } else {
            if(keyword === 'pillage' && participantsWithKeyword.length > 1) {
                this.promptForPillageOrder(ability, participantsWithKeyword);
            } else {
                this.resolveAbility(ability, participantsWithKeyword);
            }

            this.game.checkWinCondition(this.challenge.winner);
        }
    }

    getParticipantsForKeyword(keyword, ability) {
        let participants = this.winnerCardsWithContext.filter(participant => {
            return participant.card.hasKeyword(keyword) && ability.meetsRequirements(participant.context);
        });

        if(keyword === 'intimidate' && participants.length > 0) {
            return [participants[0]];
        }

        return participants;
    }

    promptForPillageOrder(ability, participants) {
        let cards = participants.map(participant => participant.card);
        this.game.promptForSelect(this.challenge.winner, {
            ordered: true,
            mode: 'exactly',
            numCards: participants.length,
            activePromptTitle: 'Select order for pillage',
            cardCondition: card => cards.includes(card),
            onSelect: (player, selectedCards) => {
                let finalParticipants = selectedCards.map(card => participants.find(participant => participant.card === card));

                this.resolveAbility(ability, finalParticipants);

                return true;
            },
            onCancel: () => {
                this.resolveAbility(ability, participants);
                return true;
            }
        });
    }

    resolveAbility(ability, participants) {
        for(let participant of participants) {
            this.game.resolveAbility(ability, participant.context);
        }
    }
}

module.exports = KeywordWindow;


text:
<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

namespace PhalexTest\Mvc;

use PHPUnit_Framework_TestCase as TestCase;
use Phalex\Mvc\Dispatcher;
use Phalex\Di\Di;
use Phalcon\Events\Manager as EventsManager;
use Phalcon\Mvc\Dispatcher as PhalconDispatcher;

/**
 * Description of DispatcherTest
 *
 * @author quangtm
 */
class DispatcherTest extends TestCase
{
    public function testConstructor()
    {
        $di         = new Di(require './tests/config/config.result.php');
        $dispatcher = new Dispatcher($di);
        $this->assertInstanceOf(PhalconDispatcher::class, $dispatcher);
        $di2 = $dispatcher->getDI();
        $this->assertInstanceOf(Di::class, $di2);
        $this->assertTrue(isset($di2['eventsManager']));
        $this->assertInstanceOf(EventsManager::class, $di2->get('eventsManager'));
    }
}


text:
using System.Linq;
using System.Threading.Tasks;

using Microsoft.EntityFrameworkCore;

using Modix.Data.ExpandableQueries;
using Modix.Data.Models.Core;

namespace Modix.Data.Repositories
{
    /// <summary>
    /// Describes a repository for managing <see cref="ConfigurationActionEntity"/> entities, within an underlying data storage provider.
    /// </summary>
    public interface IConfigurationActionRepository
    {
        /// <summary>
        /// Retrieves information about a configuration action, based on its ID.
        /// </summary>
        /// <param name="actionId">The <see cref="ModerationActionEntity.Id"/> value of the configuration action to be retrieved.</param>
        /// <returns>
        /// A <see cref="Task"/> which will complete when the operation is complete,
        /// containing the requested configuration action, or null if no such configuration action exists.
        /// </returns>
        Task<ConfigurationActionSummary> ReadAsync(long actionId);
    }

    /// <inheritdoc />
    public class ConfigurationActionRepository : RepositoryBase, IConfigurationActionRepository
    {
        /// <summary>
        /// Constructs a new <see cref="ConfigurationActionRepository"/> from the given dependencies.
        /// See <see cref="RepositoryBase"/> for details.
        /// </summary>
        public ConfigurationActionRepository(ModixContext modixContext)
            : base(modixContext) { }

        /// <inheritdoc />
        public Task<ConfigurationActionSummary> ReadAsync(long actionId)
            => ModixContext.ConfigurationActions.AsNoTracking()
                .AsExpandable()
                .Select(ConfigurationActionSummary.FromEntityProjection)
                .FirstOrDefaultAsync(x => x.Id == actionId);
    }
}


text:
/* Ensure classes are prefixed. */
.something {
  font-size: 40px;
}

/* Ensure child selectors are kept. */
.something p {
  color: red;
}


text:
class Build < ActiveRecord::Base
  attr_accessible :build_number, :skipped_test, :total_test, :authors, :project, :change_sets, :total_changes, :java_changes, :test_changes
  belongs_to :project
  has_many :change_sets
  has_many :authors
end


text:
using Demo.Features.Screens;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Input;
using MonoGame.Extended.Screens;

namespace Demo.Features.Demos
{
    public class ScreensDemo : DemoBase
    {
        public override string Name => "Screens";

        public ScreensDemo(GameMain game) : base(game)
        {
            ScreenGameComponent screenGameComponent;
            Components.Add(screenGameComponent = new ScreenGameComponent(game));

            screenGameComponent.Register(new MainMenuScreen(game.Services, game));
            screenGameComponent.Register(new LoadGameScreen(game.Services));
            screenGameComponent.Register(new OptionsScreen(game.Services));
            screenGameComponent.Register(new AudioOptionsScreen(game.Services));
            screenGameComponent.Register(new VideoOptionsScreen(game.Services));
            screenGameComponent.Register(new KeyboardOptionsScreen(game.Services));
            screenGameComponent.Register(new MouseOptionsScreen(game.Services));
        }

        protected override void Update(GameTime gameTime)
        {
            var keyboardState = Keyboard.GetState();

            if (keyboardState.IsKeyDown(Keys.Escape))
                Exit();

            base.Update(gameTime);
        }

        protected override void Draw(GameTime gameTime)
        {
            base.Draw(gameTime);
        }
    }
}


text:
/**
 * @author Pavel Dolgov
 */
package org.apache.harmony.awt.wtk;

import junit.framework.TestCase;

public class ShutdownThreadTest extends TestCase {

    private ShutdownThread t;

    public static void main(String[] args) {
        junit.textui.TestRunner.run(ShutdownThreadTest.class);
    }

    @Override
    protected void setUp() throws Exception {
        super.setUp();
        t = new ShutdownThread();
    }

    public void testStartAndShutdown() {
        assertFalse(t.isAlive());
        t.start();
        assertTrue(t.isAlive());
        t.shutdown();
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        assertFalse(t.isAlive());
    }
}


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

<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Custom Container - Scalable boundries with custom corners</title>

Color Calculator

This script displays uses images to create dynamic round corner call outs. Paste your text in the textarea below can view the availabel option

<textarea name="textBox" id="textBox"></textarea>
<button type="button" onClick="updateT();">Update</button>
<button type="button" onClick="wide();"><-Wide -></button>
<button type="button" onClick="standard();">Standard</button>
<button type="button" onClick="narrow();">-> Narrow <-</button>


text:
package com.lambdaworks.redis.masterslave;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.lambdaworks.redis.RedisException;
import com.lambdaworks.redis.RedisURI;
import com.lambdaworks.redis.api.StatefulRedisConnection;
import com.lambdaworks.redis.internal.LettuceAssert;
import com.lambdaworks.redis.models.role.RedisInstance;
import com.lambdaworks.redis.models.role.RedisNodeDescription;

import io.netty.util.internal.logging.InternalLogger;
import io.netty.util.internal.logging.InternalLoggerFactory;

/**
 * Topology provider using Redis Standalone and the {@code INFO REPLICATION} output. Slaves are listed as {@code slaveN=...}
 * entries.
 *
 * @author Mark Paluch
 * @since 4.1
 */
public class MasterSlaveTopologyProvider implements TopologyProvider {

    public static final Pattern ROLE_PATTERN = Pattern.compile("^role\\:([a-z]+)$", Pattern.MULTILINE);
    public static final Pattern SLAVE_PATTERN = Pattern.compile("^slave(\\d+)\\:([a-zA-Z\\,\\=\\d\\.\\:]+)$", Pattern.MULTILINE);
    public static final Pattern MASTER_HOST_PATTERN = Pattern.compile("^master_host\\:([a-zA-Z\\,\\=\\d\\.\\:\\-]+)$",
            Pattern.MULTILINE);
    public static final Pattern MASTER_PORT_PATTERN = Pattern.compile("^master_port\\:(\\d+)$", Pattern.MULTILINE);
    public static final Pattern IP_PATTERN = Pattern.compile("ip\\=([a-zA-Z\\d\\.\\:]+)");
    public static final Pattern PORT_PATTERN = Pattern.compile("port\\=([\\d]+)");

    private static final InternalLogger logger = InternalLoggerFactory.getInstance(MasterSlaveTopologyProvider.class);

    private final StatefulRedisConnection<?, ?> connection;
    private final RedisURI redisURI;

    /**
     * Creates a new {@link MasterSlaveTopologyProvider}.
     *
     * @param connection must not be {@literal null}
     * @param redisURI must not be {@literal null}
     */
    public MasterSlaveTopologyProvider(StatefulRedisConnection<?, ?> connection, RedisURI redisURI) {

        LettuceAssert.notNull(connection, "Redis Connection must not be null");
        LettuceAssert.notNull(redisURI, "RedisURI must not be null");

        this.connection = connection;
        this.redisURI = redisURI;
    }

    @Override
    public List<RedisNodeDescription> getNodes() {

        logger.debug("Performing topology lookup");

        String info = connection.sync().info("replication");
        try {
            return getNodesFromInfo(info);
        } catch (RuntimeException e) {
            throw new RedisException(e);
        }
    }

    protected List<RedisNodeDescription> getNodesFromInfo(String info) {
        List<RedisNodeDescription> result = new ArrayList<>();

        RedisNodeDescription currentNodeDescription = getCurrentNodeDescription(info);

        result.add(currentNodeDescription);

        if (currentNodeDescription.getRole() == RedisInstance.Role.MASTER) {
            result.addAll(getSlavesFromInfo(info));
        } else {
            result.add(getMasterFromInfo(info));
        }

        return result;
    }

    private RedisNodeDescription getCurrentNodeDescription(String info) {

        Matcher matcher = ROLE_PATTERN.matcher(info);

        if (!matcher.find()) {
            throw new IllegalStateException("No role property in info " + info);
        }

        return getRedisNodeDescription(matcher);
    }

    private List<RedisNodeDescription> getSlavesFromInfo(String info) {

        List<RedisNodeDescription> slaves = new ArrayList<>();

        Matcher matcher = SLAVE_PATTERN.matcher(info);
        while (matcher.find()) {

            String group = matcher.group(2);
            String ip = getNested(IP_PATTERN, group, 1);
            String port = getNested(PORT_PATTERN, group, 1);

            slaves.add(new RedisMasterSlaveNode(ip, Integer.parseInt(port), redisURI, RedisInstance.Role.SLAVE));
        }

        return slaves;
    }

    private RedisNodeDescription getMasterFromInfo(String info) {

        Matcher masterHostMatcher = MASTER_HOST_PATTERN.matcher(info);
        Matcher masterPortMatcher = MASTER_PORT_PATTERN.matcher(info);

        boolean foundHost = masterHostMatcher.find();
        boolean foundPort = masterPortMatcher.find();

        if (!foundHost || !foundPort) {
            throw new IllegalStateException("Cannot resolve master from info " + info);
        }

        String host = masterHostMatcher.group(1);
        int port = Integer.parseInt(masterPortMatcher.group(1));

        return new RedisMasterSlaveNode(host, port, redisURI, RedisInstance.Role.MASTER);
    }

    private String getNested(Pattern pattern, String string, int group) {

        Matcher matcher = pattern.matcher(string);
        if (matcher.find()) {
            return matcher.group(group);
        }

        throw new IllegalArgumentException("Cannot extract group " + group + " with pattern " + pattern + " from " + string);

    }

    private RedisNodeDescription getRedisNodeDescription(Matcher matcher) {

        String roleString = matcher.group(1);
        RedisInstance.Role role = null;

        if (RedisInstance.Role.MASTER.name().equalsIgnoreCase(roleString)) {
            role = RedisInstance.Role.MASTER;
        }

        if (RedisInstance.Role.SLAVE.name().equalsIgnoreCase(roleString)) {
            role = RedisInstance.Role.SLAVE;
        }

        if (role == null) {
            throw new IllegalStateException("Cannot resolve role " + roleString + " to " + RedisInstance.Role.MASTER + " or "
                    + RedisInstance.Role.SLAVE);
        }

        return new RedisMasterSlaveNode(redisURI.getHost(), redisURI.getPort(), redisURI, role);
    }

}


text:
package org.apache.spark.streaming

import org.apache.spark.annotation.Experimental

/**
 * :: Experimental ::
 * Abstract class for getting and updating the state in mapping function used in the `mapWithState`
 * operation of a [[org.apache.spark.streaming.dstream.PairDStreamFunctions pair DStream]] (Scala)
 * or a [[org.apache.spark.streaming.api.java.JavaPairDStream JavaPairDStream]] (Java).
 *
 * Scala example of using `State`:
 * {{{
 *    // A mapping function that maintains an integer state and returns a String
 *    def mappingFunction(key: String, value: Option[Int], state: State[Int]): Option[String] = {
 *      // Check if state exists
 *      if (state.exists) {
 *        val existingState = state.get  // Get the existing state
 *        val shouldRemove = ...         // Decide whether to remove the state
 *        if (shouldRemove) {
 *          state.remove()     // Remove the state
 *        } else {
 *          val newState = ...
 *          state.update(newState)    // Set the new state
 *        }
 *      } else {
 *        val initialState = ...
 *        state.update(initialState)  // Set the initial state
 *      }
 *      ... // return something
 *    }
 *
 * }}}
 *
 * Java example of using `State`:
 * {{{
 *    // A mapping function that maintains an integer state and returns a String
 *    Function3<String, Optional<Integer>, State<Integer>, String> mappingFunction =
 *       new Function3<String, Optional<Integer>, State<Integer>, String>() {
 *
 *         @Override
 *         public String call(String key, Optional<Integer> value, State<Integer> state) {
 *           if (state.exists()) {
 *             int existingState = state.get(); // Get the existing state
 *             boolean shouldRemove = ...; // Decide whether to remove the state
 *             if (shouldRemove) {
 *               state.remove(); // Remove the state
 *             } else {
 *               int newState = ...;
 *               state.update(newState); // Set the new state
 *             }
 *           } else {
 *             int initialState = ...; // Set the initial state
 *             state.update(initialState);
 *           }
 *           // return something
 *         }
 *       };
 * }}}
 *
 * @tparam S Class of the state
 */
@Experimental
sealed abstract class State[S] {

  /** Whether the state already exists */
  def exists(): Boolean

  /**
   * Get the state if it exists, otherwise it will throw `java.util.NoSuchElementException`.
   * Check with `exists()` whether the state exists or not before calling `get()`.
   *
   * @throws java.util.NoSuchElementException If the state does not exist.
   */
  def get(): S

  /**
   * Update the state with a new value.
   *
   * State cannot be updated if it has been already removed (that is, `remove()` has already been
   * called) or it is going to be removed due to timeout (that is, `isTimingOut()` is `true`).
   *
   * @throws java.lang.IllegalArgumentException If the state has already been removed, or is
   *                                            going to be removed
   */
  def update(newState: S): Unit

  /**
   * Remove the state if it exists.
   *
   * State cannot be updated if it has been already removed (that is, `remove()` has already been
   * called) or it is going to be removed due to timeout (that is, `isTimingOut()` is `true`).
   */
  def remove(): Unit

  /**
   * Whether the state is timing out and going to be removed by the system after the current batch.
   * This timeout can occur if timeout duration has been specified in the
   * [[org.apache.spark.streaming.StateSpec StatSpec]] and the key has not received any new data
   * for that timeout duration.
   */
  def isTimingOut(): Boolean

  /**
   * Get the state as a `scala.Option`. It will be `Some(state)` if it exists, otherwise `None`.
   */
  @inline final def getOption(): Option[S] = if (exists) Some(get()) else None

  @inline final override def toString(): String = {
    getOption.map { _.toString }.getOrElse("<state not set>")
  }
}

/** Internal implementation of the [[State]] interface */
private[streaming] class StateImpl[S] extends State[S] {

  private var state: S = null.asInstanceOf[S]
  private var defined: Boolean = false
  private var timingOut: Boolean = false
  private var updated: Boolean = false
  private var removed: Boolean = false

  // ========= Public API =========
  override def exists(): Boolean = {
    defined
  }

  override def get(): S = {
    if (defined) {
      state
    } else {
      throw new NoSuchElementException("State is not set")
    }
  }

  override def update(newState: S): Unit = {
    require(!removed, "Cannot update the state after it has been removed")
    require(!timingOut, "Cannot update the state that is timing out")
    state = newState
    defined = true
    updated = true
  }

  override def isTimingOut(): Boolean = {
    timingOut
  }

  override def remove(): Unit = {
    require(!timingOut, "Cannot remove the state that is timing out")
    require(!removed, "Cannot remove the state that has already been removed")
    defined = false
    updated = false
    removed = true
  }

  // ========= Internal API =========

  /** Whether the state has been marked for removing */
  def isRemoved(): Boolean = {
    removed
  }

  /** Whether the state has been updated */
  def isUpdated(): Boolean = {
    updated
  }

  /**
   * Update the internal data and flags in `this` to the given state option.
   * This method allows `this` object to be reused across many state records.
   */
  def wrap(optionalState: Option[S]): Unit = {
    optionalState match {
      case Some(newState) =>
        this.state = newState
        defined = true

      case None =>
        this.state = null.asInstanceOf[S]
        defined = false
    }
    timingOut = false
    removed = false
    updated = false
  }

  /**
   * Update the internal data and flags in `this` to the given state that is going to be timed out.
   * This method allows `this` object to be reused across many state records.
   */
  def wrapTimingOutState(newState: S): Unit = {
    this.state = newState
    defined = true
    timingOut = true
    removed = false
    updated = false
  }
}