text:
import urllib2, json, re, random, sys

# Makes a request to a given URL (first argument) and optional params (second argument)
def make_request(*args):
    opener = urllib2.build_opener()
    opener.addheaders = [('User-agent', 'Mozilla/5.0'+str(random.randrange(1000000)))]
    try:
        return opener.open(*args).read().strip()
    except Exception,e:
        try: p = e.read().strip()
        except: p = e
        raise Exception(p)

# Gets the unspent outputs of one or more addresses
def unspent(*args):
    # Valid input formats: unspent([addr1, addr2,addr3])
    #                      unspent(addr1, addr2, addr3)
    if len(args) == 0: return []
    elif isinstance(args[0],list): addrs = args[0]
    else: addrs = args
    u = []
    for addr in addrs:
        try: data = make_request('https://blockchain.info/unspent?address='+addr)
        except Exception,e:
            if str(e) == 'No free outputs to spend': continue
            else: raise Exception(e)
        try:
            jsonobj = json.loads(data)
            #print 'd',data
            for o in jsonobj["unspent_outputs"]:
                h = o['tx_hash'].decode('hex')[::-1].encode('hex')
                u.append({
                    "output": h+':'+str(o['tx_output_n']),
                    "value": o['value']
                })
        except:
            raise Exception("Failed to decode data: "+data)
    return u

def blockr_unspent(*args):
    # Valid input formats: blockr_unspent([addr1, addr2,addr3])
    #                      blockr_unspent(addr1, addr2, addr3)
    #                      blockr_unspent([addr1, addr2, addr3], network)
    #                      blockr_unspent(addr1, addr2, addr3, network)
    # Where network is 'btc' or 'testnet'

    network = 'btc'
    addr_args = args
    if len(args) >= 1 and args[-1] in ('testnet', 'btc'):
        network = args[-1]
        addr_args = args[:-1]

    if network == 'testnet':
        blockr_url = 'https://tbtc.blockr.io/api/v1/address/unspent/'
    elif network == 'btc':
        blockr_url = 'https://btc.blockr.io/api/v1/address/unspent/'
    else:
        raise Exception('Unsupported network {0} for blockr_unspent'.format(network))

    if len(addr_args) == 0: return []
    elif isinstance(addr_args[0],list): addrs = addr_args[0]
    else: addrs = addr_args
    res = make_request(blockr_url+','.join(addrs))
    data = json.loads(res)['data']
    o = []
    if 'unspent' in data: data = [data]
    for dat in data:
        for u in dat['unspent']:
            o.append({
                "output": u['tx']+':'+str(u['n']),
                "value": int(u['amount'].replace('.',''))
            })
    return o

# Gets the transaction output history of a given set of addresses,
# including whether or not they have been spent
def history(*args):
    # Valid input formats: history([addr1, addr2,addr3])
    #                      history(addr1, addr2, addr3)
    if len(args) == 0: return []
    elif isinstance(args[0],list): addrs = args[0]
    else: addrs = args

    txs = []
    for addr in addrs:
        offset = 0
        while 1:
            data = make_request('https://blockchain.info/address/%s?format=json&offset=%s' % (addr,offset))
            try:
                jsonobj = json.loads(data)
            except:
                raise Exception("Failed to decode data: "+data)
            txs.extend(jsonobj["txs"])
            if len(jsonobj["txs"]) < 50: break
            offset += 50
            sys.stderr.write("Fetching more transactions... "+str(offset)+'\n')
    outs = {}
    for tx in txs:
        for o in tx["out"]:
            if o['addr'] in addrs:
                key = str(tx["tx_index"])+':'+str(o["n"])
                outs[key] = {
                    "address" : o["addr"],
                    "value" : o["value"],
                    "output" : tx["hash"]+':'+str(o["n"]),
                    "block_height" : tx.get("block_height",None)
                }
    for tx in txs:
        for i, inp in enumerate(tx["inputs"]):
            if inp["prev_out"]["addr"] in addrs:
                key = str(inp["prev_out"]["tx_index"])+':'+str(inp["prev_out"]["n"])
                if outs.get(key): outs[key]["spend"] = tx["hash"]+':'+str(i)
    return [outs[k] for k in outs]

# Pushes a transaction to the network using https://blockchain.info/pushtx
def pushtx(tx):
    if not re.match('^[0-9a-fA-F]*$',tx): tx = tx.encode('hex')
    return make_request('https://blockchain.info/pushtx','tx='+tx)

def eligius_pushtx(tx):
    if not re.match('^[0-9a-fA-F]*$',tx): tx = tx.encode('hex')
    s = make_request('http://eligius.st/~wizkid057/newstats/pushtxn.php','transaction='+tx+'&send=Push')
    strings = re.findall('string[^"]*"[^"]*"',s)
    for string in strings:
        quote = re.findall('"[^"]*"',string)[0]
        if len(quote) >= 5: return quote[1:-1]

def blockr_pushtx(tx, network='btc'):

    if network == 'testnet':
        blockr_url = 'https://tbtc.blockr.io/api/v1/tx/push'
    elif network == 'btc':
        blockr_url = 'https://btc.blockr.io/api/v1/tx/push'
    else:
        raise Exception('Unsupported network {0} for blockr_pushtx'.format(network))

    if not re.match('^[0-9a-fA-F]*$', tx): tx = tx.encode('hex')
    return make_request(blockr_url, '{"hex":"%s"}' % tx)

def last_block_height():
    data = make_request('https://blockchain.info/latestblock')
    jsonobj = json.loads(data)
    return jsonobj["height"]

# Gets a specific transaction
def bci_fetchtx(txhash):
    if not re.match('^[0-9a-fA-F]*$',txhash): txhash = txhash.encode('hex')
    data = make_request('https://blockchain.info/rawtx/'+txhash+'?format=hex')
    return data

def blockr_fetchtx(txhash, network='btc'):

    if network == 'testnet':
        blockr_url = 'https://tbtc.blockr.io/api/v1/tx/raw/'
    elif network == 'btc':
        blockr_url = 'https://btc.blockr.io/api/v1/tx/raw/'
    else:
        raise Exception('Unsupported network {0} for blockr_fetchtx'.format(network))

    if not re.match('^[0-9a-fA-F]*$',txhash): txhash = txhash.encode('hex')
    jsondata = json.loads(make_request(blockr_url+txhash))
    return jsondata['data']['tx']['hex']

def fetchtx(txhash):
    try: return bci_fetchtx(txhash)
    except: return blockr_fetchtx(txhash)

def firstbits(address):
    if len(address) >= 25:
        return make_request('https://blockchain.info/q/getfirstbits/'+address)
    else:
        return make_request('https://blockchain.info/q/resolvefirstbits/'+address)


text:
# ISO8601-duration
Node/Js-module for parsing and making sense of ISO8601-durations

[![XO code style](https://img.shields.io/badge/code_style-XO-5ed9c7.svg)][1]
[![Build Status: Travis](https://img.shields.io/travis/tolu/ISO8601-duration/master.svg)][2]
[![npm version](https://img.shields.io/npm/v/iso8601-duration.svg)][3]

## The ISO8601 duration format

Durations in ISO8601 comes in two formats:
* **`PnYnMnDTnHnMnS`**  - `P<date>T<time>`
  The `n` is replaced by the value for each of the date and time elements that follow the `n`.
  Leading zeros are not required
* **`PnW`** - the week format

Check out the details on [Wikipedia](https://en.wikipedia.org/wiki/ISO_8601#Durations)

## Install

```
$ npm install iso8601-duration
```

## Usage
Most noteworthy of the interface is the ability to provide a `date` for `toSeconds`-calculations.
Why becomes evident when working with durations that span dates as all months are not equally long.
E.g January of 2016 is **744 hours** compared to the **696 hours** of February 2016.

If a date is not provided for `toSeconds` the timestamp `Date.now()` is used as baseline.

### Interface

```js
export const toSeconds; // fn = (obj, date?) => number
export const pattern;   // ISO8601 RegExp
export const parse;     // fn = string => obj
export default {
	toSeconds,
	pattern,
	parse
}
```

### Example
Simple usage
```js
import {parse, toSeconds, pattern} from 'iso8601-duration';

console.log(parse('P1Y2M4DT20H44M12.67S'));
/* outputs =>
{
	years: 1,
	months: 2,
	days: 4,
	hours: 20,
	minutes: 44,
	seconds: 12.67
}
*/

console.log( toSeconds( parse('PT1H30M10.5S') ) );
// outputs => 5410.5

```

A more complete usecase / example
```js
import {parse, toSeconds, pattern} from 'iso8601-duration';

// convert iso8601 duration-strings to total seconds from some api
const getWithSensibleDurations = someApiEndpoint => {
	// return promise, like fetch does
	return new Promise(resolve => {
		// fetch text
		fetch(someApiEndpoint)
			.then(res => res.text())
			.then(jsonString => {

				// create new pattern that matches on surrounding double-quotes
				// so we can replace the string with an actual number
				const replacePattern = new RegExp(`\\"${pattern.source}\\"`, 'g');
				jsonString = jsonString.replace(replacePattern, m => {
					return toSeconds(parse(m));
				});
				// resolve original request with sensible durations in object
				resolve( JSON.parse(jsonString) );
		});
	});
}

```

## License

MIT © Tobias Lundin

[1]: https://github.com/sindresorhus/xo "xo on github"
[2]: https://travis-ci.org/tolu/ISO8601-duration "travis build status"
[3]: https://www.npmjs.com/package/iso8601-duration "npm package"

redpajama_set_name: RedPajamaGithub


text:
static i: int =
    0xu32 //~ ERROR: no valid digits
;


text:
<?php

namespace OCA\Files_Sharing\External;

class Cache extends \OC\Files\Cache\Cache {
	private $remote;
	private $remoteUser;
	private $storage;

	/**
	 * @param \OCA\Files_Sharing\External\Storage $storage
	 * @param string $remote
	 * @param string $remoteUser
	 */
	public function __construct($storage, $remote, $remoteUser) {
		$this->storage = $storage;
		list(, $remote) = explode('://', $remote, 2);
		$this->remote = $remote;
		$this->remoteUser = $remoteUser;
		parent::__construct($storage);
	}

	public function get($file) {
		$result = parent::get($file);
		$result['displayname_owner'] = $this->remoteUser . '@' . $this->remote;
		if (!$file || $file === '') {
			$result['is_share_mount_point'] = true;
			$mountPoint = rtrim($this->storage->getMountPoint());
			$result['name'] = basename($mountPoint);
		}
		return $result;
	}

	public function getFolderContentsById($id) {
		$results = parent::getFolderContentsById($id);
		foreach ($results as &$file) {
			$file['displayname_owner'] = $this->remoteUser . '@' . $this->remote;
		}
		return $results;
	}
}


text:
class Ignored
  def ignore
    I18n.t("translation.ignored")
  end
end


text:
A central repository for NMS Data Skills guides and workshop materials.

To see the latest version of a guide, or to see a guide that is still under
development, you may need to switch to the appropriate feature branch.

## Contents
- [R Introduction](R_Intro/guide.md)
- [R Data Structures](R_Data_Structures/guide.md)
- [Resources](resources.md)

## North Mississippi Data Skills
We provide accessible training in professional, open-source data workflows and best practices to researchers from various backgrounds.

Our workshops are designed for students with research projects in mind.
We assume that your program of study involves some statistical preparation relevant to your research.
From experience, we also assume that your instructor had to cover a lot of theoretical details
and only had so much time to cover professional tools.
That's where we hope to be of assistance!

If you're interested in learning more or attending a workshop,
join us on Slack at [nmsdataskills.slack.com](http://nmsdataskills.slack.com).
Currently, anyone with an msstate.edu email address can join the Slack team.

## Thanks!
We'd like to thank the MSU Mitchell Memorial Library and the MSU Instructional Media Center
for providing us with this meeting space.

In addition, many thanks are owed to those attendees who have patiently attended the early workshops,
reviewed materials, and provided valuable feedback. Your support is very much appreciated!


text:
package extra.javax.xml.stream;

import javax.xml.namespace.NamespaceContext;

public interface XMLStreamWriter {

  /**
   * Writes a start tag to the output.  All writeStartElement methods
   * open a new scope in the internal namespace context.  Writing the
   * corresponding EndElement causes the scope to be closed.
   * @param localName local name of the tag, may not be null
   * @throws XMLStreamException
   */
  public void writeStartElement(String localName)
    throws XMLStreamException;

  /**
   * Writes a start tag to the output
   * @param namespaceURI the namespaceURI of the prefix to use, may not be null
   * @param localName local name of the tag, may not be null
   * @throws XMLStreamException if the namespace URI has not been bound to a prefix and
   * javax.xml.stream.isPrefixDefaulting has not been set to true
   */
  public void writeStartElement(String namespaceURI, String localName)
    throws XMLStreamException;

  /**
   * Writes a start tag to the output
   * @param localName local name of the tag, may not be null
   * @param prefix the prefix of the tag, may not be null
   * @param namespaceURI the uri to bind the prefix to, may not be null
   * @throws XMLStreamException
   */
  public void writeStartElement(String prefix,
                                String localName,
                                String namespaceURI)
    throws XMLStreamException;

  /**
   * Writes an empty element tag to the output
   * @param namespaceURI the uri to bind the tag to, may not be null
   * @param localName local name of the tag, may not be null
   * @throws XMLStreamException if the namespace URI has not been bound to a prefix and
   * javax.xml.stream.isPrefixDefaulting has not been set to true
   */
  public void writeEmptyElement(String namespaceURI, String localName)
    throws XMLStreamException;

  /**
   * Writes an empty element tag to the output
   * @param prefix the prefix of the tag, may not be null
   * @param localName local name of the tag, may not be null
   * @param namespaceURI the uri to bind the tag to, may not be null
   * @throws XMLStreamException
   */
  public void writeEmptyElement(String prefix, String localName, String namespaceURI)
    throws XMLStreamException;

  /**
   * Writes an empty element tag to the output
   * @param localName local name of the tag, may not be null
   * @throws XMLStreamException
   */
  public void writeEmptyElement(String localName)
    throws XMLStreamException;

  /**
   * Writes string data to the output without checking for well formedness.
   * The data is opaque to the XMLStreamWriter, i.e. the characters are written
   * blindly to the underlying output.  If the method cannot be supported
   * in the currrent writing context the implementation may throw a
   * UnsupportedOperationException.  For example note that any
   * namespace declarations, end tags, etc. will be ignored and could
   * interfere with proper maintanence of the writers internal state.
   *
   * @param data the data to write
   */
  //  public void writeRaw(String data) throws XMLStreamException;

  /**
   * Writes an end tag to the output relying on the internal
   * state of the writer to determine the prefix and local name
   * of the event.
   * @throws XMLStreamException
   */
  public void writeEndElement()
    throws XMLStreamException;

  /**
   * Closes any start tags and writes corresponding end tags.
   * @throws XMLStreamException
   */
  public void writeEndDocument()
    throws XMLStreamException;

  /**
   * Close this writer and free any resources associated with the
   * writer.  This must not close the underlying output stream.
   * @throws XMLStreamException
   */
  public void close()
    throws XMLStreamException;

  /**
   * Write any cached data to the underlying output mechanism.
   * @throws XMLStreamException
   */
  public void flush()
    throws XMLStreamException;

  /**
   * Writes an attribute to the output stream without
   * a prefix.
   * @param localName the local name of the attribute
   * @param value the value of the attribute
   * @throws IllegalStateException if the current state does not allow Attribute writing
   * @throws XMLStreamException
   */
  public void writeAttribute(String localName, String value)
    throws XMLStreamException;

  /**
   * Writes an attribute to the output stream
   * @param prefix the prefix for this attribute
   * @param namespaceURI the uri of the prefix for this attribute
   * @param localName the local name of the attribute
   * @param value the value of the attribute
   * @throws IllegalStateException if the current state does not allow Attribute writing
   * @throws XMLStreamException if the namespace URI has not been bound to a prefix and
   * javax.xml.stream.isPrefixDefaulting has not been set to true
   */

  public void writeAttribute(String prefix,
                             String namespaceURI,
                             String localName,
                             String value)
    throws XMLStreamException;

  /**
   * Writes an attribute to the output stream
   * @param namespaceURI the uri of the prefix for this attribute
   * @param localName the local name of the attribute
   * @param value the value of the attribute
   * @throws IllegalStateException if the current state does not allow Attribute writing
   * @throws XMLStreamException if the namespace URI has not been bound to a prefix and
   * javax.xml.stream.isPrefixDefaulting has not been set to true
   */
  public void writeAttribute(String namespaceURI,
                             String localName,
                             String value)
    throws XMLStreamException;

  /**
   * Writes a namespace to the output stream
   * If the prefix argument to this method is the empty string,
   * "xmlns", or null this method will delegate to writeDefaultNamespace
   *
   * @param prefix the prefix to bind this namespace to
   * @param namespaceURI the uri to bind the prefix to
   * @throws IllegalStateException if the current state does not allow Namespace writing
   * @throws XMLStreamException
   */
  public void writeNamespace(String prefix, String namespaceURI)
    throws XMLStreamException;

  /**
   * Writes the default namespace to the stream
   * @param namespaceURI the uri to bind the default namespace to
   * @throws IllegalStateException if the current state does not allow Namespace writing
   * @throws XMLStreamException
   */
  public void writeDefaultNamespace(String namespaceURI)
    throws XMLStreamException;

  /**
   * Writes an xml comment with the data enclosed
   * @param data the data contained in the comment, may be null
   * @throws XMLStreamException
   */
  public void writeComment(String data)
    throws XMLStreamException;

  /**
   * Writes a processing instruction
   * @param target the target of the processing instruction, may not be null
   * @throws XMLStreamException
   */
  public void writeProcessingInstruction(String target)
    throws XMLStreamException;

  /**
   * Writes a processing instruction
   * @param target the target of the processing instruction, may not be null
   * @param data the data contained in the processing instruction, may not be null
   * @throws XMLStreamException
   */
  public void writeProcessingInstruction(String target,
                                         String data)
    throws XMLStreamException;

  /**
   * Writes a CData section
   * @param data the data contained in the CData Section, may not be null
   * @throws XMLStreamException
   */
  public void writeCData(String data)
    throws XMLStreamException;

  /**
   * Write a DTD section.  This string represents the entire doctypedecl production
   * from the XML 1.0 specification.
   *
   * @param dtd the DTD to be written
   * @throws XMLStreamException
   */
  public void writeDTD(String dtd)
    throws XMLStreamException;

  /**
   * Writes an entity reference
   * @param name the name of the entity
   * @throws XMLStreamException
   */
  public void writeEntityRef(String name)
    throws XMLStreamException;

  /**
   * Write the XML Declaration. Defaults the XML version to 1.0, and the encoding to utf-8
   * @throws XMLStreamException
   */
  public void writeStartDocument()
    throws XMLStreamException;

  /**
   * Write the XML Declaration. Defaults the XML version to 1.0
   * @param version version of the xml document
   * @throws XMLStreamException
   */
  public void writeStartDocument(String version)
    throws XMLStreamException;

  /**
   * Write the XML Declaration.  Note that the encoding parameter does
   * not set the actual encoding of the underlying output.  That must
   * be set when the instance of the XMLStreamWriter is created using the
   * XMLOutputFactory
   * @param encoding encoding of the xml declaration
   * @param version version of the xml document
   * @throws XMLStreamException
   */
  public void writeStartDocument(String encoding,
                                 String version)
    throws XMLStreamException;

  /**
   * Write text to the output
   * @param text the value to write
   * @throws XMLStreamException
   */
  public void writeCharacters(String text)
    throws XMLStreamException;

  /**
   * Write text to the output
   * @param text the value to write
   * @param start the starting position in the array
   * @param len the number of characters to write
   * @throws XMLStreamException
   */
  public void writeCharacters(char[] text, int start, int len)
    throws XMLStreamException;

  /**
   * Gets the prefix the uri is bound to
   * @return the prefix or null
   * @throws XMLStreamException
   */
  public String getPrefix(String uri)
    throws XMLStreamException;

  /**
   * Sets the prefix the uri is bound to.  This prefix is bound
   * in the scope of the current START_ELEMENT / END_ELEMENT pair.
   * If this method is called before a START_ELEMENT has been written
   * the prefix is bound in the root scope.
   * @param prefix the prefix to bind to the uri, may not be null
   * @param uri the uri to bind to the prefix, may be null
   * @throws XMLStreamException
   */
  public void setPrefix(String prefix, String uri)
    throws XMLStreamException;

  /**
   * Binds a URI to the default namespace
   * This URI is bound
   * in the scope of the current START_ELEMENT / END_ELEMENT pair.
   * If this method is called before a START_ELEMENT has been written
   * the uri is bound in the root scope.
   * @param uri the uri to bind to the default namespace, may be null
   * @throws XMLStreamException
   */
  public void setDefaultNamespace(String uri)
    throws XMLStreamException;

  /**
   * Sets the current namespace context for prefix and uri bindings.
   * This context becomes the root namespace context for writing and
   * will replace the current root namespace context.  Subsequent calls
   * to setPrefix and setDefaultNamespace will bind namespaces using
   * the context passed to the method as the root context for resolving
   * namespaces.  This method may only be called once at the start of
   * the document.  It does not cause the namespaces to be declared.
   * If a namespace URI to prefix mapping is found in the namespace
   * context it is treated as declared and the prefix may be used
   * by the StreamWriter.
   * @param context the namespace context to use for this writer, may not be null
   * @throws XMLStreamException
   */
  public void setNamespaceContext(NamespaceContext context)
    throws XMLStreamException;

  /**
   * Returns the current namespace context.
   * @return the current NamespaceContext
   */
  public NamespaceContext getNamespaceContext();

  /**
   * Get the value of a feature/property from the underlying implementation
   * @param name The name of the property, may not be null
   * @return The value of the property
   * @throws IllegalArgumentException if the property is not supported
   * @throws NullPointerException if the name is null
   */
  public Object getProperty(java.lang.String name) throws IllegalArgumentException;

}


text:
namespace sf
{
namespace priv
{
////////////////////////////////////////////////////////////
/// \brief sf::priv::InputImpl helper
///
/// This class manage as a singleton instance the joysticks.
/// It's only purpose is to help sf::priv::JoystickImpl class.
///
////////////////////////////////////////////////////////////
class HIDJoystickManager : NonCopyable
{
public:

    ////////////////////////////////////////////////////////////
    /// \brief Get the unique instance of the class
    ///
    /// \note Private use only
    ///
    /// \return Reference to the HIDJoystickManager instance
    ///
    ////////////////////////////////////////////////////////////
    static HIDJoystickManager& getInstance();

public:

    ////////////////////////////////////////////////////////////
    /// \brief Get the number of currently connected joystick
    ///
    ////////////////////////////////////////////////////////////
    unsigned int getJoystickCount();

    ////////////////////////////////////////////////////////////
    /// \brief Copy the devices associated with this HID manager
    ///
    /// \return a retained CFSetRef of IOHIDDeviceRef or NULL
    ///
    ////////////////////////////////////////////////////////////
    CFSetRef copyJoysticks();

private:

    ////////////////////////////////////////////////////////////
    /// \brief Default constructor
    ///
    ////////////////////////////////////////////////////////////
    HIDJoystickManager();

    ////////////////////////////////////////////////////////////
    /// \brief Destructor
    ///
    ////////////////////////////////////////////////////////////
    ~HIDJoystickManager();

    ////////////////////////////////////////////////////////////
    /// \brief Make sure all event have been processed in the run loop
    ///
    ////////////////////////////////////////////////////////////
    void update();

private:

    ////////////////////////////////////////////////////////////
    /// \brief Private "plug-in" callback
    /// \note Only 'context' parameter is used.
    /// \see IOHIDDeviceCallback
    ///
    ////////////////////////////////////////////////////////////
    static void pluggedIn(void* context, IOReturn, void*, IOHIDDeviceRef);

    ////////////////////////////////////////////////////////////
    /// \brief Private "plug-out" callback
    /// \note Only 'context' parameter is used.
    /// \see IOHIDDeviceCallback
    ///
    ////////////////////////////////////////////////////////////
    static void pluggedOut(void* context, IOReturn, void*, IOHIDDeviceRef);

private:

    ////////////////////////////////////////////////////////////
    // Member data
    ////////////////////////////////////////////////////////////
    IOHIDManagerRef m_manager;      ///< HID Manager
    unsigned int    m_joystickCount;///< Number of joysticks currently connected
};

} // namespace priv

} // namespace sf

#endif


text:
Issue Submit Information
========================

Forward a Redmine user to the projects page by default, rather than the "home" page.

Copyright (c) 2011 Jon McManus, released under the MIT license.

Forked from `overview-view-page-forward`_, which was:

Forked from `project-page-forward`_, which was:

Forked from `single-project-forward`_: Copyright (c) 2010 [James Kassemi], released under the MIT license

 .. _`overview-view-page-forward`: https://github.com/jmcb/overview-view-page-forward

 .. _`single-project-forward`: https://github.com/jkassemi/single-project-forward

 .. _`project-page-forward`: https://github.com/jmcb/overview-view-page-forward


text:
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.0-b52-fcs
// See http://java.sun.com/xml/jaxb
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2012.09.06 at 09:23:00 오후 KST
//

package com.athena.chameleon.engine.entity.xml.ejbjar.weblogic.v9_0;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlID;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.adapters.CollapsedStringAdapter;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;

/**
 *
Java class for stateful-session-descriptorType complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType name="stateful-session-descriptorType">
 *   <complexContent>
 *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       <sequence>
 *         <element name="stateful-session-cache" type="{http://www.bea.com/ns/weblogic/90}stateful-session-cacheType" minOccurs="0"/>
 *         <element name="persistent-store-dir" type="{http://www.bea.com/ns/weblogic/90}persistent-store-dirType" minOccurs="0"/>
 *         <element name="stateful-session-clustering" type="{http://www.bea.com/ns/weblogic/90}stateful-session-clusteringType" minOccurs="0"/>
 *         <element name="allow-concurrent-calls" type="{http://www.bea.com/ns/weblogic/90}true-falseType" minOccurs="0"/>
 *         <element name="allow-remove-during-transaction" type="{http://www.bea.com/ns/weblogic/90}true-falseType" minOccurs="0"/>
 *       </sequence>
 *       <attribute name="id" type="{http://www.w3.org/2001/XMLSchema}ID" />
 *     </restriction>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "stateful-session-descriptorType", propOrder = {
    "statefulSessionCache",
    "persistentStoreDir",
    "statefulSessionClustering",
    "allowConcurrentCalls",
    "allowRemoveDuringTransaction"
})
public class StatefulSessionDescriptorType {

    @XmlElement(name = "stateful-session-cache", namespace = "http://www.bea.com/ns/weblogic/90")
    protected StatefulSessionCacheType statefulSessionCache;
    @XmlElement(name = "persistent-store-dir", namespace = "http://www.bea.com/ns/weblogic/90")
    protected PersistentStoreDirType persistentStoreDir;
    @XmlElement(name = "stateful-session-clustering", namespace = "http://www.bea.com/ns/weblogic/90")
    protected StatefulSessionClusteringType statefulSessionClustering;
    @XmlElement(name = "allow-concurrent-calls", namespace = "http://www.bea.com/ns/weblogic/90")
    protected TrueFalseType allowConcurrentCalls;
    @XmlElement(name = "allow-remove-during-transaction", namespace = "http://www.bea.com/ns/weblogic/90")
    protected TrueFalseType allowRemoveDuringTransaction;
    @XmlAttribute
    @XmlJavaTypeAdapter(CollapsedStringAdapter.class)
    @XmlID
    protected java.lang.String id;

    /**
     * Gets the value of the statefulSessionCache property.
     *
     * @return
     *     possible object is
     *     {@link StatefulSessionCacheType }
     *
     */
    public StatefulSessionCacheType getStatefulSessionCache() {
        return statefulSessionCache;
    }

    /**
     * Sets the value of the statefulSessionCache property.
     *
     * @param value
     *     allowed object is
     *     {@link StatefulSessionCacheType }
     *
     */
    public void setStatefulSessionCache(StatefulSessionCacheType value) {
        this.statefulSessionCache = value;
    }

    /**
     * Gets the value of the persistentStoreDir property.
     *
     * @return
     *     possible object is
     *     {@link PersistentStoreDirType }
     *
     */
    public PersistentStoreDirType getPersistentStoreDir() {
        return persistentStoreDir;
    }

    /**
     * Sets the value of the persistentStoreDir property.
     *
     * @param value
     *     allowed object is
     *     {@link PersistentStoreDirType }
     *
     */
    public void setPersistentStoreDir(PersistentStoreDirType value) {
        this.persistentStoreDir = value;
    }

    /**
     * Gets the value of the statefulSessionClustering property.
     *
     * @return
     *     possible object is
     *     {@link StatefulSessionClusteringType }
     *
     */
    public StatefulSessionClusteringType getStatefulSessionClustering() {
        return statefulSessionClustering;
    }

    /**
     * Sets the value of the statefulSessionClustering property.
     *
     * @param value
     *     allowed object is
     *     {@link StatefulSessionClusteringType }
     *
     */
    public void setStatefulSessionClustering(StatefulSessionClusteringType value) {
        this.statefulSessionClustering = value;
    }

    /**
     * Gets the value of the allowConcurrentCalls property.
     *
     * @return
     *     possible object is
     *     {@link TrueFalseType }
     *
     */
    public TrueFalseType getAllowConcurrentCalls() {
        return allowConcurrentCalls;
    }

    /**
     * Sets the value of the allowConcurrentCalls property.
     *
     * @param value
     *     allowed object is
     *     {@link TrueFalseType }
     *
     */
    public void setAllowConcurrentCalls(TrueFalseType value) {
        this.allowConcurrentCalls = value;
    }

    /**
     * Gets the value of the allowRemoveDuringTransaction property.
     *
     * @return
     *     possible object is
     *     {@link TrueFalseType }
     *
     */
    public TrueFalseType getAllowRemoveDuringTransaction() {
        return allowRemoveDuringTransaction;
    }

    /**
     * Sets the value of the allowRemoveDuringTransaction property.
     *
     * @param value
     *     allowed object is
     *     {@link TrueFalseType }
     *
     */
    public void setAllowRemoveDuringTransaction(TrueFalseType value) {
        this.allowRemoveDuringTransaction = value;
    }

    /**
     * Gets the value of the id property.
     *
     * @return
     *     possible object is
     *     {@link java.lang.String }
     *
     */
    public java.lang.String getId() {
        return id;
    }

    /**
     * Sets the value of the id property.
     *
     * @param value
     *     allowed object is
     *     {@link java.lang.String }
     *
     */
    public void setId(java.lang.String value) {
        this.id = value;
    }

}


text:
import React from 'react';
import PropTypes from 'prop-types';
import cx from 'classnames';

import {BranchPropType} from '../prop-types';

export default class BranchView extends React.Component {
  static propTypes = {
    currentBranch: BranchPropType.isRequired,
    refRoot: PropTypes.func,
  }

  static defaultProps = {
    refRoot: () => {},
  }

  render() {
    const classNames = cx(
      'github-branch', 'inline-block', {'github-branch-detached': this.props.currentBranch.isDetached()},
    );

    return (

        {this.props.currentBranch.getName()}

    );
  }
}


text:
package com.muatik.flj.flj.UI.entities;

import com.muatik.flj.flj.UI.RESTful.API;

import java.io.Serializable;

import retrofit2.Call;
import retrofit2.Response;

/**
 * Created by muatik on 24.07.2016.
 */
public class Job implements Serializable {
    private String job_id;
    private String title;
    private String employer;
    private String description;
    private String created_at;
    private String country;
    private String city;
    private String latitude;
    private String longitude;
    private Integer user;
    private Integer view_counter;
    private boolean applicable;
    private String source_url;

    public Job() {

    }

    public Job(String title, String created_at, String city, String country) {
        this.title = title;
        this.city = city;
        this.country = country;
        this.created_at= created_at;
    }

    public void setJob_id(String job_id) {
        this.job_id = job_id;
    }

    public String getId() {
        return job_id;
    }

    public String getTitle() {
        return title;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public String getDescription() {
        return description;
    }

    public String getCountry() {
        return country;
    }

    public String getCity() {
        return city;
    }

    public String getLatitude() {
        return latitude;
    }

    public String getLongitude() {
        return longitude;
    }

    public void setUser(Integer user) {
        this.user = user;
    }

    public Integer getUser() {
        return user;
    }

    public String getCreated_at() {
        return created_at;
    }

    public String getJob_id() {
        return job_id;
    }

    public String getEmployer() {
        return employer;
    }

    public void setEmployer(String employer) {
        this.employer = employer;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public void setCountry(String country) {
        this.country = country;
    }

    public void setCity(String city) {
        this.city = city;
    }

    public Integer getView_counter() {
        return view_counter;
    }

    public void setView_counter(Integer view_counter) {
        this.view_counter = view_counter;
    }

    public void countView() {
        API.authorized.countView(getId()).enqueue(new API.BriefCallback<Job>() {
            @Override
            public void onFailure(Call<Job> call, Throwable t, Response<Job> response) {

            }

            @Override
            public void onSuccess(Call<Job> call, Response<Job> response) {
                Job job = response.body();
                Job.this.setView_counter(job.getView_counter());
            }
        });
    }

    public boolean isApplicable() {
        return applicable;
    }

    public void setApplicable(boolean applicable) {
        this.applicable = applicable;
    }

    public String getSource_url() {
        return source_url;
    }

    public void setSource_url(String source_url) {
        this.source_url = source_url;
    }

    public void setLatLong(double latitude, double longitude) {
        this.latitude = String.valueOf(latitude);
        this.longitude = String.valueOf(longitude);
    }
}


text:
layout: post
title: "Building Serverless Apps with Webtask.io"
description: "Webtask is Function-as-a-Service platform for building serverless apps. Learn how to build applications without worrying about servers, and common use-cases where serverless shines."
date: 2016-06-28 08:30
alias: /2016/06/28/building-serverless-apps-with-webtask/
category: Technical Guide, Serverless, Webtasks
author:
  name: "Ado Kukic"
  url: "https://twitter.com/kukicadnan"
  mail: "ado@auth0.com"
  avatar: "https://s.gravatar.com/avatar/99c4080f412ccf46b9b564db7f482907?s=200"
design:
  bg_color: "#5F3237"
  image: "https://cdn.auth0.com/blog/webtask/logo.png"
tags:
- Serverless
- Webtask
- Webtask.io
- Function-as-a-Service
- faas
- Serverless-Authentication
related:
- 2016-06-09-what-is-serverless
- 2015-10-07-extensibility-through-code-using-webtasks
- 2015-12-11-get-your-twitter-share-count-back-with-a-webtask
---

  This post is out of date. The AWS Cognito Integration API has been deprecated.  This post will be updated soon with a working solution.  We also recommend using the Auth0 Centralised Login Pages as opposed to the Lock solution used in this post.

---

**TL;DR** Webtask.io allows you to build applications without thinking about infrastructure. Simply write your server-side logic, deploy your functions via the Webtask CLI, and access your serverless backend over HTTP. Preferring code to configuration, the Webtask platform comes with a familiar programming model, excellent authentication and authorization support, and more to ensure a pleasant development experience.

For our tutorial today, we'll enhance a static blog with some dynamic functionality that would normally require a traditional backend. Check out the [Github repo](https://github.com/auth0-blog/serverless-stories) for the code to follow along.

---

[Webtask.io](https://webtask.io) is a Function-as-a-Service (FaaS) platform that allows you to build serverless applications. Built by the team that brought you Auth0, Webtask features a familiar programming model, an easy to use CLI and a powerful infrastructure to help you accomplish your goals.

Webtasks are secure, self-contained functions accessed over the HTTPS protocol that perform server-side logic. With Webtasks, you can securely call APIs that require secret keys, set up webhooks that get triggered after certain actions in your application are performed, or talk directly to your existing database or backend just to name a few. The power of serverless computing is that it is there for you when you need it and out of the way when you don't.

## Serverless? Function as a Service? What?

Serverless computing is a fairly recent trend is software development that allows developers to focus on writing application logic and not worry about provisioning and managing servers. It's akin to the Platform-as-a-Service (PaaS) architecture where a company provides an API that developers use to accomplish their goals. In fact, serverless computing is a level of abstraction higher than the traditional PaaS - and is often referred to as Function-as-a-Service.

Serverless, and by extension Webtask, is there for you when you need it and out of the way when you don't. You can extend your current backend with Webtask, build your entire backend around Webtask functions and never provision any servers or set up infrastructure yourself, or use it for more specialized cases such as webhooks. To learn more about serverless computing, check out this [blog post](https://auth0.com/blog/2016/06/09/what-is-serverless/).

## Serverless Use Cases

Serverless and FaaS can prove useful in various use-cases. If you are building a static website, but would like to add the ability to capture user emails for a newsletter, you would either need to setup a backend or register with a 3rd party email service and use their widget or API to capture emails. If a 3rd party API you want to use requires secret keys, you would have to build a backend so that you could safely make calls to the API. Webtasks, like other first class backends, allow the developer to create a trust boundary between the client and server.

## Building a Serverless App with Webtask

Today we will build a serverless application. The app we are building is a blog called Serverless Stories, where the authors write about the latest and greatest serverless trends. Before we get started, let's look at **why** a blog might be a great fit for serverless.

### The Problem

Blogs tend to have large spikes in traffic when breaking news happen. Many blogs are hosted on small budgets, often on shared hosting providers and more often than not on a Content Management System like Wordpress which requires a backend and database. As soon as traffic spikes, the blog crashes and burns. It's such a common occurrence that we even have a phrase for it: [slashdot effect](https://en.wikipedia.org/wiki/Slashdot_effect) - or more recently Reddit hug of death.

### The Solution

With these assumptions in mind, our Serverless Stories blog will be completely static, but we'll augment it with Webtasks to add functionality readers have come to expect. Our Serverless Stories blog could use any number of static site generators, like [Jekyll](https://jekyllrb.com/) or [Hugo](https://gohugo.io/), or it could be totally hand-crafted - we're crazy like that sometimes.

Our blog is comprised of HTML, CSS and JS files. We don't have a backend nor do we rely on a database. This makes our website much more resilient when a traffic surge occurs. A static site is simply not enough in the modern day though. We will add the ability to allow users to sign up for our newsletter. Normally, this would require a backend system, but we'll accomplish it with Webtasks. Let's get started.

## Serverless Stories

![Serverless Stories Homepage](https://cdn.auth0.com/blog/webtask/app.png)

Our blog has three views. The **homepage**, where we can see a list of stories and subscribe to the newsletter. An **article** page, which contains the full content for each article. Finally, a secret **admin** page, where authenticated users can see who has subscribed to the newsletter. We'll use [Bootstrap](http://getbootstrap.com/) to help us build out a clean UI.

We will omit the HTML code for brevity. Pull the code from the [Github repo](https://github.com/auth0-blog/serverless-stories) to follow along.

## Adding Functionality with Webtasks

With our static blog up and running, it's time to add some dynamic functionality. The Webtask we are creating is called Newsletter. We have two goals to achieve: add the ability to capture a users email address and display an authenticated user the list of subscribers.

### Getting Started with Webtask

To start working with Webtasks we will need to install the Webtask CLI. You will need [Node.js](https://nodejs.org/en/) and [npm](https://npmjs.com) installed on your machine, then run the `npm install wt-cli -g` command. This will install the Webtask CLI globally so you can access it from anywhere on your computer. Once the install is complete, run the `wt -v` command to ensure that Webtask is properly working. If it is, you'll get the current version, which as of this article is 3.1.0.

{% include tweet_quote.html quote_text="Write your application logic. Run wt create webtask_name. Done. You can deploy a Webtask faster than it took to write this tweet." %}

With the Webtask CLI installed, our next step is to get a Webtask account. To get an account, run the `wt init` command. You will prompted to enter a phone number or email address. Once you provide a phone number or email address, you'll get a confirmation code. Input this confirmation code, and you will be ready to start creating Webtasks.

In the future, if you want to log in to a different account, run the `wt init` command and you'll have the option to login with a new account.

### Webtask Programming Model

If you've ever worked with Node.js, you should feel right at home writing Webtasks. Each webtask exports a single function (which is the typical unit of logic in Function-as-a-Service). There are [several](https://webtask.io/docs/model) programming models supported. The simplest programming model is a function that accepts a single parameter - a callback. An example of this would be:

```js
module.exports = function(callback){
  // Prints the message "Hello Webtask" when accessed
  callback(null, "Hello Webtask");
}
```

Next, a more advanced programming model that accepts two parameters: `context` and `callback`. The `context` parameter is a JavaScript object that contains various properties such as `query`, `secrets`, `body`. The `context` parameter also offers access to the `context.storage.get` and `context.storage.set` API which allow access to Webtasks durable storage. An example of a Webtask using this programming model:

```js
module.exports = function(context, callback){
  var name = context.query.name;
  // Prints the message "Hello {name}", where the {name} is the contents of the name query string.
  // If no name query string is provided then it will simply print "Hello"
  callback(null, "Hello " + name);
}
```

Finally, the most advanced programming model gives us full control over the HTTP request and response. This model takes three parameters: `context`, `request`, `response`. An example of a Webtask using this programming model:

```js
module.exports = function(context, request, response){
  response.writeHead(200, { 'Content-Type': 'text/html '});
  response.end('<h1>Hello Webtask!</h1>');
}
```

These three programming options give you flexibility to decide on just how much control you need.

### Our First Webtask - Newsletter Email Capture

Our first Webtask will capture and save a users email address. To create this Webtask, create a file called `newsletter.js`. Our implementation is below:

```js
// We can use over 800 of the most popular JavaScript modules.
// Get the full list here https://tehsis.github.io/webtaskio-canirequire/
// If the module you need is not here, you can manually bundle it with
// https://github.com/auth0/webtask-bundle
var _ = require('lodash');

// We'll set up some generic response messages based on what our Webtask does
const RESPONSE = {
  OK : {
    status : "ok",
    message: "You have successfully subscribed to the newsletter!",
  },
  DUPLICATE : {
    status : "error",
    message : "You are already subscribed."
  },
  ERROR : {
    status : "error",
    message: "Something went wrong. Please try again."
  }
};

// We'll use the programming model where we...
module.exports = function(context, cb){
  // We use the context to extract the email query string.
  var email = context.query.email;

  // If we get an email, we proceed, otherwise we stop execution and send error message
  if(email){
    // Each Webtask comes with 500kb of storage
    // You can store any valid JSON in this storage variable
    // Useful for when you just need to store a small amount and setting up an external database would be overkill
    // Here we retrieve the contents of the storage
    context.storage.get(function(err, data){
      if(err){
        cb(null, RESPONSE.ERROR);
      }

      data = data || [];

      // We use the lodash library we required earlier to check if the email sent already exists in our storage
      // If it does not, we'll add it.
      if(_.indexOf(data, email)){
        data.push(email);
        // Here we use the set method to add data to the storage variable
        context.storage.set(data, function(err){
          if(err){
            cb(null, RESPONSE.ERROR);
          } else {
            cb(null, RESPONSE.OK);
          }
        })
      } else {
        // If it is already in storage, we'll send an appropriate message.
        cb(null, RESPONSE.DUPLICATE);
      }
    })
  } else {
    // If we didn't get a query parameter named email, we'll return the error response
    cb(null, RESPONSE.ERROR)
  }
};
```

To see this Webtask in action, we can deploy it by running the `wt create {name}` command - so in your terminal execute `wt create newsletter.js`. In a few seconds, you'll see a link to your Webtask in the format of `https://webtask.it.auth0.com/api/run/{YOUR_ACCOUNT}/newsletter?webtask_no_cache=1`. Navigate to the URL and you will see the error response we wrote displayed. This is because we did not add the email query string. Let's try again, but this time append `&email=john.doe@email.com` so the URL looks like `https://webtask.it.auth0.com/api/run/{YOUR_ACCOUNT}/newsletter?webtask_no_cache=1&email=john.doe@email.com`. Now you should see a message saying that the email was successfully added. If you try it again with the same email address, you'll get the email exists error message. So far so good.

### Webtask to Retrieve Subscribers

The email capture Webtask was fairly simple. For our next Webtask, we'll make use of some of the more advanced features of the platform. We'll secure our Webtask, set up additional routes, and use the Express framework in our Webtask. Let's take a look at the code and explanation below. We'll update our existing Webtask to support this new functionality. Let's walk through the code.

```js
// First things first, we'll include the required libraries
var app = new (require('express'))();
// webtask-tools allows for additional helper functions
var wt = require('webtask-tools');
var _ = require('lodash');

// We're going to update our response messages and actually include the status code
// as we're going to take full control of the HTTP request and response objects
const RESPONSE = {
  OK : {
    statusCode : 200,
    message: "You have successfully subscribed to the newsletter!",
  },
  DUPLICATE : {
    status : 400,
    message : "You are already subscribed."
  },
  ERROR : {
    statusCode : 400,
    message: "Something went wrong. Please try again."
  },
  UNAUTHORIZED : {
    statusCode : 401,
    message : "You must be logged in to access this resource."
  }
};

// We will register a new route '/subscribe' which will allow users
// to subscribe to the newsletter. Since we are sending data, it may be more
// fitting to send the email through a POST request, so we'll do that here.
// The pattern is pretty similar to how traditional Express apps are written
app.post('/subscribe', function(req, res){
  // The 'context' parameter from the earlier example is now accessed through
  // 'webtaskContext'.
  var email = req.webtaskContext.body.email;
  if(email){
    req.webtaskContext.storage.get(function(err, data){
      if(err){
        // Taking full control over the HTTP response allows us to full
        // flexibility, so we'll set an response code as well as content-type
        res.writeHead(400, { 'Content-Type': 'application/json'});
        res.end(JSON.stringify(RESPONSE.ERROR));
      }

      data = data || [];

      if(_.indexOf(data, email) == -1){
        data.push(email);
        req.webtaskContext.storage.set(data, function(err){
          if(err){
            res.writeHead(400, { 'Content-Type': 'application/json'});
            res.end(JSON.stringify(RESPONSE.ERROR));
          } else {
            res.writeHead(200, { 'Content-Type': 'application/json'});
            res.end(JSON.stringify(RESPONSE.OK));
          }
        })
      } else {
        res.writeHead(400, { 'Content-Type': 'application/json'});
        res.end(JSON.stringify(RESPONSE.DUPLICATE));
      }
    })
  } else {
    res.writeHead(200, { 'Content-Type': 'application/json'});
    res.end(JSON.stringify(RESPONSE.ERROR));
  }
})

// We are going to add a new route '/subscribers/ that will retrieve
// the list of users subscribed to our newsletter. The route will be accessed
// via a GET request - but the user will need to be authenticated
app.get('/subscribers', function(req,res){
  req.webtaskContext.storage.get(function(err, data){
      if(!err){
        res.writeHead(400, { 'Content-Type': 'application/json'});
        res.end(JSON.stringify(data));
      }
  });
});

// Here we are exporting our express app using the wt helper library
module.exports = wt.fromExpress(app).auth0({
  // We are excluding the 'subscribe' route, so that anyone can subscribe to the newsletter
  exclude : [
    '/subscribe'
  ],
  // Here we are implementing a custom login error function which will send
  // the user an appropriate message if the request is not authorized
  loginError: function (error, ctx, req, res, baseUrl) {
        res.writeHead(401, { 'Content-Type': 'application/json'})
        res.end(JSON.stringify(RESPONSE.UNAUTHORIZED))
    }
});
```

Our updated Webtask has a lot more going on. Since we are adding Auth0 to the Webtask now, we'll need to get our Auth0 credentials and pass them when we deploy the Webtask. Sign up for a free Auth0 account to continue.

Once you have created your Auth0 account, navigate to the [management dashboard](https://manage.auth0.com) and navigate into your newly created app. From here you will want to get the **Client ID**, **Client Secret** and **Domain**. Now, we'll deploy a new version of our newsletter Webtask with our Auth0 app credentials. Let's see how to do this:

```bash
wt create newsletter.js
    -s AUTH0_CLIENT_ID=YOUR_AUTH0_CLIENT_ID
    -s AUTH0_CLIENT_SECRET=YOUR_AUTHO_CLIENT_SECRET
    -s AUTH0_DOMAIN=YOUR_AUTH0_DOMAIN.auth0.com
    -s AUTH0_SECRET_ENCODING=utf8
```

With the deployment complete, we are ready to integrate our Webtask into our Serverless Stories blog.

## Integrating Webtasks into Serverless Stories

We have our Serverless Stories blog and our Webtask built. Next, let's integrate the two and add some dynamic functionality to our blog. We will do this in three parts: implement the newsletter subscription so that users can sign up for the newsletter, add user login and registration with Auth0 and Lock, and finally add the functionality for logged in users to view the list of newsletter subscribers.

### Newsletter Webtask Integration

Let's add the functionality for our newsletter. We have the user interface and the Webtask up and running, so all we need to do is send a POST request to the Webtask after a user has added their email address. The implementation looks like:

```js
$('#newsletter').submit(function(e){
  // When the newsletter form is submitted, we'll make an AJAX request to our Webtask and pass the provided email.
  $.ajax({
    type : 'POST',
    url : 'https://webtask.it.auth0.com/api/run/{YOUR_WEBTASK_ACCOUNT}/newsletter/subscribe?webtask_no_cache=1',
    data : {email : $('#email').val()},
    dataType    : 'json'
  }).done(function(data) {
    if(data.statusCode == 200){
      $('#newsletter').hide();
      $('#response').append('<div class="alert alert-success">'+ data.message +'</div>')
    } else {
      $('#newsletter').hide();
      $('#response').append('<div class="alert alert-danger">'+ data.message +'</div>')
    }
  });
  e.preventDefault();
})
```

If all went well, after you enter an email address and hit the **Submit** button, you'll see a message saying that your email was added. You can try sending the same email again, and you'll see the duplicate error message telling you that you've already subscribed.

![Successful Subscription](https://cdn.auth0.com/blog/webtask/subscribed.png)

### Auth0 and Lock

Auth0 provides an intuitive and easy to use widget called [Lock](https://auth0.com/lock) that can handle both user login and registration. We'll use Lock in our application. We'll use the hosted Lock off the Auth0 CDN, so in your `index.html` files, add the following snippet:

```html
 <script src="https://cdn.auth0.com/js/lock/10.0/lock.min.js"></script>
```

Let's use the Auth0 Lock widget in our HTML5 application. Open up the `app.js` file to get started.

```js
// We'll instantiate lock, passing our Auth0 Client ID and Domain
var lock = new Auth0Lock('YOUR_AUTH0_CLIENT_ID', 'YOUR_AUTH0_DOMAIN.auth0.com');

// The login function once invoked will display the Lock widget
// Upon successful login, we'll store the user profile and token in localStorage
function login(){
  lock.show();
};

lock.on("authenticated", function(authResult) {
  lock.getProfile(authResult.idToken, function(error, profile) {

    if (error) {
       return alert(error.message);
    }

    localStorage.setItem('profile', JSON.stringify(profile))
    localStorage.setItem('token', authResult.idToken)
    updateAuthenticationStatus();
  });
});

// The logout function, will remove the user information and token from localStorage
function logout(){
  localStorage.removeItem('profile');
  localStorage.removeItem('token');
  updateAuthenticationStatus();
};

// The getUser helper function will get the current status of our user
// and display user information or a link to login if there is no
// authenticated user
function updateAuthenticationStatus(){
  $('#user').empty();
  $('#login').empty();
  var user = localStorage.getItem('profile');
  if(user){
    user = JSON.parse(user);
    $('#user').show().append('<a onclick="logout()">' + user.email + ' (Log out)</a>');
    $('#login').hide();
  } else {
    $('#login').show().append('<a onclick="login()">Log in</a>');
    $('#user').hide();
  }
}

// Any time a page is loaded, we'll check to see if there is a user.
$(document).ready(function(){
  updateAuthenticationStatus();
});
```

Pretty easy implementation right? Refresh your browser and you should see a login button displayed in the right side of the nav. Clicking on the login button will bring up the Lock UI where you can login or create a new account. Upon successful login, the login button will disappear and you will see the logged in users email address and have the option to log out. The Lock widget has many configuration options and settings for you to play with, read all about them in the [docs](https://auth0.com/docs/libraries/lock).

![Lock in Action](https://cdn.auth0.com/blog/webtask/login.png)

### Super Secret Admin Page

Finally, we'll build an admin page, that will give us a list of all the users that have subscribed to our newsletter. Take a look at the implementation below.

```js
function loadAdmin(){
  // This code will only run if we are on the admin page
  if(window.location.pathname == '/admin/'){
    // We'll check localStorage to see if a user is logged in and has a token
    if(localStorage.getItem('token')){
      // If they do, we'll go ahead and make the AJAX call to get the list of users
      $.ajax({
        type : 'GET',
        url : 'https://webtask.it.auth0.com/api/run/wt-kukicadnan-gmail_com-0/newsletter-complex/subscribers?webtask_no_cache=1',
        // As this endpoint requires the user to be authenticated, we'll pass an Authorization header with the users JWT
        headers : {
          Authorization : 'Bearer ' + localStorage.getItem('token')
        }
      // If the JWT is valid, we'll get back the list of users, and display it in the UI
      }).done(function(data) {
        for(var i = 0; i < data.length; i++){
          $('#subscribers').append('<h4>' + data[i] + '</h4>');
        }
      });
    } else {
      window.location = '/';
    }
  }
}
```

With this implementation in place, let's launch our app and test the functionality. First try subscribing to the newsletter. Next, try accessing the `localhost:8080/admin`, you will be redirected to the homepage. Finally, login and then try accessing the admin route and you will see the list of subscribed users. How cool is that?

![Secret Admin Page](https://cdn.auth0.com/blog/webtask/admin.png)

## Putting It All Together

Our app is finally complete. We built a static website that can be hosted anywhere, but added common functionality with Webtask that would normally require a backend but that's barely scratching the surface. In the current application, any logged in user would be able to see the list of subscribers. We could write a rule in either the Auth0 dashboard, or our Webtask to authorize only specific users, but consider that your homework.

You can try [Webtask.io](https://webtask.io) for free and get started today. When you are ready to scale, paid plans offer additional features to meet your needs.

## Conclusion

Serverless and function-as-a-service platforms provide an essential utility to modern day software development. Today, we showed just one use case where serverless saved the day, but that's barely scratching the surface. Webhooks, cron jobs, and much more can easily be accomplished with Webtask. [Start here](https://webtask.io/docs/101) to learn more about Webtask and how it can simplify and enhance your development experience.

{% include tweet_quote.html quote_text="With Webtasks, you can focus on development rather than servers." %}


text:
from provider import Provider
from time import sleep

def size(collection):
    return len(collection)

class App(Provider):

    """
    App initialization. Initializes the provider and its socket.

    Important!
    Modify this function with care.
    """
    def __init__(self):
        Provider.__init__(self)

    """
    size_x1
    Gets the size of an item. If the item is an array, returns the length of the array. If the item
    is a map, gets the number of keys in the map. This function is allocated 1 core.
    """
    def size_x1(self, collection, progress, fail):
        return size(collection)

    """
    size_x2
    Gets the size of an item. If the item is an array, returns the length of the array. If the item
    is a map, gets the number of keys in the map. This function is allocated 2 cores.
    """
    def size_x2(self, collection, progress, fail):
        return size(collection)

    """
    size_x4
    Gets the size of an item. If the item is an array, returns the length of the array. If the item
    is a map, gets the number of keys in the map. This function is allocated 4 cores.
    """
    def size_x4(self, collection, progress, fail):
        return size(collection)

    """
    size_x8
    Gets the size of an item. If the item is an array, returns the length of the array. If the item
    is a map, gets the number of keys in the map. This function is allocated 8 cores.
    """
    def size_x8(self, collection, progress, fail):
        return size(collection)

    """
    size_x16
    Gets the size of an item. If the item is an array, returns the length of the array. If the item
    is a map, gets the number of keys in the map. This function is allocated 16 cores.
    """
    def size_x16(self, collection, progress, fail):
        return size(collection)

if __name__ == "__main__":

    app = App()
    app.run()


text:
(C) Copyright 2014 William Dyce

All rights reserved. This program and the accompanying materials
are made available under the terms of the GNU Lesser General Public License
(LGPL) version 2.1 which accompanies this distribution, and is available at
http://www.gnu.org/licenses/lgpl-2.1.html

This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
--]]

--[[------------------------------------------------------------
CONSTANTS
--]]--

local SPEED = 32
local SPEED_FLEE = 96

--[[------------------------------------------------------------
Initialisation
--]]--

local Monster = Class
{
  FRICTION = 100,

  type = GameObject.newType("Monster"),

  init = function(self, x, y)
    GameObject.init(self, x, y, 6)
    self.fire_t = math.random()
    self.heart = math.random()
    self.visibility = 0
  end,
}
Monster:include(GameObject)

--[[------------------------------------------------------------
Destruction
--]]--

function Monster:onPurge()
end

--[[------------------------------------------------------------
States
--]]--

function Monster:setState(newStateClass, ...)

  if self.state.class == newStateClass then
    return
  end
  local newState = newState(self, ...)
  newState.class = newStateClass

  local oldState = self.state
  if oldState.exitTo then
    oldState.exitTo(newState)
  end
  if newState.enterFrom then
    newState.enterFrom(oldState)
  end
  self.state = newState
end

function Monster:isAfraid()
  return self.fire or isDaytime()
end

--[[------------------------------------------------------------
Game loop
--]]--

function Monster:update(dt)

  -- disappear like darkness!
  self.visibility = math.max(0, self.visibility - dt)

  -- heartbeat
  self.heart = self.heart + dt

  if self:isAfraid() then
    -- run away!
    local dx, dy, dist = Vector.normalize(self.x - WORLD_W*0.5, self.y - WORLD_H*0.5)
    self.dx, self.dy = dx*SPEED_FLEE, dy*SPEED_FLEE
    if dist > WORLD_W then
      self.purge = true
    end
  else

    if not self.target or self.heart > 1 then
      self.target = GameObject.getNearestOfType("Human", self.x, self.y,
        function(h) return not h.dying end)
    else
      local t = self.target
      if t.dying then
        self.target = nil
      else

        if self:isNear(t) then
          -- attack target
          t:kill()
          self.target = nil
        else
          -- move to target
          local dx, dy = Vector.normalize(t.x - self.x, t.y - self.y)
          self.dx, self.dy = dx*SPEED, dy*SPEED
        end
      end
    end
  end

  if self.fire then
    self.fire_t = self.fire_t + 20*dt
    -- burn, howl in pain!
    if self.fire_t > 1 then

      if math.random() > 0.5 then
        local angle = math.random()*math.pi*2
        local speed = 18 + math.random()*8
        local dx, dy = math.cos(angle), math.sin(angle)
        Particle.Smoke(self.x + dx*4, self.y + dy*4,
          dx*speed,
          dy*speed,
          60 + math.random()*20)
      else
        local angle = math.random()*math.pi*2
        local speed = 18 + math.random()*8
        local dx, dy = math.cos(angle), math.sin(angle)
        Particle.Fire(self.x + dx*4, self.y + dy*4,
          dx*speed,
          dy*speed,
          60 + math.random()*20)
      end

      self.fire_t = self.fire_t - 1
    end
  end

  -- loop heart beat
  if self.heart > 1 then
    self.heart = self.heart - 1
  end

  GameObject.update(self, dt)
end

function Monster:draw(x, y)

  -- breathe air
  local breath = math.sin(((self:isAfraid() and 4) or 1)*self.heart*math.pi)

  -- burn!
  if self.fire then
    light(self.x, self.y, 32, 1)
  end

  -- body
  local w, h = (7 + breath), 32 - breath
  love.graphics.setColor(122, 152, 178)
    love.graphics.rectangle("fill", self.x - w, self.y - h, 2*w, h)
  useful.bindWhite()

  -- shadow
  useful.pushCanvas(SHADOW_CANVAS)
    useful.oval("fill", self.x, self.y, 14, 14*VIEW_OBLIQUE)
  useful.popCanvas()

  -- debug
  if DEBUG and self.target then
    useful.bindBlack()
      love.graphics.line(x, y, self.target.x, self.target.y)
    useful.bindWhite()
  end

end

--[[------------------------------------------------------------
Combat
--]]--

function Monster:ignite()
  self.fire = true
end

function Monster:isOnFire()
  return self.fire
end

--[[------------------------------------------------------------
Collisions
--]]--

function Monster:eventCollision(other, dt)
  if other:isType("Monster") then
    other:shoveAwayFrom(self, 100*dt)
  elseif other:isType("Human") then
    other:shoveAwayFrom(self, 300*dt)
  elseif other:isType("Light") then
    self.visibility = math.min(1, self.visibility + 2*dt)
  end
end

--[[------------------------------------------------------------
Export
--]]--

return Monster


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#ffffff"
    android:orientation="vertical">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        android:elevation="5dp"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar" />

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical">

            <br.tiagohm.markdownview.MarkdownView
                android:id="@+id/mMdvPrivacy"
                app:escapeHtml="false"
                android:layout_width="match_parent"
                android:layout_height="match_parent"/>
        </LinearLayout>
    </ScrollView>
</LinearLayout>


text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="ChangeListManager">
    <list default="true" id="227a5af6-fa58-4cd7-88fe-ee8b05ecd834" name="Default" comment="">
      <change type="MODIFICATION" beforePath="$PROJECT_DIR$/about.html" afterPath="$PROJECT_DIR$/about.html" />
    </list>
    <ignored path="djkooks.github.com.iws" />
    <ignored path=".idea/workspace.xml" />
    <ignored path="$PROJECT_DIR$/.tmp/" />
    <ignored path="$PROJECT_DIR$/temp/" />
    <ignored path="$PROJECT_DIR$/tmp/" />
    <option name="EXCLUDED_CONVERTED_TO_IGNORED" value="true" />
    <option name="TRACKING_ENABLED" value="true" />
    <option name="SHOW_DIALOG" value="false" />
    <option name="HIGHLIGHT_CONFLICTS" value="true" />
    <option name="HIGHLIGHT_NON_ACTIVE_CHANGELIST" value="false" />
    <option name="LAST_RESOLUTION" value="IGNORE" />
  </component>
  <component name="CreatePatchCommitExecutor">
    <option name="PATCH_PATH" value="" />
  </component>
  <component name="ExecutionTargetManager" SELECTED_TARGET="default_target" />
  <component name="FavoritesManager">
    <favorites_list name="djkooks.github.com" />
  </component>
  <component name="FileEditorManager">
    <leaf SIDE_TABS_SIZE_LIMIT_KEY="300">
      <file leaf-file-name="main.css" pinned="false" current-in-tab="false">
        <entry file="file://$PROJECT_DIR$/_site/assets/css/main.css">
          <provider selected="true" editor-type-id="text-editor">
            <state relative-caret-position="0">
              <caret line="0" column="8316" selection-start-line="0" selection-start-column="8316" selection-end-line="0" selection-end-column="8316" />
              <folding />
            </state>
          </provider>
        </entry>
      </file>
      <file leaf-file-name="main.css" pinned="false" current-in-tab="false">
        <entry file="file://$PROJECT_DIR$/assets/css/main.css">
          <provider selected="true" editor-type-id="text-editor">
            <state relative-caret-position="0">
              <caret line="0" column="8316" selection-start-line="0" selection-start-column="8316" selection-end-line="0" selection-end-column="8316" />
              <folding />
            </state>
          </provider>
        </entry>
      </file>
      <file leaf-file-name="Readme.md" pinned="false" current-in-tab="false">
        <entry file="file://$PROJECT_DIR$/Readme.md">
          <provider editor-type-id="MarkdownFxPreviewEditor">
            <state />
          </provider>
          <provider selected="true" editor-type-id="split-provider[text-editor;MarkdownPreviewEditor]">
            <state split_layout="FIRST">
              <first_editor relative-caret-position="690">
                <caret line="46" column="12" selection-start-line="46" selection-start-column="12" selection-end-line="46" selection-end-column="12" />
                <folding />
              </first_editor>
              <second_editor />
            </state>
          </provider>
        </entry>
      </file>
      <file leaf-file-name="index.html" pinned="false" current-in-tab="false">
        <entry file="file://$PROJECT_DIR$/_site/how-to-use/index.html">
          <provider selected="true" editor-type-id="text-editor">
            <state relative-caret-position="1065">
              <caret line="71" column="9" selection-start-line="71" selection-start-column="9" selection-end-line="71" selection-end-column="9" />
              <folding />
            </state>
          </provider>
        </entry>
      </file>
      <file leaf-file-name="about.html" pinned="false" current-in-tab="true">
        <entry file="file://$PROJECT_DIR$/about.html">
          <provider selected="true" editor-type-id="text-editor">
            <state relative-caret-position="195">
              <caret line="13" column="42" selection-start-line="13" selection-start-column="42" selection-end-line="13" selection-end-column="42" />
              <folding />
            </state>
          </provider>
        </entry>
      </file>
    </leaf>
  </component>
  <component name="Git.Settings">
    <option name="RECENT_GIT_ROOT_PATH" value="$PROJECT_DIR$" />
  </component>
  <component name="IdeDocumentHistory">
    <option name="CHANGED_PATHS">
      <list>
        <option value="$PROJECT_DIR$/_site/assets/css/main.css" />
        <option value="$PROJECT_DIR$/src/styl/_header.styl" />
        <option value="$PROJECT_DIR$/_site/how-to-use/index.html" />
        <option value="$PROJECT_DIR$/_config.yml" />
        <option value="$PROJECT_DIR$/about.html" />
      </list>
    </option>
  </component>
  <component name="JsBuildToolGruntFileManager" detection-done="true" sorting="DEFINITION_ORDER" />
  <component name="JsBuildToolPackageJson" detection-done="true" sorting="DEFINITION_ORDER">
    <package-json value="$PROJECT_DIR$/package.json" />
  </component>
  <component name="JsGulpfileManager">
    <detection-done>true</detection-done>
    <gulpfiles>
      <GulpfileState>
        <gulpfile-path>$PROJECT_DIR$/gulpfile.js</gulpfile-path>
      </GulpfileState>
    </gulpfiles>
    <sorting>DEFINITION_ORDER</sorting>
  </component>
  <component name="ProjectFrameBounds">
    <option name="x" value="64" />
    <option name="y" value="23" />
    <option name="width" value="1216" />
    <option name="height" value="777" />
  </component>
  <component name="ProjectLevelVcsManager" settingsEditedManually="false">
    <OptionsSetting value="true" id="Add" />
    <OptionsSetting value="true" id="Remove" />
    <OptionsSetting value="true" id="Checkout" />
    <OptionsSetting value="true" id="Update" />
    <OptionsSetting value="true" id="Status" />
    <OptionsSetting value="true" id="Edit" />
    <ConfirmationsSetting value="0" id="Add" />
    <ConfirmationsSetting value="0" id="Remove" />
  </component>
  <component name="ProjectView">
    <navigator currentView="ProjectPane" proportions="" version="1">
      <flattenPackages />
      <showMembers />
      <showModules />
      <showLibraryContents />
      <hideEmptyPackages />
      <abbreviatePackageNames />
      <autoscrollToSource />
      <autoscrollFromSource />
      <sortByType />
      <manualOrder />
      <foldersAlwaysOnTop value="true" />
    </navigator>
    <panes>
      <pane id="ProjectPane">
        <subPane>
          <PATH>
            <PATH_ELEMENT>
              <option name="myItemId" value="djkooks.github.com" />
              <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.ProjectViewProjectNode" />
            </PATH_ELEMENT>
          </PATH>
          <PATH>
            <PATH_ELEMENT>
              <option name="myItemId" value="djkooks.github.com" />
              <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.ProjectViewProjectNode" />
            </PATH_ELEMENT>
            <PATH_ELEMENT>
              <option name="myItemId" value="djkooks.github.com" />
              <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" />
            </PATH_ELEMENT>
          </PATH>
          <PATH>
            <PATH_ELEMENT>
              <option name="myItemId" value="djkooks.github.com" />
              <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.ProjectViewProjectNode" />
            </PATH_ELEMENT>
            <PATH_ELEMENT>
              <option name="myItemId" value="djkooks.github.com" />
              <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" />
            </PATH_ELEMENT>
            <PATH_ELEMENT>
              <option name="myItemId" value="src" />
              <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" />
            </PATH_ELEMENT>
          </PATH>
          <PATH>
            <PATH_ELEMENT>
              <option name="myItemId" value="djkooks.github.com" />
              <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.ProjectViewProjectNode" />
            </PATH_ELEMENT>
            <PATH_ELEMENT>
              <option name="myItemId" value="djkooks.github.com" />
              <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" />
            </PATH_ELEMENT>
            <PATH_ELEMENT>
              <option name="myItemId" value="_posts" />
              <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" />
            </PATH_ELEMENT>
          </PATH>
        </subPane>
      </pane>
      <pane id="Scope" />
      <pane id="Scratches" />
    </panes>
  </component>
  <component name="PropertiesComponent">
    <property name="settings.editor.selected.configurable" value="preferences.lookFeel" />
    <property name="settings.editor.splitter.proportion" value="0.2" />
    <property name="last_opened_file_path" value="$PROJECT_DIR$" />
    <property name="WebServerToolWindowFactoryState" value="false" />
    <property name="HbShouldOpenHtmlAsHb" value="" />
    <property name="nodejs_interpreter_path" value="/usr/local/bin/node" />
  </component>
  <component name="RunManager">
    <configuration default="true" type="NodeJSConfigurationType" factoryName="Node.js" path-to-node="project" working-dir="">
      <method />
    </configuration>
  </component>
  <component name="ShelveChangesManager" show_recycled="false">
    <option name="remove_strategy" value="false" />
  </component>
  <component name="TaskManager">
    <task active="true" id="Default" summary="Default task">
      <changelist id="227a5af6-fa58-4cd7-88fe-ee8b05ecd834" name="Default" comment="" />
      <created>1468293535463</created>
      <option name="number" value="Default" />
      <option name="presentableId" value="Default" />
      <updated>1468293535463</updated>
      <workItem from="1468293537147" duration="631000" />
      <workItem from="1468395166282" duration="645000" />
      <workItem from="1471254224179" duration="1368000" />
      <workItem from="1472033091550" duration="594000" />
    </task>
    <servers />
  </component>
  <component name="TimeTrackingManager">
    <option name="totallyTimeSpent" value="3238000" />
  </component>
  <component name="ToolWindowManager">
    <frame x="64" y="23" width="1216" height="777" extended-state="0" />
    <editor active="true" />
    <layout>
      <window_info id="Gulp" active="false" anchor="left" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.33" sideWeight="0.5" order="2" side_tool="true" content_ui="tabs" />
      <window_info id="Project" active="false" anchor="left" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="true" show_stripe_button="true" weight="0.24937238" sideWeight="0.5" order="0" side_tool="false" content_ui="combo" />
      <window_info id="TODO" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.33" sideWeight="0.5" order="6" side_tool="false" content_ui="tabs" />
      <window_info id="Event Log" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.33" sideWeight="0.5" order="7" side_tool="true" content_ui="tabs" />
      <window_info id="npm" active="false" anchor="left" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.33" sideWeight="0.5" order="2" side_tool="true" content_ui="tabs" />
      <window_info id="Version Control" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.33" sideWeight="0.5" order="7" side_tool="false" content_ui="tabs" />
      <window_info id="Structure" active="false" anchor="left" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.25" sideWeight="0.5" order="1" side_tool="false" content_ui="tabs" />
      <window_info id="Terminal" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.33" sideWeight="0.5" order="7" side_tool="false" content_ui="tabs" />
      <window_info id="Favorites" active="false" anchor="left" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.33" sideWeight="0.5" order="2" side_tool="true" content_ui="tabs" />
      <window_info id="Cvs" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.25" sideWeight="0.5" order="4" side_tool="false" content_ui="tabs" />
      <window_info id="Message" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.33" sideWeight="0.5" order="0" side_tool="false" content_ui="tabs" />
      <window_info id="Commander" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.4" sideWeight="0.5" order="0" side_tool="false" content_ui="tabs" />
      <window_info id="Inspection" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.4" sideWeight="0.5" order="5" side_tool="false" content_ui="tabs" />
      <window_info id="Run" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.33" sideWeight="0.5" order="2" side_tool="false" content_ui="tabs" />
      <window_info id="Hierarchy" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.25" sideWeight="0.5" order="2" side_tool="false" content_ui="combo" />
      <window_info id="Find" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="true" show_stripe_button="true" weight="0.329927" sideWeight="0.5" order="1" side_tool="false" content_ui="tabs" />
      <window_info id="Ant Build" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.25" sideWeight="0.5" order="1" side_tool="false" content_ui="tabs" />
      <window_info id="Debug" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.4" sideWeight="0.5" order="3" side_tool="false" content_ui="tabs" />
    </layout>
  </component>
  <component name="Vcs.Log.UiProperties">
    <option name="RECENTLY_FILTERED_USER_GROUPS">
      <collection />
    </option>
    <option name="RECENTLY_FILTERED_BRANCH_GROUPS">
      <collection />
    </option>
  </component>
  <component name="VcsContentAnnotationSettings">
    <option name="myLimit" value="2678400000" />
  </component>
  <component name="XDebuggerManager">
    <breakpoint-manager />
    <watches-manager />
  </component>
  <component name="editorHistoryManager">
    <entry file="file://$PROJECT_DIR$/_site/assets/css/main.css">
      <provider selected="true" editor-type-id="text-editor">
        <state relative-caret-position="0">
          <caret line="0" column="8316" selection-start-line="0" selection-start-column="8316" selection-end-line="0" selection-end-column="8316" />
          <folding />
        </state>
      </provider>
    </entry>
    <entry file="file://$PROJECT_DIR$/assets/css/main.css">
      <provider selected="true" editor-type-id="text-editor">
        <state relative-caret-position="0">
          <caret line="0" column="8316" selection-start-line="0" selection-start-column="8316" selection-end-line="0" selection-end-column="8316" />
          <folding />
        </state>
      </provider>
    </entry>
    <entry file="file://$PROJECT_DIR$/Readme.md">
      <provider editor-type-id="MarkdownFxPreviewEditor">
        <state />
      </provider>
      <provider selected="true" editor-type-id="split-provider[text-editor;MarkdownPreviewEditor]">
        <state split_layout="FIRST">
          <first_editor relative-caret-position="690">
            <caret line="46" column="12" selection-start-line="46" selection-start-column="12" selection-end-line="46" selection-end-column="12" />
            <folding />
          </first_editor>
          <second_editor />
        </state>
      </provider>
    </entry>
    <entry file="file://$PROJECT_DIR$/_site/how-to-use/index.html">
      <provider selected="true" editor-type-id="text-editor">
        <state relative-caret-position="1065">
          <caret line="71" column="9" selection-start-line="71" selection-start-column="9" selection-end-line="71" selection-end-column="9" />
          <folding />
        </state>
      </provider>
    </entry>
    <entry file="file://$PROJECT_DIR$/about.html">
      <provider selected="true" editor-type-id="text-editor">
        <state relative-caret-position="0">
          <caret line="0" column="0" selection-start-line="0" selection-start-column="0" selection-end-line="0" selection-end-column="0" />
          <folding />
        </state>
      </provider>
    </entry>
    <entry file="file://$PROJECT_DIR$/_site/assets/css/main.css">
      <provider selected="true" editor-type-id="text-editor">
        <state relative-caret-position="0">
          <caret line="0" column="8316" selection-start-line="0" selection-start-column="8316" selection-end-line="0" selection-end-column="8316" />
          <folding />
        </state>
      </provider>
    </entry>
    <entry file="file://$PROJECT_DIR$/assets/css/main.css">
      <provider selected="true" editor-type-id="text-editor">
        <state relative-caret-position="0">
          <caret line="0" column="8316" selection-start-line="0" selection-start-column="8316" selection-end-line="0" selection-end-column="8316" />
          <folding />
        </state>
      </provider>
    </entry>
    <entry file="file://$PROJECT_DIR$/Readme.md">
      <provider editor-type-id="MarkdownFxPreviewEditor">
        <state />
      </provider>
      <provider selected="true" editor-type-id="split-provider[text-editor;MarkdownPreviewEditor]">
        <state split_layout="FIRST">
          <first_editor relative-caret-position="690">
            <caret line="46" column="12" selection-start-line="46" selection-start-column="12" selection-end-line="46" selection-end-column="12" />
            <folding />
          </first_editor>
          <second_editor />
        </state>
      </provider>
    </entry>
    <entry file="file://$PROJECT_DIR$/_site/how-to-use/index.html">
      <provider selected="true" editor-type-id="text-editor">
        <state relative-caret-position="0">
          <caret line="0" column="0" selection-start-line="0" selection-start-column="0" selection-end-line="0" selection-end-column="0" />
          <folding />
        </state>
      </provider>
    </entry>
    <entry file="file://$PROJECT_DIR$/Readme.md">
      <provider editor-type-id="MarkdownFxPreviewEditor">
        <state />
      </provider>
      <provider selected="true" editor-type-id="split-provider[text-editor;MarkdownPreviewEditor]">
        <state split_layout="FIRST">
          <first_editor relative-caret-position="690">
            <caret line="46" column="12" selection-start-line="46" selection-start-column="12" selection-end-line="46" selection-end-column="12" />
            <folding />
          </first_editor>
          <second_editor />
        </state>
      </provider>
    </entry>
    <entry file="file://$PROJECT_DIR$/src/styl/_header.styl">
      <provider selected="true" editor-type-id="text-editor">
        <state relative-caret-position="167">
          <caret line="28" column="23" selection-start-line="28" selection-start-column="23" selection-end-line="28" selection-end-column="23" />
        </state>
      </provider>
    </entry>
    <entry file="file://$PROJECT_DIR$/assets/css/main.css">
      <provider selected="true" editor-type-id="text-editor">
        <state relative-caret-position="0">
          <caret line="0" column="8316" selection-start-line="0" selection-start-column="8316" selection-end-line="0" selection-end-column="8316" />
          <folding />
        </state>
      </provider>
    </entry>
    <entry file="file://$PROJECT_DIR$/_site/assets/css/main.css">
      <provider selected="true" editor-type-id="text-editor">
        <state relative-caret-position="0">
          <caret line="0" column="8316" selection-start-line="0" selection-start-column="8316" selection-end-line="0" selection-end-column="8316" />
          <folding />
        </state>
      </provider>
    </entry>
    <entry file="file://$PROJECT_DIR$/_site/gulpfile.js">
      <provider selected="true" editor-type-id="text-editor">
        <state relative-caret-position="-75">
          <caret line="11" column="43" selection-start-line="11" selection-start-column="43" selection-end-line="11" selection-end-column="43" />
        </state>
      </provider>
    </entry>
    <entry file="file://$PROJECT_DIR$/_site/how-to-use/index.html">
      <provider selected="true" editor-type-id="text-editor">
        <state relative-caret-position="1065">
          <caret line="71" column="9" selection-start-line="71" selection-start-column="9" selection-end-line="71" selection-end-column="9" />
          <folding />
        </state>
      </provider>
    </entry>
    <entry file="file://$PROJECT_DIR$/_config.yml">
      <provider selected="true" editor-type-id="text-editor">
        <state relative-caret-position="225">
          <caret line="15" column="19" selection-start-line="15" selection-start-column="19" selection-end-line="15" selection-end-column="19" />
        </state>
      </provider>
    </entry>
    <entry file="file://$PROJECT_DIR$/about.html">
      <provider selected="true" editor-type-id="text-editor">
        <state relative-caret-position="195">
          <caret line="13" column="42" selection-start-line="13" selection-start-column="42" selection-end-line="13" selection-end-column="42" />
          <folding />
        </state>
      </provider>
    </entry>
  </component>
</project>


text:
/*
 * @test
 * @bug 6331746
 * @summary Deadlock on synchronization problem
 * @author Shanliang JIANG
 * @run main DeadlockTest
 */

import javax.management.*;
import javax.management.timer.*;

public class DeadlockTest extends StandardMBean {
    public <T> DeadlockTest(T implementation, Class<T> mbeanInterface)
    throws NotCompliantMBeanException {
        super(implementation, mbeanInterface);
    }

    public MBeanInfo getCachedMBeanInfo() {
        return super.getCachedMBeanInfo();
    }

    public void cacheMBeanInfo(MBeanInfo mi) {
        super.cacheMBeanInfo(mi);
    }

    public static void main(String[] args) throws Exception {
        System.out.println("main: No deadlock please.");

        System.out.println("main: Create a BadBay to hold the lock forever.");
        DeadlockTest dt = new DeadlockTest(new Timer(), TimerMBean.class);

        BadBoy bb = new BadBoy(dt);
        bb.start();

        final long timeout = 2000;
        long stopTime = System.currentTimeMillis() + timeout;
        long timeToWait = timeout;
        synchronized(bb) {
            while(!bb.gotLock || timeToWait > 0) {
                bb.wait(timeToWait);

                timeToWait = stopTime - System.currentTimeMillis();
            }
        }

        if (!bb.gotLock) {
            throw new RuntimeException("Failed to get lock, impossible!");
        }

        System.out.println("main: The BadBay is holding the lock forever.");

        System.out.println("main: Create a WorkingBoy to see blocking ...");
        WorkingBoy wb = new WorkingBoy(dt);

        stopTime = System.currentTimeMillis() + timeout;
        timeToWait = timeout;

        synchronized(wb) {
            wb.start();

            while(!wb.done || timeToWait > 0) {
                wb.wait(timeToWait);

                timeToWait = stopTime - System.currentTimeMillis();
            }
        }

        if (!wb.done) {
            throw new RuntimeException("It is blocked!");
        }

        System.out.println("main: OK, bye bye.");
    }

    private static class BadBoy extends Thread {
        public BadBoy(Object o) {
            setDaemon(true);

            this.o = o;
        }

        public void run() {
            System.out.println("BadBoy-run: keep synchronization lock forever!");

            synchronized(o) {
                synchronized(this) {
                    gotLock = true;

                    this.notify();
                }

                try {
                    Thread.sleep(10000000);
                } catch (Exception e) {
                    // OK
                }
            }
        }

        final Object o;
        public boolean gotLock;
    }

    private static class WorkingBoy extends Thread {
        public WorkingBoy(DeadlockTest sm) {
            setDaemon(true);

            this.sm = sm;
        }

        public void run() {
            try {
                System.out.println("WorkingBoy-run: calling StandardMBean methods ...");

                System.out.println("WorkingBoy-run: calling setImplementation ...");
                sm.setImplementation(new Timer());

                System.out.println("WorkingBoy-run: calling getImplementation ...");
                sm.getImplementation();

                System.out.println("WorkingBoy-run: calling getMBeanInterface ...");
                sm.getMBeanInterface();

                System.out.println("WorkingBoy-run: calling getImplementationClass ...");
                sm.getImplementationClass();

                System.out.println("WorkingBoy-run: calling cacheMBeanInfo ...");
                sm.cacheMBeanInfo(null);

                System.out.println("WorkingBoy-run: calling getCachedMBeanInfo ...");
                sm.getCachedMBeanInfo();

                System.out.println("WorkingBoy-run: All done!");

                synchronized(this) {
                    done = true;

                    this.notifyAll();
                }
            } catch (NotCompliantMBeanException ne) {
                // Impossible?
                throw new RuntimeException(ne);
            }
        }

        final DeadlockTest sm;
        public boolean done;
    }
}


text:
import os
import subprocess

from telemetry.core import util
from telemetry.core.platform import platform_backend

class DesktopPlatformBackend(platform_backend.PlatformBackend):

  # This is an abstract class. It is OK to have abstract methods.
  # pylint: disable=W0223

  def GetFlushUtilityName(self):
    return NotImplementedError()

  def _FindNewestFlushUtility(self):
    flush_command = None
    flush_command_mtime = 0

    chrome_root = util.GetChromiumSrcDir()
    for build_dir, build_type in util.GetBuildDirectories():
      candidate = os.path.join(chrome_root, build_dir, build_type,
                               self.GetFlushUtilityName())
      if os.access(candidate, os.X_OK):
        candidate_mtime = os.stat(candidate).st_mtime
        if candidate_mtime > flush_command_mtime:
          flush_command = candidate
          flush_command_mtime = candidate_mtime

    return flush_command

  def FlushSystemCacheForDirectory(self, directory, ignoring=None):
    assert directory and os.path.exists(directory), \
        'Target directory %s must exist' % directory
    flush_command = self._FindNewestFlushUtility()
    assert flush_command, \
        'You must build %s first' % self.GetFlushUtilityName()

    args = [flush_command, '--recurse']
    directory_contents = os.listdir(directory)
    for item in directory_contents:
      if not ignoring or item not in ignoring:
        args.append(os.path.join(directory, item))

    if len(args) < 3:
      return

    p = subprocess.Popen(args)
    p.wait()
    assert p.returncode == 0, 'Failed to flush system cache'