text:
SmartAss Reference Guide
========

 * Literals

   SmartAss literals are mapped to their Java equivalent,
   you can also note that there is no primitive in SmartAss,
   everything is an Object

   ```
   null              // Void
   true              // Boolean
   false             // Boolean
   2                 // Integer
   3.14              // Double
   10000000000       // Long
   10000000000000000000000000000  // BigInteger
   "foo"             // String
   'foo              // a symbol (a Klass or a String depending on the context)
   [1, 2, 3]         // List
   { "a": "b" }      // Map
   ```

 * Block of code and semicolon

   A block of code is a suite of expressions.
   The value of a block of code is the value of the last expression.

   Expressions are either separated by a end of line or by a semicolon,
   so the two codes below are equivalent
   ```
   b = 3
   print(b)
   ```
   ```
   b = 3; print(b)
   ```

   To make the grammar regular, an end of line is always considered
   as a separator of expressions if the text before the end of line
   is a valid expression.

   By example, for
   ```
   2
   + 3
   ```
   the result value is 3 (the last expression of the block)
   and not 5 because for the end of line after '2', '2' is
   a valid expression.

   And for
   ```
   2 +
   3
   ```
   the result value is 5 because 2 + is not a valid expression.

 * Local variable and Symbols

   A local variable exists from the first time the variable is assigned
   to the last time the local variable is read.
   ```
   a = 2      // a is created
   b = a      // b is created then a is destroyed
   print(b)   // then b is destroyed
   ```

   If a local variable is read without being assigned,
   SmartAss will try to consider the name as a symbol i.e.
   a reference to a Klass.
   By example, the code below
   ```
   print(a)   // a is not a valid symbol or a local variable
   ```
   will produce an error at the execution.

   If there is a Klass in the context with the same name,
   the class will be used, by example
   ```
   alias('java.lang.Integer, 'Int)
   print(Int)  // Int is not a valid local variable but it's a Klass name
   ```

   In case of a call of a method, if the name is neither a local variable
   nor a Klass name, it will be considered as a String.
   By example, in
   ```
   result = sum(3, 4)
   ```
   sum is a String.

   If there is a local variable in the current scope,
   it will be preferred to a symbol, thus the following
   code will calculate 3 + 7
   ```
   sum = (a, b: a + b)   // defined an anonymous method with two parameters 'a' and 'b'
   result = sum(3, 7)
   ```

   So the rule is, if there is a name, check first if it's a local variable,
   then if it's a Klass and when it can be a method name, considere that
   this is a String.

 * Lambdas

   In SmartAss, everything is an expression, there is no declaration,
   so SmartAss use the mechanism of lambda to represent a delayed
   computation.

   By example, the following code represent an anonymous function
   (usually called a lambda) that prints its first argument
   ```
   p = \(x: print(x))
   p(hello)
   ```

   A lambda can also reference value of variable defined in the outer environment,
   so by example the local variable 'script' can be used inside the lambda body.
   ```
   script = this
   p = \(x: script.print(x))
   p("hello")
   ```
   The first line may be weird, a simple explanation is that 'this' represent
   the current script, if you want the whole explanation,
   see the section about object orientation below.

   A variable defined in the outer environment can *not* be changed inside the lambda,
   because the runtime copy the value of the variable when the lambda is created.
   By example
   ```
   x = 3
   l = \(: x = 4)
   print(x)  // prints 3
   ```

   By default, you can not define a function in SmartAss, by the default environment
   (core.sms) adds a way to define something close to a function
   ```
   require("samples/core.sms")   // load core.sms niceties

   def('bestValue:
     42
   )
   print(bestValue())    // print 42
   ```

   the call to def use a shortcut syntax for this call
   ```
   def('bestValue, \(:
     42
   ))
   ```
   so the interpreter will call 'def with the String 'destValue and a lambda
   that when called will return the value 42. 'def will associate the name
   'bestValue to the Function object corresponding to the lambda (: 42).

   At that point, you may think that SmartAss is a functional language,
   but it's not, SmartAss is a methodical language, all functions
   are in fact methods, i.e. are defined on a class, in our case,
   def which is a method of the class Script.

   so when writing the code above, the interpreter understands this code
   ```
   script.def('bestValue, \(:
     42
   ))
   script.print(script.bestValue())    // print 42
   ```

 * Object Oriented

   SmartAss is object oriented, so you can create a class, add methods
   to that class, create instances of that class, call methods on
   instance, obviously polymorphism works (also named virtual call
   or late binding) but there is no mechanism
   for doing inheritance or mixins by default
   (mostly because you can implement something like that yourself).

   A class is defined by using the method named 'class' defined
   inside the class Script. By example, the following code creates
   a class Book with two fields author and name,
   ```
   class('Book, {'author, 'title}:
     // code
   )
   ```

   A class is represented by an instance of the class named Klass,
   a call to that class allows to instantiate an object of that class
   ```
   b = Book("Dan Brown", "Da Vinci Code")
   ```

   A method is defined using the method 'def' defined in class Klass.
   Like in Ruby, the syntax to access to a fied inside a class is @field.
   By example, to get the author of a Book, one can write
   ```
   class('Book, {'author, 'title}:
     def('author: @author )
   )
   b = Book("Dan Brown", "Da Vinci Code")
   b.author()  // Dan Brown
   ```

   Like in Ruby, you can re-open any classes at your will,
   so the following code is valid
   ```
   class('Book, {'author, 'title}:
     def('author: @author )
   )
   class('Book:                // re-open the class Book
     def('str: @author.concat(" ").concat(@title))
   )
   ```
   But unlike in Ruby you can not add new fields when
   a class is re-opened (having the fields defined once
   forever allows to avoid to change the layout of all
   instances a runtime which is a performance hog
   because it requires a full GC).

   A Java class can be re-open too,
   by example, you can add a method '+' to java.lang.String
   ```
   class('java.lang.String:    // re-open the class String
     def('+ | other:
       this.concat(other)
     )
   )
   class('Book:                // re-open the class Book
     def('str2: @author + " " + @title)
   )
   ```

   In SmartAss, the class creation is in fact just a method call with a lambda.
   By example, the definition of the class Book
   ```
   class(`Book, {'author, 'title}:
   )
   ```
   can be re-written as a method call on the current script object
   with the symbol Book. The code above is just a shortcut for this code
   ```
   this.class('Book, {'author, 'title}, (:
   ))
   ```

   Inside the lambda body, it's possible to execute any expression, not only call
   'def. By example to print the name of 'this' ('this' being the newly created Klass).
   ```
   script = this
   class('Book, {'author, 'title}:
     def('author: @author )

     script.print(this.getName())
   )
   b = Book("Dan Brown", "Da Vinci Code")
   b.author()  // print Book (the name of the klass) and returns "Dan Brown"
   b.author()  // returns "Dan Brown"
   ```

   The evaluation of the initializer of a class, in fact the initializers
   because you can have more than one if you re-open a class,
   is not executed when the class is defined but the first time
   a method of the class is executed.
   This trick allows to defined a lot of classes but
   only pay for the ones used.

   SmartAss is methodical, not functional, so every call is a method call,
   even a call a lambda. By example this code
   ```
   script = this
   def('printIf | list, filter:
     list.stream().forEach(element:
       if(filter(element): print(element))
     )
   )
   printIf([0, 1, 2, 3, 4] | x: x % 3 == 0)
   ```
   can be rewritten to
   ```
   script = this
   def('printIf | list, filter:
     list.stream().forEach(element:
       if(element.filter(): print(element))
     )
   )
   printIf([0, 1, 2, 3, 4]: this % 3 == 0)
   ```
   Here, filter is called as a method call i.e. element.filter() and not
   filter(element), so the element is sent as 'this' inside the lambda,
   hence the code of the lambda is (:this % 3 == 0) and not
   (x: x % 3 == 0)

 * One expression to rule them all

   In SmartAss, almost everything is a method call or a shortcut to a method call.

   ```
   a + b
   ```
   is transformed to
   ```
   a.'+(b)
   ```

   ```
   foo(2, 3)
   ```
   is transformed to
   ```
   this.'foo(2, 3)
   ```

   ```
   star = (text: '*' + text + '*')
   star(text)
   ```
   is transformed to
   ```
   star = (text: '*' + text + '*')
   this.'star(text)
   ```

 * if, while, return and throw

   As a concession to practicality, SmartAss provide these 4 constructs
   that you will find in most imperative languages.
   Using them is obviously not require.

   There are two forms of if, the if with 2 branches,
   ```
   a = if(b == 3: 4: 7)
   ```
   and the if with only one branch that will be evaluated only
   if the condition is true, otherwise the result will be null.
   ```
   a = 7
   if(b == 3:
     a = 3
   )
   ```

   The condition (here b == 3) can be any expression, evaluated to null, false
   or 0 it will be considered as false, any other values will be considered as true.

   The syntax of while loop is similar to the if syntax
   ```
   i = 0
   while(i < 10:
     print(i)
     i = i + 1
   )
   ```
   and like if a while loop returns a value
   ```
   a = while(b == 3: b = 3)
   ```
   In the example above, if b = 0 before calling the code, the value
   of a is 3, if b = 3 then the value of a is null.

   While the syntax of 'if' (or 'while') and a method call is
   very similar, the blocks defined inside an 'if' or a 'while' are
   not lambda thus share the same environment.
   So a block inside an 'if' can modify the variables declared
   before the 'if'.

   'throw' and 'return' can be used to stop the control flow,
   ```
   if(a == 3:
     return 2
   )
   ```
   or
   ```
   if(a == 3:
     throw 2
   )
   ```

   'return' must be followed by an expression and 'throw' is able to throw
   any value indicating an unrecoverable error (there is no way to catch
   an exception in SmartAss).

 * Java interoperability

   TODO


text:
class MovableGraphicsPixmapItem : public QObject, public QGraphicsPixmapItem
{
   Q_OBJECT
   Q_PROPERTY(QPointF pos READ pos WRITE setPos)

public:
  QTimeLine *timeline;
  MovableGraphicsPixmapItem( const QPixmap& pixmap,QGraphicsItem* parent = 0)
   : QObject(), QGraphicsPixmapItem(pixmap){
  timeline = new QTimeLine(200,this);
  }

private slots:
};

redpajama_set_name: RedPajamaGithub


text:
package org.assertj.core.error;

/**
 * Creates an error message indicating that an assertion that verifies that a {@link Throwable} have a cause instance of
 * a certain type.
 *
 * @author Jean-Christophe Gay
 */
public class ShouldHaveCauseInstance extends BasicErrorMessageFactory {

  /**
   * Creates a new </code>{@link org.assertj.core.error.BasicErrorMessageFactory}</code>.
   *
   * @param actual the actual value in the failed assertion.
   * @param expectedCauseType the expected cause type.
   * @return the created {@code ErrorMessageFactory}.
   */
  public static ErrorMessageFactory shouldHaveCauseInstance(Throwable actual,
      Class<? extends Throwable> expectedCauseType) {
    return actual.getCause() == null ? new ShouldHaveCauseInstance(expectedCauseType) : new ShouldHaveCauseInstance(
        actual, expectedCauseType);
  }

  private ShouldHaveCauseInstance(Throwable actual, Class<? extends Throwable> expectedCauseType) {
    super("%nExpecting a throwable with cause being an instance of:%n <%s>%nbut was an instance of:%n <%s>",
        expectedCauseType, actual.getCause());
  }

  private ShouldHaveCauseInstance(Class<? extends Throwable> expectedCauseType) {
    super("%nExpecting a throwable with cause being an instance of:%n <%s>%nbut current throwable has no cause.",
        expectedCauseType);
  }
}


text:
<ion-modal-view>
    <ion-header-bar ng-class="mainClass.bar">

{{labels.languages}}

    </ion-header-bar>
    <ion-content>
        <ion-list>
            <ion-radio ng-model="$parent.$parent.language" value="english">
                {{labels.english}}
            </ion-radio>
            <ion-radio ng-model="$parent.$parent.language" value="spanish">
                {{labels.spanish}}
            </ion-radio>
        </ion-list>
    </ion-content>

        <button class="button ng-class:mainClass.button" ng-click="changeLanguage(language)">{{labels.select}}</button>
        <button class="button ng-class:mainClass.button" ng-click="closeOptModal()">{{labels.cancel}}</button>

</ion-modal-view>


text:
function Find-AVSignature
{
<#
.SYNOPSIS

Locate tiny AV signatures.

PowerSploit Function: Find-AVSignature
Authors: Chris Campbell (@obscuresec) & Matt Graeber (@mattifestation)
License: BSD 3-Clause
Required Dependencies: None
Optional Dependencies: None

.DESCRIPTION

Locates single Byte AV signatures utilizing the same method as DSplit from "class101" on heapoverflow.com.

.PARAMETER Startbyte

Specifies the first byte to begin splitting on.

.PARAMETER Endbyte

Specifies the last byte to split on.

.PARAMETER Interval

Specifies the interval size to split with.

.PARAMETER Path

Specifies the path to the binary you want tested.

.PARAMETER OutPath

Optionally specifies the directory to write the binaries to.

.PARAMETER BufferLen

Specifies the length of the file read buffer .  Defaults to 64KB.

.PARAMETER Force

Forces the script to continue without confirmation.

.EXAMPLE

Find-AVSignature -Startbyte 0 -Endbyte max -Interval 10000 -Path c:\test\exempt\nc.exe
Find-AVSignature -StartByte 10000 -EndByte 20000 -Interval 1000 -Path C:\test\exempt\nc.exe -OutPath c:\test\output\run2 -Verbose
Find-AVSignature -StartByte 16000 -EndByte 17000 -Interval 100 -Path C:\test\exempt\nc.exe -OutPath c:\test\output\run3 -Verbose
Find-AVSignature -StartByte 16800 -EndByte 16900 -Interval 10 -Path C:\test\exempt\nc.exe -OutPath c:\test\output\run4 -Verbose
Find-AVSignature -StartByte 16890 -EndByte 16900 -Interval 1 -Path C:\test\exempt\nc.exe -OutPath c:\test\output\run5 -Verbose

.NOTES

Several of the versions of "DSplit.exe" available on the internet contain malware.

.LINK

http://obscuresecurity.blogspot.com/2012/12/finding-simple-av-signatures-with.html
https://github.com/mattifestation/PowerSploit
http://www.exploit-monday.com/
http://heapoverflow.com/f0rums/project.php?issueid=34&filter=changes&page=2
#>

    [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSShouldProcess', '')]
    [CmdletBinding()]
    Param(
        [Parameter(Mandatory = $True)]
        [ValidateRange(0,4294967295)]
        [UInt32]
        $StartByte,

        [Parameter(Mandatory = $True)]
        [String]
        $EndByte,

        [Parameter(Mandatory = $True)]
        [ValidateRange(0,4294967295)]
        [UInt32]
        $Interval,

        [String]
        [ValidateScript({Test-Path $_ })]
        $Path = ($pwd.path),

        [String]
        $OutPath = ($pwd),

        [ValidateRange(1,2097152)]
        [UInt32]
        $BufferLen = 65536,

        [Switch] $Force
    )

    #test variables
    if (!(Test-Path $Path)) {Throw "File path not found"}
    $Response = $True
    if (!(Test-Path $OutPath)) {
        if ($Force -or ($Response = $psCmdlet.ShouldContinue("The `"$OutPath`" does not exist! Do you want to create the directory?",""))){new-item ($OutPath)-type directory}
    }
    if (!$Response) {Throw "Output path not found"}
    if (!(Get-ChildItem $Path).Exists) {Throw "File not found"}
    [Int32] $FileSize = (Get-ChildItem $Path).Length
    if ($StartByte -gt ($FileSize - 1) -or $StartByte -lt 0) {Throw "StartByte range must be between 0 and $Filesize"}
    [Int32] $MaximumByte = (($FileSize) - 1)
    if ($EndByte -ceq "max") {$EndByte = $MaximumByte}

    #Recast $Endbyte into an Integer so that it can be compared properly.
    [Int32]$EndByte = $EndByte

    #If $Endbyte is greater than the file Length, use $MaximumByte.
    if ($EndByte -gt $FileSize) {$EndByte = $MaximumByte}

    #If $Endbyte is less than the $StartByte, use 1 Interval past $StartByte.
    if ($EndByte -lt $StartByte) {$EndByte = $StartByte + $Interval}

    Write-Verbose "StartByte: $StartByte"
    Write-Verbose "EndByte: $EndByte"

    #find the filename for the output name
    [String] $FileName = (Split-Path $Path -leaf).Split('.')[0]

    #Calculate the number of binaries
    [Int32] $ResultNumber = [Math]::Floor(($EndByte - $StartByte) / $Interval)
    if (((($EndByte - $StartByte) % $Interval)) -gt 0) {$ResultNumber = ($ResultNumber + 1)}

    #Prompt user to verify parameters to avoid writing binaries to the wrong directory
    $Response = $True
    if ( $Force -or ( $Response = $psCmdlet.ShouldContinue("This script will result in $ResultNumber binaries being written to `"$OutPath`"!",
             "Do you want to continue?"))){}
    if (!$Response) {Return}

    Write-Verbose "This script will now write $ResultNumber binaries to `"$OutPath`"."
    [Int32] $Number = [Math]::Floor($Endbyte/$Interval)

    #Create a Read Buffer and Stream.
    #Note: The Filestream class takes advantage of internal .NET Buffering.  We set the default internal buffer to 64KB per http://research.microsoft.com/pubs/64538/tr-2004-136.doc.
    [Byte[]] $ReadBuffer=New-Object byte[] $BufferLen
    [System.IO.FileStream] $ReadStream = New-Object System.IO.FileStream($Path, [System.IO.FileMode]::Open, [System.IO.FileAccess]::Read, [System.IO.FileShare]::Read, $BufferLen)

    #write out the calculated number of binaries
    [Int32] $i = 0
    for ($i -eq 0; $i -lt $ResultNumber + 1 ; $i++)
    {
        # If this is the Final Binary, use $EndBytes, Otherwise calculate based on the Interval
        if ($i -eq $ResultNumber) {[Int32]$SplitByte = $EndByte}
        else {[Int32] $SplitByte = (($StartByte) + (($Interval) * ($i)))}

        Write-Verbose "Byte 0 -> $($SplitByte)"

        #Reset ReadStream to beginning of file
        $ReadStream.Seek(0, [System.IO.SeekOrigin]::Begin) | Out-Null

        #Build a new FileStream for Writing
        [String] $outfile = Join-Path $OutPath "$($FileName)_$($SplitByte).bin"
        [System.IO.FileStream] $WriteStream = New-Object System.IO.FileStream($outfile, [System.IO.FileMode]::Create, [System.IO.FileAccess]::Write, [System.IO.FileShare]::None, $BufferLen)

        [Int32] $BytesLeft = $SplitByte
        Write-Verbose "$($WriteStream.name)"

        #Write Buffer Length to the Writing Stream until the bytes left is smaller than the buffer
        while ($BytesLeft -gt $BufferLen){
            [Int32]$count = $ReadStream.Read($ReadBuffer, 0, $BufferLen)
            $WriteStream.Write($ReadBuffer, 0, $count)
            $BytesLeft = $BytesLeft - $count
        }

        #Write the remaining bytes to the file
        do {
            [Int32]$count = $ReadStream.Read($ReadBuffer, 0, $BytesLeft)
            $WriteStream.Write($ReadBuffer, 0, $count)
            $BytesLeft = $BytesLeft - $count
        }
        until ($BytesLeft -eq 0)
        $WriteStream.Close()
        $WriteStream.Dispose()
    }
    Write-Verbose "Files written to disk. Flushing memory."
    $ReadStream.Dispose()

    #During testing using large binaries, memory usage was excessive so lets fix that
    [System.GC]::Collect()
    Write-Verbose "Completed!"
}


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

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>ConnectionRecordSet (guacamole-ext 1.0.0 API)</title>
<meta name="date" content="2018-12-21">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

org.apache.guacamole.net.auth

Interface ConnectionRecordSet

All Superinterfaces:

ActivityRecordSet<ConnectionRecord>

All Known Implementing Classes:

SimpleConnectionRecordSet

Deprecated.

Use ActivityRecordSet<ConnectionRecord> instead.

@Deprecated
public interface ConnectionRecordSet
extends ActivityRecordSet<ConnectionRecord>

The set of all available connection records, or a subset of those records.

Nested Class Summary

Nested classes/interfaces inherited from interface org.apache.guacamole.net.auth.ActivityRecordSet

ActivityRecordSet.SortableProperty

Method Summary

Methods inherited from interface org.apache.guacamole.net.auth.ActivityRecordSet

asCollection, contains, limit, sort

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

Copyright © 2018. All rights reserved.


text:
<?php
# Generated by the protocol buffer compiler.  DO NOT EDIT!
# source: google/cloud/bigquery/migration/v2/translation_config.proto

namespace Google\Cloud\BigQuery\Migration\V2;

use Google\Protobuf\Internal\GPBType;
use Google\Protobuf\Internal\RepeatedField;
use Google\Protobuf\Internal\GPBUtil;

/**
 * Represents the default source environment values for the translation.
 *
 * Generated from protobuf message google.cloud.bigquery.migration.v2.SourceEnv
 */
class SourceEnv extends \Google\Protobuf\Internal\Message
{
    /**
     * The default database name to fully qualify SQL objects when their database
     * name is missing.
     *
     * Generated from protobuf field string default_database = 1;
     */
    private $default_database = '';
    /**
     * The schema search path. When SQL objects are missing schema name,
     * translation engine will search through this list to find the value.
     *
     * Generated from protobuf field repeated string schema_search_path = 2;
     */
    private $schema_search_path;

    /**
     * Constructor.
     *
     * @param array $data {
     *     Optional. Data for populating the Message object.
     *
     *     @type string $default_database
     *           The default database name to fully qualify SQL objects when their database
     *           name is missing.
     *     @type array<string>|\Google\Protobuf\Internal\RepeatedField $schema_search_path
     *           The schema search path. When SQL objects are missing schema name,
     *           translation engine will search through this list to find the value.
     * }
     */
    public function __construct($data = NULL) {
        \GPBMetadata\Google\Cloud\Bigquery\Migration\V2\TranslationConfig::initOnce();
        parent::__construct($data);
    }

    /**
     * The default database name to fully qualify SQL objects when their database
     * name is missing.
     *
     * Generated from protobuf field string default_database = 1;
     * @return string
     */
    public function getDefaultDatabase()
    {
        return $this->default_database;
    }

    /**
     * The default database name to fully qualify SQL objects when their database
     * name is missing.
     *
     * Generated from protobuf field string default_database = 1;
     * @param string $var
     * @return $this
     */
    public function setDefaultDatabase($var)
    {
        GPBUtil::checkString($var, True);
        $this->default_database = $var;

        return $this;
    }

    /**
     * The schema search path. When SQL objects are missing schema name,
     * translation engine will search through this list to find the value.
     *
     * Generated from protobuf field repeated string schema_search_path = 2;
     * @return \Google\Protobuf\Internal\RepeatedField
     */
    public function getSchemaSearchPath()
    {
        return $this->schema_search_path;
    }

    /**
     * The schema search path. When SQL objects are missing schema name,
     * translation engine will search through this list to find the value.
     *
     * Generated from protobuf field repeated string schema_search_path = 2;
     * @param array<string>|\Google\Protobuf\Internal\RepeatedField $var
     * @return $this
     */
    public function setSchemaSearchPath($var)
    {
        $arr = GPBUtil::checkRepeatedField($var, \Google\Protobuf\Internal\GPBType::STRING);
        $this->schema_search_path = $arr;

        return $this;
    }

}


text:
package org.wildfly.extension.camel.deployment;

import org.jboss.as.server.deployment.DeploymentPhaseContext;
import org.jboss.as.server.deployment.DeploymentUnit;
import org.jboss.as.server.deployment.DeploymentUnitProcessingException;
import org.jboss.as.server.deployment.DeploymentUnitProcessor;

/**
 * Unattaches the {@link CamelDeploymentSettings.Builder} set by {@link CamelDeploymentSettingsBuilderProcessor}, builds
 * and attaches a new {@link CamelDeploymentSettings} using it.
 *
 * @author Peter Palaga
 */
public final class CamelDeploymentSettingsProcessor implements DeploymentUnitProcessor {

    public void deploy(DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException {

        final DeploymentUnit depUnit = phaseContext.getDeploymentUnit();

        CamelDeploymentSettings.Builder depSettingsBuilder = depUnit
                .removeAttachment(CamelDeploymentSettings.BUILDER_ATTACHMENT_KEY);
        if (depSettingsBuilder != null && depUnit.getParent() == null) {
            /*
             * We do this only for parentless deployments because for ones that have a parent the build and attachment
             * is done by CamelDeploymentSettings.Builder.build() if the parent
             */
            final CamelDeploymentSettings depSettings = depSettingsBuilder.build();
            depUnit.putAttachment(CamelDeploymentSettings.ATTACHMENT_KEY, depSettings);
        }

    }

    public void undeploy(final DeploymentUnit depUnit) {
        CamelDeploymentSettings.remove(CamelDeploymentSettingsBuilderProcessor.getDeploymentName(depUnit));
    }

}


text:
package com.littleinc.orm_benchmark.sqlite;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteStatement;
import android.util.Log;
import com.littleinc.orm_benchmark.BenchmarkExecutable;
import com.littleinc.orm_benchmark.util.Util;

import java.sql.SQLException;
import java.util.LinkedList;
import java.util.List;

import static com.littleinc.orm_benchmark.util.Util.getRandomString;

public enum SQLiteExecutorFast implements BenchmarkExecutable {

    INSTANCE;

    private DataBaseHelper mHelper;

    @Override
    public int getProfilerId() {
        return 1;
    }

    @Override
    public String getOrmName() {
        return "RAWFAST";
    }

    @Override
    public void init(Context context, boolean useInMemoryDb) {
        mHelper = new DataBaseHelper(context, useInMemoryDb, "fast");
    }

    @Override
    public long createDbStructure() throws SQLException {
        long start = System.nanoTime();
        User.createTable(mHelper);
        Message.createTable(mHelper);
        return System.nanoTime() - start;
    }

    @Override
    public long writeWholeData() throws SQLException {
        List<User> users = new LinkedList<User>();
        for (int i = 0; i < NUM_USER_INSERTS; i++) {
            User newUser = new User();
            newUser.setLastName(getRandomString(10));
            newUser.setFirstName(getRandomString(10));

            users.add(newUser);
        }

        List<Message> messages = new LinkedList<Message>();
        for (int i = 0; i < NUM_MESSAGE_INSERTS; i++) {
            Message newMessage = new Message();
            newMessage.setCommandId(i);
            newMessage.setSortedBy(System.nanoTime());
            newMessage.setContent(Util.getRandomString(100));
            newMessage.setClientId(System.currentTimeMillis());
            newMessage
                    .setSenderId(Math.round(Math.random() * NUM_USER_INSERTS));
            newMessage
                    .setChannelId(Math.round(Math.random() * NUM_USER_INSERTS));
            newMessage.setCreatedAt((int) (System.currentTimeMillis() / 1000L));

            messages.add(newMessage);
        }

        long start = System.nanoTime();
        SQLiteDatabase db = mHelper.getWritableDatabase();

        try {
            db.beginTransaction();

            ContentValues userCv = new ContentValues();
            for (User user : users) {
                user.prepareForInsert(userCv);
                db.insert(User.TABLE_NAME, null, userCv);
            }
            Log.d(SQLiteExecutorFast.class.getSimpleName(), "Done, wrote "
                    + NUM_USER_INSERTS + " users");

//            insertMessagesContentValues(messages, db);

            insertMessagesCompiled(messages, db);

            Log.d(SQLiteExecutorFast.class.getSimpleName(), "Done, wrote "
                    + NUM_MESSAGE_INSERTS + " messages");
            db.setTransactionSuccessful();
        } finally {
            db.endTransaction();
        }
        return System.nanoTime() - start;
    }

    private void insertMessagesContentValues(List<Message> messages, SQLiteDatabase db)
    {
        ContentValues messageCv = new ContentValues();
        for (Message message : messages) {
            message.prepareForInsert(messageCv);
            db.insert(Message.TABLE_NAME, null, messageCv);
        }
    }

    private void insertMessagesCompiled(List<Message> messages, SQLiteDatabase db)
    {
        SQLiteStatement sqlStatement = createSqlStatement(db);
        for (Message message : messages)
        {
            bindValues(sqlStatement, message);
            sqlStatement.execute();
        }
    }

    protected SQLiteStatement createSqlStatement(SQLiteDatabase db)
    {
        String sql = "INSERT INTO message(_id, client_id, sorted_by, created_at, content, sender_id, channel_id, command_id) values " +
                "(?, ?, ?, ?, ?, ?, ?, ?)";

        return db.compileStatement(sql);
    }

    protected void bindValues(SQLiteStatement stmt, Message entity) {
            stmt.clearBindings();

//            Long id = entity.getId();
//            if (id != null) {
//                stmt.bindLong(1, id);
//            }

            String content = entity.getContent();
            if (content != null) {
                stmt.bindString(2, content);
            }

            Long client_id = entity.getClientId();
            if (client_id != null) {
                stmt.bindLong(3, client_id);
            }

            Integer created_at = entity.getCreatedAt();
            if (created_at != null) {
                stmt.bindLong(4, created_at);
            }

            Double sorted_by = entity.getSortedBy();
            if (sorted_by != null) {
                stmt.bindDouble(5, sorted_by);
            }

            Long command_id = entity.getCommandId();
            if (command_id != null) {
                stmt.bindLong(6, command_id);
            }
            stmt.bindLong(7, entity.getSenderId());
            stmt.bindLong(8, entity.getChannelId());
        }

    @Override
    public long readWholeData() throws SQLException {
        long start = System.nanoTime();
        Cursor c = null;
        try {
            SQLiteDatabase db = mHelper.getReadableDatabase();
            List<Message> messages = new LinkedList<Message>();
            c = db.query(Message.TABLE_NAME, Message.PROJECTION, null, null,
                    null, null, null);

            while (c != null && c.moveToNext()) {
                Message newMessage = new Message();
                newMessage.setChannelId(c.getLong(c
                        .getColumnIndex(Message.CHANNEL_ID)));
                newMessage.setClientId(c.getLong(c
                        .getColumnIndex(Message.CLIENT_ID)));
                newMessage.setCommandId(c.getLong(c
                        .getColumnIndex(Message.COMMAND_ID)));
                newMessage.setContent(c.getString(c
                        .getColumnIndex(Message.CONTENT)));
                newMessage.setCreatedAt(c.getInt(c
                        .getColumnIndex(Message.CREATED_AT)));
                newMessage.setSenderId(c.getLong(c
                        .getColumnIndex(Message.SENDER_ID)));
                newMessage.setSortedBy(c.getDouble(c
                        .getColumnIndex(Message.SORTED_BY)));

                messages.add(newMessage);
            }
            Log.d(SQLiteExecutorFast.class.getSimpleName(),
                    "Read, " + messages.size() + " rows");
        } finally {
            if (c != null) {
                c.close();
            }
        }
        return System.nanoTime() - start;
    }

    @Override
    public long readIndexedField() throws SQLException {
        long start = System.nanoTime();
        Cursor c = null;
        try {
            SQLiteDatabase db = mHelper.getReadableDatabase();
            String selection = Message.COMMAND_ID + "=?";
            String[] selectionArgs = new String[] { String
                    .valueOf(LOOK_BY_INDEXED_FIELD) };
            c = db.query(Message.TABLE_NAME, Message.PROJECTION, selection,
                    selectionArgs, null, null, null);

            if (c != null && c.moveToFirst()) {
                Message newMessage = new Message();
                newMessage.setChannelId(c.getLong(c
                        .getColumnIndex(Message.CHANNEL_ID)));
                newMessage.setClientId(c.getLong(c
                        .getColumnIndex(Message.CLIENT_ID)));
                newMessage.setCommandId(c.getLong(c
                        .getColumnIndex(Message.COMMAND_ID)));
                newMessage.setContent(c.getString(c
                        .getColumnIndex(Message.CONTENT)));
                newMessage.setCreatedAt(c.getInt(c
                        .getColumnIndex(Message.CREATED_AT)));
                newMessage.setSenderId(c.getLong(c
                        .getColumnIndex(Message.SENDER_ID)));
                newMessage.setSortedBy(c.getDouble(c
                        .getColumnIndex(Message.SORTED_BY)));

                Log.d(SQLiteExecutorFast.class.getSimpleName(),
                        "Read, " + c.getCount() + " rows");
            }
        } finally {
            if (c != null) {
                c.close();
            }
        }
        return System.nanoTime() - start;
    }

    @Override
    public long readSearch() throws SQLException {
        long start = System.nanoTime();
        Cursor c = null;
        try {
            SQLiteDatabase db = mHelper.getReadableDatabase();
            String selection = Message.CONTENT + " LIKE ?";
            List<Message> messages = new LinkedList<Message>();
            String[] selectionArgs = new String[] { '%' + SEARCH_TERM + '%' };
            c = db.query(Message.TABLE_NAME, Message.PROJECTION, selection,
                    selectionArgs, null, null, null,
                    String.valueOf(SEARCH_LIMIT));

            while (c != null && c.moveToNext()) {
                Message newMessage = new Message();
                newMessage.setChannelId(c.getLong(c
                        .getColumnIndex(Message.CHANNEL_ID)));
                newMessage.setClientId(c.getLong(c
                        .getColumnIndex(Message.CLIENT_ID)));
                newMessage.setCommandId(c.getLong(c
                        .getColumnIndex(Message.COMMAND_ID)));
                newMessage.setContent(c.getString(c
                        .getColumnIndex(Message.CONTENT)));
                newMessage.setCreatedAt(c.getInt(c
                        .getColumnIndex(Message.CREATED_AT)));
                newMessage.setSenderId(c.getLong(c
                        .getColumnIndex(Message.SENDER_ID)));
                newMessage.setSortedBy(c.getDouble(c
                        .getColumnIndex(Message.SORTED_BY)));

                messages.add(newMessage);
            }
            Log.d(SQLiteExecutorFast.class.getSimpleName(),
                    "Read, " + messages.size() + " rows");
        } finally {
            if (c != null) {
                c.close();
            }
        }
        return System.nanoTime() - start;
    }

    @Override
    public long dropDb() throws SQLException {
        long start = System.nanoTime();
        User.dropTable(mHelper);
        Message.dropTable(mHelper);
        return System.nanoTime() - start;
    }
}


text:
package libpod

import (
	"context"
	"fmt"
	"os"
	"path/filepath"

	"github.com/containers/podman/v3/libpod/define"
	"github.com/containers/podman/v3/pkg/rootless"
	"github.com/containers/podman/v3/pkg/util"
	"github.com/containers/storage"
	"github.com/pkg/errors"
	"github.com/sirupsen/logrus"
)

// Reset removes all storage
func (r *Runtime) Reset(ctx context.Context) error {
	pods, err := r.GetAllPods()
	if err != nil {
		return err
	}
	for _, p := range pods {
		if err := r.RemovePod(ctx, p, true, true); err != nil {
			if errors.Cause(err) == define.ErrNoSuchPod {
				continue
			}
			logrus.Errorf("Error removing Pod %s: %v", p.ID(), err)
		}
	}

	ctrs, err := r.GetAllContainers()
	if err != nil {
		return err
	}

	for _, c := range ctrs {
		if err := r.RemoveContainer(ctx, c, true, true); err != nil {
			if err := r.RemoveStorageContainer(c.ID(), true); err != nil {
				if errors.Cause(err) == define.ErrNoSuchCtr {
					continue
				}
				logrus.Errorf("Error removing container %s: %v", c.ID(), err)
			}
		}
	}

	if err := r.stopPauseProcess(); err != nil {
		logrus.Errorf("Error stopping pause process: %v", err)
	}

	ir := r.ImageRuntime()
	images, err := ir.GetImages()
	if err != nil {
		return err
	}

	for _, i := range images {
		if err := i.Remove(ctx, true); err != nil {
			if errors.Cause(err) == define.ErrNoSuchImage {
				continue
			}
			logrus.Errorf("Error removing image %s: %v", i.ID(), err)
		}
	}
	volumes, err := r.state.AllVolumes()
	if err != nil {
		return err
	}
	for _, v := range volumes {
		if err := r.RemoveVolume(ctx, v, true); err != nil {
			if errors.Cause(err) == define.ErrNoSuchVolume {
				continue
			}
			logrus.Errorf("Error removing volume %s: %v", v.config.Name, err)
		}
	}

	xdgRuntimeDir := filepath.Clean(os.Getenv("XDG_RUNTIME_DIR"))
	_, prevError := r.store.Shutdown(true)
	graphRoot := filepath.Clean(r.store.GraphRoot())
	if graphRoot == xdgRuntimeDir {
		if prevError != nil {
			logrus.Error(prevError)
		}
		prevError = errors.Errorf("failed to remove runtime graph root dir %s, since it is the same as XDG_RUNTIME_DIR", graphRoot)
	} else {
		if err := os.RemoveAll(graphRoot); err != nil {
			if prevError != nil {
				logrus.Error(prevError)
			}
			prevError = err
		}
	}
	runRoot := filepath.Clean(r.store.RunRoot())
	if runRoot == xdgRuntimeDir {
		if prevError != nil {
			logrus.Error(prevError)
		}
		prevError = errors.Errorf("failed to remove runtime root dir %s, since it is the same as XDG_RUNTIME_DIR", runRoot)
	} else {
		if err := os.RemoveAll(runRoot); err != nil {
			if prevError != nil {
				logrus.Error(prevError)
			}
			prevError = err
		}
	}
	runtimeDir, err := util.GetRuntimeDir()
	if err != nil {
		return err
	}
	tempDir := r.config.Engine.TmpDir
	if tempDir == runtimeDir {
		tempDir = filepath.Join(tempDir, "containers")
	}
	if filepath.Clean(tempDir) == xdgRuntimeDir {
		if prevError != nil {
			logrus.Error(prevError)
		}
		prevError = errors.Errorf("failed to remove runtime tmpdir %s, since it is the same as XDG_RUNTIME_DIR", tempDir)
	} else {
		if err := os.RemoveAll(tempDir); err != nil {
			if prevError != nil {
				logrus.Error(prevError)
			}
			prevError = err
		}
	}
	if storageConfPath, err := storage.DefaultConfigFile(rootless.IsRootless()); err == nil {
		if _, err = os.Stat(storageConfPath); err == nil {
			fmt.Printf("A storage.conf file exists at %s\n", storageConfPath)
			fmt.Println("You should remove this file if you did not modified the configuration.")
		}
	} else {
		if prevError != nil {
			logrus.Error(prevError)
		}
		prevError = err
	}

	return prevError
}


text:
package org.cboard.controller;

import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Charsets;
import com.google.common.base.Functions;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.hash.Hashing;
import org.apache.commons.io.IOUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.cboard.dao.*;
import org.cboard.dataprovider.DataProviderManager;
import org.cboard.dataprovider.DataProviderViewManager;
import org.cboard.dataprovider.config.AggConfig;
import org.cboard.dataprovider.result.AggregateResult;
import org.cboard.dto.*;
import org.cboard.pojo.*;
import org.cboard.services.*;
import org.cboard.services.job.JobService;
import org.cboard.services.persist.excel.XlsProcessService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * Created by yfyuan on 2016/8/9.
 */
@RestController
@RequestMapping("/dashboard")
public class DashboardController extends BaseController {

    @Autowired
    private BoardDao boardDao;

    @Autowired
    private DatasourceDao datasourceDao;

    @Autowired
    private DataProviderService dataProviderService;

    @Autowired
    private DatasourceService datasourceService;

    @Autowired
    private WidgetService widgetService;

    @Autowired
    private WidgetDao widgetDao;

    @Autowired
    private BoardService boardService;

    @Autowired
    private CategoryDao categoryDao;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private DatasetDao datasetDao;

    @Autowired
    private DatasetService datasetService;

    @Autowired
    private JobService jobService;

    @Autowired
    private JobDao jobDao;

    @Autowired
    private XlsProcessService xlsProcessService;

    @RequestMapping(value = "/test")
    public ServiceStatus test(@RequestParam(name = "datasource", required = false) String datasource, @RequestParam(name = "query", required = false) String query) {
        JSONObject queryO = JSONObject.parseObject(query);
        JSONObject datasourceO = JSONObject.parseObject(datasource);
        return dataProviderService.test(datasourceO, Maps.transformValues(queryO, Functions.toStringFunction()));
    }

    @RequestMapping(value = "/getDatasourceList")
    public List<ViewDashboardDatasource> getDatasourceList() {
        return datasourceService.getViewDatasourceList(() -> datasourceDao.getDatasourceList(tlUser.get().getUserId()));
    }

    @RequestMapping(value = "/getProviderList")
    public Set<String> getProviderList() {
        return DataProviderManager.getProviderList();
    }

    @RequestMapping(value = "/getConfigParams")
    public List<Map<String, Object>> getConfigParams(@RequestParam(name = "type") String type,
                                                     @RequestParam(name = "page") String page,
                                                     @RequestParam(name = "datasourceId", required = false) Long datasourceId) {
        Map<String, String> dataSource = null;
        if (datasourceId != null) {
            dataSource = dataProviderService.getDataSource(datasourceId);
        }
        return DataProviderViewManager.getQueryParams(type, page, dataSource);
    }

    @RequestMapping(value = "/getConfigView")
    public String getConfigView(@RequestParam(name = "type") String type,
                                @RequestParam(name = "page") String page,
                                @RequestParam(name = "datasourceId", required = false) Long datasourceId) {
        Map<String, String> dataSource = null;
        if (datasourceId != null) {
            dataSource = dataProviderService.getDataSource(datasourceId);
        }
        return DataProviderViewManager.getQueryView(type, page, dataSource);
    }

    @RequestMapping(value = "/getDatasourceParams")
    public List<Map<String, Object>> getDatasourceParams(@RequestParam(name = "type") String type) {
        return DataProviderViewManager.getDatasourceParams(type);
    }

    @RequestMapping(value = "/getDatasourceView")
    public String getDatasourceView(@RequestParam(name = "type") String type) {
        return DataProviderViewManager.getDatasourceView(type);
    }

    @RequestMapping(value = "/saveNewDatasource")
    public ServiceStatus saveNewDatasource(@RequestParam(name = "json") String json) {
        return datasourceService.save(tlUser.get().getUserId(), json);
    }

    @RequestMapping(value = "/updateDatasource")
    public ServiceStatus updateDatasource(@RequestParam(name = "json") String json) {
        return datasourceService.update(tlUser.get().getUserId(), json);
    }

    @RequestMapping(value = "/deleteDatasource")
    public ServiceStatus deleteDatasource(@RequestParam(name = "id") Long id) {
        return datasourceService.delete(tlUser.get().getUserId(), id);
    }

    @RequestMapping(value = "/saveNewWidget")
    public ServiceStatus saveNewWidget(@RequestParam(name = "json") String json) {
        return widgetService.save(tlUser.get().getUserId(), json);
    }

    @RequestMapping(value = "/getAllWidgetList")
    public List<ViewDashboardWidget> getAllWidgetList() {
        List<DashboardWidget> list = widgetDao.getAllWidgetList();
        return Lists.transform(list, ViewDashboardWidget.TO);
    }

    @RequestMapping(value = "/getWidgetList")
    public List<ViewDashboardWidget> getWidgetList() {
        List<DashboardWidget> list = widgetDao.getWidgetList(tlUser.get().getUserId());
        return Lists.transform(list, ViewDashboardWidget.TO);
    }

    @RequestMapping(value = "/updateWidget")
    public ServiceStatus updateWidget(@RequestParam(name = "json") String json) {
        return widgetService.update(tlUser.get().getUserId(), json);
    }

    @RequestMapping(value = "/deleteWidget")
    public ServiceStatus deleteWidget(@RequestParam(name = "id") Long id) {
        return widgetService.delete(tlUser.get().getUserId(), id);
    }

    @RequestMapping(value = "/getBoardList")
    public List<ViewDashboardBoard> getBoardList() {
        List<DashboardBoard> list = boardService.getBoardList(tlUser.get().getUserId());
        return Lists.transform(list, ViewDashboardBoard.TO);
    }

    @RequestMapping(value = "/saveNewBoard")
    public ServiceStatus saveNewBoard(@RequestParam(name = "json") String json) {
        return boardService.save(tlUser.get().getUserId(), json);
    }

    @RequestMapping(value = "/updateBoard")
    public ServiceStatus updateBoard(@RequestParam(name = "json") String json) {
        return boardService.update(tlUser.get().getUserId(), json);
    }

    @RequestMapping(value = "/deleteBoard")
    public ServiceStatus deleteBoard(@RequestParam(name = "id") Long id) {
        return boardService.delete(tlUser.get().getUserId(), id);
    }

    @RequestMapping(value = "/getBoardData")
    public ViewDashboardBoard getBoardData(@RequestParam(name = "id") Long id) {
        return boardService.getBoardData(id);
    }

    @RequestMapping(value = "/saveNewCategory")
    public ServiceStatus saveNewCategory(@RequestParam(name = "json") String json) {
        return categoryService.save(tlUser.get().getUserId(), json);
    }

    @RequestMapping(value = "/getCategoryList")
    public List<DashboardCategory> getCategoryList() {
        List<DashboardCategory> list = categoryDao.getCategoryList();
        return list;
    }

    @RequestMapping(value = "/updateCategory")
    public ServiceStatus updateCategory(@RequestParam(name = "json") String json) {
        return categoryService.update(tlUser.get().getUserId(), json);
    }

    @RequestMapping(value = "/deleteCategory")
    public String deleteCategory(@RequestParam(name = "id") Long id) {
        return categoryService.delete(id);
    }

    @RequestMapping(value = "/getWidgetCategoryList")
    public List<String> getWidgetCategoryList() {
        return widgetDao.getCategoryList();
    }

    @RequestMapping(value = "/saveNewDataset")
    public ServiceStatus saveNewDataset(@RequestParam(name = "json") String json) {
        return datasetService.save(tlUser.get().getUserId(), json);
    }

    @RequestMapping(value = "/getAllDatasetList")
    public List<ViewDashboardDataset> getAllDatasetList() {
        List<DashboardDataset> list = datasetDao.getAllDatasetList();
        return Lists.transform(list, ViewDashboardDataset.TO);
    }

    @RequestMapping(value = "/getDatasetList")
    public List<ViewDashboardDataset> getDatasetList() {
        List<DashboardDataset> list = datasetDao.getDatasetList(tlUser.get().getUserId());
        return Lists.transform(list, ViewDashboardDataset.TO);
    }

    @RequestMapping(value = "/updateDataset")
    public ServiceStatus updateDataset(@RequestParam(name = "json") String json) {
        return datasetService.update(tlUser.get().getUserId(), json);
    }

    @RequestMapping(value = "/deleteDataset")
    public ServiceStatus deleteDataset(@RequestParam(name = "id") Long id) {
        return datasetService.delete(tlUser.get().getUserId(), id);
    }

    @RequestMapping(value = "/getDatasetCategoryList")
    public List<String> getDatasetCategoryList() {
        return datasetDao.getCategoryList();
    }

    @RequestMapping(value = "/checkWidget")
    public ServiceStatus checkWidget(@RequestParam(name = "id") Long id) {
        return widgetService.checkRule(tlUser.get().getUserId(), id);
    }

    @RequestMapping(value = "/checkDatasource")
    public ServiceStatus checkDatasource(@RequestParam(name = "id") Long id) {
        return datasourceService.checkDatasource(tlUser.get().getUserId(), id);
    }

    @RequestMapping(value = "/getDimensionValues")
    public String[] getDimensionValues(@RequestParam(name = "datasourceId", required = false) Long datasourceId,
                                       @RequestParam(name = "query", required = false) String query,
                                       @RequestParam(name = "datasetId", required = false) Long datasetId,
                                       @RequestParam(name = "colmunName", required = true) String colmunName,
                                       @RequestParam(name = "cfg", required = false) String cfg,
                                       @RequestParam(name = "reload", required = false, defaultValue = "false") Boolean reload) {
        Map<String, String> strParams = null;
        if (query != null) {
            JSONObject queryO = JSONObject.parseObject(query);
            strParams = Maps.transformValues(queryO, Functions.toStringFunction());
        }
        AggConfig config = null;
        if (cfg != null) {
            config = ViewAggConfig.getAggConfig(JSONObject.parseObject(cfg, ViewAggConfig.class));
        }
        return dataProviderService.getDimensionValues(datasourceId, strParams, datasetId, colmunName, config, reload);
    }

    @RequestMapping(value = "/getColumns")
    public DataProviderResult getColumns(@RequestParam(name = "datasourceId", required = false) Long datasourceId,
                                         @RequestParam(name = "query", required = false) String query,
                                         @RequestParam(name = "datasetId", required = false) Long datasetId,
                                         @RequestParam(name = "reload", required = false, defaultValue = "false") Boolean reload) {
        Map<String, String> strParams = null;
        if (query != null) {
            JSONObject queryO = JSONObject.parseObject(query);
            strParams = Maps.transformValues(queryO, Functions.toStringFunction());
        }
        return dataProviderService.getColumns(datasourceId, strParams, datasetId, reload);
    }

    @RequestMapping(value = "/getAggregateData")
    public AggregateResult getAggregateData(@RequestParam(name = "datasourceId", required = false) Long datasourceId,
                                            @RequestParam(name = "query", required = false) String query,
                                            @RequestParam(name = "datasetId", required = false) Long datasetId,
                                            @RequestParam(name = "cfg") String cfg,
                                            @RequestParam(name = "reload", required = false, defaultValue = "false") Boolean reload) {
        Map<String, String> strParams = null;
        if (query != null) {
            JSONObject queryO = JSONObject.parseObject(query);
            strParams = Maps.transformValues(queryO, Functions.toStringFunction());
        }
        AggregateResult aggResult = null;
        // data source aggreagtor instance need not lock
        boolean isDataSourceAggInstance = dataProviderService.isDataSourceAggInstance(datasourceId, strParams, datasetId);
        String randomFlag = isDataSourceAggInstance ? UUID.randomUUID().toString() : "1";
        String lockString = Hashing.md5().newHasher()
                .putString(datasourceId + query + datasetId + tlUser.get().getUserId() + randomFlag, Charsets.UTF_8)
                .hash().toString();
        synchronized (lockString.intern()) {
            AggConfig config = ViewAggConfig.getAggConfig(JSONObject.parseObject(cfg, ViewAggConfig.class));
            aggResult = dataProviderService.queryAggData(datasourceId, strParams, datasetId, config, reload);
        }
        return aggResult;
    }

    @RequestMapping(value = "/viewAggDataQuery")
    public String[] viewAggDataQuery(@RequestParam(name = "datasourceId", required = false) Long datasourceId,
                                     @RequestParam(name = "query", required = false) String query,
                                     @RequestParam(name = "datasetId", required = false) Long datasetId,
                                     @RequestParam(name = "cfg") String cfg) {
        Map<String, String> strParams = null;
        if (query != null) {
            JSONObject queryO = JSONObject.parseObject(query);
            strParams = Maps.transformValues(queryO, Functions.toStringFunction());
        }
        AggConfig config = ViewAggConfig.getAggConfig(JSONObject.parseObject(cfg, ViewAggConfig.class));
        return new String[]{dataProviderService.viewAggDataQuery(datasourceId, strParams, datasetId, config)};
    }

    @RequestMapping(value = "/dashboardWidget")
    public ViewDashboardWidget dashboardWidget(@RequestParam(name = "id") Long id) {
        DashboardWidget widget = widgetDao.getWidget(id);
        return new ViewDashboardWidget(widget);
    }

    @RequestMapping(value = "/saveJob")
    public ServiceStatus saveJob(@RequestParam(name = "json") String json) {
        return jobService.save(tlUser.get().getUserId(), json);
    }

    @RequestMapping(value = "/updateJob")
    public ServiceStatus updateJob(@RequestParam(name = "json") String json) {
        return jobService.update(tlUser.get().getUserId(), json);
    }

    @RequestMapping(value = "/getJobList")
    public List<ViewDashboardJob> getJobList() {
        return jobDao.getJobList(tlUser.get().getUserId()).stream().map(ViewDashboardJob::new).collect(Collectors.toList());
    }

    @RequestMapping(value = "/deleteJob")
    public ServiceStatus deleteJob(@RequestParam(name = "id") Long id) {
        return jobService.delete(tlUser.get().getUserId(), id);
    }

    @RequestMapping(value = "/execJob")
    public ServiceStatus execJob(@RequestParam(name = "id") Long id) {
        return jobService.exec(tlUser.get().getUserId(), id);
    }

    @RequestMapping(value = "/exportBoard")
    public ResponseEntity<byte[]> exportBoard(@RequestParam(name = "id") Long id) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        headers.setContentDispositionFormData("attachment", "report.xls");
        return new ResponseEntity<>(boardService.exportBoard(id, tlUser.get().getUserId()), headers, HttpStatus.CREATED);
    }

    @RequestMapping(value = "/tableToxls")
    public ResponseEntity<byte[]> tableToxls(@RequestParam(name = "data") String data) {
        HSSFWorkbook wb = xlsProcessService.tableToxls(JSONObject.parseObject(data));
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        try {
            wb.write(out);
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            headers.setContentDispositionFormData("attachment", "table.xls");
            return new ResponseEntity<>(out.toByteArray(), headers, HttpStatus.CREATED);
        } catch (IOException e) {
            LOG.error("", e);
        }
        return null;
    }

    @RequestMapping(value = "/getJobStatus")
    public ViewDashboardJob getJobStatus(@RequestParam(name = "id") Long id) {
        return new ViewDashboardJob(jobDao.getJob(id));
    }

    @RequestMapping(value = "/getBoardParam")
    public DashboardBoardParam getBoardParam(@RequestParam(name = "boardId") Long boardId) {
        return boardDao.getBoardParam(boardId, tlUser.get().getUserId());
    }

    @RequestMapping(value = "/saveBoardParam")
    @Transactional
    public String saveBoardParam(@RequestParam(name = "boardId") Long boardId,
                                 @RequestParam(name = "config") String config) {
        if (boardId == null) {
            return "";
        }
        DashboardBoardParam boardParam = new DashboardBoardParam();
        boardParam.setBoardId(boardId);
        boardParam.setUserId(tlUser.get().getUserId());
        boardParam.setConfig(config);
        boardDao.deleteBoardParam(boardId, tlUser.get().getUserId());
        boardDao.saveBoardParam(boardParam);
        return "1";
    }

    @ExceptionHandler
    public ServiceStatus exp(HttpServletResponse response, Exception ex) {
        response.setStatus(500);
        LOG.error("Gloal exception Handler", ex);
        return new ServiceStatus(ServiceStatus.Status.Fail, ex.getMessage());
    }

    @RequestMapping(value = "/uploadImage")
    public String uploadImage(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
        String imgPath = imgPath(request);
        String fileName = file.getOriginalFilename();
        String tempFile = tempDir(imgPath) + fileName;
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(tempFile);
            fos.write(file.getBytes());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            IOUtils.closeQuietly(fos);
        }
        return tempFile.split(imgPath)[1];
    }

    private String imgPath(HttpServletRequest request) {
        String templateDir = request.getSession().getServletContext().getRealPath("/");
        templateDir = templateDir.replace("\\","/");
        templateDir = templateDir + "imgs/cockpit";
        return templateDir;
    }

    private String tempDir(String templateDir) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String timestamp = sdf.format(new Date());
        templateDir = templateDir + "/upload/" + timestamp + "/";
        File file = new File(templateDir);
        if (!file.exists()) {
            file.mkdirs();
        }
        return templateDir;
    }
}


text:
using NetToolBox.Core.Abstractions;
using System;
using System.Collections.Generic;
using System.Text;

namespace NetToolBox.Queueing.Abstractions
{
    public abstract class RequeuePolicy
    {
        protected readonly IDateTimeProvider _dateTimeProvider;

        public RequeuePolicy(IDateTimeProvider dateTimeProvider)
        {
            _dateTimeProvider = dateTimeProvider;
        }
        public abstract DateTime CalculateNextQueueTime();

        public bool HasExpired(DateTime initialQueueTime)
        {
            var retval = false;
            if (DateTime.UtcNow > initialQueueTime.Add(FinalExpirationTimeSpan)) retval = true;
            return retval;

        }
        protected virtual TimeSpan FinalExpirationTimeSpan => TimeSpan.FromDays(1);
    }
}


text:
using System;
using LanguageExt;
using LanguageExt.Sys;
using LanguageExt.Pipes;
using LanguageExt.Common;
using LanguageExt.Sys.Traits;
using LanguageExt.Effects.Traits;
using static LanguageExt.Prelude;
using static LanguageExt.Pipes.Proxy;

namespace EffectsExamples
{
    /// <summary>
    /// Fold test
    /// </summary>
    /// <remarks>
    /// Processes keys from the keyboard into words, when a whitespace is encountered the folded word is yielded
    /// down the pipe
    /// </remarks>
    public class FoldTest<RT> where RT :
        struct,
        HasCancel<RT>,
        HasConsole<RT>
    {
        public static Aff<RT, Unit> main =>
            mainEffect.RunEffect();

        static Effect<RT, Unit> mainEffect =>
            repeat(Console<RT>.readKeys)
                | exitIfEscape
                | keyChar
                | words
                | filterEmpty
                | writeLine;

        static Pipe<RT, ConsoleKeyInfo, ConsoleKeyInfo, Unit> exitIfEscape =>
            from k in awaiting<ConsoleKeyInfo>()
            from x in guardnot(k.Key == ConsoleKey.Escape, Errors.Cancelled).ToAff<RT>()
            from _ in yield(k)
            select unit;

        static Pipe<RT, ConsoleKeyInfo, char, Unit> keyChar =>
            map<ConsoleKeyInfo, char>(k => k.KeyChar);

        static Pipe<RT, char, string, Unit> words =>
            foldUntil("", (word, ch) => word + ch, (char x) => char.IsWhiteSpace(x));

        static Pipe<RT, string, string, Unit> filterEmpty =>
            filter<string>(notEmpty);

        static Consumer<RT, string, Unit> writeLine =>
            from l in awaiting<string>()
            from _ in Console<RT>.writeLine(l)
            select unit;
    }
}


text:
<!doctype html>

  <meta charset="utf-8">
  <meta name="description" content="">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <meta name="generator" content="Polymer Starter Kit" />
  <title>Movie Trailer</title>

  <meta name="theme-color" content="#303F9F">

  <link rel="manifest" href="manifest.json">

  <meta name="msapplication-TileColor" content="#3372DF">

  <meta name="mobile-web-app-capable" content="yes">
  <meta name="application-name" content="Polymer Starter Kit">
  <link rel="icon" sizes="192x192" href="images/touch/chrome-touch-icon-192x192.png">

  <meta name="apple-mobile-web-app-capable" content="yes">
  <meta name="apple-mobile-web-app-status-bar-style" content="black">
  <meta name="apple-mobile-web-app-title" content="Polymer Starter Kit">
  <link rel="apple-touch-icon" href="images/touch/apple-touch-icon.png">

  <meta name="msapplication-TileImage" content="images/touch/ms-touch-icon-144x144-precomposed.png">

  <link rel="stylesheet" href="styles/main.css">

  <link rel="import" href="elements/elements.html">

  <template is="dom-bind" id="app">

    <paper-drawer-panel id="paperDrawerPanel">

        <paper-toolbar id="drawerToolbar">
          Menu
        </paper-toolbar>

          <paper-menu class="list" attr-for-selected="data-route" selected="{{route}}" on-iron-select="onMenuSelect">

                <iron-icon icon="home"></iron-icon>
                All Trailers

                <iron-icon icon="favorite"></iron-icon>
                My Trailers

                <iron-icon icon="mail"></iron-icon>
                Contact

          </paper-menu>

      <paper-header-panel main mode="waterfall-tall">

        <paper-toolbar id="mainToolbar">
          <paper-icon-button id="paperToggle" icon="menu" paper-drawer-toggle></paper-icon-button>

          <paper-icon-button icon="refresh" onclick="location.reload()" alt="Reload"></paper-icon-button>
          <paper-icon-button icon="account-circle" onclick="user.login()" alt="Login"></paper-icon-button>
          <paper-icon-button icon="cancel" onclick="user.logout()" aria-label="Logout"></paper-icon-button>

Movie Trailers

        </paper-toolbar>

          <iron-pages attr-for-selected="data-route" selected="{{route}}">

                <trailer-list-all></trailer-list-all>
                <trailer-button-add></trailer-button-add>

                <trailer-list-favorite id="favelid" user-id="" api-url="https://resplendent-inferno-5602.firebaseio.com/favorites/"></trailer-list-favorite>

              <paper-material elevation="1">

Contact

Esté Tigele

eitigele@student.avans.nl

              </paper-material>

              <trailer-item edit=false></trailer-item>

              <trailer-item edit="true" itemid="{{params.id}}"></trailer-item>

          </iron-pages>

      </paper-header-panel>
    </paper-drawer-panel>

    <paper-toast id="caching-complete"
                 duration="6000"
                 text="Caching complete! This app will work offline.">
    </paper-toast>

    <paper-toast id="add-to-favorite-error"
                 duration="6000"
                 text="To add an item to favorites you need to be logged in!">
    </paper-toast>

    <paper-toast id="add-to-favorite-success"
                 duration="6000"
                 text="You have successfully added an item to your favorites!">
    </paper-toast>

    <paper-toast id="remove-from-favorite-success"
                 duration="6000"
                 text="You have successfully removed an item from your favorites!">
    </paper-toast>

    <paper-toast id="already-logged-in-error"
                 duration="6000"
                 text="You are already logged in!">
    </paper-toast>

    <paper-toast id="already-logged-out-error"
                 duration="6000"
                 text="You are already logged out!">
    </paper-toast>

    <paper-toast id="login-success"
                 duration="6000"
                 text="You have successfully logged in">
    </paper-toast>

    <paper-toast id="logout-success"
                 duration="6000"
                 text="You have successfully logged out">
    </paper-toast>

    <platinum-sw-register auto-register
                          clients-claim
                          skip-waiting
                          on-service-worker-installed="displayInstalledToast">
      <platinum-sw-cache default-cache-strategy="networkFirst"
                         precache-file="precache.json">
      </platinum-sw-cache>
    </platinum-sw-register>

  </template>


text:
package org.commonjava.indy.ftest.core.content;

import org.commonjava.indy.client.core.IndyClientException;
import org.commonjava.indy.ftest.core.AbstractContentManagementTest;
import org.commonjava.indy.ftest.core.category.EventDependent;
import org.commonjava.indy.model.core.HostedRepository;
import org.junit.Before;
import org.junit.Test;
import org.junit.experimental.categories.Category;

import java.io.ByteArrayInputStream;

import static org.commonjava.indy.pkg.PackageTypeConstants.PKG_TYPE_MAVEN;

/**
 * Given two snapshot pom paths and test the metadata merge.
 */
public class HostedMetadataMergeSnapshotTest
                extends AbstractContentManagementTest
{
    private static final String HOSTED_A_NAME= "A";

    private static final String A_VERSION = "1.0-SNAPSHOT";
    private static final String B_VERSION = "1.1-SNAPSHOT";

    private static final String PATH = "/org/foo/bar/maven-metadata.xml";

    private static final String SNAPSHOT_METADATA_PATH = "/org/foo/bar/%version%/maven-metadata.xml";

    private static final String POM_PATH_TEMPLATE = "/org/foo/bar/%version%/bar-%version%.pom";

    /* @formatter:off */
    private static final String POM_CONTENT_TEMPLATE = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
        "<project>\n" +
        "  <modelVersion>4.0.0</modelVersion>\n" +
        "  <groupId>org.foo</groupId>\n" +
        "  <artifactId>bar</artifactId>\n" +
        "  <version>%version%</version>\n" +
        "  <name>Bar</name>\n" +
        "  <dependencies>\n" +
        "    <dependency>\n" +
        "      <groupId>org.something</groupId>\n" +
        "      <artifactId>oh</artifactId>\n" +
        "      <version>1.0.1</version>\n" +
        "    </dependency>\n" +
        "  </dependencies>\n" +
        "</project>\n";

    private static final String AFTER_PROMOTE_CONTENT = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
        "<metadata>\n" +
        "  <groupId>org.foo</groupId>\n" +
        "  <artifactId>bar</artifactId>\n" +
        "  <versioning>\n" +
        "    <latest>1.1-SNAPSHOT</latest>\n" +
        "    <versions>\n" +
        "      <version>1.0-SNAPSHOT</version>\n" +
        "      <version>1.1-SNAPSHOT</version>\n" +
        "    </versions>\n" +
        "    <lastUpdated>20150722164334</lastUpdated>\n" +
        "  </versioning>\n" +
        "</metadata>\n";

    private static final String SNAPSHOT_METADATA_CONTENT = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
        + "<metadata>\n"
        + "  <groupId>org.foo</groupId>\n"
        + "  <artifactId>bar</artifactId>\n"
        + "  <version>1.1-SNAPSHOT</version>\n"
        + "  <versioning>\n"
        + "    <snapshot>\n"
        + "      <localCopy>true</localCopy>\n"
        + "    </snapshot>\n"
        + "    <snapshotVersions>\n"
        + "      <snapshotVersion>\n"
        + "        <extension>pom</extension>\n"
        + "        <value>1.1-SNAPSHOT</value>\n"
        + "        <updated>20190629074244</updated>\n"
        + "      </snapshotVersion>\n"
        + "    </snapshotVersions>\n"
        + "  </versioning>\n"
        + "</metadata>\n";
    /* @formatter:on */

    private HostedRepository hosted;

    private String aPomPath;
    private String aPomContent;

    private String bPomPath;
    private String bPomContent;

    @Before
    public void setupRepos()
                    throws IndyClientException
    {
        String message = "test setup";

        hosted = new HostedRepository( PKG_TYPE_MAVEN, HOSTED_A_NAME );
        hosted.setAllowSnapshots( true );
        hosted = client.stores().create( hosted, message, HostedRepository.class );

        aPomPath = POM_PATH_TEMPLATE.replaceAll( "%version%", A_VERSION );
        aPomContent = POM_CONTENT_TEMPLATE.replaceAll( "%version%", A_VERSION );
        client.content()
              .store( hosted.getKey(), aPomPath, new ByteArrayInputStream(
                              aPomContent.getBytes() ) );

        bPomPath = POM_PATH_TEMPLATE.replaceAll( "%version%", B_VERSION );
        bPomContent = POM_CONTENT_TEMPLATE.replaceAll( "%version%", B_VERSION );
        client.content()
              .store( hosted.getKey(), bPomPath, new ByteArrayInputStream(
                              bPomContent.getBytes() ) );
    }

    @Test
    @Category( EventDependent.class )
    public void run()
                    throws Exception
    {
        assertMetadataContent( hosted, PATH, AFTER_PROMOTE_CONTENT );

        assertMetadataContent( hosted, SNAPSHOT_METADATA_PATH.replaceAll( "%version%", B_VERSION ),
                               SNAPSHOT_METADATA_CONTENT );
    }

    @Override
    protected boolean createStandardTestStructures()
    {
        return false;
    }

}


text:
package 'gdisk'

# NOTE: Only used for filestore and not bluestore!
# TODO: Put a gaurd in for that!

# Remove the journal partitions
journals = get_journals
if !journals.empty?
  journals.each do | journal |
    execute "ceph-journal-zap for #{journal}" do
      command <<-EOH
        for i in $(sgdisk #{journal} -p | grep ceph | awk '{print $1}'); do
          sgdisk #{journal} -d $i
        done
      EOH
      action :run
    end
  end
end


text:
@import includes._
@(tags: List[TagWithCount])(implicit request: play.api.mvc.Request[Any])
@header(request, title = "About | Vachin")
@topbar(tags, request = Some(request))

About

Vachin came from the Sanskrit word वचन (vácana) which has two meanings like

promise, word, oath, vow

word, utterance, speech

So by considering the second meaning Vachin is the curated store of texts, quotes, messages which we generally use to express ourselves.

The inspiration behind Vachin is that most of us can't express our feelings in words.
        And in layman terms only a few can express their feelings with words and the rest have better feelings but they can't express them.

Vachin aggregate best sentences from people and history and sort them with relevancy. So that who in need of those messages or quotes can use them anywhere they are.

We will maintain this crowd sourced texts always available for all kinds of users across the world and coming soon in more languages.

We need to thank Unsplash It for their beautiful placeholder images which we are using as background for our texts. And soon we are planning to attribute each contributor of those images.

We provide free access to our APIs which is in progress and it will be available soon through https://dev.vach.in which is for developers.

If anyone want to contribute in your free times, feel free to Contact Us

@footer()


text:
/* @test %W% %E%
 * @summary Tests the WeakSoftTable class.
 * @author Tim Blackman
 * @library ../../../../../unittestlib
 * @build UnitTestUtilities BasicTest Test
 * @build TestUtilities
 * @run main/othervm/policy=policy TestWeakSoftTable
 */

import java.lang.ref.Reference;
import java.lang.ref.ReferenceQueue;
import java.util.*;
import com.sun.jini.collection.WeakSoftTable;

public abstract class TestWeakSoftTable extends TestUtilities {

    static class Key {
	private static int nextIndex;
	private final String name;
	private final int index = ++nextIndex;
	Key(String name) { this.name = name; }
	public int hashCode() { return name.hashCode(); }
	public boolean equals(Object o) {
	    return (o instanceof Key) && name.equals(((Key) o).name);
	}
	public String toString() {
	    return "key" + name + "[" + index + "]";
	}
    }

    static class WeakKey extends WeakSoftTable.WeakKey {
	WeakKey(Object key) { super(key); }
	private WeakKey(WeakKey weakKey, ReferenceQueue queue) {
	    super(weakKey, queue);
	}
	public WeakSoftTable.RemovableReference copy(ReferenceQueue queue) {
	    return new WeakKey(this, queue);
	}
	public String toString() {
	    return String.valueOf(get());
	}
    }

    static class SoftValue extends WeakSoftTable.SoftValue {
	SoftValue(WeakKey key, Object value) { super(key, value); }
	private SoftValue(SoftValue softValue, ReferenceQueue queue) {
	    super(softValue, queue);
	}
	public WeakSoftTable.RemovableReference copy(ReferenceQueue queue) {
	    return new SoftValue(this, queue);
	}
	public String toString() {
	    return String.valueOf(get());
	}
    }

    public static Collection tests = new ArrayList();

    static final Key keyA = new Key("A");
    static final String valA = "valA";
    static final Key keyA2 = new Key("A");
    static final String valA2 = "valA2";
    static final Key keyB = new Key("B");
    static final String valB = "valB";
    static final String valB2 = "valB2";
    static final Key keyX = new Key("X");

    static final LazyField hash = new LazyField(
	"com.sun.jini.collection", "WeakSoftTable", "hash");

    public static void main(String[] args) {
	test(tests);
    }

    static Object[] array(Object a) {
	return new Object[] { a };
    }

    static Object[] array(Object a, Object b) {
	return new Object[] { a, b };
    }

    static Object[] array(Object a, Object b, Object c, Object d) {
	return new Object[] { a, b, c, d };
    }

    static boolean contains(Collection c, Object o) {
	for (Iterator iter = c.iterator(); iter.hasNext(); ) {
	    if (iter.next() == o) {
		return true;
	    }
	}
	return false;
    }

    static abstract class LocalTest extends BasicTest {
	WeakSoftTable table;
	Object[] keysAndValues;
	Collection clear;

	LocalTest(String name,
		  Object[] keysAndValues,
		  Object[] clear,
		  Object result)
	{
	    super(name +
		  "\n  keysAndValues = " + toString(keysAndValues) +
		  (clear == null ? "" :
		   "\n  clear = " + toString(clear)),
		  result);
	    /* Hold reference to the keys and values so they don't get GC'ed */
	    this.keysAndValues = (keysAndValues == null) ? new Object[0]
		: keysAndValues;
	    this.clear = (clear == null) ? Collections.EMPTY_LIST
		: Arrays.asList(clear);
	}

	Object get(Object key, int index) {
	    SoftValue softValue =
		(SoftValue) table.get(new WeakKey(key), index);
	    return softValue == null ? null : softValue.get();
	}

	void add(Object key, Object value) {
	    WeakKey weakKey = new WeakKey(key);
	    table.add(weakKey, new SoftValue(weakKey, value));
	}

	Object remove(Object key, int index) {
	    SoftValue softValue =
		(SoftValue) table.remove(new WeakKey(key), index);
	    return softValue == null ? null : softValue.get();
	}

	void maybeClear(boolean force) {
	    if (clear == null) {
		return;
	    }
	    for (Iterator iter = getHash().entrySet().iterator();
		 iter.hasNext(); )
	    {
		Map.Entry entry = (Map.Entry) iter.next();
		Reference key = (Reference) entry.getKey();
		if (contains(clear, key.get())) {
		    key.clear();
		    key.enqueue();
		}
		List list = (List) entry.getValue();
		for (int i = list.size(); --i >= 0; ) {
		    Reference value = (Reference) list.get(i);
		    if (contains(clear, value.get())) {
			value.clear();
			value.enqueue();
		    }
		}
	    }

	    /* Force processing queue */
	    if (force) {
		remove(keyX, 0);
	    }
	}

	void initTable() {
	    table = new WeakSoftTable();
	    for (int i = 0; i < keysAndValues.length; i += 2) {
		add(keysAndValues[i], keysAndValues[i+1]);
	    }
	}

	Map getHash() {
	    return (Map) hash.get(table);
	}
    }

    static {
	tests.add(TestGet.localtests);
    }

    public static class TestGet extends LocalTest {
	static Test[] localtests = {
	    new TestGet(keyA, 0, null, null, null),
	    new TestGet(keyA, 33, null, null, null),
	    new TestGet(keyA, 0, array(keyA, valA), null, valA),
	    new TestGet(keyA, 1, array(keyA, valA), null, null),
	    new TestGet(keyA, 0, array(keyA2, valA), null, null),
	    new TestGet(keyA, 0, array(keyB, valA), null, null),
	    new TestGet(keyA, 0, array(keyA, valA), array(keyA), null),
	    new TestGet(keyA, 0, array(keyA, valA), array(valA), null),
	    new TestGet(keyA, 0, array(keyA, valA, keyA, valA2), null, valA),
	    new TestGet(keyA, 1, array(keyA, valA, keyA, valA2), null, valA2),
	    new TestGet(keyA, 0, array(keyA, valA, keyA, valA2), array(keyA),
			null),
	    new TestGet(keyA, 0, array(keyA, valA, keyA, valA2), array(valA),
			valA2),
	    new TestGet(keyA, 0, array(keyA, valA, keyA, valA2), array(valA2),
			valA),
	    new TestGet(keyA, 0, array(keyA, valA, keyA, valA2),
			array(valA, valA2), null),
	    new TestGet(keyA, 1, array(keyA, valA, keyA, valA2), array(valA),
			null),
	    new TestGet(keyA, 0, array(keyA, valA, keyB, valB), array(keyB),
			valA)
	};

	final Object key;
	final int index;

	TestGet(Object key,
		int index,
		Object[] keysAndValues,
		Object[] clear,
		Object result)
	{
	    super("get(" + key + ", " + index + ")",
		  keysAndValues, clear, result);
	    this.key = key;
	    this.index = index;
	}

	public Object run() {
	    initTable();
	    maybeClear(true);
	    return get(key, index);
	}

	public void check(Object result) throws Exception {
	    super.check(result);
	    super.check(get(key, index));
	}
    }

    static {
	tests.add(TestAdd.localtests);
    }

    public static class TestAdd extends LocalTest {
	static Test[] localtests = {
	    new TestAdd(keyA, valA, null, null, 0),
	    new TestAdd(keyA, valA2, array(keyA, valA), null, 1),
	    new TestAdd(keyA, valA2, array(keyA, valA), array(keyA), 0),
	    new TestAdd(keyA, valA2, array(keyA, valA), array(valA), 0)
	};

	final Object key;
	final int index;

	TestAdd(Object key,
		Object value,
		Object[] keysAndValues,
		Object[] clear,
		int index)
	{
	    super("add(" + key + ", " + value + ")",
		  keysAndValues, clear, value);
	    this.key = key;
	    this.index = index;
	}

	public Object run() {
	    initTable();
	    maybeClear(false);
	    add(key, getCompareTo());
	    return get(key, index);
	}
    }

    static {
	tests.add(TestRemove.localtests);
    }

    public static class TestRemove extends LocalTest {
	static Test[] localtests = {
	    new TestRemove(keyA, 0, null, null, null, null),
	    new TestRemove(keyA, 0, array(keyA, valA), null, valA, null),
	    new TestRemove(keyA, 0, array(keyA, valA, keyA, valA2), null,
			   valA, valA2)
	};

	final Object key;
	final int index;
	final Object nextResult;

	TestRemove(Object key,
		   int index,
		   Object[] keysAndValues,
		   Object[] clear,
		   Object result,
		   Object nextResult)
	{
	    super("remove(" + key + ", " + index + ")",
		  keysAndValues, clear, result);
	    this.key = key;
	    this.index = index;
	    this.nextResult = nextResult;
	}

	public Object run() {
	    initTable();
	    maybeClear(false);
	    return remove(key, index);
	}

	public void check(Object result) throws Exception {
	    super.check(result);
	    Object get = get(key, index);
	    if (get != nextResult) {
		throw new FailedException("Wrong next value, found " + get +
					  ", expected " + nextResult);
	    }
	}
    }
}


text:
package com.example.android.miwok;

import android.media.MediaPlayer;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;

import java.util.ArrayList;

public class PhrasesActivity extends AppCompatActivity {
    private MediaPlayer mMediaPlayer;
    private MediaPlayer.OnCompletionListener mOnCompletionListener = new MediaPlayer.OnCompletionListener() {
        @Override
        public void onCompletion(MediaPlayer mp) {
            releaseMediaPlayer();
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.word_list);

        final ArrayList<Word> words = new ArrayList<>();
        words.add(new Word("Where are you going?", "minto wuksus",
                R.raw.phrase_where_are_you_going));
        words.add(new Word("What is your name?", "tinnә oyaase'nә",
                R.raw.phrase_what_is_your_name));
        words.add(new Word("My name is...", "oyaaset...", R.raw.phrase_my_name_is));
        words.add(new Word("How are you feeling?", "michәksәs?", R.raw.phrase_how_are_you_feeling));
        words.add(new Word("I'm feeling good.", "kuchi achit", R.raw.phrase_im_feeling_good));
        words.add(new Word("Are you coming?", "әәnәs'aa?", R.raw.phrase_are_you_coming));
        words.add(new Word("Yes, I'm coming.", "hәә' әәnәm", R.raw.phrase_yes_im_coming));
        words.add(new Word("I'm coming.", "әәnәm", R.raw.phrase_im_coming));
        words.add(new Word("Let's go.", "yoowutis", R.raw.phrase_lets_go));
        words.add(new Word("Come here.", "әnni'nem", R.raw.phrase_come_here));

        ListView listView = (ListView) findViewById(R.id.list);
        WordAdapter adapter = new WordAdapter(this, words, R.color.category_phrases);
        listView.setAdapter(adapter);

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                releaseMediaPlayer();
                Word word = words.get(position);
                mMediaPlayer = MediaPlayer.create(PhrasesActivity.this, word.getAudioResourceID());
                mMediaPlayer.start();
                mMediaPlayer.setOnCompletionListener(mOnCompletionListener);

            }
        });
    }

    @Override
    protected void onStop() {
        super.onStop();
        releaseMediaPlayer();
    }
    private void releaseMediaPlayer(){

        if (mMediaPlayer != null){
            mMediaPlayer.release();
            mMediaPlayer = null;
        }
    }
}