text:
#include "ogr_mysql.h"
#include "cpl_conv.h"
#include "cpl_multiproc.h"

CPL_CVSID("$Id: ogrmysqldriver.cpp 29019 2015-04-25 20:34:19Z rouault $");

static CPLMutex* hMutex = NULL;
static int   bInitialized = FALSE;

/************************************************************************/
/*                        OGRMySQLDriverUnload()                        */
/************************************************************************/

static void OGRMySQLDriverUnload( CPL_UNUSED GDALDriver* poDriver )
{
    if( bInitialized )
    {
        mysql_library_end();
        bInitialized = FALSE;
    }
    if( hMutex != NULL )
    {
        CPLDestroyMutex(hMutex);
        hMutex = NULL;
    }
}

/************************************************************************/
/*                         OGRMySQLDriverIdentify()                     */
/************************************************************************/

static int OGRMySQLDriverIdentify( GDALOpenInfo* poOpenInfo )

{
    return EQUALN(poOpenInfo->pszFilename,"MYSQL:",6);
}

/************************************************************************/
/*                                Open()                                */
/************************************************************************/

static GDALDataset *OGRMySQLDriverOpen( GDALOpenInfo* poOpenInfo )

{
    OGRMySQLDataSource     *poDS;

    if( !OGRMySQLDriverIdentify(poOpenInfo) )
        return NULL;

    {
        CPLMutexHolderD(&hMutex);
        if( !bInitialized )
        {
            if ( mysql_library_init( 0, NULL, NULL ) )
            {
                CPLError( CE_Failure, CPLE_AppDefined, "Could not initialize MySQL library" );
                return NULL;
            }
            bInitialized = TRUE;
        }
    }

    poDS = new OGRMySQLDataSource();

    if( !poDS->Open( poOpenInfo->pszFilename, poOpenInfo->papszOpenOptions,
                     poOpenInfo->eAccess == GA_Update ) )
    {
        delete poDS;
        return NULL;
    }
    else
        return poDS;
}

/************************************************************************/
/*                               Create()                               */
/************************************************************************/

static GDALDataset *OGRMySQLDriverCreate( const char * pszName,
                                          CPL_UNUSED int nBands,
                                          CPL_UNUSED int nXSize,
                                          CPL_UNUSED int nYSize,
                                          CPL_UNUSED GDALDataType eDT,
                                          CPL_UNUSED char **papszOptions )
{
    OGRMySQLDataSource     *poDS;

    poDS = new OGRMySQLDataSource();

    if( !poDS->Open( pszName, NULL, TRUE ) )
    {
        delete poDS;
        CPLError( CE_Failure, CPLE_AppDefined,
         "MySQL driver doesn't currently support database creation.\n"
                  "Please create database before using." );
        return NULL;
    }

    return poDS;
}

/************************************************************************/
/*                          RegisterOGRMySQL()                          */
/************************************************************************/

void RegisterOGRMySQL()

{
    if (! GDAL_CHECK_VERSION("MySQL driver"))
        return;

    GDALDriver  *poDriver;

    if( GDALGetDriverByName( "MySQL" ) == NULL )
    {
        poDriver = new GDALDriver();

        poDriver->SetDescription( "MySQL" );
        poDriver->SetMetadataItem( GDAL_DCAP_VECTOR, "YES" );
        poDriver->SetMetadataItem( GDAL_DMD_LONGNAME,
                                   "MySQL" );
        poDriver->SetMetadataItem( GDAL_DMD_HELPTOPIC,
                                   "drv_mysql.html" );

        poDriver->SetMetadataItem( GDAL_DMD_CONNECTION_PREFIX, "MYSQL:" );

        poDriver->SetMetadataItem( GDAL_DMD_OPENOPTIONLIST,
"<OpenOptionList>"
"  <Option name='DBNAME' type='string' description='Database name' required='true'/>"
"  <Option name='PORT' type='int' description='Port'/>"
"  <Option name='USER' type='string' description='User name'/>"
"  <Option name='PASSWORD' type='string' description='Password'/>"
"  <Option name='HOST' type='string' description='Server hostname'/>"
"  <Option name='TABLES' type='string' description='Restricted set of tables to list (comma separated)'/>"
"</OpenOptionList>");

        poDriver->SetMetadataItem( GDAL_DMD_CREATIONOPTIONLIST, "<CreationOptionList/>");

        poDriver->SetMetadataItem( GDAL_DS_LAYER_CREATIONOPTIONLIST,
    "<LayerCreationOptionList>"
    "  <Option name='OVERWRITE' type='boolean' description='Whether to overwrite an existing table with the layer name to be created' default='NO'/>"
    "  <Option name='LAUNDER' type='boolean' description='Whether layer and field names will be laundered' default='YES'/>"
    "  <Option name='PRECISION' type='boolean' description='Whether fields created should keep the width and precision' default='YES'/>"
    "  <Option name='GEOMETRY_NAME' type='string' description='Name of geometry column.' default='SHAPE'/>"
    "  <Option name='SPATIAL_INDEX' type='boolean' description='Whether to create a spatial index' default='YES'/>"
    "  <Option name='FID' type='string' description='Name of the FID column to create' default='OGR_FID' deprecated_alias='MYSQL_FID'/>"
    "  <Option name='FID64' type='boolean' description='Whether to create the FID column with BIGINT type to handle 64bit wide ids' default='NO'/>"
    "  <Option name='ENGINE' type='string' description='Database engine to use.'/>"
    "</LayerCreationOptionList>");

        poDriver->SetMetadataItem( GDAL_DMD_CREATIONFIELDDATATYPES, "Integer Integer64 Real String Date DateTime Time Binary" );
        poDriver->SetMetadataItem( GDAL_DCAP_NOTNULL_FIELDS, "YES" );
        poDriver->SetMetadataItem( GDAL_DCAP_DEFAULT_FIELDS, "YES" );

        poDriver->pfnOpen = OGRMySQLDriverOpen;
        poDriver->pfnIdentify = OGRMySQLDriverIdentify;
        poDriver->pfnCreate = OGRMySQLDriverCreate;
        poDriver->pfnUnloadDriver = OGRMySQLDriverUnload;

        GetGDALDriverManager()->RegisterDriver( poDriver );
    }
}


text:
{% extends "album.html" %}
{% block layout %}
{% include "fragments/album_layout_select.html" %}
{% endblock %}

{% block album %}

    {% for hash in items[:3] %}

            {{ render_media(hash, album=True) | safe }}

    {% endfor %}

{% endblock %}

redpajama_set_name: RedPajamaGithub


text:
Without [Nick Sutterer](https://github.com/apotonick) and fine folks who contribute to [Trailblazer, Cells, Reform, Roar,
etc](http://trailblazer.to/)  - none of this would be possible. So - THANK YOU!

### Purpose and General comments

This started as a way to document my steps setting up a new Rails 5 project with Traiblazer 2.0. This isn't meant to be an authoritative document - but I did poke brains of some of smart people on the TRB support channel on gitter as I was working on this.

I would suggest in general to avoid all the extra baggage provided by Rails if you are not going to use it: sprockets, js, trubolinks, spring, etc. You could use --api flag as well. Having said that, this app was setup with everything in place. I only specified my DB of choice - MariaDB/MySQL. But you can use whatever you prefer - I highly recommend to match your production.

## Just get to it already
If you want to - you can just clone the repo and pick up from where I left off, and refer to this Readme and TRB docs as a guide. Keep reading on if you want to get some "best practices" tips as discussed on the Gitter channel, and how everything fits togeather.

## Initial Setup
**Warning 1:** You need to use Ruby 2.2 ~ 2.3 . There are currently problems with Rails 5 with TRB on Ruby 2.4 yet because of the Bignum/ Fixnum change and changes to Forwardable. As well as some other common non-trb gems  don't work yet. There is a .ruby-version file in the root of the project, that indicated which version of ruby to be used by rbenv, if you use it. It's locked to 2.3.4 , but you can try it with other versions.

**Warning 2:** If you are going to have loading problems - 50% of problems with loading stuff in Rails + TRB can be traced to Spring and/or Rails autoloading. If you disable spring from the getgo, you may save yourself some headaches. TRB inspired tests, run very fast without spring. But there are some brave souls, who have been using Spring with success. The other 50% of loading problems usually end up being incorrectly namespaced Concepts - Cells, Operations, Contracts, etc.

**Warning 3:** This is more or less accurate and working as of July 2017. TRB is developing very quickly, and some stuff may change. I will try to lock relevant gems in Gemfile to a specific version.

**Warning 4:** Gems are locked to specific versions to ensure

### Console

Suggested (once you are comfortable with TRB):
```shell
    rails new trailblazer-rails-basic-setup --skip-turbolinks
                                            --skip-sprockets
                                            --skip-puma
                                            --database=mysql
```
Actual (used in this setup):
```shell
      rails new trailblazer-rails-basic-setup --database=mysql
```

### Database:
Don't forget to setup test & dev DBs and setup user/pass in database.yml

### Update Gemfile

```ruby
    # Trailblazer
    gem "trailblazer", '2.0.6'
    gem "trailblazer-rails"

    # If you want to replace ActionView with the awesomeness of Cells
    # Otherwise what are you doing here? ;-)
    gem "trailblazer-cells"

    # There are adapters for ERB, Slim & Haml as well. Hamlit is faster than both.
    # If you are planing on using fancy form building with Simple Form or Formtastic - use Slim or Haml or ERB.
    # Also there is Formular form builder, developed by TRB team. Check it out, it's pretty awesome.
    # Hamlit right now has a small bug, that's being worked on. I prefer to build my UI using React,
    # so it's not really an issue, as I don't generate forms forms dynamically.
    # If you find that hamlit doesn't work you can always switch-back to Haml, they are interchangable/.
    gem "cells-hamlit"
    gem 'hamlit-rail'

    # For validation. You could stick with ActiveModel validations, but dry.rb stuff is better IMHO
    gem "dry-validation"

    # Add minitest to test / development. You are welcome to use rspec.
    gem 'minitest'
```
Disable stuff in Gemfile you won't need. For instance I run my stuff under passenger both in dev and production - there is no need to load Puma
(an excelent webserver otherwise)

Most gems are locked up to minor version, so that you can have a good working known setup. You can update gems as needed.

### application.rb
Some defaults in config/application.rb
```ruby
    config.time_zone = 'Central Time (US & Canada)'

    config.generators do |g|
      # Hamlit uses haml name where possible, so it should be a drop-in replacement in most cases
      g.template_engine :haml
      g.test_framework :minitest, spec: true, fixture: false
    end

    # Up to you. You may want to set it up later or use sidekiq or something else.
    config.active_job.queue_adapter = :delayed_job

```

# Getting Home page up and running

Let's give our domain logic a place and also setup a root controller called Home, place for Layouts, and a root route

Create this folder / file structure
```
-- app
---- concepts
------ home
-------- cell
---------- index.rb
-------- view
---------- index.haml
-------- layout
```

```shell
rails g controller home
```

```ruby
# routes.rb
  root 'home#index'
```

## Run pending migrations
```shell
# Since you are getting a proejct that was already setup, it will run several sample migrations,
# that were actually setup later. These are models such as Song, Album, Cover, Artist.
# You can simply remove them - they are there just to serve as an example.
# If you don't create these tables now, Rails server won't bootup, complaining of pending migrations.
rake db:migrate

# If you want just to bootup server and look at home page you can also change this setting, and boot up without running migrations

 # in config/environments/development.rb
 config.active_record.migration_error = false
 # Or comment out that line if it's set to :page_load
```

## Bootup
```shell
rails s
```

Now you can try hiting :
http://localhost:3000/home/index.json
http://localhost:3000/home/index.html

## What did we do to get here?
Check out these files to understand what's happening:
app/controllers/home_controller.rb has an index action. When we hit it, we process the request and call up a Cell, that lives in app/concepts/home/cell/index.rb

It's pretty straightforward. As we explore more involved structures and concepts, you will notice, that overall - the architecture is the same: simple and straightforward. It's very easy to keep a mental model of a fairly large project.

## Easy tests
It's ridiculously easy to test home view now. Check out test/concepts/home/index_cell_test.rb

## No more ActionView
We can comment out ActionView now.
 ```ruby
# in config/application.rb
#require 'action_view/railtie'
 ```
Our app is blazingly fast .  Granted we haven't created any complicated models and view yet, but 4ms views? 1ms json responses? on Rails? It's possible....

# Let's create a song controller, view, reform, etc. Everything a modern concept needs ;-)


text:
/**
 * @file mip-truckcn-tel 组件
 * @author
 */

define(function (require) {
    var MIP = window.MIP || {};
    var a = MIP.hash.get('a');
    var customElement = require('customElement').create();
    customElement.prototype.firstInviewCallback = function () {
        if (a) {
            var tel = (a.split('*', 1));
        }
        else {
            var element = this.element;
            tel = element.getAttribute('default-tel');
        }
        document.write('', tel, '');
    };
    return customElement;
});


text:
class TextAnswersController < ApplicationController

  def new
    @questionnaire = Questionnaire.find(params[:questionnaire_id], :include => :questionnaire_fields) if params[:questionnaire_id]
    @text_answer = TextAnswer.new
    @text_answer.text_answer_fields.build
    if @questionnaire
      @questionnaire.questionnaire_fields.each do |field|
        @text_answer.answer_type_fields.build(:language => field.language, :is_default_language => field.is_default_language )
      end
    end
    respond_to do |format|
      format.js
    end
  end

  def edit
    @text_answer = TextAnswer.find_or_initialize_by_id(params[:id]) #, :include => :answer_type_fields)
    if @text_answer.new_record?
      @text_answer.text_answer_fields.build
    end
    @questionnaire = Questionnaire.find(params[:questionnaire_id], :include => :questionnaire_fields) if params[:questionnaire_id]
    if @questionnaire
      @questionnaire.questionnaire_fields.each do |field|
        @text_answer.answer_type_fields.build(:language => field.language, :is_default_language => field.is_default_language ) unless @text_answer.answer_type_fields.find_by_language(field.language)
      end
    end
    respond_to do |format|
      format.html
      format.js
    end
  end
end


text:
<?php
if ( ! defined( 'WPINC' ) || ! defined( 'POF' ) ) die;

/**
 * Panda Options Slider Field
 *
 * @class   Panda_Options_Slider_Field
 * @package Panda_Options
 * @version 1.0
 *
 * @author  Uncleserj <serj[at]serj[dot]pro>
 */

if ( ! class_exists( 'Panda_Options_Slider_Field' ) ) {

	class Panda_Options_Slider_Field extends Panda_Options_Field {

		/**
		 * Field hooks
		 */

		public function hooks() {

			wp_enqueue_script( 'jquery-ui-slider' );

			add_action( 'admin_footer', function() {

				if ( ! wp_style_is( 'pof-slider-field', 'registered' ) ) {

					global $_wp_admin_css_colors;

					if ( $_wp_admin_css_colors ) $admin_colors = $_wp_admin_css_colors[get_user_option('admin_color')]->colors;

					wp_register_style( 'pof-slider-field', __FILE__ ); ?>

			<?php }

			} );

		}

		/**
		 * Print field content
		 */

		public function output() {

			$field = $this->field;
			$options = $this->options;
			$prefix = $this->prefix;

			isset( $field->std ) ? $default = $this->sanitize( $field->std ) : $default = 0;

			if ( ! isset( $options[$field->name] ) ) $options[$field->name] = $default;

			if ( ! isset( $field->min ) ) $field->min = 0;

			if ( ! isset( $field->max ) ) $field->max = 100;

			if ( ! isset( $field->step ) ) $field->step = 1;

			if ( ! isset( $field->sign ) ) $field->sign = '';

			if ( floatval($options[$field->name]) < floatval($field->min) ) $options[$field->name] = $field->min;

			if ( floatval($options[$field->name]) > floatval($field->max) ) $options[$field->name] = $field->max;
			?>
			<input type='hidden' data-min='<?php echo $field->min; ?>' data-max='<?php echo $field->max; ?>' data-step='<?php echo $field->step; ?>' id='<?php echo $field->name; ?>' data-sign='<?php echo $field->sign; ?>' name='<?php echo POF . $prefix; ?>[<?php echo $field->name; ?>]' value='<?php echo esc_attr( $options[$field->name] ); ?>' />

			<?php if ( isset( $field->desc ) ) { ?>
			<label class="<?php echo $field->type; ?>-label" for="<?php echo $field->name; ?>"><?php echo $this->get_sanitized_text( $field->desc ); ?>
			<?php }
		}

		/**
		 * Check required attributes of field
		 */

		public function check_field() {

			if ( isset( $this->field->name ) && isset( $this->field->type ) && isset( $this->field->title ) ) return true;

			return false;

		}

		/**
		 * Sanitize input
		 *
		 * @param string|int|array Dirty value
		 */

		public function sanitize( $value ) {

			$value = floatval( $value );

			return $value;

		}

	}

}
?>


text:
#ifndef __PANGO_FC_FONT_MAP_H__
#define __PANGO_FC_FONT_MAP_H__

#include <pango/pango.h>
#include <fontconfig/fontconfig.h>
#include <pango/pangofc-decoder.h>
#include <pango/pangofc-font.h>

G_BEGIN_DECLS

#ifdef PANGO_ENABLE_BACKEND

/**
 * PangoFcFontsetKey:
 *
 * An opaque structure containing all the information needed for
 * loading a fontset with the PangoFc fontmap.
 *
 * Since: 1.24
 **/
typedef struct _PangoFcFontsetKey  PangoFcFontsetKey;

PANGO_AVAILABLE_IN_1_24
PangoLanguage              *pango_fc_fontset_key_get_language      (const PangoFcFontsetKey *key);
PANGO_AVAILABLE_IN_1_24
const PangoFontDescription *pango_fc_fontset_key_get_description   (const PangoFcFontsetKey *key);
PANGO_AVAILABLE_IN_1_24
const PangoMatrix          *pango_fc_fontset_key_get_matrix        (const PangoFcFontsetKey *key);
PANGO_AVAILABLE_IN_1_24
double                      pango_fc_fontset_key_get_absolute_size (const PangoFcFontsetKey *key);
PANGO_AVAILABLE_IN_1_24
double                      pango_fc_fontset_key_get_resolution    (const PangoFcFontsetKey *key);
PANGO_AVAILABLE_IN_1_24
gpointer                    pango_fc_fontset_key_get_context_key   (const PangoFcFontsetKey *key);

/**
 * PangoFcFontKey:
 *
 * An opaque structure containing all the information needed for
 * loading a font with the PangoFc fontmap.
 *
 * Since: 1.24
 **/
typedef struct _PangoFcFontKey     PangoFcFontKey;

PANGO_AVAILABLE_IN_1_24
const FcPattern   *pango_fc_font_key_get_pattern     (const PangoFcFontKey *key);
PANGO_AVAILABLE_IN_1_24
const PangoMatrix *pango_fc_font_key_get_matrix      (const PangoFcFontKey *key);
PANGO_AVAILABLE_IN_1_24
gpointer           pango_fc_font_key_get_context_key (const PangoFcFontKey *key);
PANGO_AVAILABLE_IN_1_40
const char        *pango_fc_font_key_get_variations  (const PangoFcFontKey *key);

#endif

/*
 * PangoFcFontMap
 */

#define PANGO_TYPE_FC_FONT_MAP              (pango_fc_font_map_get_type ())
#define PANGO_FC_FONT_MAP(object)           (G_TYPE_CHECK_INSTANCE_CAST ((object), PANGO_TYPE_FC_FONT_MAP, PangoFcFontMap))
#define PANGO_IS_FC_FONT_MAP(object)        (G_TYPE_CHECK_INSTANCE_TYPE ((object), PANGO_TYPE_FC_FONT_MAP))

typedef struct _PangoFcFontMap        PangoFcFontMap;
typedef struct _PangoFcFontMapClass   PangoFcFontMapClass;
typedef struct _PangoFcFontMapPrivate PangoFcFontMapPrivate;

#ifdef PANGO_ENABLE_BACKEND

#define PANGO_FC_FONT_MAP_CLASS(klass)      (G_TYPE_CHECK_CLASS_CAST ((klass), PANGO_TYPE_FC_FONT_MAP, PangoFcFontMapClass))
#define PANGO_IS_FC_FONT_MAP_CLASS(klass)   (G_TYPE_CHECK_CLASS_TYPE ((klass), PANGO_TYPE_FC_FONT_MAP))
#define PANGO_FC_FONT_MAP_GET_CLASS(obj)    (G_TYPE_INSTANCE_GET_CLASS ((obj), PANGO_TYPE_FC_FONT_MAP, PangoFcFontMapClass))

/**
 * PangoFcFontMap:
 *
 * #PangoFcFontMap is a base class for font map implementations
 * using the Fontconfig and FreeType libraries. To create a new
 * backend using Fontconfig and FreeType, you derive from this class
 * and implement a new_font() virtual function that creates an
 * instance deriving from #PangoFcFont.
 **/
struct _PangoFcFontMap
{
  PangoFontMap parent_instance;

  PangoFcFontMapPrivate *priv;
};

/**
 * PangoFcFontMapClass:
 * @default_substitute: (nullable): Substitutes in default
 *  values for unspecified fields in a #FcPattern. This will
 *  be called prior to creating a font for the pattern. May be
 *  %NULL.  Deprecated in favor of @font_key_substitute().
 * @new_font: Creates a new #PangoFcFont for the specified
 *  pattern of the appropriate type for this font map. The
 *  @pattern argument must be passed to the "pattern" property
 *  of #PangoFcFont when you call g_object_new(). Deprecated
 *  in favor of @create_font().
 * @get_resolution: Gets the resolution (the scale factor
 *  between logical and absolute font sizes) that the backend
 *  will use for a particular fontmap and context. @context
 *  may be null.
 * @context_key_get: Gets an opaque key holding backend
 *  specific options for the context that will affect
 *  fonts created by @create_font(). The result must point to
 *  persistant storage owned by the fontmap. This key
 *  is used to index hash tables used to look up fontsets
 *  and fonts.
 * @context_key_copy: Copies a context key. Pango uses this
 *  to make a persistant copy of the value returned from
 *  @context_key_get.
 * @context_key_free: Frees a context key copied with
 *  @context_key_copy.
 * @context_key_hash: Gets a hash value for a context key
 * @context_key_equal: Compares two context keys for equality.
 * @fontset_key_substitute: (nullable): Substitutes in
 *  default values for unspecified fields in a
 *  #FcPattern. This will be called prior to creating a font
 *  for the pattern. May be %NULL.  (Since: 1.24)
 * @create_font: (nullable): Creates a new #PangoFcFont for
 *  the specified pattern of the appropriate type for this
 *  font map using information from the font key that is
 *  passed in. The @pattern member of @font_key can be
 *  retrieved using pango_fc_font_key_get_pattern() and must
 *  be passed to the "pattern" property of #PangoFcFont when
 *  you call g_object_new().  If %NULL, new_font() is used.
 *  (Since: 1.24)
 *
 * Class structure for #PangoFcFontMap.
 **/
struct _PangoFcFontMapClass
{
  /*< private >*/
  PangoFontMapClass parent_class;

  /*< public >*/
  /* Deprecated in favor of fontset_key_substitute */
  void         (*default_substitute) (PangoFcFontMap   *fontmap,
				      FcPattern        *pattern);
  /* Deprecated in favor of create_font */
  PangoFcFont  *(*new_font)          (PangoFcFontMap  *fontmap,
				      FcPattern       *pattern);

  double       (*get_resolution)     (PangoFcFontMap             *fcfontmap,
				      PangoContext               *context);

  gconstpointer (*context_key_get)   (PangoFcFontMap             *fcfontmap,
				      PangoContext               *context);
  gpointer     (*context_key_copy)   (PangoFcFontMap             *fcfontmap,
				      gconstpointer               key);
  void         (*context_key_free)   (PangoFcFontMap             *fcfontmap,
				      gpointer                    key);
  guint32      (*context_key_hash)   (PangoFcFontMap             *fcfontmap,
				      gconstpointer               key);
  gboolean     (*context_key_equal)  (PangoFcFontMap             *fcfontmap,
				      gconstpointer               key_a,
				      gconstpointer               key_b);
  void         (*fontset_key_substitute)(PangoFcFontMap             *fontmap,

				      PangoFcFontsetKey          *fontsetkey,
				      FcPattern                  *pattern);
  PangoFcFont  *(*create_font)       (PangoFcFontMap             *fontmap,
				      PangoFcFontKey             *fontkey);
  /*< private >*/

  /* Padding for future expansion */
  void (*_pango_reserved1) (void);
  void (*_pango_reserved2) (void);
  void (*_pango_reserved3) (void);
  void (*_pango_reserved4) (void);
};

#ifndef PANGO_DISABLE_DEPRECATED
PANGO_DEPRECATED_IN_1_22_FOR(pango_font_map_create_context)
PangoContext * pango_fc_font_map_create_context (PangoFcFontMap *fcfontmap);
#endif
PANGO_AVAILABLE_IN_1_4
void           pango_fc_font_map_shutdown       (PangoFcFontMap *fcfontmap);

#endif

PANGO_AVAILABLE_IN_ALL
GType pango_fc_font_map_get_type (void) G_GNUC_CONST;

PANGO_AVAILABLE_IN_1_4
void           pango_fc_font_map_cache_clear    (PangoFcFontMap *fcfontmap);

PANGO_AVAILABLE_IN_1_38
void
pango_fc_font_map_config_changed (PangoFcFontMap *fcfontmap);

PANGO_AVAILABLE_IN_1_38
void
pango_fc_font_map_set_config (PangoFcFontMap *fcfontmap,
			      FcConfig       *fcconfig);
PANGO_AVAILABLE_IN_1_38
FcConfig *
pango_fc_font_map_get_config (PangoFcFontMap *fcfontmap);

/**
 * PangoFcDecoderFindFunc:
 * @pattern: a fully resolved #FcPattern specifying the font on the system
 * @user_data: user data passed to pango_fc_font_map_add_decoder_find_func()
 *
 * Callback function passed to pango_fc_font_map_add_decoder_find_func().
 *
 * Return value: a new reference to a custom decoder for this pattern,
 *  or %NULL if the default decoder handling should be used.
 **/
typedef PangoFcDecoder * (*PangoFcDecoderFindFunc) (FcPattern *pattern,
						    gpointer   user_data);

PANGO_AVAILABLE_IN_1_6
void pango_fc_font_map_add_decoder_find_func (PangoFcFontMap        *fcfontmap,
					      PangoFcDecoderFindFunc findfunc,
					      gpointer               user_data,
					      GDestroyNotify         dnotify);
PANGO_AVAILABLE_IN_1_26
PangoFcDecoder *pango_fc_font_map_find_decoder (PangoFcFontMap *fcfontmap,
					        FcPattern      *pattern);

PANGO_AVAILABLE_IN_1_4
PangoFontDescription *pango_fc_font_description_from_pattern (FcPattern *pattern,
							      gboolean   include_size);

/**
 * PANGO_FC_GRAVITY:
 *
 * String representing a fontconfig property name that Pango sets on any
 * fontconfig pattern it passes to fontconfig if a #PangoGravity other
 * than %PANGO_GRAVITY_SOUTH is desired.
 *
 * The property will have a #PangoGravity value as a string, like "east".
 * This can be used to write fontconfig configuration rules to choose
 * different fonts for horizontal and vertical writing directions.
 *
 * Since: 1.20
 */
#define PANGO_FC_GRAVITY "pangogravity"

/**
 * PANGO_FC_VERSION:
 *
 * String representing a fontconfig property name that Pango sets on any
 * fontconfig pattern it passes to fontconfig.
 *
 * The property will have an integer value equal to what
 * pango_version() returns.
 * This can be used to write fontconfig configuration rules that only affect
 * certain pango versions (or only pango-using applications, or only
 * non-pango-using applications).
 *
 * Since: 1.20
 */
#define PANGO_FC_VERSION "pangoversion"

/**
 * PANGO_FC_PRGNAME:
 *
 * String representing a fontconfig property name that Pango sets on any
 * fontconfig pattern it passes to fontconfig.
 *
 * The property will have a string equal to what
 * g_get_prgname() returns.
 * This can be used to write fontconfig configuration rules that only affect
 * certain applications.
 *
 * This is equivalent to FC_PRGNAME in versions of fontconfig that have that.
 *
 * Since: 1.24
 */
#define PANGO_FC_PRGNAME "prgname"

/**
 * PANGO_FC_FONT_FEATURES:
 *
 * String representing a fontconfig property name that Pango reads from font
 * patterns to populate list of OpenType features to be enabled for the font
 * by default.
 *
 * The property will have a number of string elements, each of which is the
 * OpenType feature tag of one feature to enable.
 *
 * This is equivalent to FC_FONT_FEATURES in versions of fontconfig that have that.
 *
 * Since: 1.34
 */
#define PANGO_FC_FONT_FEATURES "fontfeatures"

/**
 * PANGO_FC_FONT_VARIATIONS:
 *
 * String representing a fontconfig property name that Pango reads from font
 * patterns to populate list of OpenType font variations to be used for a font.
 *
 * The property will have a string elements, each of which a comma-separated
 * list of OpenType axis setting of the form AXIS=VALUE.
 */
#define PANGO_FC_FONT_VARIATIONS "fontvariations"

G_END_DECLS

#endif /* __PANGO_FC_FONT_MAP_H__ */


text:
module.exports = Backbone.View.extend({

    initialize: function(options)
    {
    	this.render();
    },

    addEventListeners: function( scope )
    {
    	$.subscribe('openLogin', this, this.openLogin);
    	$.subscribe('apiLogin', this, this.updateLoginDetails);
    	$.subscribe('apiLoginFailure', this, this.loginFailed);
    	$.subscribe('doLogout', this, this.logout);//starts logout
    	$.subscribe('logout', this, this.onLoggedout);//after logout action

    	$.subscribe('addSplash', this, this.onAddSplash);
    	$.subscribe('removeSplash', this, this.onRemoveSplash);
    },

    openLogin: function()
    {
    	appUtil.openPopup('Login', '210px', '500px');
    },

    onAddSplash: function()
    {
    	w2ui['layout'].lock('main', 'Loading...', true);
    },

    onRemoveSplash: function()
    {
    	w2ui['layout'].unlock('main');
    },

	updateLoginDetails: function( event )
	{
		w2ui['LoginForm'].unlock();
		w2ui['LoginForm'].refresh();

		$().w2popup('close');

    	var login = event.data;
    	//w2ui['applicationButtonToolbar'].get('user').caption = login.username;
    	//w2ui['applicationButtonToolbar'].refresh();
	},

	loginFailed: function(event)
	{
		w2ui['LoginForm'].unlock();
		w2ui['LoginForm'].error(event.data.value);
	},

	onLoggedout: function( event )
	{
	},

   logout: function()
   {
	   this.model.logout();
   },

    initComponents: function( scope )
    {

    	$().w2form({
			name: 'LoginForm',
			style: 'border: 0px; background-color: transparent;',
			formURL  : 'assets/popups/LoginForm.html',
			fields: [
				{ name: 'username', type: 'text', required: true },
				{ name: 'password', type: 'password', required: true },
			],

			actions: {
				"save": function () {
					var errors = this.validate();
					if (errors.length !== 0) {
						return;
					}
					this.lock('Logging In...');
					scope.model.login(this.record.username, this.record.password);
					this.clear();
				},
				"reset": function () { this.clear(); }
			}
		});

    },

	render: function()
	{
		this.initComponents( this );
		this.addEventListeners( this );
		return this;
	}

});


text:
<!doctype html>

    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Foundation | Welcome</title>
    <link rel="stylesheet" href="http://dhbhdrzi4tiry.cloudfront.net/cdn/sites/foundation.min.css">

Yeti Store

              One

One

Two

Three

Two

Three

<input type="search" placeholder="Search">

<button type="button" class="button">Search</button>

Home

Features

Gene Splicing

            Current:  Cloning

My Awesome Product

Nunc eu ullamcorper orci. Quisque eget odio ac lectus vestibulum faucibus eget in metus. In pellentesque faucibus vestibulum. Nulla at nulla justo, eget luctus tortor. Nulla facilisi. Duis aliquet egestas purus in.

        Size
        <select>
          <option value="husker">Small</option>
          <option value="starbuck">Medium</option>
          <option value="hotdog">Large</option>
          <option value="apollo">Yeti</option>
        </select>

            Quantity

            <input type="text" id="middle-label" placeholder="One fish two fish">

        Buy Now

            Facebook
            Twitter
            Yo

Reviews

Similar Products

Reviews

Mike Stevenson

I'm going to improvise. Listen, there's something you should know about me... about inception. An idea is like a virus, resilient, highly contagious. The smallest seed of an idea can grow. It can grow to define or destroy you.

Mike Stevenson

I'm going to improvise. Listen, there's something you should know about me... about inception. An idea is like a virus, resilient, highly contagious. The smallest seed of an idea can grow. It can grow to define or destroy you

Mike Stevenson

I'm going to improvise. Listen, there's something you should know about me... about inception. An idea is like a virus, resilient, highly contagious. The smallest seed of an idea can grow. It can grow to define or destroy you

            My Review
            <textarea placeholder="None"></textarea>

          <button class="button">Submit Review</button>

Other Product $22

In condimentum facilisis porta. Sed nec diam eu diam mattis viverra. Nulla fringilla, orci ac euismod semper, magna diam.

              Buy Now

Other Product $22

In condimentum facilisis porta. Sed nec diam eu diam mattis viverra. Nulla fringilla, orci ac euismod semper, magna diam.

              Buy Now

Other Product $22

In condimentum facilisis porta. Sed nec diam eu diam mattis viverra. Nulla fringilla, orci ac euismod semper, magna diam.

              Buy Now

Other Product $22

In condimentum facilisis porta. Sed nec diam eu diam mattis viverra. Nulla fringilla, orci ac euismod semper, magna diam.

              Buy Now

Other Product $22

In condimentum facilisis porta. Sed nec diam eu diam mattis viverra. Nulla fringilla, orci ac euismod semper, magna diam.

              Buy Now

Yeti Store

Home

About

Contact

Copyright 2016


text:
<?php

namespace NewUp\Templates\Renderers\Functions;

use NewUp\Templates\Renderers\TemplateRenderer;

class ArgumentFunction extends BaseFunction
{

    /**
     * The name of the function.
     *
     * @var string
     */
    protected $name = 'argument';

    /**
     * The function context (TemplateRenderer).
     *
     * @var TemplateRenderer
     */
    protected $context = null;

    /**
     * Gets the function that is passed to the rendering environment.
     *
     * @return mixed|\Closure
     */
    public function getFunction()
    {
        return function ($argument, $default = null) {
            return array_get($this->context->getData(), 'user_args.' . $argument, $default);
        };
    }

}


text:
namespace VKE
{
    namespace Core
    {
        class CImage;
    } // Core
    namespace RenderSystem
    {
        class CTextureManager;

        struct STextureManagerDesc
        {

        };

        class CTextureManager
        {
            friend class CDeviceContext;
            friend class CGraphicsContext;
            friend class CComputeContext;
            friend class CTransferContext;
            friend class CTexture;

            struct SFreeTextureHandle
            {
                hash_t      descHash;
                uint32_t    idx;
            };

            struct SLoadTextureTaskData
            {
                Core::SLoadFileInfo LoadFileInfo;
                CTexture* pTexture = nullptr;
            };

            template<class T> using TaskPool = Utils::TSFreePool<T, uint32_t, 1024>;
            // using CreateShaderTaskPool = TaskPool< ShaderManagerTasks::SCreateShaderTask >;
            using LoadTextureTask = Threads::TSDataTypedTask<SLoadTextureTaskData>;
            using LoadTextureTaskPool = TaskPool<LoadTextureTask>;

            //using TextureBuffer = Core::TSResourceBuffer< TextureRefPtr, CTexture* >;
            //using TextureViewBuffer = Core::TSResourceBuffer< TextureViewRefPtr, CTextureView* >;
            //using TextureBuffer = Utils::TSFreePool< CTexture*, TextureHandle >;
            using TextureBuffer = Core::TSVectorResourceBuffer< CTexture*, CTexture*, 1 >;
            using TextureViewBuffer = Utils::TSFreePool< CTextureView* >;
            using RenderTargetBuffer = Utils::TSFreePool< CRenderTarget* >;
            using RenderTargetNameMap = vke_hash_map< cstr_t, RenderTargetHandle >;
            using SamplerMap = Core::TSHashMap < hash_t, CSampler* >;

            using TextureViewNameMap = vke_hash_map< hash_t, TextureViewPtr >;

            using TexMemMgr = Memory::CFreeListPool;
            using TexViewMemMgr = Memory::CFreeListPool;
            using RenderTargetMemMgr = Memory::CFreeListPool;
            using SamplerMemMgr = Memory::CFreeListPool;

            public:

                CTextureManager( CDeviceContext* pCtx );
                ~CTextureManager();

                Result              Create( const STextureManagerDesc& Desc );
                void                Destroy();

                TextureHandle       CreateTexture( const STextureDesc& Desc );
                TextureHandle       CreateTexture(const Core::ImageHandle& hImg);
                Result              LoadTexture(const Core::SLoadFileInfo& Info, TextureHandle* phOut);
                void                DestroyTexture( TextureHandle* phTexture );
                //void                FreeTexture( TextureHandle* phTexture );
                TextureRefPtr       GetTexture( TextureHandle hTexture );

                TextureViewHandle   CreateTextureView( const STextureViewDesc& Desc );
                void                DestroyTextureView( TextureViewHandle* phTextureView );
                //void                FreeTextureView( TextureViewHandle* phTextureView );
                TextureViewRefPtr   GetTextureView( TextureViewHandle hTextureView );
                TextureViewRefPtr   GetTextureView( const TextureHandle& hTexture );
                TextureViewRefPtr   GetTextureView( const RenderTargetHandle& hRT );

                RenderTargetHandle  CreateRenderTarget( const SRenderTargetDesc& Desc );
                RenderTargetRefPtr  GetRenderTarget( const RenderTargetHandle& hRT );
                RenderTargetRefPtr  GetRenderTarget( cstr_t pName );
                void                DestroyRenderTarget( RenderTargetHandle* phRT );

                SamplerHandle       CreateSampler( const SSamplerDesc& Desc );
                SamplerRefPtr       GetSampler( const SamplerHandle& hSampler );
                void                DestroySampler( SamplerHandle* phSampler );

                Result              UpdateTexture(  const SUpdateMemoryInfo& Info, TextureHandle* phInOut );

            protected:

                CTexture*           _CreateTextureTask( const STextureDesc& Desc );
              Result _CreateTexture( const Core::ImageHandle& hImg, STAGING_BUFFER_FLAGS updateInfoFlags, CTexture** );
                Result             _LoadTextureTask(const Core::SLoadFileInfo& Info, CTexture**);
                CTexture*           _CreateTextureFromImage(const Core::ImageHandle& hImg);
                void                _DestroyTexture( CTexture** ppInOut );
                Result              _UploadTextureMemoryTask(const SUpdateMemoryInfo& Info, CTexture** ppInOut);
                Result _UploadTextureMemoryTask( STAGING_BUFFER_FLAGS flags, Core::CImage* pImg, CTexture** ppInOut);

                CTextureView*       _CreateTextureViewTask( const STextureDesc& Desc );
                void                _DestroyTextureView( CTextureView** ppInOut );

                CTexture*           _FindFreeTextureForReuse( const STextureDesc& Desc );
                void                _FreeTexture( CTexture** ppInOut );
                void                _AddTexture( CTexture* pTexture );

                CTextureView*       _FindFreeTextureViewForReuse( const STextureViewDesc& Desc );
                void                _FreeTextureView( CTextureView** ppInOut );
                void                _AddTextureView( CTextureView* pTexture );

                void                _DestroyRenderTarget( CRenderTarget** ppInOut );
                void                _DestroySampler( CSampler** ppInOut );

            protected:

                CDeviceContext*         m_pCtx;
                TextureBuffer           m_Textures;
                TextureViewBuffer       m_TextureViews;
                SamplerMap              m_Samplers;
                RenderTargetBuffer      m_RenderTargets;
                RenderTargetNameMap     m_mRenderTargetNames;
                //FreeTextureType          m_FreeTextures;
                Threads::SyncObject     m_SyncObj;
                LoadTextureTaskPool     m_LoadTaskPool;
                TexMemMgr               m_TexMemMgr;
                TexViewMemMgr           m_TexViewMemMgr;
                RenderTargetMemMgr      m_RenderTargetMemMgr;
                SamplerMemMgr           m_SamplerMemMgr;
        };
    } // RenderSystem
} // VKE

#endif // VKE_VULKAN_RENDER_SYSTEM


text:
package com.dblima.agendocontatos.acEvento;
import acCommon.Endereco;
import acCommon.acEnum.Exclusividade;
import acContato.Contato;

import java.util.Date;

public class Evento extends Endereco {
    private String titulo;
    private String local;
    private Date data;
    private Exclusividade exclusividade;
    private int maxConvidados;
    private Float valor;

    // TOdo avaliar como contatos serma armazenados
    private int contatos[] = new int[100];
    private int nc=0;

    public Date getData() {
        return data;
    }

    public void setData(Date data) {
        this.data = data;
    }

    public void insereContato(int c){
        contatos[nc]=c;
        nc++;
    }

    public void insereContatos(Contato c[]){

    }
}


text:
export default class AnalyticsService {

    static _instance;

    constructor(private $http, private authService, private toastr) {}

    static create($http, authService, toastr) {
        this._instance = new this($http, authService, toastr);
        return this._instance;
    }

    static getInstance() {
        return this._instance;
    }

    private _getAction(event) {
        var action = event;
        if (action.slice(-1) === 's') {
            action = action.slice(0, -1);
        }
        return action;
    }

    fetchUserAction(doc, events) {
        var actions = [] as any[];
        events.forEach((event) => {
            actions.push(this._getAction(event));
        });
        var solrCall = 'solr/analytics/select?q=*:*';
        var fields = '&fl=action';
        var filters = '&fq=id:' + doc.id + '&fq=action:(' + actions.join(' ') + ')&fq=user:' + this.authService.getUser().id;
        var suffix = '&r=' + Math.random() + '&wt=json';
        solrCall += fields + filters + suffix;
        return this.$http.get(config.root + solrCall).then(function(res) {
            return res.data.response.docs;
        });
    }

    track(doc, event, value) {
        var action = this._getAction(event);
        var data = {
            action: action,
            category: 'results',
            label: doc.format,
            id: doc.id,
            user: this.authService.getUser().id,
        };
        if (value !== undefined) {
            data['value'] = value;
        }
        var analyticsApi = config.root + 'api/rest/analytics/track';

        return this.$http.post(analyticsApi, JSON.stringify(data)).then(function() {
            doc[event] += 1;
            if (event.indexOf('likes') !== -1 && value === -1) {
                var inverseEvent = event === 'likes' ? 'dislikes' : 'likes';
                doc[inverseEvent] += -1;
            }
        });
    }

    addBehavior(doc, action) {
        if (this.authService.isLoggedIn()) {
            this.fetchUserAction(doc, ['likes', 'dislikes']).then((docs) => {
                if (docs.length === 0) {
                    this.track(doc, action, undefined);
                } else if (docs[0].action === this._getAction(action)) {
                    this.toastr.info('You already ' + docs[0].action + 'd that.');
                } else {
                    this.track(doc, action, -1);
                }
            });
        } else {
            this.toastr.info('You must me logged in to do that.');
        }
    }
}


text:
namespace
{
using namespace testing;
using namespace iox;

class SharedMemoryObject_Test : public Test
{
  public:
    void SetUp() override
    {
        internal::CaptureStderr();
    }

    void TearDown() override
    {
        std::string output = internal::GetCapturedStderr();
        if (Test::HasFailure())
        {
            std::cout << output << std::endl;
        }
    }

    static void PerformDeathTest(const std::function<void()>& deathTest)
    {
        std::set_terminate([]() { std::cout << "", std::abort(); });

        internal::GetCapturedStderr();
        // @todo iox-#1613 remove EXPECT_DEATH
        // NOLINTBEGIN(hicpp-avoid-goto, cppcoreguidelines-avoid-goto, cert-err33-c, cppcoreguidelines-pro-type-vararg,
        // hiccpp-vararg)
        EXPECT_DEATH({ deathTest(); }, ".*");
        // NOLINTEND(hicpp-avoid-goto, cppcoreguidelines-avoid-goto, cert-err33-c, cppcoreguidelines-pro-type-vararg,
        // hiccpp-vararg)
        internal::CaptureStderr();
    }
};

TEST_F(SharedMemoryObject_Test, CTorWithValidArguments)
{
    ::testing::Test::RecordProperty("TEST_ID", "bbda60d2-d741-407e-9a9f-f0ca74d985a8");
    auto sut = iox::posix::SharedMemoryObjectBuilder()
                   .name("validShmMem")
                   .memorySizeInBytes(100)
                   .accessMode(iox::posix::AccessMode::READ_WRITE)
                   .openMode(iox::posix::OpenMode::PURGE_AND_CREATE)
                   .create();

    EXPECT_THAT(sut.has_error(), Eq(false));
}

TEST_F(SharedMemoryObject_Test, CTorOpenNonExistingSharedMemoryObject)
{
    ::testing::Test::RecordProperty("TEST_ID", "d80278c3-1dd8-409d-9162-f7f900892526");
    auto sut = iox::posix::SharedMemoryObjectBuilder()
                   .name("pummeluff")
                   .memorySizeInBytes(100)
                   .accessMode(iox::posix::AccessMode::READ_WRITE)
                   .openMode(iox::posix::OpenMode::OPEN_EXISTING)
                   .create();

    EXPECT_THAT(sut.has_error(), Eq(true));
}

TEST_F(SharedMemoryObject_Test, AllocateMemoryInSharedMemoryAndReadIt)
{
    ::testing::Test::RecordProperty("TEST_ID", "6169ac70-a08e-4a19-80e4-57f0d5f89233");
    auto sut = iox::posix::SharedMemoryObjectBuilder()
                   .name("shmAllocate")
                   .memorySizeInBytes(16)
                   .accessMode(iox::posix::AccessMode::READ_WRITE)
                   .openMode(iox::posix::OpenMode::PURGE_AND_CREATE)
                   .permissions(cxx::perms::owner_all)
                   .create();

    ASSERT_THAT(sut.has_error(), Eq(false));
    int* test = static_cast<int*>(sut->allocate(sizeof(int), 1));
    ASSERT_THAT(test, Ne(nullptr));
    *test = 123;
    EXPECT_THAT(*test, Eq(123));
}

TEST_F(SharedMemoryObject_Test, AllocateWholeSharedMemoryWithOneChunk)
{
    ::testing::Test::RecordProperty("TEST_ID", "2def907e-683d-4aaa-a969-47b5468d5383");
    auto sut = iox::posix::SharedMemoryObjectBuilder()
                   .name("shmAllocate")
                   .memorySizeInBytes(8)
                   .accessMode(iox::posix::AccessMode::READ_WRITE)
                   .openMode(iox::posix::OpenMode::PURGE_AND_CREATE)
                   .permissions(cxx::perms::owner_all)
                   .create();

    ASSERT_THAT(sut.has_error(), Eq(false));
    void* test = sut->allocate(8, 1);
    ASSERT_THAT(test, Ne(nullptr));
}

TEST_F(SharedMemoryObject_Test, AllocateWholeSharedMemoryWithMultipleChunks)
{
    ::testing::Test::RecordProperty("TEST_ID", "dd70c0aa-fef5-49ed-875c-4bb768894ae5");
    auto sut = iox::posix::SharedMemoryObjectBuilder()
                   .name("shmAllocate")
                   .memorySizeInBytes(8)
                   .accessMode(iox::posix::AccessMode::READ_WRITE)
                   .openMode(iox::posix::OpenMode::PURGE_AND_CREATE)
                   .permissions(cxx::perms::owner_all)
                   .create();

    ASSERT_THAT(sut.has_error(), Eq(false));

    for (uint64_t i = 0; i < 8; ++i)
    {
        void* test = sut->allocate(1, 1);
        ASSERT_THAT(test, Ne(nullptr));
    }
}

TEST_F(SharedMemoryObject_Test, AllocateTooMuchMemoryInSharedMemoryWithOneChunk)
{
    ::testing::Test::RecordProperty("TEST_ID", "4b054aac-1d49-4260-afc0-908b184e0b12");
    uint64_t memorySize{8U};

    auto sut = iox::posix::SharedMemoryObjectBuilder()
                   .name("shmAllocate")
                   .memorySizeInBytes(memorySize)
                   .accessMode(iox::posix::AccessMode::READ_WRITE)
                   .openMode(iox::posix::OpenMode::PURGE_AND_CREATE)
                   .permissions(cxx::perms::owner_all)
                   .create();

    ASSERT_THAT(sut.has_error(), Eq(false));

    PerformDeathTest([&] { sut->allocate(cxx::align(memorySize, posix::Allocator::MEMORY_ALIGNMENT) + 1, 1); });
}

TEST_F(SharedMemoryObject_Test, AllocateTooMuchSharedMemoryWithMultipleChunks)
{
    ::testing::Test::RecordProperty("TEST_ID", "5bb3c7fc-0f15-4487-8479-b27d1d4a17d3");
    uint64_t memorySize{8U};
    auto sut = iox::posix::SharedMemoryObjectBuilder()
                   .name("shmAllocate")
                   .memorySizeInBytes(memorySize)
                   .accessMode(iox::posix::AccessMode::READ_WRITE)
                   .openMode(iox::posix::OpenMode::PURGE_AND_CREATE)
                   .permissions(cxx::perms::owner_all)
                   .create();

    ASSERT_THAT(sut.has_error(), Eq(false));

    for (uint64_t i = 0; i < cxx::align(memorySize, posix::Allocator::MEMORY_ALIGNMENT); ++i)
    {
        void* test = sut->allocate(1, 1);
        ASSERT_THAT(test, Ne(nullptr));
    }

    PerformDeathTest([&] { sut->allocate(1, 1); });
}

TEST_F(SharedMemoryObject_Test, AllocateAfterFinalizeAllocation)
{
    ::testing::Test::RecordProperty("TEST_ID", "e4711eaa-e811-41d4-927a-63384cdcb984");
    auto sut = iox::posix::SharedMemoryObjectBuilder()
                   .name("shmAllocate")
                   .memorySizeInBytes(8)
                   .accessMode(iox::posix::AccessMode::READ_WRITE)
                   .openMode(iox::posix::OpenMode::PURGE_AND_CREATE)
                   .permissions(cxx::perms::owner_all)
                   .create();

    ASSERT_THAT(sut.has_error(), Eq(false));
    sut->finalizeAllocation();
    PerformDeathTest([&] { sut->allocate(2, 1); });
}

TEST_F(SharedMemoryObject_Test, OpeningSharedMemoryAndReadMultipleContents)
{
    ::testing::Test::RecordProperty("TEST_ID", "14f77425-34aa-43d0-82dd-e05efd93464b");
    uint64_t memorySize = 128;

    auto shmMemory = iox::posix::SharedMemoryObjectBuilder()
                         .name("shmSut")
                         .memorySizeInBytes(memorySize)
                         .accessMode(iox::posix::AccessMode::READ_WRITE)
                         .openMode(iox::posix::OpenMode::PURGE_AND_CREATE)
                         .permissions(cxx::perms::owner_all)
                         .create();

    ASSERT_THAT(shmMemory.has_error(), Eq(false));

    int* test = static_cast<int*>(shmMemory->allocate(sizeof(int), 1));
    *test = 4557;
    int* test2 = static_cast<int*>(shmMemory->allocate(sizeof(int), 1));
    *test2 = 8912;

    auto sut = iox::posix::SharedMemoryObjectBuilder()
                   .name("shmSut")
                   .memorySizeInBytes(memorySize)
                   .accessMode(iox::posix::AccessMode::READ_WRITE)
                   .openMode(iox::posix::OpenMode::OPEN_EXISTING)
                   .permissions(cxx::perms::owner_all)
                   .create();

    int* sutValue1 = static_cast<int*>(sut->allocate(sizeof(int), 1));
    int* sutValue2 = static_cast<int*>(sut->allocate(sizeof(int), 1));

    EXPECT_THAT(*sutValue1, Eq(4557));
    EXPECT_THAT(*sutValue2, Eq(8912));
}
} // namespace


text:
require 'test_helper'

module Vinz::Clortho
  class SSHKeyPathManagerTest < Minitest::Test
    def setup
      @initial_committers = {"authors" => {"hp" => "Harry Potter", "hg" => "Hermione Granger"},
                             "emails" => {"hp" => "hpotter@pivotal.io", "hg" => "hgranger@pivotal.io"},
                             "sshkey_paths" =>
                                 {"hp" => "/Volumes/hpotter/.ssh/id_rsa",
                                  "hg" => "/Volumes/hgranger/.ssh/id_rsa"}}
    end

    def test_looks_for_git_authors_in_any_parent_directory
      current_dir_git_authors = File.join(Dir.pwd, '.git-authors')
      parent_dir_git_authors = File.join(File.expand_path('..', Dir.pwd), '.git-authors')
      File.unstub(:exist?)
      File.expects(:exist?).with(current_dir_git_authors).returns false
      File.expects(:exist?).with(parent_dir_git_authors).returns true

      YAML.unstub(:load_file)
      YAML.expects(:load_file).with(parent_dir_git_authors).returns @initial_committers
      SSHKeyPathManager.new
    end

    def test_key_path_for_throws_exception_if_no_git_authors_file
      File.unstub(:exist?)
      YAML.unstub(:load_file)
      File.expects(:exist?).at_least_once.returns false

      mgr = SSHKeyPathManager.new
      error = assert_raises(UserNotFoundError) {
        mgr.key_path_for("hp")
      }
      assert_match /Unable to find committer initials in \.git-authors/, error.message
    end

    def test_key_path_for_throws_exception_when_unable_to_find_initials
      mgr = SSHKeyPathManager.new
      error = assert_raises(UserNotFoundError) {
        mgr.key_path_for("rw")
      }
      assert_match /Unable to find committer initials in \.git-authors/, error.message
    end

    def test_ssh_setup_displays_usage_when_initials_are_missing
      mgr = SSHKeyPathManager.new
      error = assert_raises(ArgumentError) {
        mgr.key_path_for nil
      }
      assert_equal 'Committer initials are required', error.message
    end

    def test_key_paths
      current_dir_git_authors = File.join(Dir.pwd, '.git-authors')
      File.expects(:exist?).with(current_dir_git_authors).returns true
      YAML.expects(:load_file).with(current_dir_git_authors).returns @initial_committers

      mgr = SSHKeyPathManager.new
      mgr.key_paths.map(&:path).each do |key_path|
        assert_includes ["/Volumes/hpotter/.ssh/id_rsa", "/Volumes/hgranger/.ssh/id_rsa"], key_path
      end
    end

    def test_key_paths_returns_all_available_paths_if_no_git_authors_file
      File.unstub(:exist?)
      YAML.unstub(:load_file)
      File.expects(:exist?).at_least_once.returns false

      keys = ["/Volumes/hpotter/.ssh/id_rsa", "/Volumes/hgranger/.ssh/id_rsa"]
      Dir.expects(:[]).with("/Volumes/*/.ssh/id_rsa").returns(keys)
      mgr = SSHKeyPathManager.new
      mgr.key_paths.map(&:path).each do |path|
        assert_includes keys, path
      end
    end

    def test_key_paths_returns_all_available_paths_if_no_sshkey_paths
      committers = @initial_committers.reject { |k, v| k == 'sshkey_paths' }
      current_dir_git_authors = File.join(Dir.pwd, '.git-authors')
      File.expects(:exist?).with(current_dir_git_authors).returns true
      YAML.expects(:load_file).with(current_dir_git_authors).returns committers

      keys = ["/Volumes/hpotter/.ssh/id_rsa", "/Volumes/hgranger/.ssh/id_rsa"]
      Dir.expects(:[]).with("/Volumes/*/.ssh/id_rsa").returns(keys)
      mgr = SSHKeyPathManager.new
      mgr.key_paths.map(&:path).each do |path|
        assert_includes keys, path
      end
    end
  end
end


text:
<!doctype html>

		<meta charset="utf-8" />
	<meta name="viewport" content="width=device-width, initial-scale=1.0" />
	<title>Refurbing my own PowerBook battery</title>
	<link rel="stylesheet" type="text/css" href="http://jonsharp.net/assets/css/styles_feeling_responsive.css" />

    <link href='http://fonts.googleapis.com/css?family=Lato:400,700,400italic|Volkhov' rel='stylesheet' type='text/css' />

  <meta name="google-site-verification" content="Vk0IOJ2jwG_qEoG7fuEXYqv0m2rLa8P778Fi_GrsgEQ" />

	<meta name="description" content="Personal website of Jon Sharp - a Seventh-day Adventist Christian, family man, lover of the outdoors, technology leader, enterprise architect, embedded systems engineer, and retrocomputing enthusiast." />

	<link rel="icon" sizes="32x32" href="http://jonsharp.net/assets/img/favicon-32x32.png" />

	<link rel="icon" sizes="192x192" href="http://jonsharp.net/assets/img/touch-icon-192x192.png" />

	<link rel="apple-touch-icon-precomposed" sizes="180x180" href="http://jonsharp.net/assets/img/apple-touch-icon-180x180-precomposed.png" />

	<link rel="apple-touch-icon-precomposed" sizes="152x152" href="http://jonsharp.net/assets/img/apple-touch-icon-152x152-precomposed.png" />

	<link rel="apple-touch-icon-precomposed" sizes="144x144" href="http://jonsharp.net/assets/img/apple-touch-icon-144x144-precomposed.png" />

	<link rel="apple-touch-icon-precomposed" sizes="120x120" href="http://jonsharp.net/assets/img/apple-touch-icon-120x120-precomposed.png" />

	<link rel="apple-touch-icon-precomposed" sizes="114x114" href="http://jonsharp.net/assets/img/apple-touch-icon-114x114-precomposed.png" />

	<link rel="apple-touch-icon-precomposed" sizes="76x76" href="http://jonsharp.net/assets/img/apple-touch-icon-76x76-precomposed.png" />

	<link rel="apple-touch-icon-precomposed" sizes="72x72" href="http://jonsharp.net/assets/img/apple-touch-icon-72x72-precomposed.png" />

	<link rel="apple-touch-icon-precomposed" href="http://jonsharp.net/assets/img/apple-touch-icon-precomposed.png" />

	<meta name="msapplication-TileImage" content="http://jonsharp.net/assets/img/msapplication_tileimage.png" />

	<meta name="msapplication-TileColor" content="#fabb00" />

	<meta property="og:locale" content="en_EN" />
	<meta property="og:type" content="website" />
	<meta property="og:title" content="Refurbing my own PowerBook battery" />
	<meta property="og:description" content="Personal website of Jon Sharp - a Seventh-day Adventist Christian, family man, lover of the outdoors, technology leader, enterprise architect, embedded systems engineer, and retrocomputing enthusiast." />
	<meta property="og:url" content="http://jonsharp.net//refurbing-my-own-powerbook-battery/" />
	<meta property="og:site_name" content="Jon Sharp, logged on the web" />

	<link type="text/plain" rel="author" href="http://jonsharp.net/humans.txt" />

 Jon Sharp, logged on the web

Navigation

Search

Contact

Home

                Projects

Gameboy

Laptop Art

Video Game Development

                Blog

Blog Archive

                Misc

Pinhoti Trail

Sun

Wishlist

Refurbing my own PowerBook battery

When I inherited my PowerBook G3 Lombard, the battery I inherited yielded less than 1 hour of battery life.  I didn't mind this, because it still allowed me to be somewhat mobile and untethered from power.  It didn't take long, however, for the battery to fail entirely, leaving me with absolutely no battery life.  Well, after running across http://www.wwc.edu/~frohro/Powerbook/Pismo/Battery/ recently for how to replace the cells inside the PowerBook battery pack myself, I decided to try it.  I ordered 9 18650 Lithium Ion cells from http://www.batteryspace.com and walked through the instructions. It was a bit tedious, and I had to be careful, but it was fairly straightforward and now I have a battery that gives me nearly 5 hours of battery life on my overclocked (466Mhz) Lombard!  I'm very excited about this as I intend to install this in my Jeep as some sort of voice-controlled car computer.

				<time class="icon-calendar pr20" datetime="2005-09-27" itemprop="datePublished"> 2005-09-27</time>

« Apple's Mighty Mouse

Archive

Overclocked Macintosh Server G3 running Darwin 8.0.1 »

        

About This Site

              Personal website of Jon Sharp - a Seventh-day Adventist Christian, family man, lover of the outdoors, technology leader, enterprise architect, embedded systems engineer, and retrocomputing enthusiast.
              More ›

Services

                    Contact

                    RSS

                    Atom

                    sitemap.xml

Thank you

                  Icons by Daniel Bruce

                  Built on Foundation

                  Using Backstretch by Scott Robbin

              Created with ♥
              by Jon Sharp
              with Jekyll
              based on Feeling Responsive.


text:
package net.liftweb
package json

import java.lang.reflect.{Constructor => JConstructor, Type, InvocationTargetException}
import java.lang.{Integer => JavaInteger, Long => JavaLong, Short => JavaShort, Byte => JavaByte, Boolean => JavaBoolean, Double => JavaDouble, Float => JavaFloat}
import java.util.Date
import java.sql.Timestamp
import scala.reflect.Manifest

/** Function to extract values from JSON AST using case classes.
 *
 *  See: ExtractionExamples.scala
 */
object Extraction {
  import Meta._
  import Meta.Reflection._

  /** Extract a case class from JSON.
   * @see net.liftweb.json.JsonAST.JValue#extract
   * @throws MappingException is thrown if extraction fails
   */
  def extract[A](json: JValue)(implicit formats: Formats, mf: Manifest[A]): A = {
    def allTypes(mf: Manifest[_]): List[Class[_]] = mf.runtimeClass :: (mf.typeArguments flatMap allTypes)

    try {
      val types = allTypes(mf)
      extract0(json, types.head, types.tail).asInstanceOf[A]
    } catch {
      case e: MappingException => throw e
      case e: Exception => throw new MappingException("unknown error", e)
    }
  }

  /** Extract a case class from JSON.
   * @see net.liftweb.json.JsonAST.JValue#extract
   */
  def extractOpt[A](json: JValue)(implicit formats: Formats, mf: Manifest[A]): Option[A] =
    try { Some(extract(json)(formats, mf)) } catch { case _: MappingException => None }

  /** Decompose a case class into JSON.
   *

   * Example:

   * case class Person(name: String, age: Int)
   * implicit val formats = net.liftweb.json.DefaultFormats
   * Extraction.decompose(Person("joe", 25)) == JObject(JField("age",JInt(25)) :: JField("name",JString("joe")) :: Nil)
   *

   */
  def decompose(a: Any)(implicit formats: Formats): JValue = {
    def prependTypeHint(clazz: Class[_], o: JObject) =
      JObject(JField(formats.typeHintFieldName, JString(formats.typeHints.hintFor(clazz))) :: o.obj)

    def mkObject(clazz: Class[_], fields: List[JField]) = formats.typeHints.containsHint_?(clazz) match {
      case true  => prependTypeHint(clazz, JObject(fields))
      case false => JObject(fields)
    }

    val serializer = formats.typeHints.serialize
    val any = a.asInstanceOf[AnyRef]
    if (formats.customSerializer(formats).isDefinedAt(a)) {
      formats.customSerializer(formats)(a)
    } else if (!serializer.isDefinedAt(a)) {
      any match {
        case null => JNull
        case x: JValue => x
        case x if primitive_?(x.getClass) => primitive2jvalue(x)(formats)
        case x: Map[_, _] => JObject((x map { case (k: String, v) => JField(k, decompose(v)) }).toList)
        case x: Iterable[_] => JArray(x.toList map decompose)
        case x if (x.getClass.isArray) => JArray(x.asInstanceOf[Array[_]].toList map decompose)
        case x: Option[_] => x.flatMap[JValue] { y => Some(decompose(y)) }.getOrElse(JNothing)
        case x: Product if formats.tuplesAsArrays && tuple_?(x.getClass) =>
          JArray(x.productIterator.toList.map(decompose))
        case x =>
          val fields = getDeclaredFields(x.getClass)
          val constructorArgs = primaryConstructorArgs(x.getClass).map{ case (name, _) => (name,fields.get(name)) }
          constructorArgs.collect { case (name, Some(f)) =>
            f.setAccessible(true)
            JField(unmangleName(name), decompose(f get x))
          } match {
            case args =>
              val fields = formats.fieldSerializer(x.getClass).map { serializer =>
                Reflection.fields(x.getClass).map {
                  case (mangledName, _) =>
                    val n = Meta.unmangleName(mangledName)
                    val fieldVal = Reflection.getField(x, mangledName)
                    val s = serializer.serializer orElse Map((n, fieldVal) -> Some(n, fieldVal))
                    s((n, fieldVal)).map { case (name, value) => JField(name, decompose(value)) }
                      .getOrElse(JField(n, JNothing))
                }
              } getOrElse Nil
              val uniqueFields = fields filterNot (f => args.find(_.name == f.name).isDefined)
              mkObject(x.getClass, uniqueFields ++ args)
          }
      }
    } else prependTypeHint(any.getClass, serializer(any))
  }

  /** Flattens the JSON to a key/value map.
   */
  def flatten(json: JValue): Map[String, String] = {
    def escapePath(str: String) = str

    def flatten0(path: String, json: JValue): Map[String, String] = {
      json match {
        case JNothing | JNull    => Map()
        case JString(s)          => Map(path -> ("\"" + JsonAST.quote(s) + "\""))
        case JDouble(num)        => Map(path -> num.toString)
        case JInt(num)           => Map(path -> num.toString)
        case JBool(value)        => Map(path -> value.toString)
        case JObject(obj)        => obj.foldLeft(Map[String, String]()) { case (map, JField(name, value)) =>
          map ++ flatten0(path + "." + escapePath(name), value)
        }
        case JArray(arr)         => arr.length match {
          case 0 => Map(path -> "[]")
          case _ => arr.foldLeft((Map[String, String](), 0)) {
                      (tuple, value) => (tuple._1 ++ flatten0(path + "[" + tuple._2 + "]", value), tuple._2 + 1)
                    }._1
        }
      }
    }

    flatten0("", json)
  }

  /** Unflattens a key/value map to a JSON object.
   */
  def unflatten(map: Map[String, String]): JValue = {
    import scala.util.matching.Regex

    def extractValue(value: String): JValue = value.toLowerCase match {
      case ""      => JNothing
      case "null"  => JNull
      case "true"  => JBool(true)
      case "false" => JBool(false)
      case "[]"    => JArray(Nil)
      case x @ _   =>
        if (value.charAt(0).isDigit) {
          if (value.indexOf('.') == -1) JInt(BigInt(value))
          else JDouble(JsonParser.parseDouble(value))
        }
        else JString(JsonParser.unquote(value.substring(1)))
    }

    def submap(prefix: String): Map[String, String] =
      Map(
        map.filter(t => t._1 == prefix || t._1.startsWith(prefix + ".") || t._1.startsWith(prefix + "[")).map(
          t => (t._1.substring(prefix.length), t._2)
        ).toList.toArray: _*
      )

    val ArrayProp = new Regex("""^(\.([^\.\[]+))\[(\d+)\].*$""")
    val ArrayElem = new Regex("""^(\[(\d+)\]).*$""")
    val OtherProp = new Regex("""^(\.([^\.\[]+)).*$""")

    val uniquePaths = map.keys.foldLeft[Set[String]](Set()) {
      (set, key) =>
        key match {
          case ArrayProp(p, f, i) => set + p
          case OtherProp(p, f)    => set + p
          case ArrayElem(p, i)    => set + p
          case x @ _              => set + x
        }
    }.toList.sortWith(_ < _) // Sort is necessary to get array order right

    uniquePaths.foldLeft[JValue](JNothing) { (jvalue, key) =>
      jvalue.merge(key match {
        case ArrayProp(p, f, i) => JObject(List(JField(f, unflatten(submap(key)))))
        case ArrayElem(p, i)    => JArray(List(unflatten(submap(key))))
        case OtherProp(p, f)    => JObject(List(JField(f, unflatten(submap(key)))))
        case ""                 => extractValue(map(key))
      })
    }
  }

  private[this] def mkMapping(clazz: Class[_], typeArgs: Seq[Class[_]])(implicit formats: Formats): Meta.Mapping = {
    if (clazz == classOf[Option[_]] || clazz == classOf[List[_]] || clazz == classOf[Set[_]] || clazz.isArray) {
      Col(TypeInfo(clazz, None), mkMapping(typeArgs.head, typeArgs.tail))
    } else if (clazz == classOf[Map[_, _]]) {
      Dict(mkMapping(typeArgs.tail.head, typeArgs.tail.tail))
    } else if (formats.tuplesAsArrays && tuple_?(clazz)) {
      val childMappings = typeArgs.map(c => mkMapping(c, Nil)).toList
      HCol(TypeInfo(clazz, None), childMappings)
    } else {
      mappingOf(clazz, typeArgs)
    }
  }

  private def extract0(json: JValue, clazz: Class[_], typeArgs: Seq[Class[_]])
                      (implicit formats: Formats): Any = {
    val mapping = mkMapping(clazz, typeArgs)
    extract0(json, mapping)
  }

  def extract(json: JValue, target: TypeInfo)(implicit formats: Formats): Any =
    extract0(json, mappingOf(target.clazz))

  private def extract0(json: JValue, mapping: Mapping)(implicit formats: Formats): Any = {
    def newInstance(constructor: Constructor, json: JValue) = {
      def findBestConstructor = {
        if (constructor.choices.size == 1) {
          constructor.choices.head // optimized common case
        } else {
          val argNames = json match {
            case JObject(fs) => fs.map(_.name)
            case x => Nil
          }
          constructor.bestMatching(argNames)
            .getOrElse(fail("No constructor for type " + constructor.targetType.clazz + ", " + json))
        }
      }

      def setFields(a: AnyRef, json: JValue, constructor: JConstructor[_]) = json match {
        case o: JObject =>
          formats.fieldSerializer(a.getClass).map { serializer =>
            val constructorArgNames =
              Reflection.constructorArgs(a.getClass, constructor, formats.parameterNameReader, None).map(_._1).toSet
            val jsonFields = o.obj.map { f =>
              val JField(n, v) = (serializer.deserializer orElse Map(f -> f))(f)
              (n, (n, v))
            }.toMap

            val fieldsToSet =
              Reflection.fields(a.getClass).filterNot(f => constructorArgNames.contains(f._1))

            fieldsToSet.foreach { case (name, typeInfo) =>
              jsonFields.get(name).foreach { case (n, v) =>
                val typeArgs = typeInfo.parameterizedType
                  .map(_.getActualTypeArguments.map(_.asInstanceOf[Class[_]]).toList.zipWithIndex
                    .map { case (t, idx) =>
                      if (t == classOf[java.lang.Object]) ScalaSigReader.readField(name, a.getClass, idx)
                      else t
                    })
                val value = extract0(v, typeInfo.clazz, typeArgs.getOrElse(Nil))
                Reflection.setField(a, n, value)
              }
            }
          }
          a
        case _ => a
      }

      def instantiate = {
        val c = findBestConstructor
        val jconstructor = c.constructor
        val args = c.args.map(a => build(json \ a.path, a))
        try {
          if (jconstructor.getDeclaringClass == classOf[java.lang.Object])
            fail("No information known about type")

          val instance = jconstructor.newInstance(args.map(_.asInstanceOf[AnyRef]).toArray: _*)
          setFields(instance.asInstanceOf[AnyRef], json, jconstructor)
        } catch {
          case exception: Exception =>
            exception match {
              case matchedException @ (_:IllegalArgumentException | _:InstantiationException) =>
                fail("Parsed JSON values do not match with class constructor\nargs=" +
                     args.mkString(",") + "\narg types=" + args.map(a => if (a != null)
                       a.asInstanceOf[AnyRef].getClass.getName else "null").mkString(",") +
                     "\nconstructor=" + jconstructor, matchedException)

              case exceptionThrownInConstructor: InvocationTargetException =>
                fail("An exception was thrown in the class constructor during extraction", exceptionThrownInConstructor)

              case unmatchedException =>
                throw unmatchedException
            }
        }
      }

      def mkWithTypeHint(typeHint: String, fields: List[JField], typeInfo: TypeInfo) = {
        val obj = JObject(fields filterNot (_.name == formats.typeHintFieldName))
        val deserializer = formats.typeHints.deserialize
        if (!deserializer.isDefinedAt(typeHint, obj)) {
          val concreteClass = formats.typeHints.classFor(typeHint) getOrElse fail("Do not know how to deserialize '" + typeHint + "'")
          val typeArgs = typeInfo.parameterizedType
            .map(_.getActualTypeArguments.toList.map(Meta.rawClassOf)).getOrElse(Nil)
          build(obj, mappingOf(concreteClass, typeArgs))
        } else deserializer(typeHint, obj)
      }

      val custom = formats.customDeserializer(formats)
      if (custom.isDefinedAt(constructor.targetType, json)) {
        custom(constructor.targetType, json)
      } else {
        json match {
          case JNull =>
            null

          case JObject(TypeHint(t, fs)) =>
            mkWithTypeHint(t, fs, constructor.targetType)

          case _ =>
            instantiate
        }
      }
    }

    object TypeHint {
      def unapply(fs: List[JField]): Option[(String, List[JField])] =
        if (formats.typeHints == NoTypeHints) None
        else {
          val grouped = fs groupBy (_.name == formats.typeHintFieldName)
          if (grouped.isDefinedAt(true))
            Some((grouped(true).head.value.values.toString, grouped.get(false).getOrElse(Nil)))
          else None
        }
    }

    def newPrimitive(elementType: Class[_], elem: JValue) = convert(elem, elementType, formats)

    def newCollection(root: JValue, m: Mapping, constructor: Array[_] => Any) = {
      val array: Array[_] = root match {
        case JArray(arr)      => arr.map(build(_, m)).toArray
        case JNothing | JNull => Array[AnyRef]()
        case x                => fail("Expected collection but got " + x + " for root " + root + " and mapping " + m)
      }

      constructor(array)
    }

    def newOption(root: JValue, m: Mapping) = {
      root match {
        case JNothing | JNull => None
        case x => Option(build(x, m))
      }
    }

    def newTuple(root: JValue, mappings: List[Mapping]): Any = {
      root match {
        case JArray(items) if items.nonEmpty && items.length <= tuples.length =>
          val builtItems: Seq[Object] = items.zip(mappings).map({
            case (item, mapping) =>
              build(item, mapping).asInstanceOf[Object]
          })
          val tupleIndex = items.length - 1

          val typedTupleConstructor = tupleConstructors.get(tupleIndex).getOrElse {
            throw new IllegalArgumentException(s"Cannot instantiate a tuple of length ${items.length} even though that should be a valid tuple length.")
          }
          typedTupleConstructor.newInstance(builtItems: _*)

        case JArray(items) =>
          throw new IllegalArgumentException("Cannot create a tuple of length " + items.length)

        case JObject(items) if items.forall(_.name.startsWith("_")) =>
          val sortedItems = items.sortWith { (i1, i2) =>
            val numerialName1 = i1.name.drop(1).toInt
            val numerialName2 = i2.name.drop(1).toInt

            numerialName1 < numerialName2
          }
          newTuple(JArray(sortedItems.map(_.value)), mappings)

        case x =>
          throw new IllegalArgumentException("Got unexpected while attempting to create tuples: " + x)
      }
    }

    def build(root: JValue, mapping: Mapping): Any = mapping match {
      case Value(targetType) =>
        convert(root, targetType, formats)

      case c: Constructor =>
        newInstance(c, root)

      case Cycle(targetType) =>
        build(root, mappingOf(targetType))

      case Arg(path, m, optional) =>
        mkValue(root, m, path, optional)

      case HCol(targetType, mappings) if formats.tuplesAsArrays =>
        val c = targetType.clazz
        if (tuples.find(_.isAssignableFrom(c)).isDefined) {
          newTuple(root, mappings)
        } else {
          fail("Expected tuple but found " + mappings)
        }

      case Col(targetType, m) =>
        val custom = formats.customDeserializer(formats)
        val c = targetType.clazz

        if (custom.isDefinedAt(targetType, root)) custom(targetType, root)
        else if (c == classOf[List[_]]) newCollection(root, m, a => List(a: _*))
        else if (c == classOf[Set[_]]) newCollection(root, m, a => Set(a: _*))
        else if (c.isArray) newCollection(root, m, mkTypedArray(c))
        else if (classOf[Seq[_]].isAssignableFrom(c)) newCollection(root, m, a => List(a: _*))
        else if (c == classOf[Option[_]]) newOption(root, m)
        else fail("Expected collection but got " + m + " for class " + c)
      case Dict(m) => root match {
        case JObject(xs) => Map(xs.map(x => (x.name, build(x.value, m))): _*)
        case x => fail("Expected object but got " + x)
      }
    }

    def mkTypedArray(c: Class[_])(a: Array[_]) = {
      import java.lang.reflect.Array.{newInstance => newArray}

      a.foldLeft((newArray(c.getComponentType, a.length), 0)) { (tuple, e) => {
        java.lang.reflect.Array.set(tuple._1, tuple._2, e); (tuple._1, tuple._2 + 1)
      }}._1
    }

    def mkList(root: JValue, m: Mapping) = root match {
      case JArray(arr) => arr.map(build(_, m))
      case JNothing | JNull => Nil
      case x => fail("Expected array but got " + x)
    }

    def mkValue(root: JValue, mapping: Mapping, path: String, optional: Boolean) = {
      if (optional && root == JNothing) {
        None
      } else {
        try {
          val x = build(root, mapping)
          if (optional) Option(x) else x
        } catch {
          case e @ MappingException(msg, _) =>
            if (optional && (root == JNothing || root == JNull)) {
              None
            } else {
              fail("No usable value for " + path + "\n" + msg, e)
            }
        }
      }
    }

    build(json, mapping)
  }

  private def convert(json: JValue, targetType: Class[_], formats: Formats): Any = json match {
    case JInt(x) if (targetType == classOf[Int]) => x.intValue
    case JInt(x) if (targetType == classOf[JavaInteger]) => new JavaInteger(x.intValue)
    case JInt(x) if (targetType == classOf[BigInt]) => x
    case JInt(x) if (targetType == classOf[Long]) => x.longValue
    case JInt(x) if (targetType == classOf[JavaLong]) => new JavaLong(x.longValue)
    case JInt(x) if (targetType == classOf[Double]) => x.doubleValue
    case JInt(x) if (targetType == classOf[JavaDouble]) => new JavaDouble(x.doubleValue)
    case JInt(x) if (targetType == classOf[Float]) => x.floatValue
    case JInt(x) if (targetType == classOf[JavaFloat]) => new JavaFloat(x.floatValue)
    case JInt(x) if (targetType == classOf[Short]) => x.shortValue
    case JInt(x) if (targetType == classOf[JavaShort]) => new JavaShort(x.shortValue)
    case JInt(x) if (targetType == classOf[Byte]) => x.byteValue
    case JInt(x) if (targetType == classOf[JavaByte]) => new JavaByte(x.byteValue)
    case JInt(x) if (targetType == classOf[String]) => x.toString
    case JInt(x) if (targetType == classOf[Number]) => x.longValue
    case JDouble(x) if (targetType == classOf[Double]) => x
    case JDouble(x) if (targetType == classOf[JavaDouble]) => new JavaDouble(x)
    case JDouble(x) if (targetType == classOf[Float]) => x.floatValue
    case JDouble(x) if (targetType == classOf[JavaFloat]) => new JavaFloat(x.floatValue)
    case JDouble(x) if (targetType == classOf[String]) => x.toString
    case JDouble(x) if (targetType == classOf[Int]) => x.intValue
    case JDouble(x) if (targetType == classOf[Long]) => x.longValue
    case JDouble(x) if (targetType == classOf[Number]) => x
    case JString(s) if (targetType == classOf[String]) => s
    case JString(s) if (targetType == classOf[Symbol]) => Symbol(s)
    case JString(s) if (targetType == classOf[Date]) => formats.dateFormat.parse(s).getOrElse(fail("Invalid date '" + s + "'"))
    case JString(s) if (targetType == classOf[Timestamp]) => new Timestamp(formats.dateFormat.parse(s).getOrElse(fail("Invalid date '" + s + "'")).getTime)
    case JBool(x) if (targetType == classOf[Boolean]) => x
    case JBool(x) if (targetType == classOf[JavaBoolean]) => new JavaBoolean(x)
    case j: JValue if (targetType == classOf[JValue]) => j
    case j: JObject if (targetType == classOf[JObject]) => j
    case j: JArray if (targetType == classOf[JArray]) => j
    case JNull => null
    case JNothing =>
      fail("Did not find value which can be converted into " + targetType.getName)
    case _ =>
      val custom = formats.customDeserializer(formats)
      val typeInfo = TypeInfo(targetType, None)

      if (custom.isDefinedAt(typeInfo, json)) {
        custom(typeInfo, json)
      } else {
        fail("Do not know how to convert " + json + " into " + targetType)
      }
  }
}


text:
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Security;
using System.Text;

using Khronos;

// ReSharper disable CheckNamespace
// ReSharper disable InconsistentNaming
// ReSharper disable JoinDeclarationAndInitializer

namespace OpenGL
{
	public partial class Gl
	{
		/// <summary>
		/// [GL] Value of GL_TEXTURE_MEMORY_LAYOUT_INTEL symbol.
		/// </summary>
		[RequiredByFeature("GL_INTEL_map_texture")]
		public const int TEXTURE_MEMORY_LAYOUT_INTEL = 0x83FF;

		/// <summary>
		/// [GL] Value of GL_LAYOUT_DEFAULT_INTEL symbol.
		/// </summary>
		[RequiredByFeature("GL_INTEL_map_texture")]
		public const int LAYOUT_DEFAULT_INTEL = 0;

		/// <summary>
		/// [GL] Value of GL_LAYOUT_LINEAR_INTEL symbol.
		/// </summary>
		[RequiredByFeature("GL_INTEL_map_texture")]
		public const int LAYOUT_LINEAR_INTEL = 1;

		/// <summary>
		/// [GL] Value of GL_LAYOUT_LINEAR_CPU_CACHED_INTEL symbol.
		/// </summary>
		[RequiredByFeature("GL_INTEL_map_texture")]
		public const int LAYOUT_LINEAR_CPU_CACHED_INTEL = 2;

		/// <summary>
		/// [GL] glSyncTextureINTEL: Binding for glSyncTextureINTEL.
		/// </summary>
		/// <param name="texture">
		/// A <see cref="T:uint"/>.
		/// </param>
		[RequiredByFeature("GL_INTEL_map_texture")]
		public static void SyncTextureINTEL(uint texture)
		{
			Debug.Assert(Delegates.pglSyncTextureINTEL != null, "pglSyncTextureINTEL not implemented");
			Delegates.pglSyncTextureINTEL(texture);
			LogCommand("glSyncTextureINTEL", null, texture			);
			DebugCheckErrors(null);
		}

		/// <summary>
		/// [GL] glUnmapTexture2DINTEL: Binding for glUnmapTexture2DINTEL.
		/// </summary>
		/// <param name="texture">
		/// A <see cref="T:uint"/>.
		/// </param>
		/// <param name="level">
		/// A <see cref="T:int"/>.
		/// </param>
		[RequiredByFeature("GL_INTEL_map_texture")]
		public static void UnmapTexture2DINTEL(uint texture, int level)
		{
			Debug.Assert(Delegates.pglUnmapTexture2DINTEL != null, "pglUnmapTexture2DINTEL not implemented");
			Delegates.pglUnmapTexture2DINTEL(texture, level);
			LogCommand("glUnmapTexture2DINTEL", null, texture, level			);
			DebugCheckErrors(null);
		}

		/// <summary>
		/// [GL] glMapTexture2DINTEL: Binding for glMapTexture2DINTEL.
		/// </summary>
		/// <param name="texture">
		/// A <see cref="T:uint"/>.
		/// </param>
		/// <param name="level">
		/// A <see cref="T:int"/>.
		/// </param>
		/// <param name="access">
		/// A <see cref="T:uint"/>.
		/// </param>
		/// <param name="stride">
		/// A <see cref="T:int[]"/>.
		/// </param>
		/// <param name="layout">
		/// A <see cref="T:int[]"/>.
		/// </param>
		[RequiredByFeature("GL_INTEL_map_texture")]
		public static IntPtr MapTexture2DINTEL(uint texture, int level, uint access, int[] stride, int[] layout)
		{
			Debug.Assert(stride.Length >= 1);
			Debug.Assert(layout.Length >= 1);
			IntPtr retValue;

			unsafe {
				fixed (int* p_stride = stride)
				fixed (int* p_layout = layout)
				{
					Debug.Assert(Delegates.pglMapTexture2DINTEL != null, "pglMapTexture2DINTEL not implemented");
					retValue = Delegates.pglMapTexture2DINTEL(texture, level, access, p_stride, p_layout);
					LogCommand("glMapTexture2DINTEL", retValue, texture, level, access, stride, layout					);
				}
			}
			DebugCheckErrors(retValue);

			return (retValue);
		}

		internal static unsafe partial class Delegates
		{
			[RequiredByFeature("GL_INTEL_map_texture")]
			[SuppressUnmanagedCodeSecurity]
			internal delegate void glSyncTextureINTEL(uint texture);

			[RequiredByFeature("GL_INTEL_map_texture")]
			[ThreadStatic]
			internal static glSyncTextureINTEL pglSyncTextureINTEL;

			[RequiredByFeature("GL_INTEL_map_texture")]
			[SuppressUnmanagedCodeSecurity]
			internal delegate void glUnmapTexture2DINTEL(uint texture, int level);

			[RequiredByFeature("GL_INTEL_map_texture")]
			[ThreadStatic]
			internal static glUnmapTexture2DINTEL pglUnmapTexture2DINTEL;

			[RequiredByFeature("GL_INTEL_map_texture")]
			[SuppressUnmanagedCodeSecurity]
			internal delegate IntPtr glMapTexture2DINTEL(uint texture, int level, uint access, int* stride, int* layout);

			[RequiredByFeature("GL_INTEL_map_texture")]
			[ThreadStatic]
			internal static glMapTexture2DINTEL pglMapTexture2DINTEL;

		}
	}

}