text:
<?php

/**
 * O3 Engine image
 *
 * Functions for handling image/picture files
 *
 * @package o3
 * @link    todo: add url
 * @author  Zotlan Fischer <zoli_fischer@yahoo.com>
 * @license http://opensource.org/licenses/gpl-license.php GNU Public License
 */

define('O3_IMAGE_IGNORE_ASPECT',1);
define('O3_IMAGE_FLATTEN',2);
define('O3_IMAGE_CLIP',4);
define('O3_IMAGE_SHRINK_LARGER',8);
define('O3_IMAGE_ENLARGE_SMALLER',16);
define('O3_IMAGE_FILL_AREA',32);
define('O3_IMAGE_OPTIMIZE',64);
define('O3_IMAGE_CROP_CENTER',128);

//standard dpi for web based picture
define('O3_IMAGE_WEB_DPI',72);

/*
* Check if image magic is installed on the system
*/
function is_imagic() {
	exec("\"".O3_IMAGE_MAGIC."\" -version", $out, $rcode);
	return $rcode === 0;
}

/*
* Resize an image
*
* @param strin $source
* @param string $destination If empty string cache file created
* @param integer $width
* @param integer $height
* @param integer $quality 1 - 100
* @param integer $flags - O3_IMAGE_IGNORE_ASPECT, O3_IMAGE_FLATTEN, O3_IMAGE_CLIP, O3_IMAGE_MATTE, O3_IMAGE_SHRINK_LARGER, O3_IMAGE_ENLARGE_SMALLER, O3_IMAGE_FILL_AREA, O3_IMAGE_OPTIMIZE, O3_IMAGE_CROP_CENTER
* @param integer $dpi = 72
* @param string $background Hex code for background color
*/
function o3_image_resize( $source, $destination = '', $width = 1024, $height = 768, $flags = null, $quality = 90, $dpi = O3_IMAGE_WEB_DPI, $background = '' ) {
	//set default
	$flags = $flags === null ? 0 : $flags;

	//get caller script path, we need for relaive paths
	$relative_path = o3_get_caller_path();

	//check for source path
	if ( !realpath(dirname($source)) ) {
		if ( $relative_path != '' )
			$source = $relative_path.'/'.$source;
	}

	if ( file_exists($source) && is_readable($source) ) {
		if ( $destination == '' ) {
			$destination = o3_cache_file( 'image-'.$width.'x'.$height.'x'.$dpi.'x'.$quality.'-'.strtolower($flags.$dpi.$background.filesize($source).filemtime($source).'-'.basename($source)) );
		} else {
			//check for destination path
			if ( !realpath(dirname($destination)) ) {
				if ( $relative_path != '' )
					$destination = $relative_path.'/'.$destination;
			}
		}

		if ( !file_exists($destination) ) {
			if ( is_imagic() ) {

				$size_flag = '';
				if ( $size_flag == '' )
					$size_flag = ( $flags & O3_IMAGE_SHRINK_LARGER ? '>' : $size_flag );
				if ( $size_flag == '' )
					$size_flag = ( $flags & O3_IMAGE_ENLARGE_SMALLER ? '<' : $size_flag );
				if ( $size_flag == '' )
					$size_flag = ( $flags & O3_IMAGE_IGNORE_ASPECT ? '!' : $size_flag );
				if ( $size_flag == '' )
					$size_flag = ( $flags & O3_IMAGE_FILL_AREA ? '^' : $size_flag );
				if ( $flags & O3_IMAGE_CROP_CENTER )
					$size_flag = '^';

				$command = "\"".O3_IMAGE_MAGIC."\" \"".addslashes($source)."\" -profile \"USWebCoatedSWOP.icc\" ".( $background !== '' ? '-background "'.$background.'"' : '')." ".( $flags & O3_IMAGE_FLATTEN ? '-flatten' : '' )." ".( $flags & O3_IMAGE_CLIP ? '-clip' : '')." -quality ".intval( ( $flags & O3_IMAGE_OPTIMIZE ) ? 100 : $quality )."% -density ".$dpi." ".( $width > 0 && $height > 0 ? " -resize \"".$width."x".$height.$size_flag."\"" : "" )." ".( ( $flags & O3_IMAGE_CROP_CENTER ) && $width > 0 && $height > 0 ?  " -gravity center -crop \"".$width."x".$height."+0+0\" " : "" )." -profile \"sRGB.icc\" \"".addslashes($destination)."\"";
				exec( $command, $out, $rcode );
				if ( file_exists($destination) ) {

					//optimize image if needed
					if ( $flags & O3_IMAGE_OPTIMIZE )
						o3_image_optimize( $destination, null, $quality );

					return $destination;
				}
			} else {
				//todo
			}
		} else {
			return $destination;
		}
	}
	return false;
}

/*
* Resize an image and return chache url
*
* @param strin $source
* @param integer $width
* @param integer $height
* @param integer $quality 1 - 100
* @param integer $flags - O3_IMAGE_IGNORE_ASPECT, O3_IMAGE_FLATTEN, O3_IMAGE_CLIP, O3_IMAGE_MATTE, O3_IMAGE_SHRINK_LARGER, O3_IMAGE_ENLARGE_SMALLER, O3_IMAGE_FILL_AREA, O3_IMAGE_OPTIMIZE, O3_IMAGE_CROP_CENTER
* @param integer $dpi = 72
* @param string $background Hex code for background color
*/
function o3_image_resize_cache_url( $source, $width = 1024, $height = 768, $flags = null, $quality = 90, $dpi = O3_IMAGE_WEB_DPI, $background = '' ) {
	//get caller script path, we need for relaive paths
	$relative_path = o3_get_caller_path();

	//check for source path
	if ( !realpath(dirname($source)) ) {
		if ( $relative_path != '' )
			$source = $relative_path.'/'.$source;
	}

	if ( file_exists($source) && is_readable($source) ) {
		$destination = o3_cache_file( 'image-'.$width.'x'.$height.'x'.$dpi.'x'.$quality.'-'.strtolower($flags.$dpi.$background.filesize($source).filemtime($source).'-'.basename($source)) );
		if ( !file_exists($destination) ) {
			$destination = o3_image_resize( $source, $destination, $width, $height, $flags, $quality, $dpi, $background );
			if ( file_exists($destination) ) {
				return O3_CACHE_URL.'/'.basename($destination);
			}
		} else {
			return O3_CACHE_URL.'/'.basename($destination);
		}
	}

	return false;
}

/*
* Check if image magic is installed on the system
*/
function is_pngcrush() {
	exec("\"".O3_IMAGE_PNGCRUSH."\" -version", $out, $rcode);
	return $rcode === 0;
}

/*
* Check if image magic is installed on the system
*/
function is_jpegoptim() {
	exec("\"".O3_IMAGE_JPEGOPTIM."\" -V", $out, $rcode);
	return $rcode === 0;
}

/*
* Optimize image for web
* Optimized images needed for high speed score in google speed insight
*
* @param string $source Path to image to optimize
* @param string $destination Optimized image path. If omited the soruce will be the target.
* @param number $quality 0 - 100, quality of lossy image, 0 - keep original
* @return boolean true if the image was optimized
*/
function o3_image_optimize( $src, $target = null, $quality = 90 ) {
	$target = $target === null ? $src : $target;

	//get caller script path, we need for relaive paths
	$relative_path = o3_get_caller_path();

	//check for source path
	if ( !realpath(dirname($src)) ) {
		if ( $relative_path != '' )
			$src = $relative_path.'/'.$src;
	}

	//check for source path
	if ( !realpath(dirname($target)) ) {
		if ( $relative_path != '' )
			$target = $relative_path.'/'.$target;
	}

	$extension = strtolower(o3_extension($src));
	switch ( $extension ) {
		case 'png':
			if ( is_pngcrush() ) {
				$filename = basename($src);
				//create temp file
				exec('"'.O3_IMAGE_PNGCRUSH.'" -rem alla -nofilecheck -reduce -m 7 "'.$src.'" "'.O3_TEMP_DIR.'/'.$filename.'"');
				if ( file_exists(O3_TEMP_DIR.'/'.$filename) && filesize(O3_TEMP_DIR.'/'.$filename) > 0 ) {
					//remove target if exists
					o3_unlink($target);
					//copy temp file to target
					copy( O3_TEMP_DIR.'/'.$filename, $target );
					//remove temp file
					o3_unlink(O3_TEMP_DIR.'/'.$filename);
					return true;
				}
			}
			break;
		case 'jpg':
		case 'jpeg':
			if ( is_jpegoptim() ) {
				$filename = basename($src);
				//create temp file
				exec('"'.O3_IMAGE_JPEGOPTIM.'" --strip-all '.( $quality > 0 ? '--m='.intval($quality) : '' ).' -f -o -d "'.O3_TEMP_DIR.'" "'.$src.'"');
				if ( file_exists(O3_TEMP_DIR.'/'.$filename) && filesize(O3_TEMP_DIR.'/'.$filename) > 0 ) {
					//remove target if exists
					o3_unlink($target);
					//copy temp file to target
					copy( O3_TEMP_DIR.'/'.$filename, $target );
					//remove temp file
					o3_unlink(O3_TEMP_DIR.'/'.$filename);
					return true;
				}
			}
			break;
	}
	return false;
}

?>

redpajama_set_name: RedPajamaGithub


text:
package com.ugg.gdxjam.view;

import com.badlogic.ashley.core.Entity;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.g2d.Batch;
import com.badlogic.gdx.graphics.g2d.ParticleEffect;
import com.badlogic.gdx.graphics.g2d.ParticleEffectPool;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.utils.Pools;
import com.ugg.gdxjam.model.enums.ParticleType;

/**
 * Created by Jose Cuellar on 05/01/2016.
 */
public class RenderableParticle extends Renderable{

    ParticleEffectPool.PooledEffect pooledEffect;

    public RenderableParticle(){
        super();
    }

    @Override
    public Renderable cloneObject() {
        RenderableParticle newRenderable = Pools.obtain(RenderableParticle.class);
        return newRenderable;
    }

    public void setEffect(ParticleEffectPool.PooledEffect effect){
        this.pooledEffect = effect;
    }

    public void update(float delta){
        pooledEffect.update(delta);
    }

    public boolean isComplete(){
        return this.pooledEffect.isComplete();
    }

    @Override
    public void setPosition(float x, float y){
        pooledEffect.setPosition(x, y);
        super.setPosition(x, y);
    }

    public void tintEmitters(Color color){
        for(int i = 0, n = this.pooledEffect.getEmitters().size; i < n; i++) {
            float[] thisColor = this.pooledEffect.getEmitters().get(i).getTint().getColors();
            thisColor[0] = color.r;
            thisColor[1] = color.g;
            thisColor[2] = color.b;
        }
    }

    @Override
    public void draw(Batch batch, float parentAlpha) {
        super.draw(batch, parentAlpha);

        final OrthographicCamera camera = (OrthographicCamera) this.getStage().getCamera();
        final float x = this.getX();
        final float y = this.getY();
        final float halfWidth = this.getWidth();
        final float halfHeight = this.getHeight();

        if(camera.frustum.boundsInFrustum(x, y, 0, halfWidth, halfHeight, 0)) {
            pooledEffect.draw(batch);
        }
    }

    @Override
    public void reset() {
        if(this.pooledEffect != null)
            pooledEffect.free();
    }
}


text:
<?php

namespace IntegrationTest;

use Zend\Mvc\Application;
use Zend\ServiceManager\ServiceManager;

/**
 * TestHelper
 *
 * @author Chuck "MANCHUCK" Reeves <chuck@manchuck.com>
 * @codeCoverageIgnore
 */
class TestHelper
{
     /**
      * @var ServiceManager
      */
     protected static $serviceManager;

    /**
     * @before
     * @return ServiceManager
     */
    public static function getServiceManager()
    {
        if (null !== static::$serviceManager) {
            return static::$serviceManager;
        }

        $appConfig = include '../config/application.config.php';

        $appConfig['module_listener_options']['config_cache_enabled'] = false;
        $appConfig['module_listener_options']['module_map_cache_enabled'] = false;

        static::$serviceManager = Application::init($appConfig)->getServiceManager();

        return static::$serviceManager;
    }
}


text:
package org.openengsb.core.ekb.api;

/**
 * Helper class for easier working with the informations that define a connector: domainId, connectorId and instanceId.
 */
public class ConnectorInformation {
    private String domainId;
    private String connectorId;
    private String instanceId;

    public ConnectorInformation(String domainId, String connectorId, String instanceId) {
        this.domainId = domainId;
        this.connectorId = connectorId;
        this.instanceId = instanceId;
    }

    public String getDomainId() {
        return domainId;
    }

    public String getConnectorId() {
        return connectorId;
    }

    public String getInstanceId() {
        return instanceId;
    }
}


text:
package main

import (
	"fmt"
	"os"

	"github.com/Symantec/Dominator/lib/fsbench"
)

// Benchmark the read speed of the underlying block device for a given file.
func main() {
	pathname := "/"
	if len(os.Args) == 2 {
		pathname = os.Args[1]
	}
	bytesPerSecond, blocksPerSecond, err := fsbench.GetReadSpeed(pathname)
	if err != nil {
		fmt.Fprintf(os.Stderr, "Error! %s\n", err)
		return
	}
	fmt.Printf("speed=%d MiB/s ", bytesPerSecond>>20)
	if blocksPerSecond > 0 {
		fmt.Printf("%d blocks/s\n", blocksPerSecond)
	} else {
		fmt.Println("I/O accounting not available")
	}
}


text:
package io.debezium.document;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Map;

import org.apache.kafka.common.serialization.Deserializer;
import org.apache.kafka.common.serialization.Serializer;

import io.debezium.annotation.Immutable;

/**
 * A Kafka {@link Deserializer} and {@link Serializer} that operates upon Debezium {@link Document}s.
 *
 * @author Randall Hauch
 */
@Immutable
public class DocumentSerdes implements Serializer<Document>, Deserializer<Document> {

    public static DocumentSerdes INSTANCE = new DocumentSerdes();

    private static final DocumentReader DOCUMENT_READER = DocumentReader.defaultReader();
    private static final DocumentWriter DOCUMENT_WRITER = DocumentWriter.defaultWriter();

    @Override
    public void configure(Map<String, ?> arg0, boolean arg1) {
    }

    @Override
    public byte[] serialize(String topic, Document data) {
        return DOCUMENT_WRITER.writeAsBytes(data);
    }

    @Override
    public Document deserialize(String topic, byte[] data) {
        try {
            return DOCUMENT_READER.read(bytesToString(data));
        }
        catch (IOException e) {
            // Should never see this, but shit if we do ...
            throw new RuntimeException(e);
        }
    }

    @Override
    public void close() {
    }

    private String bytesToString(byte[] bytes) {
        return new String(bytes, StandardCharsets.UTF_8);
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
     android:orientation="vertical"
    android:layout_width="match_parent"
    android:id="@+id/contentView"
    android:layout_height="70dp"
   >

    <LinearLayout

        android:layout_marginLeft="15dp"
        android:layout_width="match_parent"
        android:layout_height="60dp"
        android:layout_gravity="center"
        android:orientation="horizontal">

        <CheckBox
           android:gravity="center"
            android:id="@+id/select_checkbox"
            android:layout_width="35dp"
            android:layout_height="35dp"
            android:layout_gravity="center_vertical"
            android:layout_marginLeft="10dp" />

        <TextView
            android:id="@+id/text"

            android:layout_width="wrap_content"
            android:layout_height="30dp"
            android:layout_gravity="center_vertical"
            android:layout_marginLeft="10dp"
            android:focusable="true"
            android:singleLine="true"
            android:text="条目"
            android:textAlignment="center"
            android:textSize="20sp" />

        <TextView
            android:id="@+id/textView6"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1.2" />

        <TextView
            android:layout_marginTop="15dp"
           android:textColor="#ffffff"
          android:textSize="20dp"
            android:gravity="right"
           android:id="@+id/time"
            android:layout_weight="1.6"
            android:layout_width="wrap_content"
            android:layout_height="match_parent" />
        <TextView
            android:textSize="16sp"
            android:gravity="center"
            android:id="@+id/amorpm"
            android:layout_marginRight="30dp"
            android:drawableBottom="@mipmap/time_icon_morningt"
            android:text=""
            android:layout_gravity="right"
            android:layout_width="55dp"
            android:layout_height="match_parent" />
    </LinearLayout>
    <View
        android:id="@+id/view"
        android:layout_marginTop="5dp"
        android:background="#999999"
        android:layout_width="match_parent"
        android:layout_height="1.2dp"></View>

</LinearLayout>


text:
package com.vmware.vim25;

/**
* @author Steve Jin (http://www.doublecloud.org)
* @version 5.1
*/

@SuppressWarnings("all")
public class VMotionInterfaceIssue extends MigrationFault {
  public boolean atSourceHost;
  public String failedHost;
  public ManagedObjectReference failedHostEntity;

  public boolean isAtSourceHost() {
    return this.atSourceHost;
  }

  public String getFailedHost() {
    return this.failedHost;
  }

  public ManagedObjectReference getFailedHostEntity() {
    return this.failedHostEntity;
  }

  public void setAtSourceHost(boolean atSourceHost) {
    this.atSourceHost=atSourceHost;
  }

  public void setFailedHost(String failedHost) {
    this.failedHost=failedHost;
  }

  public void setFailedHostEntity(ManagedObjectReference failedHostEntity) {
    this.failedHostEntity=failedHostEntity;
  }
}


text:
package com.yahoo.sshd.utils.streams;

import java.io.IOException;
import java.io.OutputStream;

/**
 * A stream that is always empty.
 *
 * @author areese
 *
 */
public class EmptyOutputStream extends OutputStream {

    @Override
    public void write(byte[] b) throws IOException {

    }

    @Override
    public void write(byte[] b, int off, int len) throws IOException {

    }

    @Override
    public void flush() throws IOException {

    }

    @Override
    public void close() throws IOException {

    }

    @Override
    public void write(int b) throws IOException {

    }

}


text:
package com.twitter.elephantbird.pig.util;

/**
 * A helper class to deal with standard Pig tokens and delimiters.
 */
public class PigTokenHelper {
  public static final byte DEFAULT_RECORD_DELIMITER = '\n';
  public static final byte DEFAULT_FIELD_DELIMITER = '\t';
  public static final String DEFAULT_FIELD_DELIMITER_STRING = "\\t";

  // String constants for each delimiter
  public static final String TUPLE_BEGIN = "(";
  public static final String TUPLE_END = ")";
  public static final String BAG_BEGIN = "{";
  public static final String BAG_END = "}";
  public static final String MAP_BEGIN = "[";
  public static final String MAP_END = "]";
  public static final String MAP_KV = "#";

  /**
   * Parse an input delimiter string, as with PigStorage, and return the byte it represents.
   * @param inputDelimiter the string passed in from the pig script.
   * @return the corresponding byte that will serve as the field separator.
   */
  public static byte evaluateDelimiter(String inputDelimiter) {
    if (inputDelimiter.length() == 1) {
      return inputDelimiter.getBytes()[0];
    } else if (inputDelimiter.length() > 1 && inputDelimiter.charAt(0) == '\\') {
      switch (inputDelimiter.charAt(1)) {
      case 't':
        return (byte)'\t';

      case 'x':
      case 'u':
        return Integer.valueOf(inputDelimiter.substring(2)).byteValue();

      default:
        throw new IllegalArgumentException("Unknown delimiter " + inputDelimiter);
      }
    } else {
      throw new IllegalArgumentException("LzoTokenizedStorage delimeter must be a single character");
    }
  }
}


text:
<?php

/*
 * This file is part of PHP CS Fixer.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *     Dariusz Rumiński <dariusz.ruminski@gmail.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace PhpCsFixer\Tests;

use PhpCsFixer\WhitespacesFixerConfig;

/**
 * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
 *
 * @internal
 *
 * @covers \PhpCsFixer\WhitespacesFixerConfig
 */
final class WhitespacesFixerConfigTest extends TestCase
{
    /**
     * @param string      $indent
     * @param string      $lineEnding
     * @param null|string $exceptionRegExp
     *
     * @dataProvider provideTestCases
     */
    public function testCases($indent, $lineEnding, $exceptionRegExp = null)
    {
        if (null !== $exceptionRegExp) {
            $this->expectException(\InvalidArgumentException::class);
            $this->expectExceptionMessageRegExp('%^'.preg_quote($exceptionRegExp, '%').'$%');
        }

        $config = new WhitespacesFixerConfig($indent, $lineEnding);

        static::assertSame($indent, $config->getIndent());
        static::assertSame($lineEnding, $config->getLineEnding());
    }

    public function provideTestCases()
    {
        return [
            ['    ', "\n"],
            ["\t", "\n"],
            ['    ', "\r\n"],
            ["\t", "\r\n"],
            ['    ', 'asd', 'Invalid "lineEnding" param, expected "\n" or "\r\n".'],
            ['    ', [], 'Invalid "lineEnding" param, expected "\n" or "\r\n".'],
            ['std', "\n", 'Invalid "indent" param, expected tab or two or four spaces.'],
            [[], "\n", 'Invalid "indent" param, expected tab or two or four spaces.'],
        ];
    }
}


text:
	{!! Form::label('name', 'Name:') !!}
	{!! Form::text('name', isset($title) ? $title->name : old('name'), ['class' => 'form-control']) !!}

	{!! Form::label('is_landed', 'Is Landed:') !!}

		{!! Form::checkbox('is_landed', '1', isset($title) ? ($title->is_landed == 1 ? ['checked' => 'checked'] : null) : (old('is_landed') == 1 ? ['checked' => 'checked'] : null)) !!}

	{!! Form::label('hierarchy', 'Hierarchy:') !!}
	{!! Form::number('hierarchy', isset($title) ? $title->hierarchy : old('hierarchy'), ['class' => 'form-control']) !!}

	{!! Form::label('fiefs_maximum', 'Fiefs Maximum:') !!}
	{!! Form::number('fiefs_maximum', isset($title) ? $title->fiefs_maximum : old('fiefs_maximum'), ['class' => 'form-control']) !!}

@if(Request::segment(1) != 'sparse')

	{!! Form::submit('Save', ['class' => 'btn btn-primary']) !!}
	Cancel

@endif


text:
<?php

namespace DebugBar\DataCollector;

/**
 * Collects info about PHP
 */
class PhpInfoCollector extends DataCollector
{
    public function collect()
    {
	return array(
	    'version' => PHP_VERSION
	);
    }

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


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
RawType (Oracle - Berkeley DB Java API)
</TITLE>

<META NAME="date" CONTENT="2010-06-25">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../style.css" TITLE="Style">

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

Berkeley DB
 version 5.0.26

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

com.sleepycat.persist.raw

Interface RawType

public interface RawType

The type definition for a simple or complex persistent type, or an array
 of persistent types.

RawType objects are thread-safe.  Multiple threads may safely
 call the methods of a shared RawType object.

Method Summary

 ClassMetadata
getClassMetadata()

          Returns the original model class metadata used to create this class, or
 null if this is not a model class.

 String
getClassName()

          Returns the class name for this type in the format specified by Class.getName().

 RawType
getComponentType()

          Returns the array component type, or null if this is not an array type.

 int
getDimensions()

          Returns the number of array dimensions, or zero if this is not an array
 type.

 EntityMetadata
getEntityMetadata()

          Returns the original model entity metadata used to create this class, or
 null if this is not an entity class.

 List<String>
getEnumConstants()

          Returns an unmodifiable list of the names of the enum instances, or null
 if this is not an enum type.

 Map<String,RawField>
getFields()

          Returns a map of field name to raw field for each non-static
 non-transient field declared in this class, or null if this is not a
 complex type (in other words, this is a simple type or an array type).

 int
getId()

          Returns the internal unique ID for this type.

 RawType
getSuperType()

          Returns the type of the superclass, or null if the superclass is Object
 or this is not a complex type (in other words, this is a simple type or
 an array type).

 int
getVersion()

          Returns the class version for this type.

 boolean
isArray()

          Returns whether this is an array type.

 boolean
isEnum()

          Returns whether this is an enum type.

 boolean
isPrimitive()

          Returns whether this type is a Java primitive: char, byte, short, int,
 long, float or double.

 boolean
isSimple()

          Returns whether this is a
 simple type:
 primitive, primitive wrapper, BigInteger, String or Date.

 String
toString()

          Returns an XML representation of the raw type.

Method Detail

getClassName

String getClassName()

Returns the class name for this type in the format specified by Class.getName().

If this class currently exists (has not been removed or renamed) then
 the class name may be passed to Class.forName(java.lang.String) to get the current
 Class object.  However, if this raw type is not the current
 version of the class, this type information may differ from that of the
 current Class.

getVersion

int getVersion()

Returns the class version for this type.  For simple types, zero is
 always returned.

See Also:
Entity.version(),
Persistent.version()

getId

int getId()

Returns the internal unique ID for this type.

isSimple

boolean isSimple()

Returns whether this is a
 simple type:
 primitive, primitive wrapper, BigInteger, String or Date.

If true is returned, isPrimitive() can be called for more
 information, and a raw value of this type is represented as a simple
 type object (not as a RawObject).

If false is returned, this is a complex type, an array type (see
 isArray()), or an enum type, and a raw value of this type is
 represented as a RawObject.

isPrimitive

boolean isPrimitive()

Returns whether this type is a Java primitive: char, byte, short, int,
 long, float or double.

If true is returned, this is also a simple type.  In other words,
 primitive types are a subset of simple types.

If true is returned, a raw value of this type is represented as a
 non-null instance of the primitive type's wrapper class.  For example,
 an int raw value is represented as an
 Integer.

isEnum

boolean isEnum()

Returns whether this is an enum type.

If true is returned, a value of this type is a RawObject and
 the enum constant String is available via RawObject.getEnum().

If false is returned, then this is a complex type, an array type (see
 isArray()), or a simple type (see isSimple()).

getEnumConstants

List<String> getEnumConstants()

Returns an unmodifiable list of the names of the enum instances, or null
 if this is not an enum type.

isArray

boolean isArray()

Returns whether this is an array type.  Raw value arrays are represented
 as RawObject instances.

If true is returned, the array component type is returned by getComponentType() and the number of array dimensions is returned by
 getDimensions().

If false is returned, then this is a complex type, an enum type (see
 isEnum()), or a simple type (see isSimple()).

getDimensions

int getDimensions()

Returns the number of array dimensions, or zero if this is not an array
 type.

getComponentType

RawType getComponentType()

Returns the array component type, or null if this is not an array type.

getFields

Map<String,RawField> getFields()

Returns a map of field name to raw field for each non-static
 non-transient field declared in this class, or null if this is not a
 complex type (in other words, this is a simple type or an array type).

getSuperType

RawType getSuperType()

Returns the type of the superclass, or null if the superclass is Object
 or this is not a complex type (in other words, this is a simple type or
 an array type).

getClassMetadata

ClassMetadata getClassMetadata()

Returns the original model class metadata used to create this class, or
 null if this is not a model class.

getEntityMetadata

EntityMetadata getEntityMetadata()

Returns the original model entity metadata used to create this class, or
 null if this is not an entity class.

toString

String toString()

Returns an XML representation of the raw type.

Overrides:
toString in class Object

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

Berkeley DB
 version 5.0.26

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

Copyright (c) 1996, 2010 Oracle and/or its affiliates.  All rights reserved.


text: Tool for training your brain/intelligance


text:
import Store from "./Store";
import {Action} from "./actions/Action";
import log from "./Logger";

class Dispatcher {
  private _stores: Set<Store> = new Set<Store>();

  dispatch(action: Action): void {
    log.debug("Dispatching action to stores", action);
    this._stores.forEach(store => store.accept(action));
  }

  register(store: Store): void {
    log.debug("Registered store", store);
    this._stores.add(store);
  }
}

export default new Dispatcher();


text:
'use strict';

const http = require('http');
const BBPromise = require('bluebird');
const express = require('express');
const compression = require('compression');
const bodyParser = require('body-parser');
const fs = BBPromise.promisifyAll(require('fs'));
const sUtil = require('./lib/util');
const apiUtil = require('./lib/api-util');
const packageInfo = require('./package.json');
const yaml = require('js-yaml');
const addShutdown = require('http-shutdown');
const path = require('path');

/**
 * Creates an express app and initialises it
 *
 * @param {Object} options the options to initialise the app with
 * @return {bluebird} the promise resolving to the app object
 */
function initApp(options) {

	// the main application object
	const app = express();

	// get the options and make them available in the app
	app.logger = options.logger;    // the logging device
	app.metrics = options.metrics;  // the metrics
	app.conf = options.config;      // this app's config options
	app.info = packageInfo;         // this app's package info

	// ensure some reasonable defaults
	app.conf.port = app.conf.port || 8888;
	app.conf.interface = app.conf.interface || '0.0.0.0';
	// eslint-disable-next-line max-len
	app.conf.compression_level = app.conf.compression_level === undefined ? 3 : app.conf.compression_level;
	app.conf.cors = app.conf.cors === undefined ? '*' : app.conf.cors;
	if (app.conf.csp === undefined) {
		app.conf.csp = "default-src 'self'; object-src 'none'; media-src 'none'; img-src 'none'; style-src 'none'; base-uri 'self'; frame-ancestors 'self'";
	}

	// set outgoing proxy
	if (app.conf.proxy) {
		process.env.HTTP_PROXY = app.conf.proxy;
		// if there is a list of domains which should
		// not be proxied, set it
		if (app.conf.no_proxy_list) {
			if (Array.isArray(app.conf.no_proxy_list)) {
				process.env.NO_PROXY = app.conf.no_proxy_list.join(',');
			} else {
				process.env.NO_PROXY = app.conf.no_proxy_list;
			}
		}
	}

	// set up header whitelisting for logging
	if (!app.conf.log_header_whitelist) {
		app.conf.log_header_whitelist = [
			'cache-control', 'content-type', 'content-length', 'if-match',
			'user-agent', 'x-request-id'
		];
	}
	app.conf.log_header_whitelist = new RegExp(`^(?:${app.conf.log_header_whitelist.map((item) => {
		return item.trim();
	}).join('|')})$`, 'i');

	// set up the request templates for the APIs
	apiUtil.setupApiTemplates(app);

	// set up the spec
	if (!app.conf.spec) {
		app.conf.spec = `${__dirname}/spec.yaml`;
	}
	if (app.conf.spec.constructor !== Object) {
		try {
			app.conf.spec = yaml.safeLoad(fs.readFileSync(app.conf.spec));
		} catch (e) {
			app.logger.log('warn/spec', `Could not load the spec: ${e}`);
			app.conf.spec = {};
		}
	}
	if (!app.conf.spec.openapi) {
		app.conf.spec.openapi = '3.0.0';
	}
	if (!app.conf.spec.info) {
		app.conf.spec.info = {
			version: app.info.version,
			title: app.info.name,
			description: app.info.description
		};
	}
	app.conf.spec.info.version = app.info.version;
	if (!app.conf.spec.paths) {
		app.conf.spec.paths = {};
	}

	// set the CORS and CSP headers
	app.all('*', (req, res, next) => {
		if (app.conf.cors !== false) {
			res.header('access-control-allow-origin', app.conf.cors);
			res.header('access-control-allow-headers', 'accept, x-requested-with, content-type');
			res.header('access-control-expose-headers', 'etag');
		}
		if (app.conf.csp !== false) {
			res.header('x-xss-protection', '1; mode=block');
			res.header('x-content-type-options', 'nosniff');
			res.header('x-frame-options', 'SAMEORIGIN');
			res.header('content-security-policy', app.conf.csp);
		}
		sUtil.initAndLogRequest(req, app);
		next();
	});

	// set up the user agent header string to use for requests
	app.conf.user_agent = app.conf.user_agent || app.info.name;

	// disable the X-Powered-By header
	app.set('x-powered-by', false);
	// disable the ETag header - users should provide them!
	app.set('etag', false);
	// enable compression
	app.use(compression({ level: app.conf.compression_level }));
	// use the JSON body parser
	app.use(bodyParser.json({ limit: app.conf.max_body_size || '100kb' }));
	// use the application/x-www-form-urlencoded parser
	app.use(bodyParser.urlencoded({ extended: true }));

	return BBPromise.resolve(app);

}

/**
 * Loads all routes declared in routes/ into the app
 *
 * @param {Application} app the application object to load routes into
 * @param {string} dir routes folder
 * @return {bluebird} a promise resolving to the app object
 */
function loadRoutes(app, dir) {

	// recursively load routes from .js files under routes/
	return fs.readdirAsync(dir).map((fname) => {
		return BBPromise.try(() => {
			const resolvedPath = path.resolve(dir, fname);
			const isDirectory = fs.statSync(resolvedPath).isDirectory();
			if (isDirectory) {
				loadRoutes(app, resolvedPath);
			} else if (/\.js$/.test(fname)) {
				// import the route file
				const route = require(`${dir}/${fname}`);
				return route(app);
			}
		}).then((route) => {
			if (route === undefined) {
				return undefined;
			}
			// check that the route exports the object we need
			if (route.constructor !== Object || !route.path || !route.router ||
                !(route.api_version || route.skip_domain)) {
				throw new TypeError(`routes/${fname} does not export the correct object!`);
			}
			// normalise the path to be used as the mount point
			if (route.path[0] !== '/') {
				route.path = `/${route.path}`;
			}
			if (route.path[route.path.length - 1] !== '/') {
				route.path = `${route.path}/`;
			}
			if (!route.skip_domain) {
				route.path = `/:domain/v${route.api_version}${route.path}`;
			}
			// wrap the route handlers with Promise.try() blocks
			sUtil.wrapRouteHandlers(route, app);
			// all good, use that route
			app.use(route.path, route.router);
		});
	}).then(() => {
		// catch errors
		sUtil.setErrorHandler(app);
		// route loading is now complete, return the app object
		return BBPromise.resolve(app);
	});

}

/**
 * Creates and start the service's web server
 *
 * @param {Application} app the app object to use in the service
 * @return {bluebird} a promise creating the web server
 */
function createServer(app) {

	// return a promise which creates an HTTP server,
	// attaches the app to it, and starts accepting
	// incoming client requests
	let server;
	return new BBPromise((resolve) => {
		server = http.createServer(app).listen(
			app.conf.port,
			app.conf.interface,
			resolve
		);
		server = addShutdown(server);
	}).then(() => {
		app.logger.log('info',
			`Worker ${process.pid} listening on ${app.conf.interface || '*'}:${app.conf.port}`);

		// Don't delay incomplete packets for 40ms (Linux default) on
		// pipelined HTTP sockets. We write in large chunks or buffers, so
		// lack of coalescing should not be an issue here.
		server.on('connection', (socket) => {
			socket.setNoDelay(true);
		});

		return server;
	});

}

/**
 * The service's entry point. It takes over the configuration
 * options and the logger- and metrics-reporting objects from
 * service-runner and starts an HTTP server, attaching the application
 * object to it.
 *
 * @param {Object} options the options to initialise the app with
 * @return {bluebird} HTTP server
 */
module.exports = (options) => {

	return initApp(options)
		.then((app) => loadRoutes(app, `${__dirname}/routes`))
		.then((app) => {
			// serve static files from static/
			app.use('/static', express.static(`${__dirname}/static`));
			return app;
		}).then(createServer);

};


text:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Administradores_model extends CI_Model {

    private $tabla = 'administradores';
    public $status = true;

  	function __construct(){
  	   parent::__construct();
    }

    public function crear($username,$email,$nombre,$apellidos,$telefono){
        $datos = array(
            'adm_username' => $username,
            'adm_email' => $email,
            'adm_nombre' => $nombre,
            'adm_apellidos' => $apellidos,
            'adm_telefono' => $telefono
        );
        if($this->db->insert($this->tabla,$datos)){
            $this->status = true;
        } else {
            $this->status = false;
        }
    }

    public function editar($admin_id,$username,$email,$nombre,$apellidos,$telefono){
        $datos = array(
            'adm_username' => $username,
            'adm_email' => $email,
            'adm_nombres' => $nombre,
            'adm_apellidos' => $apellidos,
            'adm_telefono' => $telefono
        );
        $this->db->where('adm_id', $admin_id);
        if($this->db->update($this->tabla,$datos)){
            $this->status = true;
        } else {
            $this->status = false;
        }
    }

    public function eliminar($admin_id, $tipo_eliminacion='logica'){
        if($tipo_eliminacion == 'logica'){
            $data = array(
                'adm_activo' => 0
            );
            $this->db->where('adm_id', $admin_id);
            if($this->db->update($this->tabla,$datos)){
                $this->status = true;
            } else {
                $this->status = false;
            }
        } else {
            $this->db->where('adm_id', $admin_id);
            if($this->db->delete($this->tabla,$datos)){
                $this->status = true;
            } else {
                $this->status = false;
            }
        }
    }

    public function cambiar_password($admin_id, $password_actual, $password_nuevo, $password_confirmacion){

        $this->load->helper('password');
        $password_actual = hashear_password($password_actual);
        $password_nuevo = hashear_password($password_nuevo);
        $password_confirmacion = hashear_password($password_confirmacion);

        if($password_nuevo == $password_confirmacion){
            $data = array(
                'adm_password' => $password_nuevo
            );
            $this->db->where('adm_password',$password_actual);
            $this->db->where('adm_id',$admin_id);
            $this->db->update($this->tabla,$data);

            if($this->db->affected_rows()>=1){
                return true;
            } else {
                return false;
            }

        } else {
            return false;
        }

    }

}
?>


text:
namespace tz::gl
{
	namespace detail
	{
		std::array<const char*, static_cast<int>(ResourceAccess::Count)> resource_access_strings
		{
			"Static Fixed",
			"Dynamic Fixed",
			"Dynamic Variable"
		};

		std::array<const char*, static_cast<int>(ResourceFlag::Count)> resource_flag_strings
		{
			"Index Buffer",
			"Renderer Output",
			"Image Filter: Nearest",
			"Image Filter: Linear",
			"Image Mip Filter: Nearest",
			"Image Mip Filter: Linear",
			"Image Wrap: Clamp To Edge",
			"Image Wrap: Repeat",
			"Image Wrap: Mirrored Repeat"
		};
	}

	ResourceType Resource::get_type() const
	{
		return this->type;
	}

	ResourceAccess Resource::get_access() const
	{
		return this->access;
	}

	const ResourceFlags& Resource::get_flags() const
	{
		return this->flags;
	}

	std::span<const std::byte> Resource::data() const
	{
		if(this->mapped_resource_data.has_value())
		{
			return this->mapped_resource_data.value();
		}
		auto beg_offsetted = this->resource_data.begin() + this->initial_alignment_offset;
		return {beg_offsetted, this->resource_data.end()};
	}

	std::span<std::byte> Resource::data()
	{
		if(this->mapped_resource_data.has_value())
		{
			return this->mapped_resource_data.value();
		}
		auto beg_offsetted = this->resource_data.begin() + this->initial_alignment_offset;
		return {beg_offsetted, this->resource_data.end()};
	}

	void Resource::dbgui()
	{
		const char* type;
		switch(this->get_type())
		{
			case ResourceType::Buffer:
				type = "Buffer";
			break;
			case ResourceType::Image:
				type = "Image";
			break;
			default:
				type = "Unknown";
			break;
		}
		ImGui::Text("Resource Type: %s", type);
		ImGui::Text("Resource Access: %s", detail::resource_access_strings[static_cast<int>(this->get_access())]);
		if(!this->get_flags().empty() && ImGui::CollapsingHeader("Resource Flags"))
		{
			ImGui::Indent();
			for(tz::gl::ResourceFlag flag : this->get_flags())
			{
				ImGui::Text("%s", detail::resource_flag_strings[static_cast<int>(flag)]);
			}
			ImGui::Unindent();
		}
	}

	void Resource::resize_data(std::size_t new_size)
	{
		this->resource_data.resize(new_size);
	}

	Resource::Resource(ResourceAccess access, std::vector<std::byte> resource_data, std::size_t initial_alignment_offset, ResourceType type, ResourceFlags flags):
	access(access),
	resource_data(resource_data),
	mapped_resource_data(std::nullopt),
	initial_alignment_offset(initial_alignment_offset),
	type(type),
	flags(flags)
	{
		hdk::assert(!flags.contains(ResourceFlag::ImageMipNearest) && !flags.contains(ResourceFlag::ImageMipLinear), "Detected resource flag related to image mip filtering. Mips are not yet implemented.");
	}

	void Resource::set_mapped_data(std::span<std::byte> mapped_resource_data)
	{
		hdk::assert(this->get_access() == ResourceAccess::DynamicFixed || this->get_access() == ResourceAccess::DynamicVariable, "Cannot set mapped data on a static resource.");
		this->mapped_resource_data = mapped_resource_data;
	}

	bool BufferResource::is_null() const
	{
		return this->data().size_bytes() == 1 && this->data_as<std::byte>().front() == std::byte{255};
	}

	std::unique_ptr<IResource> BufferResource::unique_clone() const
	{
		return std::make_unique<BufferResource>(*this);
	}

	void BufferResource::dbgui()
	{
		Resource::dbgui();
		auto size_bytes = this->data().size_bytes();
		ImGui::Text("Buffer Size: ");
		ImGui::SameLine();
		if(size_bytes > (1024*1024*1024))
		{
			ImGui::Text("%.2f GiB", size_bytes / (1024.0f * 1024 * 1024));
		}
		else if(size_bytes > (1024*1024))
		{
			ImGui::Text("%.2f MiB", size_bytes / (1024.0f * 1024));
		}
		else if(size_bytes > 1024)
		{
			ImGui::Text("%.2f KiB", size_bytes / 1024.0f);
		}
		else
		{
			ImGui::Text("%zu B", size_bytes);
		}
	}

	BufferResource::BufferResource(ResourceAccess access, std::vector<std::byte> resource_data, std::size_t initial_alignment_offset, ResourceFlags flags):
	Resource(access, resource_data, initial_alignment_offset, ResourceType::Buffer, flags){}

	ImageResource ImageResource::from_uninitialised(ImageInfo info)
	{
		std::size_t pixel_size = tz::gl::pixel_size_bytes(info.format);
		std::vector<std::byte> resource_data(pixel_size * info.dimensions[0] * info.dimensions[1]);
		// TODO: Sanity check? Is it correct to just not give a shit about alignment here?
		return {info.access, resource_data, 0, info.format, info.dimensions, info.flags};
	}

	bool ImageResource::is_null() const
	{
		const ImageResource null = ImageResource::null();
		auto null_data = null.data();
		auto my_data = this->data();
		return this->get_dimensions() == null.get_dimensions() && this->get_format() == null.get_format() && std::equal(my_data.begin(), my_data.end(), null_data.begin());
	}

	std::unique_ptr<IResource> ImageResource::unique_clone() const
	{
		return std::make_unique<ImageResource>(*this);
	}

	void ImageResource::dbgui()
	{
		Resource::dbgui();
		ImGui::Text("Image Dimensions: {%u, %u}", this->dimensions[0], this->dimensions[1]);
		ImGui::Text("Image Format: %s", detail::image_format_strings[static_cast<int>(this->get_format())]);
	}

	ImageFormat ImageResource::get_format() const
	{
		return this->format;
	}

	hdk::vec2ui ImageResource::get_dimensions() const
	{
		return this->dimensions;
	}

	void ImageResource::set_dimensions(hdk::vec2ui dims)
	{
		this->dimensions = dims;
	}

	ImageResource::ImageResource(ResourceAccess access, std::vector<std::byte> resource_data, std::size_t initial_alignment_offset, ImageFormat format, hdk::vec2ui dimensions, ResourceFlags flags):
	Resource(access, resource_data, initial_alignment_offset, ResourceType::Image, flags),
	format(format),
	dimensions(dimensions){}
}


text:
package net.adamcin.oakpal.cli;

import net.adamcin.oakpal.api.Fun;
import net.adamcin.oakpal.api.Nothing;
import net.adamcin.oakpal.api.Result;
import net.adamcin.oakpal.api.Severity;
import net.adamcin.oakpal.core.InstallHookPolicy;
import net.adamcin.oakpal.core.OakpalPlan;
import net.adamcin.oakpal.core.opear.AdhocOpear;
import net.adamcin.oakpal.core.opear.Opear;
import net.adamcin.oakpal.core.opear.OpearFile;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URI;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.Base64;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.function.Function;
import java.util.jar.JarFile;
import java.util.stream.Collectors;

import static net.adamcin.oakpal.api.Fun.compose1;
import static net.adamcin.oakpal.api.Fun.constantly1;
import static net.adamcin.oakpal.api.Fun.result1;

final class Options {
    static final String CACHE_DIR_NAME = ".oakpal-cache";
    static final Function<StructuredMessage, IO<Nothing>> EMPTY_PRINTER = message -> IO.empty;
    static final Options DEFAULT_OPTIONS = new Options();
    private final boolean justHelp;
    private final boolean justVersion;
    private final boolean storeBlobs;
    private final URL planUrl;
    private final ClassLoader scanClassLoader;
    private final File cacheDir;
    private final File opearFile;
    private final String planName;
    private final File planFile;
    private final File planFileBaseDir;
    private final List<File> preInstallFiles;
    private final List<File> repoInitFiles;
    private final List<String> runModes;
    private final boolean noRunModes;
    private final List<File> extendedClassPathFiles;
    private final boolean noHooks;
    private final List<File> scanFiles;
    private final Function<StructuredMessage, IO<Nothing>> printer;
    private final Severity failOnSeverity;

    Options() {
        this(true, true, false,
                OakpalPlan.BASIC_PLAN_URL, Options.class.getClassLoader(),
                new File(System.getProperty("java.io.tmpdir")),
                null, null, null, null,
                Collections.emptyList(),
                Collections.emptyList(),
                Collections.emptyList(), false,
                Collections.emptyList(), false,
                Collections.emptyList(),
                EMPTY_PRINTER,
                Severity.MAJOR);
    }

    Options(final boolean justHelp,
            final boolean justVersion,
            final boolean storeBlobs,
            final @NotNull URL planUrl,
            final @NotNull ClassLoader scanClassLoader,
            final @NotNull File cacheDir,
            final @Nullable File opearFile,
            final @Nullable String planName,
            final @Nullable File planFile,
            final @Nullable File planFileBaseDir,
            final @NotNull List<File> preInstallFiles,
            final @NotNull List<File> repoInitFiles,
            final @NotNull List<String> runModes,
            final boolean noRunModes,
            final @NotNull List<File> extendedClassPathFiles,
            final boolean noHooks,
            final @NotNull List<File> scanFiles,
            final @NotNull Function<StructuredMessage, IO<Nothing>> printer,
            final @NotNull Severity failOnSeverity) {
        this.justHelp = justHelp;
        this.justVersion = justVersion;
        this.storeBlobs = storeBlobs;
        this.planUrl = planUrl;
        this.scanClassLoader = scanClassLoader;
        this.cacheDir = cacheDir;
        this.opearFile = opearFile;
        this.planName = planName;
        this.planFile = planFile;
        this.planFileBaseDir = planFileBaseDir;
        this.preInstallFiles = preInstallFiles;
        this.repoInitFiles = repoInitFiles;
        this.runModes = runModes;
        this.noRunModes = noRunModes;
        this.extendedClassPathFiles = extendedClassPathFiles;
        this.noHooks = noHooks;
        this.scanFiles = scanFiles;
        this.printer = printer;
        this.failOnSeverity = failOnSeverity;
    }

    public boolean isJustHelp() {
        return justHelp;
    }

    public boolean isJustVersion() {
        return justVersion;
    }

    public boolean isStoreBlobs() {
        return storeBlobs;
    }

    public boolean isNoHooks() {
        return noHooks;
    }

    public URL getPlanUrl() {
        return planUrl;
    }

    public ClassLoader getScanClassLoader() {
        return scanClassLoader;
    }

    public File getCacheDir() {
        return cacheDir;
    }

    public @Nullable File getOpearFile() {
        return opearFile;
    }

    public @Nullable String getPlanName() {
        return planName;
    }

    public @Nullable File getPlanFile() {
        return planFile;
    }

    public @Nullable File getPlanFileBaseDir() {
        return planFileBaseDir;
    }

    public @NotNull List<File> getPreInstallFiles() {
        return preInstallFiles;
    }

    public @NotNull List<File> getRepoInitFiles() {
        return repoInitFiles;
    }

    public @NotNull List<String> getRunModes() {
        return runModes;
    }

    public boolean isNoRunModes() {
        return noRunModes;
    }

    public @NotNull List<File> getExtendedClassPathFiles() {
        return extendedClassPathFiles;
    }

    public List<File> getScanFiles() {
        return scanFiles;
    }

    public Function<StructuredMessage, IO<Nothing>> getPrinter() {
        return printer;
    }

    public Severity getFailOnSeverity() {
        return failOnSeverity;
    }

    boolean hasOverrides() {
        return noHooks || !getPreInstallFiles().isEmpty() || !getRepoInitFiles().isEmpty()
                || !getRunModes().isEmpty() || noRunModes;
    }

    public OakpalPlan applyOverrides(final @NotNull OakpalPlan basePlan) {
        if (hasOverrides()) {
            final OakpalPlan.Builder overridePlan = new OakpalPlan.Builder(basePlan.getBase(), basePlan.getName())
                    .startingWithPlan(basePlan);
            if (!getPreInstallFiles().isEmpty()) {
                List<URL> allUrls = new ArrayList<>(basePlan.getPreInstallUrls());
                getPreInstallFiles().stream().map(compose1(File::toURI, result1(URI::toURL)))
                        .collect(Result.tryCollect(Collectors.toList())).forEach(allUrls::addAll);
                overridePlan.withPreInstallUrls(allUrls);
            }
            if (!getRepoInitFiles().isEmpty()) {
                List<URL> allUrls = new ArrayList<>(basePlan.getRepoInitUrls());
                if (!basePlan.getRepoInits().isEmpty()) {
                    cacheRepoInits(getCacheDir(), basePlan.getRepoInits()).forEach(repoInitUrl -> {
                        allUrls.add(repoInitUrl);
                        overridePlan.withRepoInits(Collections.emptyList());
                    });
                }
                getRepoInitFiles().stream().map(compose1(File::toURI, result1(URI::toURL)))
                        .collect(Result.tryCollect(Collectors.toList())).forEach(allUrls::addAll);
                overridePlan.withRepoInitUrls(allUrls);
            }
            if (noRunModes) {
                overridePlan.withRunModes(Collections.emptyList());
            } else if (!getRunModes().isEmpty()) {
                overridePlan.withRunModes(getRunModes());
            }
            if (isNoHooks()) {
                overridePlan.withInstallHookPolicy(InstallHookPolicy.SKIP);
                overridePlan.withEnablePreInstallHooks(false);
            }
            return overridePlan.build();
        } else {
            return basePlan;
        }
    }

    static byte[] getRepoInitBytes(final List<String> repoInits) {
        return String.join("\n", repoInits).getBytes(StandardCharsets.UTF_8);
    }

    static Result<String> fileNameForRepoInitBytes(final byte[] repoInitBytes) {
        return result1((Fun.ThrowingFunction<? super String, MessageDigest>) MessageDigest::getInstance)
                .apply("SHA-1")
                .map(digest -> digest.digest(repoInitBytes))
                .map(Base64.getUrlEncoder()::encodeToString);
    }

    static Result<Nothing> writeToStream(final @NotNull byte[] bytesToWrite,
                                         final @NotNull Fun.ThrowingSupplier<OutputStream> streamSupplier) {
        try (OutputStream out = streamSupplier.tryGet()) {
            out.write(bytesToWrite);
            return Result.success(Nothing.instance);
        } catch (Exception e) {
            return Result.failure(e);
        }
    }

    static Result<URL> cacheRepoInits(final @NotNull File cacheDir, final @NotNull List<String> repoInits) {
        if (repoInits.isEmpty()) {
            return Result.failure("refusing to cache empty repoinit script");
        }
        final byte[] repoInitBytes = getRepoInitBytes(repoInits);
        final File parentDir = cacheDir.toPath().resolve("repoinits").toFile();
        parentDir.mkdirs();
        return fileNameForRepoInitBytes(repoInitBytes)
                .map(fileName -> new File(parentDir, fileName))
                .flatMap(cacheFile -> {
                    final Result<URL> cacheFileUrl = compose1(File::toURI, result1(URI::toURL)).apply(cacheFile);
                    if (cacheFile.exists()) {
                        return cacheFileUrl;
                    } else {
                        return writeToStream(repoInitBytes, () -> new FileOutputStream(cacheFile))
                                .flatMap(constantly1(() -> cacheFileUrl));
                    }
                });
    }

    static final class Builder {
        private boolean justHelp;
        private boolean justVersion;
        private boolean storeBlobs;
        private boolean outputJson;
        private boolean noPlan;
        private boolean noHooks;
        private String planName;
        private File planFile;
        private File planFileBaseDir;
        private List<File> preInstallFiles = new ArrayList<>();
        private List<File> repoInitFiles = new ArrayList<>();
        private List<String> runModes = new ArrayList<>();
        private boolean noRunModes;
        private List<File> extendedClassPathFiles = new ArrayList<>();
        private File outFile;
        private File cacheDir;
        private File opearFile;
        private List<File> scanFiles = new ArrayList<>();
        private Severity failOnSeverity;

        public Builder setJustHelp(final boolean justHelp) {
            this.justHelp = justHelp;
            return this;
        }

        public Builder setJustVersion(final boolean justVersion) {
            this.justVersion = justVersion;
            return this;
        }

        public Builder setStoreBlobs(final boolean storeBlobs) {
            this.storeBlobs = storeBlobs;
            return this;
        }

        public Builder setOutputJson(final boolean outputJson) {
            this.outputJson = outputJson;
            return this;
        }

        public Builder setNoPlan(final boolean noPlan) {
            this.noPlan = noPlan;
            return this;
        }

        public Builder setNoHooks(final boolean noHooks) {
            this.noHooks = noHooks;
            return this;
        }

        public Builder setPlanName(final @Nullable String planName) {
            this.planName = planName;
            return this;
        }

        public Builder setPlanFileBaseDir(final @Nullable File planFileBaseDir) {
            this.planFileBaseDir = planFileBaseDir;
            return this;
        }

        public Builder setPlanFile(final @Nullable File planFile) {
            this.planFile = planFile;
            return this;
        }

        public Builder setPreInstallFiles(final @NotNull List<File> preInstallFiles) {
            this.preInstallFiles = preInstallFiles;
            return this;
        }

        public Builder addPreInstallFile(final @NotNull File preInstallFile) {
            this.preInstallFiles.add(preInstallFile);
            return this;
        }

        public Builder setRepoInitFiles(final @NotNull List<File> repoInitFiles) {
            this.repoInitFiles = repoInitFiles;
            return this;
        }

        public Builder addRepoInitFile(final @NotNull File repoInitFile) {
            this.repoInitFiles.add(repoInitFile);
            return this;
        }

        public Builder setRunModes(final @NotNull List<String> runModes) {
            this.runModes = runModes;
            return this;
        }

        public Builder setNoRunModes(final boolean noRunModes) {
            this.noRunModes = noRunModes;
            return this;
        }

        public Builder setExtendedClassPathFiles(final @NotNull List<File> extendedClassPathFiles) {
            this.extendedClassPathFiles = new ArrayList<>(extendedClassPathFiles);
            return this;
        }

        public Builder addExtendedClassPathFile(final @NotNull File extendedClassPathFile) {
            this.extendedClassPathFiles.add(extendedClassPathFile);
            return this;
        }

        public Builder setOutFile(final @Nullable File outFile) {
            this.outFile = outFile;
            return this;
        }

        public Builder setCacheDir(final @Nullable File cacheDir) {
            this.cacheDir = cacheDir;
            return this;
        }

        public Builder setOpearFile(final @Nullable File opearFile) {
            this.opearFile = opearFile;
            return this;
        }

        public Builder addScanFile(final @NotNull File scanFile) {
            this.scanFiles.add(scanFile);
            return this;
        }

        public Builder setFailOnSeverity(final @Nullable Severity failOnSeverity) {
            this.failOnSeverity = failOnSeverity;
            return this;
        }

        Result<Opear> buildOpear(final @NotNull Console console, final @NotNull File opearCache) {
            final Result<Opear> baseOpear;
            if (planFile != null) {
                baseOpear = buildAdhocOpear(console).map(Function.identity());
            } else {
                baseOpear = buildOpearFile(console, opearCache).map(Function.identity());
            }
            return baseOpear;
        }

        Result<AdhocOpear> buildAdhocOpear(final @NotNull Console console) {
            return AdhocOpear.fromPlanFile(planFile, planFileBaseDir);
        }

        Result<OpearFile> buildOpearFile(final @NotNull Console console, final @NotNull File opearCache) {
            final File opearResolved = Optional.ofNullable(opearFile).orElseGet(() ->
                    console.getCwd().toPath().resolve(
                            console.getEnv().getOrDefault(Console.ENV_OAKPAL_OPEAR, "."))
                            .toFile());

            return Result.success(opearResolved.getAbsoluteFile())
                    .flatMap(file -> {
                        if (file.isFile()) {
                            try (JarFile jarFile = new JarFile(file, true)) {
                                return OpearFile.fromJar(jarFile, opearCache);
                            } catch (IOException e) {
                                return Result.failure(String.format("%s is not a jar format file", file.getPath()), e);
                            }
                        } else {
                            return OpearFile.fromDirectory(file);
                        }
                    });
        }

        Result<ClassLoader> getExtendedClassLoader(final @NotNull Opear opear,
                                                   final @NotNull ClassLoader parentClassLoader) {
            if (this.extendedClassPathFiles.isEmpty()) {
                return Result.success(opear.getPlanClassLoader(getClass().getClassLoader()));
            } else {
                final URL[] urls = this.extendedClassPathFiles.stream()
                        .filter(File::exists)
                        .filter(file -> file.isDirectory() || file.getName().endsWith(".jar"))
                        .flatMap(compose1(compose1(File::toURI, result1(URI::toURL)), Result::stream))
                        .toArray(URL[]::new);
                return Result.success(new URLClassLoader(urls, opear.getPlanClassLoader(parentClassLoader)));
            }
        }

        Result<Options> build(final @NotNull Console console) {
            final File realCacheDir = this.cacheDir != null
                    ? this.cacheDir
                    : console.getCwd().toPath().resolve(CACHE_DIR_NAME).toFile().getAbsoluteFile();
            final File opearCache = new File(realCacheDir, "opears");
            opearCache.mkdirs();

            Result<Opear> opearResult = buildOpear(console, opearCache);

            return opearResult.flatMap(opear -> Optional.ofNullable(planName).map(opear::getSpecificPlan)
                    .orElse(Result.success(noPlan ? OakpalPlan.EMPTY_PLAN_URL : opear.getDefaultPlan()))
                    .flatMap(planUrl -> getExtendedClassLoader(opear, getClass().getClassLoader())
                            .flatMap(classLoader -> messageWriter(console, outputJson, outFile).map(writer ->
                                    new Options(justHelp, justVersion, storeBlobs, planUrl,
                                            classLoader, realCacheDir, opearFile, planName, planFile,
                                            planFileBaseDir, preInstallFiles, repoInitFiles, runModes, noRunModes,
                                            extendedClassPathFiles, noHooks, scanFiles, writer,
                                            Optional.ofNullable(failOnSeverity)
                                                    .orElse(DEFAULT_OPTIONS.failOnSeverity))))));
        }
    }

    /**
     * Writes a structured message to the appropriate stream in the appropriate format.
     *
     * @param outputJson whether to output json or not
     * @return a nothing IO monad.
     */
    static @NotNull Result<Function<StructuredMessage, IO<Nothing>>> messageWriter(final @NotNull Console console,
                                                                                final boolean outputJson,
                                                                                final @Nullable File outFile) {
        final Function<StructuredMessage, Object> objectifier = outputJson
                ? StructuredMessage::toJson : message -> message;
        final Result<Function<Object, IO<Nothing>>> printerResult = Optional.ofNullable(outFile)
                .map(file -> console.openPrinter(file).map(printer -> (Function<Object, IO<Nothing>>) printer))
                .orElse(Result.success(console::printLine));
        return printerResult.map(objectifier::andThen);
    }

}


text:
id: reference-cli-pulsar-shell
title: Pulsar CLI tools - pulsar-shell
sidebar_label: "cli-pulsar-shell"
---

## `pulsar-shell`

[Pulsar shell](administration-pulsar-shell.md) tool.

### Interactive mode

Usage

```bash
pulsar-shell
```

Options

| Flag               | Description                                                               | Default          |
|--------------------|---------------------------------------------------------------------------|------------------|
| `-c`, `--config`   | Client configuration file. It is used as a `default` config.           | conf/client.conf |
| `--fail-on-error` | If true, the shell is interrupted when a command throws an exception.  | false            |
| `-h`, `--help`     | Show this help.                                                            | |

### Non interactive mode

Usage

```bash
pulsar-shell -f [FILE]
pulsar-shell -e [COMMAND]
echo "[COMMAND]" | pulsar-shell -
```

Options

| Flag                      | Description                                                                                | Default         |
|---------------------------|-----------------------------------------------------------------------------------------------------|-----------------|
| `-c`, `--config`          | Client configuration file. It is used as a `default` config.                                     | conf/client.conf |
| `--fail-on-error`         | If true, the shell is interrupted when a command throws an exception.                            | false           |
| `-np`, `--no-progress`    | Display raw output of the commands without the fancy progress visualization.                        | false           |
| `-f`, `--filename`        | Input filename with a list of commands to be executed. Each command must be separated by a newline. |                 |
| `-e`, `--execute-command` | Execute this command and exit.                                                                      | |
| `-` | Read commands from the standard input.                                                              | |
| `-h`, `--help`     | Show this help.                                                                                | |

Commands
* `admin` - See [Admin API](admin-api-overview.md)
* `client` - See [pulsar-client](#pulsar-client)
* `config`

### `config`

Manage shell configurations.

#### `use`

Use a specific configuration for next commands.

```bash
default(localhost)> config use mycluster
```

#### `create`

Create a new configuration.

```bash
default(localhost)> config create --file ./conf/client.conf mycluster
```

Options

| Flag     | Description              | Default         |
|----------|--------------------------|-----------------|
| `--file` | File path of the config. |  |
| `--url`  | URL of the config.       |  |
| `--value`  | Inline value of the config. Base64-encoded value is supported with the prefix `base64:`. |  |

#### `update`

Update an existing configuration.

```bash
default(localhost)> config update --file ./conf/client.conf mycluster
```

Options

| Flag     | Description              | Default         |
|----------|--------------------------|-----------------|
| `--file` | File path of the config. |  |
| `--url`  | URL of the config.       |  |
| `--value`  | Inline value of the config. Base64-encoded value is supported with the prefix `base64:`. |  |

#### `set-property`

Set a value for a specified configuration property.

```bash
default(localhost)> config set-property -p webServiceUrl -v http://<cluster-hostname> mycluster
```

Options

| Flag               | Description                 | Default         |
|--------------------|-----------------------------|-----------------|
| `-p`, `--property` | Property name to update.    |  |
| `-v`, `--value`    | New value for the property. |  |

#### `get-property`

Get the value for a specified configuration property.

```bash
default(localhost)> config get-property -p webServiceUrl mycluster
```

Options

| Flag               | Description                 | Default         |
|--------------------|-----------------------------|-----------------|
| `-p`, `--property` | Property name to update.    |  |

#### `view`

View details of a config.

```bash
default(localhost)> config view mycluster
```

#### `delete`

Delete a config. You can't delete a config if it's currently used.

```bash
default(localhost)> config delete mycluster
```

#### `list`

List all the configuration names.

```bash
default(localhost)> config list
```


text:
// Copyright (C) 2005 and onwards Google, Inc.

/**
 * A simple listdictionary implementation. Items added to the dictionary can be
 * indexed by key, but are also retrievable in the order they were added.
 *
 * Depends on:
 * google3/lang.js
 */
function CLB_ListDictionary() {
  this.index_ = {};
  this.items_ = [];
}

CLB_ListDictionary.ITEM_EXISTS_ERROR
  = new Error("The specified key already exists.");

CLB_ListDictionary.prototype.debugZone = "CLB_ListDictionary";

CLB_ListDictionary.prototype.addItem = function(key, val) {
  if (isDef(this.index_[key])) {
    throw CLB_ListDictionary.ITEM_EXISTS_ERROR;
  }

  this.index_[key] = this.items_.push({key:key, val:val}) - 1;
}

CLB_ListDictionary.prototype.addOrReplaceItem = function(key, val) {
  var idx = this.index_[key];

  if (!isDef(idx)) {
    this.addItem(key, val);
  } else {
    this.items_[idx] = {key:key, val:val};
  }
}

CLB_ListDictionary.prototype.getItem = function(key) {
  if (isDef(this.index_[key])) {
    return this.items_[this.index_[key]].val;
  }
}

CLB_ListDictionary.prototype.getList = function() {
  return this.items_;
}

CLB_ListDictionary.prototype.deleteItem = function(key) {
  var idx = this.index_[key];

  if (isDef(idx)) {
    delete this.index_[key];
    this.items_.splice(idx, 1);
    for (var i = idx; i < this.items_.length; i++) {
      this.index_[this.items_[i].key]--;
    }
  }
}

//G_debugService.loggifier.loggify(CLB_ListDictionary.prototype);


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="description" content="ECharts">
    <meta name="author" content="kener.linfeng@gmail.com">
    <title>ECharts · Example</title>

    <link rel="shortcut icon" href="../asset/ico/favicon.png">

    <link href="../asset/css/font-awesome.min.css" rel="stylesheet">
    <link href="../asset/css/bootstrap.css" rel="stylesheet">
    <link href="../asset/css/carousel.css" rel="stylesheet">
    <link href="../asset/css/echartsHome.css" rel="stylesheet">

    <link href="../asset/css/codemirror.css" rel="stylesheet">
    <link href="../asset/css/monokai.css" rel="stylesheet">

option

                    <textarea id="code" name="code">
var heatData = [];
for (var i = 0; i < 20; ++i) {
    heatData.push([
        400 + Math.random() * 300,
        5 + Math.random() * 10,
        Math.random()
    ]);
}
for (var i = 0; i < 100; ++i) {
    heatData.push([
        100 + Math.random() * 600,
        150 + Math.random() * 50,
        Math.random()
    ]);
}
for (var i = 0; i < 200; ++i) {
    heatData.push([
        Math.random() * 1000,
        Math.random() * 800,
        Math.random() * 0.5
    ]);
}
option = {
    title : {
        text: '热力图'
    },
    series : [
        {
            type : 'heatmap',
            data : heatData,
            hoverable : false
        }
    ]
};
                    </textarea>

                    <button type="button" class="btn btn-sm btn-success" onclick="refresh(true)">刷 新</button>
                    切换主题
                    <select id="theme-select"></select>


text:
license: >
    Licensed to the Apache Software Foundation (ASF) under one
    or more contributor license agreements.  See the NOTICE file
    distributed with this work for additional information
    regarding copyright ownership.  The ASF licenses this file
    to you 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.

title: notification.alert
---

notification.alert
==================

Shows a custom alert or dialog box.

    navigator.notification.alert(message, alertCallback, [title], [buttonName])

- __message:__ Dialog message (`String`)
- __alertCallback:__ Callback to invoke when alert dialog is dismissed. (`Function`)
- __title:__ Dialog title (`String`) (Optional, Default: "Alert")
- __buttonName:__ Button name (`String`) (Optional, Default: "OK")

Description
-----------

Most Cordova implementations use a native dialog box for this feature.  However, some platforms simply use the browser's `alert` function, which is typically less customizable.

Supported Platforms
-------------------

- Android
- BlackBerry OS 5 - 7 and BlackBerry 10
- iPhone
- Windows Phone 7 and 8
- Bada 1.2 & 2.x
- webOS
- Tizen
- Windows 8

Quick [Example](../storage/storage.opendatabase.html)
-------------

    // Android / BlackBerry OS 5 - 7 and BlackBerry 10 / iPhone / Tizen
    //
    function alertDismissed() {
        // do something
    }

    navigator.notification.alert(
        'You are the winner!',  // message
        alertDismissed,         // callback
        'Game Over',            // title
        'Done'                  // buttonName
    );

Full [Example](../storage/storage.opendatabase.html)
------------

    <!DOCTYPE html>

        <title>Notification Example</title>

Show Alert

Windows Phone 7 and 8 Quirks
-------------

- There is no built in browser alert, so if you want to just write alert('foo'); you can assign window.alert = navigator.notification.alert;
- alert + confirm calls are non-blocking, and result is only available asynchronously.

Bada 2.x Quirks
---------------
- alert uses javascript alert


text:
/* Copyright (c) <2014> Author Vance King Saxbe. A, and contributors Power Dominion Enterprise, Precieux Consulting and other contributors. Modelled, Architected and designed by Vance King Saxbe. A. with the geeks from GoldSax Consulting and GoldSax Technologies email @vsaxbe@yahoo.com. Development teams from Power Dominion Enterprise, Precieux Consulting. Project sponsored by GoldSax Foundation, GoldSax Group and executed by GoldSax Manager.*/package com.goldsaxfoundation.bigdata.Module5;

import org.apache.avro.Schema;
import org.apache.avro.file.*;
import org.apache.avro.generic.*;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.io.FileUtils;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.*;
import org.apache.hadoop.io.IOUtils;

import java.io.*;
import java.nio.ByteBuffer;

public class SmallFilesWrite {

  public static final String FIELD_FILENAME = "filename";
  public static final String FIELD_CONTENTS = "contents";
  private static final String SCHEMA_JSON = //<co id="ch02_smallfilewrite_comment1"/>
          "{\"type\": \"record\", \"name\": \"SmallFilesTest\", "
          + "\"fields\": ["
          + "{\"name\":\"" + FIELD_FILENAME
          + "\", \"type\":\"string\"},"
          + "{\"name\":\"" + FIELD_CONTENTS
          + "\", \"type\":\"bytes\"}]}";
  public static final Schema SCHEMA = Schema.parse(SCHEMA_JSON);

  public static void writeToAvro(File srcPath,
          OutputStream outputStream)
          throws IOException {
    DataFileWriter<Object> writer =
            new DataFileWriter<Object>(
                new GenericDatumWriter<Object>())
                .setSyncInterval(100);                 //<co id="ch02_smallfilewrite_comment2"/>
    writer.setCodec(CodecFactory.snappyCodec());   //<co id="ch02_smallfilewrite_comment3"/>
    writer.create(SCHEMA, outputStream);           //<co id="ch02_smallfilewrite_comment4"/>
    for (Object obj : FileUtils.listFiles(srcPath, null, false)) {
      File file = (File) obj;
      String filename = file.getAbsolutePath();
      byte content[] = FileUtils.readFileToByteArray(file);
      GenericRecord record = new GenericData.Record(SCHEMA);  //<co id="ch02_smallfilewrite_comment5"/>
      record.put(FIELD_FILENAME, filename);                   //<co id="ch02_smallfilewrite_comment6"/>
      record.put(FIELD_CONTENTS, ByteBuffer.wrap(content));   //<co id="ch02_smallfilewrite_comment7"/>
      writer.append(record);                                  //<co id="ch02_smallfilewrite_comment8"/>
      System.out.println(
              file.getAbsolutePath()
              + ": "
              + DigestUtils.md5Hex(content));
    }

    IOUtils.cleanup(null, writer);
    IOUtils.cleanup(null, outputStream);
  }

  public static void main(String... args) throws Exception {
    Configuration config = new Configuration();
    FileSystem hdfs = FileSystem.get(config);

    File sourceDir = new File(args[0]);
    Path destFile = new Path(args[1]);

    OutputStream os = hdfs.create(destFile);
    writeToAvro(sourceDir, os);
  }
}
/*Packages, Programs, Algos for Mapreduce, Machine learning, ETL, as applicable in ERP & Financial domains. Modelled, Architected and designed by Vance King Saxbe. A. with the geeks from GoldSax Consulting, GoldSax Money, GoldSax Treasury, GoldSax Finance, GoldSax Banking and GoldSax Technologies email @vsaxbe@yahoo.com. Development teams from Power Dominion Enterprise, Precieux Consulting. Project sponsored by GoldSax Foundation, GoldSax Group and executed by GoldSax Manager.*//*email to provide support at vancekingsaxbe@powerdominionenterprise.com, businessaffairs@powerdominionenterprise.com, For donations please write to fundraising@powerdominionenterprise.com*/


text:
// Copyright 2008 Google Inc. All Rights Reserved.

package com.google.opengse.testlet.WebApp;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Using the absolution path (to the context) to load a static file, e.g. HTML.
 *
 * @author Wenbo Zhu
 */
public class StaticFileIncludeTestlet extends HttpServlet {

  @Override
  protected void service(HttpServletRequest request,
      HttpServletResponse response) throws ServletException, IOException {
    response.setContentType("text/plain");
    RequestDispatcher rd = getServletContext().getRequestDispatcher("/doc/jsp-include.txt");
    rd.include(request, response);
  }
}


text:
package org.ow2.proactive.process_tree_killer;

import java.util.Collection;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Util {

    /**
     * Pattern for capturing variables. Either $xyz, ${xyz} or ${a.b} but not $a.b, while ignoring "$$"
     */
    private static final Pattern VARIABLE = Pattern.compile("\\$([A-Za-z0-9_]+|\\{[A-Za-z0-9_.]+\\}|\\$)");

    /**
     * Concatenate multiple strings by inserting a separator.
     */
    public static String join(Collection<?> strings, String separator) {
        StringBuilder buf = new StringBuilder();
        boolean first = true;
        for (Object s : strings) {
            if (first)
                first = false;
            else
                buf.append(separator);
            buf.append(s);
        }
        return buf.toString();
    }

    /**
     * Replaces the occurrence of '$key' by <tt>properties.get('key')</tt>.
     *
     *

     * Unlike shell, undefined variables are left as-is (this behavior is the same as Ant.)
     *
     */

    public static String replaceMacro(String s, Map<String, String> properties) {
        return replaceMacro(s, new VariableResolver.ByMap<String>(properties));
    }

    /**
     * Replaces the occurrence of '$key' by <tt>resolver.get('key')</tt>.
     *
     *

     * Unlike shell, undefined variables are left as-is (this behavior is the same as Ant.)
     */
    public static String replaceMacro(String s, VariableResolver<String> resolver) {
        if (s == null) {
            return null;
        }

        int idx = 0;
        while (true) {
            Matcher m = VARIABLE.matcher(s);
            if (!m.find(idx))
                return s;

            String key = m.group().substring(1);

            // escape the dollar sign or get the key to resolve
            String value;
            if (key.charAt(0) == '$') {
                value = "$";
            } else {
                if (key.charAt(0) == '{')
                    key = key.substring(1, key.length() - 1);
                value = resolver.resolve(key);
            }

            if (value == null)
                idx = m.end(); // skip this
            else {
                s = s.substring(0, m.start()) + value + s.substring(m.end());
                idx = m.start() + value.length();
            }
        }
    }

}


text:
FILE(REMOVE_RECURSE
  "CMakeFiles/slab_cache.test.dir/slab_cache.c.o"
  "slab_cache.test.pdb"
  "slab_cache.test"
)

# Per-language clean rules from dependency scanning.
FOREACH(lang C)
  INCLUDE(CMakeFiles/slab_cache.test.dir/cmake_clean_${lang}.cmake OPTIONAL)
ENDFOREACH(lang)


text:
package ru.olamedia.postprocessing.blenders;

import ru.olamedia.postprocessing.BaseShaderBlender;

public class Subtract extends BaseShaderBlender {
	@Override
	public void init() {
		loadFragmentShader("subtract.fp");
	}
}


text:
/**
 * Created by doctor on 15-6-21.
 */

var names = new List();
names.append("doctor");
names.append("doctor who");

console.log(names.toString());
console.log(names.length());
console.log(names.listSize);
console.log(names.find("who"));
names.remove("doctor");
console.log(names.toString());

function List(){
    this.listSize = 0;
    this.pos = 0;
    this.dataStore = [];
    this.append = function(element){
        this.dataStore[this.listSize++] = element;
    };
    this.find = function(element){
        for(var i = 0 ; i < this.dataStore.length; ++i){
            if(this.dataStore[i] == element){
                return i;
            }
        }
        return -1;
    };

    this.remove = function(element){
        var foundAt = this.find(element);
        if(foundAt != -1){
            this.dataStore.splice(foundAt,1);
            --this.listSize;
            return true;
        }
        return false;
    };

    this.length = function(){
        return this.listSize;
    };
    this.toString = function(){
        return this.dataStore;
    };

    this.insert = function(element,after){
        var insertPos = this.find(after);
        if(insertPos != -1){
            this.dataStore.splice(insertPos+1,0,element);
            ++this.listSize;
            return true;
        }

        return false;
    };

    this.clear = function(){
        delete  this.dataStore;
        this.dataStore = [];
        this.listSize = this.pos = 0;
    }
}


text:
<?php

    /**
    * GoCardless WHMCS module redirect.php
    * This file confirms verifies a preauth and creates a bill underneath it
    * Either a one of payment (bill) or a pre authorisation can be handled by this file
    * @author WHMCS <info@whmcs.com>
    * @version 1.1.0
    */

    # load all required files
    $whmcsdir = dirname(__FILE__) . '/../../../';

    require_once $whmcsdir . 'dbconnect.php';
    require_once $whmcsdir . '/includes/functions.php';
    // Looking for WHMCS 5.2 compatability? Comment the above two lines with
    // "//" and then uncomment the line below:
    //
    // require_once $whmcsdir . 'init.php';

    require_once $whmcsdir . '/includes/gatewayfunctions.php';
    require_once $whmcsdir . '/includes/invoicefunctions.php';
    require_once $whmcsdir . '/modules/gateways/gocardless.php';

    # get gateway params
    $gateway = getGatewayVariables('gocardless');

    # sanity check to ensure module is active
    if (!$gateway['type']) die("Module Not Activated");

    # set relevant API information for GoCardless module
    gocardless_set_account_details($gateway);

    # if the resource ID and resouce type are set, confirm it using the GoCardless API
    if (isset($_GET['resource_id']) && isset($_GET['resource_type'])) {

        # if GoCardless fails to confirm the resource, an exception will be thrown
        # we will handle the exception gracefully
        try {
            $confirmed_resource = GoCardless::confirm_resource(array(
                    'resource_id'   => $_GET['resource_id'],
                    'resource_type' => $_GET['resource_type'],
                    'resource_uri'  => $_GET['resource_uri'],
                    'signature'     => $_GET['signature'],
                    'state'         => $_GET['state']
                ));
        } catch(Exception $e) {
            # failed to verify the resource with GoCardless. Log transaction and ouput error message to client
            logTransaction($gateway['paymentmethod'],'GoCardless Redirect Failed (Resource not verified) : ' .print_r($_GET,true) . 'Exception: ' . print_r($e,true),'Unsuccessful');
            header('HTTP/1.1 400 Bad Request');
            exit('Your request could not be completed');
        }

    } else {
        # failed to get resource ID and resource type, invalid request. Log transaction and ouput error message to client
        logTransaction($gateway['paymentmethod'],'GoCardless Redirect Failed (No data provided) : ' .print_r($_GET,true),'Unsuccessful');
        header('HTTP/1.1 400 Bad Request');
        exit('Your request could not be completed');
    }

    # split invoice data into invoiceID and invoiceAmount
    list($invoiceID) = explode(':', $_GET['state']);

    # check we have the invoiceID
    if($invoiceID) {
        # get the invoice amount and user ID by querying the invoice table
        $aResult = mysql_fetch_array(select_query('tblinvoices','userid,total',array('id' => $invoiceID)));
        $userID = $aResult['userid'];
        $invoiceAmount = $aResult['total'];

        # check this invoice exists (halt execution if it doesnt)
        checkCbInvoiceID($invoiceID, $gateway['paymentmethod']);

        # get user ID and gateway ID for use further down the script
        $gatewayID = mysql_result(select_query('tblclients', 'gatewayid', array('id' => $userID)),0,0);

        # if the user records gateway is blank, set it to gocardless
        if (empty($gatewayID)) {
            update_query('tblclients', array('gatewayid' => $gateway['paymentmethod']), array('id' => $userID));
        }

        # check if we are handling a preauth or a one time bill
        switch ($_GET['resource_type']) {

            case "pre_authorization":

            # get the confirmed resource (pre_auth) and created a referenced param $pre_auth
            $pre_auth = &$confirmed_resource;

            # check if we have a setup_fee
            $setup_id = false;
            $setup_amount = 0;
            if($pre_auth->setup_fee > 0) {
                # store the bill in $oSetupBill for later user
                $aoSetupBills = $pre_auth->bills();
                $oSetupBill = $aoSetupBills[0];
                $setup_id = $oSetupBill->id;
                $setup_amount = $oSetupBill->amount;
                unset($aoSetupBills);
            }

            # create a GoCardless bill and store it in $bill
            try {
                $amount_to_charge = $invoiceAmount - $setup_amount;
                $oBill = $pre_auth->create_bill(array(
                    'amount' => $amount_to_charge,
                    'name' => "Invoice #" . $invoiceID
                ));
            } catch (Exception $e) {
                # log that we havent been able to create the bill and exit out
                logTransaction($gateway['paymentmethod'],'Failed to create new bill: ' . print_r($e,true),'GoCardless Error');
                exit('Your request could not be completed');
            }

			try {
				# if we have been able to create the bill, the preauth ID being null suggests payment is pending
				# (this will display in the admin)
				if ($oBill->id) {
                    if($setup_id) {
                        # if we have a setup ID, we want to insert this into the query
                        if(!insert_query('mod_gocardless', array('invoiceid' => $invoiceID, 'billcreated' => 1, 'resource_id' => $oBill->id, 'setup_id' => $setup_id, 'preauth_id' => $pre_auth->id))) {
                            throw new Exception('Failed to record new mod_gocardless record for bill #'.$oBill->id);
                        }
                    } else {
                        # no setup ID bill
                        if(!insert_query('mod_gocardless', array('invoiceid' => $invoiceID, 'billcreated' => 1, 'resource_id' => $oBill->id, 'preauth_id' => $pre_auth->id))) {
                            throw new Exception('Failed to record new mod_gocardless record for bill #'.$oBill->id);
                        }
                    }
				} else {
					throw new Exception('Could not create GoCardless bill on Preauth #'.$pre_auth->id);
				}
			} catch (Exception $e) {
				logTransaction($gateway['paymentmethod'],$e->getMessage().'Exception Details: ' . print_r($e,true)."\r\nBill Details: " . print_r($oBill,true) . "\r\nInvoice #".$invoiceID);
				exit('Failed to record transaction, please contact support for more details.');
			}

            # query tblinvoiceitems to get the related service ID
            # update subscription ID with the resource ID on all hosting services corresponding with the invoice
            $d = select_query('tblinvoiceitems', 'relid', array('type' => 'Hosting', 'invoiceid' => $invoiceID));
            while ($res = mysql_fetch_assoc($d)) {
                update_query('tblhosting', array('subscriptionid' => $pre_auth->id), array('id' => $res['relid']));
            }

            # clean up
            unset($d,$res);
            break;

            case 'bill':
                # the response is a one time bill, we need to add the bill to the database
                $oBill = $confirmed_resource;
                insert_query('mod_gocardless', array('invoiceid' => $invoiceID, 'billcreated' => 1, 'resource_id' => $oBill->id));
                break;

            default:
                # we cannot handle anything other than a bill or preauths
                header('HTTP/1.1 400 Bad Request');
                exit('Your request could not be completed');
                break;
        }

        if($gateway['instantpaid'] == on) {
            # The "Instant Activation" option is enabled, so we need to mark now

            # convert currency where necessary (GoCardless only handles GBP)
            $aCurrency = getCurrency($res['userid']);
            if($gateway['convertto'] && ($aCurrency['id'] != $gateway['convertto'])) {
                # the users currency is not the same as the GoCardless currency, convert to the users currency
                $oBill->amount = convertCurrency($oBill->amount,$gateway['convertto'],$aCurrency['id']);
                $oBill->gocardless_fee = convertCurrency($oBill->gocardless_fee,$gateway['convertto'],$aCurrency['id']);

                # currency conversion on the setup fee bill
                if(isset($oSetupBill)) {
                    $oSetupBill->amount = convertCurrency($oBill->amount,$gateway['convertto'],$aCurrency['id']);
                    $oSetupBill->gocardless_fee = convertCurrency($oBill->gocardless_fee,$gateway['convertto'],$aCurrency['id']);

                }
            }

            # check if we are handling a preauth setup fee
            # if we are then we need to add it to the total bill
            if(isset($oSetupBill)) {
                addInvoicePayment($invoiceID, $oSetupBill->id, $oSetupBill->amount, $oSetupBill->gocardless_fees, $gateway['paymentmethod']);
                logTransaction($gateway['paymentmethod'], 'Setup fee of ' . $oSetupBill->amount . ' raised and logged for invoice ' . $invoiceID . ' with GoCardless ID ' . $oSetupBill->id, 'Successful');
            }

            # Log the payment for the amount of the main bill against the inovice
            addInvoicePayment($invoiceID, $oBill->id, $oBill->amount, $oBill->gocardless_fees, $gateway['paymentmethod']);
            logTransaction($gateway['paymentmethod'], 'Bill of ' . $oBill->amount . ' raised and logged for invoice ' . $invoiceID . ' with GoCardless ID ' . $oBill->id, 'Successful');
        } else {
            # Instant activation isn't enabled, so we will log in the Gateway Log but will not put anything on the invoice

            if(isset($oSetupBill)) {
                logTransaction($gateway['paymentmethod'], 'Setup fee bill ' . $oSetupBill->id . ' (' . $oSetupBill->amount . ') and bill ' . $oBill->id . ' (' . $oBill->amount . ') raised with GoCardless for invoice ' . $invoiceID . ', but not marked on invoice.', 'Pending');
            } else {
                logTransaction($gateway['paymentmethod'], 'Bill ' . $oBill->id . ' (' . $oBill->amount . ') raised with GoCardless for invoice ' . $invoiceID . ', but not marked on invoice.', 'Pending');
            }
        }

        # if we get to this point, we have verified everything we need to, redirect to invoice
        $systemURL = ($CONFIG['SystemSSLURL'] ? $CONFIG['SystemSSLURL'] : $CONFIG['SystemURL']);
        header('HTTP/1.1 303 See Other');
        header("Location: {$systemURL}/viewinvoice.php?id={$invoiceID}");
        exit();

    } else {
        # we could not get an invoiceID so cannot process this further
        header('HTTP/1.1 400 Bad Request');
        exit('Your request could not be completed');
}