text:
<!DOCTYPE html>

<title>
Oct10
</title>

Multiplexing and Demultiplexing

    A multiplexing/demultiplexing
    service is needed for all computer networks. Your computer
    recieves data through the transport layer and is redirected
    to different processes. For example if are downloading web
    pages on one FTP session and two Telnet sessions, there are
    4 process: one FTP, two Telnet, one HTTP.

Sockets: doors that pass data from the processes to
        network, and from the network to processes.

Because at any time there can be more than one socket in
    the recieving host, each socket has a unique identifier.
    Identifiers depend the types UDP or TCP socket.

Demultiplexing:  the job of delivering data in a transport-layer
        segment to the correct socket.

Multiplexing: The job of collecting data chunks
            at the source host from different sockets, encapsulating header info, creating
             segments, and passing the segments to the network layer.

It is important to note that multiplexing and demultiplexing
    are used when a single protocol in one layer is used by multiple
    protocols at the next layer above it. Special fields that indicate
     the socket for segments to be delivered to are source port number field, and destination port number field.
Each port number is a 16-bit integer ranging from 0 - 65535. The port
numbers ranging from 0 - 1023 are called well-known port numbers and are restricted. This means
 that they are reserved for well known applicaiton protocols such as HTTP and FTP. Every new application
  must be assigned the application port number. UDP basically does
  multi and demultiplexing by assigning each socket in the host a port
  number, so when a segment is recieved at the host, the transport
   layer examines the destination port number and sends that segment to the
   corresponding socket.

Connectionless Multiplexing and Demultiplexing

A UDP socket is identified by a pair that has
a destination IP address and a destination port number. Therefore, if two
UDP segments have different source IP addresses / source port numbers, but have
the same destination IP address / destination port number, then the two segments
will be directed to the same destination process via the same destination socket

Connection-Oriented Multiplexing and Demultiplexing

One difference between a TCP and UDP socket is that a TCP is defined
    by a 4 tuple: source
IP address, source port number, destination IP address, destination port number.

TCP server applications have a socket that waits for established connection
        requests from the clients on port number 1200.

A connection-establishment request is a TCP segment
        with port number 1200, with a special connection-establishment bit set
         in the header, and the segment includes a source port number that is chosen by the client.


text:
require 'jellyfish/test'

class RegexpLookAlike
  class MatchData
    def captures
      ["this", "is", "a", "test"]
    end
  end

  def match(string)
    ::RegexpLookAlike::MatchData.new if string == "/this/is/a/test/"
  end

  def keys
    ["one", "two", "three", "four"]
  end
end

# stolen from sinatra
describe 'Sinatra routing_test.rb' do
  paste :jellyfish

  %w[get put post delete options patch head].each do |verb|
    would "define #{verb.upcase} request handlers with #{verb}" do
      app = Class.new{
        include Jellyfish
        send verb, '/hello' do
          'Hello World'
        end
      }.new

      status, _, body = send(verb, '/hello', app)
      status.should.eq 200
      body  .should.eq ['Hello World']
    end
  end

  would '404s when no route satisfies the request' do
    app = Class.new{
      include Jellyfish
      get('/foo'){}
    }.new
    status, _, _ = get('/bar', app)
    status.should.eq 404
  end

  would 'allows using unicode' do
    app = Class.new{
      include Jellyfish
      controller_include Jellyfish::NormalizedPath
      get("/f\u{f6}\u{f6}"){}
    }.new
    status, _, _ = get('/f%C3%B6%C3%B6', app)
    status.should.eq 200
  end

  would 'handle encoded slashes correctly' do
    app = Class.new{
      include Jellyfish
      controller_include Jellyfish::NormalizedPath
      get(%r{^/(.+)}){ |m| m[1] }
    }.new
    status, _, body = get('/foo%2Fbar', app)
    status.should.eq 200
    body  .should.eq ['foo/bar']
  end

  would 'override the content-type in error handlers' do
    app = Class.new{
      include Jellyfish
      get{
        self.headers 'Content-Type' => 'text/plain'
        status, headers, body = jellyfish.app.call(env)
        self.status  status
        self.body    body
        headers_merge(headers)
      }
    }.new(Class.new{
      include Jellyfish
      handle Jellyfish::NotFound do
        headers_merge 'Content-Type' => 'text/html'
        status 404
        '
Not Found
'
      end
    }.new)

    status, headers, body = get('/foo', app)
    status                 .should.eq 404
    headers['Content-Type'].should.eq 'text/html'
    body                   .should.eq ['
Not Found
']
  end

  would 'match empty PATH_INFO to "/" if no route is defined for ""' do
    app = Class.new{
      include Jellyfish
      controller_include Jellyfish::NormalizedPath
      get('/'){ 'worked' }
    }.new

    status, _, body = get('', app)
    status.should.eq 200
    body  .should.eq ['worked']
  end

  would 'exposes params with indifferent hash' do
    app = Class.new{
      include Jellyfish
      controller_include Jellyfish::NormalizedParams

      get %r{^/(?<foo>\w+)} do
        params['foo'].should.eq 'bar'
        params[:foo ].should.eq 'bar'
        'well, alright'
      end
    }.new

    _, _, body = get('/bar', app)
    body.should.eq ['well, alright']
  end

  would 'merges named params and query string params in params' do
    app = Class.new{
      include Jellyfish
      controller_include Jellyfish::NormalizedParams

      get %r{^/(?<foo>\w+)} do
        params['foo'].should.eq 'bar'
        params['baz'].should.eq 'biz'
      end
    }.new

    status, _, _ = get('/bar', app, 'QUERY_STRING' => 'baz=biz')
    status.should.eq 200
  end

  would 'support named captures like %r{/hello/(?<person>[^/?#]+)}' do
    app = Class.new{
      include Jellyfish
      get Regexp.new('/hello/(?<person>[^/?#]+)') do |m|
        "Hello #{m['person']}"
      end
    }.new

    _, _, body = get('/hello/Frank', app)
    body.should.eq ['Hello Frank']
  end

  would 'support optional named captures' do
    app = Class.new{
      include Jellyfish
      get Regexp.new('/page(?<format>.[^/?#]+)?') do |m|
        "format=#{m[:format]}"
      end
    }.new

    status, _, body = get('/page.html', app)
    status.should.eq 200
    body  .should.eq ['format=.html']

    status, _, body = get('/page.xml', app)
    status.should.eq 200
    body  .should.eq ['format=.xml']

    status, _, body = get('/page', app)
    status.should.eq 200
    body  .should.eq ['format=']
  end

  would 'not concatinate params with the same name' do
    app = Class.new{
      include Jellyfish
      controller_include Jellyfish::NormalizedParams

      get(%r{^/(?<foo>\w+)}){ |m| params[:foo] }
    }.new

    _, _, body = get('/a', app, 'QUERY_STRING' => 'foo=b')
    body.should.eq ['a']
  end

  would 'support basic nested params' do
    app = Class.new{
      include Jellyfish
      get('/hi'){ request.params['person']['name'] }
    }.new

    status, _, body = get('/hi', app,
                          'QUERY_STRING' => 'person[name]=John+Doe')
    status.should.eq 200
    body.should.eq ['John Doe']
  end

  would "expose nested params with indifferent hash" do
    app = Class.new{
      include Jellyfish
      controller_include Jellyfish::NormalizedParams

      get '/testme' do
        params['bar']['foo'].should.eq 'baz'
        params['bar'][:foo ].should.eq 'baz'
        'well, alright'
      end
    }.new

    _, _, body = get('/testme', app, 'QUERY_STRING' => 'bar[foo]=baz')
    body.should.eq ['well, alright']
  end

  would 'preserve non-nested params' do
    app = Class.new{
      include Jellyfish
      get '/foo' do
        request.params['article_id']     .should.eq '2'
        request.params['comment']['body'].should.eq 'awesome'
        request.params['comment[body]']  .should.eq nil
        'looks good'
      end
    }.new

    status, _, body = get('/foo', app,
      'QUERY_STRING' => 'article_id=2&comment[body]=awesome')
    status.should.eq 200
    body  .should.eq ['looks good']
  end

  would 'match paths that include spaces encoded with %20' do
    app = Class.new{
      include Jellyfish
      controller_include Jellyfish::NormalizedPath
      get('/path with spaces'){ 'looks good' }
    }.new

    status, _, body = get('/path%20with%20spaces', app)
    status.should.eq 200
    body  .should.eq ['looks good']
  end

  would 'match paths that include spaces encoded with +' do
    app = Class.new{
      include Jellyfish
      controller_include Jellyfish::NormalizedPath
      get('/path with spaces'){ 'looks good' }
    }.new

    status, _, body = get('/path+with+spaces', app)
    status.should.eq 200
    body  .should.eq ['looks good']
  end

  would 'make regular expression captures available' do
    app = Class.new{
      include Jellyfish
      get(/^\/fo(.*)\/ba(.*)/) do |m|
        m[1..-1].should.eq ['orooomma', 'f']
        'right on'
      end
    }.new

    status, _, body = get('/foorooomma/baf', app)
    status.should.eq 200
    body  .should.eq ['right on']
  end

  would 'support regular expression look-alike routes' do
    app = Class.new{
      include Jellyfish
      controller_include Jellyfish::NormalizedParams
      matcher = Object.new
      def matcher.match path
        %r{/(?<one>\w+)/(?<two>\w+)/(?<three>\w+)/(?<four>\w+)}.match(path)
      end

      get(matcher) do |m|
        [m, params].each do |q|
          q[:one]  .should.eq 'this'
          q[:two]  .should.eq 'is'
          q[:three].should.eq 'a'
          q[:four] .should.eq 'test'
        end
        'right on'
      end
    }.new

    status, _, body = get('/this/is/a/test/', app)
    status.should.eq 200
    body  .should.eq ['right on']
  end

  would 'raise a TypeError when pattern is not a String or Regexp' do
    lambda{ Class.new{ include Jellyfish; get(42){} } }.
      should.raise(TypeError)
  end

  would 'match routes defined in superclasses' do
    sup = Class.new{
      include Jellyfish
      get('/foo'){ 'foo' }
    }
    app = Class.new(sup){
      get('/bar'){ 'bar' }
    }.new

    %w[foo bar].each do |path|
      status, _, body = get("/#{path}", app)
      status.should.eq 200
      body  .should.eq [path]
    end
  end

  would 'match routes itself first then downward app' do
    sup = Class.new{
      include Jellyfish
      get('/foo'){ 'foo sup' }
      get('/bar'){ 'bar sup' }
    }
    app = Class.new{
      include Jellyfish
      get('/foo'){ 'foo sub' }
    }.new(sup.new)

    status, _, body = get('/foo', app)
    status.should.eq 200
    body  .should.eq ['foo sub']

    status, _, body = get('/bar', app)
    status.should.eq 200
    body  .should.eq ['bar sup']
  end

  would 'allow using call to fire another request internally' do
    app = Class.new{
      include Jellyfish
      get '/foo' do
        status, headers, body = call(env.merge('PATH_INFO' => '/bar'))
        self.status  status
        self.headers headers
        self.body    body.map(&:upcase)
      end

      get '/bar' do
        'bar'
      end
    }.new

    status, _, body = get('/foo', app)
    status.should.eq 200
    body  .should.eq ['BAR']
  end

  would 'play well with other routing middleware' do
    middleware = Class.new{include Jellyfish}
    inner_app  = Class.new{include Jellyfish; get('/foo'){ 'hello' } }
    app = Rack::Builder.app do
      use middleware
      map('/test'){ run inner_app.new }
    end

    status, _, body = get('/test/foo', app)
    status.should.eq 200
    body  .should.eq ['hello']
  end
end

redpajama_set_name: RedPajamaGithub


text:
package org.cagrid.websso.client.acegi;

public class DefaultUserDetailsService extends BaseUserDetailsService {

	@Override
	protected WebSSOUser loadUserByGridId(String gridId) {
		//retrieve user information from database using CSM or Data Access Service by unique GridID.
		//for default implementation username=gridId;
		String userName=gridId;
		DefaultGrantedAuthority [] grantedAuthorities=new DefaultGrantedAuthority[]{new DefaultGrantedAuthority("ROLE_DEFAULT")};
		WebSSOUser user=new WebSSOUser(userName, "default",true,true,true,true,grantedAuthorities);
		return user;
	}
}


text:
<!DOCTYPE html>

	<meta charset="UTF-8">
	<title>App Movil</title>
	<link rel="shortcut icon" type="text/css" href="{{STATIC_URL}}img/icono de la Aplicacion Movil.png">
	<link rel="stylesheet" type="text/css" href="{{STATIC_URL}}jquery.mobile-1.3.1/jquery.mobile-1.3.1.css">
	<link rel="stylesheet" type="text/css" href="{{STATIC_URL}}css/css.css">

Lugares Turisticos

	Atrás

		{% for elemento in lugares_turisticos %}

{{elemento.nombre}}

{{elemento.descripcion}}

			{% empty %}
			NO SE ENCUENTRA NADA REGISTRADO POR EL MOMENTO
		{% endfor %}


text:
/*
 *      linux/arch/alpha/kernel/irq_i8259.c
 *
 * This is the 'legacy' 8259A Programmable Interrupt Controller,
 * present in the majority of PC/AT boxes.
 *
 * Started hacking from linux-2.3.30pre6/arch/i386/kernel/i8259.c.
 */

#include <linux/init.h>
#include <linux/cache.h>
#include <linux/sched.h>
#include <linux/irq.h>
#include <linux/interrupt.h>

#include <asm/io.h>

#include "proto.h"
#include "irq_impl.h"

/* Note mask bit is true for DISABLED irqs.  */
static unsigned int cached_irq_mask = 0xffff;
static DEFINE_SPINLOCK(i8259_irq_lock);

static inline void
i8259_update_irq_hw(unsigned int irq, unsigned long mask)
{
	int port = 0x21;
	if (irq & 8) mask >>= 8;
	if (irq & 8) port = 0xA1;
	outb(mask, port);
}

inline void
i8259a_enable_irq(struct irq_data *d)
{
	spin_lock(&i8259_irq_lock);
	i8259_update_irq_hw(d->irq, cached_irq_mask &= ~(1 << d->irq));
	spin_unlock(&i8259_irq_lock);
}

static inline void
__i8259a_disable_irq(unsigned int irq)
{
	i8259_update_irq_hw(irq, cached_irq_mask |= 1 << irq);
}

void
i8259a_disable_irq(struct irq_data *d)
{
	spin_lock(&i8259_irq_lock);
	__i8259a_disable_irq(d->irq);
	spin_unlock(&i8259_irq_lock);
}

void
i8259a_mask_and_ack_irq(struct irq_data *d)
{
	unsigned int irq = d->irq;

	spin_lock(&i8259_irq_lock);
	__i8259a_disable_irq(irq);

	/* Ack the interrupt making it the lowest priority.  */
	if (irq >= 8) {
		outb(0xE0 | (irq - 8), 0xa0);   /* ack the slave */
		irq = 2;
	}
	outb(0xE0 | irq, 0x20);			/* ack the master */
	spin_unlock(&i8259_irq_lock);
}

struct irq_chip i8259a_irq_type = {
	.name		= "XT-PIC",
	.irq_unmask	= i8259a_enable_irq,
	.irq_mask	= i8259a_disable_irq,
	.irq_mask_ack	= i8259a_mask_and_ack_irq,
};

void __init
init_i8259a_irqs(void)
{
	static struct irqaction cascade = {
		.handler	= no_action,
		.name		= "cascade",
	};

	long i;

	outb(0xff, 0x21);	/* mask all of 8259A-1 */
	outb(0xff, 0xA1);	/* mask all of 8259A-2 */

	for (i = 0; i < 16; i++) {
		irq_set_chip_and_handler(i, &i8259a_irq_type, handle_level_irq);
	}

	setup_irq(2, &cascade);
}

#if defined(CONFIG_ALPHA_GENERIC)
# define IACK_SC	alpha_mv.iack_sc
#elif defined(CONFIG_ALPHA_APECS)
# define IACK_SC	APECS_IACK_SC
#elif defined(CONFIG_ALPHA_LCA)
# define IACK_SC	LCA_IACK_SC
#elif defined(CONFIG_ALPHA_CIA)
# define IACK_SC	CIA_IACK_SC
#elif defined(CONFIG_ALPHA_PYXIS)
# define IACK_SC	PYXIS_IACK_SC
#elif defined(CONFIG_ALPHA_TITAN)
# define IACK_SC	TITAN_IACK_SC
#elif defined(CONFIG_ALPHA_TSUNAMI)
# define IACK_SC	TSUNAMI_IACK_SC
#elif defined(CONFIG_ALPHA_IRONGATE)
# define IACK_SC        IRONGATE_IACK_SC
#endif
/* Note that CONFIG_ALPHA_POLARIS is intentionally left out here, since
   sys_rx164 wants to use isa_no_iack_sc_device_interrupt for some reason.  */

#if defined(IACK_SC)
void
isa_device_interrupt(unsigned long vector)
{
	/*
	 * Generate a PCI interrupt acknowledge cycle.  The PIC will
	 * respond with the interrupt vector of the highest priority
	 * interrupt that is pending.  The PALcode sets up the
	 * interrupts vectors such that irq level L generates vector L.
	 */
	int j = *(vuip) IACK_SC;
	j &= 0xff;
	handle_irq(j);
}
#endif

#if defined(CONFIG_ALPHA_GENERIC) || !defined(IACK_SC)
void
isa_no_iack_sc_device_interrupt(unsigned long vector)
{
	unsigned long pic;

	/*
	 * It seems to me that the probability of two or more *device*
	 * interrupts occurring at almost exactly the same time is
	 * pretty low.  So why pay the price of checking for
	 * additional interrupts here if the common case can be
	 * handled so much easier?
	 */
	/*
	 *  The first read of gives you *all* interrupting lines.
	 *  Therefore, read the mask register and and out those lines
	 *  not enabled.  Note that some documentation has 21 and a1
	 *  write only.  This is not true.
	 */
	pic = inb(0x20) | (inb(0xA0) << 8);	/* read isr */
	pic &= 0xFFFB;				/* mask out cascade & hibits */

	while (pic) {
		int j = ffz(~pic);
		pic &= pic - 1;
		handle_irq(j);
	}
}
#endif


text:
<?xml version="1.0" encoding="UTF-8"?><?xml-stylesheet href="test-to-html.xsl" type="text/xml"?>

<!--

Copyright (c) 2001-2004 World Wide Web Consortium,
(Massachusetts Institute of Technology, Institut National de
Recherche en Informatique et en Automatique, Keio University).  All
Rights Reserved.  This program is distributed under the W3C's Software
Intellectual Property License.  This program 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 W3C License http://www.w3.org/Consortium/Legal/ for more details.

-->

<!DOCTYPE test SYSTEM "dom3.dtd">
<test xmlns="http://www.w3.org/2001/DOM-Test-Suite/Level-3" name="nodegetbaseuri12">
<metadata>
<title>nodegetbaseuri12</title>
<creator>IBM</creator>
<description>
	Using getBaseURI verify if the entity epsilon is absolute
	and matches the URL of the document entity.
</description>
<contributor>Neil Delima</contributor>
<date qualifier="created">2002-06-10</date>
<subject resource="http://www.w3.org/TR/2004/REC-DOM-Level-3-Core-20040407/core#Node3-baseURI"/>
<subject resource="http://www.w3.org/Bugs/Public/show_bug.cgi?id=419"/>
<subject resource="http://www.w3.org/TR/2004/REC-DOM-Level-3-Core-20040407/infoset-mapping#Infoset2Entity"/>
</metadata>
<var name="doc" type="Document"/>
<var name="docType" type="DocumentType"/>
<var name="entitiesMap" type="NamedNodeMap"/>
<var name="entity" type="Entity"/>
<var name="baseURI" type="DOMString"/>
<load var="doc" href="hc_staff" willBeModified="false"/>
<doctype var="docType" obj="doc"/>
<entities var="entitiesMap" obj="docType"/>
<getNamedItem var="entity" obj="entitiesMap" name='"epsilon"'/>
<baseURI var="baseURI" obj="entity" interface="Node"/>
<assertURIEquals actual="baseURI" id="entityBase" isAbsolute="true" name='"hc_staff"'/>
</test>


text:
<?php

namespace Auth\Factory\Form;

use Auth\Form\Login;
use Auth\Form\LoginInputFilter;
use Interop\Container\ContainerInterface;
use Laminas\ServiceManager\FactoryInterface;
use Laminas\ServiceManager\ServiceLocatorInterface;
use Laminas\Form\FormElementManager;

class LoginFactory implements FactoryInterface
{
    /**
     * Create a Login form
     *
     * @param  ContainerInterface $container
     * @param  string             $requestedName
     * @param  null|array         $options
     *
     * @return Login
     * @throws ServiceNotFoundException if unable to resolve the service.
     * @throws ServiceNotCreatedException if an exception is raised when
     *     creating a service.
     * @throws ContainerException if any other error occurs
     */
    public function __invoke(ContainerInterface $container, $requestedName, array $options = null)
    {
        /* @var LoginInputFilter $filter */
        $filter = $container->get('Auth\Form\LoginInputFilter');
        $form = new Login(null, array());
        $form->setInputfilter($filter);
        return $form;
    }

    /**
     * Create service
     *
     * @param ServiceLocatorInterface $serviceLocator
     *
     * @return Login
     */
    public function createService(ServiceLocatorInterface $serviceLocator)
    {
        return $this($serviceLocator, Login::class);
    }
}


text:
using namespace rubinius;

class VMTest {
public:
  SharedState* shared;
  VM* state;
  ConfigParser* config_parser;
  Configuration config;

  void create() {
    config_parser = new ConfigParser;
    shared = new SharedState(0, config, *config_parser);
    state = shared->new_vm();
    state->initialize();
    state->boot();

    state->global_lock().take();
  }

  void destroy() {
    state->global_lock().drop();
    VM::discard(state);
    SharedState::discard(shared);
  }

  void setUp() {
    create();
  }

  void tearDown() {
    destroy();
  }

  VM* new_vm() {
    return shared->new_vm();
  }

};

#endif


text:
<?php

namespace Saxulum\JsonDocument\NodeToArray;

use Saxulum\JsonDocument\AbstractNode;

class NodeToArray
{
    /**
     * @var AbstractNodeToArrayHandler[]
     */
    protected $handlers;

    /**
     * @param array $handlers
     */
    public function __construct(array $handlers)
    {
        foreach ($handlers as $handler) {
            if (!$handler instanceof AbstractNodeToArrayHandler) {
                throw new \InvalidArgumentException("Handlers must extend AbstractNodeToArrayHandler!");
            }

            $handler->setMainHandler($this);
            $this->handlers[] = $handler;
        }
    }

    /**
     * @param  AbstractNode $node
     * @param  bool         $embedded
     * @return array
     */
    public function getArray(AbstractNode $node, $embedded = false)
    {
        foreach ($this->handlers as $handler) {
            if ($handler->isResponsible($node)) {
                return $handler->getArray($node, $embedded);
            }
        }
    }
}


text:
package almhirt.streaming

import scala.concurrent.ExecutionContext
import scala.concurrent.duration._
import org.reactivestreams.{ Subscriber, Subscription }
import akka.actor._
import almhirt.common._

object DelegatingSubscriber {
  def apply[T](delegateTo: ActorRef): Subscriber[T] =
    new DelegatingSubscriber[T](delegateTo, None)

  def apply[T](delegateTo: ActorRef, onErrorAction: Throwable ⇒ Unit): Subscriber[T] =
    new DelegatingSubscriber[T](delegateTo, Some(onErrorAction))

}

object DelegatingEventSubscriber {
  def apply[T <: Event](delegateTo: ActorRef): Subscriber[T] =
    DelegatingSubscriber[T](delegateTo)

  def apply[T <: Event](delegateTo: ActorRef, onErrorAction: Throwable ⇒ Unit): Subscriber[T] =
    DelegatingSubscriber[T](delegateTo, onErrorAction)

}

object DelegatingCommandSubscriber {
  def apply[T <: Command](delegateTo: ActorRef): Subscriber[T] =
    DelegatingSubscriber[T](delegateTo)
}

private[streaming] class DelegatingSubscriber[T](delegateTo: ActorRef, onErrorAction: Option[Throwable ⇒ Unit]) extends Subscriber[T] {
  private[this] var sub: Option[Subscription] = None

  private def requestMore() = sub.map(_.request(1))

  override def onError(cause: Throwable): Unit = {
    onErrorAction.foreach(_(cause))
    scala.sys.error(cause.getMessage)
  }

  override def onSubscribe(subscription: Subscription): Unit = {
    sub = Some(subscription)
    requestMore()
  }

  override def onComplete(): Unit = {
    sub.foreach(s ⇒ {
      s.cancel()
      sub = None
    })
  }

  override def onNext(element: T): Unit = {
    delegateTo ! element
    requestMore()
  }
}


text:
layout: post

#event information
title:  "Script to Stage to Script"
cover: "/images/William_Hogarth_016.jpg"
attribution:
  name: "Painting of John Gay's The Beggar's Opera, Act 5"
  author: "William Hogarth"
  license: "the public domain"
  name_url: "https://commons.wikimedia.org/wiki/File:William_Hogarth_016.jpg"
  license_url: "http://fairuse.stanford.edu/overview/public-domain/welcome"
date:   "2016-03-17 19:00"
endDate:   "2016-03-17 21:00"
creation: "2016-03-11"
start_time: "7:00 PM"
end_time: "9:00 PM"
location:
  name: "Folger Shakespeare Library"
  address:
    - "201 E Capitol St SE"
  city: Washington
  state: DC
  zip: 20003
tags: [ 'Folger Shakespeare Library', 'Arts', 'Lectures' ]
excerpt: >
  Join leading scholars for insightful talks and thought-provoking
  conversations with the Shakespeare Anniversary Lecture Series
  at the Folger.

---

Dr. Tiffany Stern, Professor of Early Modern Drama at Oxford
University, presents a lecture on the relationship between ballads
and Shakespeare's plays on stage and page. Considering the way ballads
were traded at playhouses, sung in plays, performed as post-play
entertainments, and sold to promote playbooks, Stern examines how
ballads, in performance and in broadsheets, came to advertise
Shakespeare – and how Shakespeare's plays, in performance and in
playbooks, came to advertise ballads.

Join leading scholars for insightful talks and thought-provoking
conversations with the Shakespeare Anniversary Lecture Series
at the Folger. Tickets are $10 for members or $15 for non-members.
They are avilable for [purchase online](http://www.folger.edu/events/tiffany-stern-script-stage-script) or by calling 202.544.7077.


text:
package people;

import party.IParty;
import platform.IPlatform;

import java.util.Map;

public interface IVoter {

    /**
     * Adds this voter's aggregate divergence from the party to a {@link java.util.Map Map} that tracks this voter's
     * aggregate divergence by party.
     *
     * @param party the party
     */
    void addPartyAggregateDivergence(IParty party);

    /**
     * Adds this voter's odds of voting for the party to a {@link java.util.Map Map} that tracks this voter's odds of
     * voting for parties.
     *
     * @param party the party
     */
    void addPartyVotingOdds(IParty party);

    IPlatform getVoterPlatform();

    Map<IParty, Double> getPartyVotingOddsMap();

    Map<IParty, Double> getPartyDivergenceMap();
}


text:
div.timeline-frame {
    overflow: hidden;
}

div.timeline-axis {
    filter: alpha(opacity = 60);
    -khtml-opacity: 0.6;
    -moz-opacity: 0.6;
    opacity: 0.6;
    border-width: 1px;
    border-top-style: solid;
}

div.timeline-axis-grid {
    border-left-style: solid;
    border-width: 1px;
}

div.timeline-axis-grid-minor {
    filter: alpha(opacity = 30);
    -khtml-opacity: 0.3;
    -moz-opacity: 0.3;
    opacity: 0.3;
}

div.timeline-axis-grid-major {
    filter: alpha(opacity = 50);
    -khtml-opacity: 0.5;
    -moz-opacity: 0.5;
    opacity: 0.5;
}

div.timeline-axis-text {
    padding: 3px;
    white-space: nowrap;
}

div.timeline-event {
    display: inline-block;
}

div.timeline-event-selected {
    z-index: 999;
}

div.timeline-event.timeline-event-box {
    text-align: center;
    border-style: solid;
    border-width: 1px;
    border-radius: 5px;
    -moz-border-radius: 5px; /* For Firefox 3.6 and older */
}

div.timeline-event.timeline-event-dot {
    border-style: solid;
    border-width: 5px;
    border-radius: 5px;
    -moz-border-radius: 5px; /* For Firefox 3.6 and older */
}

div.timeline-event.timeline-event-range {
    border-style: solid;
    border-width: 1px;
    border-radius: 2px;
    -moz-border-radius: 2px; /* For Firefox 3.6 and older */
}

div.timeline-frame div.timeline-event-dot-container {
    border: none;
}

div.timeline-event-range-drag-left {
    cursor: w-resize;
    z-index: 1000;
}

div.timeline-event-range-drag-right {
    cursor: e-resize;
    z-index: 1000;
}

div.timeline-event-line {
    border-left-width: 1px;
    border-left-style: solid;
}

div.timeline-event-content {
    margin: 5px;
    white-space: nowrap;
    overflow: hidden;
}

div.timeline-groups-axis {
    border-width: 1px;
}

div.timeline-groups-axis-onleft {
    border-style: none groove none none;
}

div.timeline-groups-axis-onright {
    border-style: none none none groove;
}

div.timeline-groups-text {
    padding-left: 10px;
    padding-right: 10px;
}

div.timeline-currenttime {
    background-color: #FF7F6E;
    width: 2px;
}

div.timeline-customtime {
    background-color: #6E94FF;
    width: 2px;
    cursor: move;
}

div.timeline-navigation-new, div.timeline-navigation-delete,
div.timeline-navigation-zoom-in, div.timeline-navigation-zoom-out,
div.timeline-navigation-move-left, div.timeline-navigation-move-right,
div.timeline-navigation-move-today {
    cursor: pointer;
    float: left;
    padding: 5px;
    text-decoration: none;
}

div.timeline-navigation-new-line {
    border-right: dotted 1px;
}

div.timeline-navigation-delete {
    padding: 0 0 0 5px;
    background: url('img/deleteEvent.png') no-repeat center;
    width: 13px;
    height: 13px;
}

div.timeline-selectable div.timeline-event {
    cursor: pointer;
}

div.timeline-selectable div.timeline-event-content {
    cursor: pointer;
}

div.timeline-event-selected div.timeline-event-content {
    cursor: move;
}


text:
#include <gio/gio.h>
#include <stdlib.h>
#include <string.h>

#include "gdbus-sessionbus.h"

typedef struct
{
  GVariant *params;
  gboolean did_run;
} Activation;

static void
activate (GAction  *action,
          GVariant *parameter,
          gpointer  user_data)
{
  Activation *activation = user_data;

  if (parameter)
    activation->params = g_variant_ref (parameter);
  else
    activation->params = NULL;
  activation->did_run = TRUE;
}

static void
test_basic (void)
{
  Activation a = { 0, };
  GSimpleAction *action;
  gchar *name;
  GVariantType *parameter_type;
  gboolean enabled;
  GVariantType *state_type;
  GVariant *state;

  action = g_simple_action_new ("foo", NULL);
  g_assert (g_action_get_enabled (G_ACTION (action)));
  g_assert (g_action_get_parameter_type (G_ACTION (action)) == NULL);
  g_assert (g_action_get_state_type (G_ACTION (action)) == NULL);
  g_assert (g_action_get_state_hint (G_ACTION (action)) == NULL);
  g_assert (g_action_get_state (G_ACTION (action)) == NULL);
  g_object_get (action,
                "name", &name,
                "parameter-type", &parameter_type,
                "enabled", &enabled,
                "state-type", &state_type,
                "state", &state,
                 NULL);
  g_assert_cmpstr (name, ==, "foo");
  g_assert (parameter_type == NULL);
  g_assert (enabled);
  g_assert (state_type == NULL);
  g_assert (state == NULL);
  g_free (name);

  g_signal_connect (action, "activate", G_CALLBACK (activate), &a);
  g_assert (!a.did_run);
  g_action_activate (G_ACTION (action), NULL);
  g_assert (a.did_run);
  a.did_run = FALSE;

  g_simple_action_set_enabled (action, FALSE);
  g_action_activate (G_ACTION (action), NULL);
  g_assert (!a.did_run);

  if (g_test_undefined ())
    {
      g_test_expect_message (G_LOG_DOMAIN, G_LOG_LEVEL_CRITICAL,
                             "*assertion*g_variant_is_of_type*failed*");
      g_action_activate (G_ACTION (action), g_variant_new_string ("xxx"));
      g_test_assert_expected_messages ();
    }

  g_object_unref (action);
  g_assert (!a.did_run);

  action = g_simple_action_new ("foo", G_VARIANT_TYPE_STRING);
  g_assert (g_action_get_enabled (G_ACTION (action)));
  g_assert (g_variant_type_equal (g_action_get_parameter_type (G_ACTION (action)), G_VARIANT_TYPE_STRING));
  g_assert (g_action_get_state_type (G_ACTION (action)) == NULL);
  g_assert (g_action_get_state_hint (G_ACTION (action)) == NULL);
  g_assert (g_action_get_state (G_ACTION (action)) == NULL);

  g_signal_connect (action, "activate", G_CALLBACK (activate), &a);
  g_assert (!a.did_run);
  g_action_activate (G_ACTION (action), g_variant_new_string ("Hello world"));
  g_assert (a.did_run);
  g_assert_cmpstr (g_variant_get_string (a.params, NULL), ==, "Hello world");
  g_variant_unref (a.params);
  a.did_run = FALSE;

  if (g_test_undefined ())
    {
      g_test_expect_message (G_LOG_DOMAIN, G_LOG_LEVEL_CRITICAL,
                             "*assertion*!= NULL*failed*");
      g_action_activate (G_ACTION (action), NULL);
      g_test_assert_expected_messages ();
    }

  g_object_unref (action);
  g_assert (!a.did_run);
}

static gboolean
strv_has_string (gchar       **haystack,
                 const gchar  *needle)
{
  guint n;

  for (n = 0; haystack != NULL && haystack[n] != NULL; n++)
    {
      if (g_strcmp0 (haystack[n], needle) == 0)
        return TRUE;
    }
  return FALSE;
}

static gboolean
strv_strv_cmp (gchar **a, gchar **b)
{
  guint n;

  for (n = 0; a[n] != NULL; n++)
    {
       if (!strv_has_string (b, a[n]))
         return FALSE;
    }

  for (n = 0; b[n] != NULL; n++)
    {
       if (!strv_has_string (a, b[n]))
         return FALSE;
    }

  return TRUE;
}

static gboolean
strv_set_equal (gchar **strv, ...)
{
  gint count;
  va_list list;
  const gchar *str;
  gboolean res;

  res = TRUE;
  count = 0;
  va_start (list, strv);
  while (1)
    {
      str = va_arg (list, const gchar *);
      if (str == NULL)
        break;
      if (!strv_has_string (strv, str))
        {
          res = FALSE;
          break;
        }
      count++;
    }
  va_end (list);

  if (res)
    res = g_strv_length ((gchar**)strv) == count;

  return res;
}

static void
test_simple_group (void)
{
  GSimpleActionGroup *group;
  Activation a = { 0, };
  GSimpleAction *simple;
  GAction *action;
  gchar **actions;
  GVariant *state;

  simple = g_simple_action_new ("foo", NULL);
  g_signal_connect (simple, "activate", G_CALLBACK (activate), &a);
  g_assert (!a.did_run);
  g_action_activate (G_ACTION (simple), NULL);
  g_assert (a.did_run);
  a.did_run = FALSE;

  group = g_simple_action_group_new ();
  g_simple_action_group_insert (group, G_ACTION (simple));
  g_object_unref (simple);

  g_assert (!a.did_run);
  g_action_group_activate_action (G_ACTION_GROUP (group), "foo", NULL);
  g_assert (a.did_run);

  simple = g_simple_action_new_stateful ("bar", G_VARIANT_TYPE_STRING, g_variant_new_string ("hihi"));
  g_simple_action_group_insert (group, G_ACTION (simple));
  g_object_unref (simple);

  g_assert (g_action_group_has_action (G_ACTION_GROUP (group), "foo"));
  g_assert (g_action_group_has_action (G_ACTION_GROUP (group), "bar"));
  g_assert (!g_action_group_has_action (G_ACTION_GROUP (group), "baz"));
  actions = g_action_group_list_actions (G_ACTION_GROUP (group));
  g_assert_cmpint (g_strv_length (actions), ==, 2);
  g_assert (strv_set_equal (actions, "foo", "bar", NULL));
  g_strfreev (actions);
  g_assert (g_action_group_get_action_enabled (G_ACTION_GROUP (group), "foo"));
  g_assert (g_action_group_get_action_enabled (G_ACTION_GROUP (group), "bar"));
  g_assert (g_action_group_get_action_parameter_type (G_ACTION_GROUP (group), "foo") == NULL);
  g_assert (g_variant_type_equal (g_action_group_get_action_parameter_type (G_ACTION_GROUP (group), "bar"), G_VARIANT_TYPE_STRING));
  g_assert (g_action_group_get_action_state_type (G_ACTION_GROUP (group), "foo") == NULL);
  g_assert (g_variant_type_equal (g_action_group_get_action_state_type (G_ACTION_GROUP (group), "bar"), G_VARIANT_TYPE_STRING));
  g_assert (g_action_group_get_action_state_hint (G_ACTION_GROUP (group), "foo") == NULL);
  g_assert (g_action_group_get_action_state_hint (G_ACTION_GROUP (group), "bar") == NULL);
  g_assert (g_action_group_get_action_state (G_ACTION_GROUP (group), "foo") == NULL);
  state = g_action_group_get_action_state (G_ACTION_GROUP (group), "bar");
  g_assert (g_variant_type_equal (g_variant_get_type (state), G_VARIANT_TYPE_STRING));
  g_assert_cmpstr (g_variant_get_string (state, NULL), ==, "hihi");
  g_variant_unref (state);

  g_action_group_change_action_state (G_ACTION_GROUP (group), "bar", g_variant_new_string ("boo"));
  state = g_action_group_get_action_state (G_ACTION_GROUP (group), "bar");
  g_assert_cmpstr (g_variant_get_string (state, NULL), ==, "boo");
  g_variant_unref (state);

  action = g_simple_action_group_lookup (group, "bar");
  g_simple_action_set_enabled (G_SIMPLE_ACTION (action), FALSE);
  g_assert (!g_action_group_get_action_enabled (G_ACTION_GROUP (group), "bar"));

  g_simple_action_group_remove (group, "bar");
  action = g_simple_action_group_lookup (group, "foo");
  g_assert_cmpstr (g_action_get_name (action), ==, "foo");
  action = g_simple_action_group_lookup (group, "bar");
  g_assert (action == NULL);

  a.did_run = FALSE;
  g_object_unref (group);
  g_assert (!a.did_run);
}

static void
test_stateful (void)
{
  GSimpleAction *action;
  GVariant *state;

  action = g_simple_action_new_stateful ("foo", NULL, g_variant_new_string ("hihi"));
  g_assert (g_action_get_enabled (G_ACTION (action)));
  g_assert (g_action_get_parameter_type (G_ACTION (action)) == NULL);
  g_assert (g_action_get_state_hint (G_ACTION (action)) == NULL);
  g_assert (g_variant_type_equal (g_action_get_state_type (G_ACTION (action)),
                                  G_VARIANT_TYPE_STRING));
  state = g_action_get_state (G_ACTION (action));
  g_assert_cmpstr (g_variant_get_string (state, NULL), ==, "hihi");
  g_variant_unref (state);

  if (g_test_undefined ())
    {
      g_test_expect_message (G_LOG_DOMAIN, G_LOG_LEVEL_CRITICAL,
                             "*assertion*g_variant_is_of_type*failed*");
      g_simple_action_set_state (action, g_variant_new_int32 (123));
      g_test_assert_expected_messages ();
    }

  g_simple_action_set_state (action, g_variant_new_string ("hello"));
  state = g_action_get_state (G_ACTION (action));
  g_assert_cmpstr (g_variant_get_string (state, NULL), ==, "hello");
  g_variant_unref (state);

  g_object_unref (action);

  action = g_simple_action_new ("foo", NULL);

  if (g_test_undefined ())
    {
      g_test_expect_message (G_LOG_DOMAIN, G_LOG_LEVEL_CRITICAL,
                             "*assertion*!= NULL*failed*");
      g_simple_action_set_state (action, g_variant_new_int32 (123));
      g_test_assert_expected_messages ();
    }

  g_object_unref (action);
}

static gboolean foo_activated = FALSE;
static gboolean bar_activated = FALSE;

static void
activate_foo (GSimpleAction *simple,
              GVariant      *parameter,
              gpointer       user_data)
{
  g_assert (user_data == GINT_TO_POINTER (123));
  g_assert (parameter == NULL);
  foo_activated = TRUE;
}

static void
activate_bar (GSimpleAction *simple,
              GVariant      *parameter,
              gpointer       user_data)
{
  g_assert (user_data == GINT_TO_POINTER (123));
  g_assert_cmpstr (g_variant_get_string (parameter, NULL), ==, "param");
  bar_activated = TRUE;
}

static void
change_volume_state (GSimpleAction *action,
                     GVariant      *value,
                     gpointer       user_data)
{
  gint requested;

  requested = g_variant_get_int32 (value);

  /* Volume only goes from 0 to 10 */
  if (0 <= requested && requested <= 10)
    g_simple_action_set_state (action, value);
}

static void
test_entries (void)
{
  const GActionEntry entries[] = {
    { "foo",    activate_foo                                     },
    { "bar",    activate_bar, "s"                                },
    { "toggle", NULL,         NULL, "false"                      },
    { "volume", NULL,         NULL, "0",     change_volume_state }
  };
  GSimpleActionGroup *actions;
  GVariant *state;

  actions = g_simple_action_group_new ();
  g_simple_action_group_add_entries (actions, entries,
                                     G_N_ELEMENTS (entries),
                                     GINT_TO_POINTER (123));

  g_assert (!foo_activated);
  g_action_group_activate_action (G_ACTION_GROUP (actions), "foo", NULL);
  g_assert (foo_activated);
  foo_activated = FALSE;

  g_assert (!bar_activated);
  g_action_group_activate_action (G_ACTION_GROUP (actions), "bar",
                                  g_variant_new_string ("param"));
  g_assert (bar_activated);
  g_assert (!foo_activated);

  if (g_test_undefined ())
    {
      const GActionEntry bad_type = {
        "bad-type", NULL, "ss"
      };
      const GActionEntry bad_state = {
        "bad-state", NULL, NULL, "flse"
      };

      g_test_expect_message (G_LOG_DOMAIN, G_LOG_LEVEL_CRITICAL,
                             "*not a valid GVariant type string*");
      g_simple_action_group_add_entries (actions, &bad_type, 1, NULL);
      g_test_assert_expected_messages ();

      g_test_expect_message (G_LOG_DOMAIN, G_LOG_LEVEL_CRITICAL,
                             "*could not parse*");
      g_simple_action_group_add_entries (actions, &bad_state, 1, NULL);
      g_test_assert_expected_messages ();
    }

  state = g_action_group_get_action_state (G_ACTION_GROUP (actions), "volume");
  g_assert_cmpint (g_variant_get_int32 (state), ==, 0);
  g_variant_unref (state);

  /* should change */
  g_action_group_change_action_state (G_ACTION_GROUP (actions), "volume",
                                      g_variant_new_int32 (7));
  state = g_action_group_get_action_state (G_ACTION_GROUP (actions), "volume");
  g_assert_cmpint (g_variant_get_int32 (state), ==, 7);
  g_variant_unref (state);

  /* should not change */
  g_action_group_change_action_state (G_ACTION_GROUP (actions), "volume",
                                      g_variant_new_int32 (11));
  state = g_action_group_get_action_state (G_ACTION_GROUP (actions), "volume");
  g_assert_cmpint (g_variant_get_int32 (state), ==, 7);
  g_variant_unref (state);

  g_object_unref (actions);
}

static void
test_parse_detailed (void)
{
  struct {
    const gchar *detailed;
    const gchar *expected_name;
    const gchar *expected_target;
    const gchar *expected_error;
  } testcases[] = {
    { "abc",              "abc",    NULL,       NULL },
    { " abc",             NULL,     NULL,       "invalid format" },
    { " abc",             NULL,     NULL,       "invalid format" },
    { "abc:",             NULL,     NULL,       "invalid format" },
    { ":abc",             NULL,     NULL,       "invalid format" },
    { "abc(",             NULL,     NULL,       "invalid format" },
    { "abc)",             NULL,     NULL,       "invalid format" },
    { "(abc",             NULL,     NULL,       "invalid format" },
    { ")abc",             NULL,     NULL,       "invalid format" },
    { "abc::xyz",         "abc",    "'xyz'",    NULL },
    { "abc('xyz')",       "abc",    "'xyz'",    NULL },
    { "abc(42)",          "abc",    "42",       NULL },
    { "abc(int32 42)",    "abc",    "42",       NULL },
    { "abc(@i 42)",       "abc",    "42",       NULL },
    { "abc (42)",         NULL,     NULL,       "invalid format" },
    { "abc(42abc)",       NULL,     NULL,       "invalid character in number" },
    { "abc(42, 4)",       "abc",    "(42, 4)",  "expected end of input" },
    { "abc(42,)",         "abc",    "(42,)",    "expected end of input" }
  };
  gint i;

  for (i = 0; i < G_N_ELEMENTS (testcases); i++)
    {
      GError *error = NULL;
      GVariant *target;
      gboolean success;
      gchar *name;

      success = g_action_parse_detailed_name (testcases[i].detailed, &name, &target, &error);
      g_assert (success == (error == NULL));
      if (success && testcases[i].expected_error)
        g_error ("Unexpected success on '%s'.  Expected error containing '%s'",
                 testcases[i].detailed, testcases[i].expected_error);

      if (!success && !testcases[i].expected_error)
        g_error ("Unexpected failure on '%s': %s", testcases[i].detailed, error->message);

      if (!success)
        {
          if (!strstr (error->message, testcases[i].expected_error))
            g_error ("Failure message '%s' for string '%s' did not contained expected substring '%s'",
                     error->message, testcases[i].detailed, testcases[i].expected_error);

          g_error_free (error);
          continue;
        }

      g_assert_cmpstr (name, ==, testcases[i].expected_name);
      g_assert ((target == NULL) == (testcases[i].expected_target == NULL));
      if (target)
        {
          GVariant *expected;

          expected = g_variant_parse (NULL, testcases[i].expected_target, NULL, NULL, NULL);
          g_assert (expected);

          g_assert (g_variant_equal (expected, target));
          g_variant_unref (expected);
          g_variant_unref (target);
        }

      g_free (name);
    }
}

GHashTable *activation_counts;

static void
count_activation (const gchar *action)
{
  gint count;

  if (activation_counts == NULL)
    activation_counts = g_hash_table_new (g_str_hash, g_str_equal);
  count = GPOINTER_TO_INT (g_hash_table_lookup (activation_counts, action));
  count++;
  g_hash_table_insert (activation_counts, (gpointer)action, GINT_TO_POINTER (count));
}

static gint
activation_count (const gchar *action)
{
  if (activation_counts == NULL)
    return 0;

  return GPOINTER_TO_INT (g_hash_table_lookup (activation_counts, action));
}

static void
activate_action (GSimpleAction *action, GVariant *parameter, gpointer user_data)
{
  count_activation (g_action_get_name (G_ACTION (action)));
}

static void
activate_toggle (GSimpleAction *action, GVariant *parameter, gpointer user_data)
{
  GVariant *old_state, *new_state;

  count_activation (g_action_get_name (G_ACTION (action)));

  old_state = g_action_get_state (G_ACTION (action));
  new_state = g_variant_new_boolean (!g_variant_get_boolean (old_state));
  g_simple_action_set_state (action, new_state);
  g_variant_unref (old_state);
}

static void
activate_radio (GSimpleAction *action, GVariant *parameter, gpointer user_data)
{
  GVariant *new_state;

  count_activation (g_action_get_name (G_ACTION (action)));

  new_state = g_variant_new_string (g_variant_get_string (parameter, NULL));
  g_simple_action_set_state (action, new_state);
}

static gboolean
compare_action_groups (GActionGroup *a, GActionGroup *b)
{
  gchar **alist;
  gchar **blist;
  gint i;
  gboolean equal;
  gboolean ares, bres;
  gboolean aenabled, benabled;
  const GVariantType *aparameter_type, *bparameter_type;
  const GVariantType *astate_type, *bstate_type;
  GVariant *astate_hint, *bstate_hint;
  GVariant *astate, *bstate;

  alist = g_action_group_list_actions (a);
  blist = g_action_group_list_actions (b);
  equal = strv_strv_cmp (alist, blist);

  for (i = 0; equal && alist[i]; i++)
    {
      ares = g_action_group_query_action (a, alist[i], &aenabled, &aparameter_type, &astate_type, &astate_hint, &astate);
      bres = g_action_group_query_action (b, alist[i], &benabled, &bparameter_type, &bstate_type, &bstate_hint, &bstate);

      if (ares && bres)
        {
          equal = equal && (aenabled == benabled);
          equal = equal && ((!aparameter_type && !bparameter_type) || g_variant_type_equal (aparameter_type, bparameter_type));
          equal = equal && ((!astate_type && !bstate_type) || g_variant_type_equal (astate_type, bstate_type));
          equal = equal && ((!astate_hint && !bstate_hint) || g_variant_equal (astate_hint, bstate_hint));
          equal = equal && ((!astate && !bstate) || g_variant_equal (astate, bstate));

          if (astate_hint)
            g_variant_unref (astate_hint);
          if (bstate_hint)
            g_variant_unref (bstate_hint);
          if (astate)
            g_variant_unref (astate);
          if (bstate)
            g_variant_unref (bstate);
        }
      else
        equal = FALSE;
    }

  g_strfreev (alist);
  g_strfreev (blist);

  return equal;
}

static gboolean
stop_loop (gpointer data)
{
  GMainLoop *loop = data;

  g_main_loop_quit (loop);

  return G_SOURCE_REMOVE;
}

static GActionEntry exported_entries[] = {
  { "undo",  activate_action, NULL, NULL,      NULL },
  { "redo",  activate_action, NULL, NULL,      NULL },
  { "cut",   activate_action, NULL, NULL,      NULL },
  { "copy",  activate_action, NULL, NULL,      NULL },
  { "paste", activate_action, NULL, NULL,      NULL },
  { "bold",  activate_toggle, NULL, "true",    NULL },
  { "lang",  activate_radio,  "s",  "'latin'", NULL },
};

static void
list_cb (GObject      *source,
         GAsyncResult *res,
         gpointer      user_data)
{
  GDBusConnection *bus = G_DBUS_CONNECTION (source);
  GMainLoop *loop = user_data;
  GError *error = NULL;
  GVariant *v;
  gchar **actions;

  v = g_dbus_connection_call_finish (bus, res, &error);
  g_assert (v);
  g_variant_get (v, "(^a&s)", &actions);
  g_assert_cmpint (g_strv_length (actions), ==, G_N_ELEMENTS (exported_entries));
  g_free (actions);
  g_variant_unref (v);
  g_main_loop_quit (loop);
}

static gboolean
call_list (gpointer user_data)
{
  GDBusConnection *bus;

  bus = g_bus_get_sync (G_BUS_TYPE_SESSION, NULL, NULL);
  g_dbus_connection_call (bus,
                          g_dbus_connection_get_unique_name (bus),
                          "/",
                          "org.gtk.Actions",
                          "List",
                          NULL,
                          NULL,
                          0,
                          G_MAXINT,
                          NULL,
                          list_cb,
                          user_data);
  g_object_unref (bus);

  return G_SOURCE_REMOVE;
}

static void
describe_cb (GObject      *source,
             GAsyncResult *res,
             gpointer      user_data)
{
  GDBusConnection *bus = G_DBUS_CONNECTION (source);
  GMainLoop *loop = user_data;
  GError *error = NULL;
  GVariant *v;
  gboolean enabled;
  gchar *param;
  GVariantIter *iter;

  v = g_dbus_connection_call_finish (bus, res, &error);
  g_assert (v);
  /* FIXME: there's an extra level of tuplelization in here */
  g_variant_get (v, "((bgav))", &enabled, &param, &iter);
  g_assert (enabled == TRUE);
  g_assert_cmpstr (param, ==, "");
  g_assert_cmpint (g_variant_iter_n_children (iter), ==, 0);
  g_free (param);
  g_variant_iter_free (iter);
  g_variant_unref (v);

  g_main_loop_quit (loop);
}

static gboolean
call_describe (gpointer user_data)
{
  GDBusConnection *bus;

  bus = g_bus_get_sync (G_BUS_TYPE_SESSION, NULL, NULL);
  g_dbus_connection_call (bus,
                          g_dbus_connection_get_unique_name (bus),
                          "/",
                          "org.gtk.Actions",
                          "Describe",
                          g_variant_new ("(s)", "copy"),
                          NULL,
                          0,
                          G_MAXINT,
                          NULL,
                          describe_cb,
                          user_data);
  g_object_unref (bus);

  return G_SOURCE_REMOVE;
}

static void
test_dbus_export (void)
{
  GDBusConnection *bus;
  GSimpleActionGroup *group;
  GDBusActionGroup *proxy;
  GSimpleAction *action;
  GMainLoop *loop;
  GError *error = NULL;
  GVariant *v;
  guint id;
  gchar **actions;

  loop = g_main_loop_new (NULL, FALSE);

  session_bus_up ();
  bus = g_bus_get_sync (G_BUS_TYPE_SESSION, NULL, NULL);

  group = g_simple_action_group_new ();
  g_simple_action_group_add_entries (group,
                                     exported_entries,
                                     G_N_ELEMENTS (exported_entries),
                                     NULL);

  id = g_dbus_connection_export_action_group (bus, "/", G_ACTION_GROUP (group), &error);
  g_assert_no_error (error);

  proxy = g_dbus_action_group_get (bus, g_dbus_connection_get_unique_name (bus), "/");

  actions = g_action_group_list_actions (G_ACTION_GROUP (proxy));
  g_assert_cmpint (g_strv_length (actions), ==, 0);
  g_strfreev (actions);

  g_timeout_add (100, stop_loop, loop);
  g_main_loop_run (loop);

  actions = g_action_group_list_actions (G_ACTION_GROUP (proxy));
  g_assert_cmpint (g_strv_length (actions), ==, G_N_ELEMENTS (exported_entries));
  g_strfreev (actions);

  /* check that calling "List" works too */
  g_idle_add (call_list, loop);
  g_main_loop_run (loop);

  /* check that calling "Describe" works */
  g_idle_add (call_describe, loop);
  g_main_loop_run (loop);

  /* test that the initial transfer works */
  g_assert (G_IS_DBUS_ACTION_GROUP (proxy));
  g_assert (compare_action_groups (G_ACTION_GROUP (group), G_ACTION_GROUP (proxy)));

  /* test that various changes get propagated from group to proxy */
  action = g_simple_action_new_stateful ("italic", NULL, g_variant_new_boolean (FALSE));
  g_simple_action_group_insert (group, G_ACTION (action));
  g_object_unref (action);

  g_timeout_add (100, stop_loop, loop);
  g_main_loop_run (loop);

  g_assert (compare_action_groups (G_ACTION_GROUP (group), G_ACTION_GROUP (proxy)));

  action = G_SIMPLE_ACTION (g_simple_action_group_lookup (group, "cut"));
  g_simple_action_set_enabled (action, FALSE);

  g_timeout_add (100, stop_loop, loop);
  g_main_loop_run (loop);

  g_assert (compare_action_groups (G_ACTION_GROUP (group), G_ACTION_GROUP (proxy)));

  action = G_SIMPLE_ACTION (g_simple_action_group_lookup (group, "bold"));
  g_simple_action_set_state (action, g_variant_new_boolean (FALSE));

  g_timeout_add (100, stop_loop, loop);
  g_main_loop_run (loop);

  g_assert (compare_action_groups (G_ACTION_GROUP (group), G_ACTION_GROUP (proxy)));

  g_simple_action_group_remove (group, "italic");

  g_timeout_add (100, stop_loop, loop);
  g_main_loop_run (loop);

  g_assert (compare_action_groups (G_ACTION_GROUP (group), G_ACTION_GROUP (proxy)));

  /* test that activations and state changes propagate the other way */

  g_assert_cmpint (activation_count ("copy"), ==, 0);
  g_action_group_activate_action (G_ACTION_GROUP (proxy), "copy", NULL);

  g_timeout_add (100, stop_loop, loop);
  g_main_loop_run (loop);

  g_assert_cmpint (activation_count ("copy"), ==, 1);
  g_assert (compare_action_groups (G_ACTION_GROUP (group), G_ACTION_GROUP (proxy)));

  g_assert_cmpint (activation_count ("bold"), ==, 0);
  g_action_group_activate_action (G_ACTION_GROUP (proxy), "bold", NULL);

  g_timeout_add (100, stop_loop, loop);
  g_main_loop_run (loop);

  g_assert_cmpint (activation_count ("bold"), ==, 1);
  g_assert (compare_action_groups (G_ACTION_GROUP (group), G_ACTION_GROUP (proxy)));
  v = g_action_group_get_action_state (G_ACTION_GROUP (group), "bold");
  g_assert (g_variant_get_boolean (v));
  g_variant_unref (v);

  g_action_group_change_action_state (G_ACTION_GROUP (proxy), "bold", g_variant_new_boolean (FALSE));

  g_timeout_add (100, stop_loop, loop);
  g_main_loop_run (loop);

  g_assert_cmpint (activation_count ("bold"), ==, 1);
  g_assert (compare_action_groups (G_ACTION_GROUP (group), G_ACTION_GROUP (proxy)));
  v = g_action_group_get_action_state (G_ACTION_GROUP (group), "bold");
  g_assert (!g_variant_get_boolean (v));
  g_variant_unref (v);

  g_dbus_connection_unexport_action_group (bus, id);

  g_object_unref (proxy);
  g_object_unref (group);
  g_main_loop_unref (loop);
  g_object_unref (bus);

  session_bus_down ();
}

static gpointer
do_export (gpointer data)
{
  GActionGroup *group = data;
  GMainContext *ctx;
  gint i;
  GError *error = NULL;
  guint id;
  GDBusConnection *bus;
  GAction *action;
  gchar *path;

  ctx = g_main_context_new ();

  g_main_context_push_thread_default (ctx);

  bus = g_bus_get_sync (G_BUS_TYPE_SESSION, NULL, NULL);
  path = g_strdup_printf("/%p", data);

  for (i = 0; i < 100000; i++)
    {
      id = g_dbus_connection_export_action_group (bus, path, G_ACTION_GROUP (group), &error);
      g_assert_no_error (error);

      action = g_simple_action_group_lookup (G_SIMPLE_ACTION_GROUP (group), "a");
      g_simple_action_set_enabled (G_SIMPLE_ACTION (action),
                                   !g_action_get_enabled (action));

      g_dbus_connection_unexport_action_group (bus, id);

      while (g_main_context_iteration (ctx, FALSE));
    }

  g_free (path);
  g_object_unref (bus);

  g_main_context_pop_thread_default (ctx);

  g_main_context_unref (ctx);

  return NULL;
}

static void
test_dbus_threaded (void)
{
  GSimpleActionGroup *group[10];
  GThread *export[10];
  static GActionEntry entries[] = {
    { "a",  activate_action, NULL, NULL, NULL },
    { "b",  activate_action, NULL, NULL, NULL },
  };
  gint i;

  session_bus_up ();

  for (i = 0; i < 10; i++)
    {
      group[i] = g_simple_action_group_new ();
      g_simple_action_group_add_entries (group[i], entries, G_N_ELEMENTS (entries), NULL);
      export[i] = g_thread_new ("export", do_export, group[i]);
    }

  for (i = 0; i < 10; i++)
    g_thread_join (export[i]);

  for (i = 0; i < 10; i++)
    g_object_unref (group[i]);

  session_bus_down ();
}

static void
test_bug679509 (void)
{
  GDBusConnection *bus;
  GDBusActionGroup *proxy;
  GMainLoop *loop;

  loop = g_main_loop_new (NULL, FALSE);

  session_bus_up ();
  bus = g_bus_get_sync (G_BUS_TYPE_SESSION, NULL, NULL);

  proxy = g_dbus_action_group_get (bus, g_dbus_connection_get_unique_name (bus), "/");
  g_strfreev (g_action_group_list_actions (G_ACTION_GROUP (proxy)));
  g_object_unref (proxy);

  g_timeout_add (100, stop_loop, loop);
  g_main_loop_run (loop);

  g_main_loop_unref (loop);
  g_object_unref (bus);

  session_bus_down ();
}

static gchar *state_change_log;

static void
state_changed (GActionGroup *group,
               const gchar  *action_name,
               GVariant     *value,
               gpointer      user_data)
{
  GString *string;

  g_assert (!state_change_log);

  string = g_string_new (action_name);
  g_string_append_c (string, ':');
  g_variant_print_string (value, string, TRUE);
  state_change_log = g_string_free (string, FALSE);
}

static void
verify_changed (const gchar *log_entry)
{
  g_assert_cmpstr (state_change_log, ==, log_entry);
  g_clear_pointer (&state_change_log, g_free);
}

static void
ensure_state (GSimpleActionGroup *group,
              const gchar        *action_name,
              const gchar        *expected)
{
  GVariant *value;
  gchar *printed;

  value = g_action_group_get_action_state (G_ACTION_GROUP (group), action_name);
  printed = g_variant_print (value, TRUE);
  g_variant_unref (value);

  g_assert_cmpstr (printed, ==, expected);
  g_free (printed);
}

static void
test_property_actions (void)
{
  GSimpleActionGroup *group;
  GPropertyAction *action;
  GSocketClient *client;
  GApplication *app;

  group = g_simple_action_group_new ();
  g_signal_connect (group, "action-state-changed", G_CALLBACK (state_changed), NULL);

  client = g_socket_client_new ();
  app = g_application_new ("org.gtk.test", 0);

  /* string... */
  action = g_property_action_new ("app-id", app, "application-id");
  g_action_map_add_action (G_ACTION_MAP (group), G_ACTION (action));
  g_object_unref (action);

  /* uint... */
  action = g_property_action_new ("keepalive", app, "inactivity-timeout");
  g_action_map_add_action (G_ACTION_MAP (group), G_ACTION (action));
  g_object_unref (action);

  /* bool... */
  action = g_property_action_new ("tls", client, "tls");
  g_action_map_add_action (G_ACTION_MAP (group), G_ACTION (action));
  g_object_unref (action);

  /* enum... */
  action = g_property_action_new ("type", client, "type");
  g_action_map_add_action (G_ACTION_MAP (group), G_ACTION (action));
  g_object_unref (action);

  /* the objects should be held alive by the actions... */
  g_object_unref (client);
  g_object_unref (app);

  ensure_state (group, "app-id", "'org.gtk.test'");
  ensure_state (group, "keepalive", "uint32 0");
  ensure_state (group, "tls", "false");
  ensure_state (group, "type", "'stream'");

  verify_changed (NULL);

  /* some string tests... */
  g_action_group_change_action_state (G_ACTION_GROUP (group), "app-id", g_variant_new ("s", "org.gtk.test2"));
  verify_changed ("app-id:'org.gtk.test2'");
  g_assert_cmpstr (g_application_get_application_id (app), ==, "org.gtk.test2");
  ensure_state (group, "app-id", "'org.gtk.test2'");

  g_action_group_activate_action (G_ACTION_GROUP (group), "app-id", g_variant_new ("s", "org.gtk.test3"));
  verify_changed ("app-id:'org.gtk.test3'");
  g_assert_cmpstr (g_application_get_application_id (app), ==, "org.gtk.test3");
  ensure_state (group, "app-id", "'org.gtk.test3'");

  g_application_set_application_id (app, "org.gtk.test");
  verify_changed ("app-id:'org.gtk.test'");
  ensure_state (group, "app-id", "'org.gtk.test'");

  /* uint tests */
  g_action_group_change_action_state (G_ACTION_GROUP (group), "keepalive", g_variant_new ("u", 1234));
  verify_changed ("keepalive:uint32 1234");
  g_assert_cmpuint (g_application_get_inactivity_timeout (app), ==, 1234);
  ensure_state (group, "keepalive", "uint32 1234");

  g_action_group_activate_action (G_ACTION_GROUP (group), "keepalive", g_variant_new ("u", 5678));
  verify_changed ("keepalive:uint32 5678");
  g_assert_cmpuint (g_application_get_inactivity_timeout (app), ==, 5678);
  ensure_state (group, "keepalive", "uint32 5678");

  g_application_set_inactivity_timeout (app, 0);
  verify_changed ("keepalive:uint32 0");
  ensure_state (group, "keepalive", "uint32 0");

  /* bool tests */
  g_action_group_change_action_state (G_ACTION_GROUP (group), "tls", g_variant_new ("b", TRUE));
  verify_changed ("tls:true");
  g_assert (g_socket_client_get_tls (client));
  ensure_state (group, "tls", "true");

  /* test toggle true->false */
  g_action_group_activate_action (G_ACTION_GROUP (group), "tls", NULL);
  verify_changed ("tls:false");
  g_assert (!g_socket_client_get_tls (client));
  ensure_state (group, "tls", "false");

  /* and now back false->true */
  g_action_group_activate_action (G_ACTION_GROUP (group), "tls", NULL);
  verify_changed ("tls:true");
  g_assert (g_socket_client_get_tls (client));
  ensure_state (group, "tls", "true");

  g_socket_client_set_tls (client, FALSE);
  verify_changed ("tls:false");
  ensure_state (group, "tls", "false");

  /* enum tests */
  g_action_group_change_action_state (G_ACTION_GROUP (group), "type", g_variant_new ("s", "datagram"));
  verify_changed ("type:'datagram'");
  g_assert_cmpint (g_socket_client_get_socket_type (client), ==, G_SOCKET_TYPE_DATAGRAM);
  ensure_state (group, "type", "'datagram'");

  g_action_group_activate_action (G_ACTION_GROUP (group), "type", g_variant_new ("s", "stream"));
  verify_changed ("type:'stream'");
  g_assert_cmpint (g_socket_client_get_socket_type (client), ==, G_SOCKET_TYPE_STREAM);
  ensure_state (group, "type", "'stream'");

  g_socket_client_set_socket_type (client, G_SOCKET_TYPE_SEQPACKET);
  verify_changed ("type:'seqpacket'");
  ensure_state (group, "type", "'seqpacket'");

  /* Check some error cases... */
  g_test_expect_message ("GLib-GIO", G_LOG_LEVEL_CRITICAL, "*non-existent*");
  action = g_property_action_new ("foo", app, "xyz");
  g_test_assert_expected_messages ();
  g_object_unref (action);

  g_test_expect_message ("GLib-GIO", G_LOG_LEVEL_CRITICAL, "*writable*");
  action = g_property_action_new ("foo", app, "is-registered");
  g_test_assert_expected_messages ();
  g_object_unref (action);

  g_test_expect_message ("GLib-GIO", G_LOG_LEVEL_CRITICAL, "*type 'GSocketAddress'*");
  action = g_property_action_new ("foo", client, "local-address");
  g_test_assert_expected_messages ();
  g_object_unref (action);

  g_object_unref (group);
}

int
main (int argc, char **argv)
{
  g_test_init (&argc, &argv, NULL);

  g_test_add_func ("/actions/basic", test_basic);
  g_test_add_func ("/actions/simplegroup", test_simple_group);
  g_test_add_func ("/actions/stateful", test_stateful);
  g_test_add_func ("/actions/entries", test_entries);
  g_test_add_func ("/actions/parse-detailed", test_parse_detailed);
  g_test_add_func ("/actions/dbus/export", test_dbus_export);
  g_test_add_func ("/actions/dbus/threaded", test_dbus_threaded);
  g_test_add_func ("/actions/property", test_property_actions);

  return g_test_run ();
}


text:
package org.apache.hadoop.yarn.service.provider;

import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.yarn.api.records.LocalResource;
import org.apache.hadoop.yarn.api.records.LocalResourceType;
import org.apache.hadoop.yarn.api.records.LocalResourceVisibility;
import org.apache.hadoop.yarn.api.records.URL;
import org.apache.hadoop.yarn.service.api.records.ConfigFile;
import org.apache.hadoop.yarn.service.api.records.Configuration;
import org.apache.hadoop.yarn.service.containerlaunch.AbstractLauncher;
import org.apache.hadoop.yarn.service.containerlaunch.ContainerLaunchService;
import org.apache.hadoop.yarn.service.utils.SliderFileSystem;
import org.junit.Assert;
import org.junit.Test;
import org.mockito.Mockito;

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

import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

/**
 * Test functionality of ProviderUtils.
 */
public class TestProviderUtils {
  @Test
  public void testStaticFileLocalization() throws IOException {
    // A bunch of mocks ...
    ContainerLaunchService.ComponentLaunchContext compLaunchCtx =
        mock(ContainerLaunchService.ComponentLaunchContext.class);
    AbstractLauncher launcher = mock(AbstractLauncher.class);
    SliderFileSystem sfs = mock(SliderFileSystem.class);
    FileSystem fs = mock(FileSystem.class);
    when(fs.getFileStatus(any(Path.class))).thenAnswer(
        invocationOnMock -> new FileStatus(1L, false, 1, 1L, 1L,
            (Path) invocationOnMock.getArguments()[0]));
    when(fs.exists(any(Path.class))).thenReturn(true);
    when(sfs.getFileSystem()).thenReturn(fs);
    Configuration conf = mock(Configuration.class);
    List<ConfigFile> configFileList = new ArrayList<>();
    when(conf.getFiles()).thenReturn(configFileList);
    when(compLaunchCtx.getConfiguration()).thenReturn(conf);
    when(sfs.createAmResource(any(Path.class), any(LocalResourceType.class),
        any(LocalResourceVisibility.class))).thenAnswer(
          invocationOnMock -> new LocalResource() {
            @Override
            public URL getResource() {
              return URL.fromPath(((Path) invocationOnMock.getArguments()[0]));
            }

            @Override
            public void setResource(URL resource) {

            }

            @Override
            public long getSize() {
              return 0;
            }

            @Override
            public void setSize(long size) {

            }

            @Override
            public long getTimestamp() {
              return 0;
            }

            @Override
            public void setTimestamp(long timestamp) {

            }

            @Override
            public LocalResourceType getType() {
              return (LocalResourceType) invocationOnMock.getArguments()[1];
            }

            @Override
            public void setType(LocalResourceType type) {

            }

            @Override
            public LocalResourceVisibility getVisibility() {
              return LocalResourceVisibility.APPLICATION;
            }

            @Override
            public void setVisibility(LocalResourceVisibility visibility) {

            }

            @Override
            public String getPattern() {
              return null;
            }

            @Override
            public void setPattern(String pattern) {

            }

            @Override
            public boolean getShouldBeUploadedToSharedCache() {
              return false;
            }

            @Override
            public void setShouldBeUploadedToSharedCache(
                boolean shouldBeUploadedToSharedCache) {

            }
          });

    // Initialize list of files.
    //archive
    configFileList.add(new ConfigFile().srcFile("hdfs://default/sourceFile1")
        .destFile("destFile1").type(ConfigFile.TypeEnum.ARCHIVE)
        .visibility(LocalResourceVisibility.APPLICATION));

    //static file
    configFileList.add(new ConfigFile().srcFile("hdfs://default/sourceFile2")
        .destFile("folder/destFile_2").type(ConfigFile.TypeEnum.STATIC)
        .visibility(LocalResourceVisibility.APPLICATION));

    //This will be ignored since type is JSON
    configFileList.add(new ConfigFile().srcFile("hdfs://default/sourceFile3")
        .destFile("destFile3").type(ConfigFile.TypeEnum.JSON)
        .visibility(LocalResourceVisibility.APPLICATION));
    //No destination file specified
    configFileList.add(new ConfigFile().srcFile("hdfs://default/sourceFile4")
        .type(ConfigFile.TypeEnum.STATIC)
        .visibility(LocalResourceVisibility.APPLICATION));

    ProviderService.ResolvedLaunchParams resolved =
        new ProviderService.ResolvedLaunchParams();
    ProviderUtils.handleStaticFilesForLocalization(launcher, sfs,
        compLaunchCtx, resolved);
    Mockito.verify(launcher).addLocalResource(Mockito.eq("destFile1"),
        any(LocalResource.class));
    Mockito.verify(launcher).addLocalResource(
        Mockito.eq("destFile_2"), any(LocalResource.class));
    Mockito.verify(launcher).addLocalResource(
        Mockito.eq("sourceFile4"), any(LocalResource.class));

    Assert.assertEquals(3, resolved.getResolvedRsrcPaths().size());
    Assert.assertEquals(resolved.getResolvedRsrcPaths().get("destFile1"),
        "destFile1");
  }

  @Test
  public void testReplaceSpacesWithDelimiter() {
    String command = "ls  -l \" space\"";
    String expected = "ls,-l, space";
    String actual = ProviderUtils.replaceSpacesWithDelimiter(command, ",");
    Assert.assertEquals("replaceSpaceWithDelimiter produces unexpected result.",
        expected, actual);
  }
}


text:
require 'rouge'

module Winnow
  module Preprocessors
    class SourceCode < Preprocessor
      attr_reader :lexer

      def initialize(language)
        @lexer = Rouge::Lexer.find(language)
      end

      def preprocess(str)
        current_index = 0
        processed_chars = []

        lexer.lex(str).to_a.each do |token|
          type, chunk = token

          processed_chunk = case
          when type <= Rouge::Token::Tokens::Name
            'x'
          when type <= Rouge::Token::Tokens::Comment
            ''
          when type <= Rouge::Token::Tokens::Text
            ''
          else
            chunk
          end

          processed_chars += processed_chunk.chars.map do |c|
            [c, current_index]
          end

          current_index += chunk.length
        end

        processed_chars
      end
    end
  end
end


text:
<?php

namespace Eulogix\Cool\Bundle\CoreBundle\Model\Core;

class Dictionary extends BaseDictionary {

    public function getSettings() {
        $pr = parent::getSettings();

        /*

        1. entire hierarchy

        $myRuntimeOverrides = array(
             'atable'=> array (
                'attributes' =>
                    array (
                        'editable' => rand()?true:false,
                    ),
                'columns' =>
                    array (
                        'afieldname' => array (
                            'control_type' => rand()?'CBOX:AVALUE':'CBOX:ANOTHERVALUE',
                        ),
                    )
                )
        );

        return array_merge(\$pr,\$myRuntimeOverrides);

        */

        /*

        2. specific settings

        $pr['atable']['attributes']['editable'] = rand()?true:false;
        $pr['atable']['columns']['afieldname']['control']['_type'] = rand()?'CBOX:AVALUE':'CBOX:ANOTHERVALUE';

        */

        return $pr;
    }

}


text:
				From
				To
				amount
				Token

				Download

							« Prev

							1

							Next »

				{{transaction.from}}
				{{transaction.to}}
				{{transaction.amount}}
				{{transaction.token}}


text:
"""
Analyze: collections permisisons within source project.
"""

import fnmatch
import os

#from Permissions import Permissions

class Analyze:
    """Analyze object that scrapes project source looking for permissions matches."""

    def __init__(self, project_root, package_name, permissions, ignore, api):
        """Init method of Analyze."""
        self.project_root = project_root
        self.package_name = package_name
        self.permissions = permissions
        self.report_file_name = "reports/source_report_" + self.package_name + ".txt"
        self.source_files = []
        self.lines = []
        self.ignore = ignore
        self.api = api

    def search_project_root(self):
        """Looks in the source root for matching files with permissions."""
        print("Analyzing from project root....")

        source_root = self.project_root + "/app/src/"
        matches = []

        if self.api == "":
            self.api = "23"

        try:
            module = __import__("PermissionsAPI" + self.api)
        except ImportError:
            print("Could not find \'PermissionsAPI" + self.api + ".py\' for your specified API level")
            print("Attempting to run against the default API level 23")
            self.api = "23"
            module = __import__("PermissionsAPI23")

        my_class = getattr(module, "PermissionsAPI" + self.api)
        instance = my_class()

        # Add any ignored group permissions to the set of individual perms
        #dangerous_permissions = Permissions().dangerous_permissions
        dangerous_permissions = instance.dangerous_permissions
        if len(self.ignore['groups']) > 0:
            for group in self.ignore['groups']:

                # Get the specific list of permission group and permissions
                ignored_permissions = dangerous_permissions[group]
                for permission in ignored_permissions:
                    dangerous_permission = "android.permission." + permission
                    self.ignore['individual'].add(dangerous_permission)

        # Ignore specific permissions
        if len(self.ignore['individual']) > 0:
            print("Based on config, ignoring the following permissions:")
            for permission in self.ignore['individual']:
                print("Ignoring: " + permission)

        # Search for matching java files
        for root, dirnames, filenames in os.walk(source_root):
            for filename in fnmatch.filter(filenames, "*.java"):
                matches.append(os.path.join(root, filename))
        for file in matches:
            current_file = ""
            with open(file) as java_file:
                for index, line in enumerate(java_file):
                    if "permission" in line:

                        # Ignore the line if it has an ignored permission,
                        # otherwise add the line to the source_lines list
                        for ignored_permission in self.ignore['individual']:
                            if ignored_permission in line:
                                break
                        else:
                            if current_file is not java_file.name:
                                current_file = java_file.name
                                self.lines.append(('{} {:>4}\n'.format("\nFile: ", current_file)))
                                self.source_files.append(current_file)
                            self.lines.append(('{}'.format(line.rstrip())))
        print("Analyzing finished!")

        # Print the source report
        with open(self.report_file_name, "w+") as report:
            print(" Source Report ".center(50, '-'), file=report)
            print("{}".format("Package: " + self.package_name), file=report)
            print(file=report)

            print(" Permissions Found in Files ".center(50, '-'), file=report)
            for line in self.source_files:
                print(line, file=report)
            print(file=report)

            print(" Occurrences in Source ".center(50, '-'), file=report)
            for line in self.lines:
                print(line, file=report)
        print("Source report printed! Location: " + self.report_file_name)
        return self.report_file_name


text:
package org.lorislab.tower.web.common.action;

/**
 * The navigation constants.
 *
 * @author Andrej Petras
 */
public final class Navigation {

    /**
     * The default constructor.
     */
    private Navigation() {
        // empty constructor
    }

    /**
     * The navigation to home page.
     */
    public static String TO_HOME = "toHome";
    /**
     * The navigation to user profile.
     */
    public static String TO_PROFILE = "toProfile";
    /**
     * The navigation to user password.
     */
    public static String TO_PASSWORD = "toPassword";
    /**
     * The navigation to project search.
     */
    public static String TO_PROJECT = "toProject";
    /**
     * The navigation to project edit.
     */
    public static String TO_PROJECT_EDIT = "toProjectEdit";
    /**
     * The navigation to application search.
     */
    public static String TO_APPLICATION = "toApplication";
    /**
     * The navigation to application edit.
     */
    public static String TO_APPLICATION_EDIT = "toApplicationEdit";
    /**
     * The navigation to system search.
     */
    public static String TO_SYSTEM = "toSystem";
    /**
     * The navigation to system edit.
     */
    public static String TO_SYSTEM_EDIT = "toSystemEdit";
    /**
     * The navigation to source control search.
     */
    public static String TO_SCM = "toSCM";
    /**
     * The navigation to source control edit.
     */
    public static String TO_SCM_EDIT = "toSCMEdit";
    /**
     * The navigation to bug tracking system search.
     */
    public static String TO_BTS = "toBTS";
    /**
     * The navigation to bug tracking system edit.
     */
    public static String TO_BTS_EDIT = "toBTSEdit";
    /**
     * The navigation to agent search.
     */
    public static String TO_AGENT = "toAgent";
    /**
     * The navigation to agent edit.
     */
    public static String TO_AGENT_EDIT = "toAgentEdit";
    /**
     * The navigation to mail settings edit.
     */
    public static String TO_MAIL = "toMail";
    /**
     * The navigation to timer settings edit.
     */
    public static String TO_TIMER = "toTimer";

    /**
     * The navigation to user search.
     */
    public static String TO_USER = "toUser";
    /**
     * The navigation to user edit.
     */
    public static String TO_USER_EDIT = "toUserEdit";
    /**
     * The navigation to role search.
     */
    public static String TO_ROLE = "toRole";
    /**
     * The navigation to role edit.
     */
    public static String TO_ROLE_EDIT = "toRoleEdit";
    /**
     * The navigation to dashboard.
     */
    public static String TO_DASHBOARD_OVERVIEW = "toDashboardOverview";

    /**
     * The navigation to deploy.
     */
    public static String TO_DEPLOY = "toDeploy";

    /**
     * The navigation to active directory configuration.
     */
    public static String TO_AD = "toAd";
    /**
     * The navigation to active directory search configuration.
     */
    public static String TO_AD_SEARCH = "toAdSearch";

    /**
     * The navigation to notification group search.
     */
    public static String TO_NOTIFY_GROUP = "toNotifyGroup";
    /**
     * The navigation to notification group edit.
     */
    public static String TO_NOTIFY_GROUP_EDIT = "toNotifyGroupEdit";

    /**
     * The navigation to build search.
     */
    public static String TO_BUILD = "toBuild";
    /**
     * The navigation to build view.
     */
    public static String TO_BUILD_VIEW = "toBuildView";
}


text:
package com.samstarling.prometheusfinagle.filter

import com.samstarling.prometheusfinagle.metrics.Telemetry
import com.twitter.finagle.http.{Request, Response}
import com.twitter.finagle.{Service, SimpleFilter}
import com.twitter.util.Future

class HttpMonitoringFilter(telemetry: Telemetry,
                           labeller: ServiceLabeller[Request, Response] =
                             new HttpServiceLabeller)
    extends SimpleFilter[Request, Response] {

  private val counter = telemetry.counter(
    name = "incoming_http_requests_total",
    help = "The number of incoming HTTP requests",
    labelNames = labeller.keys
  )

  override def apply(request: Request,
                     service: Service[Request, Response]): Future[Response] = {
    service(request) onSuccess { response =>
      counter.labels(labeller.labelsFor(request, response): _*).inc()
    }
  }
}


text:
import sys
try:
    from setuptools import setup
except ImportError:
    # Let's not fail if setuptools is not available
    from distutils.core import setup

long_description = """
A pure-Python tiling window manager.

Features
========

    * Simple, small and extensible. It's easy to write your own layouts,
      widgets and commands.
    * Configured in Python.
    * Command shell that allows all aspects of
      Qtile to be managed and inspected.
    * Complete remote scriptability - write scripts to set up workspaces,
      manipulate windows, update status bar widgets and more.
    * Qtile's remote scriptability makes it one of the most thoroughly
      unit-tested window mangers around.
"""

dependencies = ['cairocffi>=0.6', 'cffi>=0.8.2', 'six>=1.4.1', 'xcffib>=0.1.10']

if sys.version_info >= (3, 4):
    pass
elif sys.version_info >= (3, 3):
    dependencies.append('asyncio')
elif sys.version_info <= (2, 6) or \
        (sys.version_info >= (3, 0) and sys.version_info <= (3, 1)):
    dependencies.append('importlib')
else:
    dependencies.append('trollius')

setup(
    name="qtile",
    version="0.9.0",
    description="A pure-Python tiling window manager.",
    long_description=long_description,
    classifiers=[
        "Intended Audience :: End Users/Desktop",
        "License :: OSI Approved :: MIT License",
        "Development Status :: 3 - Alpha",
        "Programming Language :: Python",
        "Operating System :: Unix",
        "Topic :: Desktop Environment :: Window Managers",
    ],
    keywords="qtile tiling window manager",
    author="Aldo Cortesi",
    author_email="aldo@nullcube.com",
    maintainer="Tycho Andersen",
    maintainer_email="tycho@tycho.ws",
    url="http://qtile.org",
    license="MIT",
    install_requires=dependencies,
    setup_requires=dependencies,
    packages=['libqtile',
              'libqtile.layout',
              'libqtile.widget',
              'libqtile.resources'
              ],
    package_data={'libqtile.resources': ['battery-icons/*.png']},
    scripts=[
        "bin/qsh",
        "bin/qtile",
        "bin/qtile-run",
        "bin/qtile-session"
    ],
    data_files=[
        ('share/man/man1', ['resources/qtile.1',
                            'resources/qsh.1'])],
)


text:
import React, { PropTypes } from 'react';
import cx from 'classnames';
import s from './ImageEditor.css';
import EditorMenu from './EditorMenu.js';
import ImageEditorHandler from './ImageEditorHandler.js';

class ImageEditor extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      x: 0,
      y: 0,
      show: false,
    };

    this.imageEditor = {};
    this.onMenuClick = this.onMenuClick.bind(this);
  }

  componentDidMount() {
    this.imageEditor = new ImageEditorHandler(this._C, {
      width: window.innerWidth,
      height: window.innerHeight,
      rightClickCallBack: this.rightClickCallBack.bind(this),
      clickCallBack: this.clickCallBack.bind(this),
    });

    window.addEventListener('resize', () => {
      let w = window.innerWidth;
      let h = window.innerHeight;
      this.imageEditor.setCanvasSize(w, h);
      this.imageEditor.reDraw();
    }, false);
  }

  rightClickCallBack(e) {
    this.openMenu(e);
  }

  clickCallBack(e) {
    this.closeMenu();
  }

  openMenu(event) {
    let x = event.clientX, y = event.clientY;
    this.setState({ x, y, show: true });
  }

  closeMenu() {
    this.setState(Object.assign({}, this.state, {
      show: false,
    }));
  }

  onMenuClick(element) {
    const role = element.getAttribute('role');
    switch(role) {
      case 'IMP':
        let input = document.createElement('input');
        input.type = 'file';
        input.multiple = true;
        input.onchange = (e) => {
          if(!e.target.files.length) return;
          this.imageEditor.inputFiles(e.target.files);
          this.closeMenu();
        };
        input.click();
        break;
      case 'Ro':
        this.imageEditor.rotateCurrentSelectedRgitn45();
        break;
      case 'R':
        this.imageEditor.removeImage(this.imageEditor.selectedImage);
        break;
      case 'X':
        break;
      default:
        break;
    }
  }

  render() {
    return (
        <div>
          <canvas className={cx(s.canvas)} ref={ e => { this._C = e; } }>
          </canvas>
          <EditorMenu {...this.state} onMenuClick={this.onMenuClick}/>
        </div>
      )
  }
}

export default ImageEditor;


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="colorPrimary">#3F51B5</color>
    <color name="colorPrimaryDark">#303F9F</color>
    <color name="colorAccent">#FF4081</color>
    <color name="background">#AFAFAF</color>
    <color name="title">#AFAFAF</color>
</resources>


text:
package com.ceco.marshmallow.gravitybox;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Environment;
import android.os.IBinder;
import android.os.ResultReceiver;
import android.util.Log;

import com.ceco.marshmallow.gravitybox.R;

public class RecordingService extends Service {
    private static final String TAG = "GB:RecordingService";

    public static final String ACTION_RECORDING_START = "gravitybox.intent.action.RECORDING_START";
    public static final String ACTION_RECORDING_STOP = "gravitybox.intent.action.RECORDING_STOP";
    public static final String ACTION_RECORDING_GET_STATUS = "gravitybox.intent.action.RECORDING_GET_STATUS";
    public static final String ACTION_RECORDING_STATUS_CHANGED = "gravitybox.intent.action.RECORDING_STATUS_CHANGED";
    public static final String EXTRA_RECORDING_STATUS = "recordingStatus";
    public static final String EXTRA_STATUS_MESSAGE = "statusMessage";
    public static final String EXTRA_AUDIO_FILENAME = "audioFileName";
    public static final String EXTRA_SAMPLING_RATE = "samplingRate";

    public static final int RECORDING_STATUS_IDLE = 0;
    public static final int RECORDING_STATUS_STARTED = 1;
    public static final int RECORDING_STATUS_STOPPED = 2;
    public static final int RECORDING_STATUS_ERROR = -1;

    public static final int DEFAULT_SAMPLING_RATE = 22050;

    private MediaRecorder mRecorder;
    private int mRecordingStatus = RECORDING_STATUS_IDLE;
    private Notification mRecordingNotif;
    private PendingIntent mPendingIntent;
    private int mSamplingRate = DEFAULT_SAMPLING_RATE;

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();

        mRecordingStatus = RECORDING_STATUS_IDLE;

        Notification.Builder builder = new Notification.Builder(this);
        builder.setContentTitle(getString(R.string.quick_settings_qr_recording));
        builder.setContentText(getString(R.string.quick_settings_qr_recording_notif));
        builder.setSmallIcon(R.drawable.ic_qs_qr_recording);
        Bitmap b = BitmapFactory.decodeResource(getResources(), R.drawable.ic_qs_qr_recording);
        builder.setLargeIcon(b);
        Intent intent = new Intent(ACTION_RECORDING_STOP);
        mPendingIntent = PendingIntent.getService(this, 0, intent, 0);
        builder.setContentIntent(mPendingIntent);
        mRecordingNotif = builder.build();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (intent != null && intent.getAction() != null) {
            if (intent.getAction().equals(ACTION_RECORDING_START)) {
                if (intent.hasExtra(EXTRA_SAMPLING_RATE)) {
                    mSamplingRate = intent.getIntExtra(EXTRA_SAMPLING_RATE, DEFAULT_SAMPLING_RATE);
                }
                startRecording();
                return START_STICKY;
            } else if (intent.getAction().equals(ACTION_RECORDING_STOP)) {
                stopRecording();
                return START_STICKY;
            } else if (intent.getAction().equals(ACTION_RECORDING_GET_STATUS)) {
                ResultReceiver receiver = intent.getParcelableExtra("receiver");
                Bundle data = new Bundle();
                data.putInt(EXTRA_RECORDING_STATUS, mRecordingStatus);
                receiver.send(0, data);
                return START_STICKY;
            }
        }

        stopSelf();
        return START_NOT_STICKY;
    }

    MediaRecorder.OnErrorListener mOnErrorListener = new MediaRecorder.OnErrorListener() {

        @Override
        public void onError(MediaRecorder mr, int what, int extra) {
            mRecordingStatus = RECORDING_STATUS_ERROR;

            String statusMessage = "Error in MediaRecorder while recording: " + what + "; " + extra;
            Intent i = new Intent(ACTION_RECORDING_STATUS_CHANGED);
            i.putExtra(EXTRA_RECORDING_STATUS, mRecordingStatus);
            i.putExtra(EXTRA_STATUS_MESSAGE, statusMessage);
            sendBroadcast(i);
            stopForeground(true);
        }
    };

    private String prepareOutputFile() {
        File outputDir = new File(Environment.getExternalStorageDirectory() + "/AudioRecordings");
        if (!outputDir.exists()) {
            if (!outputDir.mkdir()) {
                Log.e(TAG, "Cannot create AudioRecordings directory");
                return null;
            }
        }
        String fileName = "AUDIO_" + new SimpleDateFormat(
                "yyyyMMdd_HHmmss", Locale.US).format(new Date()) + ".mp4";
        return (outputDir.getAbsolutePath() + "/" + fileName);
    }

    private void startRecording() {
        String statusMessage = "";
        String audioFileName = prepareOutputFile();
        try {
            mRecorder = new MediaRecorder();
            mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
            mRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
            mRecorder.setOutputFile(audioFileName);
            mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
            mRecorder.setAudioEncodingBitRate(96000);
            mRecorder.setAudioSamplingRate(mSamplingRate);
            mRecorder.setOnErrorListener(mOnErrorListener);
            mRecorder.prepare();
            mRecorder.start();
            mRecordingStatus = RECORDING_STATUS_STARTED;
            startForeground(1, mRecordingNotif);
        } catch (Exception e) {
            e.printStackTrace();
            mRecordingStatus = RECORDING_STATUS_ERROR;
            statusMessage = e.getMessage();
        } finally {
            Intent i = new Intent(ACTION_RECORDING_STATUS_CHANGED);
            i.putExtra(EXTRA_RECORDING_STATUS, mRecordingStatus);
            if (mRecordingStatus == RECORDING_STATUS_STARTED) {
                i.putExtra(EXTRA_AUDIO_FILENAME, audioFileName);
            }
            i.putExtra(EXTRA_STATUS_MESSAGE, statusMessage);
            sendBroadcast(i);
        }
    }

    private void stopRecording() {
        if (mRecorder == null) return;

        String statusMessage = "";
        try {
            mRecorder.stop();
            mRecorder.release();
            mRecorder = null;
            mRecordingStatus = RECORDING_STATUS_STOPPED;
        } catch (Exception e) {
            e.printStackTrace();
            mRecordingStatus = RECORDING_STATUS_ERROR;
            statusMessage = e.getMessage();
        } finally {
            Intent i = new Intent(ACTION_RECORDING_STATUS_CHANGED);
            i.putExtra(EXTRA_RECORDING_STATUS, mRecordingStatus);
            i.putExtra(EXTRA_STATUS_MESSAGE, statusMessage);
            sendBroadcast(i);
            stopForeground(true);
        }
    }

    @Override
    public void onDestroy() {
        stopRecording();
        super.onDestroy();
    }
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<title>Boost.Locale: whello.cpp</title>

<link href="tabs.css" rel="stylesheet" type="text/css"/>
<link href="doxygen.css" rel="stylesheet" type="text/css" />
<link href="navtree.css" rel="stylesheet" type="text/css"/>

Boost.Locale

Main Page

Modules

Namespaces

Classes

Files

Examples

whello.cpp

Basic example of using various functions with wide strings provided by this library

//
//  Copyright (c) 2009-2011 Artyom Beilis (Tonkikh)
//
//  Distributed under the Boost Software License, Version 1.0. (See
//  accompanying file LICENSE_1_0.txt or copy at
//  http://www.boost.org/LICENSE_1_0.txt)
//
#include <boost/locale.hpp>
#include <iostream>

#include <ctime>

int main()
{
    using namespace boost::locale;
    using namespace std;

    // Create system default locale
    generator gen;
    locale loc=gen("");
    locale::global(loc);
    wcout.imbue(loc);

    // This is needed to prevent C library to
    // convert strings to narrow
    // instead of C++ on some platforms
    std::ios_base::sync_with_stdio(false);

    wcout <<wformat(L"Today {1,date} at {1,time} we had run our first localization example") % time(0)
          <<endl;

    wcout<<L"This is how we show numbers in this locale "<<as::number << 103.34 <<endl;
    wcout<<L"This is how we show currency in this locale "<<as::currency << 103.34 <<endl;
    wcout<<L"This is typical date in the locale "<<as::date << std::time(0) <<endl;
    wcout<<L"This is typical time in the locale "<<as::time << std::time(0) <<endl;
    wcout<<L"This is upper case "<<to_upper(L"Hello World!")<<endl;
    wcout<<L"This is lower case "<<to_lower(L"Hello World!")<<endl;
    wcout<<L"This is title case "<<to_title(L"Hello World!")<<endl;
    wcout<<L"This is fold case "<<fold_case(L"Hello World!")<<endl;

}

// vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4

© Copyright 2009-2012 Artyom Beilis,  Distributed under the Boost Software License, Version 1.0.


text:
from flask import Flask, render_template, request
from flask_socketio import SocketIO, send, emit
from datetime import datetime

app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
socketio = SocketIO(app)

@socketio.on('secret_room')
def handle_s2c(json):
    print 'received message: %s'%json
    socketio.emit('secret_room', json)

@app.route("/click")
def sliderbar():
	return render_template('click.html')

@app.route("/show")
def display():
	return render_template('show.html')

if __name__ == "__main__":
    #app.run(host='0.0.0.0',port=4999,debug=True)
    socketio.run(app)


text:
//==============================================================================
// QScintillaSupport global
//==============================================================================

#pragma once

//==============================================================================

#ifdef _WIN32
    #ifdef QScintillaSupport_PLUGIN
        #define QSCINTILLASUPPORT_EXPORT __declspec(dllexport)
    #else
        #define QSCINTILLASUPPORT_EXPORT __declspec(dllimport)
    #endif
#else
    #define QSCINTILLASUPPORT_EXPORT
#endif

//==============================================================================
// End of file
//==============================================================================


text:
import get from 'ember-metal/get'
import {A} from 'ember-array/utils'

// ----- Ember addons -----
import computed from 'ember-macro-helpers/computed'
import createClassComputed from 'ember-macro-helpers/create-class-computed'
import normalizeArrayKey from 'ember-macro-helpers/normalize-array-key'

export const mapExisting = createClassComputed(
  // the first param is the observer list
  // it refers to incoming keys
  // the bool is whether a value change should recreate the macro
  [
    false, true, false,
  ],
  // the second param is the callback function where you create your computed property
  // it is passed in the values of the properties you marked true above
  (arrayPropName, callback) => {
    let previousItems = new Map()

    // when `key` changes, we need to watch a new property on the array
    // since our computed property is now invalid, we need to create a new one
    return computed(
      `${arrayPropName}.[]`, callback,
      function (array, callback) {
        previousItems.forEach((value, item) => {
          if (array.includes(item)) return
          previousItems.delete(item)
        })

        if (!array) return A()

        const result = array.map((item, index) => {
          if (previousItems.has(item)) return previousItems.get(item)

          const value = callback.call(this, item, index, array)

          previousItems.set(item, value)

          return value
        })

        return A(result)
      }
    )
  }
)

export const mapExistingByKey = createClassComputed(
  // the first param is the observer list
  // it refers to incoming keys
  // the bool is whether a value change should recreate the macro
  [
    false, true, false,
  ],
  // the second param is the callback function where you create your computed property
  // it is passed in the values of the properties you marked true above
  (arrayPropName, itemPropName, callback) => {
    let previousItems = new Map()

    // when `key` changes, we need to watch a new property on the array
    // since our computed property is now invalid, we need to create a new one
    return computed(
      normalizeArrayKey(arrayPropName, [itemPropName]), callback,
      function (array, callback) {
        if (!array) {
          previousItems = new Map()
          return A()
        }

        const items = array.map(item => get(item, itemPropName))

        previousItems.forEach((value, item) => {
          if (items.includes(item)) return
          previousItems.delete(item)
        })

        const result = array.map((item, index) => {
          const key = get(item, itemPropName)

          if (previousItems.has(key)) return previousItems.get(key)

          const value = callback.call(this.context, item, index, array)

          previousItems.set(key, value)

          return value
        })

        return A(result)
      }
    )
  }
)


text:
var q = require('q');
var Client = require('../models/client');

module.exports = function (prefix, app) {

    require('./entity')(prefix, app, Client);
}