text:
/*
 * Oracle GPL Disclaimer: For the avoidance of doubt, except that if any license choice
 * other than GPL or LGPL is available it will apply instead, Oracle elects to use only
 * the General Public License version 2 (GPLv2) at this time for any software where
 * a choice of GPL license versions is made available with the language indicating
 * that GPLv2 or any later version may be used, or where a choice of which version
 * of the GPL is applied is otherwise unspecified.
 */

#include <X11/Xlib.h>
#include <X11/Xatom.h>
#include <X11/Xutil.h>
#include "rdesktop.h"

#define _NET_WM_STATE_REMOVE        0	/* remove/unset property */
#define _NET_WM_STATE_ADD           1	/* add/set property */
#define _NET_WM_STATE_TOGGLE        2	/* toggle property  */

extern Display *g_display;

static Atom g_net_wm_state_maximized_vert_atom, g_net_wm_state_maximized_horz_atom,
	g_net_wm_state_hidden_atom, g_net_wm_name_atom, g_utf8_string_atom,
	g_net_wm_state_skip_taskbar_atom, g_net_wm_state_skip_pager_atom,
	g_net_wm_state_modal_atom, g_net_wm_icon_atom, g_net_wm_state_above_atom;

Atom g_net_wm_state_atom, g_net_wm_desktop_atom;

/*
   Get window property value (32 bit format)
   Returns zero on success, -1 on error
*/
static int
get_property_value(Window wnd, char *propname, long max_length,
		   unsigned long *nitems_return, unsigned char **prop_return, int nowarn)
{
	int result;
	Atom property;
	Atom actual_type_return;
	int actual_format_return;
	unsigned long bytes_after_return;

	property = XInternAtom(g_display, propname, True);
	if (property == None)
	{
		fprintf(stderr, "Atom %s does not exist\n", propname);
		return (-1);
	}

	result = XGetWindowProperty(g_display, wnd, property, 0,	/* long_offset */
				    max_length,	/* long_length */
				    False,	/* delete */
				    AnyPropertyType,	/* req_type */
				    &actual_type_return,
				    &actual_format_return,
				    nitems_return, &bytes_after_return, prop_return);

	if (result != Success)
	{
		fprintf(stderr, "XGetWindowProperty failed\n");
		return (-1);
	}

	if (actual_type_return == None || actual_format_return == 0)
	{
		if (!nowarn)
			fprintf(stderr, "Window is missing property %s\n", propname);
		return (-1);
	}

	if (bytes_after_return)
	{
		fprintf(stderr, "%s is too big for me\n", propname);
		return (-1);
	}

	if (actual_format_return != 32)
	{
		fprintf(stderr, "%s has bad format\n", propname);
		return (-1);
	}

	return (0);
}

/*
   Get current desktop number
   Returns -1 on error
*/
static int
get_current_desktop(void)
{
	unsigned long nitems_return;
	unsigned char *prop_return;
	int current_desktop;

	if (get_property_value
	    (DefaultRootWindow(g_display), "_NET_CURRENT_DESKTOP", 1, &nitems_return,
	     &prop_return, 0) < 0)
		return (-1);

	if (nitems_return != 1)
	{
		fprintf(stderr, "_NET_CURRENT_DESKTOP has bad length\n");
		return (-1);
	}

	current_desktop = *prop_return;
	XFree(prop_return);
	return current_desktop;
}

/*
  Get workarea geometry
  Returns zero on success, -1 on error
 */

int
get_current_workarea(uint32 * x, uint32 * y, uint32 * width, uint32 * height)
{
	int current_desktop;
	unsigned long nitems_return;
	unsigned char *prop_return;
	long *return_words;
	const uint32 net_workarea_x_offset = 0;
	const uint32 net_workarea_y_offset = 1;
	const uint32 net_workarea_width_offset = 2;
	const uint32 net_workarea_height_offset = 3;
	const uint32 max_prop_length = 32 * 4;	/* Max 32 desktops */

	if (get_property_value
	    (DefaultRootWindow(g_display), "_NET_WORKAREA", max_prop_length, &nitems_return,
	     &prop_return, 0) < 0)
		return (-1);

	if (nitems_return % 4)
	{
		fprintf(stderr, "_NET_WORKAREA has odd length\n");
		return (-1);
	}

	current_desktop = get_current_desktop();

	if (current_desktop < 0)
		return -1;

	return_words = (long *) prop_return;

	*x = return_words[current_desktop * 4 + net_workarea_x_offset];
	*y = return_words[current_desktop * 4 + net_workarea_y_offset];
	*width = return_words[current_desktop * 4 + net_workarea_width_offset];
	*height = return_words[current_desktop * 4 + net_workarea_height_offset];

	XFree(prop_return);

	return (0);

}

void
ewmh_init()
{
	/* FIXME: Use XInternAtoms */
	g_net_wm_state_maximized_vert_atom =
		XInternAtom(g_display, "_NET_WM_STATE_MAXIMIZED_VERT", False);
	g_net_wm_state_maximized_horz_atom =
		XInternAtom(g_display, "_NET_WM_STATE_MAXIMIZED_HORZ", False);
	g_net_wm_state_hidden_atom = XInternAtom(g_display, "_NET_WM_STATE_HIDDEN", False);
	g_net_wm_state_skip_taskbar_atom =
		XInternAtom(g_display, "_NET_WM_STATE_SKIP_TASKBAR", False);
	g_net_wm_state_skip_pager_atom = XInternAtom(g_display, "_NET_WM_STATE_SKIP_PAGER", False);
	g_net_wm_state_modal_atom = XInternAtom(g_display, "_NET_WM_STATE_MODAL", False);
	g_net_wm_state_above_atom = XInternAtom(g_display, "_NET_WM_STATE_ABOVE", False);
	g_net_wm_state_atom = XInternAtom(g_display, "_NET_WM_STATE", False);
	g_net_wm_desktop_atom = XInternAtom(g_display, "_NET_WM_DESKTOP", False);
	g_net_wm_name_atom = XInternAtom(g_display, "_NET_WM_NAME", False);
	g_net_wm_icon_atom = XInternAtom(g_display, "_NET_WM_ICON", False);
	g_utf8_string_atom = XInternAtom(g_display, "UTF8_STRING", False);
}

/*
   Get the window state: normal/minimized/maximized.
*/
#ifndef MAKE_PROTO
int
ewmh_get_window_state(Window w)
{
	unsigned long nitems_return;
	unsigned char *prop_return;
	unsigned long *return_words;
	unsigned long item;
	RD_BOOL maximized_vert, maximized_horz, hidden;

	maximized_vert = maximized_horz = hidden = False;

	if (get_property_value(w, "_NET_WM_STATE", 64, &nitems_return, &prop_return, 0) < 0)
		return SEAMLESSRDP_NORMAL;

	return_words = (unsigned long *) prop_return;

	for (item = 0; item < nitems_return; item++)
	{
		if (return_words[item] == g_net_wm_state_maximized_vert_atom)
			maximized_vert = True;
		if (return_words[item] == g_net_wm_state_maximized_horz_atom)
			maximized_horz = True;
		if (return_words[item] == g_net_wm_state_hidden_atom)
			hidden = True;
	}

	XFree(prop_return);

	/* In EWMH, HIDDEN overrides MAXIMIZED_VERT/MAXIMIZED_HORZ */
	if (hidden)
		return SEAMLESSRDP_MINIMIZED;
	else if (maximized_vert && maximized_horz)
		return SEAMLESSRDP_MAXIMIZED;
	else
		return SEAMLESSRDP_NORMAL;
}

static int
ewmh_modify_state(Window wnd, int add, Atom atom1, Atom atom2)
{
	Status status;
	XEvent xevent;

	int result;
	unsigned long nitems;
	unsigned char *props;
	uint32 state = WithdrawnState;

	/* The spec states that the window manager must respect any
	   _NET_WM_STATE attributes on a withdrawn window. In order words, we
	   modify the attributes directly for withdrawn windows and ask the WM
	   to do it for active windows. */
	result = get_property_value(wnd, "WM_STATE", 64, &nitems, &props, 1);
	if ((result >= 0) && nitems)
	{
		state = *(uint32 *) props;
		XFree(props);
	}

	if (state == WithdrawnState)
	{
		if (add)
		{
			Atom atoms[2];

			atoms[0] = atom1;
			nitems = 1;
			if (atom2)
			{
				atoms[1] = atom2;
				nitems = 2;
			}

			XChangeProperty(g_display, wnd, g_net_wm_state_atom, XA_ATOM,
					32, PropModeAppend, (unsigned char *) atoms, nitems);
		}
		else
		{
			Atom *atoms;
			int i;

			if (get_property_value(wnd, "_NET_WM_STATE", 64, &nitems, &props, 1) < 0)
				return 0;

			atoms = (Atom *) props;

			for (i = 0; i < nitems; i++)
			{
				if ((atoms[i] == atom1) || (atom2 && (atoms[i] == atom2)))
				{
					if (i != (nitems - 1))
						memmove(&atoms[i], &atoms[i + 1],
							sizeof(Atom) * (nitems - i - 1));
					nitems--;
					i--;
				}
			}

			XChangeProperty(g_display, wnd, g_net_wm_state_atom, XA_ATOM,
					32, PropModeReplace, (unsigned char *) atoms, nitems);

			XFree(props);
		}

		return 0;
	}

	xevent.type = ClientMessage;
	xevent.xclient.window = wnd;
	xevent.xclient.message_type = g_net_wm_state_atom;
	xevent.xclient.format = 32;
	if (add)
		xevent.xclient.data.l[0] = _NET_WM_STATE_ADD;
	else
		xevent.xclient.data.l[0] = _NET_WM_STATE_REMOVE;
	xevent.xclient.data.l[1] = atom1;
	xevent.xclient.data.l[2] = atom2;
	xevent.xclient.data.l[3] = 0;
	xevent.xclient.data.l[4] = 0;
	status = XSendEvent(g_display, DefaultRootWindow(g_display), False,
			    SubstructureNotifyMask | SubstructureRedirectMask, &xevent);
	if (!status)
		return -1;

	return 0;
}

/*
   Set the window state: normal/minimized/maximized.
   Returns -1 on failure.
*/
int
ewmh_change_state(Window wnd, int state)
{
	/*
	 * Deal with the max atoms
	 */
	if (state == SEAMLESSRDP_MAXIMIZED)
	{
		if (ewmh_modify_state
		    (wnd, 1, g_net_wm_state_maximized_vert_atom,
		     g_net_wm_state_maximized_horz_atom) < 0)
			return -1;
	}
	else
	{
		if (ewmh_modify_state
		    (wnd, 0, g_net_wm_state_maximized_vert_atom,
		     g_net_wm_state_maximized_horz_atom) < 0)
			return -1;
	}

	return 0;
}

int
ewmh_get_window_desktop(Window wnd)
{
	unsigned long nitems_return;
	unsigned char *prop_return;
	int desktop;

	if (get_property_value(wnd, "_NET_WM_DESKTOP", 1, &nitems_return, &prop_return, 0) < 0)
		return (-1);

	if (nitems_return != 1)
	{
		fprintf(stderr, "_NET_WM_DESKTOP has bad length\n");
		return (-1);
	}

	desktop = *prop_return;
	XFree(prop_return);
	return desktop;
}

int
ewmh_move_to_desktop(Window wnd, unsigned int desktop)
{
	Status status;
	XEvent xevent;

	xevent.type = ClientMessage;
	xevent.xclient.window = wnd;
	xevent.xclient.message_type = g_net_wm_desktop_atom;
	xevent.xclient.format = 32;
	xevent.xclient.data.l[0] = desktop;
	xevent.xclient.data.l[1] = 0;
	xevent.xclient.data.l[2] = 0;
	xevent.xclient.data.l[3] = 0;
	xevent.xclient.data.l[4] = 0;
	status = XSendEvent(g_display, DefaultRootWindow(g_display), False,
			    SubstructureNotifyMask | SubstructureRedirectMask, &xevent);
	if (!status)
		return -1;

	return 0;
}

void
ewmh_set_wm_name(Window wnd, const char *title)
{
	int len;

	len = strlen(title);
	XChangeProperty(g_display, wnd, g_net_wm_name_atom, g_utf8_string_atom,
			8, PropModeReplace, (unsigned char *) title, len);
}

int
ewmh_set_window_popup(Window wnd)
{
	if (ewmh_modify_state
	    (wnd, 1, g_net_wm_state_skip_taskbar_atom, g_net_wm_state_skip_pager_atom) < 0)
		return -1;
	return 0;
}

int
ewmh_set_window_modal(Window wnd)
{
	if (ewmh_modify_state(wnd, 1, g_net_wm_state_modal_atom, 0) < 0)
		return -1;
	return 0;
}

void
ewmh_set_icon(Window wnd, int width, int height, const char *rgba_data)
{
	unsigned long nitems, i;
	unsigned char *props;
	unsigned long *cur_set, *new_set;
	unsigned long *icon;

	cur_set = NULL;
	new_set = NULL;

	if (get_property_value(wnd, "_NET_WM_ICON", 10000, &nitems, &props, 1) >= 0)
	{
		cur_set = (unsigned long *) props;

		for (i = 0; i < nitems;)
		{
			if (cur_set[i] == width && cur_set[i + 1] == height)
				break;

			i += 2 + cur_set[i] * cur_set[i + 1];
		}

		if (i != nitems)
			icon = cur_set + i;
		else
		{
			new_set = xmalloc((nitems + width * height + 2) * sizeof(unsigned long));
			memcpy(new_set, cur_set, nitems * sizeof(unsigned long));
			icon = new_set + nitems;
			nitems += width * height + 2;
		}
	}
	else
	{
		new_set = xmalloc((width * height + 2) * sizeof(unsigned long));
		icon = new_set;
		nitems = width * height + 2;
	}

	icon[0] = width;
	icon[1] = height;

	/* Convert RGBA -> ARGB */
	for (i = 0; i < width * height; i++)
	{
		icon[i + 2] =
			rgba_data[i * 4 + 3] << 24 |
			((rgba_data[i * 4 + 0] << 16) & 0x00FF0000) |
			((rgba_data[i * 4 + 1] << 8) & 0x0000FF00) |
			((rgba_data[i * 4 + 2] << 0) & 0x000000FF);
	}

	XChangeProperty(g_display, wnd, g_net_wm_icon_atom, XA_CARDINAL, 32,
			PropModeReplace, (unsigned char *) (new_set ? new_set : cur_set), nitems);

	if (cur_set)
		XFree(cur_set);
	if (new_set)
		xfree(new_set);
}

void
ewmh_del_icon(Window wnd, int width, int height)
{
	unsigned long nitems, i, icon_size;
	unsigned char *props;
	unsigned long *cur_set, *new_set;

	cur_set = NULL;
	new_set = NULL;

	if (get_property_value(wnd, "_NET_WM_ICON", 10000, &nitems, &props, 1) < 0)
		return;

	cur_set = (unsigned long *) props;

	for (i = 0; i < nitems;)
	{
		if (cur_set[i] == width && cur_set[i + 1] == height)
			break;

		i += 2 + cur_set[i] * cur_set[i + 1];
	}

	if (i == nitems)
		goto out;

	icon_size = width * height + 2;
	new_set = xmalloc((nitems - icon_size) * sizeof(unsigned long));

	if (i != 0)
		memcpy(new_set, cur_set, i * sizeof(unsigned long));
	if (i != nitems - icon_size)
		memcpy(new_set + i, cur_set + i + icon_size,
		       (nitems - (i + icon_size)) * sizeof(unsigned long));

	nitems -= icon_size;

	XChangeProperty(g_display, wnd, g_net_wm_icon_atom, XA_CARDINAL, 32,
			PropModeReplace, (unsigned char *) new_set, nitems);

	xfree(new_set);

      out:
	XFree(cur_set);
}

int
ewmh_set_window_above(Window wnd)
{
	if (ewmh_modify_state(wnd, 1, g_net_wm_state_above_atom, 0) < 0)
		return -1;
	return 0;
}

RD_BOOL
ewmh_is_window_above(Window w)
{
	unsigned long nitems_return;
	unsigned char *prop_return;
	unsigned long *return_words;
	unsigned long item;
	RD_BOOL above;

	above = False;

	if (get_property_value(w, "_NET_WM_STATE", 64, &nitems_return, &prop_return, 0) < 0)
		return False;

	return_words = (unsigned long *) prop_return;

	for (item = 0; item < nitems_return; item++)
	{
		if (return_words[item] == g_net_wm_state_above_atom)
			above = True;
	}

	XFree(prop_return);

	return above;
}

#endif /* MAKE_PROTO */

#if 0

/* FIXME: _NET_MOVERESIZE_WINDOW is for pagers, not for
   applications. We should implement _NET_WM_MOVERESIZE instead */

int
ewmh_net_moveresize_window(Window wnd, int x, int y, int width, int height)
{
	Status status;
	XEvent xevent;
	Atom moveresize;

	moveresize = XInternAtom(g_display, "_NET_MOVERESIZE_WINDOW", False);
	if (!moveresize)
	{
		return -1;
	}

	xevent.type = ClientMessage;
	xevent.xclient.window = wnd;
	xevent.xclient.message_type = moveresize;
	xevent.xclient.format = 32;
	xevent.xclient.data.l[0] = StaticGravity | (1 << 8) | (1 << 9) | (1 << 10) | (1 << 11);
	xevent.xclient.data.l[1] = x;
	xevent.xclient.data.l[2] = y;
	xevent.xclient.data.l[3] = width;
	xevent.xclient.data.l[4] = height;

	status = XSendEvent(g_display, DefaultRootWindow(g_display), False,
			    SubstructureNotifyMask | SubstructureRedirectMask, &xevent);
	if (!status)
		return -1;
	return 0;
}

#endif


text:
<?php return array(

  // Markup
  ////////////////////////////////////////////////////////////////////

  // Whether labels should be automatically computed from name
  'automatic_label'   => true,

  // The default form type
  'default_form_type' => 'horizontal',

  // The framework to be used by Former
  'framework'         => 'ZurbFoundation4',

  // Validation
  ////////////////////////////////////////////////////////////////////

  // Whether Former should fetch errors from Session
  'fetch_errors'      => true,

  // Whether Former should try to apply Validator rules as attributes
  'live_validation'   => true,

  // Whether Former should automatically fetch error messages and
  // display them next to the matching fields
  'error_messages'    => true,

  // Checkables
  ////////////////////////////////////////////////////////////////////

  // Whether checkboxes should always be present in the POST data,
  // no matter if you checked them or not
  'push_checkboxes'   => false,

  // The value a checkbox will have in the POST array if unchecked
  'unchecked_value'   => 0,

  // Required fields
  ////////////////////////////////////////////////////////////////////

  // The class to be added to required fields
  'required_class'    => 'required',

  // A facultative text to append to the labels of required fields
  'required_text'     => '<sup>*</sup>',

  // Translations
  ////////////////////////////////////////////////////////////////////

  // Where Former should look for translations
  'translate_from'    => 'validation.attributes',

  // Whether text that comes out of the translated
  // should be capitalized (ex: email => Email) automatically
  'capitalize_translations' => true,

  // An array of attributes to automatically translate
  'translatable'      => array(
    'help', 'inlineHelp', 'blockHelp',
    'placeholder', 'data_placeholder',
    'label'
  ),
);

redpajama_set_name: RedPajamaGithub


text:
package com.palmelf.eoffice.dao.admin.impl;

import com.palmelf.core.dao.impl.BaseDaoImpl;
import com.palmelf.eoffice.dao.admin.FixedAssetsDao;
import com.palmelf.eoffice.model.admin.FixedAssets;

public class FixedAssetsDaoImpl extends BaseDaoImpl<FixedAssets> implements
		FixedAssetsDao {
	public FixedAssetsDaoImpl() {
		super(FixedAssets.class);
	}
}


text:
'use strict';

// test ad api:

const
    appsetup = require('./_appsetup'), // <-- MUST be import first!
    appclose = require('./_appclose'),
    sleep = require('sleep-promise'),
    _ = require('lodash'),
    fs = require('fs'),
    moment = require('moment'),
    request = require('supertest'),
    expect = require('chai').expect,
    cache = require('../cache'),
    logger = require('../logger'),
    helper = require('../helper'),
    adApi = require('../controllers/adApi'),
    db = require('../db'),
    AdSlot = db.AdSlot,
    AdPeriod = db.AdPeriod,
    AdMaterial = db.AdMaterial,
    nextId = db.nextId,
    constants = require('../constants');

describe('#ad api', () => {

    before(appsetup);

    after(appclose);

    beforeEach(async () => {
        logger.info('delete all ads...');
        await AdMaterial.destroy($ALL);
        await AdPeriod.destroy($ALL);
        await AdSlot.destroy($ALL);
        // IMPORTANT: clear cache:
        await cache.remove(constants.cache.ADS);
        // create 2 AdSlots and set global variables:
        let response;
        response = await request($SERVER)
            .post('/api/adslots')
            .set('Authorization', auth($ADMIN))
            .send({
                name: 'A',
                alias: 'a',
                description: 'slot-A',
                price: 100,
                width: 336,
                height: 280,
                num_slots: 2,
                num_auto_fill: 1,
                auto_fill: '
slot-A
'
            })
            .expect('Content-Type', /application\/json/)
            .expect(200);
        global.$ADSLOT_1 = response.body;
        response = await request($SERVER)
            .post('/api/adslots')
            .set('Authorization', auth($ADMIN))
            .send({
                name: 'B',
                alias: 'b',
                description: 'slot-B',
                price: 200,
                width: 300,
                height: 600,
                num_slots: 2,
                num_auto_fill: 1,
                auto_fill: '
slot-B
'
            })
            .expect('Content-Type', /application\/json/)
            .expect(200);
        global.$ADSLOT_2 = response.body;
    });

    afterEach(async () => {
        // IMPORTANT: clear cache:
        await cache.remove(constants.cache.ADS);
    });

    it('get adslots by editor failed.', async () => {
        let response = await request($SERVER)
            .get('/api/adslots')
            .set('Authorization', auth($EDITOR))
            .expect('Content-Type', /application\/json/)
            .expect(400);
        expect(response.body.error).to.equal('permission:denied');
    });

    it('should get 2 adslots', async () => {
        let response = await request($SERVER)
            .get('/api/adslots')
            .set('Authorization', auth($ADMIN))
            .expect('Content-Type', /application\/json/)
            .expect(200);
        expect(response.body).to.a('object');
        expect(response.body.adslots).to.a('array').and.to.have.lengthOf(2);
        expect(response.body.adslots[0]).to.a('object');
        expect(response.body.adslots[0].name).to.equal('A');
        expect(response.body.adslots[0].alias).to.equal('a');
        expect(response.body.adslots[1]).to.a('object');
        expect(response.body.adslots[1].name).to.equal('B');
        expect(response.body.adslots[1].alias).to.equal('b');
        // get ad slot A:
        let id = response.body.adslots[0].id;
        response = await request($SERVER)
            .get('/api/adslots/' + id)
            .set('Authorization', auth($ADMIN))
            .expect('Content-Type', /application\/json/)
            .expect(200);
        expect(response.body).to.a('object');
        expect(response.body.name).to.equal('A');
        expect(response.body.alias).to.equal('a');
    });

    it('create and should get 3 adslots', async () => {
        let response = await request($SERVER)
            .post('/api/adslots')
            .set('Authorization', auth($ADMIN))
            .send({
                name: 'C',
                alias: 'c',
                description: 'slot-C',
                price: 300,
                width: 640,
                height: 480,
                num_slots: 2,
                num_auto_fill: 1,
                auto_fill: '
slot-C
'
            })
            .expect('Content-Type', /application\/json/)
            .expect(200);
        expect(response.body).to.a('object');
        expect(response.body.name).to.equal('C');
        response = await request($SERVER)
            .get('/api/adslots')
            .set('Authorization', auth($ADMIN))
            .expect('Content-Type', /application\/json/)
            .expect(200);
        expect(response.body).to.a('object');
        expect(response.body.adslots).to.a('array').and.to.have.lengthOf(3);
        expect(response.body.adslots[0]).to.a('object');
        expect(response.body.adslots[0].name).to.equal('A');
        expect(response.body.adslots[1]).to.a('object');
        expect(response.body.adslots[1].name).to.equal('B');
        expect(response.body.adslots[2]).to.a('object');
        expect(response.body.adslots[2].name).to.equal('C');
        expect(response.body.adslots[2].alias).to.equal('c');
    });

    it('create adslots failed by editor failed', async () => {
        let response = await request($SERVER)
            .post('/api/adslots')
            .set('Authorization', auth($EDITOR))
            .send({
                name: 'C',
                alias: 'c',
                description: 'slot-C',
                price: 300,
                width: 640,
                height: 480,
                num_slots: 2,
                num_auto_fill: 1,
                auto_fill: '
slot-C
'
            })
            .expect('Content-Type', /application\/json/)
            .expect(400);
        expect(response.body.error).to.equal('permission:denied');
    });

    it('update adslot failed by editor', async () => {
        let id = $ADSLOT_1.id;
        let response = await request($SERVER)
            .post('/api/adslots/' + id)
            .set('Authorization', auth($EDITOR))
            .send({
                name: 'changed',
                description: 'slot-changed',
                price: 999,
                num_slots: 9,
                num_auto_fill: 3,
                auto_fill: '
slot-changed
'
            })
            .expect('Content-Type', /application\/json/)
            .expect(400);
        expect(response.body.error).to.equal('permission:denied');
    });

    it('update adslot ok by admin', async () => {
        let id = $ADSLOT_1.id;
        let response = await request($SERVER)
            .post('/api/adslots/' + id)
            .set('Authorization', auth($ADMIN))
            .send({
                name: 'A-changed',
                description: 'slot-changed',
                price: 999,
                width: 666,
                height: 555,
                num_slots: 9,
                num_auto_fill: 3,
                auto_fill: '
slot-changed
'
            })
            .expect('Content-Type', /application\/json/)
            .expect(200);
        expect(response.body.name).to.be.a('string').and.to.equal('A-changed');
        // query to check:
        response = await request($SERVER)
            .get('/api/adslots')
            .set('Authorization', auth($ADMIN))
            .expect('Content-Type', /application\/json/)
            .expect(200);
        let adslot = response.body.adslots[0];
        expect(adslot.name).to.equal('A-changed');
        expect(adslot.description).to.equal('slot-changed');
        expect(adslot.price).to.equal(999);
        expect(adslot.num_slots).to.equal(9);
        expect(adslot.num_auto_fill).to.equal(3);
        expect(adslot.auto_fill).to.equal('
slot-changed
');
        // width and height CANNOT be updated:
        expect(adslot.width).to.equal(336);
        expect(adslot.height).to.equal(280);
    });

    it('delete adslot failed by editor', async () => {
        let id = $ADSLOT_1.id;
        let response = await request($SERVER)
            .post('/api/adslots/' + id + '/delete')
            .set('Authorization', auth($EDITOR))
            .send({})
            .expect('Content-Type', /application\/json/)
            .expect(400);
        expect(response.body.error).to.equal('permission:denied');
    });

    it('delete adslot ok by admin', async () => {
        let id = $ADSLOT_1.id;
        let response = await request($SERVER)
            .post('/api/adslots/' + id + '/delete')
            .set('Authorization', auth($ADMIN))
            .send({})
            .expect('Content-Type', /application\/json/)
            .expect(200);
        expect(response.body.id).to.equal(id);
        // query to check:
        response = await request($SERVER)
            .get('/api/adslots')
            .set('Authorization', auth($ADMIN))
            .expect('Content-Type', /application\/json/)
            .expect(200);
        expect(response.body).to.a('object');
        expect(response.body.adslots).to.a('array').and.to.have.lengthOf(1);
    });

    it('delete adslot failed by admin for unexpired adperiod', async () => {
        // create active adperiod:
        let
            start = moment().startOf('month'),
            end = start.clone().add(2, 'months');
        let response = await request($SERVER)
            .post('/api/adperiods')
            .set('Authorization', auth($ADMIN))
            .send({
                user_id: $SPONSOR.id,
                adslot_id: $ADSLOT_1.id,
                start_at: start.format('YYYY-MM-DD'),
                months: 2
            })
            .expect('Content-Type', /application\/json/)
            .expect(200);
        let id = $ADSLOT_1.id;
        response = await request($SERVER)
            .post('/api/adslots/' + id + '/delete')
            .set('Authorization', auth($ADMIN))
            .send({})
            .expect('Content-Type', /application\/json/)
            .expect(400);
        expect(response.body.error).to.equal('entity:conflict');

    });

    it('should get empty active adperiods', async () => {
        let adperiods = await adApi.getActiveAdPeriods();
        expect(adperiods).to.a('array').and.to.have.lengthOf(0);
    });

    it('create adperiod by editor failed', async () => {
        let response = await request($SERVER)
            .post('/api/adperiods')
            .set('Authorization', auth($EDITOR))
            .send({
                user_id: $SPONSOR.id,
                adslot_id: $ADSLOT_1.id,
                start_at: '2017-07-08',
                months: 2
            })
            .expect('Content-Type', /application\/json/)
            .expect(400);
        expect(response.body.error).to.equal('permission:denied');
    });

    it('create adperiod by admin failed for invalid sponsor', async () => {
        let response = await request($SERVER)
            .post('/api/adperiods')
            .set('Authorization', auth($ADMIN))
            .send({
                user_id: $EDITOR.id,
                adslot_id: $ADSLOT_1.id,
                start_at: '2017-07-08',
                months: 2
            })
            .expect('Content-Type', /application\/json/)
            .expect(400);
        expect(response.body.error).to.equal('parameter:invalid');
        expect(response.body.data).to.equal('user_id');
    });

    it('create adperiod by admin failed for invalid start_at', async () => {
        let response = await request($SERVER)
            .post('/api/adperiods')
            .set('Authorization', auth($ADMIN))
            .send({
                user_id: $SPONSOR.id,
                adslot_id: $ADSLOT_1.id,
                start_at: '2017/07/08',
                months: 2
            })
            .expect('Content-Type', /application\/json/)
            .expect(400);
        expect(response.body.error).to.equal('parameter:invalid');
        expect(response.body.data).to.equal('start_at');
        // start_at > 28:
        response = await request($SERVER)
            .post('/api/adperiods')
            .set('Authorization', auth($ADMIN))
            .send({
                user_id: $SPONSOR.id,
                adslot_id: $ADSLOT_1.id,
                start_at: '2017-07-29',
                months: 2
            })
            .expect('Content-Type', /application\/json/)
            .expect(400);
        expect(response.body.error).to.equal('parameter:invalid');
        expect(response.body.data).to.equal('start_at');
    });

    it('create adperiod by admin failed for invalid months', async () => {
        let response = await request($SERVER)
            .post('/api/adperiods')
            .set('Authorization', auth($ADMIN))
            .send({
                user_id: $SPONSOR.id,
                adslot_id: $ADSLOT_1.id,
                start_at: '2017-07-08',
                months: 0
            })
            .expect('Content-Type', /application\/json/)
            .expect(400);
        expect(response.body.error).to.equal('parameter:invalid');
        expect(response.body.data).to.equal('months');
    });

    it('create non-active adperiod by admin ok', async () => {
        let response = await request($SERVER)
            .post('/api/adperiods')
            .set('Authorization', auth($ADMIN))
            .send({
                user_id: $SPONSOR.id,
                adslot_id: $ADSLOT_1.id,
                start_at: '2016-07-08',
                months: 2
            })
            .expect('Content-Type', /application\/json/)
            .expect(200);
        expect(response.body.adslot_id).to.equal($ADSLOT_1.id);
        expect(response.body.start_at).to.equal('2016-07-08');
        expect(response.body.end_at).to.equal('2016-09-08');
        // check:
        let ps = await adApi.getActiveAdPeriods();
        expect(ps).to.be.a('array').and.to.have.lengthOf(0);
    });

    it('create active adperiod by admin ok', async () => {
        let
            start = moment().startOf('month'),
            end = start.clone().add(2, 'months');
        let response = await request($SERVER)
            .post('/api/adperiods')
            .set('Authorization', auth($ADMIN))
            .send({
                user_id: $SPONSOR.id,
                adslot_id: $ADSLOT_1.id,
                start_at: start.format('YYYY-MM-DD'),
                months: 2
            })
            .expect('Content-Type', /application\/json/)
            .expect(200);
        expect(response.body.adslot_id).to.equal($ADSLOT_1.id);
        expect(response.body.start_at).to.equal(start.format('YYYY-MM-DD'));
        expect(response.body.end_at).to.equal(end.format('YYYY-MM-DD'));
        // check:
        let ps = await adApi.getActiveAdPeriods();
        expect(ps).to.be.a('array').and.to.have.lengthOf(1);
        expect(ps[0].id).to.equal(response.body.id);
    });

    it('extend adperiod by editor failed', async () => {
        let response = await request($SERVER)
            .post('/api/adperiods/' + nextId() + '/extend')
            .set('Authorization', auth($EDITOR))
            .send({
                months: 2
            })
            .expect('Content-Type', /application\/json/)
            .expect(400);
        expect(response.body.error).to.equal('permission:denied');
    });

    it('extend non-active adperiod by admin failed', async () => {
        let response = await request($SERVER)
            .post('/api/adperiods')
            .set('Authorization', auth($ADMIN))
            .send({
                user_id: $SPONSOR.id,
                adslot_id: $ADSLOT_1.id,
                start_at: '2016-07-08',
                months: 2
            })
            .expect('Content-Type', /application\/json/)
            .expect(200);
        let adpId = response.body.id;
        response = await request($SERVER)
            .post('/api/adperiods/' + adpId + '/extend')
            .set('Authorization', auth($ADMIN))
            .send({
                months: 2
            })
            .expect('Content-Type', /application\/json/)
            .expect(400);
        expect(response.body.error).to.equal('parameter:invalid');
        expect(response.body.data).to.equal('id');
    });

    it('extend active adperiod by admin failed', async () => {
        let
            start = moment().startOf('month'),
            end = start.clone().add(2, 'months');
        let response = await request($SERVER)
            .post('/api/adperiods')
            .set('Authorization', auth($ADMIN))
            .send({
                user_id: $SPONSOR.id,
                adslot_id: $ADSLOT_1.id,
                start_at: start.format('YYYY-MM-DD'),
                months: 2
            })
            .expect('Content-Type', /application\/json/)
            .expect(200);
        let adpId = response.body.id;
        response = await request($SERVER)
            .post('/api/adperiods/' + adpId + '/extend')
            .set('Authorization', auth($ADMIN))
            .send({
                months: 0
            })
            .expect('Content-Type', /application\/json/)
            .expect(400);
        expect(response.body.error).to.equal('parameter:invalid');
        expect(response.body.data).to.equal('months');
    });

    it('extend active adperiod by admin ok', async () => {
        let
            start = moment().startOf('month'),
            end = start.clone().add(2, 'months');
        let response = await request($SERVER)
            .post('/api/adperiods')
            .set('Authorization', auth($ADMIN))
            .send({
                user_id: $SPONSOR.id,
                adslot_id: $ADSLOT_1.id,
                start_at: start.format('YYYY-MM-DD'),
                months: 2
            })
            .expect('Content-Type', /application\/json/)
            .expect(200);
        let adpId = response.body.id;
        response = await request($SERVER)
            .post('/api/adperiods/' + adpId + '/extend')
            .set('Authorization', auth($ADMIN))
            .send({
                months: 3
            })
            .expect('Content-Type', /application\/json/)
            .expect(200);
        expect(response.body.id).to.equal(adpId);
        expect(response.body.start_at).to.equal(start.format('YYYY-MM-DD'));
        expect(response.body.end_at).to.equal(end.clone().add(3, 'months').format('YYYY-MM-DD'));
    });

    it('create admaterial by editor failed', async () => {
        let
            start = moment().startOf('month'),
            end = start.clone().add(2, 'months');
        let response = await request($SERVER)
            .post('/api/adperiods')
            .set('Authorization', auth($ADMIN))
            .send({
                user_id: $SPONSOR.id,
                adslot_id: $ADSLOT_1.id,
                start_at: start.format('YYYY-MM-DD'),
                months: 2
            })
            .expect('Content-Type', /application\/json/)
            .expect(200);
        let adpId = response.body.id;
        response = await request($SERVER)
            .post('/api/adperiods/' + adpId + '/admaterials')
            .set('Authorization', auth($EDITOR))
            .send({})
            .expect('Content-Type', /application\/json/)
            .expect(400);
        expect(response.body.error).to.equal('permission:denied');
    });

    it('create admaterial by another sponsor failed', async () => {
        let response = await request($SERVER)
            .post('/api/adperiods')
            .set('Authorization', auth($ADMIN))
            .send({
                user_id: $SPONSOR.id,
                adslot_id: $ADSLOT_1.id,
                start_at: '2017-01-01',
                months: 2
            })
            .expect('Content-Type', /application\/json/)
            .expect(200);
        let adpId = response.body.id;
        response = await request($SERVER)
            .post('/api/adperiods/' + adpId + '/admaterials')
            .set('Authorization', auth($SPONSOR_2))
            .send({
                url: 'http://www.example.com/',
                image: fs.readFileSync(__dirname + '/res-image-336x280.jpg').toString('base64')
            })
            .expect('Content-Type', /application\/json/)
            .expect(400);
        expect(response.body.error).to.equal('permission:denied');
    });

    it('create admaterial by sponsor failed for bad adperiod id', async () => {
        let response = await request($SERVER)
            .post('/api/adperiods/' + nextId() + '/admaterials')
            .set('Authorization', auth($SPONSOR))
            .send({
                url: ' http://www.sample.io/ ',
                weight: 100,
                start_at: '2017-01-01',
                image: fs.readFileSync(__dirname + '/res-image-336x280.jpg').toString('base64')
            })
            .expect('Content-Type', /application\/json/)
            .expect(400);
        expect(response.body.error).to.equal('entity:notfound');
        expect(response.body.data).to.equal('AdPeriod');
    });

    it('create admaterial by sponsor failed for bad url', async () => {
        let
            start = moment().startOf('month'),
            end = start.clone().add(2, 'months');
        let response = await request($SERVER)
            .post('/api/adperiods')
            .set('Authorization', auth($ADMIN))
            .send({
                user_id: $SPONSOR.id,
                adslot_id: $ADSLOT_1.id,
                start_at: start.format('YYYY-MM-DD'),
                months: 2
            })
            .expect('Content-Type', /application\/json/)
            .expect(200);
        let adpId = response.body.id;
        // bad url:
        response = await request($SERVER)
            .post('/api/adperiods/' + adpId + '/admaterials')
            .set('Authorization', auth($SPONSOR))
            .send({
                url: '  ', // invalid url
                weight: 100,
                start_at: start.format('YYYY-MM-DD'),
                end_at: end.format('YYYY-MM-DD'),
                image: fs.readFileSync(__dirname + '/res-image-336x280.jpg').toString('base64')
            })
            .expect('Content-Type', /application\/json/)
            .expect(400);
        expect(response.body.error).to.equal('parameter:invalid');
        expect(response.body.data).to.equal('url');
        // bad url:
        response = await request($SERVER)
            .post('/api/adperiods/' + adpId + '/admaterials')
            .set('Authorization', auth($SPONSOR))
            .send({
                url: ' ftp://www.sample.io/ ', // invalid url
                weight: 100,
                start_at: start.format('YYYY-MM-DD'),
                end_at: end.format('YYYY-MM-DD'),
                image: fs.readFileSync(__dirname + '/res-image-336x280.jpg').toString('base64')
            })
            .expect('Content-Type', /application\/json/)
            .expect(400);
        expect(response.body.error).to.equal('parameter:invalid');
        expect(response.body.data).to.equal('url');
    });

    it('create admaterial by sponsor failed for bad image', async () => {
        let
            start = moment().startOf('month'),
            end = start.clone().add(2, 'months');
        let response = await request($SERVER)
            .post('/api/adperiods')
            .set('Authorization', auth($ADMIN))
            .send({
                user_id: $SPONSOR.id,
                adslot_id: $ADSLOT_1.id,
                start_at: start.format('YYYY-MM-DD'),
                months: 2
            })
            .expect('Content-Type', /application\/json/)
            .expect(200);
        let adpId = response.body.id;
        // bad image:
        response = await request($SERVER)
            .post('/api/adperiods/' + adpId + '/admaterials')
            .set('Authorization', auth($SPONSOR))
            .send({
                url: 'http://www.example.com/',
                weight: 100,
                start_at: start.format('YYYY-MM-DD'),
                end_at: end.format('YYYY-MM-DD'),
                image: fs.readFileSync(__dirname + '/res-html-0.html').toString('base64')
            })
            .expect('Content-Type', /application\/json/)
            .expect(400);
        expect(response.body.error).to.equal('parameter:invalid');
        expect(response.body.data).to.equal('image');
        // bad image:
        response = await request($SERVER)
            .post('/api/adperiods/' + adpId + '/admaterials')
            .set('Authorization', auth($SPONSOR))
            .send({
                url: 'http://www.example.com/',
                weight: 100,
                start_at: start.format('YYYY-MM-DD'),
                end_at: end.format('YYYY-MM-DD'),
                // image too large:
                image: fs.readFileSync(__dirname + '/res-image-2.jpg').toString('base64')
            })
            .expect('Content-Type', /application\/json/)
            .expect(400);
        expect(response.body.error).to.equal('parameter:invalid');
        expect(response.body.data).to.equal('image');
    });

    it('create admaterial by sponsor ok', async () => {
        let
            start = moment().startOf('month'),
            end = start.clone().add(2, 'months');
        let response = await request($SERVER)
            .post('/api/adperiods')
            .set('Authorization', auth($ADMIN))
            .send({
                user_id: $SPONSOR.id,
                adslot_id: $ADSLOT_1.id,
                start_at: start.format('YYYY-MM-DD'),
                months: 2
            })
            .expect('Content-Type', /application\/json/)
            .expect(200);
        let adpId = response.body.id;
        response = await request($SERVER)
            .post('/api/adperiods/' + adpId + '/admaterials')
            .set('Authorization', auth($SPONSOR))
            .send({
                url: ' http://www.example.com/ ',
                weight: 100,
                start_at: start.format('YYYY-MM-DD'),
                end_at: end.format('YYYY-MM-DD'),
                image: fs.readFileSync(__dirname + '/res-image-336x280.jpg').toString('base64')
            })
            .expect('Content-Type', /application\/json/)
            .expect(200);
        expect(response.body).to.a('object');
        expect(response.body.user_id).to.equal($SPONSOR.id);
        expect(response.body.adperiod_id).to.equal(adpId);
        expect(response.body.start_at).to.equal(start.format('YYYY-MM-DD'));
        expect(response.body.end_at).to.equal(end.format('YYYY-MM-DD'));
        expect(response.body.url).to.equal('http://www.example.com/');
        expect(response.body.cover_id).to.a('string');
        // download image:
        let imageId = response.body.cover_id;
        response = await request($SERVER)
            .get('/files/attachments/' + imageId)
            .expect('Content-Type', /image\/jpeg/)
            .expect('Content-Length', '12834')
            .expect(200);
        // download size of s, m, l:
        for (let size of ['s', 'm', 'l']) {
            response = await request($SERVER)
                .get(`/files/attachments/${imageId}/${size}`)
                .expect(200);
        }
    });

    it('create admaterial by sponsor failed for too many', async () => {
        let
            start = moment().startOf('month'),
            end = start.clone().add(2, 'months');
        let response = await request($SERVER)
            .post('/api/adperiods')
            .set('Authorization', auth($ADMIN))
            .send({
                user_id: $SPONSOR.id,
                adslot_id: $ADSLOT_1.id,
                start_at: start.format('YYYY-MM-DD'),
                months: 2
            })
            .expect('Content-Type', /application\/json/)
            .expect(200);
        let adpId = response.body.id;
        // create 10 AdMaterials:
        for (let i=0; i<10; i++) {
            response = await request($SERVER)
                .post('/api/adperiods/' + adpId + '/admaterials')
                .set('Authorization', auth($SPONSOR))
                .send({
                    url: ' http://www.example.com/' + i,
                    weight: 10 + i,
                    start_at: start.format('YYYY-MM-DD'),
                    end_at: end.format('YYYY-MM-DD'),
                    image: fs.readFileSync(__dirname + '/res-image-336x280.jpg').toString('base64')
                })
                .expect('Content-Type', /application\/json/)
                .expect(200);
            expect(response.body).to.a('object');
            expect(response.body.user_id).to.equal($SPONSOR.id);
            expect(response.body.adperiod_id).to.equal(adpId);
            expect(response.body.url).to.equal('http://www.example.com/' + i);
        }
        // create another:
        response = await request($SERVER)
            .post('/api/adperiods/' + adpId + '/admaterials')
            .set('Authorization', auth($SPONSOR))
            .send({
                url: ' http://www.example.com/ ',
                weight: 100,
                start_at: start.format('YYYY-MM-DD'),
                end_at: end.format('YYYY-MM-DD'),
                image: fs.readFileSync(__dirname + '/res-image-336x280.jpg').toString('base64')
            })
            .expect('Content-Type', /application\/json/)
            .expect(400);
        expect(response.body.error).to.equal('maximum:reached');
    });

    it('create admaterial by sponsor ok then delete it', async () => {
        let
            start = moment().startOf('month'),
            end = start.clone().add(2, 'months');
        let response = await request($SERVER)
            .post('/api/adperiods')
            .set('Authorization', auth($ADMIN))
            .send({
                user_id: $SPONSOR.id,
                adslot_id: $ADSLOT_1.id,
                start_at: start.format('YYYY-MM-DD'),
                months: 2
            })
            .expect('Content-Type', /application\/json/)
            .expect(200);
        let adpId = response.body.id;
        response = await request($SERVER)
            .post('/api/adperiods/' + adpId + '/admaterials')
            .set('Authorization', auth($SPONSOR))
            .send({
                url: ' http://www.example.com/',
                weight: 10,
                start_at: start.format('YYYY-MM-DD'),
                end_at: end.format('YYYY-MM-DD'),
                image: fs.readFileSync(__dirname + '/res-image-336x280.jpg').toString('base64')
            })
            .expect('Content-Type', /application\/json/)
            .expect(200);
        expect(response.body).to.a('object');
        expect(response.body.user_id).to.equal($SPONSOR.id);
        expect(response.body.adperiod_id).to.equal(adpId);
        let admId = response.body.id;
        // delete it by another sponsor:
        response = await request($SERVER)
            .post('/api/admaterials/' + admId + '/delete')
            .set('Authorization', auth($SPONSOR_2))
            .send({})
            .expect('Content-Type', /application\/json/)
            .expect(400);
        expect(response.body.error).to.equal('permission:denied');
        // delete it ok:
        response = await request($SERVER)
            .post('/api/admaterials/' + admId + '/delete')
            .set('Authorization', auth($SPONSOR))
            .send({})
            .expect('Content-Type', /application\/json/)
            .expect(200);
        expect(response.body.id).to.equal(admId);
    });

});


text:
package org.eclipse.php.core.compiler.ast.nodes;

import org.eclipse.dltk.ast.ASTVisitor;
import org.eclipse.dltk.ast.expressions.Expression;
import org.eclipse.dltk.utils.CorePrinter;
import org.eclipse.php.internal.core.compiler.ast.visitor.ASTPrintVisitor;

/**
 * Represents an reference to a variable to be used inside function call.
 *
 *

 * e.g.
 *
 *

 * &$a, &$a[0], &$$a, &$a{'key'}
 */
public class ReferenceExpression extends Expression {

	private final Expression variable;

	public ReferenceExpression(int start, int end, Expression variable) {
		super(start, end);

		assert variable != null;
		this.variable = variable;
	}

	public void traverse(ASTVisitor visitor) throws Exception {
		final boolean visit = visitor.visit(this);
		if (visit) {
			variable.traverse(visitor);
		}
		visitor.endvisit(this);
	}

	public int getKind() {
		return ASTNodeKinds.REFERENCE;
	}

	public Expression getVariable() {
		return variable;
	}

	/**
	 * We don't print anything - we use {@link ASTPrintVisitor} instead
	 */
	public final void printNode(CorePrinter output) {
	}

	public String toString() {
		return ASTPrintVisitor.toXMLString(this);
	}
}


text:
package com.arpnetworking.utility;

import akka.dispatch.Mapper;

/**
 * Map method that just casts to another class.
 *
 * @param <T> Input type
 * @param <R> Output type
 * @author Brandon Arp (barp at groupon dot com)
 */
public class CastMapper<T, R> extends Mapper<T, R> {
    /**
     * {@inheritDoc}
     */
    @Override
    @SuppressWarnings("unchecked")
    public R apply(final T parameter) {
        return (R) parameter;
    }
}


text:
<?php

/* CriveroPruebaBundle:Usuarios:clientes.html.twig */
class __TwigTemplate_c6c73cc2b9ea8fd5d630f3552c35a6dc3933ce3377fba41826d31f613d8c3e9b extends Twig_Template
{
    public function __construct(Twig_Environment $env)
    {
        parent::__construct($env);

        // line 1
        try {
            $this->parent = $this->env->loadTemplate("CriveroPruebaBundle::main.html.twig");
        } catch (Twig_Error_Loader $e) {
            $e->setTemplateFile($this->getTemplateName());
            $e->setTemplateLine(1);

            throw $e;
        }

        $this->blocks = array(
            'title' => array($this, 'block_title'),
            'contenido' => array($this, 'block_contenido'),
            'javascripts' => array($this, 'block_javascripts'),
        );
    }

    protected function doGetParent(array $context)
    {
        return "CriveroPruebaBundle::main.html.twig";
    }

    protected function doDisplay(array $context, array $blocks = array())
    {
        $this->parent->display($context, array_merge($this->blocks, $blocks));
    }

    // line 2
    public function block_title($context, array $blocks = array())
    {
        echo " Clientes ";
    }

    // line 3
    public function block_contenido($context, array $blocks = array())
    {
        echo "

            Loading...

    ";
        // line 10
        echo twig_include($this->env, $context, "CriveroPruebaBundle:Default:messages/success.html.twig");
        echo "

Clientes

                ";
        // line 17
        if ( !twig_length_filter($this->env, (isset($context["pagination"]) ? $context["pagination"] : $this->getContext($context, "pagination")))) {
            // line 18
            echo "
No se encontraron clientes

                ";
        } else {
            // line 20
            echo "

                                    ";
            // line 25
            echo $this->env->getExtension('knp_pagination')->sortable($this->env, (isset($context["pagination"]) ? $context["pagination"] : $this->getContext($context, "pagination")), "Usuario", "u.username");
            echo "
                                    ";
            // line 26
            echo $this->env->getExtension('knp_pagination')->sortable($this->env, (isset($context["pagination"]) ? $context["pagination"] : $this->getContext($context, "pagination")), "Nombre", "u.nombre");
            echo "
                                    ";
            // line 27
            echo $this->env->getExtension('knp_pagination')->sortable($this->env, (isset($context["pagination"]) ? $context["pagination"] : $this->getContext($context, "pagination")), "Correo electrónico", "u.email");
            echo "
                                    ";
            // line 28
            echo $this->env->getExtension('knp_pagination')->sortable($this->env, (isset($context["pagination"]) ? $context["pagination"] : $this->getContext($context, "pagination")), "Creado", "u.registro");
            echo "
                                    Acciones

                                ";
            // line 33
            $context['_parent'] = (array) $context;
            $context['_seq'] = twig_ensure_traversable((isset($context["pagination"]) ? $context["pagination"] : $this->getContext($context, "pagination")));
            foreach ($context['_seq'] as $context["_key"] => $context["usuario"]) {
                // line 34
                echo "
env, $this->getAttribute($context["usuario"], "id", array()), "html", null, true);
                echo "\">
                                        env, $this->env->getExtension('assets')->getAssetUrl(("images/" . $this->getAttribute($context["usuario"], "imagen", array()))), "html", null, true);
                echo "\" class=\"img-responsive center-block \" style=\"max-width: 45px\"/>
                                            ";
                // line 36
                if (($this->getAttribute($context["usuario"], "activo", array()) == 1)) {
                    // line 37
                    echo "                                            ";
                    echo twig_escape_filter($this->env, $this->getAttribute($context["usuario"], "username", array()), "html", null, true);
                    echo "
                                        ";
                } else {
                    // line 39
                    echo "                                            ";
                    echo twig_escape_filter($this->env, $this->getAttribute($context["usuario"], "username", array()), "html", null, true);
                    echo "
                                                ";
                }
                // line 41
                echo "                                        ";
                echo twig_escape_filter($this->env, $this->getAttribute($context["usuario"], "nombre", array()), "html", null, true);
                echo "
                                        ";
                // line 42
                echo twig_escape_filter($this->env, $this->getAttribute($context["usuario"], "email", array()), "html", null, true);
                echo "
                                        ";
                // line 43
                echo twig_escape_filter($this->env, twig_date_format_filter($this->env, $this->getAttribute($context["usuario"], "registro", array()), "d/m/Y"), "html", null, true);
                echo "

                                            ";
                // line 45
                if (($this->getAttribute($context["usuario"], "activo", array()) == 1)) {
                    // line 46
                    echo "                                                env, $this->env->getExtension('routing')->getPath("crivero_prueba_cliente", array("id" => $this->getAttribute($context["usuario"], "id", array()))), "html", null, true);
                    echo "\" class=\"btn btn-sm btn-info noMargenBoton\">
                                                    Ver

                                            ";
                } else {
                    // line 50
                    echo "                                                <button class=\"btn btn-sm btn-info noMargenBoton\" disabled>Ver</button>
                                            ";
                }
                // line 52
                echo "                                            env, $this->env->getExtension('routing')->getPath("crivero_prueba_editarUsuario", array("id" => $this->getAttribute($context["usuario"], "id", array()))), "html", null, true);
                echo "\" class=\"btn btn-sm btn-primary noMargenBoton\">
                                                Editar

                                            ";
                // line 55
                if (($this->getAttribute($context["usuario"], "activo", array()) == 1)) {
                    // line 56
                    echo "                                                env, $this->env->getExtension('routing')->getPath("crivero_prueba_pagos_usuario", array("id" => $this->getAttribute($context["usuario"], "id", array()))), "html", null, true);
                    echo "\" class=\"btn btn-sm btn-warning noMargenBoton\">
                                                    Pagos

                                            ";
                } else {
                    // line 60
                    echo "                                                <button class=\"btn btn-sm btn-warning noMargenBoton\" disabled>Pagos</button>
                                            ";
                }
                // line 62
                echo "
                                                Eliminar

                                ";
            }
            $_parent = $context['_parent'];
            unset($context['_seq'], $context['_iterated'], $context['_key'], $context['usuario'], $context['_parent'], $context['loop']);
            $context = array_intersect_key($context, $_parent) + $_parent;
            // line 68
            echo "

                ";
        }
        // line 72
        echo "

                    ";
        // line 73
        echo $this->env->getExtension('knp_pagination')->render($this->env, (isset($context["pagination"]) ? $context["pagination"] : $this->getContext($context, "pagination")));
        echo "

        ";
        // line 77
        echo twig_include($this->env, $context, "CriveroPruebaBundle:Default:forms/form.html.twig", array("form" => (isset($context["delete_form_ajax"]) ? $context["delete_form_ajax"] : $this->getContext($context, "delete_form_ajax")), "id" => "form-delete", "with_submit" => false));
        echo "
    ";
    }

    // line 80
    public function block_javascripts($context, array $blocks = array())
    {
        // line 81
        echo "        ";
        $this->displayParentBlock("javascripts", $context, $blocks);
        echo "

    ";
    }

    public function getTemplateName()
    {
        return "CriveroPruebaBundle:Usuarios:clientes.html.twig";
    }

    public function isTraitable()
    {
        return false;
    }

    public function getDebugInfo()
    {
        return array (  215 => 82,  210 => 81,  207 => 80,  201 => 77,  194 => 73,  191 => 72,  185 => 68,  174 => 62,  170 => 60,  162 => 56,  160 => 55,  153 => 52,  149 => 50,  141 => 46,  139 => 45,  134 => 43,  130 => 42,  125 => 41,  119 => 39,  113 => 37,  111 => 36,  107 => 35,  102 => 34,  98 => 33,  90 => 28,  86 => 27,  82 => 26,  78 => 25,  71 => 20,  67 => 18,  65 => 17,  55 => 10,  44 => 3,  38 => 2,  11 => 1,);
    }
}


text:
[![Build Status](https://secure.travis-ci.org/angelozerr/tern-aui2.0.x.png)](http://travis-ci.org/angelozerr/tern-aui2.0.x)
[![NPM version](https://img.shields.io/npm/v/tern-aui2.0.x.svg)](https://www.npmjs.org/package/tern-aui2.0.x)

[tern-aui2.0.x](https://github.com/angelozerr/tern-aui2.0.x) is a plugin which adds support for [AlloyUI 2.0.x](http://alloyui.com/versions/2.0.x/) to the JavaScript code intelligence system [Tern](http://ternjs.net/).

Please read [Features](https://github.com/angelozerr/tern-aui2.0.x/wiki/Features) section to see the whole feature of this tern plugin.

## Demo

You can play with [online demo](http://demo-angelozerr.rhcloud.com/CodeMirror-Java/aui2.0.x.html) or see demo with CodeMirror (inside Web Browser) [demos/aui.html](https://github.com/angelozerr/tern-aui2.0.x/blob/master/demos/aui.html) :

![CodeMirror & Y Modules](https://github.com/angelozerr/tern-aui2.0.x/wiki/images/CodeMirror_CompletionForYModules.png)

If you wish to use Eclipse as IDE, see [Eclipse AlloyUI support](https://github.com/angelozerr/tern.java/wiki/Tern-&-AlloyUI-support).

![Eclipse & Y Modules](https://github.com/angelozerr/tern-aui2.0.x/wiki/images/Eclipse_CompletionForYModules.png)

##  Installation

`tern-aui2.0.x` works with the NodeJS [tern-server](http://ternjs.net/doc/manual.html#server), and within a browser. It depends on :

 * `brower` and `ecma5` JSON Type Definitions coming from the tern.
 * [yui3](https://github.com/angelozerr/tern-yui3) tern plugin.

### Short version

After installing Tern according the setup instructions of your desired [editor
plugin]([tern-editor]: http://ternjs.net/doc/manual.html#editor), go to the place where the [Tern package](https://www.npmjs.org/package/tern) was
installed (or the [Tern repo](https://github.com/marijnh/tern) was cloned) and run

```
$ npm install tern-aui2.0.x
```

Or, if you're not sure where Tern was installed, you can try
```
$ npm install -g tern-aui2.0.x
```

### Long version

See [INSTALL.md](INSTALL.md) for instructions tailored to each editor.

##  Configuration

### With Node.js

In order for Tern to load the tern-aui2.0.x plugin once it is installed, you must
include `aui2.0.x` in the `plugins` section of your [Tern configuration
file](http://ternjs.net/doc/manual.html#configuration). The configuration file can be either a file named
`.tern-project` in your project's root directory, or `.tern-config` in your home directory.

Here is a minimal example `.tern-project` configuration file:

```json
{
  "libs": ["ecma5","browser"],
  "plugins": {
    "yui3": {},
    "aui2.0.x": {}
  }
}
```

Note that [yui3](https://github.com/angelozerr/tern-yui3) tern plugin must be declared before `aui2.0.x`

#### "Project directory" and `.tern-project` vs `.tern-config`

Tern looks for `.tern-project` first, walking up the directory tree, and uses
its location as the "project directory". If no `.tern-project` is found, your
`.tern-config` is loaded instead, and *the working directory of the Tern server
process is used as the "project directory"*.

### With WebBrowser (CodeMirror)

See [demos/aui.html](https://github.com/angelozerr/tern-aui2.0.x/blob/master/demos/aui.html)

## How to generate aui2.0.x?

### Introduction

The tern plugin [aui2.0.x.js](https://github.com/angelozerr/tern-aui2.0.x/blob/master/aui2.0.x.js) is generated from the JavaScript sources of [AlloyUI 2.0.x](https://github.com/liferay/alloy-ui/tree/2.0.x). Process of this generation is :

 * AlloyUI sources uses [YUIDoc](http://yui.github.io/yuidoc/) comments. [YUIDoc](http://yui.github.io/yuidoc/) is able to generate a JSON representation of JavaScript sources. In this project, we use the this [api.json](https://github.com/angelozerr/tern-aui2.0.x/blob/master/generator/data/api.json) which is a copy/paste of the online [data.json](http://alloyui.com/versions/2.0.x/api/data.json).
 * generate JSON Type Definition from [api.json](https://github.com/angelozerr/tern-aui2.0.x/blob/master/generator/data/api.json) (YUIDoc format) by using the transformer [aui2tern.js](https://github.com/angelozerr/tern-aui2.0.x/blob/master/generator/aui2tern.js). Note that you can debug with Chrome this transformer by opening [aui2tern.html](https://github.com/angelozerr/tern-aui2.0.x/blob/master/generator/html/aui2tern.html).
 * generate the tern plugin by using the generated JSON Type Definition by calling :

`node generator/node/make_plugin`

### Instruction

Here the steps :

* open cmd
* `cd $HOME/tern-aui2.0.x`
* Generate the tern plugin **aui2.0.x** from [api.json](https://github.com/angelozerr/tern-aui2.0.x/blob/master/generator/data/api.json), by launching :

`node generator/node/make_plugin`

* You can execute tests with

`node test/all`

## Structure

The basic structure of the project is given in the following way:

* `aui2.0.x.js` the tern plugin.
* `demos/` demos with `aui2.0.x` tern plugin which use CodeMirror.


text:
from itertools import product
from collections import defaultdict, OrderedDict

import h5py
import numpy
import tables
from six.moves import zip, range

from fuel.datasets import Dataset
from fuel.utils import do_not_pickle_attributes

@do_not_pickle_attributes('nodes', 'h5file')
class PytablesDataset(Dataset):
    """A pytables dataset.

    An HDF5 Dataset which was created with pytables. The dataset should
    have the following structure: `/<data_node>/paths/to/sources`. In
    order to have train/validation/test split you may want to open
    several datasets with different data nodes or source paths. It is
    also possible to use start and stop arguments to split your dataset.

    Parameters
    ----------
    sources : tuple of strings
        Sources which the dataset returns.
    start : int
        Start index. Optional, by default is 0.
    stop : int
        Stop index. Optional, if is not provided, will be set to the
        number of rows of the first source.
    data_node : str
        Parent data node in HDF5 file, all path are relative to this node.
    sources_in_file : tuple of strings
        Names of nodes in HDF5 file which contain sources. Should the same
        length as `sources`.
        Optional, if not set will be equal to `sources`.

    """
    def __init__(self, path, sources, start=0, stop=None, data_node='Data',
                 sources_in_file=None):
        if sources_in_file is None:
            sources_in_file = sources
        self.sources_in_file = sources_in_file
        self.provides_sources = sources
        self.path = path
        self.data_node = data_node
        self.start = start
        self.stop = stop
        self.nodes = None
        self.open_file(path)
        super(PytablesDataset, self).__init__(self.provides_sources)

    def open_file(self, path):
        self.h5file = tables.open_file(path, mode="r")
        node = self.h5file.get_node('/', self.data_node)

        self.nodes = [getattr(node, source) for source in self.sources_in_file]
        if self.stop is None:
            self.stop = self.nodes[0].nrows
        self.num_examples = self.stop - self.start

    def load(self):
        self.open_file(self.path)

    def close_file(self):
        self.h5file.close()
        del self._h5file
        del self._nodes

    def get_data(self, state=None, request=None):
        """ Returns data from HDF5 dataset.

        .. note:: The best performance if `request` is a slice.

        """
        if isinstance(request, slice):
            request = slice(request.start + self.start,
                            request.stop + self.start, request.step)
            data = [node[request] for node in self.nodes]
        elif isinstance(request, list):
            request = [index + self.start for index in request]
            data = [node[request, ...] for node in self.nodes]
        else:
            raise ValueError
        return data

@do_not_pickle_attributes('data_sources', 'external_file_handle',
                          'source_shapes')
class H5PYDataset(Dataset):
    """An h5py-fueled HDF5 dataset.

    This dataset class assumes a particular file layout:

    * Data sources reside in the root group, and their names define the
      source names.
    * Data sources are not explicitly split. Instead, splits are defined
      in the `split` attribute of the root group. It's expected to be a
      1D numpy array of compound ``dtype`` with six fields, organized as
      follows:

      1. ``split`` : string identifier for the split name
      2. ``source`` : string identifier for the source name
      3. ``start`` : start index (inclusive) of the split in the source
         array
      4. ``stop`` : stop index (exclusive) of the split in the source
         array
      5. ``available`` : boolean, ``False`` is this split is not available
         for this source
      6. ``comment`` : comment string

    Parameters
    ----------
    file_or_path : :class:`h5py.File` or str
        HDF5 file handle, or path to the HDF5 file.
    which_set : str
        Which split to use.
    subset : slice, optional
        A slice of data *within the context of the split* to use. Defaults
        to `None`, in which case the whole split is used. **Note:
        at the moment, `slice.step` must be either 1 or `None`.**
    load_in_memory : bool, optional
        Whether to load the data in main memory. Defaults to `False`.
    driver : str, optional
        Low-level driver to use. Defaults to `None`. See h5py
        documentation for a complete list of available options.
    sort_indices : bool, optional
        Whether to explicitly sort requested indices when data is
        requested in the form of a list of indices. Defaults to `True`.
        This flag can be set to `False` for greater performance. In
        that case, it is the user's responsibility to make sure that
        indices are ordered.

    """
    interface_version = '0.2'
    _ref_counts = defaultdict(int)
    _file_handles = {}

    def __init__(self, file_or_path, which_set, subset=None,
                 load_in_memory=False, driver=None, sort_indices=True,
                 **kwargs):
        if isinstance(file_or_path, h5py.File):
            self.path = file_or_path.filename
            self.external_file_handle = file_or_path
        else:
            self.path = file_or_path
            self.external_file_handle = None
        self.driver = driver
        self.sort_indices = sort_indices
        if which_set not in self.available_splits:
            raise ValueError(
                "'{}' split is not provided by this ".format(which_set) +
                "dataset. Available splits are " +
                "{}.".format(self.available_splits))
        self.which_set = which_set
        subset = subset if subset else slice(None)
        if subset.step not in (1, None):
            raise ValueError("subset.step must be either 1 or None")
        self._subset_template = subset
        self.load_in_memory = load_in_memory

        kwargs.setdefault('axis_labels', self.load_axis_labels())
        super(H5PYDataset, self).__init__(**kwargs)

    @staticmethod
    def create_split_array(split_dict):
        """Create a valid array for the `split` attribute of the root node.

        Parameters
        ----------
        split_dict : dict
            Maps split names to dict. Those dict map source names to
            tuples. Those tuples contain two or three elements:
            the start index, the stop index and (optionally) a comment.
            If a particular split/source combination isn't present
            in the split dict, it's considered as unavailable and the
            `available` element will be set to `False` it its split array
            entry.

        """
        # Determine maximum split, source and string lengths
        split_len = max(len(split) for split in split_dict)
        sources = set()
        comment_len = 1
        for split in split_dict.values():
            sources |= set(split.keys())
            for val in split.values():
                if len(val) == 3:
                    comment_len = max([comment_len, len(val[-1])])
        sources = sorted(list(sources))
        source_len = max(len(source) for source in sources)

        # Instantiate empty split array
        split_array = numpy.empty(
            len(split_dict) * len(sources),
            dtype=numpy.dtype([
                ('split', 'a', split_len),
                ('source', 'a', source_len),
                ('start', numpy.int64, 1), ('stop', numpy.int64, 1),
                ('available', numpy.bool, 1),
                ('comment', 'a', comment_len)]))

        # Fill split array
        for i, (split, source) in enumerate(product(split_dict, sources)):
            if source in split_dict[split]:
                start, stop = split_dict[split][source][:2]
                available = True
                # Workaround for bug when pickling an empty string
                comment = '.'
                if len(split_dict[split][source]) == 3:
                    comment = split_dict[split][source][2]
                    if not comment:
                        comment = '.'
            else:
                (start, stop, available, comment) = (0, 0, False, '.')
            # Workaround for H5PY being unable to store unicode type
            split_array[i]['split'] = split.encode('utf8')
            split_array[i]['source'] = source.encode('utf8')
            split_array[i]['start'] = start
            split_array[i]['stop'] = stop
            split_array[i]['available'] = available
            split_array[i]['comment'] = comment.encode('utf8')

        return split_array

    @staticmethod
    def parse_split_array(split_array):
        split_dict = OrderedDict()
        for row in split_array:
            split, source, start, stop, available, comment = row
            split = split.decode('utf8')
            source = source.decode('utf8')
            comment = comment.decode('utf8')
            if available:
                if split not in split_dict:
                    split_dict[split] = OrderedDict()
                split_dict[split][source] = (start, stop, comment)
        return split_dict

    @staticmethod
    def unsorted_fancy_index(request, indexable):
        """Safe unsorted list indexing.

        Some objects, such as h5py datasets, only support list indexing
        if the list is sorted.

        This static method adds support for unsorted list indexing by
        sorting the requested indices, accessing the corresponding
        elements and re-shuffling the result.

        Parameters
        ----------
        request : list of int
            Unsorted list of example indices.
        indexable : any fancy-indexable object
            Indexable we'd like to do unsorted fancy indexing on.

        """
        if len(request) > 1:
            indices = numpy.argsort(request)
            data = numpy.empty(shape=(len(request),) + indexable.shape[1:],
                               dtype=indexable.dtype)
            data[indices] = indexable[numpy.array(request)[indices], ...]
        else:
            data = indexable[request]
        return data

    @property
    def split_dict(self):
        if not hasattr(self, '_split_dict'):
            self._out_of_memory_open()
            handle = self._file_handle
            split_array = handle.attrs['split']
            self._split_dict = H5PYDataset.parse_split_array(split_array)
            self._out_of_memory_close()
        return self._split_dict

    def load_axis_labels(self):
        self._out_of_memory_open()
        handle = self._file_handle
        axis_labels = {}
        for source_name in handle:
            if source_name in self.vlen_sources:
                axis_labels[source_name] = (
                    (handle[source_name].dims[0].label,) +
                    tuple(label.decode('utf8') for label in
                          handle[source_name].dims[0]['shape_labels']))
            else:
                axis_labels[source_name] = tuple(
                    dim.label for dim in handle[source_name].dims)
        self._out_of_memory_close()
        return axis_labels

    @property
    def available_splits(self):
        return tuple(self.split_dict.keys())

    @property
    def provides_sources(self):
        return tuple(self.split_dict[self.which_set].keys())

    @property
    def vlen_sources(self):
        if not hasattr(self, '_vlen_sources'):
            self._out_of_memory_open()
            handle = self._file_handle
            vlen_sources = []
            for source_name in self.sources:
                source = handle[source_name]
                if len(source.dims) > 0 and 'shapes' in source.dims[0]:
                    if len(source.dims) > 1:
                        raise ValueError('Variable-length sources must have '
                                         'only one dimension.')
                    vlen_sources.append(source_name)
            self._vlen_sources = tuple(vlen_sources)
            self._out_of_memory_close()
        return self._vlen_sources

    @property
    def subsets(self):
        if not hasattr(self, '_subsets'):
            subsets = [self._subset_template for source in self.sources]
            num_examples = None
            for i, source_name in enumerate(self.sources):
                start, stop = self.split_dict[self.which_set][source_name][:2]
                subset = subsets[i]
                subset = slice(
                    start if subset.start is None else subset.start,
                    stop if subset.stop is None else subset.stop,
                    subset.step)
                subsets[i] = subset
                if num_examples is None:
                    num_examples = subset.stop - subset.start
                if num_examples != subset.stop - subset.start:
                    raise ValueError("sources have different lengths")
            self._subsets = subsets
        return self._subsets

    def load(self):
        if not hasattr(self, '_external_file_handle'):
            self.external_file_handle = None
        self._out_of_memory_open()
        handle = self._file_handle
        if self.load_in_memory:
            self.data_sources = tuple(
                handle[source_name][subset] for source_name, subset in
                zip(self.sources, self.subsets))
            self.source_shapes = tuple(
                handle[source_name].dims[0]['shapes'][subset]
                if source_name in self.vlen_sources else None
                for source_name, subset in zip(self.sources, self.subsets))
        else:
            self.data_sources = None
            self.source_shapes = None
        self._out_of_memory_close()

    @property
    def num_examples(self):
        return self.subsets[0].stop - self.subsets[0].start

    def open(self):
        return None if self.load_in_memory else self._out_of_memory_open()

    def _out_of_memory_open(self):
        if not self._external_file_handle:
            if self.path not in self._file_handles:
                handle = h5py.File(
                    name=self.path, mode="r", driver=self.driver)
                self._file_handles[self.path] = handle
            self._ref_counts[self.path] += 1

    def close(self, state):
        if not self.load_in_memory:
            self._out_of_memory_close()

    def _out_of_memory_close(self):
        if not self._external_file_handle:
            self._ref_counts[self.path] -= 1
            if not self._ref_counts[self.path]:
                del self._ref_counts[self.path]
                self._file_handles[self.path].close()
                del self._file_handles[self.path]

    @property
    def _file_handle(self):
        if self._external_file_handle:
            return self._external_file_handle
        elif self.path in self._file_handles:
            return self._file_handles[self.path]
        else:
            raise IOError('no open handle for file {}'.format(self.path))

    def get_data(self, state=None, request=None):
        if self.load_in_memory:
            data, shapes = self._in_memory_get_data(state, request)
        else:
            data, shapes = self._out_of_memory_get_data(state, request)
        for i in range(len(data)):
            if shapes[i] is not None:
                for j in range(len(data[i])):
                    data[i][j] = data[i][j].reshape(shapes[i][j])
        return tuple(data)

    def _in_memory_get_data(self, state=None, request=None):
        if state is not None or request is None:
            raise ValueError
        data = [data_source[request] for data_source in self.data_sources]
        shapes = [shape[request] if shape is not None else None
                  for shape in self.source_shapes]
        return data, shapes

    def _out_of_memory_get_data(self, state=None, request=None):
        data = []
        shapes = []
        handle = self._file_handle
        for source_name, subset in zip(self.sources, self.subsets):
            if isinstance(request, slice):
                req = slice(request.start + subset.start,
                            request.stop + subset.start, request.step)
                val = handle[source_name][req]
                if source_name in self.vlen_sources:
                    shape = handle[
                        source_name].dims[0]['shapes'][req]
                else:
                    shape = None
            elif isinstance(request, list):
                req = [index + subset.start for index in request]
                if self.sort_indices:
                    val = self.unsorted_fancy_index(req, handle[source_name])
                    if source_name in self.vlen_sources:
                        shape = self.unsorted_fancy_index(
                            req, handle[source_name].dims[0]['shapes'])
                    else:
                        shape = None
                else:
                    val = handle[source_name][req]
                    if source_name in self.vlen_sources:
                        shape = handle[
                            source_name].dims[0]['shapes'][req]
                    else:
                        shape = None
            else:
                raise ValueError
            data.append(val)
            shapes.append(shape)
        return data, shapes


text:
<!--

********************************************************************************

WARNING:

    DO NOT EDIT "pypy/README.md"

    IT IS AUTO-GENERATED

    (from the other files in "pypy/" combined with a set of templates)

********************************************************************************

-->

# Supported tags and respective `Dockerfile` links

-	[`2-6.0.0`, `2-6.0`, `2-6`, `2`, `2-6.0.0-jessie`, `2-6.0-jessie`, `2-6-jessie`, `2-jessie` (*2/Dockerfile*)](https://github.com/docker-library/pypy/blob/d813837c73e726c0b5568297eff2f5a4b00c123f/2/Dockerfile)
-	[`2-6.0.0-slim`, `2-6.0-slim`, `2-6-slim`, `2-slim`, `2-6.0.0-slim-jessie`, `2-6.0-slim-jessie`, `2-6-slim-jessie`, `2-slim-jessie` (*2/slim/Dockerfile*)](https://github.com/docker-library/pypy/blob/d813837c73e726c0b5568297eff2f5a4b00c123f/2/slim/Dockerfile)
-	[`3-6.0.0`, `3-6.0`, `3-6`, `3`, `latest`, `3-6.0.0-jessie`, `3-6.0-jessie`, `3-6-jessie`, `3-jessie`, `jessie` (*3/Dockerfile*)](https://github.com/docker-library/pypy/blob/d813837c73e726c0b5568297eff2f5a4b00c123f/3/Dockerfile)
-	[`3-6.0.0-slim`, `3-6.0-slim`, `3-6-slim`, `3-slim`, `slim`, `3-6.0.0-slim-jessie`, `3-6.0-slim-jessie`, `3-6-slim-jessie`, `3-slim-jessie`, `slim-jessie` (*3/slim/Dockerfile*)](https://github.com/docker-library/pypy/blob/d813837c73e726c0b5568297eff2f5a4b00c123f/3/slim/Dockerfile)

# Quick reference

-	**Where to get help**:
	[the Docker Community Forums](https://forums.docker.com/), [the Docker Community Slack](https://blog.docker.com/2016/11/introducing-docker-community-directory-docker-community-slack/), or [Stack Overflow](https://stackoverflow.com/search?tab=newest&q=docker)

-	**Where to file issues**:
	[https://github.com/docker-library/pypy/issues](https://github.com/docker-library/pypy/issues)

-	**Maintained by**:
	[the Docker Community](https://github.com/docker-library/pypy)

-	**Supported architectures**: ([more info](https://github.com/docker-library/official-images#architectures-other-than-amd64))
	[`amd64`](https://hub.docker.com/r/amd64/pypy/), [`arm32v5`](https://hub.docker.com/r/arm32v5/pypy/), [`i386`](https://hub.docker.com/r/i386/pypy/)

-	**Published image artifact details**:
	[repo-info repo's `repos/pypy/` directory](https://github.com/docker-library/repo-info/blob/master/repos/pypy) ([history](https://github.com/docker-library/repo-info/commits/master/repos/pypy))
	(image metadata, transfer size, etc)

-	**Image updates**:
	[official-images PRs with label `library/pypy`](https://github.com/docker-library/official-images/pulls?q=label%3Alibrary%2Fpypy)
	[official-images repo's `library/pypy` file](https://github.com/docker-library/official-images/blob/master/library/pypy) ([history](https://github.com/docker-library/official-images/commits/master/library/pypy))

-	**Source of this description**:
	[docs repo's `pypy/` directory](https://github.com/docker-library/docs/tree/master/pypy) ([history](https://github.com/docker-library/docs/commits/master/pypy))

-	**Supported Docker versions**:
	[the latest release](https://github.com/docker/docker-ce/releases/latest) (down to 1.6 on a best-effort basis)

# What is PyPy?

PyPy is a Python interpreter and just-in-time compiler. PyPy focuses on speed, efficiency and compatibility with the original CPython interpreter.

PyPy started out as a Python interpreter written in the Python language itself. Current PyPy versions are translated from RPython to C code and compiled. The PyPy JIT (short for "Just In Time") compiler is capable of turning Python code into machine code at run time.

> [wikipedia.org/wiki/PyPy](https://en.wikipedia.org/wiki/PyPy)

![logo](https://raw.githubusercontent.com/docker-library/docs/ff804ee81e3f94dab5cd207a0a0504e5e67606dd/pypy/logo.png)

# How to use this image

## Create a `Dockerfile` in your Python app project

```dockerfile
FROM pypy:3

WORKDIR /usr/src/app

COPY requirements.txt ./
RUN pip install --no-cache-dir -r requirements.txt

COPY . .

CMD [ "pypy3", "./your-daemon-or-script.py" ]
```

or (if you need to use Python 2):

```dockerfile
FROM pypy:2

WORKDIR /usr/src/app

COPY requirements.txt ./
RUN pip install --no-cache-dir -r requirements.txt

COPY . .

CMD [ "pypy", "./your-daemon-or-script.py" ]
```

You can then build and run the Docker image:

```console
$ docker build -t my-python-app .
$ docker run -it --rm --name my-running-app my-python-app
```

## Run a single Python script

For many simple, single file projects, you may find it inconvenient to write a complete `Dockerfile`. In such cases, you can run a Python script by using the Python Docker image directly:

```console
$ docker run -it --rm --name my-running-script -v "$PWD":/usr/src/myapp -w /usr/src/myapp pypy:3 pypy3 your-daemon-or-script.py
```

or (again, if you need to use Python 2):

```console
$ docker run -it --rm --name my-running-script -v "$PWD":/usr/src/myapp -w /usr/src/myapp pypy:2 pypy your-daemon-or-script.py
```

# Image Variants

The `pypy` images come in many flavors, each designed for a specific use case.

## `pypy:<version>`

This is the defacto image. If you are unsure about what your needs are, you probably want to use this one. It is designed to be used both as a throw away container (mount your source code and start the container to start your app), as well as the base to build other images off of. This tag is based off of [`buildpack-deps`](https://registry.hub.docker.com/_/buildpack-deps/). `buildpack-deps` is designed for the average user of docker who has many images on their system. It, by design, has a large number of extremely common Debian packages. This reduces the number of packages that images that derive from it need to install, thus reducing the overall size of all images on your system.

## `pypy:slim`

This image does not contain the common packages contained in the default tag and only contains the minimal packages needed to run `pypy`. Unless you are working in an environment where *only* the `pypy` image will be deployed and you have space constraints, we highly recommend using the default image of this repository.

# License

View [license information](https://bitbucket.org/pypy/pypy/src/c3ff0dd6252b6ba0d230f3624dbb4aab8973a1d0/LICENSE?at=default) for software contained in this image.

As with all Docker images, these likely also contain other software which may be under other licenses (such as Bash, etc from the base distribution, along with any direct or indirect dependencies of the primary software being contained).

Some additional license information which was able to be auto-detected might be found in [the `repo-info` repository's `pypy/` directory](https://github.com/docker-library/repo-info/tree/master/repos/pypy).

As for any pre-built image usage, it is the image user's responsibility to ensure that any use of this image complies with any relevant licenses for all software contained within.


text:
import os
import stdeb.util as util

from distutils.core import Command

__all__ = ['bdist_deb']

class bdist_deb(Command):
    description = 'distutils command to create debian binary package'

    user_options = [
        ('sign-results', None,
         'Use gpg to sign the resulting .dsc and .changes file'),
        ('ignore-source-changes', None,
         'Ignore all changes on source when building source package '
         '(add -i.* option to dpkg-source'),
        ]
    boolean_options = [
        'sign-results',
        'ignore-source-changes',
        ]

    def initialize_options(self):
        self.sign_results = False
        self.ignore_source_changes = False

    def finalize_options(self):
        self.sign_results = bool(self.sign_results)
        self.ignore_source_changes = bool(self.ignore_source_changes)

    def run(self):
        # generate .dsc source pkg
        self.run_command('sdist_dsc')

        # get relevant options passed to sdist_dsc
        sdist_dsc = self.get_finalized_command('sdist_dsc')
        dsc_tree = sdist_dsc.dist_dir

        # execute system command and read output
        # (execute and read output of find cmd)
        target_dirs = []
        for entry in os.listdir(dsc_tree):
            fulldir = os.path.join(dsc_tree, entry)
            if os.path.isdir(fulldir):
                if entry == 'tmp_py2dsc':
                    continue
                target_dirs.append(fulldir)

        if len(target_dirs) > 1:
            raise ValueError('More than one directory in deb_dist. '
                             'Unsure which is source directory. All: %r' % (
                                target_dirs,))

        if len(target_dirs) == 0:
            raise ValueError('could not find debian source directory')

        # define system command to execute (gen .deb binary pkg)
        syscmd = ['dpkg-buildpackage', '-rfakeroot', '-b']

        if not self.sign_results:
            syscmd.append('-uc')

        if self.ignore_source_changes:
            syscmd.append('-i.*')

        util.process_command(syscmd, cwd=target_dirs[0])


text:
@interface UICircularSliderViewController ()

@property (unsafe_unretained, nonatomic) IBOutlet UISlider *slider;
@property (unsafe_unretained, nonatomic) IBOutlet UIProgressView *progressView;
@property (unsafe_unretained, nonatomic) IBOutlet UICircularSlider *circularSlider;

@end

@implementation UICircularSliderViewController
@synthesize slider = _slider;
@synthesize progressView = _progressView;
@synthesize circularSlider = _circularSlider;

- (void)viewDidLoad {
    [super viewDidLoad];
	[self.circularSlider addTarget:self action:@selector(updateProgress:) forControlEvents:UIControlEventValueChanged];
	[self.circularSlider setMinimumValue:self.slider.minimumValue];
	[self.circularSlider setMaximumValue:self.slider.maximumValue];
}

- (void)viewDidUnload {
	[self setProgressView:nil];
	[self setCircularSlider:nil];
	[self setSlider:nil];
    [super viewDidUnload];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
	return YES;
}

- (IBAction)updateProgress:(UISlider *)sender {
	float progress = translateValueFromSourceIntervalToDestinationInterval(sender.value, sender.minimumValue, sender.maximumValue, 0.0, 1.0);
	[self.progressView setProgress:progress];
	[self.circularSlider setValue:sender.value];
	[self.slider setValue:sender.value];
}

@end


text:
package Paws::Pinpoint::GetImportJobResponse;
  use Moose;
  has ImportJobResponse => (is => 'ro', isa => 'Paws::Pinpoint::ImportJobResponse', required => 1);
  use MooseX::ClassAttribute;
  class_has _stream_param => (is => 'ro', default => 'ImportJobResponse');
  has _request_id => (is => 'ro', isa => 'Str');
1;

### main pod documentation begin ###

=head1 NAME

Paws::Pinpoint::GetImportJobResponse

=head1 ATTRIBUTES

=head2 B<REQUIRED> ImportJobResponse => L<Paws::Pinpoint::ImportJobResponse>

=head2 _request_id => Str

=cut


text:
package com.aurorasdk;

public class CommandTimeout implements Runnable {

    public interface TimeoutHandler {
        void onTimeout();
    }

    private TimeoutHandler timeoutHandler;

    CommandTimeout(TimeoutHandler timeoutHandler){

        this.timeoutHandler = timeoutHandler;
    }

    @Override
    public void run() {

        if (timeoutHandler != null){

            //this try/catch is important, because otherwise
            //the handler will silently fail if any exception
            //is thrown...very very confusing
            try {
                timeoutHandler.onTimeout();
            }
            catch (Exception e){

                e.printStackTrace();
            }
        }
    }
}


text:
//========================================================================
//Copyright 2007-2010 David Yu dyuproject@gmail.com
//------------------------------------------------------------------------
//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//http://www.apache.org/licenses/LICENSE-2.0
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
//========================================================================

package com.dyuproject.protostuff.parser;

import java.io.File;

import junit.framework.TestCase;

/**
 * Test for the default proto loader.
 *
 * @author David Yu
 * @created May 16, 2010
 */
public class DefaultProtoLoaderTest extends TestCase
{

    public void testPackageBaseDir() throws Exception
    {
        File f = ProtoParserTest.getFile(
                "com/dyuproject/protostuff/parser/test_default_proto_loader.proto");
        assertTrue(f.exists());
        Proto p = ProtoUtil.parseProto(f);
        assertEquals("com.dyuproject.protostuff.parser", p.getPackageName());
    }

    public void testLoadProtoFromClasspath() throws Exception
    {
        Proto proto = DefaultProtoLoader.loadFromClasspath(
                "google/protobuf/unittest_import.proto", null);
        assertNotNull(proto);
        assertEquals("protobuf_unittest_import", proto.getPackageName());
    }

    public void testImportFromClasspath() throws Exception
    {
        File f = new File("src/main/etc/test_default_proto_loader.proto");
        assertTrue(f.exists());
        Proto p = ProtoUtil.parseProto(f);
        assertEquals("com.dyuproject.protostuff.parser", p.getPackageName());

        Message testMessage = p.getMessage("TestMessage");
        assertNotNull(testMessage);

        Field<?> f1 = testMessage.getField("imported_message1");
        Field<?> f2 = testMessage.getField("imported_message2");

        assertNotNull(f1);
        assertNotNull(f2);

        assertTrue(f1 instanceof MessageField);
        assertTrue(f2 instanceof MessageField);

        Message importedMessage1 = ((MessageField)f1).getMessage();
        Message importedMessage2 = ((MessageField)f2).getMessage();

        assertNotNull(importedMessage1);
        assertNotNull(importedMessage2);

        assertTrue(importedMessage1 == importedMessage2);
    }

}


text:
Daniel

Terence
## 0.0.1 - 2017-09-14
### Added

- Quotes to individual pages
- Hyperlinks to images that send to individual pages
- Tooltip
- Trump avatar
- changelog file


text:
Implemented this design: https://www.uplabs.com/posts/glazzy-free-portfolio-psd-template

Made with HTML + CSS + React.js


text:
package codeu.chat.common;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.UUID;

import codeu.chat.util.Serializer;
import codeu.chat.util.Serializers;
import codeu.chat.util.Time;
import codeu.chat.util.Uuid;

public final class Message {

  public static final Serializer<Message> SERIALIZER = new Serializer<Message>() {

    @Override
    public void write(OutputStream out, Message value) throws IOException {

      Uuid.SERIALIZER.write(out, value.id);
      Uuid.SERIALIZER.write(out, value.next);
      Uuid.SERIALIZER.write(out, value.previous);
      Time.SERIALIZER.write(out, value.creation);
      Uuid.SERIALIZER.write(out, value.author);
      Serializers.STRING.write(out, value.content);
      Uuid.SERIALIZER.write(out, value.convoId);
      Serializers.INTEGER.write(out, value.likes);

    }

    @Override
    public Message read(InputStream in) throws IOException {

      return new Message(
          Uuid.SERIALIZER.read(in),
          Uuid.SERIALIZER.read(in),
          Uuid.SERIALIZER.read(in),
          Time.SERIALIZER.read(in),
          Uuid.SERIALIZER.read(in),
          Serializers.STRING.read(in),
          Uuid.SERIALIZER.read(in),
          Serializers.INTEGER.read(in)
      );

    }
  };

  public final Uuid id;
  public final Uuid previous;
  public final Time creation;
  public final Uuid author;
  public final String content;
  public final Uuid convoId;
  public Uuid next;
  public int likes;

  public Message(Uuid id, Uuid next, Uuid previous, Time creation, Uuid author, String content, Uuid convoId, int likes) {

    this.id = id;
    this.next = next;
    this.previous = previous;
    this.creation = creation;
    this.author = author;
    this.content = content;
    this.convoId = convoId;
    this.likes = likes;

  }
}