text:
/**
 * Similar to env1, an Environment with a customer- and an order-Database
 * is created; a third Database is created which manages the 1:n relationship
 * between the other two.
 */

#include <stdio.h>
#include <string.h>
#include <stdlib.h> /* for exit() */
#include <ups/upscaledb.h>

void
error(const char *foo, ups_status_t st) {
  printf("%s() returned error %d: %s\n", foo, st, ups_strerror(st));
  exit(-1);
}

#define MAX_DBS           3

#define DBNAME_CUSTOMER   1
#define DBNAME_ORDER      2
#define DBNAME_C2O        3   /* C2O: Customer To Order */

#define DBIDX_CUSTOMER    0
#define DBIDX_ORDER       1
#define DBIDX_C2O         2

#define MAX_CUSTOMERS     4
#define MAX_ORDERS        8

/* A structure for the "customer" database */
typedef struct {
  uint32_t id;         /* customer id; will be the key of the customer table */
  char name[32];        /* customer name */
  /* ... additional information could follow here */
} customer_t;

/* A structure for the "orders" database */
typedef struct {
  uint32_t id;         /* order id; will be the key of the order table */
  uint32_t customer_id;/* customer id */
  char assignee[32];    /* assigned to whom? */
  /* ... additional information could follow here */
} order_t;

int
main(int argc, char **argv) {
  int i;
  ups_status_t st;               /* status variable */
  ups_db_t *db[MAX_DBS];         /* upscaledb database objects */
  ups_env_t *env;                /* upscaledb environment */
  ups_cursor_t *cursor[MAX_DBS]; /* a cursor for each database */
  ups_key_t key = {0};
  ups_key_t cust_key = {0};
  ups_key_t ord_key = {0};
  ups_key_t c2o_key = {0};
  ups_record_t record = {0};
  ups_record_t cust_record = {0};
  ups_record_t ord_record = {0};
  ups_record_t c2o_record = {0};

  ups_parameter_t params[] = {
    {UPS_PARAM_KEY_TYPE, UPS_TYPE_UINT32},
    {0, }
  };

  ups_parameter_t c2o_params[] = {
    {UPS_PARAM_KEY_TYPE, UPS_TYPE_UINT32},
    {UPS_PARAM_RECORD_SIZE, sizeof(uint32_t)},
    {0, }
  };

  customer_t customers[MAX_CUSTOMERS] = {
    { 1, "Alan Antonov Corp." },
    { 2, "Barry Broke Inc." },
    { 3, "Carl Caesar Lat." },
    { 4, "Doris Dove Brd." }
  };

  order_t orders[MAX_ORDERS] = {
    { 1, 1, "Joe" },
    { 2, 1, "Tom" },
    { 3, 3, "Joe" },
    { 4, 4, "Tom" },
    { 5, 3, "Ben" },
    { 6, 3, "Ben" },
    { 7, 4, "Chris" },
    { 8, 1, "Ben" }
  };

  /* Now create a new database file for the Environment */
  st = ups_env_create(&env, "test.db", 0, 0664, 0);
  if (st != UPS_SUCCESS)
    error("ups_env_create", st);

  /*
   * Then create the two Databases in this Environment; each Database
   * has a name - the first is our "customer" Database, the second
   * is for the "orders"; the third manages our 1:n relation and
   * therefore needs to enable duplicate keys
   */
  st = ups_env_create_db(env, &db[DBIDX_CUSTOMER], DBNAME_CUSTOMER,
                  0, &params[0]);
  if (st != UPS_SUCCESS)
    error("ups_env_create_db(customer)", st);
  st = ups_env_create_db(env, &db[DBIDX_ORDER], DBNAME_ORDER, 0, &params[0]);
  if (st != UPS_SUCCESS)
    error("ups_env_create_db(order)", st);
  st = ups_env_create_db(env, &db[DBIDX_C2O], DBNAME_C2O,
                  UPS_ENABLE_DUPLICATE_KEYS, &c2o_params[0]);
  if (st != UPS_SUCCESS)
    error("ups_env_create_db(c2o)", st);

  /* Create a Cursor for each Database */
  for (i = 0; i < MAX_DBS; i++) {
    st = ups_cursor_create(&cursor[i], db[i], 0, 0);
    if (st != UPS_SUCCESS)
      error("ups_cursor_create" , st);
  }

  /*
   * Insert the customers in the customer table
   *
   * INSERT INTO customers VALUES (1, "Alan Antonov Corp.");
   * INSERT INTO customers VALUES (2, "Barry Broke Inc.");
   * etc
   */
  for (i = 0; i < MAX_CUSTOMERS; i++) {
    key.size = sizeof(int);
    key.data = &customers[i].id;

    record.size = sizeof(customer_t);
    record.data = &customers[i];

    st = ups_db_insert(db[0], 0, &key, &record, 0);
    if (st != UPS_SUCCESS)
      error("ups_db_insert (customer)", st);
  }

  /*
   * And now the orders in the second Database; contrary to env1,
   * we only store the assignee, not the whole structure
   *
   * INSERT INTO orders VALUES (1, "Joe");
   * INSERT INTO orders VALUES (2, "Tom");
   */
  for (i = 0; i < MAX_ORDERS; i++) {
    key.size = sizeof(int);
    key.data = &orders[i].id;

    record.size = sizeof(orders[i].assignee);
    record.data = orders[i].assignee;

    st = ups_db_insert(db[1], 0, &key, &record, 0);
    if (st != UPS_SUCCESS)
      error("ups_db_insert (order)", st);
  }

  /*
   * And now the 1:n relationships; the flag UPS_DUPLICATE creates
   * a duplicate key, if the key already exists
   *
   * INSERT INTO c2o VALUES (1, 1);
   * INSERT INTO c2o VALUES (2, 1);
   * etc
   */
  for (i = 0; i < MAX_ORDERS; i++) {
    key.size = sizeof(int);
    key.data = &orders[i].customer_id;

    record.size = sizeof(int);
    record.data = &orders[i].id;

    st = ups_db_insert(db[2], 0, &key, &record, UPS_DUPLICATE);
    if (st != UPS_SUCCESS)
      error("ups_db_insert(c2o)", st);
  }

  /*
   * Now start the query - we want to dump each customer with his
   * orders
   *
   * loop over the customer; for each customer, loop over the 1:n table
   * and pick those orders with the customer id. then load the order
   * and print it
   *
   * the outer loop is similar to:
   *  SELECT * FROM customers WHERE 1;
   */
  while (1) {
    customer_t *customer;

    st = ups_cursor_move(cursor[0], &cust_key, &cust_record, UPS_CURSOR_NEXT);
    if (st != UPS_SUCCESS) {
      /* reached end of the database? */
      if (st == UPS_KEY_NOT_FOUND)
        break;
      else
        error("ups_cursor_next(customer)", st);
    }

    customer = (customer_t *)cust_record.data;

    /* print the customer id and name */
    printf("customer %d ('%s')\n", customer->id, customer->name);

    /*
     * loop over the 1:n table
     *
     * before we start the loop, we move the cursor to the
     * first duplicate key
     *
     * SELECT * FROM customers, orders, c2o
     *   WHERE c2o.customer_id=customers.id AND
     *    c2o.order_id=orders.id;
     */
    c2o_key.data = &customer->id;
    c2o_key.size = sizeof(int);
    st = ups_cursor_find(cursor[2], &c2o_key, 0, 0);
    if (st != UPS_SUCCESS) {
      if (st == UPS_KEY_NOT_FOUND)
        continue;
      error("ups_cursor_find(c2o)", st);
    }
    st = ups_cursor_move(cursor[2], 0, &c2o_record, 0);
    if (st != UPS_SUCCESS)
      error("ups_cursor_move(c2o)", st);

    do {
      int order_id;

      order_id = *(int *)c2o_record.data;
      ord_key.data = &order_id;
      ord_key.size = sizeof(int);

      /*
       * load the order
       * SELECT * FROM orders WHERE id = order_id;
       */
      st = ups_db_find(db[1], 0, &ord_key, &ord_record, 0);
      if (st != UPS_SUCCESS)
        error("ups_db_find(order)", st);

      printf("  order: %d (assigned to %s)\n",
          order_id, (char *)ord_record.data);

      /*
       * The flag UPS_ONLY_DUPLICATES restricts the cursor
       * movement to the duplicate list.
       */
      st = ups_cursor_move(cursor[2], &c2o_key,
          &c2o_record, UPS_CURSOR_NEXT|UPS_ONLY_DUPLICATES);
      if (st != UPS_SUCCESS) {
        /* reached end of the database? */
        if (st == UPS_KEY_NOT_FOUND)
          break;
        else
          error("ups_cursor_next(c2o)", st);
      }
    } while (1);
  }

  /*
   * Now close the Environment handle; the flag
   * UPS_AUTO_CLEANUP will automatically close all Databases and
   * Cursors
   */
  st = ups_env_close(env, UPS_AUTO_CLEANUP);
  if (st != UPS_SUCCESS)
    error("ups_env_close", st);

  printf("success!\n");
  return (0);
}


text:
class CreateNodes < ActiveRecord::Migration
  def change
    create_table :nodes do |t|
      t.string :title
      t.boolean :complete?, default: false
      t.integer :parent_id
    end
  end
end

redpajama_set_name: RedPajamaGithub


text:
namespace XRoadLib.Wsdl
{
    public class OperationInput : OperationMessage
    {
        protected override string ElementName { get; } = "input";
    }
}


text:
@extends('layout')
@section('title')
Inspire. Be inspired.
@stop
@section('header_title')
Making kids happier & healthier
@stop
@section('header_subtitle')
using sports & technology to build creative learning environments.
@stop
{{-- @section('calltoaction')
Get Started
@stop --}}
@section('body')
<?php /*		*/
?>

group

Improving relationships.

We value loyalty.

We take time to build, nurture, and reflect over our most important relationships.

alarm_on

Saving time.

We value time.

We are improving communication one classroom at a time and providing a simple way to grow, learn, and give back to the world, all at the same time.

mood

Having the fun times of our life.

We value fun and community.

We have fun along the way with our family, our friends, and all our loved ones and we take time to become better citizens of our changing communities.

@stop


text:
function Trout() {
    // The route names are named in this naming scheme
    // because of removing keyword errors (with JavaScript's get and delete keywords).
    this.routes = {
        GET : {},
        POST: {},
        PUT  : {},
        DELETE  : {}
    };
    this.groups = [];
    this.groupPath = "";
}

Trout.prototype.get = function (route, callback) {
    this.routes.GET[this.groupPath + route] = callback;
};

Trout.prototype.post = function (route, callback) {
    this.routes.POST[this.groupPath + route] = callback;
};

Trout.prototype.put = function (route, callback) {
    this.routes.PUT[this.groupPath + route] = callback;
};

Trout.prototype.delete = function (route, callback) {
    this.routes.DELETE[this.groupPath + route] = callback;
};

Trout.prototype.errorPage404 = function (req, res) {
    res.writeHead(404, {"Content-Type": "text/plain"});
    res.write("404 Page Not Found");
    res.end();
};

Trout.prototype.group = function(pathName, routeDeclarations) {
    this.groups.push(pathName);
    this.groupPath = this.groups.join("");
    routeDeclarations();
    this.groups.pop();
    this.groupPath = this.groups.join("");
};
/**
 *
 * @param req
 * @param res
 *
 */
Trout.prototype.pass = function (req, res) {
    // Need to breakup route delimits with question mark
    // to prevent parsing URL parameters
    var viewFunction = this.errorPage404;
    var routeParameters = {
        __g: {},
        __r: {},
        __c: {}
    };
    matchedRoute = this.existsRoute(req.url, req.method);
    if (matchedRoute) {
        viewFunction = this.routes[req.method][matchedRoute.routeName];
        routeParameters = matchedRoute.routeParameters;
    }

    req = this.populateRequestParameters(req, routeParameters);
    viewFunction(req, res);
    //res.write('testing the passing functionality');
    //res.end();
};

Trout.prototype.populateRequestParameters = function (req, routeParameters) {
    var normalParameter, resourceParameter, collectionParameter;
    req.params = {
        resources: {},
        collections: {}
    };
    for (normalParameter in routeParameters.__g) {
        req.params[normalParameter] = routeParameters.__g[normalParameter];
    }
    for (resourceParameter in routeParameters.__r) {
        req.params.resources[resourceParameter] = routeParameters.__r[resourceParameter];
    }
    for (collectionParameter in routeParameters.__c) {
        req.params.collections[collectionParameter] = routeParameters.__c[collectionParameter];
    }
    return req;
};

/**
 * Returns the name of the route in the particular routeArray if
 * it is a succesful match, or false if it is not found in the particular array.
 *
 *
 */
Trout.prototype.existsRoute = function (passedRoute, method) {
    var routeNames = Object.keys(this.routes[method]);
    var length = routeNames.length;
    var i, routeName, validParameters, routeData;
    for (i = 0; i < length; i += 1) {
        routeName = routeNames[i];
        validParameters = this.getRouteParameters(passedRoute, routeName);
        if (validParameters) {
            routeData = {
                routeName : routeName,
                routeParameters : validParameters
            };
            return routeData;
        }
    }
    return false;
};

Trout.prototype.tokenize = function (routeString) {
    try {
        // Allows for having an optional backslash at the end of the URL.
        var noParamString = routeString.split("?")[0];
        var tokens = noParamString.split("/").splice(1);
        if (tokens[tokens.length - 1] === "") {
            tokens.pop();
        }
        return tokens;
    } catch (e) {
        console.log(e);
    }
};

/**
 * Returns true if a route passed in matches a particular saved route
 * when taking into account the parameter rules.
 *
 */
Trout.prototype.getRouteParameters = function (passedRoute, savedRoute) {
    var passedTokens = this.tokenize(passedRoute);
    var savedTokens = this.tokenize(savedRoute);
    // First of all to check they are the same length
    var numTokens = savedTokens.length;
    if (passedTokens.length !== numTokens) {
        return false;
    }
    var parameters = {
        __g : {},
        __c : {},
        __r : {}
    };
    var i, currentPassedToken, currentSavedToken, parameterTokens, parameterTokensLength;
    var compareToken, parameterCategory, parameterName;
    for (i = 0; i < numTokens; i += 1) {
        currentPassedToken = passedTokens[i];
        currentSavedToken = savedTokens[i];
        parameterTokens = currentSavedToken.split(":");
        parameterTokensLength = parameterTokens.length;
        // The case when there's no parameter and it's a direct string comparison.
        if (parameterTokensLength === 1) {
            compareToken = parameterTokens[0];
            if (currentPassedToken !== compareToken) {
                return false;
            }
        }
        // Handles cases when there parameters.
        else if (parameterTokensLength === 2) {
            parameterCategory = parameterTokens[0];
            parameterName = parameterTokens[1];
            if (parameterCategory === "") {
                parameterCategory = '__g';
            }
            else if (parameterCategory === "r") {
                parameterCategory = '__r';
            }
            else if (parameterCategory === "c") {
                parameterCategory = '__c';
            }
            parameters[parameterCategory][parameterName] = currentPassedToken;
        }
    }
    return parameters;
};
router = new Trout();
module.exports = router;


text:
package org.joinfaces.security.taglib;

import java.io.IOException;

import org.joinfaces.test.mock.JsfIT;
import org.junit.jupiter.api.Test;

import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.security.test.context.support.WithAnonymousUser;
import org.springframework.security.test.context.support.WithMockUser;

import static org.assertj.core.api.Assertions.assertThat;

/**
 * Unit tests for {@link FaceletsAuthorizeTagUtils}.
 */
@SpringBootTest(classes = SecurityConfiguration.class, webEnvironment = SpringBootTest.WebEnvironment.MOCK)
class FaceletsAuthorizeTagUtilsIT extends JsfIT {

	@Test
	@WithMockUser
	void testAnonymous() throws IOException {
		assertThat(FaceletsAuthorizeTagUtils.isAnonymous()).isFalse();
	}

	@Test
	@WithMockUser
	void testAuthenticated() throws IOException {
		assertThat(FaceletsAuthorizeTagUtils.isAuthenticated()).isTrue();
	}

	@Test
	@WithMockUser
	void testFullyAuthenticated() throws IOException {
		assertThat(FaceletsAuthorizeTagUtils.isFullyAuthenticated()).isTrue();
	}

	@Test
	@WithMockUser(roles = "A")
	void testAreNotGranted() throws IOException {
		assertThat(FaceletsAuthorizeTagUtils.areNotGranted(Roles.ROLE_C))
			.isTrue();
	}

	@Test
	@WithMockUser(roles = {"A", "B"})
	void testAreAllGranted() throws IOException {
		assertThat(FaceletsAuthorizeTagUtils.areAllGranted(Roles.ROLE_A + "," + Roles.ROLE_C))
			.isFalse();
	}

	@Test
	@WithMockUser(roles = {"A", "B"})
	void testAreAnyGranted() throws IOException {
		assertThat(FaceletsAuthorizeTagUtils.areAnyGranted(Roles.ROLE_A + "," + Roles.ROLE_C))
			.isTrue();
	}

	@Test
	@WithMockUser(roles = {"A", "B"})
	void testIsAllowed() throws IOException {
		assertThat(FaceletsAuthorizeTagUtils.isAllowed("myurl", "mymethod"))
			.isTrue();
	}

	@Test
	@WithAnonymousUser
	void testIsAllowedFalse() throws IOException {
		assertThat(FaceletsAuthorizeTagUtils.isAllowed("myurl", "mymethod"))
			.isFalse();
	}

}


text:
package edu.ucar.unidata.rosetta.exceptions;

/**
 * Exception dealing with Rosetta File IO issues.
 *
 * @author oxelson@ucar.edu
 */
public class RosettaFileException extends Exception {

  public RosettaFileException() {}

  public RosettaFileException(String message) {
    super(message);
  }
}


text:
require 'set'
require 'fog/core/model'
require 'harp-runtime/models/assembly'
require 'harp-runtime/resources/assembly/assembly'
require 'json'

module Harp
  module Resources

    class AssemblySalt < Assembly

      include Harp::Resources

      identity  :id
      attribute :description
      attribute :live_resource
      attribute :state
      attribute :type

      attribute :name
      attribute :cloud
      attribute :configurations
      attribute :tool
      attribute :cloud_credential
      attribute :image

      attribute :packages
      attribute :server_options

      attribute :private_ip_address,      :aliases => 'privateIpAddress'
      attribute :public_ip_address,       :aliases => 'ipAddress'

      register_resource :assembly_salt, RESOURCES_ASSEMBLY

      # Only keeping a few properties, simplest define keeps.
      @keeps = /^id$|^.*_ip_address/

      def self.persistent_type()
        ::AssemblySalt
      end

      def init_provisioner
        bootstrap_file  = File.open(File.expand_path("../salt-bootstrap/salt_bootstrap.sh", __FILE__)).read
        user_data = ""
        line_num=0
        bootstrap_file.each_line do |line|
          if line_num == 0
            user_data << line
            line_num += 1
            user_data << 'packages_yaml="' + parse_packages + '"'
            line_num += 1
          else
            user_data << line
            line_num += 1
          end
        end
        server_options["user_data"] = user_data
      end

      def parse_packages
        yaml_hash = {}
        packages.each do |p|
          yaml_hash[p['name']] = {'pkg'=>['installed']}
        end
        yaml_hash.to_yaml
      end

      def provision_server(server_ip,provisioner)
        server = @service.servers.get(id)
        server.username = config["ssh"]["user"]
        @ssh_key = Key.get_by_name(config['ssh']['keys'][0]).temp_file
        server.private_key_path = @ssh_key.path
        @boot_counter = 0
        bootstrap(server)
        @ssh_key.unlink
      end

      def bootstrap(server)
        @boot_counter += 1
        begin
          puts "waiting 30 seconds for bootstrap..."
          sleep(30)
          puts server.ssh(["wget -O - http://bootstrap.saltstack.org | sudo sh"])[0].stdout
          puts server.ssh(["sudo salt-call --local state.highstate -l debug"])[0].stdout
        rescue
          raise 'Bootstrap timeout error' if @boot_counter > 15
          puts "retrying bootstrap: "
          bootstrap(server)
        end
      end

      def destroy_provisioner(private_dns_name)
      end

    end
  end
end


text:
package org.appsroid.fxpro.bitmap;

import java.io.IOException;
import java.util.Random;

import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.ColorFilter;
import android.graphics.ColorMatrix;
import android.graphics.ColorMatrixColorFilter;
import android.graphics.LightingColorFilter;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.RadialGradient;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Shader;
import android.media.ExifInterface;

public class BitmapProcessing {

	// [-360, +360] -> Default = 0
	public static Bitmap rotate(Bitmap bitmap, float degrees) {
		Matrix matrix = new Matrix();
		matrix.postRotate(degrees);
		return Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
	}

	public static Bitmap flip(Bitmap bitmap, boolean horizontal, boolean vertical) {
		Matrix matrix = new Matrix();
		matrix.preScale(horizontal ? -1 : 1, vertical ? -1 : 1);
		return Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
	}

	public static Bitmap emboss(Bitmap src) {
		double[][] EmbossConfig = new double[][] {
				{ -1 ,  0, -1 },
				{  0 ,  4,  0 },
				{ -1 ,  0, -1 }
		};
		ConvolutionMatrix convMatrix = new ConvolutionMatrix(3);
		convMatrix.applyConfig(EmbossConfig);
		convMatrix.Factor = 1;
		convMatrix.Offset = 127;
		return ConvolutionMatrix.computeConvolution3x3(src, convMatrix);
	}

	// [0, 150], default => 100
	public static Bitmap cfilter(Bitmap src, double red, double green, double blue) {
		red = (double) red / 100;
		green = (double) green / 100;
		blue = (double) blue / 100;

		// image size
		int width = src.getWidth();
		int height = src.getHeight();
		// create output bitmap
		Bitmap bmOut = Bitmap.createBitmap(width, height, src.getConfig());
		// color information
		int A, R, G, B;
		int pixel;

		// scan through all pixels
		for(int x = 0; x < width; ++x) {
			for(int y = 0; y < height; ++y) {
				// get pixel color
				pixel = src.getPixel(x, y);
				// apply filtering on each channel R, G, B
				A = Color.alpha(pixel);
				R = (int)(Color.red(pixel) * red);
				G = (int)(Color.green(pixel) * green);
				B = (int)(Color.blue(pixel) * blue);
				// set new color pixel to output bitmap
				bmOut.setPixel(x, y, Color.argb(A, R, G, B));
			}
		}

		src.recycle();
		src = null;

		// return final image
		return bmOut;
	}

	public static Bitmap gaussian(Bitmap src) {
		double[][] GaussianBlurConfig = new double[][] {
				{ 1, 2, 1 },
				{ 2, 4, 2 },
				{ 1, 2, 1 }
		};
		ConvolutionMatrix convMatrix = new ConvolutionMatrix(3);
		convMatrix.applyConfig(GaussianBlurConfig);
		convMatrix.Factor = 16;
		convMatrix.Offset = 0;
		return ConvolutionMatrix.computeConvolution3x3(src, convMatrix);
	}

	// bitOffset = (16, 32, 64, 128)
	public static Bitmap cdepth(Bitmap src, int bitOffset) {
		// get image size
		int width = src.getWidth();
		int height = src.getHeight();
		// create output bitmap
		Bitmap bmOut = Bitmap.createBitmap(width, height, src.getConfig());
		// color information
		int A, R, G, B;
		int pixel;

		// scan through all pixels
		for(int x = 0; x < width; ++x) {
			for(int y = 0; y < height; ++y) {
				// get pixel color
				pixel = src.getPixel(x, y);
				A = Color.alpha(pixel);
				R = Color.red(pixel);
				G = Color.green(pixel);
				B = Color.blue(pixel);

				// round-off color offset
				R = ((R + (bitOffset / 2)) - ((R + (bitOffset / 2)) % bitOffset) - 1);
				if(R < 0) { R = 0; }
				G = ((G + (bitOffset / 2)) - ((G + (bitOffset / 2)) % bitOffset) - 1);
				if(G < 0) { G = 0; }
				B = ((B + (bitOffset / 2)) - ((B + (bitOffset / 2)) % bitOffset) - 1);
				if(B < 0) { B = 0; }

				// set pixel color to output bitmap
				bmOut.setPixel(x, y, Color.argb(A, R, G, B));
			}
		}

		src.recycle();
		src = null;

		return bmOut;
	}

	public static Bitmap sharpen(Bitmap src) {
		double[][] SharpConfig = new double[][] {
				{ 0 , -2    , 0  },
				{ -2, 11, -2 },
				{ 0 , -2    , 0  }
		};
		ConvolutionMatrix convMatrix = new ConvolutionMatrix(3);
		convMatrix.applyConfig(SharpConfig);
		convMatrix.Factor = 3;
		return ConvolutionMatrix.computeConvolution3x3(src, convMatrix);
	}

	public static Bitmap noise(Bitmap source) {
		final int COLOR_MAX = 0xFF;

		// get image size
		int width = source.getWidth();
		int height = source.getHeight();
		int[] pixels = new int[width * height];
		// get pixel array from source
		source.getPixels(pixels, 0, width, 0, 0, width, height);
		// a random object
		Random random = new Random();

		int index = 0;
		// iteration through pixels
		for(int y = 0; y < height; ++y) {
			for(int x = 0; x < width; ++x) {
				// get current index in 2D-matrix
				index = y * width + x;
				// get random color
				int randColor = Color.rgb(random.nextInt(COLOR_MAX),
						random.nextInt(COLOR_MAX), random.nextInt(COLOR_MAX));
				// OR
				pixels[index] |= randColor;
			}
		}
		// output bitmap
		Bitmap bmOut = Bitmap.createBitmap(width, height, source.getConfig());
		bmOut.setPixels(pixels, 0, width, 0, 0, width, height);

		source.recycle();
		source = null;

		return bmOut;
	}

	// [-255, +255] -> Default = 0
	public static Bitmap brightness(Bitmap src, int value) {
		// image size
		int width = src.getWidth();
		int height = src.getHeight();
		// create output bitmap
		Bitmap bmOut = Bitmap.createBitmap(width, height, src.getConfig());
		// color information
		int A, R, G, B;
		int pixel;

		// scan through all pixels
		for(int x = 0; x < width; ++x) {
			for(int y = 0; y < height; ++y) {
				// get pixel color
				pixel = src.getPixel(x, y);
				A = Color.alpha(pixel);
				R = Color.red(pixel);
				G = Color.green(pixel);
				B = Color.blue(pixel);

				// increase/decrease each channel
				R += value;
				if(R > 255) { R = 255; }
				else if(R < 0) { R = 0; }

				G += value;
				if(G > 255) { G = 255; }
				else if(G < 0) { G = 0; }

				B += value;
				if(B > 255) { B = 255; }
				else if(B < 0) { B = 0; }

				// apply new pixel color to output bitmap
				bmOut.setPixel(x, y, Color.argb(A, R, G, B));
			}
		}

		src.recycle();
		src = null;

		return bmOut;
	}

	public static Bitmap sepia(Bitmap src) {
		// image size
		int width = src.getWidth();
		int height = src.getHeight();
		// create output bitmap
		Bitmap bmOut = Bitmap.createBitmap(width, height, src.getConfig());
		// constant grayscale
		final double GS_RED = 0.3;
		final double GS_GREEN = 0.59;
		final double GS_BLUE = 0.11;
		// color information
		int A, R, G, B;
		int pixel;

		// scan through all pixels
		for(int x = 0; x < width; ++x) {
			for(int y = 0; y < height; ++y) {
				// get pixel color
				pixel = src.getPixel(x, y);
				// get color on each channel
				A = Color.alpha(pixel);
				R = Color.red(pixel);
				G = Color.green(pixel);
				B = Color.blue(pixel);
				// apply grayscale sample
				B = G = R = (int)(GS_RED * R + GS_GREEN * G + GS_BLUE * B);

				// apply intensity level for sepid-toning on each channel
				R += 110;
				if(R > 255) { R = 255; }

				G += 65;
				if(G > 255) { G = 255; }

				B += 20;
				if(B > 255) { B = 255; }

				// set new pixel color to output image
				bmOut.setPixel(x, y, Color.argb(A, R, G, B));
			}
		}

		src.recycle();
		src = null;

		return bmOut;
	}

	// red, green, blue [0, 48]
	public static Bitmap gamma(Bitmap src, double red, double green, double blue) {
		red = (double) (red + 2) / 10.0;
		green = (double) (green + 2) / 10.0;
		blue = (double) (blue + 2) / 10.0;
		// create output image
		Bitmap bmOut = Bitmap.createBitmap(src.getWidth(), src.getHeight(), src.getConfig());
		// get image size
		int width = src.getWidth();
		int height = src.getHeight();
		// color information
		int A, R, G, B;
		int pixel;
		// constant value curve
		final int    MAX_SIZE = 256;
		final double MAX_VALUE_DBL = 255.0;
		final int    MAX_VALUE_INT = 255;
		final double REVERSE = 1.0;

		// gamma arrays
		int[] gammaR = new int[MAX_SIZE];
		int[] gammaG = new int[MAX_SIZE];
		int[] gammaB = new int[MAX_SIZE];

		// setting values for every gamma channels
		for(int i = 0; i < MAX_SIZE; ++i) {
			gammaR[i] = (int)Math.min(MAX_VALUE_INT,
					(int)((MAX_VALUE_DBL * Math.pow(i / MAX_VALUE_DBL, REVERSE / red)) + 0.5));
			gammaG[i] = (int)Math.min(MAX_VALUE_INT,
					(int)((MAX_VALUE_DBL * Math.pow(i / MAX_VALUE_DBL, REVERSE / green)) + 0.5));
			gammaB[i] = (int)Math.min(MAX_VALUE_INT,
					(int)((MAX_VALUE_DBL * Math.pow(i / MAX_VALUE_DBL, REVERSE / blue)) + 0.5));
		}

		// apply gamma table
		for(int x = 0; x < width; ++x) {
			for(int y = 0; y < height; ++y) {
				// get pixel color
				pixel = src.getPixel(x, y);
				A = Color.alpha(pixel);
				// look up gamma
				R = gammaR[Color.red(pixel)];
				G = gammaG[Color.green(pixel)];
				B = gammaB[Color.blue(pixel)];
				// set new color to output bitmap
				bmOut.setPixel(x, y, Color.argb(A, R, G, B));
			}
		}

		src.recycle();
		src = null;

		// return final image
		return bmOut;
	}

	// [-100, +100] -> Default = 0
	public static Bitmap contrast(Bitmap src, double value) {
		// image size
		int width = src.getWidth();
		int height = src.getHeight();
		// create output bitmap

		// create a mutable empty bitmap
		Bitmap bmOut = Bitmap.createBitmap(width, height, src.getConfig());

		// create a canvas so that we can draw the bmOut Bitmap from source bitmap
		Canvas c = new Canvas();
		c.setBitmap(bmOut);

		// draw bitmap to bmOut from src bitmap so we can modify it
		c.drawBitmap(src, 0, 0, new Paint(Color.BLACK));

		// color information
		int A, R, G, B;
		int pixel;
		// get contrast value
		double contrast = Math.pow((100 + value) / 100, 2);

		// scan through all pixels
		for(int x = 0; x < width; ++x) {
			for(int y = 0; y < height; ++y) {
				// get pixel color
				pixel = src.getPixel(x, y);
				A = Color.alpha(pixel);
				// apply filter contrast for every channel R, G, B
				R = Color.red(pixel);
				R = (int)(((((R / 255.0) - 0.5) * contrast) + 0.5) * 255.0);
				if(R < 0) { R = 0; }
				else if(R > 255) { R = 255; }

				G = Color.green(pixel);
				G = (int)(((((G / 255.0) - 0.5) * contrast) + 0.5) * 255.0);
				if(G < 0) { G = 0; }
				else if(G > 255) { G = 255; }

				B = Color.blue(pixel);
				B = (int)(((((B / 255.0) - 0.5) * contrast) + 0.5) * 255.0);
				if(B < 0) { B = 0; }
				else if(B > 255) { B = 255; }

				// set new pixel color to output bitmap
				bmOut.setPixel(x, y, Color.argb(A, R, G, B));
			}
		}
		src.recycle();
		src = null;
		return bmOut;
	}

	// [0, 200] -> Default = 100
	public static Bitmap saturation(Bitmap src, int value) {
		float f_value = (float) (value / 100.0);

		int w = src.getWidth();
		int h = src.getHeight();

		Bitmap bitmapResult =
				Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
		Canvas canvasResult = new Canvas(bitmapResult);
		Paint paint = new Paint();
		ColorMatrix colorMatrix = new ColorMatrix();
		colorMatrix.setSaturation(f_value);
		ColorMatrixColorFilter filter = new ColorMatrixColorFilter(colorMatrix);
		paint.setColorFilter(filter);
		canvasResult.drawBitmap(src, 0, 0, paint);

		src.recycle();
		src = null;

		return bitmapResult;
	}

	public static Bitmap grayscale(Bitmap src) {
		//Array to generate Gray-Scale image
		float[] GrayArray = {
				0.213f, 0.715f, 0.072f, 0.0f, 0.0f,
				0.213f, 0.715f, 0.072f, 0.0f, 0.0f,
				0.213f, 0.715f, 0.072f, 0.0f, 0.0f,
				0.0f, 0.0f, 0.0f, 1.0f, 0.0f,
		};

		ColorMatrix colorMatrixGray = new ColorMatrix(GrayArray);

		int w = src.getWidth();
		int h = src.getHeight();

		Bitmap bitmapResult = Bitmap
				.createBitmap(w, h, Bitmap.Config.ARGB_8888);
		Canvas canvasResult = new Canvas(bitmapResult);
		Paint paint = new Paint();

		ColorMatrixColorFilter filter = new ColorMatrixColorFilter(colorMatrixGray);
		paint.setColorFilter(filter);
		canvasResult.drawBitmap(src, 0, 0, paint);

		src.recycle();
		src = null;

		return bitmapResult;
	}

	public static Bitmap vignette(Bitmap image) {
		final int width = image.getWidth();
		final int height = image.getHeight();

	    float radius = (float) (width/1.2);
	    int[] colors = new int[] { 0, 0x55000000, 0xff000000 };
        float[] positions = new float[] { 0.0f, 0.5f, 1.0f };

	    RadialGradient gradient = new RadialGradient(width / 2, height / 2, radius, colors, positions, Shader.TileMode.CLAMP);

	    //RadialGradient gradient = new RadialGradient(width / 2, height / 2, radius, Color.TRANSPARENT, Color.BLACK, Shader.TileMode.CLAMP);

	    Canvas canvas = new Canvas(image);
	    canvas.drawARGB(1, 0, 0, 0);

	    final Paint paint = new Paint();
	    paint.setAntiAlias(true);
	    paint.setColor(Color.BLACK);
	    paint.setShader(gradient);

	    final Rect rect = new Rect(0, 0, image.getWidth(), image.getHeight());
	    final RectF rectf = new RectF(rect);

	    canvas.drawRect(rectf, paint);

	    paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
    	canvas.drawBitmap(image, rect, rect, paint);

	    return image;
	}

	// hue = [0, 360] -> Default = 0
	public static Bitmap hue(Bitmap bitmap, float hue) {
		Bitmap newBitmap = bitmap.copy(bitmap.getConfig(), true);
		final int width = newBitmap.getWidth();
		final int height = newBitmap.getHeight();
		float [] hsv = new float[3];

		for(int y = 0; y < height; y++){
			for(int x = 0; x < width; x++){
				int pixel = newBitmap.getPixel(x,y);
				Color.colorToHSV(pixel,hsv);
				hsv[0] = hue;
				newBitmap.setPixel(x,y,Color.HSVToColor(Color.alpha(pixel),hsv));
			}
		}

		bitmap.recycle();
		bitmap = null;

		return newBitmap;
	}

	public static Bitmap tint(Bitmap src, int color) {
		// image size
		int width = src.getWidth();
		int height = src.getHeight();
		// create output bitmap

		// create a mutable empty bitmap
		Bitmap bmOut = Bitmap.createBitmap(width, height, src.getConfig());

		Paint p = new Paint(Color.RED);
		ColorFilter filter = new LightingColorFilter(color, 1);
		p.setColorFilter(filter);

		Canvas c = new Canvas();
		c.setBitmap(bmOut);
		c.drawBitmap(src, 0, 0, p);

		src.recycle();
		src = null;

		return bmOut;
	}

	public static Bitmap invert(Bitmap src) {
		Bitmap output = Bitmap.createBitmap(src.getWidth(), src.getHeight(), src.getConfig());
		int A, R, G, B;
		int pixelColor;
		int height = src.getHeight();
		int width = src.getWidth();

		for (int y = 0; y < height; y++) {
			for (int x = 0; x < width; x++) {
				pixelColor = src.getPixel(x, y);
				A = Color.alpha(pixelColor);

				R = 255 - Color.red(pixelColor);
				G = 255 - Color.green(pixelColor);
				B = 255 - Color.blue(pixelColor);

				output.setPixel(x, y, Color.argb(A, R, G, B));
			}
		}

		src.recycle();
		src = null;

		return output;
	}

	// percent = [0, 150], type = (1, 2, 3) => (R, G, B)
	public static Bitmap boost(Bitmap src, int type, float percent) {
		percent = (float) percent / 100;

		int width = src.getWidth();
		int height = src.getHeight();
		Bitmap bmOut = Bitmap.createBitmap(width, height, src.getConfig());

		int A, R, G, B;
		int pixel;

		for(int x = 0; x < width; ++x) {
			for(int y = 0; y < height; ++y) {
				pixel = src.getPixel(x, y);
				A = Color.alpha(pixel);
				R = Color.red(pixel);
				G = Color.green(pixel);
				B = Color.blue(pixel);
				if(type == 1) {
					R = (int)(R * (1 + percent));
					if(R > 255) R = 255;
				}
				else if(type == 2) {
					G = (int)(G * (1 + percent));
					if(G > 255) G = 255;
				}
				else if(type == 3) {
					B = (int)(B * (1 + percent));
					if(B > 255) B = 255;
				}
				bmOut.setPixel(x, y, Color.argb(A, R, G, B));
			}
		}

		src.recycle();
		src = null;

		return bmOut;
	}

	public static final Bitmap sketch(Bitmap src) {
		int type = 6;
		int threshold = 130;

		int width = src.getWidth();
		int height = src.getHeight();
		Bitmap result = Bitmap.createBitmap(width, height, src.getConfig());

		int A, R, G, B;
		int sumR, sumG, sumB;
		int[][] pixels = new int[3][3];
		for(int y = 0; y < height - 2; ++y) {
			for(int x = 0; x < width - 2; ++x) {
				//      get pixel matrix
				for(int i = 0; i < 3; ++i) {
					for(int j = 0; j < 3; ++j) {
						pixels[i][j] = src.getPixel(x + i, y + j);
					}
				}
				// get alpha of center pixel
				A = Color.alpha(pixels[1][1]);
				// init color sum
				sumR = sumG = sumB = 0;
				sumR = (type*Color.red(pixels[1][1])) - Color.red(pixels[0][0]) - Color.red(pixels[0][2]) - Color.red(pixels[2][0]) - Color.red(pixels[2][2]);
				sumG = (type*Color.green(pixels[1][1])) - Color.green(pixels[0][0]) - Color.green(pixels[0][2]) - Color.green(pixels[2][0]) - Color.green(pixels[2][2]);
				sumB = (type*Color.blue(pixels[1][1])) - Color.blue(pixels[0][0]) - Color.blue(pixels[0][2]) - Color.blue(pixels[2][0]) - Color.blue(pixels[2][2]);
				// get final Red
				R = (int)(sumR  + threshold);
				if(R < 0) { R = 0; }
				else if(R > 255) { R = 255; }
				// get final Green
				G = (int)(sumG  + threshold);
				if(G < 0) { G = 0; }
				else if(G > 255) { G = 255; }
				// get final Blue
				B = (int)(sumB  + threshold);
				if(B < 0) { B = 0; }
				else if(B > 255) { B = 255; }

				result.setPixel(x + 1, y + 1, Color.argb(A, R, G, B));
			}
		}

		src.recycle();
		src = null;

		return result;
	}

	public static Bitmap modifyOrientation(Bitmap bitmap, String image_url) throws IOException {
		ExifInterface ei = new ExifInterface(image_url);
		int orientation = ei.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);

		switch (orientation) {
		case ExifInterface.ORIENTATION_ROTATE_90:
			return rotate(bitmap, 90);

		case ExifInterface.ORIENTATION_ROTATE_180:
			return rotate(bitmap, 180);

		case ExifInterface.ORIENTATION_ROTATE_270:
			return rotate(bitmap, 270);

		case ExifInterface.ORIENTATION_FLIP_HORIZONTAL:
			return flip(bitmap, true, false);

		case ExifInterface.ORIENTATION_FLIP_VERTICAL:
			return flip(bitmap, false, true);

		default:
			return bitmap;
		}
	}

}


text:
import React, { PropTypes } from 'react'
import { Link as RouterLink } from 'react-router'
import { Card, CardTitle, CardActions } from 'react-toolbox/lib/card'
import { IconButton } from 'react-toolbox/lib/button'
import style from './IdeaListItem.scss'
import moment from 'moment'

let IdeaListItem = (props) => {
  const { name, imageUrl, author, id, votes, description, addVote, createdAt, comments } = props

  return (
    <div className={style.idea}>
      <Card className={style.card}>
        <RouterLink to={`ideas/${id}`}>
          <CardTitle
            avatar={imageUrl || 'https://help.github.com/assets/images/help/profile/identicon.png'}
            title={author}
            subtitle={`submitted ${moment(createdAt).fromNow()}`}
            className={style.header}
          />
          <CardTitle
            title={name}
            subtitle={description.length > 70 ? `${description.substring(0, 70)}...` : description}
            className={style.details}
          />
        </RouterLink>
        <CardActions>
          <IconButton icon="favorite_border" accent onClick={() => addVote(id)} />{votes.length}
          <RouterLink to={`ideas/${id}`}>
            <IconButton icon="chat_bubble_outline" />{comments.length}
          </RouterLink>
        </CardActions>
      </Card>
    </div>
  )
}

IdeaListItem.propTypes = {
  id: PropTypes.string.isRequired,
  name: PropTypes.string.isRequired,
  description: PropTypes.string.isRequired,
  imageUrl: PropTypes.string,
  author: PropTypes.string.isRequired,
  votes: PropTypes.array.isRequired,
  comments: PropTypes.array.isRequired,
  status: PropTypes.string.isRequired,
  addVote: PropTypes.func.isRequired,
  createdAt: PropTypes.instanceOf(Date).isRequired
}

IdeaListItem.defaultProps = {
  votes: [],
  comments: [],
  status: 'open'
}

export default IdeaListItem


text:
<?php

class ArenaController extends BaseController {

    public function handle() {
        $user = Auth::user();

        return View::make('arena/index', compact('user'));
    }

    public function start() {
        $user = Auth::user();

        return View::make('arena/start', compact('user'));
    }

    public function start_session() {
        $user = Auth::user();
        $user->start();
        $user->save();

        return Redirect::route('arena');
    }

    public function result() {
        $user = Auth::user();

        return View::make('arena/result', compact('user'));
    }

    public function logout() {
        Auth::logout();

        return Redirect::route('home');
    }

    public function proper_redirect() {
        $user = Auth::user();
        if($user->isFresh()) {
            return Redirect::ajaxAwareRoute('start');
        } else  if($user->isInProgress()) {
            return Redirect::ajaxAwareRoute('arena');
        } else {
            return Redirect::ajaxAwareRoute('result');
        }
    }
}


text:
using System;
using System.Collections.Generic;
using System.Xml;

using XenAdmin.Core;
using XenAdmin.Network;
using XenAPI;

namespace XenAdmin.Actions
{
    /// <summary>
    /// Asks the server for a list of NetApp aggregates and SRs on a given filer.
    /// </summary>
    public class SrScanAction : AsyncAction
    {
        private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

        private readonly string hostname;
        private readonly string username;
        private readonly string password;
        private readonly SR.SRTypes type;

        private List<SR.SRInfo> srs;

        private List<NetAppAggregate> aggregates;
        private List<DellStoragePool> storagePools;

        public SrScanAction(IXenConnection connection, string hostname, string username,
            string password, SR.SRTypes type)
            : base(connection, String.Format(Messages.ACTION_SR_SCAN_NAME, hostname),
            String.Format(Messages.ACTION_SR_SCAN_DESCRIPTION, SR.GetFriendlyTypeName(type), hostname), true)
        {
            this.hostname = hostname;
            this.username = username;
            this.password = password;
            this.type = type;
        }

        /// <summary>
        /// Will be null if the scan has not yet successfully returned.
        /// </summary>
        public List<SR.SRInfo> SRs
        {
            get
            {
                return srs;
            }
        }

        /// <summary>
        /// Will be null if the scan has not yet successfully returned.
        /// </summary>
        public List<NetAppAggregate> Aggregates
        {
            get
            {
                return aggregates;
            }
        }

        /// <summary>
        /// Will be null if the scan has not yet successfully returned.
        /// </summary>
        public List<DellStoragePool> StoragePools
        {
            get
            {
                return storagePools;
            }
        }

        protected override void Run()
        {
            // Fill in dictionary params
            Dictionary<String, String> dconf = new Dictionary<String, String>();
            dconf.Add("target", hostname);
            dconf.Add("username", username);
            dconf.Add("password", password);

            log.DebugFormat("Attempting to find SRs on {0} filer {1}.", type, hostname);

            RelatedTask = XenAPI.SR.async_probe(Session, Helpers.GetCoordinator(Connection).opaque_ref,
                dconf, type.ToString(), new Dictionary<String, String>());
            this.PollToCompletion();
            srs = XenAPI.SR.ParseSRListXML(this.Result);

            log.DebugFormat("Attempting to find aggregates on {0} filer {1}.", type, hostname);

            try
            {
                RelatedTask = XenAPI.SR.async_create(Session, hostname, dconf, 0,
                    Helpers.GuiTempObjectPrefix, "", type.ToString(), "", true,
                    new Dictionary<String, String>());

                this.PollToCompletion(50, 100);

                throw new BadServerResponse(hostname);
            }
            catch (Failure exn)
            {
                if (exn.ErrorDescription.Count < 1)
                    throw new BadServerResponse(hostname);

                // We expect a particular sort of failure, whose error details contain
                // the list of aggregates on the filer in XML.

                switch (exn.ErrorDescription[0])
                {
                    case "SR_BACKEND_FAILURE_123":
                        // We want a custom error if the server returns no iqns.
                        if (exn.ErrorDescription.Count < 4 || exn.ErrorDescription[3].Length == 0)
                            break;

                        aggregates = ParseAggregateXML(exn.ErrorDescription[3], hostname);

                        break;

                    case "SR_BACKEND_FAILURE_163":
                        // We want a custom error if the server returns no iqns.
                        if (exn.ErrorDescription.Count < 4 || exn.ErrorDescription[3].Length == 0)
                            break;

                        storagePools = ParseDellStoragePoolsXML(exn.ErrorDescription[3], hostname);

                        break;

                    default:
                        throw;
                }

                if (ListIsNullOrEmpty(srs)
                    && ListIsNullOrEmpty(aggregates)
                    && ListIsNullOrEmpty(storagePools))
                    throw new NoExistingAndNowhereToCreateException(hostname);
            }
        }

        public static bool ListIsNullOrEmpty<T>(List<T> list)
        {
            return list == null || list.Count <= 0;
        }

        private static List<NetAppAggregate> ParseAggregateXML(String xml, String hostname)
        {
            List<NetAppAggregate> results = new List<NetAppAggregate>();

            try
            {
                // Parse XML
                XmlDocument doc = new XmlDocument();
                doc.LoadXml(xml);

                foreach (XmlNode aggr in doc.GetElementsByTagName("Aggr"))
                {
                    string name = "";
                    long size = -1;
                    int disks = -1;
                    string raidType = "";
                    bool asisCapable = false;
                    foreach (XmlNode info in aggr.ChildNodes)
                    {
                        // use name for build < 7040, aggregate after this
                        if (info.Name.ToLowerInvariant() == "name" || info.Name.ToLowerInvariant() == "aggregate")
                        {
                            name = info.InnerText.Trim();
                        }
                        else if (info.Name.ToLowerInvariant() == "size")
                        {
                            size = long.Parse(info.InnerText.Trim(), System.Globalization.CultureInfo.InvariantCulture);
                        }
                        else if (info.Name.ToLowerInvariant() == "disks")
                        {
                            disks = int.Parse(info.InnerText.Trim(), System.Globalization.CultureInfo.InvariantCulture);
                        }
                        else if (info.Name.ToLowerInvariant() == "raidtype")
                        {
                            raidType = info.InnerText.Trim();
                        }
                        else if (info.Name.ToLowerInvariant() == "asis_dedup")
                        {
                            asisCapable = bool.Parse(info.InnerText.Trim().ToLowerInvariant());
                        }
                    }

                    results.Add(new NetAppAggregate(name, size, disks, raidType, asisCapable));
                }

                results.Sort();
            }
            catch
            {
                throw new BadServerResponse(hostname);
            }

            return results;
        }

        private static List<DellStoragePool> ParseDellStoragePoolsXML(String xml, String hostname)
        {
            List<DellStoragePool> results = new List<DellStoragePool>();

            try
            {
                // Parse XML
                XmlDocument doc = new XmlDocument();
                doc.LoadXml(xml);

                foreach (XmlNode aggr in doc.GetElementsByTagName("StoragePool"))
                {
                    String Name = "";
                    bool Default = false;
                    int Members = 0;
                    int Volumes = 0;
                    long Capacity = 0;
                    long Freespace = 0;

                    foreach (XmlNode info in aggr.ChildNodes)
                    {
                        switch(info.Name.ToLowerInvariant())
                        {
                            case "name":
                                Name = info.InnerText.Trim();
                                break;

                            case "default":
                                bool.TryParse(info.InnerText.Trim(), out Default);
                                break;

                            case "members":
                                int.TryParse(info.InnerText.Trim(), out Members);
                                break;

                            case "volumes":
                                int.TryParse(info.InnerText.Trim(), out Volumes);
                                break;

                            case "capacity":
                                long.TryParse(info.InnerText.Trim(), out Capacity);
                                break;

                            case "freespace":
                                long.TryParse(info.InnerText.Trim(), out Freespace);
                                break;
                        }
                    }

                    results.Add(new DellStoragePool(Name, Default, Members, Volumes, Capacity, Freespace));
                }

                results.Sort();
            }
            catch
            {
                throw new BadServerResponse(hostname);
            }

            return results;
        }
    }

    public struct NetAppAggregate : IComparable<NetAppAggregate>
    {
        public readonly string Name;
        public readonly long Size;
        public readonly int Disks;
        public readonly string RaidType;
        public readonly bool AsisCapable;

        public NetAppAggregate(string name, long size, int disks, string raidType, bool asisCapable)
        {
            this.Name = name;
            this.Size = size;
            this.Disks = disks;
            this.RaidType = raidType;
            this.AsisCapable = asisCapable;
        }

        public int CompareTo(NetAppAggregate other)
        {
            return Name.CompareTo(other.Name);
        }
    }

    public struct DellStoragePool : IComparable<DellStoragePool>
    {
        public readonly String Name;
        public readonly bool Default;
        public readonly int Members;
        public readonly int Volumes;
        public readonly long Capacity;
        public readonly long Freespace;

        public DellStoragePool(String Name, bool Default, int Members,
            int Volumes, long Capacity, long Freespace)
        {
            this.Name = Name;
            this.Default = Default;
            this.Members = Members;
            this.Volumes = Volumes;
            this.Capacity = Capacity;
            this.Freespace = Freespace;
        }

        public int CompareTo(DellStoragePool other)
        {
            return Name.CompareTo(other.Name);
        }
    }

    public class NoExistingAndNowhereToCreateException : Exception
    {
        private String host;

        public NoExistingAndNowhereToCreateException(String host)
        {
            this.host = host;
        }

        public override string Message
        {
            get
            {
                return Messages.NEWSR_NOWHERE_TO_CREATE;
            }
        }
    }
}


text:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Net.Http;
using System.Text;
using CacheCow.Common;
using NUnit.Framework;

namespace CacheCow.Client.MemcachedCacheStore.Tests
{
    [TestFixture]
    public class IntegrationTests
    {

        private HttpResponseMessage _response;
        private CacheKey _key;
        public IntegrationTests()
        {
            _response = new HttpClient().GetAsync("http://google.com").Result;
            _key = new CacheKey(_response.RequestMessage.RequestUri.AbsoluteUri, new string[0]);
        }

        [Ignore]
        [Test]
        public void TestGet()
        {
            using (var mc = new MemcachedStore())
            {
                mc.AddOrUpdate(_key, _response);

                HttpResponseMessage message;

                var success = mc.TryGetValue(_key, out message);
                Assert.AreEqual(_response.Content.Headers.ContentLength, message.Content.Headers.ContentLength);
                Assert.AreEqual(_response.Content.ReadAsStringAsync().Result,
                    message.Content.ReadAsStringAsync().Result);
                Assert.IsTrue(success);
            }
        }

        [Ignore]
        [Test]
        public void TestRemove()
        {
            using (var mc = new MemcachedStore())
            {
                mc.AddOrUpdate(_key, _response);
                HttpResponseMessage message;

                var success = mc.TryRemove(_key);
                var getFailure = mc.TryGetValue(_key, out message);

                var failure = mc.TryRemove(_key);

                Assert.IsTrue(success);
                Assert.IsTrue(!failure);
                Assert.IsTrue(!getFailure);
            }

        }

    }
}


text:
<stbui-base-layout scrollStrategy="strategy">
  <stbui-base-layout-header>header</stbui-base-layout-header>
  <stbui-base-layout-toolbar>toolbar</stbui-base-layout-toolbar>
  <app-demo-content></app-demo-content>
</stbui-base-layout>


text:
import uuid

from oslo.serialization import jsonutils
import six

from keystone.common import wsgi
from keystone import exception
from keystone import tests

class ExceptionTestCase(tests.TestCase):
    def assertValidJsonRendering(self, e):
        resp = wsgi.render_exception(e)
        self.assertEqual(e.code, resp.status_int)
        self.assertEqual('%s %s' % (e.code, e.title), resp.status)

        j = jsonutils.loads(resp.body)
        self.assertIsNotNone(j.get('error'))
        self.assertIsNotNone(j['error'].get('code'))
        self.assertIsNotNone(j['error'].get('title'))
        self.assertIsNotNone(j['error'].get('message'))
        self.assertNotIn('\n', j['error']['message'])
        self.assertNotIn('  ', j['error']['message'])
        self.assertTrue(type(j['error']['code']) is int)

    def test_all_json_renderings(self):
        """Everything callable in the exception module should be renderable.

        ... except for the base error class (exception.Error), which is not
        user-facing.

        This test provides a custom message to bypass docstring parsing, which
        should be tested separately.

        """
        for cls in [x for x in exception.__dict__.values() if callable(x)]:
            if cls is not exception.Error and isinstance(cls, exception.Error):
                self.assertValidJsonRendering(cls(message='Overridden.'))

    def test_validation_error(self):
        target = uuid.uuid4().hex
        attribute = uuid.uuid4().hex
        e = exception.ValidationError(target=target, attribute=attribute)
        self.assertValidJsonRendering(e)
        self.assertIn(target, six.text_type(e))
        self.assertIn(attribute, six.text_type(e))

    def test_not_found(self):
        target = uuid.uuid4().hex
        e = exception.NotFound(target=target)
        self.assertValidJsonRendering(e)
        self.assertIn(target, six.text_type(e))

    def test_403_title(self):
        e = exception.Forbidden()
        resp = wsgi.render_exception(e)
        j = jsonutils.loads(resp.body)
        self.assertEqual('Forbidden', e.title)
        self.assertEqual('Forbidden', j['error'].get('title'))

    def test_unicode_message(self):
        message = u'Comment \xe7a va'
        e = exception.Error(message)

        try:
            self.assertEqual(message, six.text_type(e))
        except UnicodeEncodeError:
            self.fail("unicode error message not supported")

    def test_unicode_string(self):
        e = exception.ValidationError(attribute='xx',
                                      target='Long \xe2\x80\x93 Dash')

        self.assertIn(u'\u2013', six.text_type(e))

    def test_invalid_unicode_string(self):
        # NOTE(jamielennox): This is a complete failure case so what is
        # returned in the exception message is not that important so long
        # as there is an error with a message
        e = exception.ValidationError(attribute='xx',
                                      target='\xe7a va')
        self.assertIn('%(attribute)', six.text_type(e))

class UnexpectedExceptionTestCase(ExceptionTestCase):
    """Tests if internal info is exposed to the API user on UnexpectedError."""

    class SubClassExc(exception.UnexpectedError):
        debug_message_format = 'Debug Message: %(debug_info)s'

    def setUp(self):
        super(UnexpectedExceptionTestCase, self).setUp()
        self.exc_str = uuid.uuid4().hex

    def test_unexpected_error_no_debug(self):
        self.config_fixture.config(debug=False)
        e = exception.UnexpectedError(exception=self.exc_str)
        self.assertNotIn(self.exc_str, six.text_type(e))

    def test_unexpected_error_debug(self):
        self.config_fixture.config(debug=True)
        e = exception.UnexpectedError(exception=self.exc_str)
        self.assertIn(self.exc_str, six.text_type(e))

    def test_unexpected_error_subclass_no_debug(self):
        self.config_fixture.config(debug=False)
        e = UnexpectedExceptionTestCase.SubClassExc(
            debug_info=self.exc_str)
        self.assertEqual(exception.UnexpectedError._message_format,
                         six.text_type(e))

    def test_unexpected_error_subclass_debug(self):
        self.config_fixture.config(debug=True)
        subclass = self.SubClassExc

        e = subclass(debug_info=self.exc_str)
        expected = subclass.debug_message_format % {'debug_info': self.exc_str}
        translated_amendment = six.text_type(exception.SecurityError.amendment)
        self.assertEqual(
            expected + six.text_type(' ') + translated_amendment,
            six.text_type(e))

    def test_unexpected_error_custom_message_no_debug(self):
        self.config_fixture.config(debug=False)
        e = exception.UnexpectedError(self.exc_str)
        self.assertEqual(exception.UnexpectedError._message_format,
                         six.text_type(e))

    def test_unexpected_error_custom_message_debug(self):
        self.config_fixture.config(debug=True)
        e = exception.UnexpectedError(self.exc_str)
        translated_amendment = six.text_type(exception.SecurityError.amendment)
        self.assertEqual(
            self.exc_str + six.text_type(' ') + translated_amendment,
            six.text_type(e))

class SecurityErrorTestCase(ExceptionTestCase):
    """Tests whether security-related info is exposed to the API user."""
    def test_unauthorized_exposure(self):
        self.config_fixture.config(debug=False)

        risky_info = uuid.uuid4().hex
        e = exception.Unauthorized(message=risky_info)
        self.assertValidJsonRendering(e)
        self.assertNotIn(risky_info, six.text_type(e))

    def test_unauthorized_exposure_in_debug(self):
        self.config_fixture.config(debug=True)

        risky_info = uuid.uuid4().hex
        e = exception.Unauthorized(message=risky_info)
        self.assertValidJsonRendering(e)
        self.assertIn(risky_info, six.text_type(e))

    def test_forbidden_exposure(self):
        self.config_fixture.config(debug=False)

        risky_info = uuid.uuid4().hex
        e = exception.Forbidden(message=risky_info)
        self.assertValidJsonRendering(e)
        self.assertNotIn(risky_info, six.text_type(e))

    def test_forbidden_exposure_in_debug(self):
        self.config_fixture.config(debug=True)

        risky_info = uuid.uuid4().hex
        e = exception.Forbidden(message=risky_info)
        self.assertValidJsonRendering(e)
        self.assertIn(risky_info, six.text_type(e))

    def test_forbidden_action_exposure(self):
        self.config_fixture.config(debug=False)

        risky_info = uuid.uuid4().hex
        action = uuid.uuid4().hex
        e = exception.ForbiddenAction(message=risky_info, action=action)
        self.assertValidJsonRendering(e)
        self.assertNotIn(risky_info, six.text_type(e))
        self.assertIn(action, six.text_type(e))

        e = exception.ForbiddenAction(action=risky_info)
        self.assertValidJsonRendering(e)
        self.assertIn(risky_info, six.text_type(e))

    def test_forbidden_action_exposure_in_debug(self):
        self.config_fixture.config(debug=True)

        risky_info = uuid.uuid4().hex

        e = exception.ForbiddenAction(message=risky_info)
        self.assertValidJsonRendering(e)
        self.assertIn(risky_info, six.text_type(e))

        e = exception.ForbiddenAction(action=risky_info)
        self.assertValidJsonRendering(e)
        self.assertIn(risky_info, six.text_type(e))

    def test_unicode_argument_message(self):
        self.config_fixture.config(debug=False)

        risky_info = u'\u7ee7\u7eed\u884c\u7f29\u8fdb\u6216'
        e = exception.Forbidden(message=risky_info)
        self.assertValidJsonRendering(e)
        self.assertNotIn(risky_info, six.text_type(e))


text:
<?php
// On démarre la session AVANT d'écrire du code HTML
session_start();

?>
<!DOCTYPE HTML>

		<?php
			include 'head_Vehicule.php';
			echo "<link href='CSS/default1.css' rel='stylesheet'>";
			echo "<link rel='stylesheet' href='CSS/google_map.css' />";
			echo "";
		?>

		<?php $_SESSION['Nav_Activ'] = 1;
		include 'Menu_Nav_Vehicule.php';?>

	<?php
			if (empty($_GET['Immatriculation'])) {
				$Immatriculation = 'TW-080-XH';
				//$Immatriculation=$_SESSION['Immatriculation'];
				//$_SESSION['Immatriculation']=$Immatriculation;
			} else {
				$Immatriculation=$_GET['Immatriculation'];
				$_SESSION['Immatriculation']=$Immatriculation;
			}

			//$sql="SELECT Immatriculation,NumeroSerie,Nom,Prenom,Marque,Modele,Genre,Couleur,Teinte,Pays FROM Vehicule where Immatriculation='$Immatriculation';";
			//$results = tableSQL($sql);

			echo "
";
			echo "
";

				//foreach ($results as $ligne) {
					//on extrait chaque valeur de la ligne courante
					$Immatriculation = 'TW-080-XH';
					$NumeroSerie = 'unNumeroSerie';
					$Nom = 'UnNom';
					$Prenom = 'UnPrenom';
					$Marque = 'Peugeot';
					$Modele = '308 SW';
					$Couleur = 'Grise';
					$Pays = 'France';
					//$Immatriculation = $ligne[0];
					//$NumeroSerie = $ligne[1];
					//$Nom = $ligne[2];
					//$Prenom = $ligne[3];
					//$Marque = $ligne[4];
					//$Modele = $ligne[5];
					//$Couleur = $ligne[7];
					//$Pays = $ligne[9];
				//}
		?>

Géolocalisation du véhicule (Test)

			<form id='annuler' action ='' method='post'>

					<button type='submit' class='btn btn-default' aria-label='Left Align'>
  						Annuler
					</button>

			</form>


text:
package org.apache.falcon.cli;

import org.apache.falcon.resource.TestContext;
import org.apache.falcon.util.OozieTestUtils;
import org.apache.falcon.util.StartupProperties;
import org.testng.Assert;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

import java.util.Map;

/**
 * Smoke Test for Falcon CLI.
 */
public class FalconCLISmokeIT {

    private static final String START_INSTANCE = "2012-04-20T00:00Z";

    @BeforeClass
    public void prepare() throws Exception {
        TestContext.prepare();

        String services = StartupProperties.get().getProperty("application.services");
        StartupProperties.get().setProperty("application.services",
                services + ",org.apache.falcon.metadata.MetadataMappingService");
    }

    @Test
    public void testSubmitAndScheduleEntityValidCommands() throws Exception {

        String filePath;
        TestContext context = new TestContext();
        Map<String, String> overlay = context.getUniqueOverlay();

        filePath = TestContext.overlayParametersOverTemplate(context.getClusterFileTemplate(), overlay);
        Assert.assertEquals(-1,
                executeWithURL("entity -submitAndSchedule -type cluster -file " + filePath));
        context.setCluster(overlay.get("cluster"));

        // this is necessary for lineage
        Assert.assertEquals(0, executeWithURL("entity -submit -type cluster -file " + filePath));
        // verify
        Assert.assertEquals(0, executeWithURL("graph -vertices -key name -value " + context.getClusterName()));

        filePath = TestContext.overlayParametersOverTemplate(TestContext.FEED_TEMPLATE1, overlay);
        Assert.assertEquals(0,
                executeWithURL("entity -submitAndSchedule -type feed -file " + filePath));

        filePath = TestContext.overlayParametersOverTemplate(TestContext.FEED_TEMPLATE2, overlay);
        Assert.assertEquals(0,
                executeWithURL("entity -submitAndSchedule -type feed -file " + filePath));

        filePath = TestContext.overlayParametersOverTemplate(TestContext.FEED_TEMPLATE1, overlay);
        Assert.assertEquals(0,
                executeWithURL("entity -submit -type feed -file " + filePath));

        filePath = TestContext.overlayParametersOverTemplate(TestContext.FEED_TEMPLATE2, overlay);
        Assert.assertEquals(0,
                executeWithURL("entity -submit -type feed -file " + filePath));

        filePath = TestContext.overlayParametersOverTemplate(TestContext.PROCESS_TEMPLATE, overlay);
        Assert.assertEquals(0,
                executeWithURL("entity -validate -type process -file " + filePath));

        filePath = TestContext.overlayParametersOverTemplate(TestContext.PROCESS_TEMPLATE, overlay);
        Assert.assertEquals(0,
                executeWithURL("entity -submitAndSchedule -type process -file "
                        + filePath));

        OozieTestUtils.waitForProcessWFtoStart(context);

        Assert.assertEquals(0,
                executeWithURL("entity -definition -type cluster -name " + overlay.get("cluster")));

        Assert.assertEquals(0,
                executeWithURL("instance -status -type feed -name "
                        + overlay.get("outputFeedName") + " -start " + START_INSTANCE));

        Assert.assertEquals(0,
                executeWithURL("instance -running -type process -name " + overlay.get("processName")));
    }

    private int executeWithURL(String command) throws Exception {
        return new FalconCLI()
                .run((command + " -url " + TestContext.BASE_URL).split("\\s+"));
    }
}


text:
* Versi 0.1-20110926

### Alur umum
[GraphViz image | ini pake gambar yang mana ya]

#### Jahit
[GraphViz image | ini pake gambar yang mana ya]

### Moda Buat Baru
#### Jahit
* Rootstrap

Rootstrap adalah proses menyiapkan struktur direktori sistem yang di dalamnya
dipasang paket-paket yang diinginkan. Rootstrap dilakukan menggunakan dalam
beberapa tahap.

* debootstrap

Sistem dibuat dari 0 menggunakan debootstrap. Hasilnya adalah sebuah direktori
berisi sistem dasar, diberi nama `$ROOTFS`. Sistem ini harus dapat dimasuki
dengan melakukan chroot.

* Instalasi paket-paket berdasarkan profil

sources.list dibuat dalam direktori `$ROOTFS` dengan menunjuk ke lumbung sesuai
profil. Sistem dasar hasil debootstrap kemudian diaktifkan menggunakan chroot.
Semua perintah `$CHROOT` di dokumen ini merupakan singkatan dari perintah

```
sudo chroot $ROOTFS
```

Di dalam chroot, perbarui semua paket yang telah dibuat menggunakan debootstrap

```
$CHROOT apt-get update
$CHROOT apt-get --purge --dist-upgrade
```

Setelah itu, instal paket bibit utama yang telah didefinisikan dalam $PACKAGES

```
$CHROOT apt-get install $PACKAGES
```

* Pasang kernel

Yang diperlukan di sini sebenarnya bukan kernelnya, tapi modul-modul kernelnya.
Kernel dan initrd yang nantinya dipakai untuk boot dipasang terpisah dalam
bootloader.

```
$CHROOT apt-get install $KERNEL_PACKAGES
```

* Hapus paket daftar hitam

Selanjutnya, hapus paket-paket yang masuk ke dalam daftar hitam. Ini berguna
untuk menghapus paket-paket yang tidak diinginkan namun terbawa karena
"recommends" oleh paket yang terpasang.

```
$CHROOT apt-get remove --force-yes --yes $BLACKLISTED_PACKAGES
```

* Pembersihan sistem

Semua berkas-berkas sementara hasil pekerjaan di atas harus dibersihkan agar
tidak memakan tempat di struktur direktori yang dihasilkan.

```
$CHROOT apt-get --force-yes --yes clean
$CHROOT apt-get --force-yes --yes autoremove
$CHROOT rm -f /var/lib/dpkg/*-old
$CHROOT rm -f /var/cache/debconf/*-old
```

Setelah tahap ini, struktur direktori siap dicetak dalam sebuah RootFS.

* RootFS

RootFS adalah berkas berisi cetakan struktur direktori yang sudah dibuat pada
proses rootstrap. RootFS dibuat menggunakan squashfs yang merupakan sistem
pemberkasan terkompresi.

```
$CHROOT mksquashfs / filesystem.squashfs -b 1048576 -processors $NUMPROC -no- progress -e /filesystem.squashfs /unmounted
```

Hasil perintah di atas adalah berkas `$ROOTFS/filesystem.squashfs`.


text:
from django.contrib import admin

from event.models import Event

class EventArtistsInline(admin.TabularInline):
    model = Event.artists.through
    verbose_name_plural = 'Artists'
    extra = 1

class EventInline(admin.StackedInline):
    model = Event
    extra = 1

class EventAdmin(admin.ModelAdmin):
    inlines = [EventArtistsInline]
    list_display = ['name', 'start', 'venue']
    list_filter = ['name', 'start', 'venue__name']
    search_fields = ['name', 'start', 'venue__name']

admin.site.register(Event, EventAdmin)


text:
def select_all
  $pad.tag_add("sel", "1.0", "end")
  $pad.mark_set("insert", "end")
end

def undo
  begin
    $pad.edit_undo
  rescue RuntimeError
  end
end

def copy
  $pad.event_generate("<Copy>")
end

def cut
  $pad.event_generate("<Cut>")
end

def paste
  $pad.event_generate("<Paste>")
end

def delete
  begin
    $pad.delete("sel.first","sel.last")
  rescue RuntimeError
  end
end

def search
  $search_window = TkToplevel.new($root) {
    title "Search"
  }

  search_content = Tk::Tile::Frame.new($search_window) {
    padding "3 3 3 3"
  }.grid( :sticky => "nsew")

  Tk::Tile::Label.new(search_content) {
    text "Search :"
  }.grid( :column => 1, :row => 1)

  $search_entry = TkVariable.new

  entry = Tk::Tile::Entry.new(search_content) {
    textvariable $search_entry
  }.grid( :column => 2, :row => 1)

  $search_selection = TkVariable.new
  $search_selection.value = "no"

  Tk::Tile::CheckButton.new(search_content) {
    text "Search in selection"
    variable $search_selection
    onvalue "yes"
    offvalue "no"
  }.grid( :column => 1, :row => 2, :columnspan => 2, :sticky => "w")

  $search_case = TkVariable.new
  $search_case.value = "no"

  Tk::Tile::CheckButton.new(search_content) {
    text "Match case"
    variable $search_case
    onvalue "yes"
    offvalue "no"
  }.grid( :column => 1, :row => 3, :columnspan => 2, :sticky => "w")

  Tk::Tile::Button.new(search_content) {
    text "Find next"
    command "search_next"
  }.grid( :column => 3, :row => 1)

  Tk::Tile::Button.new(search_content) {
    text "Cancel"
    command "search_exit"
  }.grid( :column => 3, :row => 3)

  Tk::Tile::Button.new(search_content) {
    text "Find all"
    command "search_all"
  }.grid( :column => 3, :row => 2)

  $search_window.bind("Return") {
    search_next
  }

  entry.focus
end

def search_next
  $pad.tag_delete("search_result")
  if ($search_pos == "" || $search_pos == nil)
    if $search_selection == "no"
      $search_start = "1.0"
    else
      $search_start = "sel.first"
    end
  end
  if $search_selection.value == "yes"
    begin
      if $search_case.value == "no"
        $search_pos = $pad.tksearch(["nocase"],$search_entry.value, $search_start, "sel.last")
      else
        $search_pos = $pad.search($search_entry.value, $search_start, "sel.last")
      end
    rescue RuntimeError
    end
  else
    if $search_case.value == "no"
      $search_pos = $pad.tksearch(["nocase"], $search_entry.value, $search_start,"end")
    else
      $search_pos = $pad.search($search_entry.value, $search_start,"end")
    end
  end
  return if $search_pos == "" || $search_pos == nil
  $pad.tag_configure("search_result", :background => "green")
  $pad.tag_add("search_result",$search_pos,"#{$search_pos+$search_entry.value.length}")
  $search_start = $search_pos+$search_entry.value.length
end

def search_all
  $pad.tag_delete("search_result")
  return if $search_entry.value == ""
  if $search_selection.value == "no"
    $search_start = "1.0"
  else
    $search_start = "sel.first"
  end
  loop {
    if $search_selection.value == "yes"
      begin
        if $search_case.value == "no"
          $search_pos = $pad.tksearch(["nocase"],$search_entry.value, $search_start, "sel.last")
        else
          $search_pos = $pad.search($search_entry.value, $search_start, "sel.last")
        end
      rescue RuntimeError
      end
    else
      if $search_case.value == "no"
        $search_pos = $pad.tksearch(["nocase"], $search_entry.value, $search_start,"end")
      else
        $search_pos = $pad.search($search_entry.value, $search_start,"end")
      end
    end
    return if $search_pos == "" || $search_pos == nil
    $pad.tag_configure("search_result", :background => "green")
    $pad.tag_add("search_result",$search_pos,"#{$search_pos+$search_entry.value.length}")
    $search_start = $search_pos+$search_entry.value.length
  }
end

def search_exit
  $pad.tag_delete("search_result")
  $search_window.destroy
end

def time_date
  time = Time.now
  output = time.hour.to_s.rjust(2, "0") + ":"
  output += time.min.to_s.rjust(2, "0") + " "
  output += time.year.to_s.rjust(4, "0") + "-"
  output += time.month.to_s.rjust(2, "0") + "-"
  output += time.day.to_s.rjust(2, "0")
  $pad.insert("insert", output)
end


text:
package nlpassessment;

import java.io.File;

import java.io.FileReader;
import java.io.FileWriter;
import java.lang.ProcessBuilder.Redirect;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Scanner;

/**
 *
 * @author Neal
 */
public class Utility {

    //Waits for the process to end & returns the result
    //TODO: build variant which returns Process
    public static int runCommand(String cmd) {

        ProcessBuilder pb = new ProcessBuilder(cmd);

        try {

            Process process = pb.start();
            process.waitFor();
            return process.exitValue();

        } catch (Exception e) {
            System.out.println("Error running command: " + cmd + "\nMessage: " + e.getMessage());
            return -1;
        }
    }

    public static int countNonemptyLines(String fileName) {
        ArrayList<String> lines = readFileAsLines(fileName);
        int lineCount = 0;
        for (String line : lines) {
            if (!line.trim().isEmpty()) {
                lineCount++;
            }
        }
        System.out.println("Non-empty lines in " + fileName + ": " + lineCount);

        return lineCount;
    }

    public static int countLinesMatching(String fileName, String regex) {
        ArrayList<String> lines = readFileAsLines(fileName);
        int lineCount = 0;
        for (String line : lines) {
            if (!line.trim().matches(regex)) {
                lineCount++;
            }
        }
        System.out.println("Non-empty lines in " + fileName + ": " + lineCount);

        return lineCount;
    }

    public static ArrayList<Token> readFileAsStandardTokens(String fileName, String targetTag) {
        return standardLinesToTokens(readFileAsLines(fileName), targetTag);
    }

    public static ArrayList<Token> readFileAsShortTokens(String fileName, int lineLength, String targetTag) {
        return shortLinesToTokens(readFileAsLines(fileName), lineLength, targetTag);
    }

    public static String listToString(ArrayList<String> lines, boolean insertLineBreaks) {
        String condensed = "";
        if (insertLineBreaks) {
            for (String line : lines) {
                condensed += ("\n" + line);
            }
        } else {
            for (String line : lines) {
                condensed += (line);
            }
        }
        return condensed;
    }

    public static String arrayToString(String[] tokens, boolean spacesBetweenTokens) {
        String string = tokens[0];
        for (int i = 1; i < tokens.length; i++) {
            string += (" " + tokens[i]);
        }
        return string;
    }

    public static Integer[] countTokensPerLine(ArrayList<String> lines) {
        Integer[] tokenCounts = new Integer[lines.size()];
        for (int i = 0; i < lines.size(); i++) {
            tokenCounts[i] = lines.get(i).split("\\s+").length;
        }
        return tokenCounts;
    }

    /*
     Reads a file and returns its lines in an arraylist
     */
    public static ArrayList<String> readFileAsLines(String fileName) {
        ArrayList<String> lines = new ArrayList<>();
        Scanner inFile = null;

        try {
            System.out.println(new File("").getAbsolutePath());
            System.out.println(fileName);
            inFile = new Scanner(new FileReader(fileName));
        } catch (Exception e) {
            System.out.println("Failed to open input file. Exiting.");
            System.exit(-1);
        }

        while (inFile.hasNextLine()) {
            lines.add(inFile.nextLine());
        }
        return lines;
    }

    public static String readFileAsString(String fileName, boolean insertLineBreaks) {
        return listToString(readFileAsLines(fileName), insertLineBreaks);
    }

    //TODO:
    public static ArrayList<Token> tsvToTokens(ArrayList<String> lines, ArrayList<String> fields) {
        ArrayList<Token> tokens = new ArrayList<>();

        //TODO: Write. Generalized.

        return tokens;
    }

    //Input: Any standardized set of lines (one token per line, 4 fields per token)
    //Returns a list of tokens corresponding to the tokens on those lines
    //Assumes all tokens are semantic
    //TODO: Check/test
    public static ArrayList<Token> standardLinesToTokens(ArrayList<String> lines, String targetTag) {

        ArrayList<Token> tokens = new ArrayList<>();
        for (String line : lines) {
            String[] split = line.split("\\s+");
            if (split.length == 4) {
                Token token = new Token(split[2]);
                token.indexInText = Integer.parseInt(split[0]);
                token.indexInSentence = Integer.parseInt(split[1]);
                token.tags.put(targetTag, split[3]);
                tokens.add(token);
            } else {
                System.out.println("Invalid line: " + line + " has " + split.length + " tokens.");
            }
        }
        return tokens;
    }

    //Input: Lines in token-whitepace-tag format
    //Output: Token list with indexInText set, and "semantic" defaulted to true
    //TODO: FIX
    public static ArrayList<Token> shortLinesToTokens(ArrayList<String> lines, int lineLength, String targetTag) {
        ArrayList<Token> tokens = new ArrayList<>();
        int tokenCount = 0;
        for (String line : lines) {
            String[] split = line.split("\\s+");
            if (split.length == 3
                    && lineLength == 3) {
                tokenCount++;
                //TODO: THIS IS WRONG
                Token token = new Token(split[0]);
                token.indexInText = tokenCount;

                tokens.add(token);
            } else if (split.length == 2
                    && lineLength == 2) {
                tokenCount++;
                Token token = new Token(split[0]);
                token.indexInText = tokenCount;
                token.tags.put(targetTag, split[1]);
                tokens.add(token);
            } else {
                System.out.println("Invalid line: " + line + " has " + split.length + " tokens.");
            }
        }
        return tokens;
    }

    //Uses Token.toString()
    public static ArrayList<String> tokensToStandardLines(ArrayList<Token> tokens) {
        ArrayList<String> lines = new ArrayList<>();
        for (Token token : tokens) {
            lines.add(token.toString());
        }
        return lines;
    }

    //Includes only Token.token and Token.tagset in each line
    public static ArrayList<String> tokensToShortLines(ArrayList<Token> tokens, String targetTag) {
        ArrayList<String> lines = new ArrayList<>();
        for (Token token : tokens) {
            lines.add(token.indexInText + "\t" + token.token + "\t" + token.tags.get(targetTag));
        }
        return lines;
    }

    public static void writeFile(String contents, String fileName) {
        try {
            File file = new File(fileName);
            FileWriter writer = null;
            writer = new FileWriter(file);
            writer.write(contents);
            writer.close();

        } catch (Exception e) {
            System.out.println("Failed to complete output file. Exiting.");
            System.exit(-1);
        }
    }

    /*
     General file output method
     */
    public static void writeFile(ArrayList<String> lines, String fileName) {

        try {
            File file = new File(fileName);
            FileWriter writer = null;
            writer = new FileWriter(file);

            for (String line : lines) {
                writer.write(line + "\n");
            }

            writer.close();

        } catch (Exception e) {
            System.out.println("Failed to complete output file. Exiting.");
            System.exit(-1);
        }

    }

    public static HashMap<String, Integer> getTagCounts(ArrayList<Token> tokens, String targetTag) {

        HashMap<String, Integer> tagCounts = new HashMap<>();

        for (Token token : tokens) {
            if (tagCounts.keySet().contains(token.tags.get(targetTag))) {
                tagCounts.put(token.tags.get(targetTag), tagCounts.get(token.tags.get(targetTag)) + 1);
            } else {
                tagCounts.put(token.tags.get(targetTag), 1);
            }
        }
        return tagCounts;
    }

    public static int getSemanticTokenCount(ArrayList<Token> tokens) {
        int count = 0;
        for (Token token : tokens) {
            if (token.semantic) {
                count++;
            }
        }
        return count;
    }

    public static void countTags(ArrayList<Token> tokens) {
        int adj = 0, noun = 0, adv = 0, verb = 0, other = 0;

        for (Token token : tokens) {
            if (token.tags.get("pos").equalsIgnoreCase("NN")) {
                noun++;
            } else if (token.tags.get("pos").equalsIgnoreCase("JJ")) {
                adj++;
            } else if (token.tags.get("pos").equalsIgnoreCase("RB")) {
                adv++;
            } else if (token.tags.get("pos").equalsIgnoreCase("VB")) {
                verb++;
            } else {
                other++;
            }
        }

    }

    //Compares tags of two standardized token lists
    //NOTE: list lengths and all contained tokens MUST match
    public static String compareTags(ArrayList<Token> results, ArrayList<Token> goldStandard, String key, String tagType) {

        if (results.size() != goldStandard.size()) {
            System.out.println("Tokens list lengths differ");
        }

        System.out.println("\n\n\nSTARTING COMPARISON"
                + "\n");

        int trueNegatives = 0;
        int falseNegatives = 0;
        int truePositives = 0;
        int falsePositives = 0;
        int tokenMismatches = 0;

        //Detect mismatches on tokens which differ between results and standard
        //Unless both are tagged "other"
        for (int i = 0; i < results.size(); i++) {
            if (!results.get(i).token.equalsIgnoreCase(goldStandard.get(i).token) //                    && !results.get(goldIter).tagset.equalsIgnoreCase("Other")
                    //                    && !goldStandard.get(goldIter).tagset.equalsIgnoreCase("Other")
                    ) {
                tokenMismatches++;
                System.out.println("Mismatch: " + results.get(i).toString() + " \t\t " + goldStandard.get(i).toString());
                System.out.println("Warning: Results invalid due to " + tokenMismatches + " token mismatches");
            }

            if (results.get(i).tags.get(tagType).equalsIgnoreCase(key)
                    && goldStandard.get(i).tags.get(tagType).equalsIgnoreCase(key)) {

                truePositives++;

            } else if (goldStandard.get(i).tags.get(tagType).equalsIgnoreCase(key)
                    && !results.get(i).tags.get(tagType).equalsIgnoreCase(key)) {

                falseNegatives++;

            } else if (results.get(i).tags.get(tagType).equalsIgnoreCase(key)
                    && !goldStandard.get(i).tags.get(tagType).equalsIgnoreCase(key)) {
                falsePositives++;

            } else {
                trueNegatives++;
            }

        }

        assert results.size() == (trueNegatives + truePositives + falseNegatives + falsePositives);

        double sensitivity = (double) truePositives / (double) (falseNegatives + truePositives);
        double specificity = (double) trueNegatives / (double) (falsePositives + trueNegatives);

        String report = key;
        report += "\nSampleSize = " + results.size();
        report += "\nTruePos = " + truePositives;
        report += "\nFalseNeg = " + falseNegatives;
        report += "\nFalsePos = " + falsePositives;
        report += "\nSensitivity = " + sensitivity;
        report += "\nSpecificity = " + specificity;

        return report;

    }

    //Returns the consensus of the input token lists
    //Inputs must already be standardized and restricted to common tokens
    //so that input list lengths are identical and all tokens match
    public static ArrayList<Token> getTagConsensus(ArrayList<ArrayList<Token>> inputs, double threshold, String target) {

        int agreement = 0;
        int unanimousDecision = 0;
        int disagreement = 0;

        ArrayList<Token> consensus = new ArrayList<>();

        //For each token i
        for (int i = 0; i < inputs.get(0).size(); i++) {

            HashMap<String, Integer> tagCount = new HashMap<>();
            Token token = new Token(inputs.get(0).get(i).token);
            token.indexInText = i;

            System.out.print("\nToken: " + token.token + " ");

            //Count instances of each tagset for this token i
            for (ArrayList<Token> list : inputs) {

                //Tokens must match
                assert list.get(i).token.equalsIgnoreCase(list.get((i + 1) % inputs.size()).token);

                String tag = list.get(i).tags.get(target);
                System.out.print(tag + " ");
                if (tagCount.containsKey(tag)) {
                    tagCount.put(tag, tagCount.get(tag) + 1);
                } else {
                    tagCount.put(tag, 1);
                }
            }

            //Find & set consensus tagset
            for (String tag : tagCount.keySet()) {
                if (tagCount.get(tag) > inputs.size() * threshold) {
                    token.tags.put(target, tag);
//                    System.out.print(" : " + tag);
                    agreement++;
                    if (tagCount.get(tag) == inputs.size()) {
                        unanimousDecision++;
                    }
                }
            }

            if (token.tags.get(target).equalsIgnoreCase("??")) {
                System.out.print(" : ????");
                disagreement++;
            }
            consensus.add(token);
        }

        assert (agreement + disagreement) == inputs.get(0).size();

        System.out.println("\nTarget tag type: " + target
                + "\nTokens: " + (agreement + disagreement)
                + "\nDisagreement: " + disagreement
                + "\nAgreements: " + agreement
                + "\nUnanimous: " + unanimousDecision);

        System.out.print("\nSizes: ");
        for (int i = 0; i < inputs.size(); i++) {
            System.out.print(inputs.get(i).size() + " ");
        }
        return consensus;
    }

    //Returns a new token list based on the "input" token list,
    //and excluding those tokens which fail to find a match in "standard"
    //"input" and "standard" lists are not modified
    //TODO: rewrite/clarify
    //skipCatchupRange helps determine how far to look when dealing with token mismatches
    //Higher skipCatchupRange numbers search further; 3 seems to work well for word-tokens
    //8 seems to work for character-tokens
    public static ArrayList<Token> getCommonTokenList(ArrayList<Token> input, ArrayList<Token> standard, int skipCatchupRange) {

        ArrayList<Token> output = new ArrayList<>();

        System.out.println("\n\nSTARTING PAIRWISE TOKEN REMOVAL");

        //Results variables
        int standardTokensIgnored = 0;
        int inputTokensExcluded = 0;
        int tokenCount = 0;

        //Iterators
        int stdIter = 0, inputIter = 0;
        while (stdIter < standard.size()
                && inputIter < input.size()) {

            //DETECTING TOKEN MISMATCH
            boolean tokenMatch = false;
            if (!input.get(inputIter).token.equalsIgnoreCase(standard.get(stdIter).token)) {
//                System.out.println("Token mismatch: std='" + standard.get(stdIter).i + "' input='" + input.get(inputIter).i + "'");
            } else {
                tokenMatch = true;
            }

            //HANDLING TOKEN MISMATCH
            //Uses the standard iterator as an anchor, searches in increasingly wide regions
            //around the output iterator, but only forward of the starting point
            //The further the standard iterator has to increase, the further the input iterator is allowed to range
            //Neither is permitted to search backwards from their starting position at mismatch,
            //since it can be assumed that immediately preceding tokens are properly matched
            if (!tokenMatch) {
                int startingInputIter = inputIter;

                //corrections for ugly algorithm below
                int deltaStdIter = -1;
                stdIter--;

                //ITERATING FORWARD IN GOLD STANDARD
                while (!tokenMatch
                        && stdIter < standard.size() - 2) {
                    stdIter++;
                    deltaStdIter++;

                    //SEARCHING INCREASINGLY WIDE IN RESULTS TO FIND MATCHING TOKEN
                    inputIter = startingInputIter + Math.max(0, deltaStdIter / 2 - skipCatchupRange);

                    while (inputIter < startingInputIter + deltaStdIter * 1.5 + skipCatchupRange
                            && inputIter < input.size()) {
                        if (input.get(inputIter).token.equalsIgnoreCase(standard.get(stdIter).token)) {
                            tokenMatch = true;

                            //Debug
//                            System.out.println("Match found: " + input.get(inputIter).i + "=" + standard.get(stdIter).i);
                            break;
                        } else {
                            inputIter++;
                        }
                    }

                }

                //CALCULATING TRACKERS
                int deltaInputIter = inputIter - startingInputIter;
//                System.out.println("Ignored " + deltaInputIter + " input tokens and " + deltaStdIter + " standard tokens this mismatch");
                standardTokensIgnored += deltaStdIter;
                inputTokensExcluded += deltaInputIter;

                //Debug
//                if (stdIter < standard.size() && inputIter < input.size()) {
//                    System.out.println("Gold: " + stdIter + " " + standard.get(stdIter).i + " Res: " + inputIter + " " + input.get(inputIter).i);
//                }
            }

            //ADD INPUT TOKEN TO OUTPUT
            if (tokenMatch) {
                tokenCount++;
                Token token = input.get(inputIter);
                token.indexInText = tokenCount;
                output.add(token);
            } else {
                System.out.println("ERROR: MATCHING FAILED");
            }

//            //Debug
//            if (stdIter >= standard.size()
//                    || inputIter >= input.size()) {
//                System.out.println("ITERATOR OUT OF BOUNDS");
//                System.out.println("Standard Iterator: " + stdIter + "/" + standard.size()
//                        + "\n" + "Target Iterator: " + inputIter + "/" + input.size());
//                break;
//            }
            inputIter++;
            stdIter++;
        }

        assert (output.size() + inputTokensExcluded == input.size());

        System.out.println("\n" + standardTokensIgnored + "/" + standard.size() + " standard tokens unmatched "
                + "\n" + inputTokensExcluded + "/" + input.size() + " input tokens excluded");

        return output;

    }

    //Returns a list of tokens, excluding any tokens which don't appear in *all* input lists
    //Uses the list at "base" as the starting list (so its tags and other data are used)
    //and restricts from there
    public static ArrayList<Token> getCommonlTokenList(ArrayList<ArrayList<Token>> inputs, int base, int skipCatchupRange) {

        //Start with arbitrary base token list
        ArrayList<Token> output = inputs.get(base);

        //Iterate through other lists, restricting base list to tokens for which
        //matches are found in the other lists
        for (int i = 0; i < inputs.size(); i++) {
            if (i != base) {
                output = getCommonTokenList(output, inputs.get(i), skipCatchupRange);
            }
        }

        System.out.print("\nInput lengths: ");
        for (ArrayList<Token> list : inputs) {
            System.out.print(list.size() + ", ");
        }

        System.out.print("\nOutput length: " + output.size());
        return output;
    }

}


text:
static const quint16 DefaultLocalPort = 1965;

O0BaseAuth::O0BaseAuth(QObject *parent, O0AbstractStore *store): QObject(parent), store_(0), useExternalWebInterceptor_(false), replyServer_(NULL) {
    localPort_ = DefaultLocalPort;
    setStore(store);
}

void O0BaseAuth::setStore(O0AbstractStore *store) {
    if (store_) {
        store_->deleteLater();
    }
    if (store) {
        store_ = store;
        store_->setParent(this);
    } else {
        store_ = new O0SettingsStore(O2_ENCRYPTION_KEY, this);
        return;
    }
}

bool O0BaseAuth::linked() {
    QString key = QString(O2_KEY_LINKED).arg(clientId_);
    bool result = !store_->value(key).isEmpty();
    qDebug() << "O0BaseAuth::linked:" << (result? "Yes": "No");
    return result;
}

void O0BaseAuth::setLinked(bool v) {
    qDebug() << "O0BaseAuth::setLinked:" << (v? "true": "false");
    bool oldValue = linked();
    QString key = QString(O2_KEY_LINKED).arg(clientId_);
    store_->setValue(key, v? "1": "");
    if (oldValue != v) {
        Q_EMIT linkedChanged();
    }
}

QString O0BaseAuth::tokenSecret() {
    QString key = QString(O2_KEY_TOKEN_SECRET).arg(clientId_);
    return store_->value(key);
}

void O0BaseAuth::setTokenSecret(const QString &v) {
    QString key = QString(O2_KEY_TOKEN_SECRET).arg(clientId_);
    store_->setValue(key, v);
    Q_EMIT tokenSecretChanged();
}

QString O0BaseAuth::token() {
    QString key = QString(O2_KEY_TOKEN).arg(clientId_);
    return store_->value(key);
}

void O0BaseAuth::setToken(const QString &v) {
    QString key = QString(O2_KEY_TOKEN).arg(clientId_);
    store_->setValue(key, v);
    Q_EMIT tokenChanged();
}

QString O0BaseAuth::clientId() {
    return clientId_;
}

void O0BaseAuth::setClientId(const QString &value) {
    clientId_ = value;
    Q_EMIT clientIdChanged();
}

QString O0BaseAuth::clientSecret() {
    return clientSecret_;
}

void O0BaseAuth::setClientSecret(const QString &value) {
    clientSecret_ = value;
    Q_EMIT clientSecretChanged();
}

bool O0BaseAuth::useExternalWebInterceptor() {
    return useExternalWebInterceptor_;
}

void O0BaseAuth::setUseExternalWebInterceptor(bool useExternalWebInterceptor) {
    useExternalWebInterceptor_ = useExternalWebInterceptor;
}

QByteArray O0BaseAuth::replyContent() const {
    if(replyServer_ != NULL) {
        return replyServer_->replyContent();
    }

    return QByteArray();
}

void O0BaseAuth::setReplyContent(const QByteArray &value) {
    if(replyServer_ != NULL) {
        return replyServer_->setReplyContent(value);
    }
}

int O0BaseAuth::localPort() {
    return localPort_;
}

void O0BaseAuth::setLocalPort(int value) {
    qDebug() << "O0BaseAuth::setLocalPort:" << value;
    localPort_ = value;
    Q_EMIT localPortChanged();
}

QVariantMap O0BaseAuth::extraTokens() {
    QString key = QString(O2_KEY_EXTRA_TOKENS).arg(clientId_);
    QString value = store_->value(key);
    QByteArray bytes = QByteArray::fromBase64(value.toLatin1());
    QDataStream stream(&bytes, QIODevice::ReadOnly);
    stream >> extraTokens_;
    return extraTokens_;
}

void O0BaseAuth::setExtraTokens(QVariantMap extraTokens) {
    extraTokens_ = extraTokens;
    QByteArray bytes;
    QDataStream stream(&bytes, QIODevice::WriteOnly);
    stream << extraTokens;
    QString key = QString(O2_KEY_EXTRA_TOKENS).arg(clientId_);
    store_->setValue(key, bytes.toBase64());
    Q_EMIT extraTokensChanged();
}

QByteArray O0BaseAuth::createQueryParameters(const QList<O0RequestParameter> &parameters) {
    QByteArray ret;
    bool first = true;
    foreach (O0RequestParameter h, parameters) {
        if (first) {
            first = false;
        } else {
            ret.append("&");
        }
        ret.append(QUrl::toPercentEncoding(h.name) + "=" + QUrl::toPercentEncoding(h.value));
    }
    return ret;
}