text:
package API::Cachegroup;
#
# Copyright 2015 Comcast Cable Communications Management, LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
#
#
# a note about locations and cachegroups. This used to be "Location", before we had physical locations in 12M. Very confusing.
# What used to be called a location is now called a "cache group" and location is now a physical address, not a group of caches working together.
#

# JvD Note: you always want to put Utils as the first use. Sh*t don't work if it's after the Mojo lines.
use UI::Utils;

use Mojo::Base 'Mojolicious::Controller';
use Data::Dumper;
use JSON;
use MojoPlugins::Response;

# Read
sub index {
	my $self = shift;
	my @data;
	my %idnames;
	my $orderby = $self->param('orderby') || "name";

	# Can't figure out how to do the join on the same table
	my $rs_idnames = $self->db->resultset("Cachegroup")->search( undef, { columns => [qw/id name/] } );
	while ( my $row = $rs_idnames->next ) {
		$idnames{ $row->id } = $row->name;
	}

	my $rs_data = $self->db->resultset("Cachegroup")->search( undef, { prefetch => [ { 'type' => undef, } ], order_by => 'me.' . $orderby } );
	while ( my $row = $rs_data->next ) {
		if ( defined $row->parent_cachegroup_id ) {
			push(
				@data, {
					"id"                   => $row->id,
					"name"                 => $row->name,
					"shortName"            => $row->short_name,
					"latitude"             => $row->latitude,
					"longitude"            => $row->longitude,
					"lastUpdated"          => $row->last_updated,
					"parentCachegroupId"   => $row->parent_cachegroup_id,
					"parentCachegroupName" => $idnames{ $row->parent_cachegroup_id },
					"typeId"               => $row->type->id,
					"typeName"             => $row->type->name,
				}
			);
		}
		else {
			push(
				@data, {
					"id"                   => $row->id,
					"name"                 => $row->name,
					"shortName"            => $row->short_name,
					"latitude"             => $row->latitude,
					"longitude"            => $row->longitude,
					"lastUpdated"          => $row->last_updated,
					"parentCachegroupId"   => $row->parent_cachegroup_id,
					"parentCachegroupName" => undef,
					"typeId"               => $row->type->id,
					"typeName"             => $row->type->name,
				}
			);
		}
	}
	$self->success( \@data );
}

# Read
sub index_trimmed {
	my $self = shift;
	my @data;
	my %idnames;
	my $orderby = $self->param('orderby') || "name";

	my $rs_data = $self->db->resultset("Cachegroup")->search( undef, { prefetch => [ { 'type' => undef, } ], order_by => 'me.' . $orderby } );
	while ( my $row = $rs_data->next ) {
		push(
			@data, {
				"name" => $row->name,
			}
		);
	}
	$self->success( \@data );
}

sub by_parameter_id {
	my $self    = shift;
	my $paramid = $self->param('paramid');

	my @data;
	my %dsids;
	my %in_use;

	# Get a list of all cachegroup id's associated with this param id
	my $rs_in_use = $self->db->resultset("CachegroupParameter")->search( { 'parameter' => $paramid } );
	while ( my $row = $rs_in_use->next ) {
		$in_use{ $row->cachegroup->id } = 1;
	}

	# Add remaining cachegroup ids to @data
	my $rs_links = $self->db->resultset("Cachegroup")->search( undef, { order_by => "name" } );
	while ( my $row = $rs_links->next ) {
		if ( !defined( $in_use{ $row->id } ) ) {
			push( @data, { "id" => $row->id, "name" => $row->name } );
		}
	}

	$self->success( { cachegroups => \@data } );
}

sub available_for_parameter {
	my $self = shift;
	my @data;
	my $paramid = $self->param('paramid');
	my %dsids;
	my %in_use;

	# Get a list of all profile id's associated with this param id
	my $rs_in_use = $self->db->resultset("CachegroupParameter")->search( { 'parameter' => $paramid } );
	while ( my $row = $rs_in_use->next ) {
		$in_use{ $row->cachegroup->id } = 1;
	}

	# Add remaining cachegroup ids to @data
	my $rs_links = $self->db->resultset("Cachegroup")->search( undef, { order_by => "name" } );
	while ( my $row = $rs_links->next ) {
		if ( !defined( $in_use{ $row->id } ) ) {
			push( @data, { "id" => $row->id, "name" => $row->name } );
		}
	}

	$self->success( \@data );
}

sub get_cachegroups {
    my $self = shift;
    my %data;
    my %cachegroups;
    my %short_names;
    my $rs = $self->db->resultset('Cachegroup');
    while ( my $cachegroup = $rs->next ) {
        $cachegroups{ $cachegroup->name }       = $cachegroup->id;
        $short_names{ $cachegroup->short_name } = $cachegroup->id;
    }
    %data = ( cachegroups => \%cachegroups, short_names => \%short_names );
    return \%data;
}

sub get_cachegroup_by_id {
    my $self = shift;
    my $id = shift;
    my $row;

    eval {
        $row = $self->db->resultset('Cachegroup')->find( { id => $id }, { prefetch => [ { 'type' => undef, } ]});
    };
    if ($@) {
        $self->app->log->error( "Failed to get cachegroup id = $id: $@" );
        return (undef, "Failed to get cachegroup id = $id: $@")
    }

    my $r;
    eval {
        $r = $self->db->resultset('Cachegroup')->find( { id => $row->parent_cachegroup_id } );
    };
    if ($@) {
        $self->app->log->error( "Failed to get cachegroup id = $id: $@" );
        return (undef, "Failed to get cachegroup id = $id: $@")
    }
    my $parentCachegroup = defined($r) ? $r->name : "";
    eval {
        $r = $self->db->resultset('Cachegroup')->find( { id => $row->secondary_parent_cachegroup_id } );
    };
    if ($@) {
        $self->app->log->error( "Failed to get cachegroup id = $id: $@" );
        return (undef, "Failed to get cachegroup id = $id: $@")
    }
    my $secondaryParentCachegroup = defined($r) ? $r->name : "";

    my $data = {
        "id"     => $row->id,
        "name"   => $row->name,
        "shortName"  => $row->short_name,
        "latitude"    => $row->latitude,
        "longitude"   => $row->longitude,
        "parentCachegroup" => $parentCachegroup,
        "parentCachegroupId" => $row->parent_cachegroup_id,
        "secondaryParentCachegroup" => $secondaryParentCachegroup,
        "secondaryParentCachegroupId" => $row->secondary_parent_cachegroup_id,
        "typeName"        => $row->type->name,
        "lastUpdated" => $row->last_updated,
    };
    return ($data, undef);
}

sub isValidCachegroup {
    my $self = shift;
    my $params = shift;
    my %errFields = ();

    if (!defined($params)) {
        return "parameters must be in JSON format,  please check!";
    }

    if (!defined($params->{'name'})) {
        $errFields{'name'} = 'is required';
    }
    if (!defined($params->{'shortName'})) {
        $errFields{'shorName'} = 'is required';
    }
    if (!defined($params->{typeName})){
        $errFields{'typeName'} = 'is required';
    }
    if (%errFields) {
        return \%errFields;
    }

    if (!($params->{'name'} =~ /^[0-9a-zA-Z_\.\-]+$/)) {
        return "Invalid name. Use alphanumeric . or _ .";
    }
    if (!($params->{'shortName'} =~ /^[0-9a-zA-Z_\.\-]+$/)) {
        return "Invalid shortName. Use alphanumeric . or _ .";
    }
    my $typeName = $params->{typeName};
    my $type_id = $self->get_typeId($typeName);
    if (!defined($type_id)) {
        return "Type ". $typeName . " is not a valid Cache Group type";
    }
    if (defined($params->{'latitude'})) {
        if(!($params->{'latitude'} =~ /^[-]*[0-9]+[.]*[0-9]*/)) {
            return "Invalid latitude entered. Must be a float number.";
        }
        if ( abs $params->{'latitude'} > 90 ) {
            return "Invalid latitude entered. May not exceed +- 90.0.";
        }
    }
    if (defined($params->{'longitude'})) {
        if(!($params->{'longitude'} =~ /^[-]*[0-9]+[.]*[0-9]*/)) {
            return "Invalid longitude entered. Must be a float number.";
        }
        if ( abs $params->{'longitude'} > 180 ) {
            return "Invalid longitude entered. May not exceed +- 180.0.";
        }
    }

	return undef;
}

sub create{
    my $self = shift;
    my $params = $self->req->json;
    if ( !&is_oper($self) ) {
        return $self->forbidden();
    }

    my $err = $self->isValidCachegroup($params);
    if (defined($err)) {
        return $self->alert($err);
    }

    my $cachegroups = $self->get_cachegroups();
    my $name    = $params->{name};
    my $shortName    = $params->{shortName};
    my $parentCachegroup = $params->{parentCachegroup};
    my $secondaryParentCachegroup = $params->{secondaryParentCachegroup};
    my $typeName = $params->{typeName};
    my $type_id = $self->get_typeId($typeName);

    if (exists $cachegroups->{'cachegroups'}->{$name}) {
        return $self->internal_server_error("cache_group_name[".$name."] already exists.");
    }
    if (exists $cachegroups->{'short_names'}->{$shortName}) {
        return $self->internal_server_error("cache_group_shortname[".$shortName."] already exists.");
    }

    my $parentCachegroupId = $cachegroups->{'cachegroups'}->{$parentCachegroup};
    $self->app->log->debug("parentCachegroup[". $parentCachegroup . "]");
    if ( $parentCachegroup ne ""  && !defined($parentCachegroupId) ) {
        return $self->alert("parentCachegroup ". $parentCachegroup . " does not exist.");
    }
    my $secondaryParentCachegroupId = $cachegroups->{'cachegroups'}->{$secondaryParentCachegroup};
    if ( $secondaryParentCachegroup ne ""  && !defined($secondaryParentCachegroupId) ) {
        return $self->alert("secondaryParentCachegroup ". $secondaryParentCachegroup . " does not exist.");
    }
    my $insert = $self->db->resultset('Cachegroup')->create(
        {
            name        => $name,
            short_name  => $shortName,
            latitude    => $params->{latitude},
            longitude  => $params->{longitude},
            parent_cachegroup_id => $parentCachegroupId,
            secondary_parent_cachegroup_id => $secondaryParentCachegroupId,
            type        => $type_id,
        }
    );
    $insert->insert();

    &log( $self, "Create cachegroup with name:" . $name, "APICHANGE" );

    my ($response, $err1) = $self->get_cachegroup_by_id($insert->id);
    if( defined($err1) ) {
        return $self->alert(
            { Error => $err1 }
        );
    }
    return $self->success($response, "Cachegroup successfully created: " . $name);
}

sub update{
    my $self = shift;
    my $params = $self->req->json;
    if ( !&is_oper($self) ) {
        return $self->forbidden();
    }

    my $err = $self->isValidCachegroup($params);
    if (defined($err)) {
        return $self->alert($err);
    }

    my $id = $self->param('id');
    my $update = $self->db->resultset('Cachegroup')->find( { id => $id } );
    if( !defined($update) ) {
        return $self->not_found();
    }

    my $type_id = undef;
    if (defined($params->{typeName})){
        my $typeName = $params->{typeName};
        $type_id = $self->get_typeId($typeName);
    }

    my $cachegroups = $self->get_cachegroups();
    my $parentCachegroupId = undef;
    if (defined($params->{parentCachegroup})){
        my $parentCachegroup = $params->{parentCachegroup};
        $parentCachegroupId = $cachegroups->{'cachegroups'}->{$parentCachegroup};
        if ( $parentCachegroup ne ""  && !defined($parentCachegroupId) ) {
            return $self->alert("parentCachegroup ". $parentCachegroup . " does not exist.");
        }
        if (defined($parentCachegroupId) && $parentCachegroupId == $id) {
            return $self->alert("Could not set the Cache Group itself as parent.");
        }
    }
    my $secondaryParentCachegroupId = undef;
    if (defined($params->{secondaryParentCachegroup})){
        my $secondaryParentCachegroup = $params->{secondaryParentCachegroup};
        $secondaryParentCachegroupId = $cachegroups->{'cachegroups'}->{$secondaryParentCachegroup};
        if ( $secondaryParentCachegroup ne ""  && !defined($secondaryParentCachegroupId) ) {
            return $self->alert("secondaryParentCachegroup ". $secondaryParentCachegroup . " does not exist.");
        }
        if (defined($secondaryParentCachegroupId) && $secondaryParentCachegroupId == $id) {
            return $self->alert("Could not set the Cache Group itself as secondary parent.");
        }
    }

    eval {
        $update->update(
            {
                name        => defined($params->{'name'}) ? $params->{'name'} : $update->name,
                short_name  => defined($params->{'shortName'}) ? $params->{'shortName'} : $update->short_name,
                latitude    => defined($params->{'latitude'}) ? $params->{'latitude'} : $update->latitude,
                longitude   => defined($params->{'longitude'}) ? $params->{'longitude'} : $update->longitude,
                parent_cachegroup_id            => defined($params->{parentCachegroup}) ? $parentCachegroupId : $update->parent_cachegroup_id,
                secondary_parent_cachegroup_id  => defined($params->{secondaryParentCachegroup}) ? $secondaryParentCachegroupId : $update->secondary_parent_cachegroup_id,
                type        => defined($type_id) ? $type_id : $update->type,
            }
        );
    };
    if ($@) {
        $self->app->log->error( "Failed to update cachegroup id = $id: $@" );
        return $self->alert(
            { Error => "Failed to update server: $@" }
        );
    }
    $update->update();

	&log( $self, "Update cachegroup with name:" . $update->name, "APICHANGE" );

    my ($response, $err1) = $self->get_cachegroup_by_id($id);
    if( defined($err1) ) {
        return $self->alert(
            { Error => $err1 }
        );
    }
    return $self->success($response, "Cachegroup was updated: " . $update->name);
}

sub delete{
    my $self = shift;
    my $rs;
    if ( !&is_oper($self) ) {
        return $self->forbidden();
    }

    my $id = $self->param('id');
    my $cg = $self->db->resultset('Cachegroup')->find( { id => $id } );
    if ( !defined($cg) ) {
        return $self->not_found();
    }
    $rs = $self->db->resultset('Cachegroup')->search( { parent_cachegroup_id => $id } );
    if ($rs->count() > 0) {
        $self->app->log->error( "Failed to delete cachegroup id = $id, which has children" );
        return $self->alert("Failed to delete cachegroup id = $id, which has children");
    }
    $rs = $self->db->resultset('Cachegroup')->search( { secondary_parent_cachegroup_id => $id } );
    if ($rs->count() > 0) {
        $self->app->log->error( "Failed to delete cachegroup id = $id, which has children" );
        return $self->alert("Failed to delete cachegroup id = $id, which has children");
    }
    $rs = $self->db->resultset('Server')->search( { cachegroup => $id } );
    if ($rs->count() > 0) {
        $self->app->log->error( "Failed to delete cachegroup id = $id has servers" );
        return $self->alert("Failed to delete cachegroup id = $id has servers");
    }
    my $delete = $self->db->resultset('Cachegroup')->search( { id => $id } );
    my $name = $delete->get_column('name')->single();
    $delete->delete();

    &log( $self, "Delete cachegroup " . $name, "APICHANGE" );

    return $self->success_message("Cachegroup was deleted: ". $name);
}

sub get_typeId {
    my $self      = shift;
    my $typeName = shift;

    my $rs = $self->db->resultset("Type")->find( { name => $typeName } );
    my $type_id;
    if (defined($rs) && ($rs->use_in_table eq "cachegroup")) {
        $type_id = $rs->id;
    }
    return($type_id);
}

sub postupdatequeue {
    my $self       = shift;
    my $params = $self->req->json;
    if ( !&is_oper($self) ) {
        return $self->forbidden("Forbidden. Insufficent privileges.");
    }

    my $name;
    my $id   = $self->param('id');
    $name = $self->db->resultset('Cachegroup')->search( { id => $id } )->get_column('name')->single();

    if (! defined($name)) {
        return $self->alert("cachegroup id[".$id."] does not exist.");
    }

    my $cdn = $params->{cdn};
    my $cdn_id = $self->db->resultset('Cdn')->search( { name => $cdn })->get_column('id')->single();
    if( !defined($cdn_id) ) {
        return $self->alert("cdn " . $cdn . " does not exist.");
    }

    my $setqueue = $params->{action};
    if ( !defined($setqueue)) {
        return $self->alert("action needed, should be queue or dequeue.");
    }
    if ( $setqueue eq "queue") {
        $setqueue = 1
    } elsif	($setqueue eq "dequeue") {
        $setqueue = 0
    } else {
        return $self->alert("action should be queue or dequeue.");
    }

    my @profiles;
    @profiles = $self->db->resultset('Server')->search(
        { 'cdn.name' => $cdn },
        {
            prefetch => 'cdn',
            select   => 'me.profile',
            distinct => 1
        }
    )->get_column('profile')->all();
    my $update = $self->db->resultset('Server')->search(
        {
            -and => [
                cachegroup => $id ,
                profile    => { -in => \@profiles }
            ]
        }
    );

    my $response;
    my @svrs = ();
    if ( $update->count() > 0 ) {
        $update->update( { upd_pending => $setqueue } );
        my @row = $update->get_column('host_name')->all();
        foreach my $svr ( @row ){
            push( @svrs, $svr);
        }
    }

    $response->{serverNames} = \@svrs;
    $response->{action}  = ($setqueue==1)?"queue":"dequeue";
    $response->{cdn}  = $cdn;
    $response->{cachegroupName}  = $name;
    $response->{cachegroupId} = $id;
    return $self->success($response);
}

1;


text:
// @namespace
var ARjs = ARjs || {}

/**
 * Create an anchor in the real world
 *
 * @param {ARjs.Session} arSession - the session on which we create the anchor
 * @param {Object} markerParameters - parameter of this anchor
 */
ARjs.HitTesting = function (arSession) {
    var _this = this
    var arContext = arSession.arContext
    var trackingBackend = arContext.parameters.trackingBackend

    this.enabled = true
    this._arSession = arSession
    this._hitTestingPlane = null
    _this._hitTestingPlane = new THREEx.HitTestingPlane(arSession.arSource.domElement)
}

//////////////////////////////////////////////////////////////////////////////
//		update function
//////////////////////////////////////////////////////////////////////////////
/**
 * update
 *
 * @param {THREE.Camera} camera   - the camera to use
 * @param {THREE.Object3D} object3d -
 */
ARjs.HitTesting.prototype.update = function (camera, pickingRoot, changeMatrixMode) {
    // if it isnt enabled, do nothing
    if (this.enabled === false) return

    if (this._hitTestingPlane !== null) {
        this._hitTestingPlane.update(camera, pickingRoot, changeMatrixMode)
    } else console.assert(false)
}

//////////////////////////////////////////////////////////////////////////////
//		actual hit testing
//////////////////////////////////////////////////////////////////////////////

/**
 * Test the real world for intersections directly from a DomEvent
 *
 * @param {Number} mouseX - position X of the hit [-1, +1]
 * @param {Number} mouseY - position Y of the hit [-1, +1]
 * @return {[ARjs.HitTesting.Result]} - array of result
 */
ARjs.HitTesting.prototype.testDomEvent = function (domEvent) {
    var trackingBackend = this._arSession.arContext.parameters.trackingBackend
    var arSource = this._arSession.arSource

    // if it isnt enabled, do nothing
    if (this.enabled === false) return []
    var mouseX = domEvent.clientX / arSource.domElementWidth()
    var mouseY = domEvent.clientY / arSource.domElementHeight()

    return this.test(mouseX, mouseY)
}

/**
 * Test the real world for intersections.
 *
 * @param {Number} mouseX - position X of the hit [0, +1]
 * @param {Number} mouseY - position Y of the hit [0, +1]
 * @return {[ARjs.HitTesting.Result]} - array of result
 */
ARjs.HitTesting.prototype.test = function (mouseX, mouseY) {
    var arContext = this._arSession.arContext
    var trackingBackend = arContext.parameters.trackingBackend
    var hitTestResults = []

    // if it isnt enabled, do nothing
    if (this.enabled === false) return []

    var result = this._hitTestingPlane.test(mouseX, mouseY)

    // if no result is found, return now
    if (result === null) return hitTestResults

    // build a ARjs.HitTesting.Result
    var hitTestResult = new ARjs.HitTesting.Result(result.position, result.quaternion, result.scale)
    hitTestResults.push(hitTestResult)

    return hitTestResults
}

//////////////////////////////////////////////////////////////////////////////
//		ARjs.HitTesting.Result
//////////////////////////////////////////////////////////////////////////////
/**
 * Contains the result of ARjs.HitTesting.test()
 *
 * @param {THREE.Vector3} position - position to use
 * @param {THREE.Quaternion} quaternion - quaternion to use
 * @param {THREE.Vector3} scale - scale
 */
ARjs.HitTesting.Result = function (position, quaternion, scale) {
    this.position = position
    this.quaternion = quaternion
    this.scale = scale
}

/**
 * Apply to a controlled object3d
 *
 * @param {THREE.Object3D} object3d - the result to apply
 */
ARjs.HitTesting.Result.prototype.apply = function (object3d) {
    object3d.position.copy(this.position)
    object3d.quaternion.copy(this.quaternion)
    object3d.scale.copy(this.scale)

    object3d.updateMatrix()
}

/**
 * Apply to a controlled object3d
 *
 * @param {THREE.Object3D} object3d - the result to apply
 */
ARjs.HitTesting.Result.prototype.applyPosition = function (object3d) {
    object3d.position.copy(this.position)

    object3d.updateMatrix()

    return this
}

/**
 * Apply to a controlled object3d
 *
 * @param {THREE.Object3D} object3d - the result to apply
 */
ARjs.HitTesting.Result.prototype.applyQuaternion = function (object3d) {
    object3d.quaternion.copy(this.quaternion)

    object3d.updateMatrix()

    return this
}

redpajama_set_name: RedPajamaGithub


text:
<md-sidenav  id="sidenav-right" class="md-sidenav-right md-whiteframe-z2 mini-scroll" md-component-id="right">

Welcome, Administrator

            <md-button class="md-fab md-mini md-primary" data-toggle="dropdown">
              <md-tooltip>Default Theme Palette</md-tooltip>
            </md-button>

            <md-tooltip>
                {{w}}
            </md-tooltip>

    <md-content>
        <md-list  ng-cloak>
            <md-list-item ng-click="gotoUrl('/#/?url=app%2Fmodules%2Fprofile&theme=red&title=profile')">
                <md-icon>

                </md-icon>

Profile

            </md-list-item>
            <md-list-item ng-click="navigateTo('settings', $event)">
                <md-icon>

                </md-icon>

Settings

            </md-list-item>
            <md-list-item ng-click="gotoUrl('/lockscreen.html')">
                <md-icon>

                </md-icon>

Lock Screen

            </md-list-item>
            <md-list-item ng-click="gotoUrl('/login.html')">
                <md-icon>

                </md-icon>

Logout

            </md-list-item>
            <md-list-item >
                <md-icon>

                </md-icon>

 Boxed Layout

                <md-switch class="md-secondary"  ng-true-value="'1'" ng-false-value="'0'" ng-model="appCfg.currentLayout"></md-switch>
            </md-list-item>
            <md-list-item >
                <md-icon>

                </md-icon>

 Tab Wrapper

                <md-switch  class="md-secondary" ng-disabled="appCfg.isFullScreen == '1'"  ng-true-value="'1'" ng-false-value="'0'" ng-model="appCfg.openInsetTab"></md-switch>
            </md-list-item>
            <md-list-item >
                <md-icon>

                </md-icon>

 Show Footer

                <md-switch class="md-secondary"  ng-true-value="'1'" ng-false-value="'0'"  ng-model="appCfg.footerEnabled"></md-switch>
            </md-list-item>
            <md-divider></md-divider>

            <md-subheader class="md-no-sticky">Todos Action Checkboxes</md-subheader>
            <md-list-item ng-repeat="topping in toppings">

 {{ topping.name }}

                <md-checkbox class="md-secondary" ng-model="topping.wanted"></md-checkbox>
            </md-list-item>
            <md-divider></md-divider>
            <md-subheader class="md-no-sticky">Messages with Avatar  </md-subheader>
            <md-list-item ng-repeat="person in people" ng-click="goToPerson(person.name, $event)">

{{ person.name }}

                <md-icon  class="md-secondary md-hue-3" ng-class="{'md-primary': person.newMessage}">

                </md-icon>
            </md-list-item>
        </md-list>
    </md-content>
</md-sidenav>


text:
> [CodeIgniter](http://www.codeigniter.com/), a powerful PHP framework with a very small footprint, built for developers who need a simple and elegant toolkit to create full-featured web applications.

TODO:

- why ci is outdated
- some improvement for ci, change index.php location for secure, command line application


text:
package com.java.inheritance02;

public class BaseFruit {

	public enum FruitColor {
		YELLOW, ORANGE, GREEN, BROWN
	}

	public enum FruitTaste {
		SWEET, SOUR, ROTTEN
	}

	private FruitColor color;
	private FruitTaste taste;

	protected BaseFruit(FruitColor color, FruitTaste taste) {
		this.color = color;
		this.taste = taste;
	}

	public FruitColor getFruitColor() {
		return color;
	}

	public FruitTaste getFruitTaste() {
		return taste;
	}

	public void spoilFruit() {
		color = FruitColor.BROWN;
		taste = FruitTaste.ROTTEN;
	}
}


text:
<?php

namespace BsbFlysystemTest\Adapter\Factory;

use BsbFlysystem\Adapter\Factory\LocalAdapterFactory;
use BsbFlysystemTest\Bootstrap;
use BsbFlysystemTest\Framework\TestCase;

class LocalAdapterFactoryTest extends TestCase
{
    /**
     * @var \ReflectionProperty
     */
    protected $property;

    /**
     * @var \ReflectionMethod
     */
    protected $method;

    public function setup()
    {
        $class          = new \ReflectionClass('BsbFlysystem\Adapter\Factory\LocalAdapterFactory');
        $this->property = $class->getProperty('options');
        $this->property->setAccessible(true);

        $this->method = $class->getMethod('validateConfig');
        $this->method->setAccessible(true);
    }

    public function testCreateService()
    {
        $sm      = Bootstrap::getServiceManager();
        $manager = $sm->get('BsbFlysystemAdapterManager');

        $factory = new LocalAdapterFactory();

        $adapter = $factory->createService($manager, 'localdefault', 'local_default');

        $this->assertInstanceOf('League\Flysystem\Adapter\Local', $adapter);
    }

    /**
     * @dataProvider validateConfigProvider
     */
    public function testValidateConfig(
        $options,
        $expectedOptions = false,
        $expectedException = false,
        $expectedExceptionMessage = false
    ) {
        $factory = new LocalAdapterFactory($options);

        if ($expectedException) {
            $this->setExpectedException($expectedException, $expectedExceptionMessage);
        }

        $this->method->invokeArgs($factory, []);

        if (is_array($expectedOptions)) {
            $this->assertEquals($expectedOptions, $this->property->getValue($factory));
        }
    }

    public function validateConfigProvider()
    {
        return [
            [
                [],
                false,
                'UnexpectedValueException',
                "Missing 'root' as option"
            ],
            [
                ['root' => '.'],
                ['root' => '.']
            ],
        ];
    }
}


text:
package io.netty.channel.kqueue;

import io.netty.bootstrap.Bootstrap;
import io.netty.testsuite.transport.TestsuitePermutation.BootstrapComboFactory;
import io.netty.testsuite.transport.socket.DatagramUnicastIPv6MappedTest;

import java.util.List;

public class KQueueDatagramUnicastIPv6MappedTest extends DatagramUnicastIPv6MappedTest {
    @Override
    protected List<BootstrapComboFactory<Bootstrap, Bootstrap>> newFactories() {
        return KQueueSocketTestPermutation.INSTANCE.datagram(internetProtocolFamily());
    }
}


text:
#include <boost/filesystem.hpp>

#include <osquery/core.h>
#include <osquery/tables.h>
#include <osquery/filesystem.h>
#include <osquery/logger.h>

#include "osquery/core/conversions.h"

namespace fs = boost::filesystem;
namespace pt = boost::property_tree;

namespace osquery {
namespace tables {

const std::vector<std::string> kLibraryStartupItemPaths = {
    "/System/Library/StartupItems/", "/Library/StartupItems/",
};

// Path (after /Users/foo) where the login items plist will be found
const std::string kLoginItemsPlistPath =
    "Library/Preferences/com.apple.loginitems.plist";

// Key to the array within the Login Items plist containing the items
const std::vector<std::string> kLoginItemsKeyPaths = {
    "SessionItems.CustomListItems", "privilegedlist.CustomListItems",
};

void genLibraryStartupItems(const std::string& sysdir, QueryData& results) {
  try {
    fs::directory_iterator it((fs::path(sysdir))), end;
    for (; it != end; ++it) {
      if (!fs::exists(it->status()) || !fs::is_directory(it->status())) {
        continue;
      }

      Row r;
      r["name"] = it->path().string();
      r["path"] = it->path().string();
      r["type"] = "Startup Item";
      r["status"] = "enabled";
      r["source"] = sysdir;
      results.push_back(r);
    }
  } catch (const fs::filesystem_error& e) {
    VLOG(1) << "Error traversing " << sysdir << ": " << e.what();
  }
}

/// Parse a Login Items Plist Alias data for bin path
Status parseAliasData(const std::string& data, std::string& result) {
  auto decoded = base64Decode(data);
  if (decoded.size() == 0) {
    // Base64 encoded data (from plist parsing) failed to decode.
    return Status(1, "Failed base64 decode");
  }

  auto alias = CFDataCreate(
      kCFAllocatorDefault, (const UInt8*)decoded.c_str(), decoded.size());
  if (alias == nullptr) {
    // Failed to create CFData object.
    return Status(2, "CFData allocation failed");
  }

  auto bookmark =
      CFURLCreateBookmarkDataFromAliasRecord(kCFAllocatorDefault, alias);
  if (bookmark == nullptr) {
    CFRelease(alias);
    return Status(1, "Alias data is not a bookmark");
  }

  auto url = CFURLCreateByResolvingBookmarkData(
      kCFAllocatorDefault, bookmark, 0, nullptr, nullptr, nullptr, nullptr);
  if (url == nullptr) {
    CFRelease(alias);
    CFRelease(bookmark);
    return Status(1, "Alias data is not a URL bookmark");
  }

  // Get the URL-formatted path.
  result = stringFromCFString(CFURLGetString(url));
  if (result.substr(0, 7) == "file://") {
    result = result.substr(7);
  }

  CFRelease(alias);
  CFRelease(bookmark);
  CFRelease(url);
  return Status(0, "OK");
}

void genLoginItems(const fs::path& homedir, QueryData& results) {
  pt::ptree tree;
  fs::path sipath = homedir / kLoginItemsPlistPath;
  if (!pathExists(sipath.string()).ok() || !isReadable(sipath.string()).ok()) {
    // User does not have a startup items list, or bad permissions.
    return;
  }

  if (!osquery::parsePlist(sipath.string(), tree).ok()) {
    // Could not parse the user's startup items plist.
    return;
  }

  // Enumerate Login Items if we successfully opened the plist.
  for (const auto& plist_path : kLoginItemsKeyPaths) {
    try {
      for (const auto& entry : tree.get_child(plist_path)) {
        Row r;
        r["name"] = entry.second.get<std::string>("Name", "");
        r["type"] = "Login Item";
        r["source"] = sipath.string();

        auto alias_data = entry.second.get<std::string>("Alias", "");
        std::string bin_path;
        if (!parseAliasData(alias_data, bin_path).ok()) {
          VLOG(1) << "No valid path found for " << r["name"] << " in "
                  << sipath;
        }
        r["path"] = bin_path;
        results.push_back(r);
      }
    } catch (const pt::ptree_error& e) {
      continue;
    }
  }
}

QueryData genStartupItems(QueryContext& context) {
  QueryData results;

  // Get the login items available for all users
  genLoginItems("/", results);

  // Get the login items available in System Preferences for each user.
  for (const auto& dir : getHomeDirectories()) {
    genLoginItems(dir, results);
  }

  // Find system wide startup items in Library directories.
  for (const auto& dir : kLibraryStartupItemPaths) {
    genLibraryStartupItems(dir, results);
  }

  return results;
}
}
}


text:
function Contact(){

}


text:
var gulp = require('gulp'),
    less = require('gulp-less'),
    runSequence = require('run-sequence'),
    args = require('yargs').argv,
    minifycss = require('gulp-minify-css'),
    concat = require('gulp-concat'),
    linker = require('gulp-linker'),
    uglify = require('gulp-uglify'),
    traceur = require('gulp-traceur'),
    del = require('del'),
    karma = require('karma').server,

    baseOutputFolder = 'build',

    fileNameBase = 'weather',
    lessFileName = fileNameBase + '.less',
    cssFileName = fileNameBase + '.css',
    cssMinifiedFileName = fileNameBase + '.min.css',

    cssFolder = 'css',
    customCssFolder = cssFolder + '/custom',
    cssOutputFolder = baseOutputFolder + '/css',

    scriptsOutputFolder = baseOutputFolder + '/js',

    scriptsSourceFolder = 'js/app',
    minifiedSourcesFileName = fileNameBase + '.min.js',

    isProduction = args.prod;

gulp.task('lessToCss', function() {
    gulp.src(customCssFolder + '/' + lessFileName)
        .pipe(less())
        .pipe(gulp.dest(customCssFolder));

    if (isProduction) {
        return gulp.src([cssFolder + '/**/*.css'])
            .pipe(concat(cssMinifiedFileName))
            .pipe(minifycss())
            .pipe(gulp.dest(cssOutputFolder));
    }
});

gulp.task('linkCss', function() {
    return gulp.src('./index.html')
        .pipe(linker({
            scripts: isProduction ? [cssOutputFolder + '/' + cssMinifiedFileName] : [cssFolder + '/*.css', customCssFolder + '/' + cssFileName],
            startTag: '<!--STYLES-->',
            endTag: '<!--STYLES END-->',
            fileTmpl: '<link rel="stylesheet" href="%s">',
            appRoot: ''
        }))
        .pipe(gulp.dest('./'));
});

gulp.task('minifyAppScripts', function() {
    var result = gulp.src([scriptsSourceFolder + '/**/*Module.js', scriptsSourceFolder + '/**/*.js'])
        .pipe(traceur());

    if (isProduction) {
        result = result.pipe(concat(minifiedSourcesFileName))
            .pipe(uglify());
    }

    return result.pipe(gulp.dest(scriptsOutputFolder));
});

gulp.task('linkScripts', function() {
    return gulp.src('./index.html')
        .pipe(linker({
            scripts: isProduction ? [(scriptsOutputFolder + '/' + minifiedSourcesFileName)] : [(scriptsOutputFolder + '/' + '/**/*Module.js'), (scriptsOutputFolder + '/' + '/**/*.js')],
            startTag: '<!--SCRIPTS-->',
            endTag: '<!--SCRIPTS END-->',
            fileTmpl: '<script type="text/javascript" src="%s"></script>',
            appRoot: ''
        }))
        .pipe(gulp.dest('./'));
});

gulp.task('clean', function(cb) {
    del([baseOutputFolder], cb);
});

gulp.task('runUnitTests', function(done) {
    karma.start({
        configFile: process.cwd() + '/unittests.conf.js',
        singleRun: true
    }, done);
})

gulp.task('default', function(callback) {
    runSequence('clean',
        'lessToCss',
        'linkCss',
        'minifyAppScripts',
        'linkScripts',
        'runUnitTests',
        callback);
});


text:
require 'inherited_resources'

module InheritedViews
  class Base < ::InheritedResources::Base

    # Set the name of the folder of the default views to use
    # within the view path.
    #
    # For example, if I want to set the default views for my
    # application to app/views/my_defaults/*.html.erb I would
    #
    #   InheritedViews::Base.default_views = 'my_defaults'
    #
    # You can also override for one specific controller from
    # within it:
    #
    #   class UsersController < InheritedViews::Base
    #     self.default_views = "my_default_admin_views"
    #   end
    #
    # which would then use app/views/my_default_admin_views
    #
    class_inheritable_accessor :default_views
    self.default_views = 'inherited_views_default'

    # Add our default views to the base path
    ActionController::Base.append_view_path File.expand_path('../default_views', __FILE__)

    include TableBuilder

    #
    #  Actions
    #

    def index
      super do |format|
        format.html { render_or_default 'index' }
      end
    end

    def new
      super do |format|
        format.html { render_or_default 'new' }
      end
    end

    def create
      create! do |success, failure|
        failure.html { render_or_default 'new' }
      end
    end

    def show
      super do |format|
        format.html { render_or_default 'show' }
      end
    end

    def edit
      super do |format|
        format.html { render_or_default 'edit' }
      end
    end

    def update
      update! do |success, failure|
        failure.html { render_or_default 'edit' }
      end
    end

    protected

    # Overriding so that we have pagination by default
    def collection
      get_collection_ivar || set_collection_ivar(end_of_association_chain.paginate(:page => params[:page]))
    end

    def show_view_columns
      resource_class.columns.collect{|column| column.name.to_sym  }
    end
    helper_method :show_view_columns

    def resource_name
      resource_class.human_name
    end
    helper_method :resource_name

    def resources_name
      resource_name.pluralize
    end
    helper_method :resources_name

    private

    # All the magic lives here :)
    #
    # This method tries to render the view you pass it, otherwise it
    # renders the view from the default view folder
    #
    def render_or_default(name, args = {})
      render name, args
    rescue ActionView::MissingTemplate
      render args.merge(:template => "#{self.class.default_views}/#{name}", :prefix => '')
    end

  end
end


text:
Originally published: 2005-12-07 22:33:00
Last updated: 2005-12-07 22:33:00
Author: Patrick Finnegan

Run DDL against a Cloudscape database using batchupdate SQL.


text:
#ifndef __MTD_ABI_H__
#define __MTD_ABI_H__

#include <linux/types.h>

struct erase_info_user {
	__u32 start;
	__u32 length;
};

struct erase_info_user64 {
	__u64 start;
	__u64 length;
};

struct mtd_oob_buf {
	__u32 start;
	__u32 length;
	unsigned char __user *ptr;
};

struct mtd_oob_buf64 {
	__u64 start;
	__u32 pad;
	__u32 length;
	__u64 usr_ptr;
};

/**
 * MTD operation modes
 *
 * @MTD_OPS_PLACE_OOB:	OOB data are placed at the given offset (default)
 * @MTD_OPS_AUTO_OOB:	OOB data are automatically placed at the free areas
 *			which are defined by the internal ecclayout
 * @MTD_OPS_RAW:	data are transferred as-is, with no error correction;
 *			this mode implies %MTD_OPS_PLACE_OOB
 *
 * These modes can be passed to ioctl(MEMWRITE) and are also used internally.
 * See notes on "MTD file modes" for discussion on %MTD_OPS_RAW vs.
 * %MTD_FILE_MODE_RAW.
 */
enum {
	MTD_OPS_PLACE_OOB = 0,
	MTD_OPS_AUTO_OOB = 1,
	MTD_OPS_RAW = 2,
};

/**
 * struct mtd_write_req - data structure for requesting a write operation
 *
 * @start:	start address
 * @len:	length of data buffer
 * @ooblen:	length of OOB buffer
 * @usr_data:	user-provided data buffer
 * @usr_oob:	user-provided OOB buffer
 * @mode:	MTD mode (see "MTD operation modes")
 * @padding:	reserved, must be set to 0
 *
 * This structure supports ioctl(MEMWRITE) operations, allowing data and/or OOB
 * writes in various modes. To write to OOB-only, set @usr_data == NULL, and to
 * write data-only, set @usr_oob == NULL. However, setting both @usr_data and
 * @usr_oob to NULL is not allowed.
 */
struct mtd_write_req {
	__u64 start;
	__u64 len;
	__u64 ooblen;
	__u64 usr_data;
	__u64 usr_oob;
	__u8 mode;
	__u8 padding[7];
};

#define MTD_ABSENT		0
#define MTD_RAM			1
#define MTD_ROM			2
#define MTD_NORFLASH		3
#define MTD_NANDFLASH		4	/* SLC NAND */
#define MTD_DATAFLASH		6
#define MTD_UBIVOLUME		7
#define MTD_MLCNANDFLASH	8	/* MLC NAND (including TLC) */

#define MTD_WRITEABLE		0x400	/* Device is writeable */
#define MTD_BIT_WRITEABLE	0x800	/* Single bits can be flipped */
#define MTD_NO_ERASE		0x1000	/* No erase necessary */
#define MTD_POWERUP_LOCK	0x2000	/* Always locked after reset */

/* Some common devices / combinations of capabilities */
#define MTD_CAP_ROM		0
#define MTD_CAP_RAM		(MTD_WRITEABLE | MTD_BIT_WRITEABLE | MTD_NO_ERASE)
#define MTD_CAP_NORFLASH	(MTD_WRITEABLE | MTD_BIT_WRITEABLE)
#define MTD_CAP_NANDFLASH	(MTD_WRITEABLE)
#define MTD_CAP_NVRAM		(MTD_WRITEABLE | MTD_BIT_WRITEABLE | MTD_NO_ERASE)

/* Obsolete ECC byte placement modes (used with obsolete MEMGETOOBSEL) */
#define MTD_NANDECC_OFF		0	// Switch off ECC (Not recommended)
#define MTD_NANDECC_PLACE	1	// Use the given placement in the structure (YAFFS1 legacy mode)
#define MTD_NANDECC_AUTOPLACE	2	// Use the default placement scheme
#define MTD_NANDECC_PLACEONLY	3	// Use the given placement in the structure (Do not store ecc result on read)
#define MTD_NANDECC_AUTOPL_USR 	4	// Use the given autoplacement scheme rather than using the default

/* OTP mode selection */
#define MTD_OTP_OFF		0
#define MTD_OTP_FACTORY		1
#define MTD_OTP_USER		2

struct mtd_info_user {
	__u8 type;
	__u32 flags;
	__u32 size;	/* Total size of the MTD */
	__u32 erasesize;
	__u32 writesize;
	__u32 oobsize;	/* Amount of OOB data per block (e.g. 16) */
	__u64 padding;	/* Old obsolete field; do not use */
};

struct region_info_user {
	__u32 offset;		/* At which this region starts,
				 * from the beginning of the MTD */
	__u32 erasesize;	/* For this region */
	__u32 numblocks;	/* Number of blocks in this region */
	__u32 regionindex;
};

struct otp_info {
	__u32 start;
	__u32 length;
	__u32 locked;
};

/*
 * Note, the following ioctl existed in the past and was removed:
 * #define MEMSETOOBSEL           _IOW('M', 9, struct nand_oobinfo)
 * Try to avoid adding a new ioctl with the same ioctl number.
 */

/* Get basic MTD characteristics info (better to use sysfs) */
#define MEMGETINFO		_IOR('M', 1, struct mtd_info_user)
/* Erase segment of MTD */
#define MEMERASE		_IOW('M', 2, struct erase_info_user)
/* Write out-of-band data from MTD */
#define MEMWRITEOOB		_IOWR('M', 3, struct mtd_oob_buf)
/* Read out-of-band data from MTD */
#define MEMREADOOB		_IOWR('M', 4, struct mtd_oob_buf)
/* Lock a chip (for MTD that supports it) */
#define MEMLOCK			_IOW('M', 5, struct erase_info_user)
/* Unlock a chip (for MTD that supports it) */
#define MEMUNLOCK		_IOW('M', 6, struct erase_info_user)
/* Get the number of different erase regions */
#define MEMGETREGIONCOUNT	_IOR('M', 7, int)
/* Get information about the erase region for a specific index */
#define MEMGETREGIONINFO	_IOWR('M', 8, struct region_info_user)
/* Get info about OOB modes (e.g., RAW, PLACE, AUTO) - legacy interface */
#define MEMGETOOBSEL		_IOR('M', 10, struct nand_oobinfo)
/* Check if an eraseblock is bad */
#define MEMGETBADBLOCK		_IOW('M', 11, __kernel_loff_t)
/* Mark an eraseblock as bad */
#define MEMSETBADBLOCK		_IOW('M', 12, __kernel_loff_t)
/* Set OTP (One-Time Programmable) mode (factory vs. user) */
#define OTPSELECT		_IOR('M', 13, int)
/* Get number of OTP (One-Time Programmable) regions */
#define OTPGETREGIONCOUNT	_IOW('M', 14, int)
/* Get all OTP (One-Time Programmable) info about MTD */
#define OTPGETREGIONINFO	_IOW('M', 15, struct otp_info)
/* Lock a given range of user data (must be in mode %MTD_FILE_MODE_OTP_USER) */
#define OTPLOCK			_IOR('M', 16, struct otp_info)
/* Get ECC layout (deprecated) */
#define ECCGETLAYOUT		_IOR('M', 17, struct nand_ecclayout_user)
/* Get statistics about corrected/uncorrected errors */
#define ECCGETSTATS		_IOR('M', 18, struct mtd_ecc_stats)
/* Set MTD mode on a per-file-descriptor basis (see "MTD file modes") */
#define MTDFILEMODE		_IO('M', 19)
/* Erase segment of MTD (supports 64-bit address) */
#define MEMERASE64		_IOW('M', 20, struct erase_info_user64)
/* Write data to OOB (64-bit version) */
#define MEMWRITEOOB64		_IOWR('M', 21, struct mtd_oob_buf64)
/* Read data from OOB (64-bit version) */
#define MEMREADOOB64		_IOWR('M', 22, struct mtd_oob_buf64)
/* Check if chip is locked (for MTD that supports it) */
#define MEMISLOCKED		_IOR('M', 23, struct erase_info_user)
/*
 * Most generic write interface; can write in-band and/or out-of-band in various
 * modes (see "struct mtd_write_req"). This ioctl is not supported for flashes
 * without OOB, e.g., NOR flash.
 */
#define MEMWRITE		_IOWR('M', 24, struct mtd_write_req)

/*
 * Obsolete legacy interface. Keep it in order not to break userspace
 * interfaces
 */
struct nand_oobinfo {
	__u32 useecc;
	__u32 eccbytes;
	__u32 oobfree[8][2];
	__u32 eccpos[32];
};

struct nand_oobfree {
	__u32 offset;
	__u32 length;
};

#define MTD_MAX_OOBFREE_ENTRIES	8
#define MTD_MAX_ECCPOS_ENTRIES	64
/*
 * OBSOLETE: ECC layout control structure. Exported to user-space via ioctl
 * ECCGETLAYOUT for backwards compatbility and should not be mistaken as a
 * complete set of ECC information. The ioctl truncates the larger internal
 * structure to retain binary compatibility with the static declaration of the
 * ioctl. Note that the "MTD_MAX_..._ENTRIES" macros represent the max size of
 * the user struct, not the MAX size of the internal OOB layout representation.
 */
struct nand_ecclayout_user {
	__u32 eccbytes;
	__u32 eccpos[MTD_MAX_ECCPOS_ENTRIES];
	__u32 oobavail;
	struct nand_oobfree oobfree[MTD_MAX_OOBFREE_ENTRIES];
};

/**
 * struct mtd_ecc_stats - error correction stats
 *
 * @corrected:	number of corrected bits
 * @failed:	number of uncorrectable errors
 * @badblocks:	number of bad blocks in this partition
 * @bbtblocks:	number of blocks reserved for bad block tables
 */
struct mtd_ecc_stats {
	__u32 corrected;
	__u32 failed;
	__u32 badblocks;
	__u32 bbtblocks;
};

/*
 * MTD file modes - for read/write access to MTD
 *
 * @MTD_FILE_MODE_NORMAL:	OTP disabled, ECC enabled
 * @MTD_FILE_MODE_OTP_FACTORY:	OTP enabled in factory mode
 * @MTD_FILE_MODE_OTP_USER:	OTP enabled in user mode
 * @MTD_FILE_MODE_RAW:		OTP disabled, ECC disabled
 *
 * These modes can be set via ioctl(MTDFILEMODE). The mode mode will be retained
 * separately for each open file descriptor.
 *
 * Note: %MTD_FILE_MODE_RAW provides the same functionality as %MTD_OPS_RAW -
 * raw access to the flash, without error correction or autoplacement schemes.
 * Wherever possible, the MTD_OPS_* mode will override the MTD_FILE_MODE_* mode
 * (e.g., when using ioctl(MEMWRITE)), but in some cases, the MTD_FILE_MODE is
 * used out of necessity (e.g., `write()', ioctl(MEMWRITEOOB64)).
 */
enum mtd_file_modes {
	MTD_FILE_MODE_NORMAL = MTD_OTP_OFF,
	MTD_FILE_MODE_OTP_FACTORY = MTD_OTP_FACTORY,
	MTD_FILE_MODE_OTP_USER = MTD_OTP_USER,
	MTD_FILE_MODE_RAW,
};

static inline int mtd_type_is_nand_user(const struct mtd_info_user *mtd)
{
	return mtd->type == MTD_NANDFLASH || mtd->type == MTD_MLCNANDFLASH;
}

#endif /* __MTD_ABI_H__ */


text:
import urllib
import sys

def check_menu(key_word="Risotto", day=0, verbose=False):
    if day == '42':
        return 1
    run_for_lunch = 0
    try:
        url = "https://gastro.lunchgate.ch/widget.php?type=standardpremium&id=652&day=" + \
            str(day)
        html_doc = urllib.urlopen(url).read().lower()

        try:
            from bs4 import BeautifulSoup
            soup = BeautifulSoup(html_doc, "html.parser")
            table = soup.find("table", attrs={"class": "dailymenus"})
            all_cells = [td.get_text()
                         for td in table.find("tr").find_all("td")]
            if key_word.lower() in all_cells[0]:
                run_for_lunch = 1
            if verbose:
                if run_for_lunch:
                    print 'Lucky you!'
                else:
                    print 'Nope :('
                print all_cells[0].capitalize()

        except ImportError:
            # Take only first choice into account
            portare = html_doc.find('class="price"')
            if html_doc.find(key_word.lower()) > -1 and html_doc.find(key_word.lower()) < portare:
                run_for_lunch = 1
            if verbose:
                if run_for_lunch:
                    print 'Lucky you!'
                else:
                    print 'Nope :('

    except ValueError:
        run_for_lunch = 0

    return run_for_lunch

if __name__ == '__main__':
    if len(sys.argv) < 3:
        print 'False'
    else:
        oggi = check_menu(key_word=sys.argv[
                          1], day=sys.argv[2], verbose=False)
        print oggi


text:
<?php

namespace ChrisHemmings\OAuth2\Client\Provider;

use League\OAuth2\Client\Provider\AbstractProvider;
use League\OAuth2\Client\Provider\Exception\IdentityProviderException;
use League\OAuth2\Client\Provider\ResourceOwnerInterface;
use League\OAuth2\Client\Token\AccessToken;
use League\OAuth2\Client\Tool\BearerAuthorizationTrait;
use Psr\Http\Message\ResponseInterface;

class DigitalOcean extends AbstractProvider
{
    use BearerAuthorizationTrait;

    /**
     * Get authorization url to begin OAuth flow
     *
     * @return string
     */
    public function getBaseAuthorizationUrl()
    {
        return 'https://cloud.digitalocean.com/v1/oauth/authorize';
    }

    /**
     * Get access token url to retrieve token
     *
     * @param array $params
     *
     * @return string
     */
    public function getBaseAccessTokenUrl(array $params)
    {
        return 'https://cloud.digitalocean.com/v1/oauth/token';
    }

    /**
     * Get provider url to fetch user details
     *
     * @param AccessToken $token
     *
     * @return string
     */
    public function getResourceOwnerDetailsUrl(AccessToken $token)
    {
        return 'https://api.digitalocean.com/v2/account?' . http_build_query(['access_token' => $token->getToken()]);
    }

    /**
     * Get the default scopes used by this provider.
     *
     * @return array
     */
    protected function getDefaultScopes()
    {
        return [];
    }

    /**
     * Check a provider response for errors.
     *
     * @param ResponseInterface $response
     * @param array|string $data
     *
     * @throws IdentityProviderException
     */
    protected function checkResponse(ResponseInterface $response, $data)
    {
        if ($response->getStatusCode() >= 400) {
            throw new IdentityProviderException(
                $data['error'] ?: $response->getReasonPhrase(),
                $response->getStatusCode(),
                $response
            );
        }
    }

    /**
     * Generate a user object from a successful user details request.
     *
     * @param array $response
     * @param AccessToken $token
     *
     * @return League\OAuth2\Client\Provider\ResourceOwnerInterface
     */
    protected function createResourceOwner(array $response, AccessToken $token)
    {
        return new DigitalOceanResourceOwner($response);
    }
}


text:
/***********************************************************************************************************************
 *
 * FixBro - an open source FIX broker (sell side) simulator
 * =========================================================
 *
 * https://github.com/embosfer
 *
 ***********************************************************************************************************************
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
 * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
 * specific language governing permissions and limitations under the License.
 *
 ***********************************************************************************************************************/
package com.embosfer.fixbro.controller.er.processor;

import com.embosfer.fixbro.model.messages.ExecutionReport;

/**
 * This component gets {@code ExecutionReport} messages and processes them
 * applying a certain strategy
 *
 * @author embosfer
 *
 */
public interface ExecutionReportProcessor {

	public void process(ExecutionReport er);
}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <!--<color name="colorPrimary">#3F51B5</color>-->
    <color name="colorPrimary">#FFD700</color>
    <!--<color name="colorPrimaryDark">#303F9F</color>-->
    <color name="colorPrimaryDark">#EFCC00</color>
    <!--<color name="colorAccent">#FF4081</color>-->
    <color name="colorAccent">#c62828</color>

    <color name="black_overlay">#000000</color>
    <color name="white_overlay">#FFFFFF</color>

    <color name="color_greyed_button">#EEEEEE</color>

    <color name="grey_overlay">#696969</color>
    <color name="blue_overlay">#545AA7</color>
</resources>


text:
package policy

import (
	"errors"
	"fmt"
	"io"

	"github.com/spf13/cobra"

	kapi "k8s.io/kubernetes/pkg/api"
	kapierrors "k8s.io/kubernetes/pkg/api/errors"
	kcmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util"

	authorizationapi "github.com/openshift/origin/pkg/authorization/api"
	"github.com/openshift/origin/pkg/cmd/util/clientcmd"
	uservalidation "github.com/openshift/origin/pkg/user/api/validation"
)

const (
	AddRoleToGroupRecommendedName      = "add-role-to-group"
	AddRoleToUserRecommendedName       = "add-role-to-user"
	RemoveRoleFromGroupRecommendedName = "remove-role-from-group"
	RemoveRoleFromUserRecommendedName  = "remove-role-from-user"

	AddClusterRoleToGroupRecommendedName      = "add-cluster-role-to-group"
	AddClusterRoleToUserRecommendedName       = "add-cluster-role-to-user"
	RemoveClusterRoleFromGroupRecommendedName = "remove-cluster-role-from-group"
	RemoveClusterRoleFromUserRecommendedName  = "remove-cluster-role-from-user"
)

const (
	addRoleToUserExample = `  # Add the 'view' role to user1 in the current project
  %[1]s view user1

  # Add the 'edit' role to serviceaccount1 in the current project
  %[1]s edit -z serviceaccount1`
)

type RoleModificationOptions struct {
	RoleNamespace       string
	RoleName            string
	RoleBindingAccessor RoleBindingAccessor

	Users    []string
	Groups   []string
	Subjects []kapi.ObjectReference
}

// NewCmdAddRoleToGroup implements the OpenShift cli add-role-to-group command
func NewCmdAddRoleToGroup(name, fullName string, f *clientcmd.Factory, out io.Writer) *cobra.Command {
	options := &RoleModificationOptions{}

	cmd := &cobra.Command{
		Use:   name + " ROLE GROUP [GROUP ...]",
		Short: "Add groups to a role in the current project",
		Long:  `Add groups to a role in the current project`,
		Run: func(cmd *cobra.Command, args []string) {
			if err := options.Complete(f, args, &options.Groups, "group", true); err != nil {
				kcmdutil.CheckErr(kcmdutil.UsageError(cmd, err.Error()))
			}

			if err := options.AddRole(); err != nil {
				kcmdutil.CheckErr(err)
			}
		},
	}

	cmd.Flags().StringVar(&options.RoleNamespace, "role-namespace", "", "namespace where the role is located: empty means a role defined in cluster policy")

	return cmd
}

// NewCmdAddRoleToUser implements the OpenShift cli add-role-to-user command
func NewCmdAddRoleToUser(name, fullName string, f *clientcmd.Factory, out io.Writer) *cobra.Command {
	options := &RoleModificationOptions{}
	saNames := []string{}

	cmd := &cobra.Command{
		Use:     name + " ROLE (USER | -z SERVICEACCOUNT) [USER ...]",
		Short:   "Add users or serviceaccounts to a role in the current project",
		Long:    `Add users or serviceaccounts to a role in the current project`,
		Example: fmt.Sprintf(addRoleToUserExample, fullName),
		Run: func(cmd *cobra.Command, args []string) {
			if err := options.CompleteUserWithSA(f, args, saNames); err != nil {
				kcmdutil.CheckErr(kcmdutil.UsageError(cmd, err.Error()))
			}

			if err := options.AddRole(); err != nil {
				kcmdutil.CheckErr(err)
			}
		},
	}

	cmd.Flags().StringVar(&options.RoleNamespace, "role-namespace", "", "namespace where the role is located: empty means a role defined in cluster policy")
	cmd.Flags().StringSliceVarP(&saNames, "serviceaccount", "z", saNames, "service account in the current namespace to use as a user")

	return cmd
}

// NewCmdRemoveRoleFromGroup implements the OpenShift cli remove-role-from-group command
func NewCmdRemoveRoleFromGroup(name, fullName string, f *clientcmd.Factory, out io.Writer) *cobra.Command {
	options := &RoleModificationOptions{}

	cmd := &cobra.Command{
		Use:   name + " ROLE GROUP [GROUP ...]",
		Short: "Remove group from role in the current project",
		Long:  `Remove group from role in the current project`,
		Run: func(cmd *cobra.Command, args []string) {
			if err := options.Complete(f, args, &options.Groups, "group", true); err != nil {
				kcmdutil.CheckErr(kcmdutil.UsageError(cmd, err.Error()))
			}

			if err := options.RemoveRole(); err != nil {
				kcmdutil.CheckErr(err)
			}
		},
	}

	cmd.Flags().StringVar(&options.RoleNamespace, "role-namespace", "", "namespace where the role is located: empty means a role defined in cluster policy")

	return cmd
}

// NewCmdRemoveRoleFromUser implements the OpenShift cli remove-role-from-user command
func NewCmdRemoveRoleFromUser(name, fullName string, f *clientcmd.Factory, out io.Writer) *cobra.Command {
	options := &RoleModificationOptions{}
	saNames := []string{}

	cmd := &cobra.Command{
		Use:   name + " ROLE USER [USER ...]",
		Short: "Remove user from role in the current project",
		Long:  `Remove user from role in the current project`,
		Run: func(cmd *cobra.Command, args []string) {
			if err := options.CompleteUserWithSA(f, args, saNames); err != nil {
				kcmdutil.CheckErr(kcmdutil.UsageError(cmd, err.Error()))
			}

			if err := options.RemoveRole(); err != nil {
				kcmdutil.CheckErr(err)
			}
		},
	}

	cmd.Flags().StringVar(&options.RoleNamespace, "role-namespace", "", "namespace where the role is located: empty means a role defined in cluster policy")
	cmd.Flags().StringSliceVarP(&saNames, "serviceaccount", "z", saNames, "service account in the current namespace to use as a user")

	return cmd
}

// NewCmdAddClusterRoleToGroup implements the OpenShift cli add-cluster-role-to-group command
func NewCmdAddClusterRoleToGroup(name, fullName string, f *clientcmd.Factory, out io.Writer) *cobra.Command {
	options := &RoleModificationOptions{}

	cmd := &cobra.Command{
		Use:   name + " <role> <group> [group]...",
		Short: "Add groups to a role for all projects in the cluster",
		Long:  `Add groups to a role for all projects in the cluster`,
		Run: func(cmd *cobra.Command, args []string) {
			if err := options.Complete(f, args, &options.Groups, "group", false); err != nil {
				kcmdutil.CheckErr(kcmdutil.UsageError(cmd, err.Error()))
			}

			if err := options.AddRole(); err != nil {
				kcmdutil.CheckErr(err)
			}
		},
	}

	return cmd
}

// NewCmdAddClusterRoleToUser implements the OpenShift cli add-cluster-role-to-user command
func NewCmdAddClusterRoleToUser(name, fullName string, f *clientcmd.Factory, out io.Writer) *cobra.Command {
	options := &RoleModificationOptions{}

	cmd := &cobra.Command{
		Use:   name + " <role> <user> [user]...",
		Short: "Add users to a role for all projects in the cluster",
		Long:  `Add users to a role for all projects in the cluster`,
		Run: func(cmd *cobra.Command, args []string) {
			if err := options.Complete(f, args, &options.Users, "user", false); err != nil {
				kcmdutil.CheckErr(kcmdutil.UsageError(cmd, err.Error()))
			}

			if err := options.AddRole(); err != nil {
				kcmdutil.CheckErr(err)
			}
		},
	}

	return cmd
}

// NewCmdRemoveClusterRoleFromGroup implements the OpenShift cli remove-cluster-role-from-group command
func NewCmdRemoveClusterRoleFromGroup(name, fullName string, f *clientcmd.Factory, out io.Writer) *cobra.Command {
	options := &RoleModificationOptions{}

	cmd := &cobra.Command{
		Use:   name + " <role> <group> [group]...",
		Short: "Remove group from role for all projects in the cluster",
		Long:  `Remove group from role for all projects in the cluster`,
		Run: func(cmd *cobra.Command, args []string) {
			if err := options.Complete(f, args, &options.Groups, "group", false); err != nil {
				kcmdutil.CheckErr(kcmdutil.UsageError(cmd, err.Error()))
			}

			if err := options.RemoveRole(); err != nil {
				kcmdutil.CheckErr(err)
			}
		},
	}

	return cmd
}

// NewCmdRemoveClusterRoleFromUser implements the OpenShift cli remove-cluster-role-from-user command
func NewCmdRemoveClusterRoleFromUser(name, fullName string, f *clientcmd.Factory, out io.Writer) *cobra.Command {
	options := &RoleModificationOptions{}

	cmd := &cobra.Command{
		Use:   name + " <role> <user> [user]...",
		Short: "Remove user from role for all projects in the cluster",
		Long:  `Remove user from role for all projects in the cluster`,
		Run: func(cmd *cobra.Command, args []string) {
			if err := options.Complete(f, args, &options.Users, "user", false); err != nil {
				kcmdutil.CheckErr(kcmdutil.UsageError(cmd, err.Error()))
			}

			if err := options.RemoveRole(); err != nil {
				kcmdutil.CheckErr(err)
			}
		},
	}

	return cmd
}

func (o *RoleModificationOptions) CompleteUserWithSA(f *clientcmd.Factory, args []string, saNames []string) error {
	if len(args) < 1 {
		return errors.New("you must specify a role")
	}

	o.RoleName = args[0]
	if len(args) > 1 {
		o.Users = append(o.Users, args[1:]...)
	}

	if (len(o.Users) == 0) && (len(saNames) == 0) {
		return errors.New("you must specify at least one user or service account")
	}

	osClient, _, err := f.Clients()
	if err != nil {
		return err
	}

	roleBindingNamespace, _, err := f.DefaultNamespace()
	if err != nil {
		return err
	}
	o.RoleBindingAccessor = NewLocalRoleBindingAccessor(roleBindingNamespace, osClient)

	for _, sa := range saNames {
		o.Subjects = append(o.Subjects, kapi.ObjectReference{Namespace: roleBindingNamespace, Name: sa, Kind: "ServiceAccount"})
	}

	return nil
}

func (o *RoleModificationOptions) Complete(f *clientcmd.Factory, args []string, target *[]string, targetName string, isNamespaced bool) error {
	if len(args) < 2 {
		return fmt.Errorf("you must specify at least two arguments: <role> <%s> [%s]...", targetName, targetName)
	}

	o.RoleName = args[0]
	*target = append(*target, args[1:]...)

	osClient, _, err := f.Clients()
	if err != nil {
		return err
	}

	if isNamespaced {
		roleBindingNamespace, _, err := f.DefaultNamespace()
		if err != nil {
			return err
		}
		o.RoleBindingAccessor = NewLocalRoleBindingAccessor(roleBindingNamespace, osClient)

	} else {
		o.RoleBindingAccessor = NewClusterRoleBindingAccessor(osClient)

	}

	return nil
}

func (o *RoleModificationOptions) AddRole() error {
	roleBindings, err := o.RoleBindingAccessor.GetExistingRoleBindingsForRole(o.RoleNamespace, o.RoleName)
	if err != nil {
		return err
	}
	roleBindingNames, err := o.RoleBindingAccessor.GetExistingRoleBindingNames()
	if err != nil {
		return err
	}

	var roleBinding *authorizationapi.RoleBinding
	isUpdate := true
	if len(roleBindings) == 0 {
		roleBinding = &authorizationapi.RoleBinding{}
		isUpdate = false
	} else {
		// only need to add the user or group to a single roleBinding on the role.  Just choose the first one
		roleBinding = roleBindings[0]
	}

	roleBinding.RoleRef.Namespace = o.RoleNamespace
	roleBinding.RoleRef.Name = o.RoleName

	newSubjects := authorizationapi.BuildSubjects(o.Users, o.Groups, uservalidation.ValidateUserName, uservalidation.ValidateGroupName)
	newSubjects = append(newSubjects, o.Subjects...)

subjectCheck:
	for _, newSubject := range newSubjects {
		for _, existingSubject := range roleBinding.Subjects {
			if existingSubject.Kind == newSubject.Kind &&
				existingSubject.Name == newSubject.Name &&
				existingSubject.Namespace == newSubject.Namespace {
				continue subjectCheck
			}
		}

		roleBinding.Subjects = append(roleBinding.Subjects, newSubject)
	}

	if isUpdate {
		err = o.RoleBindingAccessor.UpdateRoleBinding(roleBinding)
	} else {
		roleBinding.Name = getUniqueName(o.RoleName, roleBindingNames)
		err = o.RoleBindingAccessor.CreateRoleBinding(roleBinding)
		// If the rolebinding was created in the meantime, rerun
		if kapierrors.IsAlreadyExists(err) {
			return o.AddRole()
		}
	}
	if err != nil {
		return err
	}

	return nil
}

func (o *RoleModificationOptions) RemoveRole() error {
	roleBindings, err := o.RoleBindingAccessor.GetExistingRoleBindingsForRole(o.RoleNamespace, o.RoleName)
	if err != nil {
		return err
	}
	if len(roleBindings) == 0 {
		return fmt.Errorf("unable to locate RoleBinding for %v/%v", o.RoleNamespace, o.RoleName)
	}

	subjectsToRemove := authorizationapi.BuildSubjects(o.Users, o.Groups, uservalidation.ValidateUserName, uservalidation.ValidateGroupName)
	subjectsToRemove = append(subjectsToRemove, o.Subjects...)

	for _, roleBinding := range roleBindings {
		roleBinding.Subjects = removeSubjects(roleBinding.Subjects, subjectsToRemove)

		err = o.RoleBindingAccessor.UpdateRoleBinding(roleBinding)
		if err != nil {
			return err
		}
	}

	return nil
}

func removeSubjects(haystack, needles []kapi.ObjectReference) []kapi.ObjectReference {
	newSubjects := []kapi.ObjectReference{}

existingLoop:
	for _, existingSubject := range haystack {
		for _, toRemove := range needles {
			if existingSubject.Kind == toRemove.Kind &&
				existingSubject.Name == toRemove.Name &&
				existingSubject.Namespace == toRemove.Namespace {
				continue existingLoop

			}
		}

		newSubjects = append(newSubjects, existingSubject)
	}

	return newSubjects
}


text:
require 'spec_helper'

# This spec was generated by rspec-rails when you ran the scaffold generator.
# It demonstrates how one might use RSpec to specify the controller code that
# was generated by the Rails when you ran the scaffold generator.

describe Forum::CategoriesController do

  def mock_category(stubs={})
    @mock_category ||= mock_model(Forum::Category, stubs).as_null_object
  end

  describe "GET index" do
    it "assigns all forum_categories as @forum_categories" do
      Forum::Category.stub(:all) { [mock_category] }
      get :index
      assigns(:forum_categories).should eq([mock_category])
    end
  end

  describe "GET show" do
    it "assigns the requested category as @category" do
      Forum::Category.stub(:find).with("37") { mock_category }
      get :show, :id => "37"
      assigns(:category).should be(mock_category)
    end
  end

  describe "GET new" do
    it "assigns a new category as @category" do
      Forum::Category.stub(:new) { mock_category }
      get :new
      assigns(:category).should be(mock_category)
    end
  end

  describe "GET edit" do
    it "assigns the requested category as @category" do
      Forum::Category.stub(:find).with("37") { mock_category }
      get :edit, :id => "37"
      assigns(:category).should be(mock_category)
    end
  end

  describe "POST create" do
    describe "with valid params" do
      it "assigns a newly created category as @category" do
        Forum::Category.stub(:new).with({'these' => 'params'}) { mock_category(:save => true) }
        post :create, :category => {'these' => 'params'}
        assigns(:category).should be(mock_category)
      end

      it "redirects to the created category" do
        Forum::Category.stub(:new) { mock_category(:save => true) }
        post :create, :category => {}
        response.should redirect_to(forum_category_url(mock_category))
      end
    end

    describe "with invalid params" do
      it "assigns a newly created but unsaved category as @category" do
        Forum::Category.stub(:new).with({'these' => 'params'}) { mock_category(:save => false) }
        post :create, :category => {'these' => 'params'}
        assigns(:category).should be(mock_category)
      end

      it "re-renders the 'new' template" do
        Forum::Category.stub(:new) { mock_category(:save => false) }
        post :create, :category => {}
        response.should render_template("new")
      end
    end
  end

  describe "PUT update" do
    describe "with valid params" do
      it "updates the requested category" do
        Forum::Category.stub(:find).with("37") { mock_category }
        mock_forum_category.should_receive(:update_attributes).with({'these' => 'params'})
        put :update, :id => "37", :category => {'these' => 'params'}
      end

      it "assigns the requested category as @category" do
        Forum::Category.stub(:find) { mock_category(:update_attributes => true) }
        put :update, :id => "1"
        assigns(:category).should be(mock_category)
      end

      it "redirects to the category" do
        Forum::Category.stub(:find) { mock_category(:update_attributes => true) }
        put :update, :id => "1"
        response.should redirect_to(forum_category_url(mock_category))
      end
    end

    describe "with invalid params" do
      it "assigns the category as @category" do
        Forum::Category.stub(:find) { mock_category(:update_attributes => false) }
        put :update, :id => "1"
        assigns(:category).should be(mock_category)
      end

      it "re-renders the 'edit' template" do
        Forum::Category.stub(:find) { mock_category(:update_attributes => false) }
        put :update, :id => "1"
        response.should render_template("edit")
      end
    end
  end

  describe "DELETE destroy" do
    it "destroys the requested category" do
      Forum::Category.stub(:find).with("37") { mock_category }
      mock_forum_category.should_receive(:destroy)
      delete :destroy, :id => "37"
    end

    it "redirects to the forum_categories list" do
      Forum::Category.stub(:find) { mock_category }
      delete :destroy, :id => "1"
      response.should redirect_to(forum_categories_url)
    end
  end

end


text:
package healthsrv

import (
	"encoding/json"
	"fmt"
	"log"
	"net/http"

	"github.com/deis/minio/src/storage"
	minio "github.com/minio/minio-go"
)

type healthZResp struct {
	Buckets []minio.BucketInfo `json:"buckets"`
}

func healthZHandler(bucketLister storage.BucketLister) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		buckets, err := bucketLister.ListBuckets()
		if err != nil {
			str := fmt.Sprintf("Probe error: listing buckets (%s)", err)
			log.Println(str)
			http.Error(w, str, http.StatusInternalServerError)
			return
		}
		if err := json.NewEncoder(w).Encode(healthZResp{Buckets: buckets}); err != nil {
			str := fmt.Sprintf("Probe error: encoding buckets json (%s)", err)
			log.Println(str)
			http.Error(w, str, http.StatusInternalServerError)
			return
		}
	})
}


text:
package com.thinkbiganalytics.util;

import com.google.common.base.Preconditions;
import com.thinkbiganalytics.nifi.thrift.api.RowVisitor;

import org.apache.avro.Schema;
import org.apache.avro.SchemaBuilder;
import org.apache.avro.SchemaBuilder.FieldAssembler;
import org.apache.avro.file.DataFileWriter;
import org.apache.avro.generic.GenericData;
import org.apache.avro.generic.GenericDatumWriter;
import org.apache.avro.generic.GenericRecord;
import org.apache.avro.io.DatumWriter;
import org.apache.commons.lang3.CharUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.text.translate.CharSequenceTranslator;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormatter;
import org.joda.time.format.ISODateTimeFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.nio.ByteBuffer;
import java.sql.Date;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Time;
import java.sql.Timestamp;
import java.sql.Types;

import javax.annotation.Nonnull;

import static java.sql.Types.ARRAY;
import static java.sql.Types.BIGINT;
import static java.sql.Types.BINARY;
import static java.sql.Types.BIT;
import static java.sql.Types.BLOB;
import static java.sql.Types.BOOLEAN;
import static java.sql.Types.CHAR;
import static java.sql.Types.CLOB;
import static java.sql.Types.DATE;
import static java.sql.Types.DECIMAL;
import static java.sql.Types.DOUBLE;
import static java.sql.Types.FLOAT;
import static java.sql.Types.INTEGER;
import static java.sql.Types.LONGNVARCHAR;
import static java.sql.Types.LONGVARBINARY;
import static java.sql.Types.LONGVARCHAR;
import static java.sql.Types.NCHAR;
import static java.sql.Types.NUMERIC;
import static java.sql.Types.NVARCHAR;
import static java.sql.Types.REAL;
import static java.sql.Types.ROWID;
import static java.sql.Types.SMALLINT;
import static java.sql.Types.TIME;
import static java.sql.Types.TIMESTAMP;
import static java.sql.Types.TINYINT;
import static java.sql.Types.VARBINARY;
import static java.sql.Types.VARCHAR;

/**
 * JDBC / SQL common functions.
 */
public class JdbcCommon {

    private static final Logger log = LoggerFactory.getLogger(JdbcCommon.class);

    /**
     * Converts the specified SQL result set to a delimited text file written to the specified output stream.
     *
     * @param rs        the SQL result set
     * @param outStream the output stream for the delimited text file
     * @param visitor   records position of the result set
     * @param delimiter the column delimiter for the delimited text file
     * @return the number of rows written
     * @throws SQLException if a SQL error occurs while reading the result set
     * @throws IOException  if an I/O error occurs while writing to the output stream
     */
    public static long convertToDelimitedStream(final ResultSet rs, final OutputStream outStream, final RowVisitor visitor, String delimiter) throws SQLException, IOException {
        // avoid overflowing log with redundant messages
        int dateConversionWarning = 0;

        if (rs == null || rs.getMetaData() == null) {
            log.warn("Received empty resultset or no metadata.");
            return 0;
        }
        OutputStreamWriter writer = new OutputStreamWriter(outStream);
        final ResultSetMetaData meta = rs.getMetaData();
        final DelimiterEscaper escaper = new DelimiterEscaper(delimiter);

        // Write header
        final int nrOfColumns = meta.getColumnCount();
        StringBuffer sb = new StringBuffer();
        for (int i = 1; i <= nrOfColumns; i++) {
            String columnName = meta.getColumnName(i);
            sb.append(escaper.translate(columnName));
            if (i != nrOfColumns) {
                sb.append(delimiter);
            } else {
                sb.append("\n");
            }
        }
        writer.append(sb.toString());
        long nrOfRows = 0;
        while (rs.next()) {
            if (visitor != null) {
                visitor.visitRow(rs);
            }
            sb = new StringBuffer();
            nrOfRows++;
            for (int i = 1; i <= nrOfColumns; i++) {
                String val = null;

                int colType = meta.getColumnType(i);
                if (colType == Types.DATE || colType == Types.TIMESTAMP) {
                    Timestamp sqlDate = null;
                    try {
                        // Extract timestamp
                        sqlDate = extractSqlDate(rs, i);
                    } catch (Exception e) {
                        // Still failed, maybe exotic date type
                        if (dateConversionWarning++ < 10) {
                            log.warn("{} is not convertible to timestamp or date", rs.getMetaData().getColumnName(i));
                        }
                    }

                    if (visitor != null) {
                        visitor.visitColumn(rs.getMetaData().getColumnName(i), colType, sqlDate);
                    }
                    if (sqlDate != null) {
                        DateTimeFormatter formatter = ISODateTimeFormat.dateTime().withZoneUTC();
                        val = formatter.print(new DateTime(sqlDate.getTime()));
                    }
                } else if (colType == Types.TIME) {
                    Time time = rs.getTime(i);
                    if (visitor != null) {
                        visitor.visitColumn(rs.getMetaData().getColumnName(i), colType, time);
                    }
                    if (time != null) {
                        DateTimeFormatter formatter = ISODateTimeFormat.time().withZoneUTC();
                        val = formatter.print(new DateTime(time.getTime()));
                    }
                } else if (colType == Types.BLOB) {
                    byte[] bytes = rs.getBytes(i);

                    if (bytes != null)
                        val = rs.getBytes(i).toString();

                    if (visitor != null) {
                        visitor.visitColumn(rs.getMetaData().getColumnName(i), colType, val);
                    }
                } else {
                    val = rs.getString(i);
                    if (visitor != null) {
                        visitor.visitColumn(rs.getMetaData().getColumnName(i), colType, val);
                    }
                }
                sb.append((val == null ? "" : escaper.translate(val)));
                if (i != nrOfColumns) {
                    sb.append(delimiter);
                } else {
                    sb.append("\n");
                }
            }
            writer.append(sb.toString());
        }
        writer.flush();
        return nrOfRows;
    }

    /**
     * Extracts a resultset col to a SQL timestamp
     */
    private static Timestamp extractSqlDate(ResultSet rs, int col) throws SQLException {
        Timestamp sqlDate = null;
        try {
            // Extract timestamp
            sqlDate = rs.getTimestamp(col);
        } catch (SQLException e) {
            // Attempt to extract date
            Date sqlDateDate = rs.getDate(col);
            if (sqlDateDate != null) {
                Long timeInMillis = sqlDateDate.getTime();
                sqlDate = new Timestamp(timeInMillis);
            }
        }
        return sqlDate;
    }

    public static long convertToAvroStream(final ResultSet rs, final OutputStream outStream, final RowVisitor visitor, final Schema schema) throws SQLException, IOException {
        int dateConversionWarning = 0;
        final GenericRecord rec = new GenericData.Record(schema);

        final DatumWriter<GenericRecord> datumWriter = new GenericDatumWriter<>(schema);
        try (final DataFileWriter<GenericRecord> dataFileWriter = new DataFileWriter<>(datumWriter)) {
            dataFileWriter.create(schema, outStream);

            final ResultSetMetaData meta = rs.getMetaData();
            final int nrOfColumns = meta.getColumnCount();
            long nrOfRows = 0;
            while (rs.next()) {
                if (visitor != null) {
                    visitor.visitRow(rs);
                }
                for (int i = 1; i <= nrOfColumns; i++) {
                    final int javaSqlType = meta.getColumnType(i);
                    final Object value = rs.getObject(i);

                    if (value == null) {
                        rec.put(i - 1, null);

                    } else if (javaSqlType == BINARY || javaSqlType == VARBINARY || javaSqlType == LONGVARBINARY || javaSqlType == ARRAY || javaSqlType == BLOB || javaSqlType == CLOB) {
                        // bytes requires little bit different handling
                        byte[] bytes = rs.getBytes(i);
                        ByteBuffer bb = ByteBuffer.wrap(bytes);
                        rec.put(i - 1, bb);

                    } else if (value instanceof Byte) {
                        // tinyint(1) type is returned by JDBC driver as java.sql.Types.TINYINT
                        // But value is returned by JDBC as java.lang.Byte
                        // (at least H2 JDBC works this way)
                        // direct put to avro record results:
                        // org.apache.avro.AvroRuntimeException: Unknown datum type java.lang.Byte
                        rec.put(i - 1, ((Byte) value).intValue());

                    } else if (value instanceof BigDecimal || value instanceof BigInteger) {
                        // Avro can't handle BigDecimal and BigInteger as numbers - it will throw an AvroRuntimeException such as: "Unknown datum type: java.math.BigDecimal: 38"
                        rec.put(i - 1, value.toString());

                    } else if (value instanceof Number || value instanceof Boolean) {
                        rec.put(i - 1, value);

                    } else if (value instanceof Date) {
                        final DateTimeFormatter formatter = ISODateTimeFormat.dateTime().withZoneUTC();
                        rec.put(i - 1, formatter.print(new DateTime(((Date) value).getTime())));

                    } else if (value instanceof Time) {
                        final DateTimeFormatter formatter = ISODateTimeFormat.time().withZoneUTC();
                        rec.put(i - 1, formatter.print(new DateTime(((Time) value).getTime())));

                    } else if (value instanceof Timestamp) {
                        final DateTimeFormatter formatter = ISODateTimeFormat.dateTime().withZoneUTC();
                        rec.put(i - 1, formatter.print(new DateTime(((Timestamp) value).getTime())));

                    } else {
                        // The different types that we support are numbers (int, long, double, float),
                        // as well as boolean values and Strings. Since Avro doesn't provide
                        // timestamp types, we want to convert those to Strings. So we will cast anything other
                        // than numbers or booleans to strings by using the toString() method.
                        rec.put(i - 1, value.toString());
                    }

                    //notify the visitor
                    if (javaSqlType == Types.DATE || javaSqlType == Types.TIMESTAMP) {
                        Timestamp sqlDate = null;
                        try {
                            // Extract timestamp
                            sqlDate = extractSqlDate(rs, i);

                        } catch (Exception e) {
                            if (dateConversionWarning++ < 10) {
                                log.warn("{} is not convertible to timestamp or date", rs.getMetaData().getColumnName(i));
                            }
                        }

                        if (visitor != null) {
                            visitor.visitColumn(rs.getMetaData().getColumnName(i), javaSqlType, sqlDate);
                        }
                    } else if (javaSqlType == Types.TIME) {
                        Time time = rs.getTime(i);
                        if (visitor != null) {
                            visitor.visitColumn(rs.getMetaData().getColumnName(i), javaSqlType, time);
                        }
                    } else {
                        if (visitor != null) {
                            visitor.visitColumn(rs.getMetaData().getColumnName(i), javaSqlType, (value != null) ? value.toString() : null);
                        }
                    }
                }
                dataFileWriter.append(rec);
                nrOfRows += 1;
            }

            return nrOfRows;
        }
    }

    public static Schema createSchema(final ResultSet rs) throws SQLException {
        final ResultSetMetaData meta = rs.getMetaData();
        final int nrOfColumns = meta.getColumnCount();
        String tableName = "";
        try {
            tableName = meta.getTableName(1);
        } catch (SQLException e) {
            // ignored
        }
        if (StringUtils.isBlank(tableName)) {
            tableName = "NiFi_ExecuteSQL_Record";
        }

        final FieldAssembler<Schema> builder = SchemaBuilder.record(tableName).namespace("any.data").fields();

        // Some missing Avro types - Decimal, Date types. May need some additional work.
        for (int i = 1; i <= nrOfColumns; i++) {
            switch (meta.getColumnType(i)) {
                case CHAR:
                case LONGNVARCHAR:
                case LONGVARCHAR:
                case NCHAR:
                case NVARCHAR:
                case VARCHAR:
                    builder.name(meta.getColumnName(i)).type().unionOf().nullBuilder().endNull().and().stringType().endUnion().noDefault();
                    break;
                case BIT:
                case BOOLEAN:
                    builder.name(meta.getColumnName(i)).type().unionOf().nullBuilder().endNull().and().booleanType().endUnion().noDefault();
                    break;

                case INTEGER:
                    if (meta.isSigned(i)) {
                        builder.name(meta.getColumnName(i)).type().unionOf().nullBuilder().endNull().and().intType().endUnion().noDefault();
                    } else {
                        builder.name(meta.getColumnName(i)).type().unionOf().nullBuilder().endNull().and().longType().endUnion().noDefault();
                    }
                    break;

                case SMALLINT:
                case TINYINT:
                    builder.name(meta.getColumnName(i)).type().unionOf().nullBuilder().endNull().and().intType().endUnion().noDefault();
                    break;

                case BIGINT:
                    builder.name(meta.getColumnName(i)).type().unionOf().nullBuilder().endNull().and().longType().endUnion().noDefault();
                    break;

                // java.sql.RowId is interface, is seems to be database
                // implementation specific, let's convert to String
                case ROWID:
                    builder.name(meta.getColumnName(i)).type().unionOf().nullBuilder().endNull().and().stringType().endUnion().noDefault();
                    break;

                case FLOAT:
                case REAL:
                    builder.name(meta.getColumnName(i)).type().unionOf().nullBuilder().endNull().and().floatType().endUnion().noDefault();
                    break;

                case DOUBLE:
                    builder.name(meta.getColumnName(i)).type().unionOf().nullBuilder().endNull().and().doubleType().endUnion().noDefault();
                    break;

                // Did not find direct suitable type, need to be clarified!!!!
                case DECIMAL:
                case NUMERIC:
                    builder.name(meta.getColumnName(i)).type().unionOf().nullBuilder().endNull().and().stringType().endUnion().noDefault();
                    break;

                // Did not find direct suitable type, need to be clarified!!!!
                case DATE:
                case TIME:
                case TIMESTAMP:
                    builder.name(meta.getColumnName(i)).type().unionOf().nullBuilder().endNull().and().stringType().endUnion().noDefault();
                    break;

                case BINARY:
                case VARBINARY:
                case LONGVARBINARY:
                case ARRAY:
                case BLOB:
                case CLOB:
                    builder.name(meta.getColumnName(i)).type().unionOf().nullBuilder().endNull().and().bytesType().endUnion().noDefault();
                    break;

                default:
                    throw new IllegalArgumentException("createSchema: Unknown SQL type " + meta.getColumnType(i) + " cannot be converted to Avro type");
            }
        }

        return builder.endRecord();
    }

    /**
     * Escapes values in delimited text files.
     */
    static class DelimiterEscaper extends CharSequenceTranslator {

        /**
         * Character for quoting values
         */
        private static final char QUOTE = '"';

        /**
         * String for quoting values
         */
        private static final String QUOTE_STR = String.valueOf(QUOTE);

        /**
         * Character for escaping values
         */
        private static final char BACKSLASH = '\\';

        /**
         * String for escaping values
         */
        private static final String BACKSLASH_STR = String.valueOf(BACKSLASH);

        /**
         * Strings that, if found, require a value to be escaped
         */
        private final String[] searchStrings;

        /**
         * Replacements for the search strings found
         */
        private final String[] replacementStrings;

        /**
         * Constructs a {@code DelimiterEscaper} with the specified delimiter.
         *
         * @param delimiter the delimiter
         */
        DelimiterEscaper(@Nonnull final String delimiter) {
            searchStrings = new String[]{delimiter, QUOTE_STR, Character.toString('\n'), Character.toString('\r') };
            replacementStrings = new String[]{delimiter, BACKSLASH_STR+QUOTE_STR, "\\\\n", "\\\\r"};
        }

        @Override
        public int translate(@Nonnull final CharSequence input, final int index, @Nonnull final Writer out) throws IOException {
            Preconditions.checkState(index == 0, "Unsupported translation index %d", index);
            String inputString = input.toString();
            if (StringUtils.containsAny(inputString, searchStrings)) {
                out.write(QUOTE);
                out.write(StringUtils.replaceEach(inputString, searchStrings, replacementStrings));
                out.write(QUOTE);
            } else {
                out.write(input.toString());
            }

            return Character.codePointCount(input, 0, input.length());
        }
    }

    /**
     * Get schema in the format for setting up the feed table
     * @param schema Avro Schema
     * @return formatted schema for setting up feed table
     */
    public static String getAvroSchemaForFeedSetup (Schema schema) {
        if (schema == null) {
            return "";
        }

        final String PIPE = "|";
        final String description = "";
        final String primaryKey = "0";
        final String createdTracker = "0";
        final String updatedTracker = "0";
        final String newLine = "\n";

        StringBuffer retVal = new StringBuffer();

        int totalFields = schema.getFields().size();
        int counter = 1;

        for (Schema.Field field: schema.getFields()) {
            String name = field.name().toLowerCase();
            String dataType = field.schema().getType().name().toLowerCase();

            if (dataType.equals("union")) {
                    for (Schema fieldSchemaType: field.schema().getTypes()) {
                        if (!fieldSchemaType.getName().toLowerCase().equals("null")) {
                            dataType = getHiveTypeForAvroType(fieldSchemaType.getName().toLowerCase());
                            break;
                        }
                    }

                    if (dataType.equals("union")) {
                        dataType = "void";
                    }
                }
            else {
                dataType = getHiveTypeForAvroType(dataType);
            }

            retVal.append(name)
                .append(PIPE)
                .append(dataType)
                .append(PIPE)
                .append(description)
                .append(PIPE)
                .append(primaryKey)
                .append(PIPE)
                .append(createdTracker)
                .append(PIPE)
                .append(updatedTracker);

            if (counter++ < totalFields) {
                retVal.append(newLine);
            }
        }

        return retVal.toString();
    }

    /*
     * Mapping of Avro's data types to Hive's data types
     */
    private static String getHiveTypeForAvroType(String avroType) {

        String hiveType;

        switch (avroType) {
            case "null":
                hiveType = "void";
                break;

            case "boolean":
                hiveType = "boolean";
                break;

            case "int":
                hiveType = "int";
                break;

            case "long":
                hiveType = "bigint";
                break;

            case "float":
                hiveType = "float";
                break;

            case "double":
                hiveType = "double";
                break;

            case "bytes":
                hiveType = "binary";
                break;

            case "string":
                hiveType = "string";
                break;

            case "record":
                hiveType = "struct";
                break;

            case "map":
                hiveType = "map";
                break;

            case "list":
                hiveType = "array";
                break;

            case "enum":
                hiveType = "string";
                break;

            case "fixed":
                hiveType = "binary";
                break;

            default:
                hiveType = "string";
                break;
        }

        return hiveType;
    }

}