text:
/**
 * use postgis and knowledge of freeway line layer to compute absolute
 * postmile for WIM stations.
 *
 *
 */

// strategy, pre-parallelizing:
// get WIM station
// place on correct freeway
// compute postmile from county line, and from start of freeway
// (review HPMS code to see how I did that there)
//
// I expect that WIM postmile (county) will be off from that computed
// via postgis freeway length.  So adjust absolute postmile?
//
// I could find nearest VDS on link, but there might not be such a thing
//
// The problem is possibly flipping the order of VDS
//
// What I could also do is just use MRB, pre and post detectors, plus
// distance, to figure out the absolute post mile
//
// So.  for those WIM sites that have a pre or post VDS site, use Pre
// or Post site, plus length of segment from WIM site to VDS site, to
// determine the postmile of WIM site.
//
// For those WIM sites without a pre or post VDS site, use county
// postmile plus length of roadway from start to county line.
//

var pg = require('pg')
var _ = require('lodash')

function ca_postmile_to_abs_postmile(options){
    var dbname = options.db || 'geocoder'
    var host = options.host|| '127.0.0.1';
    var username = options.username
    var password = options.password
    var port = options.port || 5432;
    var connectionString = "pg://"+username+":"+password+"@"+host+":"+port+"/"+dbname;
    // the service accepts a ca postmile (county line based miles) and
    // a highway, and a county, and returns the absolue mile post for
    // that location
    var validate_county = /\d\d\d/;
    var digits = /(\d*)/
    var doit = function(req,cb){
        if( req.county === undefined) return cb('req.county is required')
        if( ! validate_county.test(req.county )) return cb('req.county must be three digit fips code')
        var county = "'"+req.county+"'"

        if(req.ca_pm === undefined) return cb('req.ca_pm required (the post mile from the county border, as a number)')
        var ca_pm = +req.ca_pm
        if(_.isNaN(ca_pm) ) return cb(' req.ca_pm required (the post mile from the county border, as a number)')

        if(req.route === undefined) return cb('req.route is required (number of the route being matched)')
        var result = digits.exec(req.route)
        var route = result[1]
        if(route === undefined ) return cb('req.route is required (number of the route being matched)')
        route = +route
        if(_.isNaN(route)) cb('req.route is required (number of the route being matched)')

        // ready to go

        // note that the query function is hardcoded, for now
        var query = 'select osm.ca_pm_abs_pm('
                  + [route,ca_pm,county].join(',')
                  +')'
        //console.log(query)
        pg.connect(connectionString,function(err,client,done){
            if(err){
                console.log('connection err '+JSON.stringify(err))
                done()
                return cb(err)
            }
            var result = client.query(query)
            var once = false
            result.on('row',function(row){
                if(!once){
                    cb(null,+row.ca_pm_abs_pm)
                    once = true
                }else{
                    throw new Error('got more than one row from sql query')
                }
                return null
            })
            result.on('end',function(result){
                done()
                return null
            })
            result.on('error',function(err){
                //done(1)
                cb(err)
                return null
            })
            return null
        })

        return null;
    }

    doit.done = function(){
        pg.end()
        return null;
    }
    return doit
}

function abs_postmile_dead_reckoning(options){
    var dbname = options.db || 'spatialvds'
    var host = options.host|| '127.0.0.1';
    var username = options.username
    var password = options.password
    var port = options.port || 5432;
    var connectionString = "pg://"+username+":"+password+"@"+host+":"+port+"/"+dbname;
    // the service accepts a ca postmile (county line based miles) and
    // a highway, and a county, and returns the absolue mile post for
    // that location
    var digits = /(\d+)/
    var validate_county = /\d\d\d/;

    var doit = function(req,cb){
        if( req.county === undefined) return cb('req.county is required')
        if( ! validate_county.test(req.county )) return cb('req.county must be three digit fips code')
        var county = req.county

        if(req.wim_id === undefined) return cb('req.wim_id is a required param (number of the wim site)')
        var result = digits.exec(req.wim_id)
        var wim_id = result[1]
        if(wim_id === undefined ) return cb('req.wim_id needs to contain wim id number')
        wim_id = +wim_id
        if(_.isNaN(wim_id)) cb('req.wim_id is required (number of the wim site)')

        var query = ["with "
                    ,"wim_info as ("
                    ,"    select w.site_no,wf.freeway_id as wim_freeway,w.cal_pm,geom as wim_geom"
                    ,"    from wim_stations w"
                    ,"    join wim_points_4326 wp on(w.site_no =wp.wim_id)"
                    ,"    join geom_points_4326 using (gid)"
                    ,"    join wim_freeway wf on(wf.wim_id=w.site_no)"
                    ,"    where site_no="+wim_id
                    ,")"
                    ,"select st_asgeojson(wim_geom,12,2) as geojson,"
                    ,"       tempseg.wim_abs_pm(wim_freeway,"
                    ,"                          st_asewkt(wim_geom))"
                    ,"                          as abs_pm"
                    ,"from wim_info"].join('\n')

        // ready to go
        //console.log(query)
        pg.connect(connectionString,function(err,client,done){
            if(err){
                console.log('connection err '+JSON.stringify(err))
                done()
                return cb(err)
            }
            var result = client.query(query)
            var once = false
            result.on('row',function(row){
                if(!once){
                    cb(null,{'geojson':row.geojson
                            ,'abs_pm':+row.abs_pm})
                    once = true
                }else{
                    throw new Error('got more than one row from sql query')
                }
                return null
            })
            result.on('end',function(result){
                if(!once){
                    once=true
                    console.log('firing callback with no rows')
                    cb('no rows')
                }
                done()
                return null
            })
            result.on('error',function(err){
                //done(1)
                if(!once){
                    once=true
                    console.log('firing callback with error')
                    cb(err)
                }
                return null
            })
            return null
        })

        return null;
    }

    doit.done = function(){
        pg.end()
        return null;
    }
    return doit
}

function abs_postmile_vds_multiline(options){
    var dbname = options.db || 'spatialvds'
    var host = options.host|| '127.0.0.1';
    var username = options.username
    var password = options.password
    var port = options.port || 5432;
    var connectionString = "pg://"+username+":"+password+"@"+host+":"+port+"/"+dbname;
    // the service accepts a ca postmile (county line based miles) and
    // a highway, and a county, and returns the absolue mile post for
    // that location
    var digits = /(\d+)/
    var validate_county = /\d\d\d/;

    var doit = function(req,cb){
        if( req.county === undefined) return cb('req.county is required')
        if( ! validate_county.test(req.county )) return cb('req.county must be three digit fips code')
        var county = req.county

        if(req.wim_id === undefined) return cb('req.wim_id is a required param (number of the wim site)')
        var result = digits.exec(req.wim_id)
        var wim_id = result[1]
        if(wim_id === undefined ) return cb('req.wim_id needs to contain wim id number')
        wim_id = +wim_id
        if(_.isNaN(wim_id)) cb('req.wim_id is required (number of the wim site)')

        var query = ["with "
                    ,"    cnty as ("
                    ,"    select cf.name,"
                    ,"        st_transform(st_buffer(st_transform(the_geom,32611),5),4326)"
                    ,"        as the_geom"
                    ,"    from carb_counties_aligned_03 cc"
                    ,"    join counties_fips cf on (lower(cf.name)=lower(cc.name))"
                    ,"    where fips='06"+county+"'"
                    ,"),"
                    ,"wim_info as ("
                    ,"    select w.site_no,wf.freeway_id as wim_freeway,SUBSTRING(w.cal_pm, '(\\d+\\.?\\d*){1,1}') as wim_cal_pm,geom as wim_geom"
                    ,"    from wim_stations w"
                    ,"    join wim_points_4326 wp on(w.site_no =wp.wim_id)"
                    ,"    join geom_points_4326 using (gid)"
                    ,"    join wim_freeway wf on(wf.wim_id=w.site_no)"
                    ,"    where site_no="+wim_id
                    ,"),"
                    ,"vds_info as ("
                    ,"  select vds.vds_id,vds.abs_pm as vds_abs_pm, SUBSTRING(vds.cal_pm,'(\\d+\\.?\\d*){1,1}') as vds_cal_pm,geom as vds_geom,"
                    ,"    w.*, st_length(st_transform(st_makeline(geom,wim_geom),32611))*(0.621371/1000) as dist"
                    ,"    from vds_geoview_full vds"
                    ,"    join cnty on (st_contains(cnty.the_geom,vds.geom))"
                    ,"    join wim_info w on (vds.freeway_id = w.wim_freeway)"
                    ,"    where vds.abs_pm is not null"
                    ,"    order by dist"
                    ,"    limit 1"
                    ,")"
                    ,"select st_asgeojson(wim_geom,12,2) as geojson,"
                    ,"       case when wim_cal_pm > vds_cal_pm then vds_abs_pm + dist"
                    ,"            else vds_abs_pm - dist"
                    ,"            end as abs_pm"
                    ,"from vds_info"].join('\n')

        // ready to go
        //console.log(query)
        pg.connect(connectionString,function(err,client,done){
            if(err){
                console.log('connection err '+JSON.stringify(err))
                done()
                return cb(err)
            }
            var result = client.query(query)
            var once = false
            result.on('row',function(row){
                if(!once){
                    cb(null,{'geojson':row.geojson
                            ,'abs_pm':+row.abs_pm})
                    once = true
                }else{
                    throw new Error('got more than one row from sql query')
                }
                return null
            })
            result.on('end',function(result){
                if(!once){
                    once=true
                    console.log('firing callback with no rows')
                    cb('no rows')
                }
                done()
                return null
            })
            result.on('error',function(err){
                //done(1)
                if(!once){
                    once=true
                    console.log('firing callback with error')
                    cb(err)
                }
                return null
            })
            return null
        })

        return null;
    }

    doit.done = function(){
        pg.end()
        return null;
    }
    return doit
}
function abs_postmile_based_on_vds_abs_pm(options){
    var dbname = options.db || 'spatialvds'
    var host = options.host|| '127.0.0.1';
    var username = options.username
    var password = options.password
    var port = options.port || 5432;
    var connectionString = "pg://"+username+":"+password+"@"+host+":"+port+"/"+dbname;
    // the service accepts a ca postmile (county line based miles) and
    // a highway, and a county, and returns the absolue mile post for
    // that location
    var digits = /(\d+)/
    var validate_county = /\d\d\d/;

    var doit = function(req,cb){
        if( req.county === undefined) return cb('req.county is required')
        if( ! validate_county.test(req.county )) return cb('req.county must be three digit fips code')
        var county = req.county

        if(req.wim_id === undefined) return cb('req.wim_id is a required param (number of the wim site)')
        var result = digits.exec(req.wim_id)
        var wim_id = result[1]
        if(wim_id === undefined ) return cb('req.wim_id needs to contain wim id number')
        wim_id = +wim_id
        if(_.isNaN(wim_id)) cb('req.wim_id is required (number of the wim site)')

        var query = ["with "
                    ,"    cnty as ("
                    ,"    select cf.name,"
                    ,"        st_transform(st_buffer(st_transform(the_geom,32611),5),4326)"
                    ,"        as the_geom"
                    ,"    from carb_counties_aligned_03 cc"
                    ,"    join counties_fips cf on (lower(cf.name)=lower(cc.name))"
                    ,"    where fips='06"+county+"'"
                    ,"),"
                    ,"wim_info as ("
                    ,"    select w.site_no,wf.freeway_id as wim_freeway,w.cal_pm,geom as wim_geom"
                    ,"    from wim_stations w"
                    ,"    join wim_points_4326 wp on(w.site_no =wp.wim_id)"
                    ,"    join geom_points_4326 using (gid)"
                    ,"    join wim_freeway wf on(wf.wim_id=w.site_no)"
                    ,"    where site_no="+wim_id
                    ,"),"
                    ,"vds_info as ("
                    ,"    select vds.vds_id,vds.abs_pm as vds_abs_pm,geom as vds_geom,w.*,st_distance(geom,w.wim_geom) as dist"
                    ,"    from vds_geoview_full vds"
                    ,"    join cnty on (st_contains(cnty.the_geom,vds.geom))"
                    ,"    join wim_info w on (vds.freeway_id = w.wim_freeway)"
                    ,"    where vds.abs_pm is not null"
                    ,"    order by dist"
                    ,"    limit 1"
                    ,")"
                    ,"select st_asgeojson(wim_geom,12,2) as geojson,"
                    ,"       tempseg.wim_abs_pm(wim_freeway,"
                    ,"                          st_asewkt(wim_geom),"
                    ,"                          st_asewkt(vds_geom),"
                    ,"                          vds_abs_pm) as abs_pm"
                    ,"from vds_info"].join('\n')

        // ready to go
        //console.log(query)
        pg.connect(connectionString,function(err,client,done){
            if(err){
                console.log('connection err '+JSON.stringify(err))
                done()
                return cb(err)
            }
            var result = client.query(query)
            var once = false
            result.on('row',function(row){
                if(!once){
                    cb(null,{'geojson':row.geojson
                            ,'abs_pm':+row.abs_pm})
                    once = true
                }else{
                    throw new Error('got more than one row from sql query')
                }
                return null
            })
            result.on('end',function(result){
                if(!once){
                    once=true
                    console.log('firing callback with no rows')
                    cb('no rows')
                }
                done()
                return null
            })
            result.on('error',function(err){
                //done(1)
                if(!once){
                    once=true
                    console.log('firing callback with error')
                    cb(err)
                }
                return null
            })
            return null
        })

        return null;
    }

    doit.done = function(){
        pg.end()
        return null;
    }
    return doit
}

function get_geojson(options){
    var dbname = options.db || 'spatialvds'
    var host = options.host|| '127.0.0.1';
    var username = options.username
    var password = options.password
    var port = options.port || 5432;
    var connectionString = "pg://"+username+":"+password+"@"+host+":"+port+"/"+dbname;
    // the service accepts a ca postmile (county line based miles) and
    // a highway, and a county, and returns the absolue mile post for
    // that location
    var digits = /(\d+)/
    var validate_county = /\d\d\d/;

    var doit = function(req,cb){
        if( req.county === undefined) return cb('req.county is required')
        if( ! validate_county.test(req.county )) return cb('req.county must be three digit fips code')
        var county = req.county

        if(req.wim_id === undefined) return cb('req.wim_id is a required param (number of the wim site)')
        var result = digits.exec(req.wim_id)
        var wim_id = result[1]
        if(wim_id === undefined ) return cb('req.wim_id needs to contain wim id number')
        wim_id = +wim_id
        if(_.isNaN(wim_id)) cb('req.wim_id is required (number of the wim site)')

        var query = ["with "
                    ,"    cnty as ("
                    ,"    select cf.name,"
                    ,"        st_transform(st_buffer(st_transform(the_geom,32611),5),4326)"
                    ,"        as the_geom"
                    ,"    from carb_counties_aligned_03 cc"
                    ,"    join counties_fips cf on (lower(cf.name)=lower(cc.name))"
                    ,"    where fips='06"+county+"'"
                    ,"),"
                    ,"wim_info as ("
                    ,"    select w.site_no,wf.freeway_id as wim_freeway,w.cal_pm,geom as wim_geom"
                    ,"    from wim_stations w"
                    ,"    join wim_points_4326 wp on(w.site_no =wp.wim_id)"
                    ,"    join geom_points_4326 using (gid)"
                    ,"    join wim_freeway wf on(wf.wim_id=w.site_no)"
                    ,"    where site_no="+wim_id
                    ,")"
                    ,"select st_asgeojson(wim_geom,12,2) as geojson"
                    ,"from wim_info"].join('\n')

        // ready to go
        // console.log(query)
        pg.connect(connectionString,function(err,client,done){
            if(err){
                console.log('connection err '+JSON.stringify(err))
                done()
                return cb(err)
            }
            var result = client.query(query)
            var once = false
            result.on('row',function(row){
                if(!once){
                    cb(null,{'geojson':row.geojson})
                    once = true
                }else{
                    throw new Error('got more than one row from sql query')
                }
                return null
            })
            result.on('end',function(result){
                if(!once){
                    once=true
                    console.log('firing callback with no rows')
                    cb('no rows')
                }
                done()
                return null
            })
            result.on('error',function(err){
                //done(1)
                if(!once){
                    once=true
                    console.log('firing callback with error')
                    cb(err)
                }
                return null
            })
            return null
        })

        return null;
    }

    doit.done = function(){
        pg.end()
        return null;
    }
    return doit
}

exports.ca_postmile_to_abs_postmile=ca_postmile_to_abs_postmile
exports.abs_postmile_based_on_vds_abs_pm=abs_postmile_based_on_vds_abs_pm
exports.abs_postmile_vds_multiline=abs_postmile_vds_multiline
exports.abs_postmile_dead_reckoning=abs_postmile_dead_reckoning
exports.get_geojson=get_geojson


text:
#include "drmP.h"
#include "drm_crtc.h"
#include "drm_crtc_helper.h"
#include "drm_fb_helper.h"

#include "exynos_drm_drv.h"
#include "exynos_drm_fb.h"
#include "exynos_drm_gem.h"

#define to_exynos_fb(x)	container_of(x, struct exynos_drm_fb, fb)

/*
 * exynos specific framebuffer structure.
 *
 * @fb: drm framebuffer obejct.
 * @exynos_gem_obj: array of exynos specific gem object containing a gem object.
 */
struct exynos_drm_fb {
	struct drm_framebuffer		fb;
	struct exynos_drm_gem_obj	*exynos_gem_obj[MAX_FB_BUFFER];
};

static void exynos_drm_fb_destroy(struct drm_framebuffer *fb)
{
	struct exynos_drm_fb *exynos_fb = to_exynos_fb(fb);
	unsigned int i;

	DRM_DEBUG_KMS("%s\n", __FILE__);

	drm_framebuffer_cleanup(fb);

	for (i = 0; i < ARRAY_SIZE(exynos_fb->exynos_gem_obj); i++) {
		struct drm_gem_object *obj;

		if (exynos_fb->exynos_gem_obj[i] == NULL)
			continue;

		obj = &exynos_fb->exynos_gem_obj[i]->base;
		drm_gem_object_unreference_unlocked(obj);
	}

	kfree(exynos_fb);
	exynos_fb = NULL;
}

static int exynos_drm_fb_create_handle(struct drm_framebuffer *fb,
					struct drm_file *file_priv,
					unsigned int *handle)
{
	struct exynos_drm_fb *exynos_fb = to_exynos_fb(fb);

	DRM_DEBUG_KMS("%s\n", __FILE__);

	return drm_gem_handle_create(file_priv,
			&exynos_fb->exynos_gem_obj[0]->base, handle);
}

static int exynos_drm_fb_dirty(struct drm_framebuffer *fb,
				struct drm_file *file_priv, unsigned flags,
				unsigned color, struct drm_clip_rect *clips,
				unsigned num_clips)
{
	DRM_DEBUG_KMS("%s\n", __FILE__);

	/* TODO */

	return 0;
}

static struct drm_framebuffer_funcs exynos_drm_fb_funcs = {
	.destroy	= exynos_drm_fb_destroy,
	.create_handle	= exynos_drm_fb_create_handle,
	.dirty		= exynos_drm_fb_dirty,
};

struct drm_framebuffer *
exynos_drm_framebuffer_init(struct drm_device *dev,
			    struct drm_mode_fb_cmd2 *mode_cmd,
			    struct drm_gem_object *obj)
{
	struct exynos_drm_fb *exynos_fb;
	int ret;

	exynos_fb = kzalloc(sizeof(*exynos_fb), GFP_KERNEL);
	if (!exynos_fb) {
		DRM_ERROR("failed to allocate exynos drm framebuffer\n");
		return ERR_PTR(-ENOMEM);
	}

	ret = drm_framebuffer_init(dev, &exynos_fb->fb, &exynos_drm_fb_funcs);
	if (ret) {
		DRM_ERROR("failed to initialize framebuffer\n");
		return ERR_PTR(ret);
	}

	drm_helper_mode_fill_fb_struct(&exynos_fb->fb, mode_cmd);
	exynos_fb->exynos_gem_obj[0] = to_exynos_gem_obj(obj);

	return &exynos_fb->fb;
}

static struct drm_framebuffer *
exynos_user_fb_create(struct drm_device *dev, struct drm_file *file_priv,
		      struct drm_mode_fb_cmd2 *mode_cmd)
{
	struct drm_gem_object *obj;
	struct drm_framebuffer *fb;
	struct exynos_drm_fb *exynos_fb;
	int nr;
	int i;

	DRM_DEBUG_KMS("%s\n", __FILE__);

	obj = drm_gem_object_lookup(dev, file_priv, mode_cmd->handles[0]);
	if (!obj) {
		DRM_ERROR("failed to lookup gem object\n");
		return ERR_PTR(-ENOENT);
	}

	fb = exynos_drm_framebuffer_init(dev, mode_cmd, obj);
	if (IS_ERR(fb)) {
		drm_gem_object_unreference_unlocked(obj);
		return fb;
	}

	exynos_fb = to_exynos_fb(fb);
	nr = exynos_drm_format_num_buffers(fb->pixel_format);

	for (i = 1; i < nr; i++) {
		obj = drm_gem_object_lookup(dev, file_priv,
				mode_cmd->handles[i]);
		if (!obj) {
			DRM_ERROR("failed to lookup gem object\n");
			exynos_drm_fb_destroy(fb);
			return ERR_PTR(-ENOENT);
		}

		exynos_fb->exynos_gem_obj[i] = to_exynos_gem_obj(obj);
	}

	return fb;
}

struct exynos_drm_gem_buf *exynos_drm_fb_buffer(struct drm_framebuffer *fb,
						int index)
{
	struct exynos_drm_fb *exynos_fb = to_exynos_fb(fb);
	struct exynos_drm_gem_buf *buffer;

	DRM_DEBUG_KMS("%s\n", __FILE__);

	if (index >= MAX_FB_BUFFER)
		return NULL;

	buffer = exynos_fb->exynos_gem_obj[index]->buffer;
	if (!buffer)
		return NULL;

	DRM_DEBUG_KMS("vaddr = 0x%lx, dma_addr = 0x%lx\n",
			(unsigned long)buffer->kvaddr,
			(unsigned long)buffer->dma_addr);

	return buffer;
}

static void exynos_drm_output_poll_changed(struct drm_device *dev)
{
	struct exynos_drm_private *private = dev->dev_private;
	struct drm_fb_helper *fb_helper = private->fb_helper;

	if (fb_helper)
		drm_fb_helper_hotplug_event(fb_helper);
}

static const struct drm_mode_config_funcs exynos_drm_mode_config_funcs = {
	.fb_create = exynos_user_fb_create,
	.output_poll_changed = exynos_drm_output_poll_changed,
};

void exynos_drm_mode_config_init(struct drm_device *dev)
{
	dev->mode_config.min_width = 0;
	dev->mode_config.min_height = 0;

	/*
	 * set max width and height as default value(4096x4096).
	 * this value would be used to check framebuffer size limitation
	 * at drm_mode_addfb().
	 */
	dev->mode_config.max_width = 4096;
	dev->mode_config.max_height = 4096;

	dev->mode_config.funcs = &exynos_drm_mode_config_funcs;
}

redpajama_set_name: RedPajamaGithub


text:
@font-face {
  font-family: 'edoregular';
  src: url("fonts/edo-webfont.eot");
  src: url("fonts/edo-webfont.eot?#iefix") format("embedded-opentype"), url("fonts/edo-webfont.woff") format("woff"), url("fonts/edo-webfont.ttf") format("truetype"), url("fonts/edo-webfont.svg#edoregular") format("svg");
  font-weight: normal;
  font-style: normal; }

/** General page styling **/
html {
  background-color: #333;
  font-family: "Helvetica Neue Light", "Helvetica Neue", Arial, sans-serif;
  font-weight: 200;
  color: #fff;
  background: url("../imgs/splashscreen.jpg") no-repeat center center fixed;
  -webkit-background-size: cover;
  -moz-background-size: cover;
  -o-background-size: cover;
  background-size: cover; }

body {
  padding: 60px;
  padding-top: 30px;
  margin: 0; }

.main {
  position: relative; }

.stageName {
    width: 100%;
    margin: 200px auto;
    text-align: center; }

.stageName p:first-of-type {
  margin: -7px;
  font-size: 20px; }

.stageName p {
  margin: 110px 0 10px 0; }

.stageName h1 {
  font-family: 'edoregular';
  font-weight: 100;
  font-size: 125px;
  margin: 0px; }

.stageName input[type="button"] {
  background: #eee;
  font-size: 12px;
  padding: 6px;
  width: 70px;
  border: 1px solid #eee;
  border-radius: 2px;
  font-weight: bold;
  text-transform: uppercase; }

.stageName input[type="button"]:hover {
  background: #ccc;
  border: 1px solid #ccc; }

.stageName input[type="text"] {
  background-color: transparent;
  /*margin-right:15px;*/
  border: 2px solid #eee;
  border-radius: 3px;
  color: white;
  padding: 5px;
  width: 154px;
  font-size: 12px;
  text-align: center;
  text-transform: uppercase; }

header h1 {
  font-family: 'edoregular';
  text-align: center;
  font-size: 50px;
  font-weight: 200;
  margin: 10px 0; }

header p {
  text-align: center;
  font-size: 14px;
  color: #666666;
  margin: 0;
  font-weight: 200; }

.container {
  margin: 0 auto;
}

/**
 * Grid container
 **/
.grid {
  /* margin-top: 30px; */
  width: 100%;
  margin: 30px auto;
}

.grid:after {
  content: '';
  display: block;
  clear: both; }

.grid-item {
  float: left;
  height: 170px;
  width: 170px; }

.grid-item img {
  position: relative;
  width: 100%;
  height: 100%;
  margin: 0 auto;
  -webkit-filter: grayscale(100%);
  filter: grayscale(100%);
  transition: .5s; }

.grid-item--large {
  width: 350px;
  height: 350px; }

.grid-item--large img {
  -webkit-filter: grayscale(0%);
  filter: grayscale(0%);
  transition: .5s; }

h2 {
  position: absolute;
  text-align: center;
  top: 55px;
  left: 0;
  width: 100%; }

h2 span {
  color: white;
  font: bold 20px Helvetica, Sans-Serif;
  /* -webkit-text-stroke: 1px black; */
  text-transform: uppercase;
  -webkit-font-smoothing: antialiased;
  padding: 5px; }

/**
 * Artist info
 **/
.artistInfo {
  color: #333;
  font: bold 10px Helvetica, Sans-Serif;
  font-weight: 400;
  letter-spacing: -.5px;
  background: #fff;
  padding: 21.25px;
  vertical-align: bottom;
  position: absolute;
  bottom: 0;
  left: 0;
  max-height: 340px; }

.artistInfo img {
  width: auto;
  height: 34px;
  display: inline-block;
  float: right; }

.artistInfo div:first-child {
  display: inline-block; }

.artistInfo div > p {
  font-weight: bold; }

.artistInfo input {
  float: right; }

.artistInfo p, .artistInfo ul {
  margin: 0; }

.artistInfo input[type="button"] {
  background: rgba(255, 255, 255, 0.6);
  padding: 5px;
  border: 2px solid black;
  font-weight: bold;
  font-size: 8px;
  text-transform: uppercase; }

.artistInfo input[type="button"]:hover {
  background: white; }

.artistInfo h3 {
  text-transform: uppercase;
  margin: 0;
  color: #F26395;
  font-size: 20px; }

.artistInfo h4 {
  margin: 0;
  text-transform: uppercase;
  font-weight: bold; }

.artifacts ul {
  list-style: none;
  padding: 0;
  list-style-type: none; }

.closeBtn {
  color: #ccc;
  opacity: .7;
  vertical-align: top;
  text-align: right;
  position: absolute;
  top: 0;
  right: 0;
  margin: 15px;
  font-size: 18px;
  -webkit-text-stroke: 1px #333; }

/*Choose Screen*/
.chooseScreen {
  -webkit-filter: blur(1px);
  height: 100%;
  width: 100%;
  transition: .5s; }

.wrapper {
    color: black;
    position: absolute;
    width: 500px;
    height: 500px;
    top: 156px;
    left: 255px;
    margin: 0 auto;
    text-align: center;
  }

.wrapper div {
  vertical-align: bottom;
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 320px;
  background-color: #fefefe;
}

.wrapper img {
  position: relative;
  width: 100%;
  height: 100%;
  margin: 0 auto;
 }

.wrapper p{
  font-size: 38px;
  font-weight: 600;
  margin-top: 70px;
  margin-bottom: 50px;
}

.wrapper p.last{
  margin-top: 90px;
  font-weight: 200;
  font-size: 20px;
}

.wrapper p.last section{
  text-transform: uppercase;
  font-size: 40px;
  font-weight: bold;
}

.wrapper p.restarting{
  font-size: 12px;
  font-weight: 500;
  text-transform: uppercase;
  margin: 100px 0 0 0;
}

.wrapper input[type="button"] {
  background: rgba(255, 255, 255, 0);
  padding: 5px;
  border: 1px solid black;
  font-weight: 400;
  margin: 0 14px;
  width: 80px;
  font-size: 10px;
  text-transform: uppercase;
  -webkit-font-smoothing: antialiased; }


text:
var exec = require('child_process').exec;

module.exports = function(options, callback) {

	// no options
	if (!callback) {
		callback = options;
		options = {};
	}

	// if options is a string, then we assume its the path
	if (typeof options == 'string') {
		options = { cwd: options };
	}

	// call it
	exec('svn info', options, function (err, stdout, stderr) {

		if (err) {
			callback(err);

	    } else {

	    	var info = {};

	    	stdout.split('\n').forEach( function(line) {

				lineParts =line.split(': ');

				if (lineParts.length == 2)
					info[lineParts[0]] = lineParts[1].trim();
			});

			if (info['svn'])
				return callback(info['svn']);

			var result = {
				rev: info['Revision'],
				url: info['URL'],
				last: {
					rev: info['Last Changed Rev'],
					author: info['Last Changed Author'],
					date: new Date(info['Last Changed Date'])
				},
				repository: {
					root: info['Repository Root'],
					id: info['Repository UUID']
				}
			};

	        callback(null, result);
	    }
	});
}


text:
<?php

namespace app\controllers;

use yii\rest\ActiveController;

class UserController extends ActiveController
{
    public $modelClass = 'app\models\User';
    // public function actions()
    // {
    //     $actions = parent::actions();

    //     // disable the "delete" and "create" actions
    //     unset($actions['delete'], $actions['create']);

    //     // customize the data provider preparation with the "prepareDataProvider()" method
    //     $actions['index']['prepareDataProvider'] = [$this, 'prepareDataProvider'];

    //     return $actions;
    // }
    // public function prepareDataProvider()
    // {
    //     // prepare and return a data provider for the "index" action
    // }
}


text:
global.SPRINGBOK_ENV=""+require('fs').readFileSync('./env');
module.exports=require('./'+(SPRINGBOK_ENV==='dev'||SPRINGBOK_ENV==='home'||SPRINGBOK_ENV==='work'?'dev':'prod')+'/app.js');


text:
package com.amazonaws.services.directory.model;

import java.io.Serializable;

import com.amazonaws.AmazonWebServiceRequest;

/**
 * Container for the parameters to the {@link com.amazonaws.services.directory.AWSDirectoryService#createAlias(CreateAliasRequest) CreateAlias operation}.
 *

 * Creates an alias for a directory and assigns the alias to the
 * directory. The alias is used to construct the access URL for the
 * directory, such as http://<alias>.awsapps.com .
 *

 *

 * IMPORTANT: After an alias has been created, it cannot be
 * deleted or reused, so this operation should only be used when
 * absolutely necessary.
 *

 *
 * @see com.amazonaws.services.directory.AWSDirectoryService#createAlias(CreateAliasRequest)
 */
public class CreateAliasRequest extends AmazonWebServiceRequest implements Serializable, Cloneable {

    /**
     * The identifier of the directory to create the alias for.
     *

     * Constraints:

     * Pattern: ^d-[0-9a-f]{10}$

     */
    private String directoryId;

    /**
     * The requested alias.
The alias must be unique amongst all aliases
     * in AWS. This operation will throw an
     * EntityAlreadyExistsException if this alias already
     * exists.
     *

     * Constraints:

     * Length: 1 - 62

     * Pattern: ^(?!d-)([\da-zA-Z]+)([-]*[\da-zA-Z])*

     */
    private String alias;

    /**
     * The identifier of the directory to create the alias for.
     *

     * Constraints:

     * Pattern: ^d-[0-9a-f]{10}$

     *
     * @return The identifier of the directory to create the alias for.
     */
    public String getDirectoryId() {
        return directoryId;
    }

    /**
     * The identifier of the directory to create the alias for.
     *

     * Constraints:

     * Pattern: ^d-[0-9a-f]{10}$

     *
     * @param directoryId The identifier of the directory to create the alias for.
     */
    public void setDirectoryId(String directoryId) {
        this.directoryId = directoryId;
    }

    /**
     * The identifier of the directory to create the alias for.
     *

     * Returns a reference to this object so that method calls can be chained together.
     *

     * Constraints:

     * Pattern: ^d-[0-9a-f]{10}$

     *
     * @param directoryId The identifier of the directory to create the alias for.
     *
     * @return A reference to this updated object so that method calls can be chained
     *         together.
     */
    public CreateAliasRequest withDirectoryId(String directoryId) {
        this.directoryId = directoryId;
        return this;
    }

    /**
     * The requested alias.
The alias must be unique amongst all aliases
     * in AWS. This operation will throw an
     * EntityAlreadyExistsException if this alias already
     * exists.
     *

     * Constraints:

     * Length: 1 - 62

     * Pattern: ^(?!d-)([\da-zA-Z]+)([-]*[\da-zA-Z])*

     *
     * @return The requested alias.
The alias must be unique amongst all aliases
     *         in AWS. This operation will throw an
     *         EntityAlreadyExistsException if this alias already
     *         exists.
     */
    public String getAlias() {
        return alias;
    }

    /**
     * The requested alias.
The alias must be unique amongst all aliases
     * in AWS. This operation will throw an
     * EntityAlreadyExistsException if this alias already
     * exists.
     *

     * Constraints:

     * Length: 1 - 62

     * Pattern: ^(?!d-)([\da-zA-Z]+)([-]*[\da-zA-Z])*

     *
     * @param alias The requested alias.
The alias must be unique amongst all aliases
     *         in AWS. This operation will throw an
     *         EntityAlreadyExistsException if this alias already
     *         exists.
     */
    public void setAlias(String alias) {
        this.alias = alias;
    }

    /**
     * The requested alias.
The alias must be unique amongst all aliases
     * in AWS. This operation will throw an
     * EntityAlreadyExistsException if this alias already
     * exists.
     *

     * Returns a reference to this object so that method calls can be chained together.
     *

     * Constraints:

     * Length: 1 - 62

     * Pattern: ^(?!d-)([\da-zA-Z]+)([-]*[\da-zA-Z])*

     *
     * @param alias The requested alias.
The alias must be unique amongst all aliases
     *         in AWS. This operation will throw an
     *         EntityAlreadyExistsException if this alias already
     *         exists.
     *
     * @return A reference to this updated object so that method calls can be chained
     *         together.
     */
    public CreateAliasRequest withAlias(String alias) {
        this.alias = alias;
        return this;
    }

    /**
     * Returns a string representation of this object; useful for testing and
     * debugging.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (getDirectoryId() != null) sb.append("DirectoryId: " + getDirectoryId() + ",");
        if (getAlias() != null) sb.append("Alias: " + getAlias() );
        sb.append("}");
        return sb.toString();
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int hashCode = 1;

        hashCode = prime * hashCode + ((getDirectoryId() == null) ? 0 : getDirectoryId().hashCode());
        hashCode = prime * hashCode + ((getAlias() == null) ? 0 : getAlias().hashCode());
        return hashCode;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) return true;
        if (obj == null) return false;

        if (obj instanceof CreateAliasRequest == false) return false;
        CreateAliasRequest other = (CreateAliasRequest)obj;

        if (other.getDirectoryId() == null ^ this.getDirectoryId() == null) return false;
        if (other.getDirectoryId() != null && other.getDirectoryId().equals(this.getDirectoryId()) == false) return false;
        if (other.getAlias() == null ^ this.getAlias() == null) return false;
        if (other.getAlias() != null && other.getAlias().equals(this.getAlias()) == false) return false;
        return true;
    }

    @Override
    public CreateAliasRequest clone() {

            return (CreateAliasRequest) super.clone();
    }

}


text:
package careerCup;

import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;

/*
 * Main Link:  http://www.careercup.com/page?pid=google-interview-questions
 * Problem Link:  http://www.careercup.com/question?id=5200686994161664
 */
public class _01googleCareerCup {

	public static void main(String[] args) {
		Scanner scanner=new Scanner(new InputStreamReader(System.in));
		String inputString=scanner.nextLine();
		Integer min=Integer.parseInt(scanner.nextLine());
		Integer max=Integer.parseInt(scanner.nextLine());
		scanner.close();
		String inputStringArray[]=inputString.split(",");
		//naiveAlgo(inputStringArray,min,max);//O(N^2)
		bestAlgo(inputStringArray,min,max);//early Termination
	}

	private static void bestAlgo(String[] inputStringArray, Integer min, Integer max) {
		Arrays.sort(inputStringArray);
		ArrayList<Integer> elementList=new ArrayList<Integer>();
		int cumulativeArray[]=new int[inputStringArray.length];
		int sum=0;
		for (int i = 0; i < inputStringArray.length; i++) {
			sum+=Integer.parseInt(inputStringArray[i]);
			elementList.add(sum);
			cumulativeArray[i]=sum;
		}
		Arrays.sort(cumulativeArray);
		for (int i = 0; i < cumulativeArray.length; i++) {

		}

	}

	private static void naiveAlgo(String[] inputStringArray, Integer min, Integer max) {
		for (int i = 0; i < inputStringArray.length; i++) {
			int sum=Integer.parseInt(inputStringArray[i]);
			if(sum>=min && sum<=max)
				System.out.println(inputStringArray[i]);
			for (int j = i+1; j < inputStringArray.length; j++) {
				sum+=Integer.parseInt(inputStringArray[j]);
				if(sum>=min && sum<=max){
					Integer end=(j<inputStringArray.length)?j+1:j;
					System.out.println(Arrays.toString(Arrays.copyOfRange(inputStringArray, i,end)));
				}
			}
		}

	}
}


text:
<?php

    @@HEADER@@

	require_once 'vendor/autoload.php';

    require_once 'idealstatus.class.php';

    class PaymentsService {

        public $lastErrorMessage = '';

        public function __construct($configuration)
        {
            $this->_configuration = $configuration;
        }

        public function createMolliePayment($payment, $idealissuer, $description, $returnurl)
        {

            $mollie = new Mollie_API_Client;
            $mollie->setApiKey($this->_configuration->getMollieApiKey());

            try
            {
                $options = array(
                    'amount'      => Payment::formatDecimal($payment->amount),
                    'description' => $description,
                    'redirectUrl' => $returnurl,
                    'webhookUrl'  => $this->_configuration->getMollieWebhookUrl(),
                    'locale'      => $payment->locale,
                    'method'      => $payment->paymentMethod,
                    'metadata'    => array(
                        'payment_id' => $payment->id,
                        'payment_verification' => $payment->paymentVerification
                    )
                );

                if ($payment->paymentMethod == 'ideal') {
                    $options['issuer'] = $idealissuer;
                }

                if ($mollie_payment = $mollie->payments->create($options)) {
                    $payments = new Payments($this->_configuration->getPaymentsDatabaseDataSourceName(), $this->_configuration->getPaymentsDatabaseUsername(), $this->_configuration->getPaymentsDatabasePassword());

                    if ($payments->updatePaymentId($payment->id, $payment->paymentVerification, $mollie_payment->id)) {
                        return $mollie_payment->getPaymentUrl();
                    }
                }

                $this->lastErrorMessage = __('An error has occured while starting your payment.', 'martinehooptopbeter');
            }
            catch (Mollie_API_Exception $e)
            {
                $this->lastErrorMessage = __('An error has occured while starting your payment.', 'martinehooptopbeter');
            }

            return false;
        }

        public function getIdealIssuersWithStatus()
        {
            $ideal = [];

            $idealstatus = new IdealStatus();

            $mollie = new Mollie_API_Client;
            $mollie->setApiKey($this->_configuration->getMollieApiKey());

            $issuers = $mollie->issuers->all();

            foreach ($issuers as $issuer)
            {
                if ($issuer->method == Mollie_API_Object_Method::IDEAL)
                {
                    $ideal[] = array('id' => $issuer->id, 'name' => $issuer->name, 'showwarning' => !$idealstatus->statusForIssuer($issuer->id));
                }
            }

            return $ideal;
        }

    }


text:
<?xml version="1.0" encoding="utf-8"?>
<resources xmlns:tools="http://schemas.android.com/tools" tools:ignore="MissingTranslation">
  <!-- General -->
  <string name="app_name">Μετρητής</string>
  <!-- Menu -->
  <string name="drawer_open">Άνοιγμα μενού πλοήγησης</string>
  <string name="drawer_close">Κλείσιμο Πλοήγησης</string>
  <string name="menu_add">Προσθήκη νέου μετρητή</string>
  <string name="menu_reset">Επαναφορά μετρητή</string>
  <string name="menu_edit">Επεξεργασία μετρητή</string>
  <string name="menu_delete">Διαγραφή μετρητή</string>
  <string name="menu_settings">Ρυθμίσεις</string>
  <!-- Dialogs -->
  <string name="dialog_delete_title">Θέλετε να σίγουρα διαγράψετε το μετρητή;</string>
  <string name="dialog_reset_title">Θέλετε σίγουρα να επαναφέρετε το μετρητή;</string>
  <string name="dialog_edit_name">Τίτλος:</string>
  <string name="dialog_edit_value">Τιμή:</string>
  <string name="dialog_button_add">Προσθήκη</string>
  <string name="dialog_button_apply">Εφαρμογή</string>
  <string name="dialog_button_reset">Επαναφορά μετρητή</string>
  <string name="dialog_button_delete">Διαγραφή μετρητή</string>
  <string name="dialog_button_cancel">Άκυρο</string>
  <!-- Settings -->
  <string name="settings_title">Ρυθμίσεις</string>
  <string name="settings_display">Εμφάνιση</string>
  <string name="settings_theme">Θέμα</string>
  <string name="settings_theme_light">Φωτεινό</string>
  <string name="settings_theme_dark">Σκοτεινό</string>
  <string name="settings_controls">Στοιχεία ελέγχου</string>
  <string name="settings_sounds_title">Ενεργοποιήσε τους ήχους</string>
  <string name="settings_vibration_title">Ενεργοποιήσε τη δόνηση</string>
  <string name="settings_hard_title">Χρήση πλήκτρων</string>
  <string name="settings_other">Άλλα</string>
  <string name="settings_version_title">Έκδοση</string>
  <string name="settings_wipe_title">Διαγραφή όλων των μετρητών</string>
  <string name="settings_wipe_confirmation">Θέλετε σίγουρα να διαγράψετε όλους τους μετρητές;</string>
  <string name="settings_wipe_confirmation_yes">Διαγραφή όλων</string>
  <!-- Toasts -->
  <string name="toast_no_name_message">Απαιτείται όνομα!</string>
  <!-- Other stuff -->
  <string name="unknown">Άγνωστο</string>
</resources>


text:
/**
 *
  Package: MAG - VistA Imaging
  WARNING: Per VHA Directive 2004-038, this routine should not be modified.
  Date Created: Nov, 2009
  Site Name:  Washington OI Field Office, Silver Spring, MD
  Developer:  vhaiswlouthj
  Description: DICOM Study cache manager. Maintains the cache of study instances
  			   and expires old studies after 15 minutes.

        ;; +--------------------------------------------------------------------+
        ;; Property of the US Government.
        ;; No permission to copy or redistribute this software is given.
        ;; Use of unreleased versions of this software requires the user
        ;;  to execute a written test agreement with the VistA Imaging
        ;;  Development Office of the Department of Veterans Affairs,
        ;;  telephone (301) 734-0100.
        ;;
        ;; The Food and Drug Administration classifies this software as
        ;; a Class II medical device.  As such, it may not be changed
        ;; in any way.  Modifications to this software may result in an
        ;; adulterated medical device under 21CFR820, the use of which
        ;; is considered to be a violation of US Federal Statutes.
        ;; +--------------------------------------------------------------------+

 */

package gov.va.med.imaging.vistaimagingdatasource.dicom.importer;

import java.util.HashMap;

import gov.va.med.imaging.core.interfaces.exceptions.ConnectionException;
import gov.va.med.imaging.core.interfaces.exceptions.MethodException;
import gov.va.med.imaging.exchange.business.dicom.DicomServerConfiguration;
import gov.va.med.imaging.exchange.business.dicom.importer.ImporterWorkItem;
import gov.va.med.imaging.exchange.business.dicom.importer.ImporterWorkItemDetails;
import gov.va.med.imaging.exchange.business.dicom.importer.Reconciliation;
import gov.va.med.imaging.exchange.business.dicom.importer.Report;
import gov.va.med.imaging.exchange.business.dicom.importer.ReportParameters;
import gov.va.med.imaging.exchange.business.dicom.importer.Study;
import gov.va.med.imaging.url.vista.StringUtils;
import gov.va.med.imaging.url.vista.VistaQuery;
import gov.va.med.imaging.vistaimagingdatasource.common.VistaSessionFactory;

public class ReportDAO extends BaseImporterDAO<Study>
{
	private static String POST_MEDIA_BUNDLE_REPORT_DATA = "MAGV IMPORT MEDIA LOG STORE";
	private static String POST_STUDY_REPORT_DATA = "MAGV IMPORT STUDY LOG STORE";
	private static String GET_IMPORTER_REPORT = "MAGV IMPORT STUDY LOG REPORT";
	//
	// Constructor
	//
	public ReportDAO(){}
	public ReportDAO(VistaSessionFactory sessionFactory)
	{
		this.setSessionFactory(sessionFactory);
	}

	//
	// Post media bundle level report data
	//
	public int postImporterMediaBundleReportData(ImporterWorkItem workItem) throws MethodException, ConnectionException
	{
		ImporterWorkItemDetails details = workItem.getWorkItemDetails();

		String mediaValidationStatusMessage = details.getMediaValidationMessage() != null ?
				                              details.getMediaValidationMessage() :
				                              "";

		VistaQuery vm = new VistaQuery(POST_MEDIA_BUNDLE_REPORT_DATA);
		vm.addParameter(VistaQuery.LITERAL, details.getReconcilingTechnicianDuz());
		vm.addParameter(VistaQuery.LITERAL, details.getWorkstationName());
		vm.addParameter(VistaQuery.LITERAL, workItem.getSubtype());
		vm.addParameter(VistaQuery.LITERAL, Integer.toString(details.getMediaValidationStatusCode()));
		vm.addParameter(VistaQuery.LITERAL, mediaValidationStatusMessage);
		String returnValue = executeRPC(vm);

		return translatePostImporterMediaBundleReportData(returnValue);

	}

	public int translatePostImporterMediaBundleReportData(String returnValue) throws MethodException
	{
		int mediaReportDataIen = 0;
		String[] lines = StringUtils.Split(returnValue, StringUtils.NEW_LINE);
		String[] fields = StringUtils.Split(lines[0], StringUtils.BACKTICK);

		if (fields[0].equals("0"))
		{
			mediaReportDataIen = Integer.parseInt(fields[1]);
		}
		else
		{
			logger.error("Error storing bundle-level report data: " + returnValue);
		}

		return mediaReportDataIen;
	}

	//
	// Post study-level report data
	//
	public void postImporterStudyReportData(
			int mediaGroupIen,
			ImporterWorkItem importerWorkItem,
			String accessionNumber,
			String studyUid,
			String patientDfn,
			String facility,
			String specialty,
			int numberOfSeries,
			int totalImagesInStudy,
			int failedImages,
			HashMap<String, String> modalityCounts)
	throws MethodException, ConnectionException
	{
		ImporterWorkItemDetails details = importerWorkItem.getWorkItemDetails();

		VistaQuery vm = new VistaQuery(POST_STUDY_REPORT_DATA);
		vm.addParameter(VistaQuery.LITERAL, details.getReconcilingTechnicianDuz());
		vm.addParameter(VistaQuery.LITERAL, DicomServerConfiguration.getConfiguration().getSiteId());
		vm.addParameter(VistaQuery.LITERAL, patientDfn);
		vm.addParameter(VistaQuery.LITERAL, accessionNumber);
		vm.addParameter(VistaQuery.LITERAL, studyUid);
		vm.addParameter(VistaQuery.LITERAL, facility);
		vm.addParameter(VistaQuery.LITERAL, specialty);
		vm.addParameter(VistaQuery.LITERAL, Integer.toString(numberOfSeries));
		vm.addParameter(VistaQuery.LIST, modalityCounts);
		vm.addParameter(VistaQuery.LITERAL, Integer.toString(mediaGroupIen));
		vm.addParameter(VistaQuery.LITERAL, Integer.toString(failedImages));

		String returnValue = executeRPC(vm);
		translatePostImporterStudyReportData(returnValue);

	}

	public void translatePostImporterStudyReportData(String returnValue) throws MethodException
	{
		// This should not prevent us from continuing with processing. Simply log it and move on
		// if there's an error
		if (!returnValue.startsWith("0"))
		{
			logger.error("Error storing study-level report data: " + returnValue);
		}
	}

	//
	// Get a report
	//
	public Report getImporterReport(ReportParameters reportParameters) throws MethodException, ConnectionException
	{
		VistaQuery vm = new VistaQuery(GET_IMPORTER_REPORT);
		vm.addParameter(VistaQuery.LITERAL, reportParameters.getReportTypeCode());
		vm.addParameter(VistaQuery.LITERAL, reportParameters.getStartDate());
		vm.addParameter(VistaQuery.LITERAL, reportParameters.getEndDate());
		String returnValue = executeRPC(vm);
		return translateGetImporterReport(returnValue);
	}

	public Report translateGetImporterReport(String returnValue) throws MethodException
	{
		Report report = new Report();

		// Split the result into lines
		String[] lines = StringUtils.Split(returnValue, LINE_SEPARATOR);

		// If the report has data, build it. Otherwise, just return the return value
		String[] fields = StringUtils.Split(lines[0], StringUtils.BACKTICK);

		if (fields[0].equals("0") && lines.length == 1)
		{
			// fields[1] is the start date
			report.setReportText(fields[1]);
		}
		else if (fields[0].equals("0") && lines.length > 1)
		{
			// We have actual report data. Build it.
			StringBuilder reportText = new StringBuilder();

			for (int i = 1; i<lines.length; i++)
			{
				reportText.append(lines[i] + LINE_SEPARATOR);
			}

			report.setReportText(reportText.toString());

		}
		else
		{
			// Probably an error code of -1 meaning no data yet in reports file.
			report.setReportText(returnValue);
		}

		return report;

	}

}


text:
import pytest
import asyncio
from paco import every
from .helpers import run_in_loop

@asyncio.coroutine
def coro(num):
    return num < 4

@asyncio.coroutine
def coro_truly(num):
    return num < 10

def test_every_truly():
    task = every(coro_truly, [1, 2, 3, 4, 3, 1])
    assert run_in_loop(task) is True

def test_every_false():
    task = every(coro, [1, 2, 3, 4, 3, 1])
    assert run_in_loop(task) is False

def test_every_empty():
    task = every(coro, [])
    assert run_in_loop(task) is True

def test_every_invalid_input():
    with pytest.raises(TypeError):
        run_in_loop(every(coro, None))


text:
Project of my master's degree in Computer Science ("Study and Research in Anti-Spam Systems").

For instructions on how to clone, build and run the project, please refer to ["How To"](https://github.com/marcelovca90/anti-spam-weka-gui/blob/master/HOW-TO.md).

- - - -

Machine learning library:
- [Weka (Waikato Environment for Knowledge Analysis)](http://www.cs.waikato.ac.nz/ml/weka/)

Data sets:
- [2017_BASE2](https://github.com/marcelovca90/anti-spam-weka-data/tree/master/2017_BASE2) (with 8, 16, 32, 64, 128, 256, 512 and 1024 features - CHI2, DF and MI)
- [2017_MULT10](https://github.com/marcelovca90/anti-spam-weka-data/tree/master/2017_MULT10) (with 10, 20, 30, 40, 50, 60, 70, 80, 90 and 100 features - CHI2, DF and MI)

Classification methods:
- [A1DE](http://weka.sourceforge.net/packageMetaData/AnDE/index.html) - Averaged 1-Dependence Estimator
- [A2DE](http://weka.sourceforge.net/packageMetaData/AnDE/index.html) - Averaged 2-Dependence Estimator
- [BFTREE](http://weka.sourceforge.net/doc.packages/bestFirstTree/weka/classifiers/trees/BFTree.html) - Best-first tree
- [CART](http://weka.sourceforge.net/doc.packages/simpleCART/weka/classifiers/trees/SimpleCart.html) - Classification And Regression Trees
- [DTNB](http://weka.sourceforge.net/doc.stable/weka/classifiers/rules/DTNB.html) - Decision Table/Naive Bayes Hybrid Classifier
- [FURIA](http://weka.sourceforge.net/packageMetaData/fuzzyUnorderedRuleInduction/index.html) - Fuzzy Unordered Rule Induction Algorithm
- [FRF](https://github.com/fracpete/fastrandomforest-weka-package) - Fast Random Forest
- [HP](http://weka.sourceforge.net/doc.packages/hyperPipes/weka/classifiers/misc/HyperPipes.html) - HyperPipe Classifier
- [IBK](http://weka.sourceforge.net/doc.dev/weka/classifiers/lazy/IBk.html) - K-Nearest Neighbours Classifier
- [J48](http://weka.sourceforge.net/doc.dev/weka/classifiers/trees/J48.html) - C4.5 Decision Tree
- [J48C](http://weka.sourceforge.net/packageMetaData/J48Consolidated/index.html) - C4.5 Consolidated Decision Tree
- [J48G](http://weka.sourceforge.net/doc.packages/J48graft/weka/classifiers/trees/J48graft.html) - C4.5 Grafted Decision Tree
- [JRIP](http://weka.sourceforge.net/doc.stable/weka/classifiers/rules/JRip.html) - Repeated Incremental Pruning to Produce Error Reduction
- [LIBLINEAR](http://weka.sourceforge.net/doc.stable/weka/classifiers/functions/LibSVM.html) - Large Linear Classifier
- [LIBSVM](http://weka.sourceforge.net/doc.stable/weka/classifiers/functions/LibSVM.html) - Support Vector Machine
- [MLP](http://weka.sourceforge.net/doc.dev/weka/classifiers/functions/MultilayerPerceptron.html) - Multilayer Perceptron
- [NB](http://weka.sourceforge.net/doc.dev/weka/classifiers/bayes/NaiveBayes.html) - Naive Bayes classifier
- [NBTREE](http://weka.sourceforge.net/doc.stable/weka/classifiers/trees/NBTree.html) - Decision Tree with Naive Bayes Classifiers at the leaves
- [RBF](http://weka.sourceforge.net/doc.packages/RBFNetwork/weka/classifiers/functions/RBFNetwork.html) - Radial Basis Function network
- [RT](http://weka.sourceforge.net/doc.dev/weka/classifiers/trees/RandomTree.html) - Random Tree
- [SGD](http://weka.sourceforge.net/doc.dev/weka/classifiers/functions/SGD.html) - Stochastic Gradient Gescent
- [SMO](http://weka.sourceforge.net/doc.dev/weka/classifiers/functions/SMO.html) - Sequential Minimal Optimization Algorithm
- [SPEGASOS](http://weka.sourceforge.net/doc.stable/weka/classifiers/functions/SPegasos.html) - Stochastic Primal Estimated sub-GrAdient SOlver for SVM
- [WRF](http://weka.sourceforge.net/doc.dev/weka/classifiers/trees/RandomForest.html) - Weka Random Forest

Metrics:
- Precision
- Recall
- Area under Precision-Recall Curve (PRC)
- Area under Receiver Operating Characteristic (ROC)
- F1 score (also known as F-score or F-measure)
- Training time
- Testing time


text:
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using ServiceStack.Text;

namespace ServiceStack.Markdown
{
	// TODO: Unit test ModelState interaction with VDD
	public class ViewDataDictionary : IDictionary<string, object>
	{
		private readonly Dictionary<string, object> innerDictionary = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
		private object model;
		private ModelMetadata modelMetadata;
		private readonly ModelStateDictionary modelState = new ModelStateDictionary();
		//private TemplateInfo _templateMetadata;

		public ViewDataDictionary() : this((object)null) { }

		public ViewDataDictionary(object model)
		{
			Model = model;
		}

		public ViewDataDictionary(ViewDataDictionary dictionary)
		{
			if (dictionary == null)
			{
				throw new ArgumentNullException("dictionary");
			}

			foreach (var entry in dictionary)
			{
				innerDictionary.Add(entry.Key, entry.Value);
			}
			foreach (var entry in dictionary.ModelState)
			{
				ModelState.Add(entry.Key, entry.Value);
			}

			Model = dictionary.Model;
			//TemplateInfo = dictionary.TemplateInfo;

			// PERF: Don't unnecessarily instantiate the model metadata
			modelMetadata = dictionary.modelMetadata;
		}

		public int Count
		{
			get
			{
				return innerDictionary.Count;
			}
		}

		public bool IsReadOnly
		{
			get
			{
				return ((IDictionary<string, object>)innerDictionary).IsReadOnly;
			}
		}

		public ICollection<string> Keys
		{
			get
			{
				return innerDictionary.Keys;
			}
		}

		public object Model
		{
			get
			{
				return model;
			}
			set
			{
				modelMetadata = null;
				SetModel(value);
			}
		}

		public virtual ModelMetadata ModelMetadata
		{
			get
			{
				if (modelMetadata == null && model != null)
				{
					modelMetadata = ModelMetadataProviders.Current.GetMetadataForType(() => model, model.GetType());
				}
				return modelMetadata;
			}
			set
			{
				modelMetadata = value;
			}
		}

		public ModelStateDictionary ModelState
		{
			get
			{
				return modelState;
			}
		}

		public virtual void PopulateModelState()
		{
			if (model == null) return;

			//Skip non-poco's, i.e. List
			var modelType = model.GetType();
			var listType = modelType.IsGenericType
				? modelType.GetTypeWithGenericInterfaceOf(typeof(IList<>))
				: null;
			if (listType != null || model.GetType().IsArray) return;

			var strModel = TypeSerializer.SerializeToString(model);
			var map = TypeSerializer.DeserializeFromString<Dictionary<string, string>>(strModel);
			foreach (var kvp in map)
			{
				var valueState = new ModelState {
					Value = new ValueProviderResult(kvp.Value, kvp.Value, CultureInfo.CurrentCulture)
				};
				modelState.Add(kvp.Key, valueState);
			}
		}

		public object this[string key]
		{
			get
			{
				object value;
				innerDictionary.TryGetValue(key, out value);
				return value;
			}
			set
			{
				innerDictionary[key] = value;
			}
		}

		//public TemplateInfo TemplateInfo {
		//    get {
		//        if (_templateMetadata == null) {
		//            _templateMetadata = new TemplateInfo();
		//        }
		//        return _templateMetadata;
		//    }
		//    set {
		//        _templateMetadata = value;
		//    }
		//}

		public ICollection<object> Values
		{
			get
			{
				return innerDictionary.Values;
			}
		}

		public void Add(KeyValuePair<string, object> item)
		{
			((IDictionary<string, object>)innerDictionary).Add(item);
		}

		public void Add(string key, object value)
		{
			innerDictionary.Add(key, value);
		}

		public void Clear()
		{
			innerDictionary.Clear();
		}

		public bool Contains(KeyValuePair<string, object> item)
		{
			return ((IDictionary<string, object>)innerDictionary).Contains(item);
		}

		public bool ContainsKey(string key)
		{
			return innerDictionary.ContainsKey(key);
		}

		public void CopyTo(KeyValuePair<string, object>[] array, int arrayIndex)
		{
			((IDictionary<string, object>)innerDictionary).CopyTo(array, arrayIndex);
		}

		public object Eval(string expression)
		{
			ViewDataInfo info = GetViewDataInfo(expression);
			return (info != null) ? info.Value : null;
		}

		public string Eval(string expression, string format)
		{
			object value = Eval(expression);

			if (value == null)
			{
				return String.Empty;
			}

			if (String.IsNullOrEmpty(format))
			{
				return Convert.ToString(value, CultureInfo.CurrentCulture);
			}
			else
			{
				return String.Format(CultureInfo.CurrentCulture, format, value);
			}
		}

		public IEnumerator<KeyValuePair<string, object>> GetEnumerator()
		{
			return innerDictionary.GetEnumerator();
		}

		public ViewDataInfo GetViewDataInfo(string expression)
		{
			if (String.IsNullOrEmpty(expression))
			{
				throw new ArgumentException(MvcResources.Common_NullOrEmpty, "expression");
			}

			return ViewDataEvaluator.Eval(this, expression);
		}

		public bool Remove(KeyValuePair<string, object> item)
		{
			return ((IDictionary<string, object>)innerDictionary).Remove(item);
		}

		public bool Remove(string key)
		{
			return innerDictionary.Remove(key);
		}

		// This method will execute before the derived type's instance constructor executes. Derived types must
		// be aware of this and should plan accordingly. For example, the logic in SetModel() should be simple
		// enough so as not to depend on the "this" pointer referencing a fully constructed object.
		protected virtual void SetModel(object value)
		{
			model = value;
		}

		public bool TryGetValue(string key, out object value)
		{
			return innerDictionary.TryGetValue(key, out value);
		}

		internal static class ViewDataEvaluator
		{
			public static ViewDataInfo Eval(ViewDataDictionary vdd, string expression)
			{
				//Given an expression "foo.bar.baz" we look up the following (pseudocode):
				//  this["foo.bar.baz.quux"]
				//  this["foo.bar.baz"]["quux"]
				//  this["foo.bar"]["baz.quux]
				//  this["foo.bar"]["baz"]["quux"]
				//  this["foo"]["bar.baz.quux"]
				//  this["foo"]["bar.baz"]["quux"]
				//  this["foo"]["bar"]["baz.quux"]
				//  this["foo"]["bar"]["baz"]["quux"]

				ViewDataInfo evaluated = EvalComplexExpression(vdd, expression);
				return evaluated;
			}

			private static ViewDataInfo EvalComplexExpression(object indexableObject, string expression)
			{
				foreach (ExpressionPair expressionPair in GetRightToLeftExpressions(expression))
				{
					string subExpression = expressionPair.Left;
					string postExpression = expressionPair.Right;

					ViewDataInfo subTargetInfo = GetPropertyValue(indexableObject, subExpression);
					if (subTargetInfo != null)
					{
						if (String.IsNullOrEmpty(postExpression))
						{
							return subTargetInfo;
						}

						if (subTargetInfo.Value != null)
						{
							ViewDataInfo potential = EvalComplexExpression(subTargetInfo.Value, postExpression);
							if (potential != null)
							{
								return potential;
							}
						}
					}
				}
				return null;
			}

			private static IEnumerable<ExpressionPair> GetRightToLeftExpressions(string expression)
			{
				// Produces an enumeration of all the combinations of complex property names
				// given a complex expression. See the list above for an example of the result
				// of the enumeration.

				yield return new ExpressionPair(expression, String.Empty);

				int lastDot = expression.LastIndexOf('.');

				string subExpression = expression;
				string postExpression = string.Empty;

				while (lastDot > -1)
				{
					subExpression = expression.Substring(0, lastDot);
					postExpression = expression.Substring(lastDot + 1);
					yield return new ExpressionPair(subExpression, postExpression);

					lastDot = subExpression.LastIndexOf('.');
				}
			}

			private static ViewDataInfo GetIndexedPropertyValue(object indexableObject, string key)
			{
				var dict = indexableObject as IDictionary<string, object>;
				object value = null;
				bool success = false;

				if (dict != null)
				{
					success = dict.TryGetValue(key, out value);
				}
				else
				{
					var tgvDel = TypeHelpers.CreateTryGetValueDelegate(indexableObject.GetType());
					if (tgvDel != null)
					{
						success = tgvDel(indexableObject, key, out value);
					}
				}

				if (success)
				{
					return new ViewDataInfo() {
						Container = indexableObject,
						Value = value
					};
				}

				return null;
			}

			private static ViewDataInfo GetPropertyValue(object container, string propertyName)
			{
				// This method handles one "segment" of a complex property expression

				// First, we try to evaluate the property based on its indexer
				var value = GetIndexedPropertyValue(container, propertyName);
				if (value != null)
				{
					return value;
				}

				// If the indexer didn't return anything useful, continue...

				// If the container is a ViewDataDictionary then treat its Model property
				// as the container instead of the ViewDataDictionary itself.
				var vdd = container as ViewDataDictionary;
				if (vdd != null)
				{
					container = vdd.Model;
				}

				// If the container is null, we're out of options
				if (container == null)
				{
					return null;
				}

				// Second, we try to use PropertyDescriptors and treat the expression as a property name
				var descriptor = TypeDescriptor.GetProperties(container).Find(propertyName, true);
				if (descriptor == null)
				{
					return null;
				}

				return new ViewDataInfo(() => descriptor.GetValue(container)) {
					Container = container,
					PropertyDescriptor = descriptor
				};
			}

			private struct ExpressionPair
			{
				public readonly string Left;
				public readonly string Right;

				public ExpressionPair(string left, string right)
				{
					Left = left;
					Right = right;
				}
			}
		}

		#region IEnumerable Members
		IEnumerator IEnumerable.GetEnumerator()
		{
			return ((IEnumerable)innerDictionary).GetEnumerator();
		}
		#endregion

	}
}


text:
package spark.rdd

import java.io.EOFException
import java.util.NoSuchElementException

import org.apache.hadoop.io.LongWritable
import org.apache.hadoop.io.NullWritable
import org.apache.hadoop.io.Text
import org.apache.hadoop.mapred.FileInputFormat
import org.apache.hadoop.mapred.InputFormat
import org.apache.hadoop.mapred.InputSplit
import org.apache.hadoop.mapred.JobConf
import org.apache.hadoop.mapred.TextInputFormat
import org.apache.hadoop.mapred.RecordReader
import org.apache.hadoop.mapred.Reporter
import org.apache.hadoop.util.ReflectionUtils

import spark.deploy.SparkHadoopUtil
import spark.{Dependency, Logging, Partition, RDD, SerializableWritable, SparkContext, TaskContext}
import spark.util.NextIterator
import org.apache.hadoop.conf.Configurable

/**
 * A Spark split class that wraps around a Hadoop InputSplit.
 */
private[spark] class HadoopPartition(rddId: Int, idx: Int, @transient s: InputSplit)
  extends Partition {

  val inputSplit = new SerializableWritable[InputSplit](s)

  override def hashCode(): Int = (41 * (41 + rddId) + idx).toInt

  override val index: Int = idx
}

/**
 * An RDD that reads a Hadoop dataset as specified by a JobConf (e.g. files in HDFS, the local file
 * system, or S3, tables in HBase, etc).
 */
class HadoopRDD[K, V](
    sc: SparkContext,
    @transient conf: JobConf,
    inputFormatClass: Class[_ <: InputFormat[K, V]],
    keyClass: Class[K],
    valueClass: Class[V],
    minSplits: Int)
  extends RDD[(K, V)](sc, Nil) with Logging {

  // A Hadoop JobConf can be about 10 KB, which is pretty big, so broadcast it
  private val confBroadcast = sc.broadcast(new SerializableWritable(conf))

  override def getPartitions: Array[Partition] = {
    SparkHadoopUtil.addCredentials(conf);
    val inputFormat = createInputFormat(conf)
    if (inputFormat.isInstanceOf[Configurable]) {
      inputFormat.asInstanceOf[Configurable].setConf(conf)
    }
    val inputSplits = inputFormat.getSplits(conf, minSplits)
    val array = new Array[Partition](inputSplits.size)
    for (i <- 0 until inputSplits.size) {
      array(i) = new HadoopPartition(id, i, inputSplits(i))
    }
    array
  }

  def createInputFormat(conf: JobConf): InputFormat[K, V] = {
    ReflectionUtils.newInstance(inputFormatClass.asInstanceOf[Class[_]], conf)
      .asInstanceOf[InputFormat[K, V]]
  }

  override def compute(theSplit: Partition, context: TaskContext) = new NextIterator[(K, V)] {
    val split = theSplit.asInstanceOf[HadoopPartition]
    var reader: RecordReader[K, V] = null

    val conf = confBroadcast.value.value
    val fmt = createInputFormat(conf)
    if (fmt.isInstanceOf[Configurable]) {
      fmt.asInstanceOf[Configurable].setConf(conf)
    }
    reader = fmt.getRecordReader(split.inputSplit.value, conf, Reporter.NULL)

    // Register an on-task-completion callback to close the input stream.
    context.addOnCompleteCallback{ () => closeIfNeeded() }

    val key: K = reader.createKey()
    val value: V = reader.createValue()

    override def getNext() = {
      try {
        finished = !reader.next(key, value)
      } catch {
        case eof: EOFException =>
          finished = true
      }
      (key, value)
    }

    override def close() {
      try {
        reader.close()
      } catch {
        case e: Exception => logWarning("Exception in RecordReader.close()", e)
      }
    }
  }

  override def getPreferredLocations(split: Partition): Seq[String] = {
    // TODO: Filtering out "localhost" in case of file:// URLs
    val hadoopSplit = split.asInstanceOf[HadoopPartition]
    hadoopSplit.inputSplit.value.getLocations.filter(_ != "localhost")
  }

  override def checkpoint() {
    // Do nothing. Hadoop RDD should not be checkpointed.
  }
}


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
null

#### Original name
Pistacia atlantica Desf.

### Remarks
null


text:
<?php

/**
 * Filter data coming from a request array (i.e. $_GET or $_POST).
 * These validations are exclusively UTF-8.
 * TODO: alternate character encodings?
 */
class Request_Filter implements ArrayAccess, IteratorAggregate {

	private $raw;
	private $utf8 = array();
	private $text = array();
	private $strip = array();

	public function __construct(array $array) {
		$this->raw = $array;
	}

	/*** ArrayAccess interface ***/

	public function offsetExists($name) {
		return isset($this->raw[$name]);
	}

	public function offsetGet($name) {
		return $this->get($name);
	}

	public function offsetSet($name, $value) {
		$this->unset($name);
		$this->raw[$name] = $value;
	}

	public function offsetUnset($name) {
		unset($this->raw[$name]);
		unset($this->utf8[$name]);
		unset($this->text[$name]);
		unset($this->strip[$name]);
	}

	/*** IteratorAggregate interface ***/

	public function getIterator() {
		return new Request_Iterator($this, array_keys($this->raw));
	}

	/**
	 * Return the array offset, stripped of all tags and
	 * exotic control characters, and verified as valid utf8.
	 * If the array offset does not exist or its value does
	 * not pass muster, the default value is returned.
	 *
	 * @param string $name
	 * @param mixed $default
	 * @return string|mixed
	 */
	public function get($name, $default = null) {
		if (!isset($this->strip[$name])) {
			if (is_array(@$this->raw[$name])) {
				$this->strip[$name] = new Request_Filter($this->raw[$name]);
			} else {
				$text = $this->text($name);
				$this->strip[$name] = $text === null ? false : filter_var($text, FILTER_SANITIZE_STRING);
			}
		}
		if ($this->strip[$name] !== false) {
			return $this->strip[$name];
		} else {
			return $default;
		}
	}

	/**
	 * Return the array offset, stripped of exotic control
	 * characters and verified as utf8.
	 *
	 * @param string $name
	 * @param mixed $default
	 * @return string|mixed
	 */
	public function text($name, $default = null) {
		if (!isset($this->text[$name])) {
			$utf8 = $this->utf8($name, false);
			$this->text[$name] = $this->stripControlCodes($utf8);
		}
		if ($this->text[$name] !== false) {
			return $this->text[$name];
		} else {
			return $default;
		}
	}

	/**
	 * Remove all control codes, with the exceptions of tab,
	 * newline and carriage return.
	 *
	 * @param string|null $text
	 * @return string|null
	 */
	private function stripControlCodes($text) {
		if (!is_string($text)) {
			return $text;
		}
		$needles = array("\x00", "\x01", "\x02", "\x03", "\x04", "\x05", "\x06", "\x07",
		                 "\x08", /* \t */ /* \n */ "\x0b", "\x0c", /* \r */ "\x0e", "\x0f",
		                 "\x10", "\x11", "\x12", "\x13", "\x14", "\x15", "\x16", "\x17",
		                 "\x18", "\x19", "\x1a", "\x1b", "\x1c", "\x1d", "\x1e", "\x1f");
		return str_replace($needles, '', $text);
	}

	/**
	 * Return the array offset if it contains valid utf8.
	 * Otherwise, return the default.
	 *
	 * @param string $name
	 * @param mixed $default
	 * @return string|mixed
	 */
	public function utf8($name, $default = null) {
		if (!isset($this->utf8[$name])) {
			$this->utf8[$name] = isset($this->raw[$name]) && mb_check_encoding($this->raw[$name], 'UTF-8');
		}
		return $this->utf8[$name] ? $this->raw[$name] : $default;
	}

	/**
	 * Return the array offset as is, if it exists.
	 * Otherwise, return the default.
	 *
	 * @param string $name
	 * @param mixed $default
	 * @return string|mixed
	 */
	public function binary($name, $default = null) {
		return isset($this->raw[$name]) ? $this->raw[$name] : $default;
	}

	/**
	 * Return a boolean based on the value at the offset.
	 * Otherwise, return default.
	 * Valid values for true: '1', 'true', 'on', 'yes'.
	 * Valid values for false: '0', 'false', 'off', 'no', ''.
	 *
	 * @param string $name
	 * @param mixed $default
	 * @return boolean|mixed
	 */
	public function boolean($name, $default = false) {
		$boolean = filter_var(@$this->raw[$name], FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE);
		return $boolean === null ? $default : $boolean;
	}

	/**
	 * Return an int based on the value at the offset.
	 * Otherwise, return default.
	 *
	 * @param string $name
	 * @param mixed $default
	 * @return int|mixed
	 */
	public function int($name, $default = 0) {
		$int = filter_var(@$this->raw[$name], FILTER_VALIDATE_INT);
		return $int === false ? $default : $int;
	}

	/**
	 * Return a float based on the value at the offset.
	 * Otherwise, return default.
	 *
	 * @param string $name
	 * @param mixed $default
	 * @return float|mixed
	 */
	public function float($name, $default = 0.0) {
		$float = filter_var(@$this->raw[$name], FILTER_VALIDATE_FLOAT);
		return $float === false ? $default : $float;
	}

	public function email($name, $default = null) {
		$email = filter_var(@$this->raw[$name], FILTER_VALIDATE_EMAIL);
		return $email === false ? $default : $email;
	}

	/**
	 * Apply a callable function to the value at offset.
	 * If the offset does not exist or the callable returns
	 * either null or false, return the default.
	 *
	 * Example:
	 *		$time = $filter->apply('strtotime', 'date', time());
	 *
	 * @param Callback $callable
	 * @param string $name
	 * @param mixed $default
	 * @return mixed
	 */
	public function apply($callable, $name, $default = null) {
		$utf8 = $this->utf8($name);
		$result = null;
		if ($utf8 !== null) {
			$result = call_user_func($callable, $this->raw[$name]);
		}
		if ($result === null || $result === false) {
			return $default;
		} else {
			return $result;
		}
	}
}


text:
package org.apache.drill.exec.server;

import io.netty.channel.EventLoopGroup;

import java.io.Closeable;

import org.apache.drill.common.config.DrillConfig;
import org.apache.drill.exec.ExecConstants;
import org.apache.drill.exec.memory.BufferAllocator;
import org.apache.drill.exec.memory.TopLevelAllocator;
import org.apache.drill.exec.metrics.DrillMetrics;
import org.apache.drill.exec.rpc.TransportCheck;

import com.codahale.metrics.MetricRegistry;

// TODO:  Doc.  What kind of context?  (For what aspects, RPC?  What kind of data?)
public class BootStrapContext implements Closeable{
  static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(BootStrapContext.class);

  private final DrillConfig config;
  private final EventLoopGroup loop;
  private final EventLoopGroup loop2;
  private final MetricRegistry metrics;
  private final BufferAllocator allocator;

  public BootStrapContext(DrillConfig config) {
    super();
    this.config = config;
    this.loop = TransportCheck.createEventLoopGroup(config.getInt(ExecConstants.BIT_SERVER_RPC_THREADS), "BitServer-");
    this.loop2 = TransportCheck.createEventLoopGroup(config.getInt(ExecConstants.BIT_SERVER_RPC_THREADS), "BitClient-");
    this.metrics = DrillMetrics.getInstance();
    this.allocator = new TopLevelAllocator(config);
  }

  public DrillConfig getConfig() {
    return config;
  }

  public EventLoopGroup getBitLoopGroup() {
    return loop;
  }

  public EventLoopGroup getBitClientLoopGroup() {
    return loop2;
  }

  public MetricRegistry getMetrics() {
    return metrics;
  }

  public BufferAllocator getAllocator() {
    return allocator;
  }

  public void close() {
    DrillMetrics.resetMetrics();
    loop.shutdownGracefully();
    allocator.close();
  }

}


text:
create or replace function unison.palias_OAD_fmt(integer)
returns text language plpgsql as '
DECLARE
	a_id alias for $1;
	rv text;
	rec record;
BEGIN
	if a_id is null then
		return null;
	end if;

	select into rv O.origin || '':'' || A.alias || '' ('' || coalesce(A.descr, ''No descr available'') || '')''
		from paliasorigin A
		join origin O on O.origin_id=A.origin_id
		where A.palias_id=a_id;

	return rv;
END;';
-- -----------------------------------------------------------------------------
comment on function unison.palias_OAD_fmt(integer)  is 'cannonical annotation format of given palias_id, like this: <origin>:<alias> (<description>)';

-- -----------------------------------------------------------------------------
-- NAME: palias_OA_fmt(integer)
-- PURPOSE: returns text string of origin and alias for a given palias_id
-- ARGUMENTS: palias_id
-- RETURNS: text
--
create or replace function unison.palias_OA_fmt(integer)
returns text language plpgsql as '
DECLARE
	a_id alias for $1;
	rv text;
BEGIN
	if a_id is null then
		return null;
	end if;
	select into rv
		O.origin || '':'' || A.alias
		from paliasorigin A
		join origin O on O.origin_id=A.origin_id
		where A.palias_id=a_id;
	return rv;
END;';
-- -----------------------------------------------------------------------------
comment on function unison.palias_OA_fmt(integer)   is 'cannonical alias format of given palias_id, like this: <origin>:<alias>';

-- -----------------------------------------------------------------------------
-- NAME: best_palias_id(integer,boolean)
-- PURPOSE: return the palias_id of the best annotation (highest ann_pref value)
-- ARGUMENTS: pseq_id, flag for whether to allow null ann_pref
-- RETURNS: text
--
create or replace function unison.best_palias_id(integer,boolean)
returns integer language plpgsql as '
DECLARE
	q_id alias for $1;
  flag alias for $2;
	a_id integer;
	o_id integer;
	rv text;
BEGIN
	select into a_id palias_id from pseq where pseq_id=q_id;
	if a_id is not null then
		return a_id;
	end if;

	-- allow null ann_pref
	if flag then
		select into a_id QA.palias_id from pseqalias QA
			join paliasorigin OA on OA.palias_id=QA.palias_id
			join origin O on O.origin_id=OA.origin_id
			where QA.pseq_id=q_id and QA.iscurrent=TRUE
			order by O.ann_pref limit 1;
	-- dont allow null ann_pref
	else
		select into a_id QA.palias_id from pseqalias QA
			join paliasorigin OA on OA.palias_id=QA.palias_id
			join origin O on O.origin_id=OA.origin_id
			where QA.pseq_id=q_id and QA.iscurrent=TRUE and O.ann_pref is not null
			order by O.ann_pref limit 1;
	end if;

	if a_id is not null then
		return a_id;
	end if;

	return NULL;
END;';
-- -----------------------------------------------------------------------------
comment on function unison.best_palias_id(integer,boolean)  is '"best" palias_id of given pseq_id; flag for null ann_pref; see best_* functions';

-- -----------------------------------------------------------------------------
-- NAME: best_palias_id(integer)
-- PURPOSE: backwardly form of best_palias_id(integer,boolean) use false for boolean
-- ARGUMENTS: pseq_id
-- RETURNS: text
--
create or replace function unison.best_palias_id(integer)
returns integer language plpgsql as
'BEGIN return best_palias_id($1,false); END;';
-- -----------------------------------------------------------------------------
comment on function unison.best_palias_id(integer)  is 'alias for best_palias_id(integer,false)';

-- -----------------------------------------------------------------------------
-- NAME: best_OA(integer,boolean)
-- PURPOSE: return best origin and alias for a given pseq_id, use boolean
--          to allow inclusion of null ann_pref origins
-- ARGUMENTS: pseq_id, boolean flag for including origins with null ann_pref
-- RETURNS: text
--
create or replace function unison.best_OA(integer,boolean)
returns text language plpgsql as
'BEGIN return palias_OA_fmt( best_palias_id( $1, $2 ) ); END;';
-- -----------------------------------------------------------------------------
comment on function unison.best_OA(integer,boolean) is '"best" <origin:alias> for pseq_id';

-- -----------------------------------------------------------------------------
-- NAME: best_OA(integer)
-- PURPOSE: backwardly form of best_OA(integer,boolean) use false for boolean
-- ARGUMENTS: pseq_id
-- RETURNS: text
--
create or replace function unison.best_OA(integer)
returns text language plpgsql as
'BEGIN return best_OA( $1, false ); END;';
-- -----------------------------------------------------------------------------
comment on function unison.best_OA(integer) is 'alias for best_OA(integer,false)';

-- -----------------------------------------------------------------------------
-- NAME: best_OAD(integer,boolean)
-- PURPOSE: return best origin, alias and descr for a given pseq_id, use boolean
--          to allow inclusion of null ann_pref origins
-- ARGUMENTS: pseq_id, boolean flag for including origins with null ann_pref
-- RETURNS: text
--
create or replace function unison.best_OAD(integer,boolean)
returns text language plpgsql as
'BEGIN return palias_OAD_fmt( best_palias_id( $1, $2 ) ); END;';
comment on function unison.best_OAD(integer,boolean) is '"best" <origin:alias (description)> for pseq_id';
-- -----------------------------------------------------------------------------

-- -----------------------------------------------------------------------------
-- NAME: best_OAD(integer)
-- PURPOSE: alias for best_OAD(integer,false)
-- ARGUMENTS: pseq_id
-- RETURNS: text
--
create or replace function unison.best_OAD(integer)
returns text language plpgsql as
'BEGIN return best_OAD( $1, false ); END;';
comment on function unison.best_OAD(integer) is 'alias for best_OAD(integer,false)';
-- -----------------------------------------------------------------------------

-- -----------------------------------------------------------------------------
-- NAME: best_alias(integer,boolean)
-- PURPOSE: alias for best_OA(integer,boolean)
-- ARGUMENTS: pseq_id, boolean flag for including origins with null ann_pref
-- RETURNS: text
--
create or replace function unison.best_alias(integer,boolean)
returns text language plpgsql as 'BEGIN	return best_OA( $1, $2 ); END;';
-- -----------------------------------------------------------------------------
comment on function unison.best_alias(integer,boolean) is 'same as best_OA';

-- -----------------------------------------------------------------------------
-- NAME: best_alias(integer)
-- PURPOSE: alias for best_alias(integer,false)
-- ARGUMENTS: pseq_id
-- RETURNS: text
--
create or replace function unison.best_alias(integer)
returns text language plpgsql as 'BEGIN	return best_alias( $1, false ); END;';
-- -----------------------------------------------------------------------------
comment on function unison.best_alias(integer) is 'alias for best_alias(integer,false)';

-- -----------------------------------------------------------------------------
-- NAME: best_annotation(integer,boolean)
-- PURPOSE: alias for best_OAD(integer,boolean)
-- ARGUMENTS: pseq_id, boolean flag for including origins with null ann_pref
-- RETURNS: text
--
create or replace function unison.best_annotation(integer,boolean)
returns text language plpgsql as 'BEGIN	return best_OAD( $1, $2 ); END;';
comment on function unison.best_annotation(integer,boolean) is 'same as best_OAD';

-- -----------------------------------------------------------------------------
-- NAME: best_annotation(integer)
-- PURPOSE: alias for best_annotation(integer,false)
-- ARGUMENTS: pseq_id
-- RETURNS: text
--
create or replace function unison.best_annotation(integer)
returns text language plpgsql as 'BEGIN	return best_annotation( $1, false ); END;';
comment on function unison.best_annotation(integer) is 'alias for best_annotation(integer,false)';


text:
networking engine based on chain of responsibility pattern

## Table of Contents
* [Installation](#installation)
* [Usage](#usage)
* [Configurability](#configurability)
* [Code Generation](#code-generation)

## Installation
drag and drop contents of MTDispatcher folder to your project's vendor folder

## Usage

for each request you'll need to create MTRequest subclass and MTResponse subclass. MTRequest subclass has to override - (MTResponse *)response method
with your custom response subclass

###interface
```objc
@interface MTHTTPBinGetSampleRequest : MTRequest

- (MTHTTPBinGetSampleResponse *)response;

@end
```
###implementation
```objc
- (NSMutableURLRequest *)serviceURLRequest {
    NSMutableURLRequest *request = [super serviceURLRequest];

    // request configuration code here

    return request;
}

- (MTHTTPBinGetSampleResponse *)response {
    return (MTHTTPBinGetSampleResponse *)_response;
}

- (Class)responseClass {
    return MTHTTPBinGetSampleResponse.class;
}
```

in MTResponse subclass you should override this method, to process feedback from server

```objc
- (NSError *)parseResponse:(NSHTTPURLResponse *)networkResponse data:(NSData *)responseData;
```

super call is required to fill json dictionary/array

```objc
- (NSError *)parseResponse:(NSHTTPURLResponse *)networkResponse data:(NSData *)responseData {
    NSError *error = [super parseResponse:networkResponse data:responseData];

    if (error == nil) {
        _origin = _jsonDictionary[@"origin"];
        _url = _jsonDictionary[@"url"];
    }

    return error;
}
```

after request/response is configured, a wannabe caller would need to import that class and MTDispatcher.h

```objc
#import "MTDispatcher.h"
#import "MTHTTPBinGetSampleRequest.h"
```

and make an actual call

```objc
MTHTTPBinGetSampleRequest *getRequest = [MTHTTPBinGetSampleRequest requestWithOwner:self];
getRequest.completionBlock = ^(MTHTTPBinGetSampleRequest *request, NSError *error) {
        if (error == nil) {
            // get parsed object(s) from request.response and do your voodoo
            // this is called in main thread, so you can safely update UI here
        }
    };

[[MTDispatcher sharedInstance] processRequest:getRequest];
```

## Configurability
Library is to certain extent configurable through MTDispatcher-info.plist file

```xml
<dict>
    <key>LOG_NETWORK</key>
    <false/>
    <key>PLIST_VERSION</key>
    <integer>1</integer>
    <key>TIMEOUT_INTERVAL</key>
    <integer>30</integer>
    <key>SUCESS_STATUS_CODES</key>
    <array>
        <string>200-299</string>
    </array>
    <key>HTTP_HEADERS</key>
    <dict>
        <key>Accept</key>
        <string>application/json</string>
        <key>Content-Type</key>
        <string>application/x-www-form-urlencoded</string>
    </dict>
    <key>DEFAULT_METHOD</key>
    <string>GET</string>
    <key>LOG_DEPOT_OPERATIONS</key>
    <false/>
</dict>
```

here you can configure logging options, timeout interval, accept status codes, default http headers and default request methods

## Code Generation
Dispatcher contains code generation script to create your request subclasses

###DISPATCHER_CODEGEN.sh

 how to use:
 1. copy script to some temp folder
 2. cd to that folder
 3. give script rights to write files: "chmod 755 DISPATCHER_CODEGEN.sh"
 4. run: "./DISPATCHER_CODEGEN.sh RequestName" (think FAGetArticleList)

 you'll see request/response templates created, just drag and drop them to your Requests folder and implement request building, response parsing


text:
<?xml version="1.0" ?>
<doc>
	<str name="Patent Number">
		US7540961
	</str>
	<str name="Application Number">
		US11/426120
	</str>
	<str name="Kind Code">
		B2
	</str>
	<str name="Title">
		Methods for manufacturing hydrogen using anaerobic digestion
	</str>
	<str name="Abstract">
		A method for manufacturing a biomass enriched with hydrogen-producing bacteria or spores includes providing a biomass comprising a hydrogen-producing bacteria and a competing bacteria and treating the biomass with a sufficient amount of a chemical agent for a period of time such that the treatment (i) kills, inhibits or injures substantially all of the competing bacteria and (ii) does not kill or inhibit the hydrogen-producing bacteria or causes the hydrogen-producing bacteria to form spores that are not destroyed during the chemical treatment. The method also includes digesting an enriched biomass with a non-sterile organic substrate. The enriched biomass includes hydrogen-producing bacteria or spores that are mixed in sufficient quantities with the organic substrate such that the hydrogen-producing bacteria can overcome the competing bacteria to consume the organic substrate and produce hydrogen.
	</str>
	<str name="Document Types">
		US | USB | DOCDB
	</str>
	<str name="Application Date">
		2006-06-23
	</str>
	<str name="Application Year">
		2006
	</str>
	<str name="Application(Year/Month)">
		2006-06
	</str>
	<str name="Publication Date">
		2009-06-02
	</str>
	<str name="Publication Year">
		2009
	</str>
	<str name="Publication(Year/Month)">
		2009-06
	</str>
	<str name="All IPC">
		C02F3/28 | C02F11/04
	</str>
	<str name="IPC Primary">
		C02F3/28
	</str>
	<str name="IPC Section">
		C
	</str>
	<str name="IPC Class">
		C02
	</str>
	<str name="IPC Subclass">
		C02F
	</str>
	<str name="IPC Group">
		C02F3
	</str>
	<str name="All UPC">
		210/603 | 210/613 | 210/631
	</str>
	<str name="UPC Primary">
		210/603
	</str>
	<str name="UPC Class">
		210
	</str>
	<str name="Family Members">
		US20060289355A1 | US7540961
	</str>
	<str name="Family Member Count">
		2
	</str>
	<str name="Family Members Cited By Count">
		1
	</str>
	<str name="Other References">
		M Okamoto, T. Miyahara, O. Mizuno and T. Noike; Biological hydrogen potential of materials characteristic of the organic fraction of municipal solid wastes; Water Science and Technology, vol. 41 No. 3 pp. 25-32 IWA Publishing 2000. cited by other | Jiunn-Jyi Lay; Modeling and Optimization of Anaerobic Digested Sludge converting Starch to Hydrogen; Biotechnology and Bioengineering, vol. 68, No. 3, pp. 269-278 May 5, 2000. cited by other | Peter Setlow; Resistance of Bacterial Spores; Bacterial Stress Responses, Department of Biochemistry, University of Connecticut Health Center, Farmington, CT 06032, Chapter 14, pp. 217-230 2000 ASM Press, Washington D.C. cited by other.
	</str>
	<str name="Other References Count">
		3
	</str>
	<str name="Cited By">
		US8246828
	</str>
	<str name="Cited By Count">
		1
	</str>
	<str name="Cites">
		US4354936 | US4696746 | US4696747 | US4919813 | US5464539 | US6416993 | US6860996 | US20050064567
	</str>
	<str name="Cites Count">
		8
	</str>
	<str name="Priority Country">
		US | US
	</str>
	<str name="Priority Number">
		42612006 | 69371005
	</str>
	<str name="Priority Date">
		2006-06-23 | 2005-06-24
	</str>
	<str name="Assignee(s)">
		UTAH STATE UNIVERSITY
	</str>
	<str name="1st Assignee">
		UTAH STATE UNIVERSITY
	</str>
	<str name="Number of Assignees">
		1
	</str>
	<str name="1st Assignee Address">
		North Logan, UT
	</str>
	<str name="Assignee(s) Address">
		North Logan, UT
	</str>
	<str name="Inventor(s)">
		HANSEN, CONLY, L. | CHEONG, DAE-YEOL
	</str>
	<str name="1st Inventor">
		HANSEN, CONLY, L.
	</str>
	<str name="Number of Inventors">
		2
	</str>
	<str name="1st Inventor Address">
		North, Logan, UT
	</str>
	<str name="Inventor(s) Address">
		North, Logan, UT | Logan, UT
	</str>
	<str name="Primary Examiner">
		PRINCE, FRED
	</str>
	<str name="cited by within 3 years">
		1
	</str>
	<str name="cited by within 5 years">
		1
	</str>
</doc>


text:
@implementation CustomIpm
- (Class)tableView:(UITableView*)tableView indexPath:(NSIndexPath*)indexpath{  // 这个方法会子类有机会重写,默认的 Cell 类型是 HomeScrollCell
    return [HomeShopCell class];
}
@end


text:
<?php

/**
 * Admin Block Helper
 *
 * @category    Mage
 * @package     Mage_Admin
 * @author      Magento Core Team <core@magentocommerce.com>
 */
class Mage_Admin_Helper_Block
{
    /**
     * Types cache
     *
     * @var array
     */
    protected $_allowedTypes;

    /**
     * Construct
     */
    public function __construct()
    {
        $this->_allowedTypes = Mage::getResourceModel('admin/block')->getAllowedTypes();
    }

    /**
     * @param string $type
     * @return bool
     */
    public function isTypeAllowed($type)
    {
        return isset($this->_allowedTypes[$type]);
    }

    /**
     *  Get disallowed names for block
     *
     * @return bool
     */
    public function getDisallowedBlockNames()
    {
        return Mage::getResourceModel('admin/block')->getDisallowedBlockNames();
    }
}