text:
#include <config.h>

#include <string.h>

#define ZLIB_CONST
#include <zlib.h>

#include "internals.h"
#include "zip.h"

#ifndef MIN
#define MIN(x,y) (((x) < (y)) ? (x) : (y))
#endif

enum {
  ARCHIVE_CLOSED = 0,
  ARCHIVE_OPEN
};

/* Seek safely within ZIP archive */
static libspectrum_error
seek( struct libspectrum_zip *z, long offset, int whence )
{
  const libspectrum_byte *ptr;

  switch( whence ) {
  case SEEK_SET:
    ptr = z->input_data + offset;
    break;

  case SEEK_CUR:
    ptr = z->ptr + offset;
    break;

  case SEEK_END:
    ptr = z->end + offset;
    break;

  default:
    return LIBSPECTRUM_ERROR_CORRUPT;
  }

  /* Validate address */
  if( ptr < z->input_data || ptr > z->end )
    return LIBSPECTRUM_ERROR_CORRUPT;

  z->ptr = ptr;

  return LIBSPECTRUM_ERROR_NONE;
}

static libspectrum_error
read_directory_info( zip_directory_info *info, const libspectrum_byte *buffer,
                     const libspectrum_byte *end )
{
  if( buffer + ZIP_DIRECTORY_INFO_SIZE > end ) {
    return LIBSPECTRUM_ERROR_CORRUPT;
  }

  info->magic                = libspectrum_read_dword( &buffer );
  info->disk_index           = libspectrum_read_word( &buffer );
  info->directory_disk_index = libspectrum_read_word( &buffer );
  info->disk_file_count      = libspectrum_read_word( &buffer );
  info->file_count           = libspectrum_read_word( &buffer );
  info->directory_size       = libspectrum_read_dword( &buffer );
  info->directory_offset     = libspectrum_read_dword( &buffer );
  info->comment_size         = libspectrum_read_word( &buffer );

  return LIBSPECTRUM_ERROR_NONE;
}

static int
read_file_header( zip_file_header *file_info, const libspectrum_byte *buffer,
                  const libspectrum_byte *end )
{
  if( buffer + ZIP_FILE_HEADER_SIZE > end ) {
    return 0;
  }

  file_info->magic             = libspectrum_read_dword( &buffer );
  file_info->creator_version   = libspectrum_read_word( &buffer );
  file_info->required_version  = libspectrum_read_word( &buffer );
  file_info->flags             = libspectrum_read_word( &buffer );
  file_info->compression       = libspectrum_read_word( &buffer );
  file_info->mod_time          = libspectrum_read_word( &buffer );
  file_info->mod_date          = libspectrum_read_word( &buffer );
  file_info->crc               = libspectrum_read_dword( &buffer );
  file_info->compressed_size   = libspectrum_read_dword( &buffer );
  file_info->uncompressed_size = libspectrum_read_dword( &buffer );
  file_info->name_size         = libspectrum_read_word( &buffer );
  file_info->extra_field_size  = libspectrum_read_word( &buffer );
  file_info->comment_size      = libspectrum_read_word( &buffer );
  file_info->disk_index        = libspectrum_read_word( &buffer );
  file_info->internal_flags    = libspectrum_read_word( &buffer );
  file_info->external_flags    = libspectrum_read_dword( &buffer );
  file_info->file_offset       = libspectrum_read_dword( &buffer );

  return ZIP_FILE_HEADER_SIZE;
}

static int
read_local_header( zip_local_header *local_info,
                   const libspectrum_byte *buffer,
                   const libspectrum_byte *end )
{
  if( buffer + ZIP_LOCAL_HEADER_SIZE > end ) {
    return 0;
  }

  local_info->magic = libspectrum_read_dword( &buffer );
  local_info->required_version = libspectrum_read_word( &buffer );
  local_info->flags = libspectrum_read_word( &buffer );
  local_info->compression = libspectrum_read_word( &buffer );
  local_info->mod_time = libspectrum_read_word( &buffer );
  local_info->mod_date = libspectrum_read_word( &buffer );
  local_info->crc = libspectrum_read_dword( &buffer );
  local_info->compressed_size = libspectrum_read_dword( &buffer );
  local_info->uncompressed_size = libspectrum_read_dword( &buffer );
  local_info->name_size = libspectrum_read_word( &buffer );
  local_info->extra_field_size = libspectrum_read_word( &buffer );

  return ZIP_LOCAL_HEADER_SIZE;
}

static int
match_file_names( const char *a, const char *b, const int ignore_case )
{
  if( !a || !b ) return 0;

  return ( ignore_case ? ( strcasecmp( a, b ) == 0 ) :
                          ( strcmp( a, b ) == 0 ) );
}

/* Close the ZIP archive */
static void
close_zip( struct libspectrum_zip *z )
{
  z->state = ARCHIVE_CLOSED;
  z->input_data = NULL;
  z->data_size = 0;
  z->ptr = NULL;
  z->end = NULL;
}

/* Locate the ZIP central directory info */
static libspectrum_error
locate_directory_info( struct libspectrum_zip *z, zip_directory_info *info )
{
  libspectrum_error error;

  error = seek( z, -ZIP_DIRECTORY_INFO_SIZE, SEEK_END );
  if( error ) return error;

  /* Such a horrible mess just because of the stupid variable size comment at
     the end. Sigh. */
  while( z->ptr >= z->input_data ) {
    if( z->ptr[0] == 'P' &&
        z->ptr[1] == 'K' &&
        z->ptr[2] == 5  &&
        z->ptr[3] == 6 ) {
      error = read_directory_info( info, z->ptr, z->end );
      if( !error ) return LIBSPECTRUM_ERROR_NONE;
    }

    z->ptr--;
  }

  return LIBSPECTRUM_ERROR_CORRUPT;
}

/* Locate the ZIP central directory */
static libspectrum_error
locate_directory( struct libspectrum_zip *z )
{
  libspectrum_error error;
  zip_directory_info info;

  if( z->directory_offset != 0 ) {
    return LIBSPECTRUM_ERROR_NONE;
  }

  error = locate_directory_info( z, &info );
  if( error ) return error;

  if( info.disk_index != info.directory_disk_index ) {
    return LIBSPECTRUM_ERROR_CORRUPT;
  }

  z->directory_offset = info.directory_offset;
  z->file_count = MIN( info.disk_file_count, info.file_count );

  return LIBSPECTRUM_ERROR_NONE;
}

/* Get the number of entries in the archive (files and directories) */
unsigned int
libspectrum_zip_num_entries( struct libspectrum_zip *z )
{
  return z ? z->file_count : 0;
}

/* Rewind to beginning of ZIP directory */
libspectrum_error
libspectrum_zip_rewind( struct libspectrum_zip *z )
{
  libspectrum_error error;

  if( !z || z->state == ARCHIVE_CLOSED )
    return LIBSPECTRUM_ERROR_INVALID;

  error = seek( z, z->directory_offset, SEEK_SET );
  if( error ) return error;

  z->file_index = 0;
  z->state = ARCHIVE_OPEN;

  return LIBSPECTRUM_ERROR_NONE;
}

/* Read next entry in the ZIP central directory */
static int
read_directory( struct libspectrum_zip *z )
{
  int retry, retval;
  libspectrum_dword name_size, skip;

  do {
    retry = 0;

    /* Stop when we have read it all */
    if( z->file_index >= z->file_count ) {
      return 1;
    }
    z->file_index++;

    /* Read the info */
    retval = read_file_header( &z->file_info, z->ptr, z->end );
    if( !retval ) {
      return 1;
    } else {
      z->ptr += retval;
    }

    /* Verify the header */
    if( z->file_info.magic != ZIP_FILE_HEADER_SIG ) {
      return 1;
    }

    /* Unix file names are case sensitive, the rest is not (or I don't know) */
    z->file_ignore_case = ( ( z->file_info.creator_version >> 8 ) != 3 );

    /* Read the name, but skip files with too long names */
    skip = z->file_info.comment_size + z->file_info.extra_field_size;
    name_size = z->file_info.name_size;

    if( z->ptr + name_size > z->end ) {
      return 1;
    }

    if( name_size < sizeof( z->file_name ) ) {
      memcpy( z->file_name, z->ptr, name_size );
      z->file_name[ name_size ] = 0;
    } else {
      retry = 1;
    }

    skip += name_size;

    /* Skip to the next file header if necessary */
    if( skip > 0 && seek( z, skip, SEEK_CUR ) ) {
      return 1;
    }

  } while( retry );

  return 0;
}

/* Open a ZIP archive from memory */
struct libspectrum_zip *
libspectrum_zip_open( const libspectrum_byte *buffer, size_t length )
{
  struct libspectrum_zip *z;
  libspectrum_error error;

  if( !buffer || !length ) return NULL;

  z = libspectrum_new0( libspectrum_zip, 1 );
  z->input_data = buffer;
  z->ptr = buffer;
  z->end = buffer + length;
  z->data_size = length;
  z->state = ARCHIVE_OPEN;

  error = locate_directory( z );
  if( error ) {
    libspectrum_print_error( error, "Unrecognized ZIP archive" );

    libspectrum_zip_close( z );
    return NULL;
  }

  if( libspectrum_zip_rewind( z ) ) {
    libspectrum_zip_close( z );
    return NULL;
  }

  return z;
}

static void
dump_entry_stat( struct libspectrum_zip *z, zip_stat *info )
{
  char *slash;
  size_t length;

  strcpy( info->name, z->file_name );
  slash = strrchr( info->name, '/' );
  info->filename = slash ? slash + 1 : info->name;

  length = strlen( z->file_name );
  info->is_dir = ( z->file_name[ length - 1 ] == '/' ) ? 1 : 0;

  info->size = z->file_info.uncompressed_size;
  info->index = z->file_index -1;
}

/* Jump to next entry in the archive */
int
libspectrum_zip_next( struct libspectrum_zip *z, zip_stat *info )
{
  if( !z || z->state == ARCHIVE_CLOSED ) return 1;

  if( read_directory( z ) ) return 1;

  dump_entry_stat( z, info );

  return 0;
}

/* Locate a file in the archive (non-sequential acces) */
int
libspectrum_zip_locate( struct libspectrum_zip *z, const char *filename,
                        int flags, zip_stat *info )
{
  int ignore_dir, ignore_case;
  size_t length;

  if( !z || z->state == ARCHIVE_CLOSED ) {
    return -1;
  }

  if( !filename || strlen( filename ) == 0 ) return -1;

  if( libspectrum_zip_rewind( z ) ) {
    close_zip( z );
    return -1;
  }

  ignore_dir = flags & ZIPFLAG_NODIR;
  ignore_case = ( flags & ZIPFLAG_AUTOCASE ) ? z->file_ignore_case :
                                               ( flags & ZIPFLAG_NOCASE );

  while( read_directory( z ) == 0 ) {
    const char *fname, *slash;

    /* Ignore directories in path */
    fname = NULL;
    if( ignore_dir ) {
      slash = strrchr( z->file_name, '/' );
      fname = slash ? slash + 1 : z->file_name;
    } else {
      fname = z->file_name;
    }

    if( !fname || strlen( fname ) == 0 ) continue;

    /* Skip entry if it is a directory */
    length = strlen( fname );
    if( fname[ length - 1 ] == '/' ) continue;

    if( match_file_names( filename, fname, ignore_case ) ) {
      dump_entry_stat( z, info );
      return info->index;
    }
  }

  return -1;
}

/* Close ZIP archive */
void
libspectrum_zip_close( struct libspectrum_zip *z )
{
  if( z ) {
    close_zip( z );
    libspectrum_free( z );
  }
}

/* Prepare stream for reading from ZIP archive */
static libspectrum_error
prepare_stream( struct libspectrum_zip *z )
{
  zip_local_header header;
  int retval;
  libspectrum_dword skip;
  libspectrum_word version;
  libspectrum_error error;

  /* Seek to the local header and read it */
  error = seek( z, z->file_info.file_offset, SEEK_SET );
  if( error ) return error;

  retval = read_local_header( &header, z->ptr, z->end );
  if( !retval ) {
    return LIBSPECTRUM_ERROR_CORRUPT;
  } else {
    z->ptr += retval;
  }

  /* Verify the header */
  if( header.magic != ZIP_LOCAL_HEADER_SIG ) {
    return LIBSPECTRUM_ERROR_SIGNATURE;
  }

  version = header.required_version & 0xff;
  if( version > ZIP_SUPPORTED_VERSION ) {
    libspectrum_print_error( LIBSPECTRUM_ERROR_SIGNATURE,
                             "Unsupported ZIP version %u.%u", version / 10,
                             version % 10 );
    return LIBSPECTRUM_ERROR_SIGNATURE;
  }

  /* Skip the variable fields. Note that we don't bother with matching the rest
     against the central directory header. The local header version may be
     masked out anyway, so we rather use the central directory version as
     authorative. */
  skip = header.name_size + header.extra_field_size;

  error = seek( z, skip, SEEK_CUR );
  if( error ) return error;

  return LIBSPECTRUM_ERROR_NONE;
}

/* Decompress the zlib compressed data */
static libspectrum_error
decompress_stream( struct libspectrum_zip *z, libspectrum_byte **buffer,
                   size_t *buffer_size )
{
  libspectrum_error error;
  size_t file_compressed_left;

  /* Note that we take the sizes from central directory rather than
     the local header, as those may be 0 in case of non-seekable compressed
     streams */
  file_compressed_left = z->file_info.compressed_size;

  /* Nothing to do */
  if( file_compressed_left == 0 ) {
    return LIBSPECTRUM_ERROR_CORRUPT;
  }

  /* Bad archive? */
  if( z->ptr + file_compressed_left > z->end ) {
    return LIBSPECTRUM_ERROR_CORRUPT;
  }

  error = libspectrum_zip_inflate( z->ptr, file_compressed_left, buffer,
                                   buffer_size );
  if( error ) return error;

  z->ptr += file_compressed_left;

  return LIBSPECTRUM_ERROR_NONE;
}

/* Read file from ZIP archive */
libspectrum_error
libspectrum_zip_read( struct libspectrum_zip *z, libspectrum_byte **buffer,
                      size_t *size )
{
  const libspectrum_byte *last = z->ptr;
  libspectrum_error error;
  libspectrum_dword file_crc;
  libspectrum_word compression;

  error = prepare_stream( z );
  if( error ) {
    z->ptr = last;
    return error;
  }

  /* Report EOF when there is no more to read */
  *size = z->file_info.uncompressed_size;

  if( *size == 0 ) {
    return LIBSPECTRUM_ERROR_UNKNOWN;
  }

  /* Now read the data depending on the compression method used */
  compression = z->file_info.compression;

  switch( compression ) {

  case 0: /* store */
    if( z->ptr + *size > z->end ) return 1;
    *buffer = libspectrum_malloc( *size );
    memcpy( *buffer, z->ptr, *size );
    break;

  case 8: /* deflate */
    if( decompress_stream( z, buffer, size ) ) {
      libspectrum_print_error( LIBSPECTRUM_ERROR_CORRUPT,
                               "ZIP decompression failed" );
      z->ptr = last;
      return LIBSPECTRUM_ERROR_CORRUPT;
    }
    break;

  default:
    z->ptr = last;
    libspectrum_print_error( LIBSPECTRUM_ERROR_INVALID,
                             "Unsupported compression method %u", compression );
    return LIBSPECTRUM_ERROR_INVALID;
  }

  /* Restore position to allow reading next header in central directory */
  z->ptr = last;

  /* Update the CRC, and report an error when it doesn't match at end */
  file_crc = crc32( 0, *buffer, *size );

  if( file_crc != z->file_info.crc ) {
    libspectrum_print_error( LIBSPECTRUM_ERROR_CORRUPT, "ZIP CRC mismatch" );
    return LIBSPECTRUM_ERROR_CORRUPT;
  }

  return LIBSPECTRUM_ERROR_NONE;
}

/* Make 'best guesses' as to what to uncompress from the archive */
libspectrum_error
libspectrum_zip_blind_read( const libspectrum_byte *zipptr, size_t ziplength,
                            libspectrum_byte **outptr, size_t *outlength )
{
  struct libspectrum_zip *z;
  zip_stat info;
  libspectrum_error error;

  z = libspectrum_zip_open( zipptr, ziplength );
  if( !z ) return LIBSPECTRUM_ERROR_INVALID;

  while( libspectrum_zip_next( z, &info ) == 0 ) {
    libspectrum_id_t type;
    libspectrum_class_t class;

    /* Skip directories and empty files */
    if( !info.size ) continue;

    /* Try to identify the file by the filename */
    error = libspectrum_identify_file_raw( &type, info.filename, NULL, 0 );
    if( error ) continue;

    error = libspectrum_identify_class( &class, type );
    if( error ) continue;

    /* Skip files not likely to be loaded in a emulator */
    if( class != LIBSPECTRUM_CLASS_UNKNOWN &&
        class != LIBSPECTRUM_CLASS_COMPRESSED &&
        class != LIBSPECTRUM_CLASS_AUXILIARY ) {

      error = libspectrum_zip_read( z, outptr, outlength );
      libspectrum_zip_close( z );

      return error;
    }
  }

  libspectrum_zip_close( z );

  return LIBSPECTRUM_ERROR_UNKNOWN;
}


text:
<?php
namespace JCSGYK\AdminBundle\Form\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use Symfony\Component\Security\Core\SecurityContext;
use JCSGYK\AdminBundle\Services\DataStore;

class UserType extends AbstractType
{
    protected $ds;
    protected $security;

    /**
     * Save the Datastore for parameter retrieval
     *
     * @param \JCSGYK\AdminBundle\Services\DataStore $ds
     */
    public function __construct(DataStore $ds, SecurityContext $security_context)
    {
        $this->ds = $ds;
        $this->security = $security_context;
    }

    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'JCSGYK\AdminBundle\Entity\User',
        ));
    }
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        // check the company for enabled client-types
        $co = $this->ds->getCompany();

        $choices = $this->ds->getRoles();

        $role_map = $this->ds->getRoleMap();
        foreach ($role_map as $type => $role) {
            if (!$this->ds->companyHas($type)) {
                unset($choices[$role]);
            }
        }

        if ($this->security->isGranted('ROLE_SUPER_ADMIN')) {
            $choices['ROLE_SUPER_ADMIN'] = 'Superadmin';
        }

        $builder->add('firstname', 'text', ['label' => 'Keresztnév']);
        $builder->add('lastname', 'text', ['label' => 'Vezetéknév']);
        $builder->add('username', 'text', ['label' => 'Felhasználói név']);
        $builder->add('email', 'email', ['label' => 'E-Mail cím', 'required' => false]);
        $builder->add('roles', 'choice', [
            'label' => 'Jogosultságok',
            'choices' => $choices,
            'multiple'  => true,
            'expanded'  => true,
        ]);
        $builder->add('enabled', 'checkbox', ['label' => 'Aktív']);

        $builder->add('plainPassword', 'repeated', array(
            'type' => 'password',
            'first_options' => array('label' => 'Jelszó'),
            'second_options' => array('label' => 'Jelszó újra'),
            'invalid_message' => 'A nem egyezik a két jelszó',
        ));
    }

    public function getName()
    {
        return 'user';
    }
}

redpajama_set_name: RedPajamaGithub


text:
package com.github.mahui53541.multithread.t210;

public class PrintString implements Runnable{
	private boolean isContinuePrint=true;

	public boolean isContinuePrint() {
		return isContinuePrint;
	}

	public void setContinuePrint(boolean isContinuePrint) {
		this.isContinuePrint = isContinuePrint;
	}

	public void printStringMethod() {
		try {
			while(isContinuePrint) {
				System.out.println("run threadName="+Thread.currentThread().getName());
				Thread.sleep(1000);
			}
		} catch (Exception e) {
			// TODO: handle exception
		}
	}
	public static void main(String[] args) {
		PrintString ps=new PrintString();
		new Thread(ps).start();
		System.out.println("我要停止他!stopThread"+Thread.currentThread().getName());
		ps.setContinuePrint(false);

	}

	@Override
	public void run() {
		printStringMethod();
	}

}


text:
.error {
    color: red;
}

.error_message {
    color: black;
}

/* Note: No JSPs are currently using the error_tooltip class, that I could find. */
span.error_tooltip {
    position: relative;
    z-index: 24;
    color: red;
}

span.error_tooltip div {
    display: none;
}

span.error_tooltip:hover div {
    display: block;
    z-index: 99999;
    font-size: xx-small;
    overflow: auto;
    position: absolute;
    top: -2em;
    left: -5em;
    background-color: white;
    border-style: dashed;
    border-width: 2px;
    border-color: black;
    min-width: 10em;
    max-width: 40em;
    text-indent: 0em;
    margin: 0em;
    padding: 0.5em;
}


text:
/// <reference path="AtomForm.js" />

(function (baseType) {
    return classCreatorEx({
        name: "WebAtoms.AtomAutoPostForm",
        base: baseType,
        start: function () {
        },
        properties: {
            isBusy: false,
            postError: null
        },
        methods: {
            pushPost: function (n) {
                if (this._isBusy)
                    return;
                if (this._pushPostTimeout) {
                    clearTimeout(this._pushPostTimeout);
                }
                if (!n)
                    n = 1000;
                var _this = this;
                this._pushPostTimeout = setTimeout(function () {
                    WebAtoms.dispatcher.callLater(function () {
                        _this.onSubmit();
                    });
                }, n);
            },

            onSubmit: function () {

                this._pushPostTimeout = 0;

                // already submitted?
                if (this._isBusy)
                    return;

                // for all nested children...
                if (!this.isValid()) {
                    //alert("Invalid Form");
                    return;
                }

                var data = this.preparePostData();
                if (!data)
                    return;

                var str = JSON.stringify(AtomBinder.getClone(data));
                if (this._cachedData) {
                    if (str == this._cachedData)
                        return;
                }
                this._cachedData = str;

                var self = this;

                var url = AtomPromise.getUrl(this._postUrl);

                //data = AtomBinder.getClone(data);

                //this.invokeAjax(url, { type: "POST", data: data, success: self._success });
                var ap = AtomPromise.json(url, null, { type: "POST", data: data }).then(self._success);
                ap.failed(function () {
                    self._isBusy = false;
                    self._postError = ap.error.msg;
                    AtomBinder.refreshValue(self, "isBusy");
                    AtomBinder.refreshValue(self, "postError");
                });
                ap.showProgress(false);
                ap.showError(false);
                ap.invoke();
            },

            onCreated: function () {
                baseType.onCreated.apply(this, arguments);
                var data = this.preparePostData();
                if (!data)
                    return;
                this._cachedData = JSON.stringify(AtomBinder.getClone(data));
            },

            onSuccess: function (p) {

                baseType.onSuccess.apply(this, arguments);

                this._isBusy = false;
                AtomBinder.refreshValue(this, "isBusy");
            },

            onKeyUp: function (e) {

                this.pushPost();

                if (e.target && e.target.nodeName && /textarea/gi.test(e.target.nodeName))
                    return;
                if (e.keyCode == 13) {
                    this.onSubmit();
                }
            },

            init: function () {
                baseType.init.call(this);

                var _this = this;
                this.pushPostHandler = function () {
                    _this.pushPost(1000);
                };
                this.bindEvent(this._element, 'click', this.pushPostHandler);

                $(this._element).find('input,select,textarea').bind('change', null, this.pushPostHandler)
            }
        }
    });
})(WebAtoms.AtomForm.prototype);


text:
/**
 *
 */
package com.example.paypro.tasks;

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

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast;

import com.example.paypro.core.Config;
import com.example.paypro.data.User;
import com.example.paypro.dbhandler.UserHelper;
import com.example.paypro.gcm.RegisterGCM;
import com.example.paypro.manager.ApplicationManager;
import com.example.paypro.manager.JSONHandler;

/**
 * @author jintu
 *
 */
public class UserRegisterTask extends AsyncTask<User, Void, User> {

	private Context context;
	private ProgressDialog progressDialog;
	private Activity activity;

	public UserRegisterTask(Activity activity) {
		this.activity=activity;
		this.context = activity;
		this.progressDialog = new ProgressDialog(context);
		this.progressDialog.setCancelable(false);
		this.progressDialog.setMessage("Registering user");

	}

	@Override
	protected void onPreExecute() {
		super.onPreExecute();
		this.progressDialog.show();
	}

	@Override
	protected User doInBackground(User... params) {
		User user = params[0];
		// Creating HTTP client
		HttpClient httpClient = new DefaultHttpClient();
		// Creating HTTP Post
		HttpPost httpPost = new HttpPost(
			Config.URL + "/users.json");

		RegisterGCM gcm = new RegisterGCM(context);
		String regId = gcm.registerGCM();

		System.out.println("GCM REGISTERED::" + regId);

		// Building post parameters
		// key and value pair
		List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(1);
		nameValuePair.add(new BasicNameValuePair("[user][first_name]", user
			.getFirstName()));
		nameValuePair.add(new BasicNameValuePair("[user][last_name]", user
			.getLastName()));
		nameValuePair.add(new BasicNameValuePair("[user][email]", user
			.getEmail()));
		nameValuePair.add(new BasicNameValuePair("[user][contact_number]",
			user.getContactNumber()));
		nameValuePair.add(new BasicNameValuePair("[user][password]", user.getPassword()));
		nameValuePair.add(new BasicNameValuePair("[user][device_registration_id]", regId));

		// Url Encoding the POST parameters
		try {
			httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));
		} catch (UnsupportedEncodingException e) {
			// writing error to Log
			e.printStackTrace();
		}

		// Making HTTP Request
		try {
			HttpResponse response = httpClient.execute(httpPost);
			String result = EntityUtils.toString(response.getEntity());
			Log.d("Http Response:", result);
			JSONObject obj = new JSONObject(result);

			if (obj.get("status").equals("success")) {
				JSONObject userJson = new JSONObject(obj.get("user")
					.toString());
				Log.d("ID", userJson.toString());
				user.setId(userJson.getLong("id"));

				return user;

			} else {
				JSONObject errorJson = new JSONObject(obj.get("errors")
					.toString().toString());

			}

			Log.d("Created User", user.toString());

			// writing response to log
			Log.d("Http Response:", result);
		} catch (ClientProtocolException e) {
			// writing exception to log
			e.printStackTrace();
		} catch (IOException e) {
			// writing exception to log
			e.printStackTrace();

		} catch (JSONException e1) {
			e1.printStackTrace();
		}
		return null;
	}

	@Override
	protected void onPostExecute(final User user) {

		if (user != null) {

			String userJson = JSONHandler.getInstance().converToJSON(user);
			SharedPreferences userDetails =context
				.getSharedPreferences("user", Context.MODE_PRIVATE);
			Editor edit = userDetails.edit();
			edit.clear();
			edit.putString("user", userJson);
			edit.commit();
			ApplicationManager.getInstance().setUser(user);
			UserHelper uh = new UserHelper(context);
			uh.createUser(user);

			Toast.makeText(context, "Login details are saved..",
				Toast.LENGTH_LONG).show();
			if(progressDialog.isShowing())  {
				progressDialog.dismiss();
			}
		ContactPullerTask contactTask = new ContactPullerTask(activity);
			contactTask.execute();
		} else {
			if(progressDialog.isShowing())  {
				progressDialog.dismiss();
			}
			Toast.makeText(context, "Error", Toast.LENGTH_LONG)
				.show();
		}
	}
}


text:
<?xml version="1.0" encoding="UTF-8"?>

DOLOGEN 325 - acetaminophen and dexbrompheniramine maleate tablet
Kramer Novis

Disclaimer: Most OTC drugs are not reviewed and approved by FDA, however they may be marketed if they comply with applicable regulations and policies. FDA has not evaluated whether this product complies.

Drug Facts

Active Ingredients: Acetaminophen-325 mg, Dexbrompheniramine Maleate-1 mg

Pain Reliever, Fever Reducer, Antihistamine

Uses

Temporarily relieves:

• minor aches and pains associated with headache, the common cold,

muscular aches, backache and minor pain from arthritis

Purpose

• runny nose and reduces sneezing, itching of the nose or throat, and itchy,

watery eyes due to hay fever or other upper respiratory allergies

Warnings

Liver Warning: This product contains acetaminophen. The maximum daily dose of

this product is 10 tablets (3,250 mg) in 24 hours for adults or 5 tablets (1,625 mg) in 24

hours for children.

Severe liver damage may occur if

• adult takes more than 4,000 mg of acetaminophen in 24 hours

• child takes more than 5 doses in 24 hours, which is the maximum daily amount

• taken with other drugs containing acetaminophen

• adult has 3 or more alcoholic drinks every day while using this product

• Do not take this product, unless directed by a doctor, if you

• may cause excitability especially in children

have a breathing problem

such as emphysema or chronic bronchitis, or if you have glaucoma or difficulty in

urination due to enlargement of the prostate gland.

• Caution: May cause drowsiness; alcohol, sedatives, and tranquilizers may increase

the drowsiness effect. Avoid alcoholic beverages while taking this product. Use

caution when driving a motor vehicle or operating machinery. Do not take this product

if you are taking sedatives or tranquilizers, without first consulting your doctor. May

cause excitability especially in children.

Warnings (continued)

Do not use:

• with any other drug containing

acetaminophen (prescription or

nonprescription). If you are not sure whether

a drug contains acetaminophen, ask a doctor

or pharmacist.

• if you are allergic to acetaminophen or any of

the inactive ingredients in this product

Ask a doctor before use if the user has

• liver disease

Ask a doctor or pharmacist before use if the

user is taking the blood thinning drug warfarin

Stop use and ask a doctor if

• pain gets worse or lasts more than 10 days

in adults

• pain gets worse or lasts more than 5 days in

children under 12 years

• fever gets worse or lasts more than 3 days

• new symptoms occur

• redness or swelling is present

• nervousness, dizziness or sleeplessness occur

These could be signs of a serious condition

Inactive Ingredients: corn starch,

hydroxypropyl methylcellulose, microcrystalline

cellulose, polydextrose,

polyethylene

glycol, povidone, sodium starch glycolate,

and stearic acid

Adults and children 12 years of age and over, take 2

caplets every 4-6 hours, or as prescribed by physician.

Do not exceed 10 caplets in 24 hours. Do not use for

more than 10 days unless directed by a doctor. Children

6 to under 11 years of age, take 1 caplet every 4-6

hours, or as prescribed by physician. Do not exceed 5

caplets in 24 hours. Do not use for more than 5 days

unless directed by a doctor.

KEEP OUT OF

REACH OF CHILDREN. In case of overdose, get

medical help or contact a Poison Control Center

right away. Prompt medical attention is critical for

adults as well as for children even if you do not

notice any signs or symptoms.

If pregnant or breast-feeding baby, ask a

health professional before use

DOLOGEN 325

acetaminophen, dexbrompheniramine tablet

Product Information

Product Type
HUMAN OTC DRUG LABEL
Item Code (Source)
NDC:52083-482

Route of Administration
ORAL
DEA Schedule

Active Ingredient/Active Moiety

Ingredient Name
Basis of Strength
Strength

ACETAMINOPHEN (ACETAMINOPHEN)
ACETAMINOPHEN
325 mg

DEXBROMPHENIRAMINE MALEATE (DEXBROMPHENIRAMINE)
DEXBROMPHENIRAMINE MALEATE
1 mg

Inactive Ingredients

Ingredient Name
Strength

STARCH, CORN

HYPROMELLOSES

CELLULOSE, MICROCRYSTALLINE

POLYDEXTROSE

POLYETHYLENE GLYCOLS

POVIDONE K30

SODIUM STARCH GLYCOLATE TYPE A CORN

STEARIC ACID

Product Characteristics

Color
white (ivory white)
Score
no score

Shape
CAPSULE (D)
Size
14mm

Flavor

Imprint Code
D

Contains

Packaging

#
Item Code
Package Description
Marketing Start Date
Marketing End Date

1
NDC:52083-482-90
90  in 1 BOTTLE

Marketing Information

Marketing Category
Application Number or Monograph Citation
Marketing Start Date
Marketing End Date

OTC monograph final
part341
08/27/2014

Labeler - Kramer Novis
							(090158395)

Registrant - Kramer Novis (090158395)

Establishment

Name
Address
ID/FEI
Business Operations

ULTRAtab Laboratories, Inc.

151051757
manufacture(52083-482)

Establishment

Name
Address
ID/FEI
Business Operations

Ultra Seal Corporation

085752004
repack(52083-482)

Revised: 8/2014

Document Id: ce40013e-1cfd-43fb-9ddc-045b46f0e279

Set id: dad63da3-cd1f-42a8-93d5-44b39aae1268

Version: 1

Effective Time: 20140827

Kramer Novis


text:
FROM rustlang/rust:nightly

ADD ./ /rocket

WORKDIR /rocket

ENV ROCKET_ENV=production
ENV DATABASE_URL=postgres://benchmarkdbuser:benchmarkdbpass@tfb-database/hello_world

RUN cargo clean
RUN RUSTFLAGS="-C target-cpu=native" cargo build --release

CMD ./target/release/rocket


text:
#ifndef _BEAM_BP_H
#define _BEAM_BP_H

#include "sys.h"
#include "erl_vm.h"
#include "global.h"

typedef struct {
    Eterm pid;
    Sint  count;
    ErtsMonotonicTime time;
} bp_data_time_item_t;

typedef struct {
    Uint n;
    Uint used;
    bp_data_time_item_t *item;
} bp_time_hash_t;

typedef struct bp_data_time {     /* Call time */
    Uint n;
    bp_time_hash_t *hash;
    erts_smp_refc_t refc;
} BpDataTime;

typedef struct {
    ErtsMonotonicTime time;
    BeamInstr *pc;
} process_breakpoint_time_t; /* used within psd */

typedef struct {
    erts_smp_atomic_t acount;
    erts_smp_refc_t refc;
} BpCount;

typedef struct {
    erts_smp_atomic_t tracer;
    erts_smp_refc_t refc;
} BpMetaTracer;

typedef struct generic_bp_data {
    Uint flags;
    Binary* local_ms;		/* Match spec for local call trace */
    Binary* meta_ms;		/* Match spec for meta trace */
    BpMetaTracer* meta_tracer;	/* Meta tracer */
    BpCount* count;		/* For call count */
    BpDataTime* time;		/* For time trace */
} GenericBpData;

#define ERTS_NUM_BP_IX 2

typedef struct generic_bp {
    BeamInstr orig_instr;
    GenericBpData data[ERTS_NUM_BP_IX];
} GenericBp;

#define ERTS_BP_CALL_TIME_SCHEDULE_IN      (0)
#define ERTS_BP_CALL_TIME_SCHEDULE_OUT     (1)
#define ERTS_BP_CALL_TIME_SCHEDULE_EXITING (2)

#ifdef ERTS_DIRTY_SCHEDULERS
extern erts_smp_mtx_t erts_dirty_bp_ix_mtx;
#endif

enum erts_break_op{
    ERTS_BREAK_NOP   =  0, /* Must be false */
    ERTS_BREAK_SET   = !0, /* Must be true */
    ERTS_BREAK_RESTART,
    ERTS_BREAK_PAUSE
};

typedef Uint32 ErtsBpIndex;

typedef struct {
    BeamInstr* pc;
    Module* mod;
} BpFunction;

typedef struct {
    Uint matched;		/* Number matched */
    BpFunction* matching;	/* Matching functions */
} BpFunctions;

/*
** Function interface exported from beam_bp.c
*/

void erts_bp_init(void);

void erts_prepare_bp_staging(void);
void erts_commit_staged_bp(void);

ERTS_GLB_INLINE ErtsBpIndex erts_active_bp_ix(void);
ERTS_GLB_INLINE ErtsBpIndex erts_staging_bp_ix(void);

void erts_bp_match_functions(BpFunctions* f, Eterm mfa[3], int specified);
void erts_bp_match_export(BpFunctions* f, Eterm mfa[3], int specified);
void erts_bp_free_matched_functions(BpFunctions* f);

void erts_install_breakpoints(BpFunctions* f);
void erts_uninstall_breakpoints(BpFunctions* f);
void erts_consolidate_bp_data(BpFunctions* f, int local);
void erts_consolidate_bif_bp_data(void);

void erts_set_trace_break(BpFunctions *f, Binary *match_spec);
void erts_clear_trace_break(BpFunctions *f);

void erts_set_call_trace_bif(BeamInstr *pc, Binary *match_spec, int local);
void erts_clear_call_trace_bif(BeamInstr *pc, int local);

void erts_set_mtrace_break(BpFunctions *f, Binary *match_spec,
			  ErtsTracer tracer);
void erts_clear_mtrace_break(BpFunctions *f);
void erts_set_mtrace_bif(BeamInstr *pc, Binary *match_spec,
			 ErtsTracer tracer);
void erts_clear_mtrace_bif(BeamInstr *pc);

void erts_set_debug_break(BpFunctions *f);
void erts_clear_debug_break(BpFunctions *f);
void erts_set_count_break(BpFunctions *f, enum erts_break_op);
void erts_clear_count_break(BpFunctions *f);

void erts_clear_all_breaks(BpFunctions* f);
int erts_clear_module_break(Module *modp);
void erts_clear_export_break(Module *modp, BeamInstr* pc);

BeamInstr erts_generic_breakpoint(Process* c_p, BeamInstr* I, Eterm* reg);
BeamInstr erts_trace_break(Process *p, BeamInstr *pc, Eterm *args,
                           Uint32 *ret_flags, ErtsTracer *tracer);

int erts_is_trace_break(BeamInstr *pc, Binary **match_spec_ret, int local);
int erts_is_mtrace_break(BeamInstr *pc, Binary **match_spec_ret,
			 ErtsTracer *tracer_ret);
int erts_is_mtrace_bif(BeamInstr *pc, Binary **match_spec_ret,
		       ErtsTracer *tracer_ret);
int erts_is_native_break(BeamInstr *pc);
int erts_is_count_break(BeamInstr *pc, Uint *count_ret);
int erts_is_time_break(Process *p, BeamInstr *pc, Eterm *call_time);

void erts_trace_time_call(Process* c_p, BeamInstr* pc, BpDataTime* bdt);
void erts_trace_time_return(Process* c_p, BeamInstr* pc);
void erts_schedule_time_break(Process *p, Uint out);
void erts_set_time_break(BpFunctions *f, enum erts_break_op);
void erts_clear_time_break(BpFunctions *f);

int erts_is_time_trace_bif(Process *p, BeamInstr *pc, Eterm *call_time);
void erts_set_time_trace_bif(BeamInstr *pc, enum erts_break_op);
void erts_clear_time_trace_bif(BeamInstr *pc);

BeamInstr *erts_find_local_func(Eterm mfa[3]);

#if ERTS_GLB_INLINE_INCL_FUNC_DEF

extern erts_smp_atomic32_t erts_active_bp_index;
extern erts_smp_atomic32_t erts_staging_bp_index;

ERTS_GLB_INLINE ErtsBpIndex erts_active_bp_ix(void)
{
    return erts_smp_atomic32_read_nob(&erts_active_bp_index);
}

ERTS_GLB_INLINE ErtsBpIndex erts_staging_bp_ix(void)
{
    return erts_smp_atomic32_read_nob(&erts_staging_bp_index);
}
#endif

#endif /* _BEAM_BP_H */


text:
<?php

/*
 * This file is part of Sulu.
 *
 * (c) Sulu GmbH
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Sulu\Bundle\ArticleBundle\Exception;

/**
 * Thrown when parameter is not allowed.
 */
class ParameterNotAllowedException extends \Exception
{
    /**
     * @var string
     */
    private $property;

    /**
     * @var string
     */
    private $class;

    public function __construct(string $property, string $class)
    {
        parent::__construct(sprintf('Parameter "%s" is not allowed for class "%s".', $property, $class));

        $this->property = $property;
        $this->class = $class;
    }

    /**
     * Returns property.
     */
    public function getProperty(): string
    {
        return $this->property;
    }

    /**
     * Returns class.
     */
    public function getClass(): string
    {
        return $this->class;
    }
}


text:
package org.knowm.xchange.anx.v2.dto.account;

import static org.assertj.core.api.Assertions.assertThat;

import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.io.InputStream;
import org.junit.Test;

/** Test ANXDepositResponse JSON parsing */
public class DepositResponseJSONTest {

  @Test
  public void testUnmarshal() throws IOException {

    // Read in the JSON from the example resources
    InputStream is =
        DepositResponseJSONTest.class.getResourceAsStream(
            "/v2/account/example-deposit-response.json");

    // Use Jackson to parse it
    ObjectMapper mapper = new ObjectMapper();
    ANXBitcoinDepositAddress anxBitcoinDepositAddress =
        mapper.readValue(is, ANXBitcoinDepositAddress.class);

    System.out.println(anxBitcoinDepositAddress.toString());

    // Verify that the example data was unmarshalled correctly
    assertThat(anxBitcoinDepositAddress.getAddress())
        .isEqualTo("1GAUBau3nKQYJ1uvMWUfWCdEbMTJ1BXFjW");
  }
}


text:
package org.webbitserver.handler;

import static org.junit.Assert.assertEquals;
import static org.webbitserver.WebServers.createWebServer;
import static org.webbitserver.testutil.HttpClient.contents;
import static org.webbitserver.testutil.HttpClient.httpGet;

import java.util.concurrent.ExecutionException;

import org.junit.After;
import org.junit.Test;
import org.webbitserver.WebServer;

public class AliasHandlerTest {
    private WebServer webServer = createWebServer(59504);

    @After
    public void die() throws InterruptedException, ExecutionException {
        webServer.stop().get();
    }

    @Test
    public void forwardsAliasedPath() throws Exception {
        webServer
                .add("/tomayto", new AliasHandler("/tomato"))
                .add("/tomato", new StringHttpHandler("text/plain", "body"))
                .start()
                .get();
        assertEquals("body", contents(httpGet(webServer, "/tomayto")));
    }
}


text:
<?php

namespace Liip\ImagineBundle\Tests\Async;

use Enqueue\Bundle\EnqueueBundle;
use Enqueue\Client\ProducerInterface;
use Enqueue\Consumption\Result;
use Enqueue\Null\NullContext;
use Enqueue\Null\NullMessage;
use Liip\ImagineBundle\Async\CacheResolved;
use Liip\ImagineBundle\Async\Commands;
use Liip\ImagineBundle\Async\ResolveCacheProcessor;
use Liip\ImagineBundle\Async\Topics;
use Liip\ImagineBundle\Imagine\Filter\FilterConfiguration;
use Liip\ImagineBundle\Model\Binary;
use Liip\ImagineBundle\Tests\AbstractTest;

class ResolveCacheProcessorTest extends AbstractTest
{
    public static function setUpBeforeClass()
    {
        if (!class_exists(EnqueueBundle::class)) {
            self::markTestSkipped('The tests are run without enqueue integration. Skip them');
        }
    }

    public function testShouldImplementProcessorInterface()
    {
        $rc = new \ReflectionClass('Liip\ImagineBundle\Async\ResolveCacheProcessor');

        $this->assertTrue($rc->implementsInterface('Interop\Queue\PsrProcessor'));
    }

    public function testShouldImplementCommandSubscriberInterface()
    {
        $rc = new \ReflectionClass('Liip\ImagineBundle\Async\ResolveCacheProcessor');

        $this->assertTrue($rc->implementsInterface('Enqueue\Client\CommandSubscriberInterface'));
    }

    public function testShouldImplementQueueSubscriberInterface()
    {
        $rc = new \ReflectionClass('Liip\ImagineBundle\Async\ResolveCacheProcessor');

        $this->assertTrue($rc->implementsInterface('Enqueue\Consumption\QueueSubscriberInterface'));
    }

    public function testShouldSubscribeToExpectedCommand()
    {
        $command = ResolveCacheProcessor::getSubscribedCommand();

        $this->assertInternalType('array', $command);
        $this->assertEquals(array(
            'processorName' => Commands::RESOLVE_CACHE,
            'queueName' => Commands::RESOLVE_CACHE,
            'queueNameHardcoded' => true,
            'exclusive' => true,
        ), $command);
    }

    public function testShouldSubscribeToExpectedQueue()
    {
        $queues = ResolveCacheProcessor::getSubscribedQueues();

        $this->assertInternalType('array', $queues);
        $this->assertEquals(array('liip_imagine_resolve_cache'), $queues);
    }

    public function testCouldBeConstructedWithExpectedArguments()
    {
        new ResolveCacheProcessor(
            $this->createCacheManagerMock(),
            $this->createFilterManagerMock(),
            $this->createDataManagerMock(),
            $this->createProducerMock()
        );
    }

    public function testShouldRejectMessagesWithInvalidJsonBody()
    {
        $processor = new ResolveCacheProcessor(
            $this->createCacheManagerMock(),
            $this->createFilterManagerMock(),
            $this->createDataManagerMock(),
            $this->createProducerMock()
        );

        $message = new NullMessage();
        $message->setBody('[}');

        $result = $processor->process($message, new NullContext());

        $this->assertInstanceOf('Enqueue\Consumption\Result', $result);
        $this->assertEquals(Result::REJECT, $result->getStatus());
        $this->assertStringStartsWith('The malformed json given.', $result->getReason());
    }

    public function testShouldSendFailedReplyOnException()
    {
        $processor = new ResolveCacheProcessor(
            $this->createCacheManagerMock(),
            $this->createFilterManagerMock(),
            $this->createDataManagerMock(),
            $this->createProducerMock()
        );

        $message = new NullMessage();
        $message->setBody('[}');

        $result = $processor->process($message, new NullContext());

        $this->assertInstanceOf('Enqueue\Consumption\Result', $result);
        $this->assertInstanceOf('Interop\Queue\PsrMessage', $result->getReply());
        $this->assertEquals(
            array(
                "status" => false,
                "exception" => "The malformed json given. Error 2 and message State mismatch (invalid or malformed JSON)"
            ),
            json_decode($result->getReply()->getBody(), true)
        );
    }

    public function testShouldRejectMessagesWithoutPass()
    {
        $processor = new ResolveCacheProcessor(
            $this->createCacheManagerMock(),
            $this->createFilterManagerMock(),
            $this->createDataManagerMock(),
            $this->createProducerMock()
        );

        $message = new NullMessage();
        $message->setBody('{}');

        $result = $processor->process($message, new NullContext());

        $this->assertInstanceOf('Enqueue\Consumption\Result', $result);
        $this->assertEquals(Result::REJECT, (string) $result);
        $this->assertEquals('The message does not contain "path" but it is required.', $result->getReason());
    }

    public function testShouldResolveCacheIfNotStored()
    {
        $originalBinary = $this->createDummyBinary();
        $filteredBinary = $this->createDummyBinary();

        $filterManagerMock = $this->createFilterManagerMock();
        $filterManagerMock
            ->expects($this->once())
            ->method('getFilterConfiguration')
            ->willReturn(new FilterConfiguration(array(
                'fooFilter' => array('fooFilterConfig'),
            )))
        ;
        $filterManagerMock
            ->expects($this->once())
            ->method('applyFilter')
            ->with($this->identicalTo($originalBinary), 'fooFilter')
            ->willReturn($filteredBinary)
        ;

        $cacheManagerMock = $this->createCacheManagerMock();
        $cacheManagerMock
            ->expects($this->atLeastOnce())
            ->method('isStored')
            ->willReturn(false)
        ;
        $cacheManagerMock
            ->expects($this->once())
            ->method('store')
            ->with(
                $this->identicalTo($filteredBinary),
                'theImagePath',
                'fooFilter'
            )
        ;
        $cacheManagerMock
            ->expects($this->once())
            ->method('resolve')
            ->with('theImagePath', 'fooFilter')
        ;

        $dataManagerMock = $this->createDataManagerMock();
        $dataManagerMock
            ->expects($this->once())
            ->method('find')
            ->with('fooFilter', 'theImagePath')
            ->willReturn($originalBinary)
        ;

        $processor = new ResolveCacheProcessor(
            $cacheManagerMock,
            $filterManagerMock,
            $dataManagerMock,
            $this->createProducerMock()
        );

        $message = new NullMessage();
        $message->setBody('{"path": "theImagePath"}');

        $result = $processor->process($message, new NullContext());

        $this->assertInstanceOf('Enqueue\Consumption\Result', $result);
        $this->assertEquals(Result::ACK, (string) $result);
    }

    public function testShouldNotResolveCacheIfStoredAndNotForce()
    {
        $filterManagerMock = $this->createFilterManagerMock();
        $filterManagerMock
            ->expects($this->once())
            ->method('getFilterConfiguration')
            ->willReturn(new FilterConfiguration(array(
                'fooFilter' => array('fooFilterConfig'),
            )))
        ;
        $filterManagerMock
            ->expects($this->never())
            ->method('applyFilter')
        ;

        $cacheManagerMock = $this->createCacheManagerMock();
        $cacheManagerMock
            ->expects($this->atLeastOnce())
            ->method('isStored')
            ->willReturn(true)
        ;
        $cacheManagerMock
            ->expects($this->never())
            ->method('store')
        ;
        $cacheManagerMock
            ->expects($this->once())
            ->method('resolve')
            ->with('theImagePath', 'fooFilter')
            ->willReturn('fooFilterUri')
        ;

        $dataManagerMock = $this->createDataManagerMock();
        $dataManagerMock
            ->expects($this->never())
            ->method('find')
        ;

        $processor = new ResolveCacheProcessor(
            $cacheManagerMock,
            $filterManagerMock,
            $dataManagerMock,
            $this->createProducerMock()
        );

        $message = new NullMessage();
        $message->setBody('{"path": "theImagePath"}');

        $result = $processor->process($message, new NullContext());

        $this->assertInstanceOf('Enqueue\Consumption\Result', $result);
        $this->assertEquals(Result::ACK, (string) $result);
    }

    public function testShouldSendMessageOnSuccessResolve()
    {
        $filterManagerMock = $this->createFilterManagerMock();
        $filterManagerMock
            ->expects($this->once())
            ->method('getFilterConfiguration')
            ->willReturn(new FilterConfiguration(array(
                'fooFilter' => array('fooFilterConfig'),
                'barFilter' => array('barFilterConfig'),
                'bazFilter' => array('bazFilterConfig'),
            )))
        ;
        $filterManagerMock
            ->expects($this->atLeastOnce())
            ->method('applyFilter')
            ->willReturn($this->createDummyBinary())
        ;

        $cacheManagerMock = $this->createCacheManagerMock();
        $cacheManagerMock
            ->expects($this->atLeastOnce())
            ->method('isStored')
            ->willReturn(false)
        ;
        $cacheManagerMock
            ->expects($this->atLeastOnce())
            ->method('store')
        ;
        $cacheManagerMock
            ->expects($this->atLeastOnce())
            ->method('resolve')
            ->willReturnCallback(function ($path, $filter) {
                return $path.$filter.'Uri';
            })
        ;

        $dataManagerMock = $this->createDataManagerMock();
        $dataManagerMock
            ->expects($this->atLeastOnce())
            ->method('find')
            ->willReturn($this->createDummyBinary())
        ;

        $testCase = $this;
        $producerMock = $this->createProducerMock();
        $producerMock
            ->expects($this->once())
            ->method('sendEvent')
            ->with(Topics::CACHE_RESOLVED, $this->isInstanceOf('Liip\ImagineBundle\Async\CacheResolved'))
        ->willReturnCallback(function ($topic, CacheResolved $message) use ($testCase) {
            $testCase->assertEquals('theImagePath', $message->getPath());
            $testCase->assertEquals(array(
                'fooFilter' => 'theImagePathfooFilterUri',
                'barFilter' => 'theImagePathbarFilterUri',
                'bazFilter' => 'theImagePathbazFilterUri',
            ), $message->getUris());
        });

        $processor = new ResolveCacheProcessor(
            $cacheManagerMock,
            $filterManagerMock,
            $dataManagerMock,
            $producerMock
        );

        $message = new NullMessage();
        $message->setBody('{"path": "theImagePath"}');

        $result = $processor->process($message, new NullContext());

        $this->assertInstanceOf('Enqueue\Consumption\Result', $result);
        $this->assertEquals(Result::ACK, (string) $result);
    }

    public function testShouldReturnReplyOnSuccessResolve()
    {
        $filterManagerMock = $this->createFilterManagerMock();
        $filterManagerMock
            ->expects($this->once())
            ->method('getFilterConfiguration')
            ->willReturn(new FilterConfiguration(array(
                'fooFilter' => array('fooFilterConfig'),
                'barFilter' => array('barFilterConfig'),
                'bazFilter' => array('bazFilterConfig'),
            )))
        ;
        $filterManagerMock
            ->expects($this->atLeastOnce())
            ->method('applyFilter')
            ->willReturn($this->createDummyBinary())
        ;

        $cacheManagerMock = $this->createCacheManagerMock();
        $cacheManagerMock
            ->expects($this->atLeastOnce())
            ->method('isStored')
            ->willReturn(false)
        ;
        $cacheManagerMock
            ->expects($this->atLeastOnce())
            ->method('store')
        ;
        $cacheManagerMock
            ->expects($this->atLeastOnce())
            ->method('resolve')
            ->willReturnCallback(function ($path, $filter) {
                return $path.$filter.'Uri';
            })
        ;

        $dataManagerMock = $this->createDataManagerMock();
        $dataManagerMock
            ->expects($this->atLeastOnce())
            ->method('find')
            ->willReturn($this->createDummyBinary())
        ;

        $processor = new ResolveCacheProcessor(
            $cacheManagerMock,
            $filterManagerMock,
            $dataManagerMock,
            $this->createProducerMock()
        );

        $message = new NullMessage();
        $message->setBody('{"path": "theImagePath"}');

        $result = $processor->process($message, new NullContext());

        $this->assertInstanceOf('Enqueue\Consumption\Result', $result);
        $this->assertInstanceOf('Interop\Queue\PsrMessage', $result->getReply());
        $this->assertEquals(
            array(
                "status" => true,
                "results" => array(
                    'fooFilter' => 'theImagePathfooFilterUri',
                    'barFilter' => 'theImagePathbarFilterUri',
                    'bazFilter' => 'theImagePathbazFilterUri',
                )
            ),
            json_decode($result->getReply()->getBody(), true)
        );
    }

    /**
     * @return \PHPUnit_Framework_MockObject_MockObject|ProducerInterface
     */
    private function createProducerMock()
    {
        return $this->createMock(ProducerInterface::class);
    }

    /**
     * @return Binary
     */
    private function createDummyBinary()
    {
        return new Binary('theContent', 'image/png', 'png');
    }
}


text: lessc ../widgets.less >built.css


text:
/**
 */
package org.afplib.afplib;

import org.afplib.base.Triplet;

/**
 *
 * A representation of the model object 'GCHST'.
 *
 *
 *

 * The following features are supported:
 *

 *

 *
{@link org.afplib.afplib.GCHST#getXPOS XPOS}

 *
{@link org.afplib.afplib.GCHST#getYPOS YPOS}

 *
{@link org.afplib.afplib.GCHST#getCP CP}

 *

 *
 * @see org.afplib.afplib.AfplibPackage#getGCHST()
 * @model
 * @generated
 */
public interface GCHST extends Triplet {
	/**
	 * Returns the value of the 'XPOS' attribute.
	 *
	 *
	 *
	 *
mandatory
fixed length

	 *
	 * @return the value of the 'XPOS' attribute.
	 * @see #setXPOS(Integer)
	 * @see org.afplib.afplib.AfplibPackage#getGCHST_XPOS()
	 * @model required="true"
	 * @generated
	 */
	Integer getXPOS();

	/**
	 * Sets the value of the '{@link org.afplib.afplib.GCHST#getXPOS XPOS}' attribute.
	 *
	 *
	 * @param value the new value of the 'XPOS' attribute.
	 * @see #getXPOS()
	 * @generated
	 */
	void setXPOS(Integer value);

	/**
	 * Returns the value of the 'YPOS' attribute.
	 *
	 *
	 *
	 *
mandatory
fixed length

	 *
	 * @return the value of the 'YPOS' attribute.
	 * @see #setYPOS(Integer)
	 * @see org.afplib.afplib.AfplibPackage#getGCHST_YPOS()
	 * @model required="true"
	 * @generated
	 */
	Integer getYPOS();

	/**
	 * Sets the value of the '{@link org.afplib.afplib.GCHST#getYPOS YPOS}' attribute.
	 *
	 *
	 * @param value the new value of the 'YPOS' attribute.
	 * @see #getYPOS()
	 * @generated
	 */
	void setYPOS(Integer value);

	/**
	 * Returns the value of the 'CP' attribute.
	 *
	 *
	 *
	 *
mandatory
variable length

	 *
	 * @return the value of the 'CP' attribute.
	 * @see #setCP(String)
	 * @see org.afplib.afplib.AfplibPackage#getGCHST_CP()
	 * @model dataType="org.afplib.base.ModcaString" required="true"
	 * @generated
	 */
	String getCP();

	/**
	 * Sets the value of the '{@link org.afplib.afplib.GCHST#getCP CP}' attribute.
	 *
	 *
	 * @param value the new value of the 'CP' attribute.
	 * @see #getCP()
	 * @generated
	 */
	void setCP(String value);

} // GCHST


text:
define("dojox/geo/charting/Map", [
	"dojo/_base/lang",
	"dojo/_base/array",
	"dojo/_base/declare",
	"dojo/_base/html",
	"dojo/dom",
	"dojo/dom-geometry",
	"dojo/dom-class",
	"dojo/_base/xhr",
	"dojo/_base/connect",
	"dojo/_base/window",
	"dojox/gfx",
	"./_base",
	"./Feature",
	"./_Marker",
	"dojo/number",
	"dojo/_base/sniff"
], function(lang, arr, declare, html, dom, domGeom, domClass, xhr, connect, win, gfx, base, Feature, Marker, number, has){

	return declare("dojox.geo.charting.Map", null, {
		// summary:
		//		Map widget interacted with charting.
		// description:
		//		Support rendering Americas, AsiaPacific, ContinentalEurope, EuropeMiddleEastAfrica,
		//		USStates, WorldCountries, and WorldCountriesMercator by default.
		// example:
		//	|	var usaMap = new dojox.geo.charting.Map(srcNode, "dojotoolkit/dojox/geo/charting/resources/data/USStates.json");
		//	|

		// defaultColor: String
		//		Default map feature color, e.g: "#B7B7B7"
		defaultColor:"#B7B7B7",
		// highlightColor: String
		//		Map feature color when mouse over it, e.g: "#"
		highlightColor:"#D5D5D5",
		// series: Array
		//		stack to data range, e.g: [{name:'label 1', min:20, max:70, color:'#DDDDDD'},{...},...]
		series:[],

		dataBindingAttribute:null,
		dataBindingValueFunction:null,
		dataStore:null,
		showTooltips: true,
		enableFeatureZoom: true,
		colorAnimationDuration:0,
		_idAttributes:null,
		_onSetListener:null,
		_onNewListener:null,
		_onDeleteListener:null,
		constructor: function(/*Node*/container, /*String|Object*/shapeData){
			// summary:
			//		Constructs a new Map instance.
			// container:
			//		map container html node/id.
			// shapeData:
			//		map shape data json object, or url to json file.

			html.style(container, "display", "block");

			this.container = container;
			var containerBounds = this._getContainerBounds();
			// get map container coords
			this.surface = gfx.createSurface(container, containerBounds.w, containerBounds.h);

			this._createZoomingCursor();

			// add transparent background for event capture
			this.mapBackground = this.surface.createRect({x: 0, y: 0, width: containerBounds.w, height: containerBounds.w}).setFill("rgba(0,0,0,0)");

			this.mapObj = this.surface.createGroup();
			this.mapObj.features = {};

			if(typeof shapeData == "object"){
				this._init(shapeData);
			}else{
				// load map shape file
				if(typeof shapeData == "string" && shapeData.length > 0){
					xhr.get({
						url: shapeData,
						handleAs: "json",
						sync: true,
						load: lang.hitch(this, "_init")
					});
				}
			}
		},

		_getContainerBounds: function(){
			// summary:
			//		returns the bounds {x:, y:, w: ,h:} of the DOM node container in absolute coordinates
			// tags:
			//		private

			var position = domGeom.position(this.container,true);
			var marginBox = domGeom.getMarginBox(this.container);
			// use contentBox for correct width and height - surface spans outside border otherwise
			var contentBox = domGeom.getContentBox(this.container);
			this._storedContainerBounds = {
					x: position.x,
					y: position.y,
					w: contentBox.w || 100,
					h: contentBox.h || 100
				};
			return this._storedContainerBounds;
		},

		resize: function(/**boolean**/ adjustMapCenter, /**boolean**/ adjustMapScale, /**boolean**/ animate){
			// summary:
			//		resize the underlying GFX surface to accommodate to parent DOM Node size change
			// adjustMapCenter: boolean
			//		keeps the center of the map when resizing the surface
			// adjustMapScale: boolean
			//		adjusts the map scale to keep the visible portion of the map as much as possible

			var oldBounds = this._storedContainerBounds;
			var newBounds = this._getContainerBounds();

			if((oldBounds.w == newBounds.w) && (oldBounds.h == newBounds.h)){
				return;
			}

			// set surface dimensions, and background
			this.mapBackground.setShape({width:newBounds.w, height:newBounds.h});
			this.surface.setDimensions(newBounds.w,newBounds.h);

			this.mapObj.marker.hide();
			this.mapObj.marker._needTooltipRefresh = true;

			if(adjustMapCenter){

				var mapScale = this.getMapScale();
				var newScale = mapScale;

				if(adjustMapScale){
					var bbox = this.mapObj.boundBox;
					var widthFactor = newBounds.w / oldBounds.w;
					var heightFactor = newBounds.h / oldBounds.h;
					newScale = mapScale * Math.sqrt(widthFactor * heightFactor);
				}

				//	current map center
				var invariantMapPoint = this.screenCoordsToMapCoords(oldBounds.w/2,oldBounds.h/2);

				//	apply new parameters
				this.setMapCenterAndScale(invariantMapPoint.x,invariantMapPoint.y,newScale,animate);
			}
		},

		_isMobileDevice: function(){
			// summary:
			//		tests whether the application is running on a mobile device (android or iOS)
			// tags:
			//		private
			return (has("safari")
					&& (navigator.userAgent.indexOf("iPhone") > -1 ||
						navigator.userAgent.indexOf("iPod") > -1 ||
						navigator.userAgent.indexOf("iPad") > -1
					)) || (navigator.userAgent.toLowerCase().indexOf("android") > -1);
		},

		setMarkerData: function(/*String*/ markerFile){
			// summary:
			//		import markers from outside file, associate with map feature by feature id
			//		which identified in map shape file, e.g: "NY":"New York"
			// markerFile:
			//		outside marker data url, handled as json style.
			//		data format: {"NY":"New York",.....}
			xhr.get({
				url: markerFile,
				handleAs: "json",
				handle: lang.hitch(this, "_appendMarker")
			});
		},

		setDataBindingAttribute: function(/*String*/prop){
			// summary:
			//		sets the property name of the dataStore items to use as value (see Feature.setValue function)
			// prop: String
			//		the property
			this.dataBindingAttribute = prop;

			// refresh data
			if(this.dataStore){
				this._queryDataStore();
			}
		},

		setDataBindingValueFunction: function(/* function */valueFunction){
			// summary:
			//		sets the function that extracts values from dataStore items,to use as Feature values (see Feature.setValue function)
			// valueFunction:
			//		the function
			this.dataBindingValueFunction = valueFunction;

			// refresh data
			if(this.dataStore){
				this._queryDataStore();
			}
		},

		_queryDataStore: function(){
			if(!this.dataBindingAttribute || (this.dataBindingAttribute.length == 0)){
				return;
			}

			var mapInstance = this;
			this.dataStore.fetch({
				scope: this,
				onComplete: function(items){
					this._idAttributes = mapInstance.dataStore.getIdentityAttributes({});
					arr.forEach(items, function(item){
						var id = mapInstance.dataStore.getValue(item, this._idAttributes[0]);
						if(mapInstance.mapObj.features[id]){
							var val = null;
							var itemVal = mapInstance.dataStore.getValue(item, mapInstance.dataBindingAttribute);
							if(itemVal){
								if(this.dataBindingValueFunction){
									val = this.dataBindingValueFunction(itemVal);
								}else{
									if(isNaN(val)){
										// regular parse
										val=number.parse(itemVal);
									}else{
										val = itemVal;
									}
								}
							}
							if(val){
								mapInstance.mapObj.features[id].setValue(val);
							}
						}
					},this);
				}
			});
		},

		_onSet:function(item,attribute,oldValue,newValue){
			// look for matching feature
			var id = this.dataStore.getValue(item, this._idAttributes[0]);
			var feature = this.mapObj.features[id];
			if(feature && (attribute == this.dataBindingAttribute)){
				if(newValue){
					feature.setValue(newValue);
				}else{
					feature.unsetValue();
				}
			}
		},

		_onNew:function(newItem,  parentItem){
			var id = this.dataStore.getValue(item, this._idAttributes[0]);
			var feature = this.mapObj.features[id];
			if(feature && (attribute == this.dataBindingAttribute)){
				feature.setValue(newValue);
			}
		},

		_onDelete:function(item){
			var id = item[this._idAttributes[0]];
			var feature = this.mapObj.features[id];
			if(feature){
				feature.unsetValue();
			}
		},

		setDataStore: function(/*dojo/data/ItemFileReadStore*/ dataStore, /*String*/ dataBindingProp){
			// summary:
			//		populate data for each map feature from fetched data store
			// dataStore: dojo/data/ItemFileReadStore
			//		the dataStore to fetch the information from
			// dataBindingProp:
			//		sets the property name of the dataStore items to use as value
			if(this.dataStore != dataStore){
				// disconnect previous listener if any
				if(this._onSetListener){
					connect.disconnect(this._onSetListener);
					connect.disconnect(this._onNewListener);
					connect.disconnect(this._onDeleteListener);
				}

				// set new dataStore
				this.dataStore = dataStore;

				// install listener on new dataStore
				if(dataStore){
					_onSetListener = connect.connect(this.dataStore,"onSet",this,this._onSet);
					_onNewListener = connect.connect(this.dataStore,"onNew",this,this._onNew);
					_onDeleteListener = connect.connect(this.dataStore,"onDelete",this,this._onDelete);
				}
			}
			if(dataBindingProp){
				this.setDataBindingAttribute(dataBindingProp);
			}
		},

		addSeries: function(/*url|Object[]*/ series){
			// summary:
			//		sets ranges of data values (associated with label, color) to style map data values
			// series:
			//		Either an url or an array of range objects such as : [{name:'label 1', min:20, max:70, color:'#DDDDDD'},{...},...]

			if(typeof series == "object"){
				this._addSeriesImpl(series);
			}else{
				// load series file
				if(typeof series == "string" && series.length > 0){
					xhr.get({
						url: series,
						handleAs: "json",
						sync: true,
						load: lang.hitch(this, function(content){
							this._addSeriesImpl(content.series);
						})
					});
				}
			}

		},

		_addSeriesImpl: function(/*Object[]*/series){

			this.series = series;

			// refresh color scheme
			for(var item in this.mapObj.features){
				var feature = this.mapObj.features[item];
				feature.setValue(feature.value);
			}
		},

		fitToMapArea: function(mapArea, pixelMargin, animate, onAnimationEnd){
			// summary:
			//		set this component's transformation so that the specified area fits in the component (centered)
			// mapArea: Object
			//		the map area that needs to fill the component expressed as {x,y,w,h}
			// pixelMargin: int
			//		a margin (in pixels) from the borders of the Map component.
			// animate: boolean
			//		true if the transform change should be animated
			// onAnimationEnd: function
			//		a callback function to be executed when the animation completes (if animate set to true).

			if(!pixelMargin){
				pixelMargin = 0;
			}
			var width = mapArea.w,
				height = mapArea.h,
				containerBounds = this._getContainerBounds(),
				scale = Math.min((containerBounds.w - 2 * pixelMargin) / width,
								(containerBounds.h - 2 * pixelMargin) / height);

			this.setMapCenterAndScale(mapArea.x + mapArea.w / 2,mapArea.y + mapArea.h / 2,scale,animate,onAnimationEnd);
		},

		fitToMapContents: function(pixelMargin,animate,/* callback function */onAnimationEnd){
			// summary:
			//		set this component's transformation so that the whole map data fits in the component (centered)
			// pixelMargin: int
			//		a margin (in pixels) from the borders of the Map component.
			// animate: boolean
			//		true if the transform change should be animated
			// onAnimationEnd: function
			//		a callback function to be executed when the animation completes (if animate set to true).

			//transform map to fit container
			var bbox = this.mapObj.boundBox;
			this.fitToMapArea(bbox,pixelMargin,animate,onAnimationEnd);
		},

		setMapCenter: function(centerX,centerY,animate,/* callback function */onAnimationEnd){
			// summary:
			//		set this component's transformation so that the map is centered on the specified map coordinates
			// centerX: float
			//		the X coordinate (in map coordinates) of the new center
			// centerY: float
			//		the Y coordinate (in map coordinates) of the new center
			// animate: boolean
			//		true if the transform change should be animated
			// onAnimationEnd: function
			//		a callback function to be executed when the animation completes (if animate set to true).

			// call setMapCenterAndScale with current map scale
			var currentScale = this.getMapScale();
			this.setMapCenterAndScale(centerX,centerY,currentScale,animate,onAnimationEnd);

		},

		_createAnimation: function(onShape,fromTransform,toTransform,/* callback function */onAnimationEnd){
			// summary:
			//		creates a transform animation object (between two transforms) used internally
			// onShape: dojox.gfx.shape.Shape
			//		The target shape.
			// fromTransform: dojox.gfx.matrix.Matrix2D
			//		the start transformation (when animation begins)
			// toTransform: dojox.gfx.matrix.Matrix2D
			//		the end transormation (when animation ends)
			// onAnimationEnd: function
			//		callback function to be executed when the animation completes.
			var fromDx = fromTransform.dx?fromTransform.dx:0;
			var fromDy = fromTransform.dy?fromTransform.dy:0;
			var toDx = toTransform.dx?toTransform.dx:0;
			var toDy = toTransform.dy?toTransform.dy:0;
			var fromScale = fromTransform.xx?fromTransform.xx:1.0;
			var toScale = toTransform.xx?toTransform.xx:1.0;

			var anim = gfx.fx.animateTransform({
				duration: 1000,
				shape: onShape,
				transform: [{
					name: "translate",
					start: [fromDx,fromDy],
					end: [toDx,toDy]
				},
				{
					name: "scale",
					start: [fromScale],
					end: [toScale]
				}
				]
			});

			//install callback
			if(onAnimationEnd){
				var listener = connect.connect(anim,"onEnd",this,function(event){
					onAnimationEnd(event);
					connect.disconnect(listener);
				});
			}

			return anim;
		},

		setMapCenterAndScale: function(centerX,centerY,scale, animate,/* callback function */onAnimationEnd){

			// summary:
			//		set this component's transformation so that the map is centered on the specified map coordinates
			//		and scaled to the specified scale.
			// centerX: float
			//		the X coordinate (in map coordinates) of the new center
			// centerY: float
			//		the Y coordinate (in map coordinates) of the new center
			// scale: float
			//		the scale of the map
			// animate: boolean
			//		true if the transform change should be animated
			// onAnimationEnd: function
			//		a callback function to be executed when the animation completes (if animate set to true).

			// compute matrix parameters
			var bbox = this.mapObj.boundBox;
			var containerBounds = this._getContainerBounds();
			var offsetX = containerBounds.w/2 - scale * (centerX - bbox.x);
			var offsetY = containerBounds.h/2 - scale * (centerY - bbox.y);
			var newTransform = new gfx.matrix.Matrix2D({xx: scale, yy: scale, dx:offsetX, dy:offsetY});

			var currentTransform = this.mapObj.getTransform();

			// can animate only if specified AND curentTransform exists
			if(!animate || !currentTransform){
				this.mapObj.setTransform(newTransform);
			}else{
				var anim = this._createAnimation(this.mapObj,currentTransform,newTransform,onAnimationEnd);
				anim.play();
			}
		},

		getMapCenter: function(){
			// summary:
			//		returns the map coordinates of the center of this Map component.
			// returns: point
			//		the center in map coordinates
			var containerBounds = this._getContainerBounds();
			return this.screenCoordsToMapCoords(containerBounds.w/2,containerBounds.h/2); // point
		},

		setMapScale: function(scale,animate,/* callback function */onAnimationEnd){
			// summary:
			//		set this component's transformation so that the map is scaled to the specified scale.
			// scale: Number
			//		the scale ratio.
			// animate: boolean
			//		true if the transform change should be animated
			// onAnimationEnd: function
			//		a callback function to be executed when the animation completes (if animate set to true).

			// default invariant is map center
			var containerBounds = this._getContainerBounds();
			var invariantMapPoint = this.screenCoordsToMapCoords(containerBounds.w/2,containerBounds.h/2);
			this.setMapScaleAt(scale,invariantMapPoint.x,invariantMapPoint.y,animate,onAnimationEnd);
		},

		setMapScaleAt: function(scale,fixedMapX,fixedMapY,animate,/* callback function */onAnimationEnd){
			// summary:
			//		set this component's transformation so that the map is scaled to the specified scale, and the specified
			//		point (in map coordinates) stays fixed on this Map component
			// scale: Number
			//		the scale ratio.
			// fixedMapX: float
			//		the X coordinate (in map coordinates) of the fixed screen point
			// fixedMapY: float
			//		the Y coordinate (in map coordinates) of the fixed screen point
			// animate: boolean
			//		true if the transform change should be animated
			// onAnimationEnd: function
			//		a callback function to be executed when the animation completes (if animate set to true).

			var invariantMapPoint = null;
			var invariantScreenPoint = null;

			invariantMapPoint = {x: fixedMapX, y: fixedMapY};
			invariantScreenPoint = this.mapCoordsToScreenCoords(invariantMapPoint.x,invariantMapPoint.y);

			// compute matrix parameters
			var bbox = this.mapObj.boundBox;
			var offsetX = invariantScreenPoint.x - scale * (invariantMapPoint.x - bbox.x);
			var offsetY = invariantScreenPoint.y - scale * (invariantMapPoint.y - bbox.y);
			var newTransform = new gfx.matrix.Matrix2D({xx: scale, yy: scale, dx:offsetX, dy:offsetY});

			var currentTransform = this.mapObj.getTransform();

			// can animate only if specified AND curentTransform exists
			if(!animate || !currentTransform){
				this.mapObj.setTransform(newTransform);
			}else{
				var anim = this._createAnimation(this.mapObj,currentTransform,newTransform,onAnimationEnd);
				anim.play();
			}
		},

		getMapScale: function(){
			// summary:
			//		returns the scale of this Map component.
			// returns: float
			//		the scale
			var mat = this.mapObj.getTransform();
			var scale = mat?mat.xx:1.0;
			return scale; // Number
		},

		mapCoordsToScreenCoords: function(mapX,mapY){
			// summary:
			//		converts map coordinates to screen coordinates given the current transform of this Map component
			// mapX: Number
			//		the x coordinate of the point to convert.
			// mapY: Number
			//		the y coordinate of the point to convert.
			// returns: {x:,y:}
			//		the screen coordinates correspondig to the specified map coordinates.
			var matrix = this.mapObj.getTransform();
			var screenPoint = gfx.matrix.multiplyPoint(matrix, mapX, mapY);
			return screenPoint; // point
		},

		screenCoordsToMapCoords: function(screenX, screenY){
			// summary:
			//		converts screen coordinates to map coordinates given the current transform of this Map component
			// screenX: Number
			//		the x coordinate of the point to convert.
			// screenY: Number
			//		the y coordinate of the point to convert.
			// returns:
			//		the map coordinates corresponding to the specified screen coordinates.
			var invMatrix = gfx.matrix.invert(this.mapObj.getTransform());
			var mapPoint = gfx.matrix.multiplyPoint(invMatrix, screenX, screenY);
			return mapPoint; // point
		},
		deselectAll: function(){
			// summary:
			//		deselect all features of map
			for(var name in this.mapObj.features){
				this.mapObj.features[name].select(false);
			}
			this.selectedFeature = null;
			this.focused = false;
		},

		_init: function(shapeData){
			// summary:
			//		inits this Map component.

			//transform map to fit container
			this.mapObj.boundBox = {x: shapeData.layerExtent[0],
									y: shapeData.layerExtent[1],
									w: (shapeData.layerExtent[2] - shapeData.layerExtent[0]),
									h: shapeData.layerExtent[3] - shapeData.layerExtent[1]};
			this.fitToMapContents(3);

			//	if there are "features", then implement them now.
			arr.forEach(shapeData.featureNames, function(item){
				var featureShape = shapeData.features[item];
				featureShape.bbox.x = featureShape.bbox[0];
				featureShape.bbox.y = featureShape.bbox[1];
				featureShape.bbox.w = featureShape.bbox[2];
				featureShape.bbox.h = featureShape.bbox[3];
				var feature = new Feature(this, item, featureShape);
				feature.init();
				this.mapObj.features[item] = feature;
			}, this);

			//	set up a marker.
			this.mapObj.marker = new Marker({}, this);
		},
		_appendMarker: function(markerData){
			this.mapObj.marker = new Marker(markerData, this);
		},
		_createZoomingCursor: function(){
			if(!dom.byId("mapZoomCursor")){
				var mapZoomCursor = win.doc.createElement("div");
				html.attr(mapZoomCursor,"id","mapZoomCursor");
				domClass.add(mapZoomCursor,"mapZoomIn");
				html.style(mapZoomCursor,"display","none");
				win.body().appendChild(mapZoomCursor);
			}
		},
		onFeatureClick: function(feature){
			// summary:
			//		Invoked when the specified feature is clicked.
			// feature: dojox.geo.charting.Feature
			//		A Feature.
			// tags:
			//		callback
		},
		onFeatureOver: function(feature){
			// summary:
			//		Invoked when the specified feature is hovered.
			// feature: dojox.geo.charting.Feature
			//		A Feature.
			// tags:
			//		callback
		},
		onZoomEnd:function(feature){
			// summary:
			//		Invoked when the specified feature has been zoomed.
			// feature: dojox.geo.charting.Feature
			//		A Feature.
			// tags:
			//		callback
		}
	});
});


text: require 'asset_version'


text:
package com.alibaba.jstorm.task.execute;

import backtype.storm.task.ICollectorCallback;
import backtype.storm.tuple.MessageId;
import backtype.storm.tuple.Tuple;
import backtype.storm.tuple.TupleImplExt;

import com.alibaba.jstorm.common.metric.AsmGauge;
import com.alibaba.jstorm.metric.*;
import com.alibaba.jstorm.task.Task;
import com.alibaba.jstorm.task.acker.Acker;
import com.alibaba.jstorm.utils.JStormUtils;
import com.alibaba.jstorm.utils.Pair;
import com.alibaba.jstorm.utils.RotatingMap;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;

/**
 * @author xiaojian.fxj
 * @since 2.1.1
 */
public class BoltBatchCollector extends BoltCollector {
    private static Logger LOG = LoggerFactory.getLogger(BoltBatchCollector.class);
    private BatchCollector batchCollector;
    private int batchSize;
    private CallIntervalGauge timeIntervalGauge;

    private final RotatingMap<Tuple, Integer> pendingTuples = new RotatingMap<Tuple, Integer>(Acker.TIMEOUT_BUCKET_NUM, true);
    private final BlockingQueue<Tuple> pendingAcks = new LinkedBlockingQueue<Tuple>();

    private class BoltMsgInfo extends MsgInfo {
        public Collection<Tuple> anchors;

        public BoltMsgInfo(String streamId, List<Object> values, Collection<Tuple> anchors, Integer outTaskId, ICollectorCallback callback) {
            super(streamId, values, outTaskId, callback);
            this.anchors = anchors;
        }
    }

    private final Map<Integer, Map<String, List<Object>>> pendingSendMsgs = new HashMap<Integer, Map<String, List<Object>>>();

    public BoltBatchCollector(Task task, RotatingMap<Tuple, Long> tuple_start_times, int message_timeout_secs) {
        super(task, tuple_start_times, message_timeout_secs);

        String componentId = topologyContext.getThisComponentId();

        timeIntervalGauge = new CallIntervalGauge();
        JStormMetrics.registerTaskMetric(MetricUtils.taskMetricName(task.getTopologyId(), componentId, task.getTaskId(), MetricDef.TASK_BATCH_INTERVAL_TIME, MetricType.GAUGE),
                new AsmGauge(timeIntervalGauge));

        batchCollector = new BatchCollector(task_id, componentId, storm_conf) {
            public void pushAndSend(String streamId, List<Object> tuple, Integer outTaskId, Collection<Tuple> anchors, Object messageId, Long rootId,
                                      ICollectorCallback callback) {
                if (anchors != null && ackerNum > 0) {
                    synchronized (pendingTuples) {
                        for (Tuple a : anchors) {
                            Integer pendingCount = pendingTuples.get(a);
                            if (pendingCount == null) {
                                pendingCount = 0;
                            }
                            pendingTuples.put(a, ++pendingCount);
                        }
                    }
                }

                if (outTaskId != null) {
                    synchronized (directBatches) {
                        List<MsgInfo> batchTobeFlushed = addToBatches(outTaskId.toString() + "-" + streamId,
                                directBatches, streamId, tuple, outTaskId, anchors, batchSize, callback);
                        if (batchTobeFlushed != null && batchTobeFlushed.size() > 0) {
                            timeIntervalGauge.incrementAndGet();
                            sendBatch(streamId, (outTaskId != null ? outTaskId.toString() : null), batchTobeFlushed, false);
                        }
                    }
                } else {
                    synchronized (streamToBatches) {
                        List<MsgInfo> batchTobeFlushed = addToBatches(streamId, streamToBatches, streamId, tuple, outTaskId, anchors, batchSize, callback);
                        if (batchTobeFlushed != null && batchTobeFlushed.size() > 0) {
                            timeIntervalGauge.incrementAndGet();
                            sendBatch(streamId, (outTaskId != null ? outTaskId.toString() : null), batchTobeFlushed, false);
                        }
                    }
                }
            }

            public synchronized void flush() {
                synchronized (streamToBatches) {
                    for (Map.Entry<String, List<MsgInfo>> entry : streamToBatches.entrySet()) {
                        List<MsgInfo> batch = streamToBatches.put(entry.getKey(), null);
                        if (batch != null && batch.size() > 0) {
                            sendBatch(entry.getKey(), null, batch, true);
                        }
                    }
                }

                synchronized (directBatches) {
                    for (Map.Entry<String, List<MsgInfo>> entry : directBatches.entrySet()) {
                        List<MsgInfo> batch = directBatches.put(entry.getKey(), null);
                        if (batch != null && batch.size() > 0) {
                            // taskId-StreamId --> [taskId, streamId]
                            String[] strings = entry.getKey().split("-", 2);
                            sendBatch(strings[1], strings[0], batch, true);
                        }
                    }
                }

                processPendingAcks();
            }

            private void processPendingAcks() {
                int size = pendingAcks.size();
                while (--size >= 0) {
                    Tuple ackTuple = pendingAcks.poll();
                    if (ackTuple != null && sendAckTuple(ackTuple) == false) {
                        try {
                           pendingAcks.put(ackTuple);
                        } catch (InterruptedException e) {
                           LOG.warn("Failed to put ackTuple, tuple=" + ackTuple, e);
                        }
                    }
                }
            }
        };

        batchSize = batchCollector.getConfigBatchSize();
    }

    @Override
    protected List<Integer> sendBoltMsg(String outStreamId, Collection<Tuple> anchors, List<Object> values, Integer outTaskId, ICollectorCallback callback) {

        batchCollector.pushAndSend(outStreamId, values, outTaskId, anchors, null, null, callback);
        return null;
    }

    private List<MsgInfo> addToBatches(String key, Map<String, List<MsgInfo>> batches, String streamId, List<Object> tuple, Integer outTaskId,
                                       Collection<Tuple> anchors, int batchSize, ICollectorCallback callback) {
        List<MsgInfo> batch = batches.get(key);
        if (batch == null) {
            batch = new ArrayList<MsgInfo>();
            batches.put(key, batch);
        }
        batch.add(new BoltMsgInfo(streamId, tuple, anchors, outTaskId, callback));
        if (batch.size() > batchSize) {
            List<MsgInfo> ret = batch;
            batches.put(key, null);
            return ret;
        } else {
            return null;
        }
    }

    /**
     * @return if size of pending batch is bigger than the configured one, return the batch for sending, otherwise, return null
     */
    private List<Object> addToPendingSendBatch(int targetTask, String streamId, List<Object> values) {
    	Map<String, List<Object>> streamToBatch = pendingSendMsgs.get(targetTask);
    	if (streamToBatch == null) {
    		streamToBatch = new HashMap<String, List<Object>>();
    		pendingSendMsgs.put(targetTask, streamToBatch);

    	}

        List<Object> batch = streamToBatch.get(streamId);
        if (batch == null) {
        	batch = new ArrayList<Object>();
        	streamToBatch.put(streamId, batch);
        }

        batch.addAll(values);
        if (batch.size() >= batchSize) {
        	return batch;
        } else {
        	return null;
        }
    }

    public List<Integer> sendBatch(String outStreamId, String outTaskId, List<MsgInfo> batchTobeFlushed, boolean isFlush) {
        final long start = emitTimer.getTime();
        try {
            Map<Object, List<MsgInfo>> outTasks = null;

            if (outTaskId != null) {
                outTasks = sendTargets.getBatch(Integer.valueOf(outTaskId), outStreamId, batchTobeFlushed);
            } else {
                outTasks = sendTargets.getBatch(outStreamId, batchTobeFlushed);
            }

            if (outTasks == null || outTasks.size() == 0) {

            } else {
                for (Map.Entry<Object, List<MsgInfo>> entry : outTasks.entrySet()) {
                    Object target = entry.getKey();
                    List<Integer> tasks = (target instanceof Integer) ? JStormUtils.mk_list((Integer) target) : ((List<Integer>) target);
                    List<MsgInfo> batch = entry.getValue();

                    for (Integer t : tasks) {
                    	List<Object> batchValues = new ArrayList<Object>();
                    	for (MsgInfo msg : batch) {
                    		BoltMsgInfo msgInfo = (BoltMsgInfo) msg;
                    		Pair<MessageId, List<Object>> pair = new Pair<MessageId, List<Object>>(getMessageId(msgInfo.anchors), msgInfo.values);
                    		batchValues.add(pair);
                    	}

                        TupleImplExt batchTuple = new TupleImplExt(topologyContext, batchValues, task_id, outStreamId, null);
                        batchTuple.setTargetTaskId(t);
                        batchTuple.setBatchTuple(true);
                        taskTransfer.transfer(batchTuple);
                    }

                    for (MsgInfo msg : batch) {
                        if (msg.callback != null) {
                            msg.callback.execute(outStreamId, tasks, msg.values);
                        }
                    }
                }
            }

            for (MsgInfo msg : batchTobeFlushed) {
                Collection<Tuple> anchors = ((BoltMsgInfo) msg).anchors;
                if (anchors != null && anchors.size() > 0) {
                    for (Tuple a : anchors) {
                        synchronized (pendingTuples) {
                            Integer pendingCount = pendingTuples.get(a);
                            if (pendingCount != null) {
                                if (--pendingCount <= 0) {
                                    pendingTuples.remove(a);
                                } else {
                                    pendingTuples.put(a, pendingCount);
                                }
                            }
                        }
                    }
                }
            }

            return null;
        } catch (Exception e) {
            LOG.error("bolt emit", e);
        } finally {
            emitTimer.updateTime(start);
        }
        return new ArrayList<Integer>();
    }

    @Override
    public void ack(Tuple input) {
        if (input.getMessageId() != null) {
            if (!sendAckTuple(input)) {
                pendingAcks.add(input);
            }
        }

        Long latencyStart = (Long) tuple_start_times.remove(input);
        task_stats.bolt_acked_tuple(input.getSourceComponent(), input.getSourceStreamId());
        if (latencyStart != null && JStormMetrics.enabled) {
            long endTime = System.currentTimeMillis();
            task_stats.update_bolt_acked_latency(input.getSourceComponent(), input.getSourceStreamId(), latencyStart, endTime);
        }
    }

    @Override
    public void fail(Tuple input) {
        // if ackerNum == 0, we can just return
        if (input.getMessageId() != null) {
            pending_acks.remove(input);
            for (Map.Entry<Long, Long> e : input.getMessageId().getAnchorsToIds().entrySet()) {
                List<Object> ackTuple = JStormUtils.mk_list((Object) e.getKey());
                sendBoltMsg(Acker.ACKER_FAIL_STREAM_ID, null, ackTuple, null, null);
            }
        }

        task_stats.bolt_failed_tuple(input.getSourceComponent(), input.getSourceStreamId());
    }

    @Override
    protected MessageId getMessageId(Collection<Tuple> anchors) {
        MessageId ret = null;
        if (anchors != null) {
            Map<Long, Long> anchors_to_ids = new HashMap<Long, Long>();
            long now = System.currentTimeMillis();
            if (now - lastRotate > rotateTime) {
                pending_acks.rotate();
                synchronized (pendingTuples) {
                    pendingTuples.rotate();
                }
                lastRotate = now;
            }
            for (Tuple a : anchors) {
                // Long edge_id = MessageId.generateId();
                Long edge_id = MessageId.generateId(random);
                synchronized (pending_acks) {
                    put_xor(pending_acks, a, edge_id);
                }
                MessageId messageId = a.getMessageId();
                if (messageId != null){
                    for (Long root_id : messageId.getAnchorsToIds().keySet()) {
                        put_xor(anchors_to_ids, root_id, edge_id);
                    }
                }
            }
            ret = MessageId.makeId(anchors_to_ids);
        }
        return ret;
    }

    private boolean sendAckTuple(Tuple input) {
        boolean ret = false;
        Integer pendingCount;
        synchronized (pendingTuples) {
            pendingCount = pendingTuples.get(input);
        }
        if (pendingCount == null || pendingCount <= 0) {
            long ack_val = 0L;
            Object pend_val = pending_acks.remove(input);
            if (pend_val != null) {
                ack_val = (Long) (pend_val);
            }
            MessageId messageId = input.getMessageId();
            if (messageId != null){
                for (Map.Entry<Long, Long> e : messageId.getAnchorsToIds().entrySet()) {
                    List<Object> ackTuple = JStormUtils.mk_list((Object) e.getKey(), JStormUtils.bit_xor(e.getValue(), ack_val));
                    sendBoltMsg(Acker.ACKER_ACK_STREAM_ID, null, ackTuple, null, null);
                }
            }
            ret = true;
        }

        return ret;
    }

    @Override
    public void flush() {
        batchCollector.flush();
    }
}


text:
elm-webmidi-ports
=================
[![Build Status](https://travis-ci.org/newlandsvalley/elm-webmidi-ports.svg?branch=master)](https://travis-ci.org/newlandsvalley/elm-webmidi-ports)

This is an Elm 0.18 pseudo-library for [Web-MIDI](http://www.w3.org/TR/webmidi/).  It started life as an almost direct translation from [elm-webmidi](https://github.com/newlandsvalley/elm-webmidi) (elm 0.16) which was deprecated a year or so ago because it made heavy use of signals which suddenly vanished from the language.  The analogue of signals in Elm 0.18 is subscriptions which act through ports.  However, one downside of ports is that their use precludes publication in the Elm package repository.

This version has one advantage over its predecessor - MIDI Event messages are now properly parsed using the [elm-comidi](https://github.com/newlandsvalley/elm-comidi) parser which means that the full range of such messages is now supported.

The only processing that is done on the message stream is to recognise volume control messages and thus to save to state the current maximum volume.  This allows programs that use the module to respond to the volume control as notes are played.

You will need to attach a MIDI device to your computer to see any effect from Web-MIDI. At the time of writing, Chrome has the best support. Recent versions of Opera and Firefox support it but playback seems unresponsive. Other browsers will fail to initialise or fail to respond (say) to key presses on a MIDI keyboard.

To build, run __make__ and browse to __webmidi.html__

Testing
-------

This project has been tested using an M-Audio KeystationMini32 keyboard.

Examples
--------

cd to the examples directory to see the sample programs.

(Examples have a dependency on elm-soundfont-ports which uses native code and which consequently is debarred from publication on http://package.elm-lang.org/. As a workaround, the elm code is reproduced in the SoundFont of the examples.)

### Basic

[Basic.elm](https://github.com/newlandsvalley/elm-webmidi-ports/blob/master/examples/src/basic/Basic.elm) is functionally identical to WebMidi.elm.  It simply illustrates how you might embed the WebMidi module inside a larger program (but in this case this program does nothing else).

### Piano

[Piano.elm](https://github.com/newlandsvalley/elm-webmidi-ports/blob/master/examples/src/piano/Piano.elm) allows you to plug in your MIDI keyboard or other MIDI device and play it as a piano. It works simply by loading the piano soundfont which is served as a local resource, initialising web-midi and requesting that any NoteOn events should be played through the soundfont.

### Send

[Send.elm](https://github.com/newlandsvalley/elm-webmidi-ports/blob/master/examples/src/send/Send.elm) allows you to send MIDI note on and off messages to any connected MIDI device.

### Pick an Instrument

[MidiInstrument.elm](https://github.com/newlandsvalley/elm-webmidi-ports/tree/master/examples/src/midiInstrument/MidiInstrument.elm) allows you to plug in your MIDI keyboard or other MIDI device and to choose the instrumental sound it makes. In this case, the soundfonts are loaded directly from Benjamin Gleitzman's github package of [pre-rendered sound fonts](https://github.com/gleitz/midi-js-soundfonts). These may take a little longer to load.

To build, invoke __compilemi.sh__ and browse to __midiInstrument.html__.

Limitations
-----------

At the moment, no attempt is made to discriminate between channels.  i.e. it is intended for use when only a single MIDI device is plugged in.  Also, no attempt is made to respond to NoteOff messages.  Each note is allowed to 'ring' for its natural duration, which will depend on the type of instrument being emulated by the soundfont.

Suggestions for Further Work
----------------------------

This would be the basis of an ideal component for anyone wishing to write a web-audio synthesiser in elm which might respond to a larger selection of control messages.

Dependencies
------------

      elm-lang/core 5.1.1
      elm-lang/html 2.0.0
      newlandsvalley/elm-comidi 2.2.0

Contributing
------------
Travis CI enforces that all code is formatted with elm-format.

To do this:
1. `npm install -g elm-format`
2. `make format`


text:
'use strict';
var UIElements = function() {

	var staticPopoverHandler = function() {
		var radioPopover = $("input[name='popoverType']");
		radioPopover.first().prop('checked', true);
		radioPopover.change(function() {
			$("#static-popover > .popover").removeAttr('class').attr('class', 'popover ' + $(this).val());
		});
	};
	var animatedProgressbarHandler = function() {
		$(".active-progressbar").on("click", function() {
			$(".progress-animated .progress-bar").each(function() {
				var _this = $(this);
				_this.progressbar({
					display_text: _this.data("display-text"),
					use_percentage: _this.data("use-percentage"),
					transition_delay: _this.data("transition-delay")
				});
			});
		});
		$(".reset-progressbar").on("click", function() {
			$(".progress-animated .progress-bar").each(function() {
				var _this = $(this);
				var _tempData = _this.data('transitiongoal');
				_this.attr('data-transitiongoal', 0).progressbar().attr('data-transitiongoal', _tempData);

			});
		});
	};
	var paginationHandler = function() {
		$("#pagination-demo").twbsPagination({
			totalPages: 35,
			visiblePages: 7,
			onPageClick: function(event, page) {
				$("#page-content").text('Page ' + page);
			}
		});
		$("#pagination-demo-2").twbsPagination({
			totalPages: 35,
			visiblePages: 8,
			href: '#page={{number}}',
			onPageClick: function(event, page) {
				$("#page-content-2").text('Page ' + page);
			}
		});
		$(".pagination-demo-3").twbsPagination({
			totalPages: 35,
			visiblePages: 10,
			onPageClick: function(event, page) {
				$("#page-content-3").text('Page ' + page);
			}
		});
	};
	var ratingHandler = function() {

		$('.rating, .rating-tooltip').each(function() {
			$(this).val() > 0 ? $(this).next(".label").show().text($(this).val() || ' ') : $(this).next(".label").hide();
		});
		$('.rating-tooltip').rating({
			extendSymbol: function(rate) {
				$(this).tooltip({
					container: 'body',
					placement: 'bottom',
					title: 'Rate ' + rate
				});
			}
		});
		$('.rating, .rating-tooltip').on('change', function() {
			$(this).next('.label').show().text($(this).val());
		});
	};
	return {
		init: function() {
			staticPopoverHandler();
			animatedProgressbarHandler();
			paginationHandler();
			ratingHandler();
		}
	};
}();