text:
package fr.areaX.dao;

import static org.junit.Assert.assertEquals;

import java.sql.Connection;

import org.json.*;
import org.postgresql.jdbc2.TimestampUtils;

import fr.areaX.biometry.Histogramme;

import java.sql.Date;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Iterator;

public class PostgreSQLJDBC {

	public int addUser(int id_card,Date birthday,String firstName, String lastName,String histogram){
		PostgreSQLJDBC server = new PostgreSQLJDBC();
		server.createCard(id_card);
		int id_user = server.createUser(firstName, lastName, birthday, new JSONArray(histogram));
		server.attachCardToUser(id_card, id_user);
		return server.createSession(id_user, 6);
	}
	private int createSession(int id_user, int hour_delay) {
		Connection c = connectToDatabase();
		Statement commande = null;
		Integer token = null;
		try {
			commande = c.createStatement();
			// TO DO generate Token, repasser à bytea pour générer dans SQL ?
			token = 5;
			String sql = "INSERT INTO session (id_session,token,time_creation,time_end,user_session,salt) VALUES(DEFAULT,"
					+ token
					+ ", current_timestamp, CURRENT_TIMESTAMP + interval '"
					+ hour_delay + " hours'"
					+ "," + id_user + ","
					+ "gen_salt('md5'))";
			commande.execute(sql);
			commande.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return token;
	}
	private Connection connectToDatabase() {
		Connection c = null;
		try {
			// Class.forName("org.postgresql.Driver");
			c = DriverManager.getConnection(
					"jdbc:postgresql://localhost:5432/test", "test", "test");
		} catch (Exception e) {
			e.printStackTrace();
			System.err.println(e.getClass().getName() + ": " + e.getMessage());
			System.exit(0);
		}
		System.out.println("Opened database successfully");
		return c;
	}

	public boolean resetTable() {
		Connection c = connectToDatabase();
		try {
			Statement commande = c.createStatement();
			// CARDS
			String sql = "DROP TABLE IF EXISTS cards CASCADE";
			commande.executeUpdate(sql);
			sql = "CREATE TABLE cards(" + "id_card serial NOT NULL,"
					+ "active boolean NOT NULL DEFAULT true,"
					+ "CONSTRAINT cards_pkey PRIMARY KEY (id_card))"
					+ "WITH (OIDS=FALSE);";
			commande.execute(sql);
			// USERS
			sql = "DROP TABLE IF EXISTS users CASCADE";
			commande.executeUpdate(sql);
			sql = "CREATE TABLE users(" + "id_user serial NOT NULL,"
					+ "first_name text," + "last_name text,"
					+ "birthdate date," + "histogram json,"
					+ "CONSTRAINT users_pkey PRIMARY KEY (id_user))"
					+ "WITH (OIDS=FALSE);";
			commande.executeUpdate(sql);
			// SESSION
			sql = "DROP TABLE IF EXISTS session CASCADE";
			commande.executeUpdate(sql);
			sql = "CREATE TABLE session(" + "id_session serial NOT NULL,"
					+ "token integer," + "time_creation timestamp with time zone,"
					+ "time_end timestamp with time zone,"
					+ "user_session integer," + "salt text,"
					+ "CONSTRAINT session_pkey PRIMARY KEY (id_session))"
					+ "WITH (OIDS=FALSE);";
			commande.executeUpdate(sql);
			// CARTE OWNER
			sql = "DROP TABLE IF EXISTS card_owner CASCADE";
			commande.executeUpdate(sql);
			sql = "CREATE TABLE card_owner(id_card_owner serial NOT NULL,"
					+ "card integer," + "owner integer,"
					+ "time_assignment timestamp with time zone,"
					+ "CONSTRAINT card_owner_pkey PRIMARY KEY (id_card_owner),"
					+ "CONSTRAINT card_owner_card_fkey FOREIGN KEY (card)"
					+ "REFERENCES cards (id_card) MATCH SIMPLE "
					+ "ON UPDATE NO ACTION ON DELETE NO ACTION)"
					+ "WITH (OIDS=FALSE);";
			commande.executeUpdate(sql);
			// LOG

			sql = "DROP TABLE IF EXISTS logs CASCADE";
			commande.executeUpdate(sql);
			sql = "CREATE TABLE logs("
					+ "id_log serial NOT NULL,"
					+ "card_owner integer,"
					+ "user_recognize integer,"
					+ "card_used integer,"
					+ "time_access timestamp with time zone,"
					+ "current_session integer,"
					+ "message text,"
					+ "CONSTRAINT logs_pkey PRIMARY KEY (id_log),"
					+ "CONSTRAINT logs_card_owner_fkey FOREIGN KEY (card_owner)"
					+ "REFERENCES card_owner (id_card_owner) MATCH SIMPLE "
					+ "ON UPDATE NO ACTION ON DELETE NO ACTION,"
					+ "CONSTRAINT logs_card_used_fkey FOREIGN KEY (card_used)"
					+ "REFERENCES cards (id_card) MATCH SIMPLE "
					+ "ON UPDATE NO ACTION ON DELETE NO ACTION,"
					+ "CONSTRAINT logs_current_session_fkey FOREIGN KEY (current_session)"
					+ "REFERENCES session (id_session) MATCH SIMPLE "
					+ "ON UPDATE NO ACTION ON DELETE NO ACTION,"
					+ "CONSTRAINT logs_user_recognize_fkey FOREIGN KEY (user_recognize)"
					+ "REFERENCES users (id_user) MATCH SIMPLE "
					+ "ON UPDATE NO ACTION ON DELETE NO ACTION)"
					+ "WITH (OIDS=FALSE)";
			commande.executeUpdate(sql);
			commande.close();

			c.close();
		} catch (SQLException e) {
			// TOO Auto-generated catch block
			e.printStackTrace();
		}
		return true;

	}

	public boolean emptyDatabase() {
		Connection c = connectToDatabase();
		try {
			Statement commande = c.createStatement();
			String sql = "TRUNCATE users, logs, cards,session, card_owner CASCADE";
			commande.executeUpdate(sql);
			commande.close();
			// c.commit();
			c.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return true;
	}

	public int createCard() {
		Connection c = connectToDatabase();
		int id_inserted = -1;
		try {
			Statement commande = c.createStatement();
			String sql = "INSERT INTO cards (id_card) VALUES (DEFAULT) RETURNING id_card";
			ResultSet result = commande.executeQuery(sql);
			if(result.next()){
			id_inserted = result.getInt("id_card");
			}
			commande.close();
			// c.commit();
			c.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return id_inserted;
	}

	public boolean createCard(int id) {
		Connection c = connectToDatabase();
		try {
			Statement commande = c.createStatement();
			String sql = "INSERT INTO cards (id_card) VALUES (" + id + ")";
			commande.executeUpdate(sql);
			commande.close();
			// c.commit();
			c.close();
		} catch (SQLException e) {
			return false;
		}
		return true;
	}

	public boolean setCardActive(int id_card, boolean state){
		Connection c = connectToDatabase();
		try {
			Statement commande = c.createStatement();
			String sql = "UPDATE cards SET active="+state+" WHERE id_card="+id_card;
			commande.executeUpdate(sql);
			commande.close();
			// c.commit();
			c.close();
		} catch (SQLException e) {
			return false;
		}
		return true;
	}

	public boolean createUser(int id, String first_name, String last_name,
			Date birthdate, JSONArray histo) {
		Connection c = connectToDatabase();
		try {
			Statement commande = c.createStatement();
			// date format YYYY-MM-DD
			String sql = "INSERT INTO users (id_user, first_name, last_name,birthdate, histogram) VALUES ("
					+ id
					+ ",'"
					+ first_name
					+ "','"
					+ last_name
					+ "','"
					+ birthdate.toString() + "','" + histo.toString() + "')";
			commande.executeUpdate(sql);
			commande.close();
			// c.commit();
			c.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		}
		return true;
	}

	/**
	 *
	 * @param first_name
	 * @param last_name
	 * @param birthdate
	 * @param histo
	 * @return
	 */
	public int createUser(String first_name, String last_name,
			Date birthdate, JSONArray histo) {
		Connection c = connectToDatabase();
		int id_user_inserted = -1;
		try {
			Statement commande = c.createStatement();
			// date format YYYY-MM-DD
			String sql = "INSERT INTO users (id_user, first_name, last_name,birthdate, histogram) VALUES (DEFAULT,'"
					+ first_name
					+ "','"
					+ last_name
					+ "','"
					+ birthdate.toString() + "','" + histo.toString() + "') RETURNING id_user";
			ResultSet result = commande.executeQuery(sql);
			if(result.next()){
				result.getInt("id_user");
			}
			commande.close();
			// c.commit();
			c.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return id_user_inserted;
	}

	public boolean verifyToken(String identifiant_card, String token) {
		Connection c = connectToDatabase();
		try {
			/*
			 * Statement commande = c.createStatement(); String[] content =
			 * cardContent.toString().split("#"); String identifiant =
			 * content[0]; String Token = content[1]; //String sql =
			 * "SELECT time_creation, time_end from session where token="
			 * +Byte.valueOf(Token)+"; if(commande.execute(sql)){
			 * commande.getResultSet(). } commande.close();
			 */
			c.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		}
		return false;
	}

	/**
	 *
	 * @param histogram
	 * @return a list of user id because the comparison can't be 100% accurate
	 */
	@SuppressWarnings("resource")
	public ArrayList<Integer> findUsersByBiometric(JSONArray histogram) {
		double ACCEPTATION_TRESHOLD = 0.15;
		ArrayList<Integer> users = new ArrayList<Integer>();
		Histogramme histo_tested = new Histogramme(histogram);
		Connection c = connectToDatabase();
		Integer id_user;
		String histo_string;
		try {
			Statement commande = c.createStatement();
			String sql = "SELECT id_user, histogram FROM users";
			ResultSet result = commande.executeQuery(sql);
			double value_distance;
			ResultSetMetaData resultMeta = result.getMetaData();
			while (result.next()) {
				System.out.println("entre dans la boucle");
				id_user = result.getInt(1);
				histo_string = result.getString(2);
				System.out.println(histo_string);
				value_distance = histo_tested.compare_histo(new Histogramme(
						histo_string));
				System.out.println("valeur bhat" + value_distance);
				if (value_distance < ACCEPTATION_TRESHOLD) {
					users.add(id_user);
				}
			}
			commande.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return users;
	}

	public Integer authenticate(int identityCard, int tokenSession,
			String histogram_string) throws Exception {
		JSONArray histogram = new JSONArray(histogram_string);
		ArrayList<Integer> user_matched = findUsersByBiometric(histogram);
		if (user_matched.size() <= 0) {
			//throw new Exception("user not find by biometrics");
			return 0;
		}
		Iterator<Integer> iter_user = user_matched.iterator();
		int user_id;
		do {
			if (cardIsValid(identityCard)) {
				user_id = iter_user.next();
				if (userIsCardOwner(user_id, identityCard)) {
					Integer tokenCurrentSession = sessionValid(user_id,
							tokenSession);
					return tokenCurrentSession;
				}
			}
		} while (iter_user.hasNext());

		return 0;
	}

	public Integer sessionValid(int user_id, int tokenSession) {
		Connection c = connectToDatabase();
		try {
			Statement commande = c.createStatement();
			// return la session la plus récente de cet utilisateur
			String sql = "SELECT token, time_creation, time_end FROM session WHERE user_session = "
					+ user_id + " ORDER BY time_creation DESC";
			ResultSet last_session = commande.executeQuery(sql);
			if (last_session.next()) {
				int tokenLastSession = last_session.getInt("token");
				if (tokenLastSession == tokenSession) {
					Timestamp time_end = last_session.getTimestamp("time_end");
					java.util.Date date = new java.util.Date();
					Timestamp currentTimestamp = new Timestamp(date.getTime());
					// expired timestamp
					if (currentTimestamp.compareTo(time_end) > 0) {
						return generateNewToken(user_id);
					} else {
						return tokenSession;
					}
				}
			}
			commande.close();
			// c.commit();
			c.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	public Integer generateNewToken(int user_id) {
		return 1;
	}

	public boolean userIsCardOwner(int id_user, int id_card) throws Exception {
		Connection c = connectToDatabase();
		Statement commande = null;
		try {
			commande = c.createStatement();
			// renvoye la dernier utilisateur associé à la carte;
			String sql = "SELECT owner,time_assignment FROM card_owner WHERE card="
					+ id_card + " ORDER BY time_assignment DESC";
			ResultSet result = commande.executeQuery(sql);
			if (result.next()) {
				int id_owner = result.getInt("owner");
				if (id_owner == id_user) {
					return true;
				}
			}
		} catch (Exception e) {
			throw e;
		} finally {
			commande.close();
		}
		return false;
	}

	/**
	 * verify if a card exist in the database and is still activated
	 *
	 * @param userData1
	 * @return
	 * @throws Exception
	 */
	public boolean cardIsValid(int id_card_tested) {
		Connection c = connectToDatabase();
		Statement commande = null;
		try {
			commande = c.createStatement();
			String sql = "SELECT active FROM cards WHERE id_card="
					+ id_card_tested +" AND active=TRUE";
			ResultSet result = commande.executeQuery(sql);
			if (result.next()) {
				boolean card_active = result.getBoolean(1);
				if (card_active) {
					return true;
				}
			}
			commande.close();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
		}
		return false;
	}

	public void attachCardToUser(int id_card, int id_user) {
		Connection c = connectToDatabase();
		Statement commande = null;
		try {
			commande = c.createStatement();
			String sql = "INSERT INTO card_owner (id_card_owner,card,owner,time_assignment) VALUES(DEFAULT,"
					+ id_card + "," + id_user + ", CURRENT_TIMESTAMP)";
			commande.execute(sql);
			commande.close();
		} catch (Exception e) {
			e.printStackTrace();
			;
		}
	}

	public Integer generateSession(int id_token, int id_user) {
		return generateSession(id_token, id_user, 0);
	}

	public Integer generateSession(int id_session, int id_user, int hour_delay) {
		Connection c = connectToDatabase();
		Statement commande = null;
		Integer token = null;
		try {
			commande = c.createStatement();
			// TO DO generate Token, repasser à bytea pour générer dans SQL ?
			token = 5;
			String sql = "INSERT INTO session (id_session,token,time_creation,time_end,user_session,salt) VALUES("
					+ id_session
					+ ","
					+ token
					+ ", current_timestamp, CURRENT_TIMESTAMP + interval '"
					+ hour_delay + " hours'"
					+ "," + id_user + ","
					+ "gen_salt('md5'))";
			commande.execute(sql);
			commande.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return token;
	}
	public void generateMockDatabase(){
		int id_card_with_user = createCard();
		int id_card_inactive = createCard();
		setCardActive(id_card_inactive, false);
		int id_card_none_affected = createCard();
		createUser("clement", "demonchy", new Date(0),new JSONArray("[0.4,0.6]"));

	}

}


text:
module EffectiveStripeHelper

  STRIPE_CONNECT_AUTHORIZE_URL = 'https://connect.stripe.com/oauth/authorize'
  STRIPE_CONNECT_TOKEN_URL = 'https://connect.stripe.com/oauth/token'

  def is_stripe_connect_seller?(user)
    Effective::Customer.for_user(user).try(:is_stripe_connect_seller?) == true
  end

  def link_to_new_stripe_connect_customer(opts = {})
    client_id = EffectiveOrders.stripe[:connect_client_id]

    raise ArgumentError.new('effective_orders config: stripe.connect_client_id has not been set') unless client_id.present?

    authorize_params = {
      response_type: :code,
      client_id: client_id,            # This is the Application's ClientID
      scope: :read_write,
      state: {
        form_authenticity_token: form_authenticity_token,   # Rails standard CSRF
        redirect_to: URI.encode(request.original_url)  # TODO: Allow this to be customized
      }.to_json
    }

    # Add the stripe_user parameter if it's possible
    stripe_user_params = opts.delete :stripe_user
    authorize_params.merge!({stripe_user: stripe_user_params}) if stripe_user_params.is_a?(Hash)

    authorize_url = STRIPE_CONNECT_AUTHORIZE_URL.chomp('/') + '?' + authorize_params.to_query
    options = {}.merge(opts)
    link_to image_tag('/assets/effective_orders/stripe_connect.png'), authorize_url, options
  end

  ### Subscriptions Helpers
  def stripe_plans_collection(plans)
    (plans || []).map { |plan| [stripe_plan_description(plan), plan.id, {'data-amount' => plan.amount}] }
  end

  def stripe_plan_description(plan)
    occurrence = case plan.interval
      when 'weekly'   ; '/week'
      when 'monthly'  ; '/month'
      when 'yearly'   ; '/year'
      when 'week'     ; plan.interval_count == 1 ? '/week' : " every #{plan.interval_count} weeks"
      when 'month'    ; plan.interval_count == 1 ? '/month' : " every #{plan.interval_count} months"
      when 'year'     ; plan.interval_count == 1 ? '/year' : " every #{plan.interval_count} years"
      else            ; plan.interval
    end

    "#{plan.name} - #{ActionController::Base.helpers.price_to_currency(plan.amount)} #{plan.currency.upcase}#{occurrence}"
  end

  def stripe_coupon_description(coupon)
    amount = coupon.amount_off.present? ? ActionController::Base.helpers.price_to_currency(coupon.amount_off) : "#{coupon.percent_off}%"

    if coupon.duration_in_months.present?
      "#{coupon.id} - #{amount} off for #{coupon.duration_in_months} months"
    else
      "#{coupon.id} - #{amount} off #{coupon.duration}"
    end
  end

end

redpajama_set_name: RedPajamaGithub


text:
<?php

// count products in cart
if (isset($_COOKIE['cart'])) {
    $cookie = urldecode($_COOKIE['cart']);
    $result = explode(',', $cookie);
    $count  = count($result);
}

$results = isset($count) ? $count : 0 ;
echo $results;


text:
#ifndef _UNLOCK_INDICATOR_H
#define _UNLOCK_INDICATOR_H

typedef enum {
    STATE_STARTED = 0,          /* default state */
    STATE_KEY_PRESSED = 1,      /* key was pressed, show unlock indicator */
    STATE_KEY_ACTIVE = 2,       /* a key was pressed recently, highlight part
                                   of the unlock indicator. */
    STATE_BACKSPACE_ACTIVE = 3  /* backspace was pressed recently, highlight
                                   part of the unlock indicator in red. */
} unlock_state_t;

typedef enum {
    STATE_PAM_IDLE = 0,         /* no PAM interaction at the moment */
    STATE_PAM_VERIFY = 1,       /* currently verifying the password via PAM */
    STATE_PAM_WRONG = 2         /* the password was wrong */
} pam_state_t;

xcb_pixmap_t draw_image(uint32_t* resolution);
void draw_image_core(cairo_t *screen_ctx, uint32_t *resolution);
void redraw_screen(void);
void start_clear_indicator_timeout(void);
void stop_clear_indicator_timeout(void);

#endif


text:
<?php

use Tygh\Registry;

include_once(Registry::get('config.dir.addons') . 'news_and_emails/schemas/breadcrumbs/backend.functions.php');

$schema['news.update'] = array (
    array (
        'title' => 'news',
        'link' => 'news.manage'
    )
);
$schema['newsletters.update'] = array (
    array(
        'function' => array('fn_br_newsletters_link', '@newsletter_id', '@type')
    ),
);

return $schema;


text:
/**
@module SoCo
@submodule graphDB
**/

/**
* Graph operations
*
* @class Graph
* @static
*/

function Graph() {};

exports = module.exports = Graph;

var Neo4j = require('./Neo4j')
  , db = new Neo4j();

Graph.getVersion = function(callback) {

    /**
    * Returns Neo4J graph db version
    *
    * @method getVersion
    * @param {Function} callback callback(err, version)
    */

    if (typeof callback !== 'function') return 'Callback required but missing';
    db.REST('GET', '/', function(err, status, body) {
        if (err) return callback(err);
        callback(null, body.neo4j_version);
    });
}


text:
class Player {
  constructor(){
    this.points = 0;
    this.moves = 13;
    this.options = [true, true, true, true, true, true, true, true,
      true, true, true, true, true];
  }
}


text:
import { screen } from '@testing-library/react';
import { Mock } from 'ts-mockery';
import { MemoryRouter } from 'react-router-dom';
import { ServerWithId } from '../../src/servers/data';
import { ManageServersRowDropdown as createManageServersRowDropdown } from '../../src/servers/ManageServersRowDropdown';
import { renderWithEvents } from '../__helpers__/setUpTest';

describe('<ManageServersRowDropdown />', () => {
  const ManageServersRowDropdown = createManageServersRowDropdown(
    ({ isOpen }) => DeleteServerModal {isOpen ? '[OPEN]' : '[CLOSED]'},
  );
  const setAutoConnect = jest.fn();
  const setUp = (autoConnect = false) => {
    const server = Mock.of<ServerWithId>({ id: 'abc123', autoConnect });
    return renderWithEvents(
      <MemoryRouter>
        <ManageServersRowDropdown setAutoConnect={setAutoConnect} server={server} />
      </MemoryRouter>,
    );
  };

  afterEach(jest.clearAllMocks);

  it('renders expected amount of dropdown items', async () => {
    const { user } = setUp();

    expect(screen.queryByRole('menu')).not.toBeInTheDocument();
    await user.click(screen.getByRole('button'));
    expect(screen.getByRole('menu')).toBeInTheDocument();

    expect(screen.getAllByRole('menuitem')).toHaveLength(4);
    expect(screen.getByRole('menuitem', { name: 'Connect' })).toHaveAttribute('href', '/server/abc123');
    expect(screen.getByRole('menuitem', { name: 'Edit server' })).toHaveAttribute('href', '/server/abc123/edit');
  });

  it('allows toggling auto-connect', async () => {
    const { user } = setUp();

    expect(setAutoConnect).not.toHaveBeenCalled();
    await user.click(screen.getByRole('button'));
    await user.click(screen.getByRole('menuitem', { name: 'Auto-connect' }));
    expect(setAutoConnect).toHaveBeenCalledWith(expect.objectContaining({ id: 'abc123' }), true);
  });

  it('renders deletion modal', async () => {
    const { user } = setUp();

    expect(screen.queryByText('DeleteServerModal [OPEN]')).not.toBeInTheDocument();
    expect(screen.getByText('DeleteServerModal [CLOSED]')).toBeInTheDocument();

    await user.click(screen.getByRole('button'));
    await user.click(screen.getByRole('menuitem', { name: 'Remove server' }));

    expect(screen.getByText('DeleteServerModal [OPEN]')).toBeInTheDocument();
    expect(screen.queryByText('DeleteServerModal [CLOSED]')).not.toBeInTheDocument();
  });
});


text:
@protocol CCoreDataManagerDelegate;

@interface CCoreDataManager : NSObject {
	NSString *name;
	NSURL *modelURL;
	NSURL *persistentStoreURL;
	NSString *storeType;
	BOOL forceReplace;
	NSDictionary *storeOptions;
    NSPersistentStoreCoordinator *persistentStoreCoordinator;
    NSManagedObjectModel *managedObjectModel;
	id threadStorageKey;
	id <CCoreDataManagerDelegate> delegate;
}

+ (NSURL *)modelURLForName:(NSString *)inName;

@property (readwrite, retain) NSString *name;
@property (readwrite, retain) NSURL *modelURL;
@property (readwrite, retain) NSURL *persistentStoreURL;
@property (readwrite, retain) NSString *storeType;
@property (readwrite, assign) BOOL forceReplace;
@property (readwrite, retain) NSDictionary *storeOptions;

@property (readwrite, nonatomic, retain) NSPersistentStoreCoordinator *persistentStoreCoordinator;
@property (readwrite, nonatomic, retain) NSManagedObjectModel *managedObjectModel;
@property (readwrite, nonatomic, retain) NSManagedObjectContext *managedObjectContext;

@property (readwrite, assign) id <CCoreDataManagerDelegate> delegate;

- (id)init;

/// You don't need to call this. Subclasses can override to change default behavior.
- (NSManagedObjectContext *)newManagedObjectContext;

- (BOOL)migrate:(NSError **)outError;

- (BOOL)save:(NSError **)outError;
- (void)save;

- (void)presentError:(NSError *)inError;

@end

#pragma mark -

@protocol CCoreDataManagerDelegate <NSObject>

@optional
- (void)coreDataManager:(CCoreDataManager *)inCoreDataManager didCreateNewManagedObjectContext:(NSManagedObjectContext *)inManagedObjectContext;
- (void)coreDataManager:(CCoreDataManager *)inCoreDataManager presentError:(NSError *)inError;

@end


text:
const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
  devtool: 'cheap-module-eval-source-map',
  entry: [
    'webpack-hot-middleware/client',
    './src/index'
  ],
  output: {
    path: path.join(__dirname, 'dist'),
    filename: '[name]-[hash].js',
    publicPath: '/'
  },
  plugins: [
    new webpack.HotModuleReplacementPlugin(),
    new webpack.NoEmitOnErrorsPlugin(),
    new HtmlWebpackPlugin({
      template: 'index.html',
      filename: 'index.html',
      title: 'React Forms tutorial',
      inject: 'body'
    }),
    new webpack.DefinePlugin({
      'process.env.NODE_ENV': JSON.stringify('development')
    }),
  ],
  module: {
    loaders: [
      {
        test: /\.js?/,
        exclude: [/node_modules/],
        loaders: ['babel-loader'],
        include: path.join(__dirname, 'src')
      }
    ]
  }
};


text:
;(function(win, doc, $, undef) {
  'use strict'

  var
  myMap,
  myPieChart,
  myBarChart,
  myTwitterGraph,
  myInstagramGraph,
  myFoodAgencyData,
  myYelpData,
  myTripadvisorData,
  myTwitterPizza,
  myTwitterBurger,
  myTwitterVegan,
  myTwitterCoffee,
  myTwitterTea,
  /**
   * Init
   */
  init = function() {

    // Map
    myMap = new Map('map', {
      center: [ -1.404351 , 50.909698 ],
      zoom:   13
    })

    // slider
    var tripadvisor_slider = document.getElementById('tripadvisor_slider')
    tripadvisor_slider.style.width = '16%'
    $('#tripadvisor_slider').hide()

    var yelp_slider = document.getElementById('yelp_slider')
    yelp_slider.style.width = '16%'
    $('#yelp_slider').hide()

    // dropdown
    var tripadvisor_dropdown = document.getElementById("tripadvisor_dropdown")
    $('#tripadvisor_dropdown').hide()

    var dropdown = document.getElementById("s1")
    dropdown.addEventListener("change", function() {
      var choice = dropdown.options[dropdown.selectedIndex].value
      myMap.updateChoice(choice)
    })

    // Plot food Agency restaurants
    d3.json('http://localhost:5000/api/restaurants', function (collection) {

      myFoodAgencyData = collection

      myMap.plot(collection,
        {
          css: 'foodAgency',
          over: popup.over(tooltip.foodAgency),
          out:  popup.out()
        })

    })

    // Download data from yelp
    d3.json('http://localhost:5000/api/yelp_restaurants', function (collection) {
      myYelpData = collection

      var min = d3.min(collection, function(d) { return d.properties.review_count })
      var max = d3.max(collection, function(d) { return d.properties.review_count })

      noUiSlider.create(yelp_slider, {
        start: [min, max],
        connect: true,
        range: {
          "min" : min,
          "max" : max
        },
        step: 1,
        tooltips: true
      })

      yelp_slider.noUiSlider.on('slide', function(values, handle) {
        myMap.updateLayer(values)
      })

    })

    // Download data from tripAdvisor
    d3.json('http://localhost:5000/api/tripadvisor_restaurants', function (collection) {

      myTripadvisorData = collection
      var min = d3.min(collection, function(d) { return d.properties.review_count })
      var max = d3.max(collection, function(d) { return d.properties.review_count })

      noUiSlider.create(tripadvisor_slider, {
        start: [min, max],
        connect: true,
        range: {
          "min" : min,
          "max" : max
        },
        step: 1,
        tooltips: true
      })

      tripadvisor_slider.noUiSlider.on('slide', function(values, handle) {
        myMap.updateLayer(values)
      })

    })

    // pie chart
    myPieChart = new pieChart('pieChart', {
      width: 700,
      height: 350
    })
    $('#pieChart').hide()

    // bar chart
    myBarChart = new barChart('barChart', {
      width: 700,
      height: 350
    })
    $('#barChart').hide()

    // create graph
    myTwitterGraph = new graph('twitterGraph', {
      width: 550,
      height: 300
    })

    myInstagramGraph = new graph('instagramGraph', {
      width: 550,
      height: 300
    })

    // fill html table
    d3.json('http://localhost:5000/api/twitter_pizza', function (collection) {
      fillCell("twitter_pizza", "pizza", collection.length)
    })
    d3.json('http://localhost:5000/api/twitter_burger', function (collection) {
      fillCell("twitter_burger", "burger", collection.length)
    })
    d3.json('http://localhost:5000/api/twitter_coffee', function (collection) {
      fillCell("twitter_coffee", "coffee", collection.length)
    })
    d3.json('http://localhost:5000/api/twitter_tea', function (collection) {
      fillCell("twitter_tea", "tea", collection.length)
    })
    d3.json('http://localhost:5000/api/twitter_vegan', function (collection) {
      fillCell("twitter_vegan", "vegan", collection.length)
    })

    d3.json('http://localhost:5000/api/instagram_food/total_count', function (collection) {
      for(var i = 0 ; i < collection.length ; i ++) {
        fillCell("instagram_" + collection[i].foodType, collection[i].foodType, collection[i].count)
      }
    })

    d3.json('http://localhost:5000/api/instagram_food/time_count', function (collection) {
      console.log(collection)
      myInstagramGraph.createGraph(collection)
    })

    d3.json('http://localhost:5000/api/twitter_time_count', function (collection) {
      console.log(collection)
      myTwitterGraph.createGraph(collection)
    })

    // handle event
    var
    foodAgency = document.getElementById('foodAgency'),
    yelp = document.getElementById('yelp'),
    tripadvisor = document.getElementById('tripadvisor')

    foodAgency.addEventListener('click', function() {
      myMap.removeLayer()
      myMap.createD3Layer()
      myMap.plot(myFoodAgencyData,
      {
        css: 'foodAgency',
        over: popup.over(tooltip.foodAgency),
        out:  popup.out()
      })

      $('#pieChart').hide(500)
      $('#barChart').hide(500)
      $('#tripadvisor_slider').hide(300)
      $('#yelp_slider').hide(300)
      $('#tripadvisor_dropdown').hide(300)
    })

    yelp.addEventListener('click', function() {
      myMap.removeLayer()
      myMap.createD3Layer()
      myMap.plot(myYelpData,
      {
        css: 'yelp',
        over: popup.over(tooltip.yelp),
        out: popup.out()
      })

      $('#pieChart').show(500)
      $('#barChart').show(500)
      $('#yelp_slider').show(300)
      $('#tripadvisor_slider').hide(300)
      $('#tripadvisor_dropdown').hide(300)
      createBarChart('yelp')
      createPieChart('yelp')
    })

    tripadvisor.addEventListener('click', function() {
      myMap.removeLayer()
      myMap.createD3Layer()
      myMap.plot(myTripadvisorData,
      {
        css: 'tripadvisor',
        over: popup.over(tooltip.tripadvisor),
        out: popup.out()
      })

      $('#pieChart').show(500)
      $('#barChart').show(500)
      $('#yelp_slider').hide(300)
      $('#tripadvisor_slider').show(300)
      $('#tripadvisor_dropdown').show(300)
      createBarChart('tripadvisor')
      createPieChart('tripadvisor')
    })

  },

  /**
   * Create a bar chart
   */
  createBarChart = function(data) {

    d3.json('http://localhost:5000/api/' + data + '_restaurants/rating', function (collection) {

      myBarChart.removeThings()
      myBarChart = new barChart('barChart', {
        width: 700,
        height: 350
      })
      myBarChart.createBar(collection)

    })

  },

  /**
   * Create a pie chart
   */
  createPieChart = function(data) {

    d3.json('http://localhost:5000/api/' + data + '_restaurants/rating', function (collection) {

      myPieChart.removeThings()
      myPieChart = new pieChart('pieChart', {
        width: 700,
        height: 350
      })
      myPieChart.fillPieChart(collection)

    })

  },

  /**
   * fill HTML table
   */
  fillCell = function(id, name, count) {

    var selectedId = document.getElementById(id)

    selectedId.innerHTML = "#" + name + " : " + count

  },

  /**
   * Tooltips
   */
  tooltip = {

    foodAgency: function(d) {

      popup.title.html(function() {
        return d.properties.name
      })

      popup.body.html(function() {
        return '
' +
          '
neighborhood
' +
          '
' + d.properties.city + '
' +
          '
'
      })

    },

    yelp: function(d) {

      popup.title.html(function() {
        return d.properties.name
      })

      popup.body.html(function() {
        return '
' +
          '
Categories
' +
          '
' + d.properties.categories[0][0] + '
' +
          '
rating
' +
          '
' + d.properties.rating + '
' +
          '
Number of reviews
' +
          '
' + d.properties.review_count + '
' +
          '
'
      })

    },

    tripadvisor: function(d) {

      popup.title.html(function() {
        return d.properties.name
      })

      popup.body.html(function() {
        return '
' +
          '
Categories
' +
          '
' + d.properties.categories + '
' +
          '
rating
' +
          '
' + d.properties.rating + '
' +
          '
Number of reviews
' +
          '
' + d.properties.review_count + '
' +
          '
'
      })

    },

  }

  /// Start
  $(init)

})(this, document, jQuery)


text:
/**
 * @author Mat Groves http://matgroves.com/ @Doormat23
 */

PIXI.TextureCache = {};
PIXI.FrameCache = {};

/**
 * A texture stores the information that represents an image or part of an image. It cannot be added to the display list directly. To do this use PIXI.Sprite. If no frame is provided then the whole image is used
 * @class Texture
 * @extends EventTarget
 * @constructor
 * @param baseTexture {BaseTexture}
 * @param frmae {Rectangle}
 */
PIXI.Texture = function(baseTexture, frame)
{
	PIXI.EventTarget.call( this );

	if(!frame)
	{
		this.noFrame = true;
		frame = new PIXI.Rectangle(0,0,1,1);
	}

	this.trim = new PIXI.Point();

	if(baseTexture instanceof PIXI.Texture)
		baseTexture = baseTexture.baseTexture;

	/**
	 * The base texture of this texture
	 * @property baseTexture
	 * @type BaseTexture
	 */
	this.baseTexture = baseTexture;

	/**
	 * The frame specifies the region of the base texture that this texture uses
	 * @property frame
	 * @type #Rectangle
	 */
	this.frame = frame;

	this.scope = this;

	if(baseTexture.hasLoaded)
	{
		if(this.noFrame)frame = new PIXI.Rectangle(0,0, baseTexture.width, baseTexture.height);
		//console.log(frame)

		this.setFrame(frame);
	}
	else
	{
		var scope = this;
		baseTexture.addEventListener( 'loaded', function(){ scope.onBaseTextureLoaded()} );
	}
}

PIXI.Texture.constructor = PIXI.Texture;

PIXI.Texture.prototype.onBaseTextureLoaded = function(event)
{
	var baseTexture = this.baseTexture;
	baseTexture.removeEventListener( 'loaded', this.onLoaded );

	if(this.noFrame)this.frame = new PIXI.Rectangle(0,0, baseTexture.width, baseTexture.height);
	this.noFrame = false;
	this.width = this.frame.width;
	this.height = this.frame.height;

	this.scope.dispatchEvent( { type: 'update', content: this } );
}

PIXI.Texture.prototype.destroy = function(destroyBase)
{
	if(destroyBase)this.baseTexture.destroy();
}

/**
 * Specifies the rectangle region of the baseTexture
 * @method setFrame
 * @param frame {Rectangle}
 */
PIXI.Texture.prototype.setFrame = function(frame)
{
	this.frame = frame;
	this.width = frame.width;
	this.height = frame.height;

	if(frame.x + frame.width > this.baseTexture.width || frame.y + frame.height > this.baseTexture.height)
	{
		throw new Error("Texture Error: frame does not fit inside the base Texture dimensions " + this);
	}

	this.updateFrame = true;

	PIXI.Texture.frameUpdates.push(this);
	//this.dispatchEvent( { type: 'update', content: this } );
}

/**
 *
 * Helper function that returns a texture based on an image url
 * If the image is not in the texture cache it will be  created and loaded
 * @static
 * @method fromImage
 * @param imageUrl {String} The image url of the texture
 * @return Texture
 */
PIXI.Texture.fromImage = function(imageUrl, crossorigin)
{
	var texture = PIXI.TextureCache[imageUrl];

	if(!texture)
	{
		texture = new PIXI.Texture(PIXI.BaseTexture.fromImage(imageUrl, crossorigin));
		PIXI.TextureCache[imageUrl] = texture;
	}

	return texture;
}

/**
 *
 * Helper function that returns a texture based on a frame id
 * If the frame id is not in the texture cache an error will be thrown
 * @method fromFrame
 * @param frameId {String} The frame id of the texture
 * @return Texture
 */
PIXI.Texture.fromFrame = function(frameId)
{
	var texture = PIXI.TextureCache[frameId];
	if(!texture)throw new Error("The frameId '"+ frameId +"' does not exist in the texture cache " + this);
	return texture;
}

/**
 *
 * Helper function that returns a texture based on a canvas element
 * If the canvas is not in the texture cache it will be  created and loaded
 * @static
 * @method fromCanvas
 * @param canvas {Canvas} The canvas element source of the texture
 * @return Texture
 */
PIXI.Texture.fromCanvas = function(canvas)
{
	var	baseTexture = new PIXI.BaseTexture(canvas);
	return new PIXI.Texture(baseTexture);
}

/**
 *
 * Adds a texture to the textureCache.
 * @method addTextureToCache
 * @param texture {Texture}
 * @param id {String} the id that the texture will be stored against.
 */
PIXI.Texture.addTextureToCache = function(texture, id)
{
	PIXI.TextureCache[id] = texture;
}

/**
 *
 * Remove a texture from the textureCache.
 * @method removeTextureFromCache
 * @param id {String} the id of the texture to be removed
 * @return {Texture} the texture that was removed
 */
PIXI.Texture.removeTextureFromCache = function(id)
{
	var texture = PIXI.TextureCache[id]
	PIXI.TextureCache[id] = null;
	return texture;
}

// this is more for webGL.. it contains updated frames..
PIXI.Texture.frameUpdates = [];


text:
<?php

/**
 * @category   Zend
 * @package    Zend_Service
 * @subpackage DeveloperGarden
 * @copyright  Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com)
 * @author     Marco Kaiser
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Service_DeveloperGarden_Response_SmsValidation_ValidatedNumber
{
    /**
     * the number
     * @var string
     */
    public $number = null;

    /**
     * is valid until this date
     * @var string
     */
    public $validUntil = null;

    /**
     * returns the number
     *
     * @return number
     */
    public function getNumber()
    {
        return $this->number;
    }

    /**
     * returns the valid until date
     *
     * @return string
     */
    public function getValidUntil()
    {
        return $this->validUntil;
    }
}


text:
package org.endeavourhealth.reference;

import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVRecord;
import org.endeavourhealth.core.database.dal.DalProvider;
import org.endeavourhealth.core.database.dal.reference.Icd10DalI;
import org.endeavourhealth.reference.helpers.OnsLsoaHelper;
import org.endeavourhealth.reference.helpers.ZipHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.Reader;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.zip.ZipInputStream;

public class Icd10Updater {
    private static final Logger LOG = LoggerFactory.getLogger(OnsLsoaHelper.class);

    /**
     * updates the icd10_lookup table in the reference DB from TRUD data
     *
     * Usage
     * =================================================================================
     * 1. Download the ICD10 data files from https://isd.digital.nhs.uk/trud3/user/authenticated/group/0/pack/28/subpack/258/releases#release-ICD_10.5.0_20151102000001
     * 4. Then run this utility as:
     *      Main icd10 <file zip path>
     *
     * Verson on AWS Live is 2 November 2015
     */
    public static void updateIcd10Lookup(String[] args) throws Exception {

        if (args.length != 2) {
            LOG.error("Incorrect number of parameters");
            LOG.error("Usage: icd10 <icd10 zip file>");
            return;
        }

        LOG.info("ICD10 Update Starting");

        File file = new File(args[1]);

        if (!file.exists()) {
            LOG.error("" + file + " doesn't exist");
            return;
        }
        if (!ZipHelper.isZip(file)) {
            LOG.error("" + file + " isn't a zip file");
            return;
        }

        ZipInputStream zis = null;
        Reader r = null;

        LOG.info("Looking for Codes and Titles File...");
        zis = ZipHelper.createZipInputStream(file);
        r = ZipHelper.findFile(zis, ".*/Content/.*_CodesAndTitlesAndMetadata_.*.txt");
        if (r == null) {
            LOG.error("Failed to find titles and metadata file");
            return;
        }
        Map<String, String> codeMap = readIcd10Records(r);
        LOG.info("Saving to DB...");
        saveIcd10Lookups(codeMap);
        zis.close();

        LOG.info("Looking for Equivalencies File...");
        zis = ZipHelper.createZipInputStream(file);
        r = ZipHelper.findFile(zis, ".*/Content/.*_TableOfCodingEquivalencesWithDescriptionsForward_.*.txt");
        if (r == null) {
            LOG.error("Failed to find titles and metadata file");
            return;
        }
        codeMap = readIcd10EquivalenceRecords(r);
        LOG.info("Saving to DB...");
        saveIcd10Lookups(codeMap);
        zis.close();

        LOG.info("Finished ICD10 Import");
    }

    private static void saveIcd10Lookups(Map<String, String> codeMap) throws Exception {

        int done = 0;

        Icd10DalI dal = DalProvider.factoryIcd10Dal();

        for (String code: codeMap.keySet()) {
            String description = codeMap.get(code);

            dal.updateIcd10Lookup(code, description);

            done ++;
            if (done % 1000 == 0) {
                LOG.info("Done " + done + " ICD10 lookups (out of approx 18k)");
            }
        }

        LOG.info("Done " + done + " ICD10 lookups");
    }

    /**
     * the file is simply five columns delimited with a tab. No column headers.
     */
    private static Map<String, String> readIcd10Records(Reader r) throws Exception {
        Map<String, String> map = new HashMap<>();

        CSVFormat format = CSVFormat.TDF.withHeader();

        CSVParser parser = null;
        try {
            parser = new CSVParser(r, format);
            Iterator<CSVRecord> iterator = parser.iterator();

            while (iterator.hasNext()) {
                CSVRecord record = iterator.next();
                String code = record.get("CODE");
                String name = record.get("DESCRIPTION");
                map.put(code, name);
            }

        } finally {
            if (parser != null) {
                parser.close();
            }
        }

        return map;
    }

    private static Map<String, String> readIcd10EquivalenceRecords(Reader r) throws Exception {
        Map<String, String> map = new HashMap<>();

        CSVFormat format = CSVFormat.TDF.withHeader();

        CSVParser parser = null;
        try {
            parser = new CSVParser(r, format);
            Iterator<CSVRecord> iterator = parser.iterator();

            while (iterator.hasNext()) {
                CSVRecord record = iterator.next();
                String code = record.get("From: ICD-10 4th Edition code");
                String name = record.get("Code Description");
                String isEquivalent = record.get("Target Different to Source?");

                //this file contains all the codes, not just those that have equivalents. The ones that are equivalents
                //have this field as Y
                if (isEquivalent.equalsIgnoreCase("Y")) {
                    map.put(code, name);
                }
            }

        } finally {
            if (parser != null) {
                parser.close();
            }
        }

        return map;
    }

}


text:
<?php

namespace JHWEB\SeguridadVialBundle\Controller;

use JHWEB\SeguridadVialBundle\Entity\SvCfgClaseAccidente;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;use Symfony\Component\HttpFoundation\Request;

/**
 * Svcfgclaseaccidente controller.
 *
 * @Route("svcfgclaseaccidente")
 */
class SvCfgClaseAccidenteController extends Controller
{
    /**
     * Lists all svCfgClaseAccidente entities.
     *
     * @Route("/", name="svcfgclaseaccidente_index")
     * @Method("GET")
     */
    public function indexAction()
    {
        $helpers = $this->get("app.helpers");

        $em = $this->getDoctrine()->getManager();

        $clasesAccidente = $em->getRepository('JHWEBSeguridadVialBundle:SvCfgClaseAccidente')->findBy(
            array('activo' => true)
        );

        $response = array(
            'status' => 'success',
            'code' => 200,
            'message' => count($clasesAccidente) . " registros encontrados",
            'data' => $clasesAccidente,
        );

        return $helpers->json($response);
    }

    /**
     * Creates a new svCfgClaseAccidente entity.
     *
     * @Route("/new", name="svcfgclaseaccidente_new")
     * @Method({"GET", "POST"})
     */
    public function newAction(Request $request)
    {
        $helpers = $this->get("app.helpers");
        $hash = $request->get("authorization", null);
        $authCheck = $helpers->authCheck($hash);

        if ($authCheck == true) {
            $json = $request->get("data", null);
            $params = json_decode($json);

            $em = $this->getDoctrine()->getManager();

            $svCfgClaseAccidente = new SvCfgClaseAccidente();

            $svCfgClaseAccidente->setNombre(mb_strtoupper($params->nombre, 'utf-8'));
            $svCfgClaseAccidente->setActivo(true);

            $em->persist($svCfgClaseAccidente);
            $em->flush();

            $response = array(
                'status' => 'success',
                'code' => 200,
                'message' => "Nuevo registro creado con éxito",
            );

        } else {
            $response = array(
                'status' => 'error',
                'code' => 400,
                'message' => "Autorizacion no valida",
            );
        }
        return $helpers->json($response);
    }

    /**
     * Finds and displays a svCfgClaseAccidente entity.
     *
     * @Route("/show", name="svcfgclaseaccidente_show")
     * @Method("POST")
     */
    public function showAction(Request $request)
    {
        $helpers = $this->get("app.helpers");
        $hash = $request->get("authorization", null);
        $authCheck = $helpers->authCheck($hash);

        if ($authCheck== true) {
            $json = $request->get("data",null);
            $params = json_decode($json);

            $em = $this->getDoctrine()->getManager();

            $svCfgClaseAccidente = $em->getRepository('JHWEBSeguridadVialBundle:SvCfgClaseAccidente')->find(
                $params->id
            );

            $response = array(
                'status' => 'success',
                'code' => 200,
                'message' => 'Registro encontrado con exito.',
                'data' => $svCfgClaseAccidente
            );
        }else{
            $response = array(
                'status' => 'error',
                'code' => 400,
                'message' => 'Autorizacion no valida.',
            );
        }

        return $helpers->json($response);
    }

    /**
     * Displays a form to edit an existing svCfgClaseAccidente entity.
     *
     * @Route("/edit", name="svcfgclaseaccidente_edit")
     * @Method({"GET", "POST"})
     */
    public function editAction(Request $request)
    {
        $helpers = $this->get("app.helpers");
        $hash = $request->get("authorization", null);
        $authCheck = $helpers->authCheck($hash);

        if ($authCheck==true) {
            $json = $request->get("data",null);
            $params = json_decode($json);

            $em = $this->getDoctrine()->getManager();
            $svCfgClaseAccidente = $em->getRepository('JHWEBSeguridadVialBundle:SvCfgClaseAccidente')->find($params->id);

            if ($svCfgClaseAccidente!=null) {
                $svCfgClaseAccidente->setNombre($params->nombre);
                $svCfgClaseAccidente->setActivo(true);
                $em->persist($svCfgClaseAccidente);
                $em->flush();
                $response = array(
                    'status' => 'success',
                    'code' => 200,
                    'message' => "Registro actualizado con exito.",
                );
            }else{
                $response = array(
                    'status' => 'error',
                    'code' => 400,
                    'message' => "El registro no se encuentra en la base de datos",
                );
            }
        }else{
            $response = array(
                    'status' => 'error',
                    'code' => 400,
                    'msj' => "Autorizacion no valida para editar.",
                );
        }

        return $helpers->json($response);
    }

    /**
     * Deletes a svCfgClaseAccidente entity.
     *
     * @Route("/delete", name="svcfgclaseaccidente_delete")
     * @Method("POST")
     */
    public function deleteAction(Request $request)
    {
        $helpers = $this->get("app.helpers");
        $hash = $request->get("authorization", null);
        $authCheck = $helpers->authCheck($hash);
        if ($authCheck==true) {
            $json = $request->get("data",null);
            $params = json_decode($json);
            $em = $this->getDoctrine()->getManager();
            $svCfgClaseAccidente = $em->getRepository('JHWEBSeguridadVialBundle:SvCfgClaseAccidente')->find($params->id);

            $svCfgClaseAccidente->setActivo(0);
            $em->persist($svCfgClaseAccidente);
            $em->flush();
            $response = array(
                'status' => 'success',
                'code' => 200,
                'message' => "Registro eliminado con éxito",
            );
        }else{
            $response = array(
                'status' => 'error',
                'code' => 400,
                'message' => "Autorización no válida",
            );
        }
        return $helpers->json($response);
    }

    /**
     * Creates a form to delete a svCfgClaseAccidente entity.
     *
     * @param SvCfgClaseAccidente $svCfgClaseAccidente The svCfgClaseAccidente entity
     *
     * @return \Symfony\Component\Form\Form The form
     */
    private function createDeleteForm(SvCfgClaseAccidente $svCfgClaseAccidente)
    {
        return $this->createFormBuilder()
            ->setAction($this->generateUrl('svcfgclaseaccidente_delete', array('id' => $svCfgClaseAccidente->getId())))
            ->setMethod('DELETE')
            ->getForm()
        ;
    }

    /**
     * datos para select 2
     *
     * @Route("/select", name="svcfgclaseaccidente_select")
     * @Method({"GET", "POST"})
     */
    public function selectAction()
    {
        $helpers = $this->get("app.helpers");

        $em = $this->getDoctrine()->getManager();

        $svCfgClaseAccidente = $em->getRepository('JHWEBSeguridadVialBundle:SvCfgClaseAccidente')->findBy(
            array('activo' => true)
        );

        $response = null;

        foreach ($svCfgClaseAccidente as $key => $svCfgClaseAccidente) {
            $response[$key] = array(
                'value' => $svCfgClaseAccidente->getId(),
                'label' => $svCfgClaseAccidente->getNombre(),
            );
        }
        return $helpers->json($response);
    }
}


text:
using System.Collections.Immutable;
using System.IO;
using System.Runtime.InteropServices;
using System.Threading;
using System.Runtime.CompilerServices;

namespace System.Reflection.Internal
{
    internal sealed class ByteArrayMemoryProvider : MemoryBlockProvider
    {
        internal readonly ImmutableArray<byte> array;
        private StrongBox<GCHandle> _pinned;

        public ByteArrayMemoryProvider(ImmutableArray<byte> array)
        {
            this.array = array;
        }

        ~ByteArrayMemoryProvider()
        {
            Dispose(disposing: false);
        }

        protected override void Dispose(bool disposing)
        {
            if (_pinned != null)
            {
                _pinned.Value.Free();
                _pinned = null;
            }
        }

        public override int Size
        {
            get
            {
                return array.Length;
            }
        }

        protected override AbstractMemoryBlock GetMemoryBlockImpl(int start, int size)
        {
            return new ByteArrayMemoryBlock(this, start, size);
        }

        public override Stream GetStream(out StreamConstraints constraints)
        {
            constraints = new StreamConstraints(null, 0, Size);
            return new ImmutableMemoryStream(array);
        }

        internal unsafe byte* Pointer
        {
            get
            {
                if (_pinned == null)
                {
                    var newPinned = new StrongBox<GCHandle>(
                        GCHandle.Alloc(ImmutableByteArrayInterop.DangerousGetUnderlyingArray(array), GCHandleType.Pinned));

                    if (Interlocked.CompareExchange(ref _pinned, newPinned, null) != null)
                    {
                        // another thread has already allocated the handle:
                        newPinned.Value.Free();
                    }
                }

                return (byte*)_pinned.Value.AddrOfPinnedObject();
            }
        }
    }
}


text:
if [ -e Trinity.fasta.gz ] && [ ! -e Trinity.fasta ]
then
    gunzip -c Trinity.fasta.gz > Trinity.fasta
fi

../../trinity-plugins/transdecoder/transcripts_to_best_scoring_ORFs.pl -t Trinity.fasta -S

echo
echo
echo See best_candidates.\*  for candidate ORFs
echo


text:
package org.goplayer.game.strategy;

import static org.junit.Assert.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import org.goplayer.go.Goban;
import org.goplayer.go.Stone;
import org.goplayer.go.StoneColor;
import org.goplayer.move.IMove;
import org.goplayer.move.PassMove;
import org.goplayer.move.StoneMove;
import org.goplayer.player.IPlayer;
import org.goplayer.player.StrategicalPlayer;
import org.goplayer.util.Coord;
import org.junit.Test;

public class FirstFreeStrategyTest {

	@Test
	public void testInitialSelectionOnEmptyGoban() {
		FirstFreeStrategy strategy = new FirstFreeStrategy();
		int rowCount = 10;
		int colCount = 5;
		Goban goban = new Goban(rowCount, colCount);

		IPlayer player = new StrategicalPlayer(strategy);
		for (int i = 0; i < 100; i++) {
			IMove move = strategy.chooseMove(goban, player);
			assertTrue(move instanceof StoneMove);
			StoneMove m = (StoneMove) move;
			assertEquals(0, m.getRow());
			assertEquals(0, m.getCol());
		}
	}

	@Test
	public void testInitialSelectionOnHalfFilledGoban() {
		Random rand = new Random();
		int rowCount = 10;
		int colCount = 5;
		for (int i = 0; i < 100; i++) {
			int rowTarget = rand.nextInt(rowCount);
			int colTarget = rand.nextInt(colCount);
			Goban goban = new Goban(rowCount, colCount);
			{
				boolean stopFilling = false;
				for (int row = 0; row < rowCount && !stopFilling; row++) {
					for (int col = 0; col < colCount && !stopFilling; col++) {
						stopFilling = rowTarget == row && colTarget == col;
						if (stopFilling) {
							continue;
						} else {
							goban.setCoordContent(row, col, new Stone(
									StoneColor.BLACK));
						}
					}
				}
			}

			FirstFreeStrategy strategy = new FirstFreeStrategy();
			IPlayer player = new StrategicalPlayer(strategy);
			for (int j = 0; j < 10; j++) {
				IMove move = strategy.chooseMove(goban, player);
				assertTrue(move instanceof StoneMove);
				StoneMove m = (StoneMove) move;
				assertEquals(rowTarget, m.getRow());
				assertEquals(colTarget, m.getCol());
			}
		}
	}

	@Test
	public void testPassOnFilledGoban() {
		int rowCount = 10;
		int colCount = 5;
		Goban goban = new Goban(rowCount, colCount);
		for (int row = 0; row < goban.getRowCount(); row++) {
			for (int col = 0; col < goban.getColCount(); col++) {
				goban.setCoordContent(row, col, new Stone(StoneColor.BLACK));
			}
		}

		FirstFreeStrategy strategy = new FirstFreeStrategy();
		IPlayer player = new StrategicalPlayer(strategy);
		for (int j = 0; j < 10; j++) {
			IMove move = strategy.chooseMove(goban, player);
			assertTrue(move instanceof PassMove);
		}
	}

	@Test
	public void testFirstFreeSelected() {
		FirstFreeStrategy strategy = new FirstFreeStrategy();
		int rowCount = 10;
		int colCount = 5;
		int totalInstances = rowCount * colCount;
		Goban goban = new Goban(rowCount, colCount);

		// compute free places
		List<Coord> freePlaces = new ArrayList<Coord>();
		for (int row = 0; row < rowCount; row++) {
			for (int col = 0; col < colCount; col++) {
				freePlaces.add(new Coord(row, col));
			}
		}

		// fill half with random stones
		Random rand = new Random();
		for (int i = 0; i < totalInstances / 2; i++) {
			Coord coord = freePlaces.remove(rand.nextInt(freePlaces.size()));
			goban.setCoordContent(coord.getRow(), coord.getCol(), new Stone(
					StoneColor.BLACK));
		}

		IPlayer player = new StrategicalPlayer(strategy);
		IMove move = null;
		move = strategy.chooseMove(goban, player);
		while (move instanceof StoneMove) {
			StoneMove actual = (StoneMove) move;
			Coord expected = freePlaces.remove(0);
			assertEquals(expected.getRow(), actual.getRow());
			assertEquals(expected.getCol(), actual.getCol());
			goban.setCoordContent(actual.getRow(), actual.getCol(), new Stone(
					StoneColor.WHITE));
			move = strategy.chooseMove(goban, player);
		}
		assertEquals(0, freePlaces.size());
	}

}


text:
.. meta::
    :author: Cask Data, Inc.
    :copyright: Copyright © 2015 Cask Data, Inc.

.. _cdap-apps-etl-plugins-transformations-validator:

==========================
Transformations: Validator
==========================

.. rubric:: Description

Validates a record, writing to an error dataset if the record is invalid.
Otherwise it passes the record on to the next stage.

The transform validates records using a custom Javascript function based on a set of
:ref:`available validator functions <cdap-apps-etl-plugins-shared-core-validator>` in the
:ref:`CoreValidator <cdap-apps-etl-plugins-shared-core-validator>`.

.. rubric:: Use Case

The transform is used when you need to validate records. For example, you may want to
validate records as being valid IP addresses or valid dates and log errors if they aren't
valid.

.. rubric:: Properties

**validators** Comma-separated list of validators that are used by the validationScript.
Example: ``"validators": "core"``

**validationScript:** Javascript that must implement a function ``isValid`` that takes a JSON object
(representing the input record) and a context object (encapsulating CDAP metrics, logger, and validators)
and returns a result JSON with validity, error code, and error message.
Example response::

  {
    "isValid" : true [or] false,
    "errorCode" : number [should be an valid integer],
    "errorMsg" : "Message indicating the error and why the record failed validation"
  }

**lookup:** The configuration of the lookup tables to be used in your script.
For example, if lookup table "purchases" is configured, then you will be able to perform
operations with that lookup table in your script: ``context.getLookup('purchases').lookup('key')``
Currently supports ``KeyValueTable``.

.. rubric:: Examples

::

      {
        "name": "Validator",
        "properties": {
          "validators": "core",
          "validationScript": "function isValid(input, context) {
                                  var coreValidator = context.getValidator(\"coreValidator\");
                                  if (!coreValidator.maxLength(input.body, 10))
                                    {
                                      return {'isValid': false, 'errorCode': 10,
                                              'errorMsg': \"body length greater than 10\"};
                                    }
                                  return {'isValid' : true};
                                };"
        }
      }

This example sends an error code ``'10'`` for any records whose ``'body'`` field contains
a value whose length is greater than 10. It has been "pretty-printed" for readability. It
uses the :ref:`CoreValidator <cdap-apps-etl-plugins-shared-core-validator>` (included
using ``"validators": "core"``) and references a function using its Javascript name
(``coreValidator.maxLength``).

::

      {
        "name": "Validator",
        "properties": {
          "lookup": "{
            \"blacklist\":{
              \"type\":\"DATASET\"
            }
          }"
          "validationScript": "function isValid(input, context) {
                                  if (context.getLookup('blacklist').lookup(input.body) !== null)
                                    {
                                      return {'isValid': false, 'errorCode': 10,
                                              'errorMsg': \"input blacklisted\"};
                                    }
                                  return {'isValid' : true};
                                };"
        }
      }

This example uses the key-value dataset ``'blacklist'`` as a lookup table,
and sends an error code ``'10'`` for any records whose ``'body'`` field exists in the ``'blacklist'`` dataset.
It has been "pretty-printed" for readability.

::

      {
        "name": "Validator",
        "properties": {
          "validators": "core",
          "validationScript": "function isValid(input, context) {
                                  var isValid = true;
                                  var errMsg = \"\";
                                  var errCode = 0;
                                  var coreValidator = context.getValidator(\"coreValidator\");
                                  var metrics = context.getMetrics();
                                  var logger = context.getLogger();
                                  if (!coreValidator.isDate(input.date)) {
                                     isValid = false; errMsg = input.date + \"is invalid date\"; errCode = 5;
                                     metrics.count(\"invalid.date\", 1);
                                  } else if (!coreValidator.isUrl(input.url)) {
                                     isValid = false; errMsg = \"invalid url\"; errCode = 7;
                                     metrics.count(\"invalid.url\", 1);
                                  } else if (!coreValidator.isInRange(input.content_length, 0, 1024 * 1024)) {
                                     isValid = false; errMsg = \"content length >1MB\"; errCode = 10;
                                     metrics.count(\"invalid.body.size\", 1);
                                  }
                                  if (!isValid) {
                                    logger.warn(\"Validation failed for record {}\", input);
                                  }
                                  return {'isValid': isValid, 'errorCode': errCode, 'errorMsg': errMsg};
                                };"
        }
      }

This example sends an error code ``'5'`` for any records whose ``'date'`` field is an
invalid date, sends an error code ``'7'`` for any records whose ``'url'`` field is an
invalid URL, and sends an error code ``'10'`` for any records whose ``'content_length'``
field is greater than 1MB.

It has been "pretty-printed" for readability. It uses the
:ref:`CoreValidator <cdap-apps-etl-plugins-shared-core-validator>` (included using
``"validators": "core"``) and references functions using their Javascript names (such as
``coreValidator.isDate``).

**Note:** These default metrics are emitted by this transform:

.. csv-table::
   :header: "Metric Name","Description"
   :widths: 40,60

   "``records.in``","Input records processed by this transform stage"
   "``records.out``","Output records sent to the next stage"
   "``invalid``","Input records invalidated at this stage"


text:
package org.entirej.applicationframework.tmt.renderers.item;

import java.io.Serializable;

import org.eclipse.jface.fieldassist.ControlDecoration;
import org.eclipse.jface.fieldassist.FieldDecorationRegistry;
import org.eclipse.jface.viewers.ColumnLabelProvider;
import org.eclipse.rap.rwt.RWT;
import org.eclipse.rap.rwt.template.Cell;
import org.eclipse.rap.rwt.template.Template;
import org.eclipse.rap.rwt.template.TextCell;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.FocusEvent;
import org.eclipse.swt.events.FocusListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Label;
import org.entirej.applicationframework.tmt.application.EJTMTImageRetriever;
import org.entirej.applicationframework.tmt.renderer.interfaces.EJTMTAppItemRenderer;
import org.entirej.applicationframework.tmt.renderers.item.definition.interfaces.EJTMTLabelItemRendererDefinitionProperties;
import org.entirej.applicationframework.tmt.table.EJTMTAbstractTableSorter;
import org.entirej.applicationframework.tmt.utils.EJTMTItemRendererVisualContext;
import org.entirej.applicationframework.tmt.utils.EJTMTVisualAttributeUtils;
import org.entirej.framework.core.data.EJDataRecord;
import org.entirej.framework.core.interfaces.EJScreenItemController;
import org.entirej.framework.core.properties.EJCoreVisualAttributeProperties;
import org.entirej.framework.core.properties.definitions.interfaces.EJFrameworkExtensionProperties;
import org.entirej.framework.core.properties.interfaces.EJItemProperties;
import org.entirej.framework.core.properties.interfaces.EJScreenItemProperties;

public class EJTMTLabelItemRenderer implements EJTMTAppItemRenderer, FocusListener, Serializable
{
    protected EJFrameworkExtensionProperties  _rendererProps;
    protected EJScreenItemController          _item;
    protected EJScreenItemProperties          _screenItemProperties;
    protected EJItemProperties                _itemProperties;
    protected String                          _registeredItemName;
    protected SWTComponentAdapter             _labelField;

    protected EJCoreVisualAttributeProperties _visualAttributeProperties;
    protected EJCoreVisualAttributeProperties _initialVAProperties;
    protected ControlDecoration               _errorDecoration;
    protected ControlDecoration               _mandatoryDecoration;
    protected VALUE_CASE                      _valueCase          = VALUE_CASE.DEFAULT;
    private EJTMTItemRendererVisualContext    _visualContext;
    private boolean                           _displayAsHyperlink = false;

    protected Object                          _baseValue;

    protected boolean controlState(Control control)
    {
        return control != null && !control.isDisposed();
    }

    @Override
    public boolean useFontDimensions()
    {
        return true;
    }

    @Override
    public void refreshItemRendererProperty(String propertyName)
    {
    }

    @Override
    public void refreshItemRenderer()
    {

    }

    @Override
    public void initialise(EJScreenItemController item, EJScreenItemProperties screenItemProperties)
    {
        _item = item;
        _itemProperties = _item.getReferencedItemProperties();
        _screenItemProperties = screenItemProperties;
        _rendererProps = _itemProperties.getItemRendererProperties();

        final String caseProperty = _rendererProps.getStringProperty(EJTMTLabelItemRendererDefinitionProperties.PROPERTY_CASE);
        if (caseProperty != null && caseProperty.trim().length() > 0)
        {
            if (caseProperty.equals(EJTMTLabelItemRendererDefinitionProperties.PROPERTY_CASE_LOWER))
            {
                _valueCase = VALUE_CASE.LOWER;
            }
            else if (caseProperty.equals(EJTMTLabelItemRendererDefinitionProperties.PROPERTY_CASE_UPPER))
            {
                _valueCase = VALUE_CASE.UPPER;
            }
        }
    }

    @Override
    public void setLabel(String label)
    {
        if (_labelField != null && controlState(_labelField.getControl()))
        {
            _labelField.setText(label == null ? "" : label);
        }
    }

    @Override
    public void setHint(String hint)
    {
        if (_labelField != null && controlState(_labelField.getControl()))
        {
            _labelField.getControl().setToolTipText(hint == null ? "" : hint);
        }
    }

    @Override
    public void enableLovActivation(boolean activate)
    {

    }

    @Override
    public EJScreenItemController getItem()
    {
        return _item;
    }

    public EJItemProperties getItemProperties()
    {
        return _itemProperties;
    }

    @Override
    public Control getGuiComponent()
    {

        return _labelField.getControl();
    }

    @Override
    public Label getGuiComponentLabel()
    {
        return null;
    }

    @Override
    public void clearValue()
    {
        _baseValue = null;
        if (_labelField != null && controlState(_labelField.getControl()))
        {

            _labelField.setText(_item.getForm().translateText(_screenItemProperties.getLabel()));
        }
    }

    @Override
    public String getRegisteredItemName()
    {
        return _registeredItemName;
    }

    @Override
    public Object getValue()
    {
        return _baseValue;
    }

    @Override
    public boolean isEditAllowed()
    {
        if (_labelField != null && controlState(_labelField.getControl()))
        {
            return _labelField.getControl().isEnabled();
        }
        return false;
    }

    @Override
    public boolean isVisible()
    {
        if (_labelField != null && controlState(_labelField.getControl()))
        {
            return _labelField.getControl().isVisible();
        }

        return false;
    }

    @Override
    public boolean isValid()
    {
        return true;
    }

    @Override
    public void gainFocus()
    {
        if (_labelField != null && controlState(_labelField.getControl()))
        {
            _labelField.getControl().forceFocus();
        }
    }

    @Override
    public void setEditAllowed(boolean editAllowed)
    {
        if (_labelField != null && controlState(_labelField.getControl()))
        {
            _labelField.getControl().setEnabled(editAllowed);
        }
    }

    @Override
    public void setInitialValue(Object value)
    {
        setValue(value);
    }

    @Override
    public void setRegisteredItemName(String name)
    {
        _registeredItemName = name;
    }

    private String toCaseValue(String string)
    {
        switch (_valueCase)
        {
            case LOWER:
                string = string.toLowerCase();
                break;
            case UPPER:
                string = string.toUpperCase();
                break;
        }

        return string;
    }

    @Override
    public void setValue(Object value)
    {
        _baseValue = value;
        if (_labelField != null && controlState(_labelField.getControl()))
        {
            if (value == null)
            {
                value = _item.getForm().translateText(_screenItemProperties.getLabel());
            }

            _labelField.setText(value == null ? "" : toCaseValue(value.toString()));
        }
    }

    @Override
    public void setVisible(boolean visible)
    {
        if (_labelField != null)
        {
            _labelField.getControl().setVisible(visible);
        }
    }

    @Override
    public void setMandatory(boolean mandatory)
    {

    }

    @Override
    public boolean isMandatory()
    {
        return false;
    }

    @Override
    public boolean valueEqualsTo(Object value)
    {
        return value.equals(this.getValue());
    }

    @Override
    public void validationErrorOccurred(boolean error)
    {
        if (_errorDecoration == null)
        {
            return;
        }
        _errorDecoration.setDescriptionText("");
        if (error)
        {
            _errorDecoration.show();
        }
        else
        {
            _errorDecoration.hide();
        }
    }

    @Override
    public void focusGained(FocusEvent event)
    {
        _item.itemFocusGained();
    }

    @Override
    public void focusLost(FocusEvent event)
    {
        _item.itemFocusLost();
    }

    @Override
    public void setVisualAttribute(EJCoreVisualAttributeProperties visualAttributeProperties)
    {
        _visualAttributeProperties = visualAttributeProperties != null ? visualAttributeProperties : _initialVAProperties;
        if (_labelField == null || _labelField.getControl() == null || _labelField.getControl().isDisposed())
        {
            return;
        }
        refreshBackground();
        refreshForeground();
        refreshFont();
    }

    @Override
    public EJCoreVisualAttributeProperties getVisualAttributeProperties()
    {
        return _visualAttributeProperties;
    }

    private void refreshBackground()
    {
        Color background = EJTMTVisualAttributeUtils.INSTANCE.getBackground(_visualAttributeProperties);
        Color color = background != null ? background : (_visualContext!=null ? _visualContext.getBackgroundColor() :null);
        if(color==null || !color.equals( _labelField.getControl().getBackground()))
        {
            _labelField.getControl().setBackground(color);
        }
    }

    private void refreshForeground()
    {
        Color foreground = EJTMTVisualAttributeUtils.INSTANCE.getForeground(_visualAttributeProperties);

        _labelField.getControl().setForeground(foreground != null ? foreground : _visualContext.getForegroundColor());
    }

    private void refreshFont()
    {
        _labelField.getControl().setFont(EJTMTVisualAttributeUtils.INSTANCE.getFont(_visualAttributeProperties, _visualContext.getItemFont()));
    }

    @Override
    public String toString()
    {
        StringBuffer buffer = new StringBuffer();
        buffer.append("LabelItem:\n");
        buffer.append("  RegisteredItemName: ");
        buffer.append(_registeredItemName);
        buffer.append("\n");
        buffer.append("  Label: ");
        buffer.append(_labelField);
        buffer.append("  GUI Component: ");
        buffer.append(_labelField);

        return buffer.toString();
    }

    @Override
    public void createComponent(Composite composite)
    {
        String alignmentProperty = _rendererProps.getStringProperty(EJTMTLabelItemRendererDefinitionProperties.PROPERTY_ALIGNMENT);
        if (alignmentProperty == null)
        {
            alignmentProperty = _rendererProps.getStringProperty("ALLIGNMENT");
        }
        boolean textWrapProperty = _rendererProps.getBooleanProperty(EJTMTLabelItemRendererDefinitionProperties.PROPERTY_TEXT_WRAP, false);
        String hint = _screenItemProperties.getHint();

        int style = SWT.NONE;
        style = getComponentStyle(alignmentProperty, style);

        if (textWrapProperty)
        {
            style = style + SWT.WRAP;
        }

        _displayAsHyperlink = _rendererProps.getBooleanProperty(EJTMTLabelItemRendererDefinitionProperties.PROPERTY_DISPLAY_AS_HYPERLINK, false);
        final String label = _screenItemProperties.getLabel();
        if (!_displayAsHyperlink)
        {
            final Label labelField = new Label(composite, style);
            labelField.setData(RWT.MARKUP_ENABLED,_rendererProps.getBooleanProperty("HTML_FORMAT", false));

            String pictureName = _rendererProps.getStringProperty(EJTMTLabelItemRendererDefinitionProperties.PROPERTY_PICTURE);

            if (pictureName != null && pictureName.length() > 0)
            {
                if (pictureName != null && pictureName.trim().length() > 0)
                {
                    labelField.setImage(EJTMTImageRetriever.get(pictureName));
                }
            }

            _labelField = new SWTComponentAdapter()
            {
                @Override
                public void setText(String text)
                {
                    if (controlState(labelField))
                    {
                        labelField.setText(text);
                    }
                }

                @Override
                public String getText()
                {
                    return labelField.getText();
                }

                @Override
                public Control getControl()
                {
                    return labelField;
                }
            };
        }
        else
        {
            // change to button
            final Button linkField = new Button(composite, style);

            _labelField = new SWTComponentAdapter()
            {
                String value;

                @Override
                public void setText(String text)
                {
                    if (controlState(linkField))
                    {
                        linkField.setText(value = text);
                    }
                }

                @Override
                public String getText()
                {
                    return value;
                }

                @Override
                public Control getControl()
                {
                    return linkField;
                }

            };

            linkField.addSelectionListener(new SelectionAdapter()
            {
                @Override
                public void widgetSelected(SelectionEvent e)
                {
                    _item.executeActionCommand();
                }
            });
        }

        _labelField.setText(label != null ? label : "");
        _labelField.getControl().setToolTipText(hint != null ? hint : "");
        _labelField.getControl().setData(_item.getReferencedItemProperties().getName());
        _labelField.getControl().addFocusListener(this);
        _visualContext = new EJTMTItemRendererVisualContext(_labelField.getControl().getBackground(), _labelField.getControl().getForeground(), _labelField
                .getControl().getFont());

        _mandatoryDecoration = new ControlDecoration(_labelField.getControl(), SWT.TOP | SWT.LEFT);
        _errorDecoration = new ControlDecoration(_labelField.getControl(), SWT.TOP | SWT.LEFT);
        _errorDecoration.setImage(EJTMTImageRetriever.get(EJTMTImageRetriever.IMG_ERROR_OVR));
        _mandatoryDecoration.setImage(EJTMTImageRetriever.get(EJTMTImageRetriever.IMG_REQUIRED_OVR));
        _mandatoryDecoration.setShowHover(true);
        _mandatoryDecoration.setDescriptionText(_screenItemProperties.getLabel() == null || _screenItemProperties.getLabel().isEmpty() ? "Required Item"
                : String.format("%s is required", _screenItemProperties.getLabel()));
        _errorDecoration.hide();
        _mandatoryDecoration.hide();
    }

    protected int getComponentStyle(String alignmentProperty, int style)
    {
        if (alignmentProperty != null && alignmentProperty.trim().length() > 0)
        {
            if (alignmentProperty.equals(EJTMTLabelItemRendererDefinitionProperties.PROPERTY_ALIGNMENT_LEFT))
            {
                style = style | SWT.LEFT;
            }
            else if (alignmentProperty.equals(EJTMTLabelItemRendererDefinitionProperties.PROPERTY_ALIGNMENT_RIGHT))
            {
                style = style | SWT.RIGHT;
            }
            else if (alignmentProperty.equals(EJTMTLabelItemRendererDefinitionProperties.PROPERTY_ALIGNMENT_CENTER))
            {
                style = style | SWT.CENTER;
            }
        }
        return style;
    }

    @Override
    public void createLable(Composite composite)
    {

    }

    @Override
    public ColumnLabelProvider createColumnLabelProvider(final EJScreenItemProperties item, EJScreenItemController controller)
    {
        ColumnLabelProvider provider = new ColumnLabelProvider()
        {
            @Override
            public Color getBackground(Object element)
            {

                EJCoreVisualAttributeProperties properties = getAttributes(item, element);
                if (properties != null)
                {
                    Color background = EJTMTVisualAttributeUtils.INSTANCE.getBackground(properties);
                    if (background != null)
                    {
                        return background;
                    }
                }
                return super.getBackground(element);
            }

            @Override
            public Color getForeground(Object element)
            {
                EJCoreVisualAttributeProperties properties = getAttributes(item, element);
                if (properties != null)
                {
                    Color foreground = EJTMTVisualAttributeUtils.INSTANCE.getForeground(properties);
                    if (foreground != null)
                    {
                        return foreground;
                    }
                }
                return super.getForeground(element);
            }

            private EJCoreVisualAttributeProperties getAttributes(final EJScreenItemProperties item, Object element)
            {
                EJCoreVisualAttributeProperties properties = null;
                if (element instanceof EJDataRecord)
                {
                    EJDataRecord record = (EJDataRecord) element;
                    properties = record.getItem(item.getReferencedItemName()).getVisualAttribute();
                }
                if (properties == null)
                {
                    properties = _visualAttributeProperties;
                }
                return properties;
            }

            @Override
            public Font getFont(Object element)
            {
                EJCoreVisualAttributeProperties properties = getAttributes(item, element);
                if (properties != null)
                {
                    return EJTMTVisualAttributeUtils.INSTANCE.getFont(properties, super.getFont(element));

                }
                return super.getFont(element);
            }

            @Override
            public String getText(Object element)
            {
                if (element instanceof EJDataRecord)
                {
                    EJDataRecord record = (EJDataRecord) element;
                    Object value = record.getValue(item.getReferencedItemName());

                    if (value != null)
                    {
                        return value.toString();
                    }
                }
                String label = item.getLabel();
                return label != null ? label : "";
            }

        };
        return provider;
    }

    @Override
    public EJTMTAbstractTableSorter getColumnSorter(EJScreenItemProperties item, EJScreenItemController controller)
    {
        return null;
    }

    private static interface SWTComponentAdapter
    {
        Control getControl();

        String getText();

        void setText(String string);
    }

    @Override
    public void setInitialVisualAttribute(EJCoreVisualAttributeProperties va)
    {
        this._initialVAProperties = va;
        setVisualAttribute(va);
    }

    @Override
    public boolean isReadOnly()
    {
        return true;
    }

    @Override
    public Cell<? extends Cell<?>> createColumnCell(EJScreenItemProperties item, EJScreenItemController controller, Template template)
    {
        TextCell textCell = new TextCell(template);
        textCell.setWrap(_rendererProps.getBooleanProperty(EJTMTLabelItemRendererDefinitionProperties.PROPERTY_TEXT_WRAP, false));
        return textCell;
    }
}


text:
package mint

import (
	"bytes"
	"crypto"
	"crypto/aes"
	"crypto/cipher"
	"crypto/hmac"
	"crypto/rand"
	"crypto/x509"
	"database/sql"
	"encoding/binary"
	"fmt"
	_ "github.com/mattn/go-sqlite3"
	"io"
	"log"
	"time"
)

type pinningStore struct {
	db sql.DB
}

var ps pinningStore

const (
	pinningTicketSecretLen = 16 // bytes
	logTypeTicketPinning   = "pinning"
)

func InitPinningStore(config *Config) {
	ps = pinningStore{}
	ps.initDB(config)
}

func (ps *pinningStore) initDB(config *Config) {
	db, err := sql.Open("sqlite3", config.PinningDB)
	if err != nil {
		log.Fatal(err)
	}
	ps.db = *db

	// Client-side
	sqlStmt := `
	create table if not exists tickets (origin string not null primary key,
		opaque blob not null,
		pinning_secret blob not null,
		valid_until datetime);
	`
	_, err = ps.db.Exec(sqlStmt)
	if err != nil {
		log.Fatalf("%q: %s\n", err, sqlStmt)
	}

	// Server-side
	sqlStmt = `
	create table if not exists protection_keys (keyid integer primary key autoincrement,
		key blob not null,
		valid_from datetime,
		valid_until datetime);
	`
	_, err = ps.db.Exec(sqlStmt)
	if err != nil {
		log.Fatalf("%q: %s\n", err, sqlStmt)
	}
}

func (ps *pinningStore) closeDB() {
	err := ps.db.Close()
	if err != nil {
		log.Fatal(err)
	}
}

func (ps *pinningStore) deleteDB() {
	_, err := ps.db.Exec("delete from tickets")
	if err != nil {
		log.Fatal(err)
	}
	_, err = ps.db.Exec("delete from protection_keys")
	if err != nil {
		log.Fatal(err)
	}
}

// Store ticket in client-side database. Lifetime given in seconds.
func (ps *pinningStore) storeTicket(origin string, ticket []byte, pinningSecret []byte, lifetime int) {
	validUntil := time.Now().Add(time.Duration(lifetime) * time.Second).Unix()
	_, err := ps.db.Exec("insert or replace into tickets values (?, ?, ?, ?)", origin, ticket, pinningSecret, validUntil)
	if err != nil {
		log.Fatal(err)
	}
}

// Client check: is ticket expired? Client only sends the ticket up to 10s before the nominal expiry
func (ps *pinningStore) expired(validUntil time.Time) bool {
	const validityMargin = 10 * time.Second
	return validUntil.Before(time.Now().Add(-validityMargin))
}

// Read the ticket from the store, indexed by origin. Ticket must be unexpired
func (ps *pinningStore) readTicket(origin string) (opaque []byte, pinningSecret []byte, validUntil time.Time, found bool) {
	rows, err := ps.db.Query("select opaque, pinning_secret, valid_until from tickets where origin = ?", origin)
	if err != nil {
		log.Fatal(err)
	}
	defer rows.Close()
	if !rows.Next() {
		found = false
		return
	}
	rows.Scan(&opaque, &pinningSecret, &validUntil)
	// validUntil = time.Unix(int64(validUntilUnix), 0)
	found = !ps.expired(validUntil)
	return
}

func (ps *pinningStore) deleteTicket(origin string) (found bool) {
	result, err := ps.db.Exec("delete from tickets where origin=?", origin)
	if err != nil {
		log.Fatal(err)
	}
	rows, err := result.RowsAffected()
	if err != nil {
		log.Fatal(err)
	}
	return (rows >= 1)
}

func (ps *pinningStore) deleteAllTickets() {
	_, err := ps.db.Exec("delete from tickets")
	if err != nil {
		log.Fatal(err)
	}
}

func DeleteTicket(origin string) (found bool) {
	return ps.deleteTicket(origin)
}

func (ps *pinningStore) storeProtectionKey(key []byte, validFrom time.Time, validUntil time.Time) uint64 {
	result, err := ps.db.Exec("insert into protection_keys(key, valid_from, valid_until) values (?, ?, ?)", key, validFrom, validUntil)
	if err != nil {
		log.Fatal(err)
	}
	keyID, err := result.LastInsertId()
	if err != nil {
		log.Fatal(err)
	}
	return uint64(keyID)
}

func (ps *pinningStore) readProtectionKey(keyID uint64) (key []byte, found bool) {
	rows, err := ps.db.Query("select key from protection_keys where keyid = ?", keyID)
	if err != nil {
		log.Fatal(err)
	}
	defer rows.Close()
	if !rows.Next() {
		found = false
		return
	}
	rows.Scan(&key)
	found = true
	return
}

// Read the current protection key. If there are several that are current, reads an arbitrary one.
func (ps *pinningStore) readCurrentProtectionKey() (key []byte, keyID uint64, found bool) {
	now := time.Now()
	// sqlite: this is string comparison, and it works!
	rows, err := ps.db.Query("select key, keyid from protection_keys where ? between valid_from and valid_until", now)
	if err != nil {
		log.Fatal(err)
	}
	defer rows.Close()
	if !rows.Next() {
		found = false
		return
	}
	rows.Scan(&key, &keyID)
	found = true
	return
}

func CreateServerPinningKey() {
	ps.createValidProtectionKey()
}

func RotateServerPinningKey() {
	ps.createValidProtectionKey()
}

// Create a protection key that's immediately valid
func (ps *pinningStore) createValidProtectionKey() {
	key := make([]byte, 16) // AES-256
	if _, err := io.ReadFull(rand.Reader, key); err != nil {
		panic(err.Error())
	}
	validFrom := time.Now().Add(-1 * time.Minute)
	validUntil := time.Now().Add(1 * time.Hour)
	_ = ps.storeProtectionKey(key, validFrom, validUntil)
}

// Delete all tickets from client's store
func ClientCleanup() {
	ps.deleteAllTickets()
}

// TODO Add server-create-first-key, server-rotate, client-cleanup, server-ramp-down ops

type pinningTicket struct {
	protectionKeyID uint64 // integrity protected (AAD)
	ticketSecret    []byte // encrypted
}

func (pt *pinningTicket) protect(protectionKey []byte) []byte {
	block, err := aes.NewCipher(protectionKey)
	if err != nil {
		panic(err.Error())
	}
	aesgcm, err := cipher.NewGCM(block)
	if err != nil {
		panic(err.Error())
	}
	nonce := make([]byte, aesgcm.NonceSize())
	if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
		panic(err.Error())
	}
	pkIDbytes := make([]byte, 8)
	binary.BigEndian.PutUint64(pkIDbytes, pt.protectionKeyID)
	encryptedTicket := aesgcm.Seal(nil, nonce, pt.ticketSecret, pkIDbytes)
	return bytes.Join([][]byte{pkIDbytes, nonce, encryptedTicket}, []byte{})
}

func readProtectionKeyID(sealedTicket []byte) (pkID uint64, err error) {
	if len(sealedTicket) < 4 {
		return 0, fmt.Errorf("Sealed ticket too short")
	}
	return binary.BigEndian.Uint64(sealedTicket[0:8]), nil
}

func validate(sealedTicket []byte, protectionKey []byte) (pt pinningTicket, err error) {
	if len(sealedTicket) < 8 {
		err = fmt.Errorf("Ticket pinning: sealed ticket too short")
		return
	}
	pt.protectionKeyID = binary.BigEndian.Uint64(sealedTicket[0:8])
	block, err := aes.NewCipher(protectionKey)
	if err != nil {
		panic(err.Error())
	}
	aesgcm, err := cipher.NewGCM(block)
	if err != nil {
		panic(err.Error())
	}
	nonce := sealedTicket[8 : 8+aesgcm.NonceSize()]
	cipherText := sealedTicket[8+aesgcm.NonceSize():]
	pkIDbytes := make([]byte, 8)
	binary.BigEndian.PutUint64(pkIDbytes, pt.protectionKeyID)
	pt.ticketSecret, err = aesgcm.Open(nil, nonce, cipherText, pkIDbytes)
	if err != nil {
		err = fmt.Errorf("Ticket pinning: failed to decrypt ticket")
		return
	}
	return
}

func newTicketSecret(hash crypto.Hash, xSS []byte, xES []byte) []byte {
	length := pinningTicketSecretLen
	dhSecrets := bytes.Join([][]byte{xSS, xES}, nil)
	ext := hkdfExtract(hash, nil, dhSecrets)
	return hkdfExpandLabel(hash, ext, "pinning secret", nil, length)
}

func newPinningProof(hash crypto.Hash, pinningSecret []byte, cRandom []byte, sRandom []byte, pubKey crypto.PublicKey) (proof []byte, err error) {
	der, err := x509.MarshalPKIXPublicKey(pubKey)
	if err != nil {
		return
	}
	h := hash.New()
	h.Write(der)
	pkeyHash := h.Sum(nil)
	rawProof := bytes.Join([][]byte{[]byte("pinning proof"), []byte{byte(len(cRandom))}, cRandom, []byte{byte(len(sRandom))}, sRandom, pkeyHash}, nil)
	hm := hmac.New(hash.New, pinningSecret)
	hm.Write(rawProof)
	proof = hm.Sum(nil)
	return
}