text:
subcategory: "Cloud Storage"
page_title: "Google: google_storage_object_signed_url"
description: |-
    Provides signed URL to Google Cloud Storage object.
---

# google\_storage\_object\_signed_url

The Google Cloud storage signed URL data source generates a signed URL for a given storage object. Signed URLs provide a way to give time-limited read or write access to anyone in possession of the URL, regardless of whether they have a Google account.

For more info about signed URL's is available [here](https://cloud.google.com/storage/docs/access-control/signed-urls).

## Example Usage

```hcl
data "google_storage_object_signed_url" "artifact" {
  bucket = "install_binaries"
  path   = "path/to/install_file.bin"
}

resource "google_compute_instance" "vm" {
  name = "vm"

  provisioner "remote-exec" {
    inline = [
      "wget '${data.google_storage_object_signed_url.artifact.signed_url}' -O install_file.bin",
      "chmod +x install_file.bin",
      "./install_file.bin",
    ]
  }
}
```

## Full Example

```hcl
data "google_storage_object_signed_url" "get_url" {
  bucket       = "fried_chicken"
  path         = "path/to/file"
  content_md5  = "pRviqwS4c4OTJRTe03FD1w=="
  content_type = "text/plain"
  duration     = "2d"
  credentials  = file("path/to/credentials.json")

  extension_headers = {
    x-goog-if-generation-match = 1
  }
}
```

## Argument Reference

The following arguments are supported:

* `bucket` - (Required) The name of the bucket to read the object from
* `path` - (Required) The full path to the object inside the bucket
* `http_method` - (Optional) What HTTP Method will the signed URL allow (defaults to `GET`)
* `duration` - (Optional) For how long shall the signed URL be valid (defaults to 1 hour - i.e. `1h`).
     See [here](https://golang.org/pkg/time/#ParseDuration) for info on valid duration formats.
* `credentials` - (Optional) What Google service account credentials json should be used to sign the URL.
     This data source checks the following locations for credentials, in order of preference: data source `credentials` attribute, provider `credentials` attribute and finally the GOOGLE_APPLICATION_CREDENTIALS environment variable.

    > **NOTE** the default google credentials configured by `gcloud` sdk or the service account associated with a compute instance cannot be used, because these do not include the private key required to sign the URL. A valid `json` service account credentials key file must be used, as generated via Google cloud console.

* `content_type` - (Optional) If you specify this in the datasource, the client must provide the `Content-Type` HTTP header with the same value in its request.
* `content_md5` - (Optional) The [MD5 digest](https://cloud.google.com/storage/docs/hashes-etags#_MD5) value in Base64.
     Typically retrieved from `google_storage_bucket_object.object.md5hash` attribute.
     If you provide this in the datasource, the client (e.g. browser, curl) must provide the `Content-MD5` HTTP header with this same value in its request.
* `extension_headers` - (Optional) As needed. The server checks to make sure that the client provides matching values in requests using the signed URL.
     Any header starting with `x-goog-` is accepted but see the [Google Docs](https://cloud.google.com/storage/docs/xml-api/reference-headers) for list of headers that are supported by Google.

## Attributes Reference

The following attributes are exported:

* `signed_url` - The signed URL that can be used to access the storage object without authentication.


text:
/* @flow */

import {Node} from "./mcts-node";
import {GameQuery} from "../../game/game-query";

export class CardplayStrategy {

	constructor() {
		this.boards = {};
		this.rootNode = undefined;
		this.started = false;
	}

	updateGameState(gameState) {
		let board = new GameQuery(gameState).currentBoard;

		if (board.biddingHasEnded) {
			this.rootNode = this.getRootNode(board);
		}
	}

	getCard() {
		this.visit(20);
		//console.log("visits = " + this.rootNode.visits);
		let card = this.rootNode.bestCard();
		return Promise.resolve(card);
	}

	visit(rounds) {
		rounds = rounds || 1;
		for (let round = 0; round < rounds; round += 1)
			this.rootNode.visit();
	}

	getRootNode(board) {
		let key = JSON.stringify(board.hands);

		if (!this.boards[key])
			this.boards[key] = new Node(null, board, null);

		return this.boards[key].seek(board.cards);
	}
}

redpajama_set_name: RedPajamaGithub


text:
"use strict";

var koTools = require('./../kotools');
var charting = require('./../charting');

//accepts and array of objects. one property of each object is used as the x-coordinate
//(determined by the xcoord option, which by default is set to 'x')
//the rest of the properties is stacked to the chart
charting.barChart = function (data, element, options, lineData) {
    var el = charting.getElementAndCheckData(element, data);
    if (!el){
        return;
    }

    var defaultOptions = {
        legend: true,
        width: 600,
        height: 200,
        xUnitName: 'x',
        itemName: 'Item',
        xcoord: 'x'
    };

    options = koTools.setDefaultOptions(defaultOptions, options);
    var xcoord = options.xcoord;

    // not all the items do have the same set of properties, therefor scan them all and concatenate the result
    var keys = [];
    data.map(function (i) {
        var itemKeys = d3.keys(i).filter(function (key) { return key !== xcoord && keys.indexOf(key) < 0; });
        keys = keys.concat(itemKeys);
    });

    //we need color for each possible variable
    var color = charting.colors.domain(keys);

    var dims = charting.getDimensions(options, el);

    var xKeys = data.map(function(d){return d[xcoord];});

    // for bar chart the x-scale is always ordinary with range bounds
    // but we run the determining X Scale method anyway
    // because it can help determine the xFormat
    charting.determineXScale(xKeys, null, options);

    var x = d3.scale.ordinal()
        .rangeRoundBands([0, dims.width], 0.3);

    var y = d3.scale.linear()
        .rangeRound([dims.height, 0]);

    //runs overs all the data. copies the result to a new array.
    //for each item we need y0 and y1 - are the y coordinates of the rectangle
    //it is bit tricky to have a something that works for stacked and grouped chart
    var arranged = [];
    var arrangedByX = {};
    data.forEach(function (d) {
        var newD = { x: d[xcoord] };
        var y0Neg = 0;
        var y0Pos = 0;

        var values = [];
        color.domain().forEach(function (m) {
            if (!koTools.isNumber(d[m]) || d[m] === 0 || d[m] === null){
                return;
            }
            var xLabel = newD.x;
            if (options.xFormat){
                xLabel = options.xFormat(newD.x);
            }
            var formattedValue = d[m];
            if (options.yFormat){
                formattedValue = options.yFormat(d[m]);
            }

            var value = {
                name:m,
                val: d[m],
                x: newD.x,
                xLabel: xLabel,
                xUnitName: options.xUnitName,
                formattedValue: formattedValue
            };

            if (d[m] > 0 && options.style === "stack") {
                value.y0 = y0Pos;
                y0Pos += d[m];
                value.y1 = y0Pos;
            } else if (d[m] < 0 && options.style === "stack"){
                var y1 = y0Neg;
                y0Neg += d[m];
                value.y0 = y0Neg;
                value.y1 =  y1;
            } else if (d[m] > 0 && options.style !== "stack"){
                value.y0 = 0;
                value.y1 = d[m];
            } else if(d[m] < 0 && options.style !== "stack"){
                value.y0 = d[m];
                value.y1 = 0;
            }
            values.push(value);
        });

        newD.values = values;
        newD.totalPositive = d3.max(newD.values, function (v) { return v.y1; });
        newD.totalNegative = d3.min(newD.values, function (v) { return v.y0; });
        arranged.push(newD);
        arrangedByX[newD.x] = newD;
    });

    charting.showStandardLegend(el, keys,color, options, dims);

    var svg = charting.appendContainer(el, dims);

    x.domain(xKeys);
    if (options.style === "stack") {
        y.domain([
            d3.min(arranged, function (d) {
              return d.totalNegative;
            }), d3.max(arranged, function (d) {
                if (!d){
                    return 0;
                }
                return d.totalPositive;
            })
        ]);
    } else {
        y.domain(
        [
            d3.min(arranged, function (d) {
                return d3.min(d.values,
                    function (i) {
                        if (i.val < 0){
                            return i.val;
                        }
                        return 0;
                    });
            }),
            d3.max(arranged, function (d) {
                return d3.max(d.values,
                    function (i) { return i.val; });
            })
        ]);
    }

    //for the groupped chart
    var x1 = d3.scale.ordinal();
    x1.domain(keys).rangeRoundBands([0, x.rangeBand()]);

    charting.createXAxis(svg, options, x, dims);
    charting.createYAxis(svg, options, y, dims);

    var onBarOver = function (d) {
        var column = arrangedByX[d.x];
        d3.select(this).style("opacity", 1);
        var info = {};
        info[d.xLabel] = "";
        info[d.name] = d.formattedValue;
        if (column.totalNegative === 0 && options.style === "stack"){
            info[d.name] += " (" + koTools.toPercent(d.val / column.totalPositive) + ")";
        }
        charting.showTooltip(info);
    };

    var onBarOut = function () {
        d3.select(this).style("stroke", 'none');
        d3.select(this).style("opacity", 0.9);
        charting.hideTooltip();
    };

    var group = svg.selectAll(".xVal")
        .data(arranged)
        .enter().append("g")
        .attr("class", "g")
        .attr("transform", function (d) { return "translate(" + x(d.x) + ",0)"; });

    var rectangles = group.selectAll("rect")
        .data(function (d) { return d.values; })
        .enter().append("rect");

    if (options.style === "stack") {
        rectangles.attr("width", x.rangeBand());
    } else {
        rectangles.attr("width", x1.rangeBand())
          .attr("x", function (d) {
              return x1(d.name);
          });
    }

    rectangles.attr("y", function (d) {
      return y(d.y1);
    })
    .attr("height", function (d) {
      var height = Math.abs(y(d.y0) - y(d.y1));
      return height;
    })
    .on("mouseover", onBarOver)
    .on("mouseout", onBarOut)
    .style("opacity", 0.9)
    .style("cursor", "pointer")
    .style("fill", function (d) {
        return color(d.name);
    });

    //Add the single line for the cashflow like charts
    if (!lineData || lineData.length === 0){
        return;
    }

    var lineY = d3.scale.linear()
        .range([dims.height, 0]);

    var line = d3.svg.line()
        .interpolate("linear")
        .x(function (d) {
            return x(d.x) + x.rangeBand() / 2;
        })
        .y(function (d) {
            return lineY(d.y);
        });

    //in some cases it makes sense to use the same scale for both
    //typically the cash-flow chart
    //for other cases (line  volumne / units correlations a separate scale should be used for each)
    if (!options.sameScaleLinesAndBars) {
        lineY.domain([
            0,
            d3.max(lineData, function (v) { return v.y; })
        ]);
    } else {
        lineY.domain(y.domain());
    }

    var yAxisLeft = d3.svg.axis()
       .scale(lineY)
       .orient("left");

    var leftAxis = svg.append("g")
       .call(yAxisLeft);

    charting.yAxisStyle(leftAxis);

    svg.append("path")
        .attr("d", line(lineData))
        .style("stroke", "blue")
        .style("stroke-width", 2)
        .style("fill", "none");

    var circles = svg.selectAll("circle")
        .data(lineData)
        .enter()
        .append("circle");

    circles.attr("cx", function (d) { return x(d.x) + x.rangeBand() / 2; })
        .attr("cy", function (d) { return lineY(d.y); })
        .attr("r", function () { return 4; })
        .style("fill", "white")
        .attr("r", function () { return 3; })
        .style("fill", "white")
        .style("stroke-width", "1")
        .style("stroke", "black")
        .style("cursor", "pointer")
        .on("mouseover", function(d) { charting.singlePointOver(this, options, d);})
        .on("click", function(d) { charting.singlePointOver(this, options, d);})
        .on("mouseout", function(d) { charting.singlePointOut(this);});
};


text:
package org.apache.commons.jxpath;

/**
 * A delegate of {@link JXPathContext} that implements the XPath "id()"
 * function. This delegate is only used when there is no default implementation
 * of the id() function. For example, it is not used
 * when the root of the context is a DOM Node.
 *
 * @author Dmitri Plotnikov
 * @version $Revision$ $Date$
 */
public interface IdentityManager {

    /**
     * Finds a node by its ID.
     * @param context JXPathContext
     * @param id String
     * @return Pointer
     */
    Pointer getPointerByID(JXPathContext context, String id);
}


text:
<?php

namespace Tests\VCard;

use Tests\BaseTestCase as TestCase,
    VCard\SourceDetector;

class SourceDetectorTest extends TestCase
{

    public function testOnVCardStarted()
    {
        $this->markTestIncomplete();
    }

    public function testOnVCardEnded()
    {
        $this->markTestIncomplete();
    }

    public function testOnEntryStarted()
    {
        $this->markTestIncomplete();
    }

    public function testOnEntryEnded()
    {
        $this->markTestIncomplete();
    }

    public function testOnPropertyCreated()
    {
        $this->markTestIncomplete();
    }

    public function testGetEstimatedType()
    {
        $this->markTestIncomplete();
    }

    public function testGetEstimatedCharset()
    {
        $this->markTestIncomplete();
    }

}


text:
package com.microsoft.azure.management.appconfiguration.v2020_06_01.implementation;

import com.microsoft.azure.arm.resources.models.implementation.GroupableResourceCoreImpl;
import com.microsoft.azure.management.appconfiguration.v2020_06_01.ConfigurationStore;
import rx.Observable;
import com.microsoft.azure.management.appconfiguration.v2020_06_01.ConfigurationStoreUpdateParameters;
import com.microsoft.azure.management.appconfiguration.v2020_06_01.ResourceIdentity;
import com.microsoft.azure.management.appconfiguration.v2020_06_01.ProvisioningState;
import org.joda.time.DateTime;
import com.microsoft.azure.management.appconfiguration.v2020_06_01.EncryptionProperties;
import java.util.List;
import com.microsoft.azure.management.appconfiguration.v2020_06_01.PrivateEndpointConnectionReference;
import com.microsoft.azure.management.appconfiguration.v2020_06_01.PublicNetworkAccess;
import com.microsoft.azure.management.appconfiguration.v2020_06_01.Sku;
import rx.functions.Func1;

class ConfigurationStoreImpl extends GroupableResourceCoreImpl<ConfigurationStore, ConfigurationStoreInner, ConfigurationStoreImpl, AppConfigurationManager> implements ConfigurationStore, ConfigurationStore.Definition, ConfigurationStore.Update {
    private ConfigurationStoreUpdateParameters updateParameter;
    ConfigurationStoreImpl(String name, ConfigurationStoreInner inner, AppConfigurationManager manager) {
        super(name, inner, manager);
        this.updateParameter = new ConfigurationStoreUpdateParameters();
    }

    @Override
    public Observable<ConfigurationStore> createResourceAsync() {
        ConfigurationStoresInner client = this.manager().inner().configurationStores();
        return client.createAsync(this.resourceGroupName(), this.name(), this.inner())
            .map(new Func1<ConfigurationStoreInner, ConfigurationStoreInner>() {
               @Override
               public ConfigurationStoreInner call(ConfigurationStoreInner resource) {
                   resetCreateUpdateParameters();
                   return resource;
               }
            })
            .map(innerToFluentMap(this));
    }

    @Override
    public Observable<ConfigurationStore> updateResourceAsync() {
        ConfigurationStoresInner client = this.manager().inner().configurationStores();
        return client.updateAsync(this.resourceGroupName(), this.name(), this.updateParameter)
            .map(new Func1<ConfigurationStoreInner, ConfigurationStoreInner>() {
               @Override
               public ConfigurationStoreInner call(ConfigurationStoreInner resource) {
                   resetCreateUpdateParameters();
                   return resource;
               }
            })
            .map(innerToFluentMap(this));
    }

    @Override
    protected Observable<ConfigurationStoreInner> getInnerAsync() {
        ConfigurationStoresInner client = this.manager().inner().configurationStores();
        return client.getByResourceGroupAsync(this.resourceGroupName(), this.name());
    }

    @Override
    public boolean isInCreateMode() {
        return this.inner().id() == null;
    }

    private void resetCreateUpdateParameters() {
        this.updateParameter = new ConfigurationStoreUpdateParameters();
    }

    @Override
    public DateTime creationDate() {
        return this.inner().creationDate();
    }

    @Override
    public EncryptionProperties encryption() {
        return this.inner().encryption();
    }

    @Override
    public String endpoint() {
        return this.inner().endpoint();
    }

    @Override
    public ResourceIdentity identity() {
        return this.inner().identity();
    }

    @Override
    public List<PrivateEndpointConnectionReference> privateEndpointConnections() {
        return this.inner().privateEndpointConnections();
    }

    @Override
    public ProvisioningState provisioningState() {
        return this.inner().provisioningState();
    }

    @Override
    public PublicNetworkAccess publicNetworkAccess() {
        return this.inner().publicNetworkAccess();
    }

    @Override
    public Sku sku() {
        return this.inner().sku();
    }

    @Override
    public ConfigurationStoreImpl withSku(Sku sku) {
        if (isInCreateMode()) {
            this.inner().withSku(sku);
        } else {
            this.updateParameter.withSku(sku);
        }
        return this;
    }

    @Override
    public ConfigurationStoreImpl withEncryption(EncryptionProperties encryption) {
        if (isInCreateMode()) {
            this.inner().withEncryption(encryption);
        } else {
            this.updateParameter.withEncryption(encryption);
        }
        return this;
    }

    @Override
    public ConfigurationStoreImpl withIdentity(ResourceIdentity identity) {
        if (isInCreateMode()) {
            this.inner().withIdentity(identity);
        } else {
            this.updateParameter.withIdentity(identity);
        }
        return this;
    }

    @Override
    public ConfigurationStoreImpl withPublicNetworkAccess(PublicNetworkAccess publicNetworkAccess) {
        if (isInCreateMode()) {
            this.inner().withPublicNetworkAccess(publicNetworkAccess);
        } else {
            this.updateParameter.withPublicNetworkAccess(publicNetworkAccess);
        }
        return this;
    }

}


text:
As an introduction to this section, to borrow from [the official docs](
http://doc.rust-lang.org/master/guide-unsafe.html), "one should try to
minimize the amount of unsafe code in a code base." With that in mind, let's
get started!
Unsafe blocks in Rust are used to bypass protections put in place by the
compiler; specifically, there are four primary things that unsafe blocks are
used for:

* dereferencing raw pointers
* calling a function over FFI (but this is covered in a different part of the
  book)
* changing types through `std::cast::transmute`
* inline assembly

### Raw Pointers
Raw pointers `*` and references `&T` function similarly, but references are
always safe because they are guaranteed to point to valid data due to the
borrow checker. Dereferencing a raw pointer can only be done through an unsafe
block.

{pointer.rs}

### Transmute
Allows simple conversion from one type to another, however both types must have
the same size and alignment:

{transmute.rs}

### Inline Assembly
Inline assembly functions very similarly to the inline assembly of C, which
makes sense considering its implementation is not handled by rust, rather by
the LLVM.  It allows for direct access to assembly manipulation, which can
massively increase speed, but it can also decrease portability and stability.
In most cases the compiler will optimize your rust code to better assembly than
you could write, so in most instances it is not worth it. The first parameter
of asm!() is the format of the assembly, the parameter following the colon is
the output variable, and the parameter(s) following that are the input
variables.

**Note**: `#![feature(asm)]` is currently required to use inline assembly.

{asm.rs}


text:
gnome-terminal -x bash -c "./django.sh"
echo "Django Server is opened"
echo "open TileStache Server"
uwsgi --http :8888 -p 4 --eval 'import TileStache; application = TileStache.WSGITileServer("/home/whu/src/TileStache/tilestache.cfg")'


text:
'use strict';

var gulp = require('gulp');
var args = require('yargs').argv;
var packages = [
  './package.json',
  './bower.json'
];

var $ = require('gulp-load-plugins')();

module.exports = function(options) {
  /**
   * Bump the version
   * --type=pre will bump the prerelease version *.*.*-x
   * --type=patch or no flag will bump the patch version *.*.x
   * --type=minor will bump the minor version *.x.*
   * --type=major will bump the major version x.*.*
   * --version=1.2.3 will bump to a specific version and ignore other flags
   */
  gulp.task('bump', function() {
    var msg = 'Bumping versions';
    var type = args.type;
    var version = args.ver;
    var options = {};
    if (version) {
      options.version = version;
      msg += ' to ' + version;
    } else {
      options.type = type;
      msg += ' for a ' + type;
    }

    return gulp
      .src(packages)
      .pipe($.print())
      .pipe($.bump(options))
      .pipe(gulp.dest('./'));
  });
};


text:
package com.thoughtworks.go.remote.work.artifact;

import com.google.gson.Gson;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import static com.thoughtworks.go.util.GoConstants.PRODUCT_NAME;
import static java.lang.String.format;

public class PluggableArtifactMetadata {
    private static final Logger LOGGER = LoggerFactory.getLogger(PluggableArtifactMetadata.class);
    private Map<String, Map<String, Map>> metadataPerPlugin = new HashMap<>();

    public void addMetadata(String pluginId, String artifactId, Map map) {
        Map<String, Map> metadata = metadataPerPlugin.get(pluginId);

        if (metadata == null) {
            metadata = new HashMap<>();
            metadataPerPlugin.put(pluginId, metadata);
        }

        metadata.put(artifactId, map);
    }

    public Map<String, Map<String, Map>> getMetadataPerPlugin() {
        return metadataPerPlugin;
    }

    public boolean isEmpty() {
        return metadataPerPlugin.isEmpty();
    }

    public File write(File workingDirectory) {
        final File pluggableArtifactMetadataFolder = new File(workingDirectory, UUID.randomUUID().toString());

        if (!pluggableArtifactMetadataFolder.mkdirs()) {
            throw new RuntimeException(format("[%s] Could not create pluggable artifact metadata folder `%s`.", PRODUCT_NAME, pluggableArtifactMetadataFolder.getName()));
        }

        for (Map.Entry<String, Map<String, Map>> entry : this.getMetadataPerPlugin().entrySet()) {
            writeMetadataFile(pluggableArtifactMetadataFolder, entry.getKey(), entry.getValue());
        }

        return pluggableArtifactMetadataFolder;
    }

    private void writeMetadataFile(File pluggableArtifactMetadataFolder, String pluginId, Map<String, Map> responseMetadata) {
        if (responseMetadata == null || responseMetadata.isEmpty()) {
            LOGGER.info(String.format("No metadata to write for plugin `%s`.", pluginId));
            return;
        }

        try {
            LOGGER.info(String.format("Writing metadata file for plugin `%s`.", pluginId));
            FileUtils.writeStringToFile(new File(pluggableArtifactMetadataFolder, format("%s.json", pluginId)), new Gson().toJson(responseMetadata), StandardCharsets.UTF_8);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}


text:
package com.github.maoo.indexer.utils;

import java.util.Iterator;

import org.alfresco.service.cmr.repository.Path;

public class Utils
{

    public static String getSiteName(Path path) {
        //Fetching Path and preparing for rendering
        Iterator<Path.Element> pathIter = path.iterator();

        //Scan the Path to find the Alfresco Site name
        boolean siteFound = false;
        while(pathIter.hasNext()) {
          String pathElement = pathIter.next().getElementString();
          //Stripping out namespace from PathElement
          int firstChar = pathElement.lastIndexOf('}');
          if (firstChar > 0) {
            pathElement = pathElement.substring(firstChar+1);
          }
          if (pathElement.equals("sites")) {
            siteFound = true;
          } else if (siteFound) {
            return pathElement;
          }
        }
        return null;
      }

}


text:
package ro.nextreports.designer.ui.wizard.demo;

import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.util.List;

import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

import ro.nextreports.designer.ui.wizard.WizardPanel;

/**
 * An implementation of the base class used for implementing a panel that is
 * displayed in a Wizard. Shows how to implement a choose file wizard panel.
 *
 * @author Decebal Suiu
 */
public class ChooseFileWizardPanel extends WizardPanel {

	private JTextField fileTextField;

    public ChooseFileWizardPanel() {
        super();
        banner.setTitle("Choose File");
        initComponents();
    }

	/**
     * Called when the panel is set.
     */
    public void onDisplay() {
    }

    /**
     * Is there be a next panel?
     *
     * @return true if there is a panel to move to next
     */
    public boolean hasNext() {
        return false;
    }

    /**
     * Called to validate the panel before moving to next panel.
     *
     * @param messages
     *            a List of messages to be displayed.
     * @return true if the panel is valid,
     */
    public boolean validateNext(List<String> messages) {
    	return true;
    }

    /**
     * Get the next panel to go to.
     */
    public WizardPanel getNextPanel() {
        return null;
    }

    /**
     * Can this panel finish the wizard?
     *
     * @return true if this panel can finish the wizard.
     */
    public boolean canFinish() {
        return true;
    }

    /**
     * Called to validate the panel before finishing the wizard. Should return
     * false if canFinish returns false.
     *
     * @param messages
     *            a List of messages to be displayed.
     * @return true if it is valid for this wizard to finish.
     */
    public boolean validateFinish(List<String> messages) {
        return true;
    }

    /**
     * Handle finishing the wizard.
     */
    public void onFinish() {
    }

    private void initComponents() {
    	setLayout(new FlowLayout(FlowLayout.LEFT, 0, 0));

    	JPanel panel = new JPanel();
    	panel.setLayout(new BoxLayout(panel, BoxLayout.LINE_AXIS));
    	panel.add(new JLabel("File"));
    	panel.add(Box.createHorizontalStrut(6));
    	fileTextField = new JTextField(20);
    	fileTextField.setMaximumSize(fileTextField.getPreferredSize());
    	panel.add(fileTextField);
    	panel.add(Box.createHorizontalStrut(6));
    	JButton browseButton = new JButton("...");
    	browseButton.addActionListener(new ActionListener() {

			public void actionPerformed(ActionEvent event) {
				browse();
			}

    	});
    	panel.add(browseButton);
    	add(panel);
	}

    private void browse() {
        JFileChooser chooser = new JFileChooser();
        int option = chooser.showOpenDialog(this);
        if (option == JFileChooser.APPROVE_OPTION) {
            File selectedFile = chooser.getSelectedFile();
            fileTextField.setText(selectedFile.getPath());
        }
    }

}


text:
package org.wso2.carbon.transport.http.netty.util.client.websocket;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.http.DefaultHttpHeaders;
import io.netty.handler.codec.http.HttpClientCodec;
import io.netty.handler.codec.http.HttpHeaders;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame;
import io.netty.handler.codec.http.websocketx.PingWebSocketFrame;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketClientHandshakerFactory;
import io.netty.handler.codec.http.websocketx.WebSocketVersion;
import io.netty.handler.codec.http.websocketx.extensions.compression.WebSocketClientCompressionHandler;
import io.netty.handler.ssl.SslContext;
import io.netty.handler.ssl.SslContextBuilder;
import io.netty.handler.ssl.util.InsecureTrustManagerFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.wso2.carbon.transport.http.netty.util.TestUtil;

import java.io.IOException;
import java.net.ProtocolException;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.ByteBuffer;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import javax.net.ssl.SSLException;

/**
 * WebSocket client class for test
 */
public class WebSocketTestClient {

    private static final Logger logger = LoggerFactory.getLogger(WebSocketTestClient.class);

    private String url = System.getProperty("url", String.format("ws://%s:%d/%s",
                                                  TestUtil.TEST_HOST, TestUtil.TEST_DEFAULT_INTERFACE_PORT, "test"));
    private final String subProtocol;
    private Map<String, String> customHeaders = new HashMap<>();

    private Channel channel = null;
    private WebSocketClientHandler handler;
    private EventLoopGroup group;
    private CountDownLatch latch;

    public WebSocketTestClient() {
        this.subProtocol = null;
    }

    public WebSocketTestClient(String url) {
        this.url = url;
        this.subProtocol = null;
        if (customHeaders != null) {
            this.customHeaders = customHeaders;
        }
    }

    public WebSocketTestClient(String subProtocol, Map<String, String> customHeaders) {
        this.subProtocol = subProtocol;
        if (customHeaders != null) {
            this.customHeaders = customHeaders;
        }
    }

    public WebSocketTestClient(CountDownLatch latch) {
        this.subProtocol = null;
        this.latch = latch;
    }

    public WebSocketTestClient(String url, CountDownLatch latch) {
        this.url = url;
        this.subProtocol = null;
        if (customHeaders != null) {
            this.customHeaders = customHeaders;
        }
        this.latch = latch;
    }

    public WebSocketTestClient(String subProtocol, Map<String, String> customHeaders, CountDownLatch latch) {
        this.subProtocol = subProtocol;
        if (customHeaders != null) {
            this.customHeaders = customHeaders;
        }
        this.latch = latch;
    }

    /**
     * @return true if the handshake is done properly.
     * @throws URISyntaxException throws if there is an error in the URI syntax.
     * @throws InterruptedException throws if the connecting the server is interrupted.
     */
    public boolean handhshake() throws InterruptedException, URISyntaxException, SSLException, ProtocolException {
        boolean isSuccess;
        URI uri = new URI(url);
        String scheme = uri.getScheme() == null ? "ws" : uri.getScheme();
        final String host = uri.getHost() == null ? "127.0.0.1" : uri.getHost();
        final int port;
        if (uri.getPort() == -1) {
            if ("ws".equalsIgnoreCase(scheme)) {
                port = 80;
            } else if ("wss".equalsIgnoreCase(scheme)) {
                port = 443;
            } else {
                port = -1;
            }
        } else {
            port = uri.getPort();
        }

        if (!"ws".equalsIgnoreCase(scheme) && !"wss".equalsIgnoreCase(scheme)) {
            logger.error("Only WS(S) is supported.");
            return false;
        }

        final boolean ssl = "wss".equalsIgnoreCase(scheme);
        final SslContext sslCtx;
        if (ssl) {
            sslCtx = SslContextBuilder.forClient()
                    .trustManager(InsecureTrustManagerFactory.INSTANCE).build();
        } else {
            sslCtx = null;
        }

        group = new NioEventLoopGroup();

        HttpHeaders headers = new DefaultHttpHeaders();
        customHeaders.entrySet().forEach(
                header -> headers.add(header.getKey(), header.getValue())
        );
        try {
            // Connect with V13 (RFC 6455 aka HyBi-17). You can change it to V08 or V00.
            // If you change it to V00, ping is not supported and remember to change
            // HttpResponseDecoder to WebSocketHttpResponseDecoder in the pipeline.
            handler =
                    new WebSocketClientHandler(
                            WebSocketClientHandshakerFactory.newHandshaker(uri, WebSocketVersion.V13, subProtocol,
                                                                           true, headers), latch);

            Bootstrap b = new Bootstrap();
            b.group(group)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) {
                            ChannelPipeline p = ch.pipeline();
                            if (sslCtx != null) {
                                p.addLast(sslCtx.newHandler(ch.alloc(), host, port));
                            }
                            p.addLast(
                                    new HttpClientCodec(),
                                    new HttpObjectAggregator(8192),
                                    WebSocketClientCompressionHandler.INSTANCE,
                                    handler);
                        }
                    });

            channel = b.connect(uri.getHost(), port).sync().channel();
            isSuccess = handler.handshakeFuture().sync().isSuccess();
            logger.debug("WebSocket Handshake successful : " + isSuccess);
            return isSuccess;
        } catch (Exception e) {
            logger.error("Handshake unsuccessful : " + e.getMessage());
            throw new ProtocolException("Protocol exception: " + e.getMessage());
        }
    }

    /**
     * Send text to the server.
     * @param text text need to be sent.
     */
    public void sendText(String text) {
        if (channel == null) {
            logger.error("Channel is null. Cannot send text.");
            throw new IllegalArgumentException("Cannot find the channel to write");
        }
        channel.writeAndFlush(new TextWebSocketFrame(text));
    }

    /**
     * Send binary data to server.
     * @param buf buffer containing the data need to be sent.
     */
    public void sendBinary(ByteBuffer buf) throws IOException {
        if (channel == null) {
            logger.error("Channel is null. Cannot send text.");
            throw new IllegalArgumentException("Cannot find the channel to write");
        }
        channel.writeAndFlush(new BinaryWebSocketFrame(Unpooled.wrappedBuffer(buf)));
    }

    /**
     * Send a ping message to the server.
     * @param buf content of the ping message to be sent.
     */
    public void sendPing(ByteBuffer buf) throws IOException {
        if (channel == null) {
            logger.error("Channel is null. Cannot send text.");
            throw new IllegalArgumentException("Cannot find the channel to write");
        }
        channel.writeAndFlush(new PingWebSocketFrame(Unpooled.wrappedBuffer(buf)));
    }

    /**
     * @return the text received from the server.
     */
    public String getTextReceived() {
        return handler.getTextReceived();
    }

    /**
     * @return the binary data received from the server.
     */
    public ByteBuffer getBufferReceived() {
        return handler.getBufferReceived();
    }

    /**
     * Check whether the connection is still open or not.
     *
     * @return true if connection is still open.
     */
    public boolean isOpen() {
       return handler.isOpen();
    }

    /**
     * Check whether a ping is received.
     *
     * @return true if a ping is received.
     */
    public boolean isPingReceived() {
        return handler.isPingReceived();
    }

    /**
     * Check whether a ping is received.
     *
     * @return true if a ping is received.
     */
    public boolean isPongReceived() {
        return handler.isPongReceived();
    }

    /**
     * Shutdown the WebSocket Client.
     */
    public void shutDown() throws InterruptedException {
        handler.shutDown();
        group.shutdownGracefully();
    }

}


text:
/*
 * Powered By cuichen
 * Since 2014 - 2016
 */
package com.seeyoui.kensite.framework.plugin.connCenter.controller;

import java.sql.Connection;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.seeyoui.kensite.common.base.controller.BaseController;
import com.seeyoui.kensite.common.base.domain.EasyUIDataGrid;
import com.seeyoui.kensite.common.base.domain.Page;
import com.seeyoui.kensite.common.constants.StringConstant;
import com.seeyoui.kensite.common.util.DBUtils;
import com.seeyoui.kensite.common.util.DateUtils;
import com.seeyoui.kensite.common.util.RequestResponseUtil;
import com.seeyoui.kensite.common.util.excel.ExportExcel;
import com.seeyoui.kensite.framework.plugin.connCenter.domain.ConnCenter;
import com.seeyoui.kensite.framework.plugin.connCenter.service.ConnCenterService;
import com.seeyoui.kensite.framework.plugin.connCenter.util.CCUtils;
/**
 * 数据库连接中心
 * @author cuichen
 * @version 2.0
 * @since 1.0
 * @date 2016-09-27
 */

@Controller
@RequestMapping(value = "ks/connCenter")
public class ConnCenterController extends BaseController {

	@Autowired
	private ConnCenterService connCenterService;

	/**
	 * 展示列表页面
	 * @param modelMap
	 * @param module
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/{page}")
	public ModelAndView view(HttpSession session,
			HttpServletResponse response, HttpServletRequest request,
			ModelMap modelMap, @PathVariable String page) throws Exception {
		return new ModelAndView("framework/plugin/connCenter/"+page, modelMap);
	}

	/**
	 * 根据ID查询单条数据
	 * @param modelMap
	 * @param module
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/data/{id}")
	@ResponseBody
	public Object data(HttpSession session,
			HttpServletResponse response, HttpServletRequest request,
			ModelMap modelMap, @PathVariable String id) throws Exception {
		ConnCenter connCenter = connCenterService.findOne(id);
		return connCenter;
	}

	/**
	 * 获取列表展示数据
	 * @param modelMap
	 * @param connCenter
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/list/data", method=RequestMethod.POST)
	@ResponseBody
	public Object listData(HttpSession session,
			HttpServletResponse response, HttpServletRequest request,
			ModelMap modelMap, ConnCenter connCenter) throws Exception {
		List<ConnCenter> connCenterList = connCenterService.findList(connCenter);
		int total = connCenterService.findTotal(connCenter);
		EasyUIDataGrid eudg = new EasyUIDataGrid();
		eudg.setTotal(String.valueOf(total));
		eudg.setRows(connCenterList);
		return eudg;
	}

	/**
	 * 获取列表展示数据带分页器用于jsp自己做分页
	 * @param modelMap
	 * @param connCenter
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/list/page", method=RequestMethod.POST)
	@ResponseBody
	public Object listPage(HttpSession session,
			HttpServletResponse response, HttpServletRequest request,
			ModelMap modelMap, ConnCenter connCenter) throws Exception {
		List<ConnCenter> connCenterList = connCenterService.findList(connCenter);
		int total = connCenterService.findTotal(connCenter);
		Page<ConnCenter> page = new Page<ConnCenter>(connCenter.getPage(), connCenter.getRows(), total);
		Map<String, Object> dataMap = new HashMap<String, Object>();
		dataMap.put("rows", connCenterList);
		dataMap.put("page", page);
		return dataMap;
	}

	/**
	 * 获取所有数据
	 * @param modelMap
	 * @param connCenter
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/list/all", method=RequestMethod.POST)
	@ResponseBody
	public Object listAll(HttpSession session,
			HttpServletResponse response, HttpServletRequest request,
			ModelMap modelMap, ConnCenter connCenter) throws Exception {
		List<ConnCenter> connCenterList = connCenterService.findAll(connCenter);
		return connCenterList;
	}

	/**
	 * 保存新增的数据
	 * @param modelMap
	 * @param connCenter
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/save", method=RequestMethod.POST)
	@ResponseBody
	public String save(HttpSession session,
			HttpServletResponse response, HttpServletRequest request,
			ModelMap modelMap, ConnCenter connCenter) throws Exception {
		if (!beanValidator(modelMap, connCenter)){
			RequestResponseUtil.putResponseStr(session, response, request, modelMap, StringConstant.FALSE);
			return null;
		}
		connCenterService.save(connCenter);
		RequestResponseUtil.putResponseStr(session, response, request, modelMap, StringConstant.TRUE);
		return null;
	}

	/**
	 * 保存修改的数据
	 * @param modelMap
	 * @param connCenter
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/update", method=RequestMethod.POST)
	@ResponseBody
	public String update(HttpSession session,
			HttpServletResponse response, HttpServletRequest request,
			ModelMap modelMap, ConnCenter connCenter) throws Exception {
		if (!beanValidator(modelMap, connCenter)){
			RequestResponseUtil.putResponseStr(session, response, request, modelMap, StringConstant.FALSE);
			return null;
		}
		connCenterService.update(connCenter);
		RequestResponseUtil.putResponseStr(session, response, request, modelMap, StringConstant.TRUE);
		return null;
	}

	/**
	 * 删除数据库
	 * @param modelMap
	 * @param connCenterId
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/delete", method=RequestMethod.POST)
	@ResponseBody
	public String delete(HttpSession session,
			HttpServletResponse response, HttpServletRequest request,
			ModelMap modelMap, String id) throws Exception {
		List<String> listId = Arrays.asList(id.split(","));
		connCenterService.delete(listId);
		RequestResponseUtil.putResponseStr(session, response, request, modelMap, StringConstant.TRUE);
		return null;
	}

	/**
	 * 导出Excel数据
	 * @param modelMap
	 * @param connCenter
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/export")
	public String export(HttpSession session,
			HttpServletResponse response, HttpServletRequest request,
			ModelMap modelMap, ConnCenter connCenter) throws Exception {
		String fileName = DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
		List<ConnCenter> connCenterList = connCenterService.findAll(connCenter);
		new ExportExcel(null, ConnCenter.class).setDataList(connCenterList).write(response, fileName).dispose();
		return null;
	}

	/**
	 * 测试数据库连接
	 * @param modelMap
	 * @param id
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/conn")
	@ResponseBody
	public String conn(HttpSession session,
			HttpServletResponse response, HttpServletRequest request,
			ModelMap modelMap, String id) throws Exception {
		Connection conn = CCUtils.getConnection(id);
//		System.out.println(conn);
//		System.out.println(DBUtils.getString(conn, "select * from sys_user where user_name like 'system'", "name", true));
		if(conn == null) {
			RequestResponseUtil.putResponseStr(session, response, request, modelMap, StringConstant.FALSE);
			return null;
		} else {
			DBUtils.close(conn, null, null);
			RequestResponseUtil.putResponseStr(session, response, request, modelMap, StringConstant.TRUE);
			return null;
		}
	}
}


text:
import re
import threading
import unittest

from django.db import connection
from django.db.models import Avg, StdDev, Sum, Variance
from django.db.models.fields import CharField
from django.db.utils import NotSupportedError
from django.test import TestCase, TransactionTestCase, override_settings
from django.test.utils import isolate_apps

from ..models import Author, Item, Object, Square

@unittest.skipUnless(connection.vendor == 'sqlite', 'SQLite tests')
class Tests(TestCase):
    longMessage = True

    def test_autoincrement(self):
        """
        auto_increment fields are created with the AUTOINCREMENT keyword
        in order to be monotonically increasing (#10164).
        """
        with connection.schema_editor(collect_sql=True) as editor:
            editor.create_model(Square)
            statements = editor.collected_sql
        match = re.search('"id" ([^,]+),', statements[0])
        self.assertIsNotNone(match)
        self.assertEqual(
            'integer NOT NULL PRIMARY KEY AUTOINCREMENT',
            match.group(1),
            'Wrong SQL used to create an auto-increment column on SQLite'
        )

    def test_aggregation(self):
        """
        Raise NotImplementedError when aggregating on date/time fields (#19360).
        """
        for aggregate in (Sum, Avg, Variance, StdDev):
            with self.assertRaises(NotSupportedError):
                Item.objects.all().aggregate(aggregate('time'))
            with self.assertRaises(NotSupportedError):
                Item.objects.all().aggregate(aggregate('date'))
            with self.assertRaises(NotSupportedError):
                Item.objects.all().aggregate(aggregate('last_modified'))
            with self.assertRaises(NotSupportedError):
                Item.objects.all().aggregate(
                    **{'complex': aggregate('last_modified') + aggregate('last_modified')}
                )

    def test_memory_db_test_name(self):
        """A named in-memory db should be allowed where supported."""
        from django.db.backends.sqlite3.base import DatabaseWrapper
        settings_dict = {
            'TEST': {
                'NAME': 'file:memorydb_test?mode=memory&cache=shared',
            }
        }
        creation = DatabaseWrapper(settings_dict).creation
        self.assertEqual(creation._get_test_db_name(), creation.connection.settings_dict['TEST']['NAME'])

@unittest.skipUnless(connection.vendor == 'sqlite', 'SQLite tests')
@isolate_apps('backends')
class SchemaTests(TransactionTestCase):

    available_apps = ['backends']

    def test_field_rename_inside_atomic_block(self):
        """
        NotImplementedError is raised when a model field rename is attempted
        inside an atomic block.
        """
        new_field = CharField(max_length=255, unique=True)
        new_field.set_attributes_from_name('renamed')
        msg = (
            "Renaming the 'backends_author'.'name' column while in a "
            "transaction is not supported on SQLite because it would break "
            "referential integrity. Try adding `atomic = False` to the "
            "Migration class."
        )
        with self.assertRaisesMessage(NotSupportedError, msg):
            with connection.schema_editor(atomic=True) as editor:
                editor.alter_field(Author, Author._meta.get_field('name'), new_field)

    def test_table_rename_inside_atomic_block(self):
        """
        NotImplementedError is raised when a table rename is attempted inside
        an atomic block.
        """
        msg = (
            "Renaming the 'backends_author' table while in a transaction is "
            "not supported on SQLite because it would break referential "
            "integrity. Try adding `atomic = False` to the Migration class."
        )
        with self.assertRaisesMessage(NotSupportedError, msg):
            with connection.schema_editor(atomic=True) as editor:
                editor.alter_db_table(Author, "backends_author", "renamed_table")

@unittest.skipUnless(connection.vendor == 'sqlite', 'Test only for SQLite')
@override_settings(DEBUG=True)
class LastExecutedQueryTest(TestCase):

    def test_no_interpolation(self):
        # This shouldn't raise an exception (#17158)
        query = "SELECT strftime('%Y', 'now');"
        connection.cursor().execute(query)
        self.assertEqual(connection.queries[-1]['sql'], query)

    def test_parameter_quoting(self):
        # The implementation of last_executed_queries isn't optimal. It's
        # worth testing that parameters are quoted (#14091).
        query = "SELECT %s"
        params = ["\"'\\"]
        connection.cursor().execute(query, params)
        # Note that the single quote is repeated
        substituted = "SELECT '\"''\\'"
        self.assertEqual(connection.queries[-1]['sql'], substituted)

    def test_large_number_of_parameters(self):
        # If SQLITE_MAX_VARIABLE_NUMBER (default = 999) has been changed to be
        # greater than SQLITE_MAX_COLUMN (default = 2000), last_executed_query
        # can hit the SQLITE_MAX_COLUMN limit (#26063).
        with connection.cursor() as cursor:
            sql = "SELECT MAX(%s)" % ", ".join(["%s"] * 2001)
            params = list(range(2001))
            # This should not raise an exception.
            cursor.db.ops.last_executed_query(cursor.cursor, sql, params)

@unittest.skipUnless(connection.vendor == 'sqlite', 'SQLite tests')
class EscapingChecks(TestCase):
    """
    All tests in this test case are also run with settings.DEBUG=True in
    EscapingChecksDebug test case, to also test CursorDebugWrapper.
    """
    def test_parameter_escaping(self):
        # '%s' escaping support for sqlite3 (#13648).
        with connection.cursor() as cursor:
            cursor.execute("select strftime('%s', date('now'))")
            response = cursor.fetchall()[0][0]
        # response should be an non-zero integer
        self.assertTrue(int(response))

@unittest.skipUnless(connection.vendor == 'sqlite', 'SQLite tests')
@override_settings(DEBUG=True)
class EscapingChecksDebug(EscapingChecks):
    pass

@unittest.skipUnless(connection.vendor == 'sqlite', 'SQLite tests')
class ThreadSharing(TransactionTestCase):
    available_apps = ['backends']

    def test_database_sharing_in_threads(self):
        def create_object():
            Object.objects.create()
        create_object()
        thread = threading.Thread(target=create_object)
        thread.start()
        thread.join()
        self.assertEqual(Object.objects.count(), 2)


text:
package com.felipecsl.asymmetricgridview.library;

import android.os.Parcelable;

public interface AsymmetricGridViewAdapterContract {
    public void recalculateItemsPerRow();

    public Parcelable saveState();

    public void restoreState(final Parcelable state);
}


text:
define(['angular','common/module-name'], function (angular,moduleName) {
    return angular.module(moduleName).service('StepperService', function () {

        var self = this;
        /**
         * subscribers of this event will get the following data passed to them
         * current  - number datatype
         * @type {string}
         */
        this.ACTIVE_STEP_EVENT = 'ACTIVE_STEP_EVENT';
        /**
         * subscribers of this event will get the following data passed to them:
         * {newStep:current,oldStep:old}
         * newStep - number datatype
         * oldStep - number datatype
         * @type {string}
         */
        this.STEP_CHANGED_EVENT = 'STEP_CHANGED_EVENT';

        /**
         * Event called when a step is enabled or disabled
         * @type {string}
         */
        this.STEP_STATE_CHANGED_EVENT = 'STEP_STATE_CHANGED_EVENT';

        /**
         * Map of stepper Name  -> to Array of Steps
         * @type {{}}
         */
        this.steppers = {};

        /**
         * Map of stepper name  -> {stepName,step}
         * populated only with self.assignStepNames
         * @type {{}}
         */
        this.stepperNameMap = {};

        this.newNameIndex = 0;
        this.registerStepper = function (name, totalSteps) {
            var steps = [];
            self.steppers[name] = steps;
            this.stepperNameMap[name] = {};
            var lastIndex = totalSteps - 1;
            var disabled = false;
            for (var i = 0; i < totalSteps; i++) {
                if (i > 0) {
                    disabled = true;
                }

                steps[i] = {
                    disabled: disabled,
                    stepName:null,
                    active: true,
                    number: (i + 1),
                    index: i,
                    icon: 'number' + (i + 1),
                    iconSize: 30,
                    nextActiveStepIndex: (i != lastIndex) ? (i + 1) : null,
                    previousActiveStepIndex: (i != 0) ? i - 1 : null,
                    visited: false,
                    complete: false,
                    updateStepType: function () {
                        if (this.complete == true && this.visited == true && this.active && !this.disabled) {
                            this.type = 'step-complete';
                            this.icon = 'check'
                            this.iconSize = 20;
                            this.iconStyle = '#F08C38';
                        }
                        else {
                            this.type = 'step-default';
                            this.icon = 'number'+ (this.number);
                            this.iconSize = 30;
                            this.iconStyle = '';
                        }
                    },
                    reset: function () {
                        this.complete = false;
                        this.visited = false;
                        this.updateStepType();
                    }
                };
            }
        }
        this.assignStepName = function(name, index, stepName){
            var step = self.getStep(name,index);
            if(step != null && step.stepName == null){
                step.stepName = stepName;
                self.assignedStepName(name,step)
            }
        };
        this.assignedStepName = function(name, step){
            if(step != null && step.stepName != null){
                 //register the step to the name map index
                self.stepperNameMap[name][step.stepName] = step;
            }
        };
        /**
         * get a step by its name.
         * Could be null
         * @param stepperName
         * @param stepName
         */
        this.getStepByName=function(stepperName,stepName){
            if(angular.isDefined(self.stepperNameMap[stepperName])){
                return  self.stepperNameMap[stepperName][stepName];
            }
            else {
                return null;
            }
        };
        this.deRegisterStepper = function (name) {
            delete self.steppers[name];
            delete self.stepperNameMap[name]
        }
        this.newStepperName = function () {
            self.newNameIndex++;
            return 'stepper_' + self.newNameIndex;
        }
        this.getStep = function (stepperName, index) {
            if (typeof index == 'string') {
                index = parseInt(index);
            }
            var steps = self.steppers[stepperName];
            if (steps != null && steps.length > 0) {
                if (index != null && index >= 0 && index < steps.length) {
                    return steps[index]
                }

            }
            return null;
        }
        this.getSteps = function (stepper) {
            return this.steppers[stepper];
        }

        this.updatePreviousNextActiveStepIndexes = function (stepper) {
            var steps = self.steppers[stepper];
            if (steps != null && steps.length > 0) {
                for (var i = 0; i < steps.length; i++) {
                    var step = steps[i];
                    var previousActiveStep = self.previousActiveStep(stepper, i);
                    if (previousActiveStep != null) {
                        step.previousActiveStepIndex = previousActiveStep.index;
                    }
                    else {
                        step.previousActiveStepIndex = null;
                    }

                    var nextActiveStep = self.nextActiveStep(stepper, i);
                    if (nextActiveStep != null) {
                        step.nextActiveStepIndex = nextActiveStep.index;
                    }
                    else {
                        step.nextActiveStepIndex = null;
                    }
                }
            }
        }

        this.deactivateStep = function (stepper, index) {
            var step = self.getStep(stepper, index);
            if (step != null) {
                step.active = false;
                step.disabled = true;
                self.updatePreviousNextActiveStepIndexes(stepper, index);
            }
        }

        this.activateStep = function (stepper, index) {
            var step = self.getStep(stepper, index);
            if (step != null) {
                step.active = true;
                self.updatePreviousNextActiveStepIndexes(stepper, index);
            }
        }

        this.stepDisabled = function (stepper, index) {
            var step = self.getStep(stepper, index);
            if (step != null) {
                step.disabled = true;
            }

        }
        this.stepEnabled = function (stepper, index) {
            var step = self.getStep(stepper, index);
            if (step != null && step.active) {
                step.disabled = false;
            }

        }

        this.arePreviousVisitedStepsComplete = function (stepper, index) {
            var complete = true;
            var steps = self.steppers[stepper];
            for (var i = 0; i < index; i++) {
                var step = steps[i];
                if (step.active && !step.complete && step.visited) {
                    complete = false;
                    break;
                }
            }
            return complete;
        }

        this.arePreviousStepsComplete = function (stepper, index) {
            var complete = true;
            var steps = self.steppers[stepper];
            for (var i = 0; i < index; i++) {
                var step = steps[i];
                if (step.active && !step.disabled && !step.complete) {
                    complete = false;
                    break;
                }
            }
            return complete;
        }

        this.arePreviousStepsVisited = function (stepper, index) {
            var complete = true;
            var steps = self.steppers[stepper];
            for (var i = 0; i < index; i++) {
                var step = steps[i];
                if (step.active && !step.visited) {
                    complete = false;
                    break;
                }
            }
            return complete;
        }

        this.arePreviousStepsDisabled = function (stepper, index) {
            var disabled = false;
            var steps = self.steppers[stepper];
            for (var i = 0; i < index; i++) {
                var step = steps[i];
                if (step.disabled) {
                    disabled = true;
                    break;
                }
            }
            return disabled;
        }

        this.previousActiveStep = function (stepperName, index) {
            var previousIndex = index - 1;
            var previousEnabledStep = null;
            var previousEnabledStepIndex = null;
            if (previousIndex >= 0) {
                var steps = self.steppers[stepperName];
                for (var i = previousIndex; i >= 0; i--) {
                    var step = steps[i];
                    if (step.active) {
                        previousEnabledStep = step;
                        previousEnabledStepIndex = i;
                        break;
                    }
                }
                return previousEnabledStep;
            }
            else {
                return null;
            }
        }

        this.nextActiveStep = function (stepperName, index) {
            var nextIndex = index + 1;
            var nextEnabledStep = null;
            var nextEnabledStepIndex = null;
            var steps = self.steppers[stepperName];
            if (nextIndex < steps.length) {
                for (var i = nextIndex; i < steps.length; i++) {
                    var step = steps[i];
                    if (step.active) {
                        nextEnabledStep = step;
                        nextEnabledStepIndex = i;
                        break;
                    }
                }
                return nextEnabledStep;
            }
            else {
                return null;
            }

        }

    });
});


text:
using Microsoft.Practices.Unity;
using MoviePicker.Common;
using MoviePicker.Common.Interfaces;
using MoviePicker.Msf;

namespace XUnitTests
{
	public class MsfMoviePickerValidationTestsContext : MoviePickerValidationTestsContext
	{
		public MsfMoviePickerValidationTestsContext()
		{
			SetupContainer();
		}
		protected sealed override void SetupContainer()
		{
			UnityContainer.RegisterType<IMovie, Movie>();
			UnityContainer.RegisterType<IMovieList, MovieList>();
			UnityContainer.RegisterType<IMoviePicker, MsfMovieSolver>();
		}
	}
}


text:
struct CEventItemBagAttr {
    CEventItemBagAttr() {
        this->m_btType = 0;
        this->m_btIndex = 0;
        this->m_btMinLevel = 0;
        this->m_btMaxLevel = 0;
        this->m_btIsSkill = 0;
        this->m_btIsLuck = 0;
        this->m_btIsOption = 0;
        this->m_btIsExItem = 0;
        this->m_btIsSetItem = 0;
        this->m_nDropRate = 0;
    }

    BYTE m_btType;
    BYTE m_btIndex;
    BYTE m_btMinLevel;
    BYTE m_btMaxLevel;
    BYTE m_btIsSkill;
    BYTE m_btIsLuck;
    BYTE m_btIsOption;
    BYTE m_btIsExItem;
    BYTE m_btIsSetItem;
    DWORD m_nDropRate;
};

struct _stEventDungeonItemInfo {
    _stEventDungeonItemInfo() {
        this->m_bUse = FALSE;
        this->m_nLevelIndex = 0;
        this->m_nMinLevel = 0;
        this->m_nMaxLevel = 0;
        this->m_nDropZen = -1;
        this->m_nDropCount = 0;
    }

    BOOL m_bUse;
    DWORD m_nLevelIndex;
    DWORD m_nMinLevel;
    DWORD m_nMaxLevel;
    int m_nDropZen;
    DWORD m_nDropCount;
    DWORD m_nExOptionAddCntRate;
    std::vector <CEventItemBagAttr> m_vtItemBagAttr;
};

class CEventDungeonItemBag {
public:
    CEventDungeonItemBag(void);

    virtual ~CEventDungeonItemBag(void);

    void LoadScript(char *szFileName);

    int DropEventItem(int nIndex, int nMaxUserLevel);

private:

    int GetLevelIndex(int nUserLevel);

    int GetRegItemCount(int nUserLevel);

    int GetDropZen(int nUserLevel);

    int GetDropItemCount(int nUserLevel);

    int GetExcDropRate(int nUserLevel);

    int GetLevel(int nMinLevel, int nMaxLevel);

    int CreateNormalItem(int nIndex, int nMaxUserLevel, CEventItemBagAttr BagObject);

    int CreateSetItem(int nIndex, CEventItemBagAttr BagObject);

    BOOL m_bLoad;
    _stEventDungeonItemInfo eventDungeonItemInfo[10];
};


text:
module Admin
  class Dashboard < Base
    skip_before :login_required
    before :check_for_user

    def index
      @activity = Activity.all(:order => [:created_at.desc], :limit => 5)
      display @activity
    end

    private
      ##
      # This checks to see if there are no users (such as when it's a fresh install) - if so, it creates a default user and redirects the user to login with those details
      def check_for_user
        if User.count == 0
          User.create({:login => "admin", :password => "password", :password_confirmation => "password", :name => 'blog owner', :email => "none@none", :time_zone => "Europe/London"})
          # Display the newly created users details
          notify "No users found, so default user created: authenticate with login \"admin\", password \"password\", and then change your password."
        end
        login_required
      end
  end
end


text:
class Family < ActiveRecord::Base
  has_many :family_trees, -> { where(token: nil) }
  has_many :members, through: :family_trees
end


text:
@interface FUWindowToolbar : NSToolbar {

}

@end


text:
package org.apereo.cas.ticket.registry;

import net.spy.memcached.MemcachedClientIF;
import org.apache.commons.pool2.ObjectPool;
import org.apereo.cas.ticket.Ticket;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.PreDestroy;
import java.util.ArrayList;
import java.util.Collection;

/**
 * Key-value ticket registry implementation that stores tickets in memcached keyed on the ticket ID.
 *
 * @author Scott Battaglia
 * @author Marvin S. Addison
 * @since 3.3
 */
public class MemcachedTicketRegistry extends AbstractTicketRegistry {
    private static final Logger LOGGER = LoggerFactory.getLogger(MemcachedTicketRegistry.class);
    /**
     * Memcached client.
     */
    private final ObjectPool<MemcachedClientIF> connectionPool;

    /**
     * Creates a new instance using the given memcached client instance, which is presumably configured via
     * {@code net.spy.memcached.spring.MemcachedClientFactoryBean}.
     *
     * @param client Memcached client.
     */
    public MemcachedTicketRegistry(final ObjectPool<MemcachedClientIF> client) {
        this.connectionPool = client;
    }

    @Override
    public Ticket updateTicket(final Ticket ticketToUpdate) {
        final Ticket ticket = encodeTicket(ticketToUpdate);
        LOGGER.debug("Updating ticket [{}]", ticket);
        final MemcachedClientIF clientFromPool = getClientFromPool();
        try {
            clientFromPool.replace(ticket.getId(), getTimeout(ticketToUpdate), ticket);
        } catch (final Exception e) {
            LOGGER.error("Failed updating [{}]", ticket, e);
        } finally {
            returnClientToPool(clientFromPool);
        }
        return ticket;
    }

    @Override
    public void addTicket(final Ticket ticketToAdd) {
        final MemcachedClientIF clientFromPool = getClientFromPool();
        try {
            final Ticket ticket = encodeTicket(ticketToAdd);
            LOGGER.debug("Adding ticket [{}]", ticket);
            clientFromPool.set(ticket.getId(), getTimeout(ticketToAdd), ticket);
        } catch (final Exception e) {
            LOGGER.error("Failed adding [{}]", ticketToAdd, e);
        } finally {
            returnClientToPool(clientFromPool);
        }
    }

    @Override
    public long deleteAll() {
        LOGGER.debug("deleteAll() isn't supported. Returning empty list");
        return 0;
    }

    @Override
    public boolean deleteSingleTicket(final String ticketIdToDelete) {
        final MemcachedClientIF clientFromPool = getClientFromPool();
        final String ticketId = encodeTicketId(ticketIdToDelete);
        try {
            clientFromPool.delete(ticketId);
        } catch (final Exception e) {
            LOGGER.error("Ticket not found or is already removed. Failed deleting [{}]", ticketId, e);
        } finally {
            returnClientToPool(clientFromPool);
        }
        return true;
    }

    @Override
    public Ticket getTicket(final String ticketIdToGet) {
        final MemcachedClientIF clientFromPool = getClientFromPool();
        final String ticketId = encodeTicketId(ticketIdToGet);
        try {
            final Ticket ticketFromCache = (Ticket) clientFromPool.get(ticketId);
            if (ticketFromCache != null) {
                final Ticket result = decodeTicket(ticketFromCache);
                if (result != null && result.isExpired()) {
                    LOGGER.debug("Ticket [{}] has expired and is now removed from the memcached", result.getId());
                    deleteSingleTicket(ticketId);
                    return null;
                }
                return result;
            }
        } catch (final Exception e) {
            LOGGER.error("Failed fetching [{}] ", ticketId, e);
        } finally {
            returnClientToPool(clientFromPool);
        }
        return null;
    }

    @Override
    public Collection<Ticket> getTickets() {
        LOGGER.debug("getTickets() isn't supported. Returning empty list");
        return new ArrayList<>(0);
    }

    /**
     * Destroy the client and shut down.
     */
    @PreDestroy
    public void destroy() {
        this.connectionPool.close();
    }

    /**
     * If not time out value is specified, expire the ticket immediately.
     *
     * @param ticket the ticket
     * @return timeout in milliseconds.
     */
    private static int getTimeout(final Ticket ticket) {
        final int ttl = ticket.getExpirationPolicy().getTimeToLive().intValue();
        if (ttl == 0) {
            return 1;
        }
        return ttl;
    }

    private MemcachedClientIF getClientFromPool() {
        try {
            return this.connectionPool.borrowObject();
        } catch (final Exception e) {
            throw new RuntimeException(e.getMessage(), e);
        }
    }

    private void returnClientToPool(final MemcachedClientIF clientFromPool) {
        try {
            if (clientFromPool != null) {
                this.connectionPool.returnObject(clientFromPool);
            }
        } catch (final Exception e) {
            LOGGER.error(e.getMessage(), e);
        }
    }
}


text:
<ivy-module version="2.0">
	<info organisation="projectlombok.org" module="spi" revision="0.2.4" publication="20100419062500">
		<license name="Apache License v2.0" url="http://www.apache.org/licenses/LICENSE-2.0" />
		<description homepage="http://code.google.com/p/spi/" />
	</info>
	<configurations>
		<conf name="build" />
	</configurations>
	<publications>
		<artifact conf="build" url="http://projectlombok.org/ivyrepo/tools/spi-0.2.4.jar" />
	</publications>
</ivy-module>


text:
A Databox driver to stream data from twitter. This driver supports twitter streaming API and usess app auth.

Its provides an example of settings persistance and the use of datasources. It also has a test actuator.

# Status

This is work in progress but getting better ;-).

# Authentication

If you wish to use this driver with your own twitter account then.

     - Go to https://apps.twitter.com/ and log in
     - Click create new app
     - Fill in the form (set website to http://127.0.0.1) agree to the T&C's
     - Then go to the 'Keys and Access Tokens' tab
     - Click on "Create my access token"
     - Then in databox find the driver tab and click on the twitter driver
     - Copy and past Consumer Key, Consumer Secret, Access Token, Access Token Secret into the driver and click save.

# Data stored
This driver writes twitter event data into a databox-store-blob for later processing.

It saves the following streams of data:

    1. twitterUserTimeLine - the logged in users timeline
    2. twitterHashTagStream - tweets that contain #raspberrypi, #mozfest, #databox, #iot and #NobelPrize
    3. twitterDirectMessage - a list of the users' direct messages
    4. twittrRetweet - a list of the users' retweets
    5. twitterFavorite - a list of the users favourited

These can then be accessed databox-store-blob API.