text:
const std::string PROGRAM_NAME = "biotool-cpp";
// Tab separated header for the output
const std::string HEADER = "FILENAME\tNUMSEQ\tTOTAL\tMIN\tAVG\tMAX";
// Default value of the minlen command line argument
const unsigned DEFAULT_MIN_LEN = 0;
#endif

redpajama_set_name: RedPajamaGithub


text:
var express = require('express')
var app = express();

app.set('port', (process.env.PORT || 8080))
app.use(express.static(__dirname + '/static'))

app.get('/hello', function(request, response) {
  response.send('Hello World!')
})

app.listen(app.get('port'), function() {
  console.log("Node app is running at localhost:" + app.get('port'))
})


text:
package io.core9.commerce.checkout;

import io.core9.core.plugin.Core9Plugin;
import io.core9.plugin.widgets.datahandler.DataHandlerFactory;

public interface CheckoutDataHandler extends DataHandlerFactory<CheckoutDataHandlerConfig>, Core9Plugin {

}


text:
'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = scrollTo;

var _offset = require('../query/offset');

var _offset2 = _interopRequireDefault(_offset);

var _height = require('../query/height');

var _height2 = _interopRequireDefault(_height);

var _scrollParent = require('../query/scrollParent');

var _scrollParent2 = _interopRequireDefault(_scrollParent);

var _scrollTop = require('../query/scrollTop');

var _scrollTop2 = _interopRequireDefault(_scrollTop);

var _requestAnimationFrame = require('./requestAnimationFrame');

var _requestAnimationFrame2 = _interopRequireDefault(_requestAnimationFrame);

var _isWindow = require('../query/isWindow');

var _isWindow2 = _interopRequireDefault(_isWindow);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function scrollTo(selected, scrollParent) {
  var offset = (0, _offset2.default)(selected);
  var poff = { top: 0, left: 0 };
  var list = void 0,
      listScrollTop = void 0,
      selectedTop = void 0,
      isWin = void 0;
  var selectedHeight = void 0,
      listHeight = void 0,
      bottom = void 0;

  if (!selected) return;

  list = scrollParent || (0, _scrollParent2.default)(selected);
  isWin = (0, _isWindow2.default)(list);
  listScrollTop = (0, _scrollTop2.default)(list);

  listHeight = (0, _height2.default)(list, true);
  isWin = (0, _isWindow2.default)(list);

  if (!isWin) poff = (0, _offset2.default)(list);

  offset = {
    top: offset.top - poff.top,
    left: offset.left - poff.left,
    height: offset.height,
    width: offset.width
  };

  selectedHeight = offset.height;
  selectedTop = offset.top + (isWin ? 0 : listScrollTop);
  bottom = selectedTop + selectedHeight;

  listScrollTop = listScrollTop > selectedTop ? selectedTop : bottom > listScrollTop + listHeight ? bottom - listHeight : listScrollTop;

  var id = (0, _requestAnimationFrame2.default)(function () {
    return (0, _scrollTop2.default)(list, listScrollTop);
  });
  return function () {
    return _requestAnimationFrame2.default.cancel(id);
  };
}
module.exports = exports['default'];


text:
module.exports = function(sequalize, DataTypes) {
	var Setting = sequalize.define("Setting", {
		uuid: {
			type: DataTypes.UUID,
			defaultValue: DataTypes.UUIDV1,
			primaryKey: true
		},
		name: {
			type: DataTypes.STRING,
			allowNull: false,
			validate: {
				notEmpty: true
			}
		},
		value: {
			type: DataTypes.STRING
		}
	},
	{
		classMethods: {
	  		getActiveSeasonId: function(callback){
		    	Setting.findOrCreate({ where: { name: "ActiveSeason" }})
		    	.then(function(setting, created) {
		    		setting = setting[0];
		    		if(setting.value) {
		    			callback(setting.value);
		    		} else {
		    			callback(null);
		    		}
		    	});
	    	},
	    	setActiveSeasonId: function(seasonid, callback) {
	    		Setting.findOrCreate({
                    where: {
                        name: "ActiveSeason"
                    },
                    defaults: {
                        value: seasonid
                    }
                }).then(function(setting) {
                	setting = setting[0];
                	setting.value = seasonid;
                	setting.save()
                	.then(function() {
                		if(callback) {
                			callback();
                		}
                	});
                });
	    	}
	  	},
	  	instanceMethods: {
	    	foo: function() {
	    		return 0;
	    	}
	  	}
	});

	return Setting;
};


text:
<!doctype html>

	<meta charset="utf-8" />
	<link rel="icon" type="image/png" href="assets/img/favicon.ico">
	<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />

	<title>Light Bootstrap Dashboard by Creative Tim</title>

	<meta content='width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0' name='viewport' />
    <meta name="viewport" content="width=device-width" />

    <link href="assets/css/bootstrap.min.css" rel="stylesheet" />

    <link href="assets/css/animate.min.css" rel="stylesheet"/>

    <link href="assets/css/light-bootstrap-dashboard.css" rel="stylesheet"/>

    <link href="assets/css/demo.css" rel="stylesheet" />

    <link href="http://maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">
    <link href='http://fonts.googleapis.com/css?family=Roboto:400,700,300' rel='stylesheet' type='text/css'>
    <link href="assets/css/pe-icon-7-stroke.css" rel="stylesheet" />

                    Blackboard v2

Dashboard

Profile

My courses

Grades

Announcements

Notifications

Logout

                    <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#navigation-example-2">
                        Toggle navigation

                    </button>
                    Notifications

Search

                                    5

                                        5 Notifications

Announcement - Requirements Engineering

Material - Requirements Engineering

Material - Software Testing

Grade - Requirements Engineering

Grade - Requirements Engineering

Notifications

                                            04-10-2017
                                            Announcement 1
                                            Requirements Engineering

                                             04-10-2017
                                            Material Posted
                                            Requirements Engineering

                                             04-10-2017
                                            Material Posted
                                            Software Testing

                                             04-10-2017
                                            Test graded
                                            Requirements Engineering

                                             04-10-2017
                                            Assignment graded
                                            Requirements Engineering


text:
@interface ViewController : UIViewController <MixScrollViewDelegate, MixScrollViewDataSource>

@end


text:
/*
NAME

     atol, atoll -- convert ASCII string to long or long long
     integer

LIBRARY

     Standard C Library (libc, -lc)

SYNOPSIS

     #include <stdlib.h>

     long
     atol(const char *str);

     long long
     atoll(const char *str);

DESCRIPTION

     The atol() function converts the initial portion of the string pointed to
     by str to long integer representation.

     It is equivalent to:

           strtol(str, (char **)NULL, 10);

     The atoll() function converts the initial portion of the string pointed
     to by str to long long integer representation.

     It is equivalent to:

           strtoll(str, (char **)NULL, 10);

     atol() and atoll() functions use the current locale.

ERRORS

     The functions atol() and atoll() need not affect the value of errno on an
     error.
*/

#include "stdlib.h"

long atol(const char *s)
{
  	return strtol (s, NULL, 10);
}

long long atoll(const char *s)
{
  	return (long long)strtol (s, NULL, 10);
}


text:
package main

import (
	"net/http"
	"os"

	log "github.com/Sirupsen/logrus"
	"github.com/gorilla/websocket"
)

type Message struct {
	Type string `json:"type"`
	Body string `json:"body"`
}

var clients = make(map[*websocket.Conn]bool)
var broadcast = make(chan Message)
var upgrader = websocket.Upgrader{
	ReadBufferSize:  1024,
	WriteBufferSize: 1024,
	CheckOrigin: func(r *http.Request) bool {
		origin := r.Header.Get("Origin")
		return validOrigin(origin)
	},
}

var environment = os.Getenv("ENVIRONMENT")

func main() {
	if environment == "DEV" {
		log.SetLevel(log.DebugLevel)
	}
	port := os.Getenv("PORT")

	if port == "" {
		log.Fatal("$PORT must be set")
	}

	fs := http.FileServer(http.Dir("public"))
	http.Handle("/", fs)

	http.HandleFunc("/ws", handleWebSockets)

	go handleMessages()

	log.Println("http server started on :" + port)
	err := http.ListenAndServe(":"+port, nil)
	if err != nil {
		log.Fatal("ListenAndServe: ", err)
	}
}

func validOrigin(origin string) (valid bool) {
	log.Println("Validating origin: " + origin)
	valid = false
	allowOrigin := []string{
		"https://retro-awesome.herokuapp.com",
	}

	if environment == "DEV" {
		valid = true
		return
	}
	for _, v := range allowOrigin {
		if origin == v {
			valid = true
			return
		}
	}
	return
}

func handleWebSockets(w http.ResponseWriter, r *http.Request) {
	if r.Method != "GET" {
		http.Error(w, "Method Not Allowed", http.StatusMethodNotAllowed)
		return
	}

	ws, err := upgrader.Upgrade(w, r, nil)

	if err != nil {
		m := "Unable to upgrade to WebSockets"
		log.WithField("err", err).Println(m)
		http.Error(w, m, http.StatusBadRequest)
		return
	}

	defer ws.Close()

	clients[ws] = true

	for {
		var msg Message
		err := ws.ReadJSON(&msg)
		if err != nil {
			log.Warnf("ReadJSON error: %v, message content: %v", err, msg)
			delete(clients, ws)
			break
		}

		log.WithField("msg", msg).Debugln("Recieved message: ")

		broadcast <- msg
	}
}

func handleMessages() {
	for {
		msg := <-broadcast

		if msg.Type == "keep-alive" {
			continue
		}

		for client := range clients {
			err := client.WriteJSON(msg)
			log.WithField("msg", msg).Debugln("Sent message: ")
			if err != nil {
				log.Warnf("WriteJSON error: %v", err)
				client.Close()
				delete(clients, client)
			}
		}
	}
}


text:
package org.pentaho.di.core.database;

import java.util.Collection;
import java.util.HashSet;

import org.pentaho.di.core.Const;
import org.pentaho.di.core.row.ValueMetaInterface;

/**
 * Contains Generic Database Connection information through static final members
 *
 * @author Matt
 * @since 11-mrt-2005
 */

public class MonetDBDatabaseMeta extends BaseDatabaseMeta implements DatabaseInterface {

  public static ThreadLocal<Boolean> safeModeLocal = new ThreadLocal<Boolean>();

  public static final int DEFAULT_VARCHAR_LENGTH = 100;

  protected static final String FIELDNAME_PROTECTOR = "_";

  private static final int MAX_VARCHAR_LENGTH = Integer.MAX_VALUE;

  private static Collection<String> reservedWordAlt = new HashSet<String>();

  static {
    reservedWordAlt.add( "IS" );
    reservedWordAlt.add( "ISNULL" );
    reservedWordAlt.add( "NOTNULL" );
    reservedWordAlt.add( "IN" );
    reservedWordAlt.add( "BETWEEN" );
    reservedWordAlt.add( "OVERLAPS" );
    reservedWordAlt.add( "LIKE" );
    reservedWordAlt.add( "ILIKE" );
    reservedWordAlt.add( "NOT" );
    reservedWordAlt.add( "AND" );
    reservedWordAlt.add( "OR" );
    reservedWordAlt.add( "CHAR" );
    reservedWordAlt.add( "VARCHAR" );
    reservedWordAlt.add( "CLOB" );
    reservedWordAlt.add( "BLOB" );
    reservedWordAlt.add( "DECIMAL" );
    reservedWordAlt.add( "DEC" );
    reservedWordAlt.add( "NUMERIC" );
    reservedWordAlt.add( "TINYINT" );
    reservedWordAlt.add( "SMALLINT" );
    reservedWordAlt.add( "INT" );
    reservedWordAlt.add( "BIGINT" );
    reservedWordAlt.add( "REAL" );
    reservedWordAlt.add( "DOUBLE" );
    reservedWordAlt.add( "BOOLEAN" );
    reservedWordAlt.add( "DATE" );
    reservedWordAlt.add( "TIME" );
    reservedWordAlt.add( "TIMESTAMP" );
    reservedWordAlt.add( "INTERVAL" );
    reservedWordAlt.add( "YEAR" );
    reservedWordAlt.add( "MONTH" );
    reservedWordAlt.add( "DAY" );
    reservedWordAlt.add( "HOUR" );
    reservedWordAlt.add( "MINUTE" );
    reservedWordAlt.add( "SECOND" );
    reservedWordAlt.add( "TIMEZONE" );
    reservedWordAlt.add( "EXTRACT" );
    reservedWordAlt.add( "CURRENT_DATE" );
    reservedWordAlt.add( "CURRENT_TIME" );
    reservedWordAlt.add( "CURRENT_TIMESTAMP" );
    reservedWordAlt.add( "LOCALTIME" );
    reservedWordAlt.add( "LOCALTIMESTAMP" );
    reservedWordAlt.add( "CURRENT_TIME" );
    reservedWordAlt.add( "SERIAL" );
    reservedWordAlt.add( "START" );
    reservedWordAlt.add( "WITH" );
    reservedWordAlt.add( "INCREMENT" );
    reservedWordAlt.add( "CACHE" );
    reservedWordAlt.add( "CYCLE" );
    reservedWordAlt.add( "SEQUENCE" );
    reservedWordAlt.add( "GETANCHOR" );
    reservedWordAlt.add( "GETBASENAME" );
    reservedWordAlt.add( "GETCONTENT" );
    reservedWordAlt.add( "GETCONTEXT" );
    reservedWordAlt.add( "GETDOMAIN" );
    reservedWordAlt.add( "GETEXTENSION" );
    reservedWordAlt.add( "GETFILE" );
    reservedWordAlt.add( "GETHOST" );
    reservedWordAlt.add( "GETPORT" );
    reservedWordAlt.add( "GETPROTOCOL" );
    reservedWordAlt.add( "GETQUERY" );
    reservedWordAlt.add( "GETUSER" );
    reservedWordAlt.add( "GETROBOTURL" );
    reservedWordAlt.add( "ISURL" );
    reservedWordAlt.add( "NEWURL" );
    reservedWordAlt.add( "BROADCAST" );
    reservedWordAlt.add( "MASKLEN" );
    reservedWordAlt.add( "SETMASKLEN" );
    reservedWordAlt.add( "NETMASK" );
    reservedWordAlt.add( "HOSTMASK" );
    reservedWordAlt.add( "NETWORK" );
    reservedWordAlt.add( "TEXT" );
    reservedWordAlt.add( "ABBREV" );
    reservedWordAlt.add( "CREATE" );
    reservedWordAlt.add( "TYPE" );
    reservedWordAlt.add( "NAME" );
    reservedWordAlt.add( "DROP" );
    reservedWordAlt.add( "USER" );
  }

  @Override
  public int[] getAccessTypeList() {
    return new int[] {
      DatabaseMeta.TYPE_ACCESS_NATIVE, DatabaseMeta.TYPE_ACCESS_ODBC, DatabaseMeta.TYPE_ACCESS_JNDI };
  }

  /**
   * @see DatabaseInterface#getNotFoundTK(boolean)
   */
  @Override
  public int getNotFoundTK( boolean use_autoinc ) {
    if ( supportsAutoInc() && use_autoinc ) {
      return 1;
    }
    return super.getNotFoundTK( use_autoinc );
  }

  @Override
  public String getDriverClass() {
    if ( getAccessType() == DatabaseMeta.TYPE_ACCESS_NATIVE ) {
      return "nl.cwi.monetdb.jdbc.MonetDriver";
    } else {
      return "sun.jdbc.odbc.JdbcOdbcDriver"; // always ODBC!
    }

  }

  @Override
  public String getURL( String hostname, String port, String databaseName ) {
    if ( getAccessType() == DatabaseMeta.TYPE_ACCESS_NATIVE ) {
      if ( Const.isEmpty( port ) ) {
        return "jdbc:monetdb://" + hostname + "/" + databaseName;
      } else {
        return "jdbc:monetdb://" + hostname + ":" + port + "/" + databaseName;
      }
    } else {
      return "jdbc:odbc:" + databaseName;
    }
  }

  /**
   * Checks whether or not the command setFetchSize() is supported by the JDBC driver...
   *
   * @return true is setFetchSize() is supported!
   */
  @Override
  public boolean isFetchSizeSupported() {
    return false;
  }

  /**
   * @return true if the database supports bitmap indexes
   */
  @Override
  public boolean supportsBitmapIndex() {
    return true;
  }

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

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

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

  /**
   * @param tableName
   *          The table to be truncated.
   * @return The SQL statement to truncate a table: remove all rows from it without a transaction
   */
  @Override
  public String getTruncateTableStatement( String tableName ) {
    return "DELETE FROM " + tableName;
  }

  /**
   * Generates the SQL statement to add a column to the specified table For this generic type, i set it to the most
   * common possibility.
   *
   * @param tablename
   *          The table to add
   * @param v
   *          The column defined as a value
   * @param tk
   *          the name of the technical key field
   * @param use_autoinc
   *          whether or not this field uses auto increment
   * @param pk
   *          the name of the primary key field
   * @param semicolon
   *          whether or not to add a semi-colon behind the statement.
   * @return the SQL statement to add a column to the specified table
   */
  @Override
  public String getAddColumnStatement( String tablename, ValueMetaInterface v, String tk, boolean use_autoinc,
    String pk, boolean semicolon ) {
    return "ALTER TABLE " + tablename + " ADD " + getFieldDefinition( v, tk, pk, use_autoinc, true, false );
  }

  /**
   * Generates the SQL statement to modify a column in the specified table
   *
   * @param tablename
   *          The table to add
   * @param v
   *          The column defined as a value
   * @param tk
   *          the name of the technical key field
   * @param use_autoinc
   *          whether or not this field uses auto increment
   * @param pk
   *          the name of the primary key field
   * @param semicolon
   *          whether or not to add a semi-colon behind the statement.
   * @return the SQL statement to modify a column in the specified table
   */
  @Override
  public String getModifyColumnStatement( String tablename, ValueMetaInterface v, String tk, boolean use_autoinc,
    String pk, boolean semicolon ) {
    return "ALTER TABLE " + tablename + " MODIFY " + getFieldDefinition( v, tk, pk, use_autoinc, true, false );
  }

  @Override
  public String[] getReservedWords() {
    return reservedWordAlt.toArray( new String[] {} );
  }

  @Override
  public String getFieldDefinition( ValueMetaInterface v, String tk, String pk, boolean use_autoinc,
    boolean add_fieldname, boolean add_cr ) {
    StringBuilder retval = new StringBuilder();

    String fieldname = v.getName();
    int length = v.getLength();
    int precision = v.getPrecision();

    Boolean mode = MonetDBDatabaseMeta.safeModeLocal.get();
    boolean safeMode = mode != null && mode.booleanValue();

    if ( add_fieldname ) {
      // protect the fieldname
      if ( safeMode ) {
        fieldname = getSafeFieldname( fieldname );
      }

      retval.append( fieldname + " " );
    }

    int type = v.getType();
    switch ( type ) {
      case ValueMetaInterface.TYPE_TIMESTAMP:
      case ValueMetaInterface.TYPE_DATE:
        retval.append( "TIMESTAMP" );
        break;
      case ValueMetaInterface.TYPE_BOOLEAN:
        if ( supportsBooleanDataType() ) {
          retval.append( "BOOLEAN" );
        } else {
          retval.append( "CHAR(1)" );
        }
        break;
      case ValueMetaInterface.TYPE_NUMBER:
      case ValueMetaInterface.TYPE_INTEGER:
      case ValueMetaInterface.TYPE_BIGNUMBER:
        if ( fieldname.equalsIgnoreCase( tk ) || // Technical key
          fieldname.equalsIgnoreCase( pk ) // Primary key
        ) {
          if ( use_autoinc ) {
            retval.append( "SERIAL" );
          } else {
            retval.append( "BIGINT" );
          }
        } else {
          // Integer values...
          if ( precision == 0 ) {
            if ( length > 9 ) {
              if ( length < 19 ) {
                // can hold signed values between -9223372036854775808 and 9223372036854775807
                // 18 significant digits
                retval.append( "BIGINT" );
              } else {
                retval.append( "DECIMAL(" ).append( length ).append( ")" );
              }
            } else if ( type == ValueMetaInterface.TYPE_NUMBER ) {
              retval.append( "DOUBLE" );
            } else {
              retval.append( "BIGINT" );
            }
          } else {
            // Floating point values...
            if ( length > 15 ) {
              retval.append( "DECIMAL(" ).append( length );
              if ( precision > 0 ) {
                retval.append( ", " ).append( precision );
              }
              retval.append( ")" );
            } else {
              // A double-precision floating-point number is accurate to approximately 15 decimal places.
              // http://mysql.mirrors-r-us.net/doc/refman/5.1/en/numeric-type-overview.html
              retval.append( "DOUBLE" );
            }
          }
        }
        break;
      case ValueMetaInterface.TYPE_STRING:
        if ( length > getMaxVARCHARLength() ) {
          retval.append( "CLOB" );
        } else {
          retval.append( "VARCHAR(" );
          if ( length > 0 ) {
            retval.append( length );
          } else {
            if ( safeMode ) {
              retval.append( DEFAULT_VARCHAR_LENGTH );
            }
          }
          retval.append( ")" );
        }
        break;
      default:
        retval.append( " UNKNOWN" );
        break;
    }

    if ( add_cr ) {
      retval.append( Const.CR );
    }

    return retval.toString();
  }

  @Override
  public String[] getUsedLibraries() {
    return new String[] { "monetdb-jdbc-2.8.jar", };
  }

  /**
   * Returns the minimal SQL to launch in order to determine the layout of the resultset for a given database table
   *
   * @param tableName
   *          The name of the table to determine the layout for
   * @return The SQL to launch.
   */
  @Override
  public String getSQLQueryFields( String tableName ) {
    return "SELECT * FROM " + tableName + ";";
  }

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

  @Override
  public int getMaxVARCHARLength() {
    return MAX_VARCHAR_LENGTH;
  }
}


text:
<!doctype html>

    <title>Data Screen</title>
    <link rel="stylesheet" href="./stylesheets/base.css" />
    <link href='http://fonts.googleapis.com/css?family=Bitter:400,700,400italic' rel='stylesheet' type='text/css' />
    <meta name="viewport"
     content="width=device-width, minimum-scale=1.0,initial-scale=1.0, user-scalable=yes" />

This is an experiment from Code for America. You can log issues and find out more from our GitHub repository. You must use Chrome to view this dashboard.

            visitors online

Live search

Active pages

Most popular pages


text:
local kong = kong
local find = string.find
local fmt  = string.format
local utils = require "kong.tools.utils"

local CONTENT_TYPE    = "Content-Type"
local ACCEPT          = "Accept"
local TYPE_GRPC       = "application/grpc"

local BODIES = {
  [400] = "Bad request",
  [404] = "Not found",
  [405] = "Method not allowed",
  [408] = "Request timeout",
  [411] = "Length required",
  [412] = "Precondition failed",
  [413] = "Payload too large",
  [414] = "URI too long",
  [417] = "Expectation failed",
  [494] = "Request header or cookie too large",
  [500] = "An unexpected error occurred",
  [502] = "An invalid response was received from the upstream server",
  [503] = "The upstream server is currently unavailable",
  [504] = "The upstream server is timing out",
}

local get_body
do
  local DEFAULT_FMT = "The upstream server responded with %d"

  get_body = function(status)
    local body = BODIES[status]

    if body then
      return body
    end

    body = fmt(DEFAULT_FMT, status)
    BODIES[status] = body

    return body
  end
end

return function(ctx)
  local accept_header = kong.request.get_header(ACCEPT)
  if accept_header == nil then
    accept_header = kong.request.get_header(CONTENT_TYPE)
    if accept_header == nil then
      accept_header = kong.configuration.error_default_type
    end
  end

  local status = kong.response.get_status()
  local message = get_body(status)

  local headers
  if find(accept_header, TYPE_GRPC, nil, true) == 1 then
    message = { message = message }

  else
    local mime_type = utils.get_mime_type(accept_header)
    message = fmt(utils.get_error_template(mime_type), message)
    headers = { [CONTENT_TYPE] = mime_type }

  end

  -- Reset relevant context values
  ctx.buffered_proxying = nil
  ctx.response_body = nil

  if ctx then
    ctx.delay_response = nil
    ctx.delayed_response = nil
    ctx.delayed_response_callback = nil
  end

  return kong.response.exit(status, message, headers)
end


text:
QUOTATION DETAIL

                Quotation Header Detail and Activities

            Dashboard   /   Quotations   /
            Quotation Detail

                            <button class="btn btn-primary" id="btnSaveQuotationDetail" name="btnSaveQuotationDetail" (click)="btnSaveQuotationDetailClick()"> Save</button>
                            <button class="btn btn-primary" id="btnPrintQuotationDetail" name="btnPrintQuotationDetail" (click)="btnPrintQuotationDetailClick()"
                                data-toggle="modal" data-backdrop="static" data-keyboard="false" data-target="#print-quotation-detail-modal"> Print</button>
                            <button class="btn btn-danger" id="btnCloseQuotationDetail" name="btnCloseQuotationDetail" (click)="backClicked()"> Close</button>

                                    Quotation Number

                                        <input type="text" [(ngModel)]="quotationNumber" [disabled]="true" class="form-control" id="quotationNumber" name="quotationNumber"
                                            placeholder="Quotation Number" />

                                    Quotation Date

                                        <wj-input-date [(value)]="quotationDateValue" [format]="'yyyy-MM-dd'" [mask]="'9999-99-99'" style="width: 100%;">
                                        </wj-input-date>
                                        <input type="hidden" class="form-control" id="quotationDateValue" />

                                    Lead Number

                                        <wj-combo-box [itemsSource]="quotationLeadObservableArray" [placeholder]="'Select Lead Number'" [displayMemberPath]="'LeadNumberDetail'"
                                            [selectedValuePath]="'Id'" [isEditable]="false" [isRequired]="true" [(selectedValue)]="quotationLeadSelectedValue"
                                            style="width: 100%;">
                                        </wj-combo-box>
                                        <input type="hidden" class="form-control" id="quotationLeadSelectedValue" />

                                    Customer

                                        <wj-combo-box [itemsSource]="quotationCustomerObservableArray" [placeholder]="'Select Customer'" [displayMemberPath]="'Article'"
                                            [selectedValuePath]="'Id'" [isEditable]="false" [isRequired]="true" [(selectedValue)]="quotationCustomerSelectedValue"
                                            style="width: 100%;">
                                        </wj-combo-box>
                                        <input type="hidden" class="form-control" id="quotationCustomerSelectedValue" />

                                    Product

                                        <wj-combo-box [itemsSource]="quotationProductObservableArray" [placeholder]="'Select Product'" [displayMemberPath]="'Article'"
                                            [selectedValuePath]="'Id'" [isEditable]="false" [isRequired]="true" [(selectedValue)]="quotationProductSelectedValue"
                                            style="width: 100%;">
                                        </wj-combo-box>
                                        <input type="hidden" class="form-control" id="quotationProductSelectedValue" />

                                    Encoded By

                                        <input type="text" [(ngModel)]="quotationEncodedBySelectedValue" [disabled]="true" class="form-control" id="quotationEncodedBySelectedValue"
                                            name="quotationEncodedBySelectedValue" placeholder="Staff" />

                                    Remarks

                                        <textarea [(ngModel)]="quotationRemarks" class="form-control" rows="7" id="quotationRemarks" name="quotationRemarks" placeholder="Remarks"></textarea>

                                    Status

                                        <wj-combo-box [itemsSource]="quotationStatusArray" [placeholder]="'Select Status'" [isEditable]="true" [isRequired]="false"
                                            [(selectedValue)]="quotationStatusSelectedValue" style="width: 100%;">
                                        </wj-combo-box>
                                        <input type="hidden" class="form-control" id="quotationStatusSelectedValue" />

 Activity

                            <button class="btn btn-primary" (click)="btnActivityDetailModal(true)" data-toggle="modal" data-backdrop="static" data-keyboard="false"
                                data-target="#activity-detail-modal"> Add</button>

                <wj-flex-grid [itemsSource]="activityCollectionView" [selectionMode]="3">
                    <wj-flex-grid-column [header]="Edit" [isReadOnly]="true" [isContentHtml]="true" [width]="60">
                        <template wjFlexGridCellTemplate [cellType]="'Cell'" let-cell="cell">
                            <button class="btn btn-primary btn-xs btn-block" (click)="btnActivityDetailModal(false)" data-toggle="modal" data-backdrop="static"
                                data-keyboard="false" data-target="#activity-detail-modal">
                                 Edit
                            </button>
                        </template>
                    </wj-flex-grid-column>
                    <wj-flex-grid-column [header]="Delete" [isReadOnly]="true" [width]="80">
                        <template wjFlexGridCellTemplate [cellType]="'Cell'" let-cell="cell">
                            <button class="btn btn-danger btn-xs btn-block" (click)="btnActivityDeleteConfirmationModal()" data-toggle="modal" data-backdrop="static"
                                data-keyboard="false" data-target="#activity-delete-confirmation-modal">
                                 Delete
                            </button>
                        </template>
                    </wj-flex-grid-column>
                    <wj-flex-grid-column [header]="Print" [isReadOnly]="true" [isContentHtml]="true" [width]="70">
                        <template wjFlexGridCellTemplate [cellType]="'Cell'" let-cell="cell">
                            <button class="btn btn-primary btn-xs btn-block" (click)="btnActivityPrintClick()">
                                 Print
                            </button>
                        </template>
                    </wj-flex-grid-column>
                    <wj-flex-grid-column [header]="'Activity No.'" [binding]="'ActivityNumber'" [isReadOnly]="true" [width]="'1*'">
                    </wj-flex-grid-column>
                    <wj-flex-grid-column [header]="'Activity Date'" [binding]="'ActivityDate'" [isReadOnly]="true" [width]="'1*'">
                    </wj-flex-grid-column>
                    <wj-flex-grid-column [header]="'Staff'" [binding]="'StaffUser'" [isReadOnly]="true" [width]="'2*'">
                    </wj-flex-grid-column>
                    <wj-flex-grid-column [header]="'Particualrs'" [binding]="'Particulars'" [isReadOnly]="true" [width]="'2.5*'">
                    </wj-flex-grid-column>
                    <wj-flex-grid-column [header]="'Status'" [binding]="'ActivityStatus'" [isReadOnly]="true" [width]="'1.5*'">
                    </wj-flex-grid-column>
                </wj-flex-grid>

                        <button type="button" class="btn btn-default" (click)="activityCollectionView.moveToFirstPage()">
                             First
                        </button>
                        <button type="button" class="btn btn-default" (click)="activityCollectionView.moveToPreviousPage()">
                             Previous
                        </button>
                        <button type="button" class="btn btn-default" disabled style="width:100px">
                            {{ activityCollectionView.pageIndex + 1 }} / {{ activityCollectionView.pageCount }}
                        </button>
                        <button type="button" class="btn btn-default" (click)="activityCollectionView.moveToNextPage()">
                            Next
                        </button>
                        <button type="button" class="btn btn-default" (click)="activityCollectionView.moveToLastPage()">
                            Last
                        </button>

{{ activityDetailModalString }} Activity

                        Activity Date

                            <wj-input-date [(value)]="activityDateValue" [format]="'yyyy-MM-dd'" [mask]="'9999-99-99'" style="width: 100%;">
                            </wj-input-date>

                        Particular Category

                            <wj-combo-box [itemsSource]="activityParticularCategories" [placeholder]="'Select Particular Category'" [isEditable]="false"
                                [isRequired]="true" [(selectedValue)]="activityParticularCategorySelectedValue" style="width: 100%;">
                            </wj-combo-box>

                        Particulars

                            <textarea class="form-control" rows="7" id="activityParticulars" name="Particulars" placeholder="Particulars"></textarea>

                        Location

                            <wj-combo-box [itemsSource]="activityLocations" [placeholder]="'Select Location'" [isEditable]="false"
                                [isRequired]="true" [(selectedValue)]="activityLocationsSelectedValue" style="width: 100%; ">
                            </wj-combo-box>

                        No. of Hours

                            <wj-combo-box [itemsSource]="activityNoOfHours" [placeholder]="'Select No. of Hours'" [isEditable]="false" [isRequired]="true"
                                [(selectedValue)]="activityNoOfHoursSelectedValue" style="width: 30%;">
                            </wj-combo-box>

                        Amount

                            <input type="text" style="text-align: right;" [(ngModel)]="activityAmount" (keypress)="onKeyPressOnlyDecimalNumberKey($event)"
                                (blur)="onBlurOnlyDecimalNumberKey()" class="form-control" id="activityAmount" name="" placeholder="0.00"
                            />

                        Status

                            <wj-combo-box [itemsSource]="activityStatus" [placeholder]="'Select Status'" [isEditable]="false" [isRequired]="true" [(selectedValue)]="activityStatusSelectedValue"
                                style="width: 100%;">
                            </wj-combo-box>

                <button type="button" class="btn btn-primary" id="btnActivitySave" (click)="btnActivitySaveClick()"> Save</button>
                <button type="button" class="btn btn-danger" id="btnActivityClose" data-dismiss="modal"> Close</button>

Delete

                Delete Activity?

                <button type="button" class="btn btn-danger" id="btnActivityDeleteConfirmation" (click)="btnActivityDeleteConfirmationClick()"> Delete</button>
                <button type="button" class="btn btn-default" id="btnActivityCloseDeleteConfirmation" data-dismiss="modal"> Close</button>

Print Quotation

Customer

Product / Service

Payment Schedule

Project Timeline and Delivery

User

                                        Customer

                                            <input type="text" class="form-control" id="printQuotationCustomer" placeholder="Customer Name" />

                                        Address

                                            <textarea class="form-control" rows="7" id="printQuotationAddress" name="printQuotationAddress" placeholder="Address"></textarea>

                                        Contact Person

                                            <input type="text" class="form-control" id="printQuotationContactPerson" placeholder="Contact Person" />

                                        Contact Number

                                            <input type="text" class="form-control" id="printQuotationContactNumber" placeholder="Contact Number" />

                                        Contact Email

                                            <input type="text" class="form-control" id="printQuotationContactEmail" placeholder="Contact Email" />

                                        QRef No

                                            <input type="text" class="form-control" id="QRefNo" placeholder="QRef No" />

                                        Date

                                            <input type="text" class="form-control" id="QDate" />

                                        Client PO No

                                            <input type="text" class="form-control" id="ClientPONo" placeholder="Client PO No" />

                                        Client PO Date

                                            <input type="text" class="form-control" id="ClientPODate" placeholder="Client PO Date" />

                                        Leads Ref No

                                            <input type="text" class="form-control" id="LeadsRefNo" placeholder="Leads Ref No" />

                                        Code

                                            <input type="text" class="form-control" id="printQuotationProductCode" placeholder="Product Code" />

                                        Description

                                            <input type="text" class="form-control" id="printQuotationProductDescription" placeholder="Product Description" />

                                        Price

                                            <input type="text" class="form-control" style="text-align: right;" (keyup)="priceOnKeyEvent($event)" [(ngModel)]="printQuotationProductPrice"
                                                id="printQuotationProductPrice" (keypress)="onKeyPressOnlyDecimalNumberKey($event)"
                                                (blur)="onBlurOnlyDecimalNumberKeyForProductPricePrintQuotation()" placeholder="Price"
                                            />

                                        Quantity

                                            <input type="text" class="form-control" style="text-align: right;" (keyup)="quantityOnKeyEvent($event)" [(ngModel)]="printQuotationProductQuantity"
                                                id="printQuotationProductQuantity" (keypress)="onKeyPressOnlyDecimalNumberKey($event)"
                                                (blur)="onBlurOnlyDecimalNumberKeyForProductQuantityPrintQuotation()" placeholder="Quantity"
                                            />

                                Remarks

                                    <textarea class="form-control" rows="7" [(ngModel)]="printQuotationProductRemarks" id="printQuotationProductRemarks" name="printQuotationProductRemarks"
                                        placeholder="Remarks"></textarea>

                                <button class="btn btn-primary" (click)="paymentOnclick()" data-toggle="modal" data-backdrop="static" data-keyboard="false"
                                    data-target="#quotation-print-add-payment"> Add</button>

                                <wj-flex-grid [itemsSource]="paymentScheduleCollectionView" [selectionMode]="3">
                                    <wj-flex-grid-column [header]="Edit" [isReadOnly]="true" [isContentHtml]="true" [width]="70">
                                        <template wjFlexGridCellTemplate [cellType]="'Cell'" let-cell="cell">
                                            <button class="btn btn-primary btn-xs btn-block" (click)="paymentEdit()" data-toggle="modal" data-backdrop="static" data-keyboard="false"
                                                data-target="#quotation-print-add-payment">
                                                 Edit
                                            </button>
                                        </template>
                                    </wj-flex-grid-column>
                                    <wj-flex-grid-column [header]="Delete" [isReadOnly]="true" [width]="90">
                                        <template wjFlexGridCellTemplate [cellType]="'Cell'" let-cell="cell">
                                            <button class="btn btn-danger btn-xs btn-block" data-toggle="modal" data-backdrop="static" data-keyboard="false" data-target="#payment-delete-confirmation-modal">
                                                 Remove
                                            </button>
                                        </template>
                                    </wj-flex-grid-column>
                                    <wj-flex-grid-column [header]="'Description'" [binding]="'Description'" [isReadOnly]="true" [width]="'1.5*'">
                                    </wj-flex-grid-column>
                                    <wj-flex-grid-column [header]="'Amount'" [binding]="'Amount'" [isReadOnly]="true" [width]="'1*'" [align]="'right'">
                                    </wj-flex-grid-column>
                                    <wj-flex-grid-column [header]="'Remarks'" [binding]="'Remarks'" [isReadOnly]="true" [width]="'2*'">
                                    </wj-flex-grid-column>
                                </wj-flex-grid>

                                        <button type="button" class="btn btn-default" (click)="paymentScheduleCollectionView.moveToFirstPage()">
                                             First
                                        </button>
                                        <button type="button" class="btn btn-default" (click)="paymentScheduleCollectionView.moveToPreviousPage()">
                                             Previous
                                        </button>
                                        <button type="button" class="btn btn-default" (click)="paymentScheduleCollectionView.moveToNextPage()">
                                            Next
                                        </button>
                                        <button type="button" class="btn btn-default" (click)="paymentScheduleCollectionView.moveToLastPage()">
                                            Last
                                        </button>

                                <button class="btn btn-primary" (click)="timelineOnclick()" data-toggle="modal" data-backdrop="static" data-keyboard="false"
                                    data-target="#quotation-print-add-timeline"> Add</button>

                                <wj-flex-grid [itemsSource]="timelineCollectionView" [selectionMode]="3">
                                    <wj-flex-grid-column [header]="Edit" [isReadOnly]="true" [isContentHtml]="true" [width]="70">
                                        <template wjFlexGridCellTemplate [cellType]="'Cell'" let-cell="cell">
                                            <button class="btn btn-primary btn-xs btn-block" (click)="timelineEdit()" data-toggle="modal" data-backdrop="static" data-keyboard="false"
                                                data-target="#quotation-print-add-timeline">
                                                 Edit
                                            </button>
                                        </template>
                                    </wj-flex-grid-column>
                                    <wj-flex-grid-column [header]="Delete" [isReadOnly]="true" [width]="90">
                                        <template wjFlexGridCellTemplate [cellType]="'Cell'" let-cell="cell">
                                            <button class="btn btn-danger btn-xs btn-block" data-toggle="modal" data-backdrop="static" data-keyboard="false" data-target="#timeline-delete-confirmation-modal">
                                                 Remove
                                            </button>
                                        </template>
                                    </wj-flex-grid-column>
                                    <wj-flex-grid-column [header]="'Product'" [binding]="'Product'" [isReadOnly]="true" [width]="'1*'">
                                    </wj-flex-grid-column>
                                    <wj-flex-grid-column [header]="'Estimated Timeline'" [binding]="'Timeline'" [isReadOnly]="true" [width]="'1.5*'" [align]="'right'">
                                    </wj-flex-grid-column>
                                    <wj-flex-grid-column [header]="'Remarks'" [binding]="'Remarks'" [isReadOnly]="true" [width]="'1.5*'">
                                    </wj-flex-grid-column>
                                </wj-flex-grid>

                                        <button type="button" class="btn btn-default" (click)="timelineCollectionView.moveToFirstPage()">
                                             First
                                        </button>
                                        <button type="button" class="btn btn-default" (click)="timelineCollectionView.moveToPreviousPage()">
                                             Previous
                                        </button>
                                        <button type="button" class="btn btn-default" (click)="timelineCollectionView.moveToNextPage()">
                                            Next
                                        </button>
                                        <button type="button" class="btn btn-default" (click)="timelineCollectionView.moveToLastPage()">
                                            Last
                                        </button>

                                        Prepared By

                                            <wj-combo-box [itemsSource]="quotationPrintPreparedByUserObservableArray" [placeholder]="'Select User'" [displayMemberPath]="'FullName'"
                                                [selectedValuePath]="'FullName'" [isEditable]="false" [isRequired]="true" [(selectedValue)]="quotationPrintPreparedByUserSelectedValue"
                                                style="width: 100%;">
                                            </wj-combo-box>

                                        Approved By

                                            <wj-combo-box [itemsSource]="quotationPrintApprovedByUserObservableArray" [placeholder]="'Select User'" [displayMemberPath]="'FullName'"
                                                [selectedValuePath]="'FullName'" [isEditable]="false" [isRequired]="true" [(selectedValue)]="quotationPrintApprovedByUserSelectedValue"
                                                style="width: 100%;">
                                            </wj-combo-box>

                <button type="button" id="btnPrintQuotationDetailPrintButton" class="btn btn-primary" (click)="btnPrintQuotationDetailPrintButtonClick()"> Print</button>
                <button type="button" id="btnPrintQuotationDetailCloseButton" class="btn btn-default" data-dismiss="modal"> Close</button>

{{ printQuotationString }} Payment Schedule

                        Description

                            <textarea class="form-control" rows="5" [(ngModel)]="quotationPrintDescription" id="quotationPrintDescription" name="Particulars"
                                placeholder="Description"></textarea>

                        Amount

                            <input type="text" class="form-control" style="text-align: right;" [(ngModel)]="quotationPrintAmount" id="quotationPrintAmount"
                                (keypress)="onKeyPressOnlyDecimalNumberKey($event)" (blur)="onBlurOnlyDecimalNumberKeyForPrintQuotation()"
                                placeholder="Amount" />

                        Remarks

                            <textarea class="form-control" rows="7" [(ngModel)]="quotationPrintRemarks" id="quotationPrintRemarks" name="Remarks" placeholder="Remarks"></textarea>

                <button type="button" class="btn btn-primary" id="btnAddPaymentData" (click)="btnAddPaymentDataClick()"> Save</button>
                <button type="button" class="btn btn-default" id="btnPaymentCloseModal" data-dismiss="modal"> Close</button>

Delete

                Delete Payment Schedule?

                <button type="button" class="btn btn-danger" id="btnPaymentDeleteConfirmation" (click)="btnPaymentDeleteConfirmationClick()"> Delete</button>
                <button type="button" class="btn btn-default" id="btnPaymentCloseDeleteConfirmation" data-dismiss="modal"> Close</button>

{{ printProductQuotationString }} Product

                <button type="button" class="btn btn-primary" id="btnAddProductData" (click)="btnAddProductDataClick()"> Save</button>
                <button type="button" class="btn btn-default" id="btnProductCloseModal" data-dismiss="modal"> Close</button>

Delete

                Delete Product?

                <button type="button" class="btn btn-danger" id="btnProductDeleteConfirmation" (click)="btnProductDeleteConfirmationClick()"> Delete </button>
                <button type="button" class="btn btn-default" id="btProductCloseDeleteConfirmation" data-dismiss="modal"> Close </button>

{{ printTimelineQuotationString }} Timeline Schedule

                        Product

                            <input type="text" class="form-control" id="printQuotationTimeLineProduct" placeholder="Product" />

                        Estimated TimeLine

                            <textarea class="form-control" rows="3" id="printQuotationTimeLine" name="printQuotationTimeLine" placeholder="Timeline"></textarea>

                        Remarks

                            <textarea class="form-control" rows="7" [(ngModel)]="printQuotationTimeLineRemarks" id="printQuotationTimeLineRemarks" name="printQuotationTimeLineRemarks"
                                placeholder="Remarks"></textarea>

                <button type="button" class="btn btn-primary" id="btnAddtimelineData" (click)="btnAddtimelineDataClick()"> Save</button>
                <button type="button" class="btn btn-default" id="btntimelineCloseModal" data-dismiss="modal"> Close</button>

Delete

                Delete Timeline Schedule?

                <button type="button" class="btn btn-danger" id="btnTimelineDeleteConfirmation" (click)="btnTimelineDeleteConfirmationClick()"> Delete</button>
                <button type="button" class="btn btn-default" id="btnTimelineCloseDeleteConfirmation" data-dismiss="modal"> Close</button>

<button id="btn-hidden-start-loading" [hidden]="true"></button>
<button id="btn-hidden-complete-loading" [hidden]="true" (click)="completeLoading()"></button>
<button id="btn-hidden-lead-data" [hidden]="true" (click)="getLeadServiceData()"></button>
<button id="btn-hidden-customer-data" [hidden]="true" (click)="getCustomerArticleData()"></button>
<button id="btn-hidden-product-data" [hidden]="true" (click)="getProductArticleData()"></button>
<button id="btn-hidden-encoded-user-data" [hidden]="true" (click)="getUserServiceData()"></button>
<button id="btn-hidden-quotation-data" [hidden]="true" (click)="getQuotationServiceData()"></button>
<button id="btn-hidden-selectedValue-data" [hidden]="true" (click)="setDropdownSelectedValueData()"></button>
<button id="btn-hidden-activity-delete-modal" [hidden]="true" data-toggle="modal" data-target="#activity-delete-confirmation-modal"></button>
<button id="btn-hidden-activity-detail-modal" [hidden]="true" data-toggle="modal" data-target="#activity-detail-modal"></button>
<button id="btn-hidden-activity-data" [hidden]="true" (click)="getListActivity(true)"></button>
<button id="btn-hidden-finished-load" [hidden]="true" (click)="finishedLoad()"></button>


text:
package com.intellij.plugins.haxe.lang.parser;

import com.intellij.lang.ASTNode;
import com.intellij.lang.PsiBuilder;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.plugins.haxe.metadata.lexer.HaxeMetadataTokenTypes;
import com.intellij.plugins.haxe.util.HaxeDebugTimeLog;
import com.intellij.psi.PsiFile;
import com.intellij.psi.impl.source.resolve.FileContextUtil;
import com.intellij.psi.tree.IElementType;

public class HaxeParserWrapper extends HaxeParser {

  private static Logger LOG = Logger.getInstance("#HaxeParserWrapper");

  /** Turns on debugging when running the parser.  On when the logger is in debug mode. */
  private static boolean debugging = LOG.isDebugEnabled();

  @Override
  public ASTNode parse(IElementType t, PsiBuilder b) {
    if (debugging) {
      HaxeDebugTimeLog timeLog = null;

      // The file is attached to the user data. :/  I suspect this was a hack, but it's what we've got available.
      PsiFile file = b.getUserDataUnprotected(FileContextUtil.CONTAINING_FILE_KEY);

      String description = null != file ? file.getName() : t.toString();
      timeLog = HaxeDebugTimeLog.startNew("HaxeParser " + description, HaxeDebugTimeLog.Since.StartAndPrevious);

      ASTNode node = super.parse(t, b);

      timeLog.stamp("Finished parsing.");
      timeLog.printIfTimeExceeds(20 /* milliseconds */);

      return node;
    }
    return super.parse(t,b);
  }

  @Override
  protected boolean parse_root_(IElementType t, PsiBuilder b, int l) {
    if (t == HaxeMetadataTokenTypes.CT_META_ARGS) {
      return compileTimeMetaArgList(b, l + 1);
    } else if (t == HaxeMetadataTokenTypes.RT_META_ARGS) {
      return runTimeMetaArgList(b, l + 1);
    }
    return haxeFile(b, l + 1);
  }
}


text:
Congratulations! Your purchase has been completed!

Please follow this instructions to get your order:

{{ instructions|safe }}

To continue shopping checkout our coins for sale


text:
require File.expand_path('../../test_helper', __FILE__)

class LinkedIssuesTest < ActionController::IntegrationTest
  include Capybara::DSL

  fixtures :projects,
           :users,
           :roles,
           :members,
           :issues

  def test_add_linked_issue_from_main_project
    visit '/login'
    fill_in "Login", :with => 'admin'
    fill_in "Password", :with => 'admin'
    click_on "Login »"

    # Ensure issues and time tracking are managed
    visit '/projects/ecookbook/settings/modules'
    check 'Issue tracking'
    check 'Time tracking'
    find("#modules-form").click_on 'Save'

    # Assign Tracker
    visit '/projects/ecookbook/settings'
    check 'Bug'
    find("#edit_project_1").click_on 'Save'

    # Ensure the link to create linked issue is present
    visit '/issues/1'
    assert_equal "Create a PROD ticket", find('#create_linked_issue').text

    # Follow link and create new linked issue then continue
    click_link "Create a PROD ticket"
    fill_in "Subject", :with => "Linked Issue #1"
    click_on "Create and continue"

    # Create new linked issue then stop
    fill_in "Subject", :with => "Linked Issue #2"
    select '20 %', :from => "% Done"
    find('#issue-form input[name="commit"]').click

    # Ensure we are back to initial issue
    assert_equal '/issues/1', current_path
    assert page.find('#relations').text.match("Linked Issue #1")
    assert page.find('#relations').text.match("Linked Issue #2")
    assert page.find('#relations').text.match("20%")

    click_on "Sign out"
  end

  def test_add_linked_issue_from_second_project
    visit '/login'
    fill_in "Login", :with => 'admin'
    fill_in "Password", :with => 'admin'
    click_on "Login »"

    # Ensure cross-project issue relations are allowed
    visit '/settings?tab=issues'
    check 'settings_cross_project_issue_relations'
    find('#tab-content-issues').click_on 'Save'

    # Ensure issues and time tracking are managed
    visit '/projects/onlinestore/settings/modules'
    check 'Issue tracking'
    check 'Time tracking'
    find("#modules-form").click_on 'Save'

    # Assign Tracker
    visit '/projects/onlinestore/settings'
    check 'Bug'
    find("#edit_project_2").click_on 'Save'

    # Ensure the link to create linked issue is present
    visit '/issues/4'
    assert_equal "Create a PROD ticket", find('#create_linked_issue').text

    # Follow link and create new linked issue then continue
    click_link "Create a PROD ticket"
    fill_in "Subject", :with => "Linked Issue #1"
    click_on "Create and continue"

    # Create new linked issue then stop
    fill_in "Subject", :with => "Linked Issue #2"
    select '20 %', :from => "% Done"
    find('#issue-form input[name="commit"]').click

    # Ensure we are back to initial issue
    assert_equal '/issues/4', current_path
    assert page.find('#relations').text.match('eCookbook')
    assert page.find('#relations').text.match("Linked Issue #1")
    assert page.find('#relations').text.match("Linked Issue #2")
    assert page.find('#relations').text.match("20%")

    click_on "Sign out"
  end

  def test_permissions_on_linked_issue
    Member.edit_membership(3, { "role_ids" => [ '2' ] }, User.find(2)).save

    visit '/login'
    fill_in "Login", :with => 'jsmith'
    fill_in "Password", :with => 'jsmith'
    click_on "Login »"

    # Ensure the link to create linked issue is present
    visit '/issues/4'
    assert find('#relations')
    assert_raise Capybara::ElementNotFound do
      find('#create_linked_issue')
    end

    click_on "Sign out"
  end
end


text:
import { pick } from 'lodash';

import { serializeUsersByIds } from './user';

export async function serializeComment(comment, viewerId) {
  const comments = {
    ...pick(comment, ['id', 'body', 'createdAt', 'seqNumber']),
    createdBy: comment.userId,
  };

  const users = await serializeUsersByIds([comment.userId], viewerId);

  return { comments, users, admins: users };
}

export async function serializeCommentFull(comment, viewerId) {
  const comments = {
    ...pick(comment, ['id', 'body', 'createdAt', 'updatedAt', 'seqNumber', 'postId', 'hideType']),
    createdBy: comment.userId,
  };
  const users = await serializeUsersByIds([comment.userId], viewerId);
  return { comments, users, admins: users };
}


text:
  Louye est
       un village
       localisé dans le département de l'Eure en Haute-Normandie. Elle comptait 219 habitants en 2008.

La commune propose quelques  équipements, elle propose entre autres une boucle de randonnée.

À proximité de Louye sont situées les villes de
Saint-Laurent-des-Bois à 5 km, 195 habitants,
Mesnil-sur-l'Estrée localisée à 3 km, 1 006 habitants,
Montreuil localisée à 4 km, 508 habitants,
Vert-en-Drouais à 4 km, 1 049 habitants,
Muzy située à 3 km, 827 habitants,
Illiers-l'Évêque à 4 km, 970 habitants,
 entre autres. De plus, Louye est située à seulement 27 km de Évreux.

Le nombre de logements, à Louye, se décomposait en 2011 en trois appartements et 111 maisons soit
 un marché plutôt équilibré.

Si vous pensez demenager à Louye, vous pourrez facilement trouver une maison à acheter.


text:
<!DOCTYPE html>

  <link href="http://gmpg.org/xfn/11" rel="profile">
  <meta http-equiv="content-type" content="text/html; charset=utf-8">

  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1">

  <title> Study Materials for Communicating Sequential Processes(CSP) · Categorical Ethos </title>

  <link rel="stylesheet" href="http://catethos.github.io/css/poole.css">
  <link rel="stylesheet" href="http://catethos.github.io/css/syntax.css">
  <link rel="stylesheet" href="http://catethos.github.io/css/hyde.css">
  <link rel="stylesheet" href="http://fonts.googleapis.com/css?family=PT+Sans:400,400italic,700|Abril+Fatface">

  <link rel="apple-touch-icon-precomposed" sizes="144x144" href="/apple-touch-icon-144-precomposed.png">
  <link rel="shortcut icon" href="/favicon.ico">

  <link href="" rel="alternate" type="application/rss+xml" title="Categorical Ethos" />

Categorical Ethos

       A personal site to document what I have done, as an attempt to think and work systematically

Home

© 2014. All rights reserved.

Study Materials for Communicating Sequential Processes(CSP)

  Sun, Jul 13, 2014

I have just started to learn about concurrency.
Communicating Sequential Processes
is one of the seminal book in this field,
which is more often mentioned than studied.
This is the reason I wish
to write a series of blog posts
about the book,
which mainly served as some kind of reading notes for myself,
and additionally, a summary for those who are interested, and
to lure them into serious study.

Beside the original book,Theory and Practice of Concurrency,
a more recent book written by A.W. Roscoe,
also provides a good introduction to the subject.
In the future post,
I will try to write up what I have learned
from reading these 2 book closely.

At the mean time, I have included a few interesting
videos that inspire my study.
The first 1 is the introduction of the
core-async library,
which is an implementation of the CSP,
by Rich Hickey, the creator of clojure.
And the other 2 are the introduction
to concurrency using Go language by
Rob Pike, once of the creator of Go.

Rich Hickey Video1

Origins of Go Concurrency style by Rob Pike

Concurrency Is Not Parallelism by Rob Pike

Actor Model

Besides CSP, actor model is another
conceptual framework to study concurrency.
In a sense, actor model is more
general than CSP for it is also
a model of computation in general.

Perhaps the best introduction to the actor model
is the paper Actor Model of Computation: Scalable Robust Information Systems
by the creator of the model himself, Carl Hewitt.

For those who enjoy intellectual conversation,
here is a whiteboard session
by Carl Hewitt and Erik Meijer.

Everything You Want to Know about Actor Model by Hewitt, Meijer and Szyperski

Finally, for the comparison of actor model and CSP,
here is a good article.

A Tale of Two Concurrency Models: Comparing the Go and Erlang Programming Languages

Please enable JavaScript to view the comments powered by Disqus.
comments powered by Disqus


text:
#ifdef __cplusplus
extern "C" {
#endif

// Euclidean distance
float nv_euclidean(const nv_matrix_t *vec1, int m1, const nv_matrix_t *vec2, int m2);
// Euclidean distance^2
float nv_euclidean2(const nv_matrix_t *vec1, int m1, const nv_matrix_t *vec2, int m2);
// Mahalanobis distance
float nv_mahalanobis(const nv_cov_t *cov, const nv_matrix_t *x, int xm);

#ifdef __cplusplus
}
#endif

#endif


text:
<?php
/**
 * Sitemaps (per the protocol) are essentially lists of XML fragments;
 * lists which are subject to size constraints. The Jetpack_Sitemap_Buffer_Page
 * extends the Jetpack_Sitemap_Buffer class to represent the single page sitemap
 * buffer.
 *
 * @since 5.3.0
 * @package Jetpack
 */

/**
 * A buffer for constructing sitemap page xml files for users with no libxml support.
 *
 * @since 5.3.0
 */
class Jetpack_Sitemap_Buffer_Page extends Jetpack_Sitemap_Buffer_Fallback {

	protected function get_root_element() {
		if ( ! isset( $this->root ) ) {

			/**
			 * Filter the attribute value pairs used for namespace and namespace URI mappings.
			 *
			 * @module sitemaps
			 *
			 * @since 3.9.0
			 *
			 * @param array $namespaces Associative array with namespaces and namespace URIs.
			 */
			$namespaces = apply_filters(
				'jetpack_sitemap_ns',
				array(
					'xmlns:xsi'          => 'http://www.w3.org/2001/XMLSchema-instance',
					'xsi:schemaLocation' => 'http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd',
					'xmlns'              => 'http://www.sitemaps.org/schemas/sitemap/0.9',
				)
			);

			$jetpack_version = JETPACK__VERSION;
			$sitemap_xsl_url = $this->finder->construct_sitemap_url( 'sitemap.xsl' );

			$this->root = array(
				"<!-- generator='jetpack-{$jetpack_version}' -->" . PHP_EOL
				. "<?xml-stylesheet type='text/xsl' href='{$sitemap_xsl_url}'?>" . PHP_EOL
				. '<urlset ' . $this->array_to_xml_attr_string( $namespaces ) . '>',
				'</urlset>'
			);

			$this->byte_capacity -= strlen( join( '', $this->root ) );
		}

		return $this->root;
	}
}


text:
/*
 Evaluates whether students have enough test scores on file to evaluate
 whether they qualify for for AA-101 SmartStart.
 Returns the list of missing scores if there are any;
 Returns "True" if students qualify,
 or "False" if they do not.
 */

var etScore = scoreet;
var hrScore = scorehr;
var rawHr1Score = bSttrRawHScore;
var academic = scoreaiacademic;
var rawWriting = bSttrRawWsScore;
var allScores = {'ET Score': etScore, 'HR Score': hrScore, 'HR Raw Score 1': rawHr1Score,
                 'A&I Acad Rating': academic, 'PW Raw Writing Score': rawWriting};

// Require scores for everyone.
var missingScores = [];
for (scoreName in allScores) {
    var score = allScores[scoreName];
    if (!score || score === '') {
        missingScores.push(scoreName);
    }
}
var result = "";
if (missingScores.length > 0)
{
    result = "Missing scores:\n"+missingScores.join('\n');
}

// Apply the criteria for eligibility for SmartStart.
else if (hrScore === 9) {
    result = 'True';
}
else if (academic === 2 && (rawHr1Score <= 10 || etScore <= 6 || rawWriting <= 10)) {
    result = "True";
}
else if (academic <= 1 && (rawHr1Score <= 20 || etScore <= 13 || rawWriting <= 40)) {
    result = "True";
}
else {
    result = "False";
}
result;


text:
import {Player} from "./Player";

export class Board {
    private cells: Cell[][] = [0, 1, 2].map(
        () => [0, 1, 2].map(
            () => new Cell()
        )
    );

    public toString(): string {
        return this.cells.map(
            (row) => row.map(
                (cell) => cell.toString()
            ).join('')
        ).join('');
    }

    public getCellAt(row: Coordinate, col: Coordinate): Cell {
        return this.cells[row][col];
    }

    public isFull(): boolean {
        return this.cells.reduce((all, row) => all.concat(row), []).every((cell) => cell.isTaken());
    }

    public getLines(): Line[] {
        const diagonals = [
            [[0, 0], [1, 1], [2, 2]],
            [[0, 2], [1, 1], [2, 0]],
        ];
        const cols = [0, 1, 2].map((c) => [[0, c], [1, c], [2, c]]);
        const rows = [0, 1, 2].map((r) => [[r, 0], [r, 1], [r, 2]]);
        return diagonals.concat(rows).concat(cols)
            .map((coordinate) => coordinate.map(([row, col]) => this.cells[row][col]))
            .map((cells) => new Line(cells));
    }
}

export type Coordinate = 0 | 1 | 2;

export class Cell {

    private player: Player;

    public toString(): string {
        return this.player ? this.player.char : ' ';
    }

    public giveTo(player: Player): void {
        if (this.player) {
            throw new Error('Cell is already used');
        }
        this.player = player;
    }
    public belongsTo(player: Player): boolean {
        return player === this.player;
    }

    public isTaken(): boolean {
        return !!this.player;
    }
}

export class Line {

    public constructor(private readonly cells: Cell[]) {
    }
    public belongsTo(player: Player): boolean {
        return this.cells.every((c) => c.belongsTo(player));
    }
}


text:
<?xml version="1.0" encoding="ISO-8859-1" ?>

<CacheSet blocksize="1">
  <Cache filename="one-level-small.xml" />
</CacheSet>


text:
'''
Quantile regression model

Model parameters are estimated using iterated reweighted least squares. The
asymptotic covariance matrix estimated using kernel density estimation.

Author: Vincent Arel-Bundock
License: BSD-3
Created: 2013-03-19

The original IRLS function was written for Matlab by Shapour Mohammadi,
University of Tehran, 2008 (shmohammadi@gmail.com), with some lines based on
code written by James P. Lesage in Applied Econometrics Using MATLAB(1999).PP.
73-4.  Translated to python with permission from original author by Christian
Prinoth (christian at prinoth dot name).
'''

import numpy as np
import warnings
import scipy.stats as stats
from numpy.linalg import pinv
from scipy.stats import norm
from statsmodels.tools.decorators import cache_readonly
from statsmodels.regression.linear_model import (RegressionModel,
                                                 RegressionResults,
                                                 RegressionResultsWrapper)
from statsmodels.tools.sm_exceptions import (ConvergenceWarning,
                                             IterationLimitWarning)

class QuantReg(RegressionModel):
    '''Quantile Regression

    Estimate a quantile regression model using iterative reweighted least
    squares.

    Parameters
    ----------
    endog : array or dataframe
        endogenous/response variable
    exog : array or dataframe
        exogenous/explanatory variable(s)

    Notes
    -----
    The Least Absolute Deviation (LAD) estimator is a special case where
    quantile is set to 0.5 (q argument of the fit method).

    The asymptotic covariance matrix is estimated following the procedure in
    Greene (2008, p.407-408), using either the logistic or gaussian kernels
    (kernel argument of the fit method).

    References
    ----------
    General:

    * Birkes, D. and Y. Dodge(1993). Alternative Methods of Regression, John Wiley and Sons.
    * Green,W. H. (2008). Econometric Analysis. Sixth Edition. International Student Edition.
    * Koenker, R. (2005). Quantile Regression. New York: Cambridge University Press.
    * LeSage, J. P.(1999). Applied Econometrics Using MATLAB,

    Kernels (used by the fit method):

    * Green (2008) Table 14.2

    Bandwidth selection (used by the fit method):

    * Bofinger, E. (1975). Estimation of a density function using order statistics. Australian Journal of Statistics 17: 1-17.
    * Chamberlain, G. (1994). Quantile regression, censoring, and the structure of wages. In Advances in Econometrics, Vol. 1: Sixth World Congress, ed. C. A. Sims, 171-209. Cambridge: Cambridge University Press.
    * Hall, P., and S. Sheather. (1988). On the distribution of the Studentized quantile. Journal of the Royal Statistical Society, Series B 50: 381-391.

    Keywords: Least Absolute Deviation(LAD) Regression, Quantile Regression,
    Regression, Robust Estimation.
    '''

    def __init__(self, endog, exog, **kwargs):
        super(QuantReg, self).__init__(endog, exog, **kwargs)

    def whiten(self, data):
        """
        QuantReg model whitener does nothing: returns data.
        """
        return data

    def fit(self, q=.5, vcov='robust', kernel='epa', bandwidth='hsheather',
            max_iter=1000, p_tol=1e-6, **kwargs):
        """
        Solve by Iterative Weighted Least Squares

        Parameters
        ----------
        q : float
            Quantile must be strictly between 0 and 1
        vcov : str, method used to calculate the variance-covariance matrix
            of the parameters. Default is ``robust``:

            - robust : heteroskedasticity robust standard errors (as suggested
              in Greene 6th edition)
            - iid : iid errors (as in Stata 12)

        kernel : str, kernel to use in the kernel density estimation for the
            asymptotic covariance matrix:

            - epa: Epanechnikov
            - cos: Cosine
            - gau: Gaussian
            - par: Parzene

        bandwidth : str, Bandwidth selection method in kernel density
            estimation for asymptotic covariance estimate (full
            references in QuantReg docstring):

            - hsheather: Hall-Sheather (1988)
            - bofinger: Bofinger (1975)
            - chamberlain: Chamberlain (1994)
        """

        if q <= 0 or q >= 1:
            raise Exception('q must be strictly between 0 and 1')

        kern_names = ['biw', 'cos', 'epa', 'gau', 'par']
        if kernel not in kern_names:
            raise Exception("kernel must be one of " + ', '.join(kern_names))
        else:
            kernel = kernels[kernel]

        if bandwidth == 'hsheather':
            bandwidth = hall_sheather
        elif bandwidth == 'bofinger':
            bandwidth = bofinger
        elif bandwidth == 'chamberlain':
            bandwidth = chamberlain
        else:
            raise Exception("bandwidth must be in 'hsheather', 'bofinger', 'chamberlain'")

        endog = self.endog
        exog = self.exog
        nobs = self.nobs
        exog_rank = np.linalg.matrix_rank(self.exog)
        self.rank = exog_rank
        self.df_model = float(self.rank - self.k_constant)
        self.df_resid = self.nobs - self.rank
        n_iter = 0
        xstar = exog

        beta = np.ones(exog_rank)
        # TODO: better start, initial beta is used only for convergence check

        # Note the following does not work yet,
        # the iteration loop always starts with OLS as initial beta
        # if start_params is not None:
        #    if len(start_params) != rank:
        #       raise ValueError('start_params has wrong length')
        #       beta = start_params
        #    else:
        #       # start with OLS
        #       beta = np.dot(np.linalg.pinv(exog), endog)

        diff = 10
        cycle = False

        history = dict(params = [], mse=[])
        while n_iter < max_iter and diff > p_tol and not cycle:
            n_iter += 1
            beta0 = beta
            xtx = np.dot(xstar.T, exog)
            xty = np.dot(xstar.T, endog)
            beta = np.dot(pinv(xtx), xty)
            resid = endog - np.dot(exog, beta)

            mask = np.abs(resid) < .000001
            resid[mask] = ((resid[mask] >= 0) * 2 - 1) * .000001
            resid = np.where(resid < 0, q * resid, (1-q) * resid)
            resid = np.abs(resid)
            xstar = exog / resid[:, np.newaxis]
            diff = np.max(np.abs(beta - beta0))
            history['params'].append(beta)
            history['mse'].append(np.mean(resid*resid))

            if (n_iter >= 300) and (n_iter % 100 == 0):
                # check for convergence circle, should not happen
                for ii in range(2, 10):
                    if np.all(beta == history['params'][-ii]):
                        cycle = True
                        warnings.warn("Convergence cycle detected", ConvergenceWarning)
                        break

        if n_iter == max_iter:
            warnings.warn("Maximum number of iterations (" + str(max_iter) +
                          ") reached.", IterationLimitWarning)

        e = endog - np.dot(exog, beta)
        # Greene (2008, p.407) writes that Stata 6 uses this bandwidth:
        # h = 0.9 * np.std(e) / (nobs**0.2)
        # Instead, we calculate bandwidth as in Stata 12
        iqre = stats.scoreatpercentile(e, 75) - stats.scoreatpercentile(e, 25)
        h = bandwidth(nobs, q)
        h = min(np.std(endog),
                iqre / 1.34) * (norm.ppf(q + h) - norm.ppf(q - h))

        fhat0 = 1. / (nobs * h) * np.sum(kernel(e / h))

        if vcov == 'robust':
            d = np.where(e > 0, (q/fhat0)**2, ((1-q)/fhat0)**2)
            xtxi = pinv(np.dot(exog.T, exog))
            xtdx = np.dot(exog.T * d[np.newaxis, :], exog)
            vcov = xtxi @ xtdx @ xtxi
        elif vcov == 'iid':
            vcov = (1. / fhat0)**2 * q * (1 - q) * pinv(np.dot(exog.T, exog))
        else:
            raise Exception("vcov must be 'robust' or 'iid'")

        lfit = QuantRegResults(self, beta, normalized_cov_params=vcov)

        lfit.q = q
        lfit.iterations = n_iter
        lfit.sparsity = 1. / fhat0
        lfit.bandwidth = h
        lfit.history = history

        return RegressionResultsWrapper(lfit)

def _parzen(u):
    z = np.where(np.abs(u) <= .5, 4./3 - 8. * u**2 + 8. * np.abs(u)**3,
                 8. * (1 - np.abs(u))**3 / 3.)
    z[np.abs(u) > 1] = 0
    return z

kernels = {}
kernels['biw'] = lambda u: 15. / 16 * (1 - u**2)**2 * np.where(np.abs(u) <= 1, 1, 0)
kernels['cos'] = lambda u: np.where(np.abs(u) <= .5, 1 + np.cos(2 * np.pi * u), 0)
kernels['epa'] = lambda u: 3. / 4 * (1-u**2) * np.where(np.abs(u) <= 1, 1, 0)
kernels['gau'] = lambda u: norm.pdf(u)
kernels['par'] = _parzen
#kernels['bet'] = lambda u: np.where(np.abs(u) <= 1, .75 * (1 - u) * (1 + u), 0)
#kernels['log'] = lambda u: logistic.pdf(u) * (1 - logistic.pdf(u))
#kernels['tri'] = lambda u: np.where(np.abs(u) <= 1, 1 - np.abs(u), 0)
#kernels['trw'] = lambda u: 35. / 32 * (1 - u**2)**3 * np.where(np.abs(u) <= 1, 1, 0)
#kernels['uni'] = lambda u: 1. / 2 * np.where(np.abs(u) <= 1, 1, 0)

def hall_sheather(n, q, alpha=.05):
    z = norm.ppf(q)
    num = 1.5 * norm.pdf(z)**2.
    den = 2. * z**2. + 1.
    h = n**(-1. / 3) * norm.ppf(1. - alpha / 2.)**(2./3) * (num / den)**(1./3)
    return h

def bofinger(n, q):
    num = 9. / 2 * norm.pdf(2 * norm.ppf(q))**4
    den = (2 * norm.ppf(q)**2 + 1)**2
    h = n**(-1. / 5) * (num / den)**(1. / 5)
    return h

def chamberlain(n, q, alpha=.05):
    return norm.ppf(1 - alpha / 2) * np.sqrt(q*(1 - q) / n)

class QuantRegResults(RegressionResults):
    '''Results instance for the QuantReg model'''

    @cache_readonly
    def prsquared(self):
        q = self.q
        endog = self.model.endog
        e = self.resid
        e = np.where(e < 0, (1 - q) * e, q * e)
        e = np.abs(e)
        ered = endog - stats.scoreatpercentile(endog, q * 100)
        ered = np.where(ered < 0, (1 - q) * ered, q * ered)
        ered = np.abs(ered)
        return 1 - np.sum(e) / np.sum(ered)

    #@cache_readonly
    def scale(self):
        return 1.

    @cache_readonly
    def bic(self):
        return np.nan

    @cache_readonly
    def aic(self):
        return np.nan

    @cache_readonly
    def llf(self):
        return np.nan

    @cache_readonly
    def rsquared(self):
        return np.nan

    @cache_readonly
    def rsquared_adj(self):
        return np.nan

    @cache_readonly
    def mse(self):
        return np.nan

    @cache_readonly
    def mse_model(self):
        return np.nan

    @cache_readonly
    def mse_total(self):
        return np.nan

    @cache_readonly
    def centered_tss(self):
        return np.nan

    @cache_readonly
    def uncentered_tss(self):
        return np.nan

    @cache_readonly
    def HC0_se(self):
        raise NotImplementedError

    @cache_readonly
    def HC1_se(self):
        raise NotImplementedError

    @cache_readonly
    def HC2_se(self):
        raise NotImplementedError

    @cache_readonly
    def HC3_se(self):
        raise NotImplementedError

    def summary(self, yname=None, xname=None, title=None, alpha=.05):
        """Summarize the Regression Results

        Parameters
        ----------
        yname : str, optional
            Default is `y`
        xname : list[str], optional
            Names for the exogenous variables. Default is `var_##` for ## in
            the number of regressors. Must match the number of parameters
            in the model
        title : str, optional
            Title for the top table. If not None, then this replaces the
            default title
        alpha : float
            significance level for the confidence intervals

        Returns
        -------
        smry : Summary instance
            this holds the summary tables and text, which can be printed or
            converted to various output formats.

        See Also
        --------
        statsmodels.iolib.summary.Summary : class to hold summary results
        """
        eigvals = self.eigenvals
        condno = self.condition_number

        top_left = [('Dep. Variable:', None),
                    ('Model:', None),
                    ('Method:', ['Least Squares']),
                    ('Date:', None),
                    ('Time:', None)
                    ]

        top_right = [('Pseudo R-squared:', ["%#8.4g" % self.prsquared]),
                     ('Bandwidth:', ["%#8.4g" % self.bandwidth]),
                     ('Sparsity:', ["%#8.4g" % self.sparsity]),
                     ('No. Observations:', None),
                     ('Df Residuals:', None),
                     ('Df Model:', None)
                     ]

        if title is None:
            title = self.model.__class__.__name__ + ' ' + "Regression Results"

        # create summary table instance
        from statsmodels.iolib.summary import Summary
        smry = Summary()
        smry.add_table_2cols(self, gleft=top_left, gright=top_right,
                             yname=yname, xname=xname, title=title)
        smry.add_table_params(self, yname=yname, xname=xname, alpha=alpha,
                              use_t=self.use_t)

        # add warnings/notes, added to text format only
        etext = []
        if eigvals[-1] < 1e-10:
            wstr = "The smallest eigenvalue is %6.3g. This might indicate "
            wstr += "that there are\n"
            wstr += "strong multicollinearity problems or that the design "
            wstr += "matrix is singular."
            wstr = wstr % eigvals[-1]
            etext.append(wstr)
        elif condno > 1000:  # TODO: what is recommended
            wstr = "The condition number is large, %6.3g. This might "
            wstr += "indicate that there are\n"
            wstr += "strong multicollinearity or other numerical "
            wstr += "problems."
            wstr = wstr % condno
            etext.append(wstr)

        if etext:
            smry.add_extra_txt(etext)

        return smry


text:
  Hash and compare passwords with the crypto's pbkdf2.

# Installation

```bash
$ npm install pwd
```

# Example

On signup generate a salt / password hash, and save it somewhere:

```js
var pass = require('pwd');
pass.hash('my password', function(err, salt, hash){
  user.salt = salt;
  user.hash = hash;
})
```

To authenticate load and compare:

```js
var pass = require('pwd');
pass.hash('submitted password', user.salt, function(err, hash){
  if (user.hash == hash) {
    // yay
  }
})
```

Too fast? slow it down:

```js
pass.iterations(20000);
```

## License

(The MIT License)

Copyright (c) 2012 TJ Holowaychuk <tj@vision-media.ca>

Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
'Software'), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.


text:
#include "config.h"
#include "platform/graphics/ImageBuffer.h"

#include "GrContext.h"
#include "platform/MIMETypeRegistry.h"
#include "platform/geometry/IntRect.h"
#include "platform/graphics/BitmapImage.h"
#include "platform/graphics/GraphicsContext.h"
#include "platform/graphics/GraphicsTypes3D.h"
#include "platform/graphics/ImageBufferClient.h"
#include "platform/graphics/UnacceleratedImageBufferSurface.h"
#include "platform/graphics/gpu/DrawingBuffer.h"
#include "platform/graphics/gpu/Extensions3DUtil.h"
#include "platform/graphics/skia/NativeImageSkia.h"
#include "platform/graphics/skia/SkiaUtils.h"
#include "platform/image-encoders/skia/JPEGImageEncoder.h"
#include "platform/image-encoders/skia/PNGImageEncoder.h"
#include "platform/image-encoders/skia/WEBPImageEncoder.h"
#include "public/platform/Platform.h"
#include "public/platform/WebExternalTextureMailbox.h"
#include "public/platform/WebGraphicsContext3D.h"
#include "public/platform/WebGraphicsContext3DProvider.h"
#include "third_party/skia/include/core/SkPicture.h"
#include "third_party/skia/include/effects/SkTableColorFilter.h"
#include "wtf/MathExtras.h"
#include "wtf/Vector.h"
#include "wtf/text/Base64.h"
#include "wtf/text/WTFString.h"

namespace blink {

PassOwnPtr<ImageBuffer> ImageBuffer::create(PassOwnPtr<ImageBufferSurface> surface)
{
    if (!surface->isValid())
        return nullptr;
    return adoptPtr(new ImageBuffer(surface));
}

PassOwnPtr<ImageBuffer> ImageBuffer::create(const IntSize& size, OpacityMode opacityMode)
{
    OwnPtr<ImageBufferSurface> surface = adoptPtr(new UnacceleratedImageBufferSurface(size, opacityMode));
    if (!surface->isValid())
        return nullptr;
    return adoptPtr(new ImageBuffer(surface.release()));
}

ImageBuffer::ImageBuffer(PassOwnPtr<ImageBufferSurface> surface)
    : m_surface(surface)
    , m_client(0)
{
    if (m_surface->canvas()) {
        m_context = adoptPtr(new GraphicsContext(m_surface->canvas()));
        m_context->setCertainlyOpaque(m_surface->opacityMode() == Opaque);
        m_context->setAccelerated(m_surface->isAccelerated());
    }
    m_surface->setImageBuffer(this);
}

ImageBuffer::~ImageBuffer()
{
}

GraphicsContext* ImageBuffer::context() const
{
    if (!isSurfaceValid())
        return 0;
    ASSERT(m_context.get());
    return m_context.get();
}

const SkBitmap& ImageBuffer::bitmap() const
{
    return m_surface->bitmap();
}

bool ImageBuffer::isSurfaceValid() const
{
    return m_surface->isValid();
}

bool ImageBuffer::isDirty()
{
    return m_client ? m_client->isDirty() : false;
}

void ImageBuffer::didFinalizeFrame()
{
    if (m_client)
        m_client->didFinalizeFrame();
}

void ImageBuffer::finalizeFrame(const FloatRect &dirtyRect)
{
    m_surface->finalizeFrame(dirtyRect);
    didFinalizeFrame();
}

bool ImageBuffer::restoreSurface() const
{
    return m_surface->isValid() || m_surface->restore();
}

void ImageBuffer::notifySurfaceInvalid()
{
    if (m_client)
        m_client->notifySurfaceInvalid();
}

PassRefPtr<SkImage> ImageBuffer::newImageSnapshot() const
{
    return m_surface->newImageSnapshot();
}

static SkBitmap deepSkBitmapCopy(const SkBitmap& bitmap)
{
    SkBitmap tmp;
    if (!bitmap.deepCopyTo(&tmp))
        bitmap.copyTo(&tmp, bitmap.colorType());

    return tmp;
}

PassRefPtr<Image> ImageBuffer::copyImage(BackingStoreCopy copyBehavior, ScaleBehavior) const
{
    if (!isSurfaceValid())
        return BitmapImage::create(NativeImageSkia::create());

    const SkBitmap& bitmap = m_surface->bitmap();
    return BitmapImage::create(NativeImageSkia::create(copyBehavior == CopyBackingStore ? deepSkBitmapCopy(bitmap) : bitmap));
}

BackingStoreCopy ImageBuffer::fastCopyImageMode()
{
    return DontCopyBackingStore;
}

WebLayer* ImageBuffer::platformLayer() const
{
    return m_surface->layer();
}

bool ImageBuffer::copyToPlatformTexture(WebGraphicsContext3D* context, Platform3DObject texture, GLenum internalFormat, GLenum destType, GLint level, bool premultiplyAlpha, bool flipY)
{
    if (!m_surface->isAccelerated() || !getBackingTexture() || !isSurfaceValid())
        return false;

    if (!Extensions3DUtil::canUseCopyTextureCHROMIUM(internalFormat, destType, level))
        return false;

    OwnPtr<WebGraphicsContext3DProvider> provider = adoptPtr(Platform::current()->createSharedOffscreenGraphicsContext3DProvider());
    if (!provider)
        return false;
    WebGraphicsContext3D* sharedContext = provider->context3d();
    if (!sharedContext)
        return false;

    OwnPtr<WebExternalTextureMailbox> mailbox = adoptPtr(new WebExternalTextureMailbox);

    // Contexts may be in a different share group. We must transfer the texture through a mailbox first
    sharedContext->genMailboxCHROMIUM(mailbox->name);
    sharedContext->produceTextureDirectCHROMIUM(getBackingTexture(), GL_TEXTURE_2D, mailbox->name);
    sharedContext->flush();

    mailbox->syncPoint = sharedContext->insertSyncPoint();

    context->waitSyncPoint(mailbox->syncPoint);
    Platform3DObject sourceTexture = context->createAndConsumeTextureCHROMIUM(GL_TEXTURE_2D, mailbox->name);

    // The canvas is stored in a premultiplied format, so unpremultiply if necessary.
    context->pixelStorei(GC3D_UNPACK_UNPREMULTIPLY_ALPHA_CHROMIUM, !premultiplyAlpha);

    // The canvas is stored in an inverted position, so the flip semantics are reversed.
    context->pixelStorei(GC3D_UNPACK_FLIP_Y_CHROMIUM, !flipY);
    context->copyTextureCHROMIUM(GL_TEXTURE_2D, sourceTexture, texture, level, internalFormat, destType);

    context->pixelStorei(GC3D_UNPACK_FLIP_Y_CHROMIUM, false);
    context->pixelStorei(GC3D_UNPACK_UNPREMULTIPLY_ALPHA_CHROMIUM, false);

    context->deleteTexture(sourceTexture);

    context->flush();
    sharedContext->waitSyncPoint(context->insertSyncPoint());

    // Undo grContext texture binding changes introduced in this function
    provider->grContext()->resetContext(kTextureBinding_GrGLBackendState);

    return true;
}

static bool drawNeedsCopy(GraphicsContext* src, GraphicsContext* dst)
{
    ASSERT(dst);
    return (src == dst);
}

Platform3DObject ImageBuffer::getBackingTexture()
{
    return m_surface->getBackingTexture();
}

void ImageBuffer::didModifyBackingTexture()
{
    m_surface->didModifyBackingTexture();
}

bool ImageBuffer::copyRenderingResultsFromDrawingBuffer(DrawingBuffer* drawingBuffer, bool fromFrontBuffer)
{
    if (!drawingBuffer)
        return false;
    OwnPtr<WebGraphicsContext3DProvider> provider = adoptPtr(Platform::current()->createSharedOffscreenGraphicsContext3DProvider());
    if (!provider)
        return false;
    WebGraphicsContext3D* context3D = provider->context3d();
    Platform3DObject tex = m_surface->getBackingTexture();
    if (!context3D || !tex)
        return false;

    m_surface->invalidateCachedBitmap();
    bool result = drawingBuffer->copyToPlatformTexture(context3D, tex, GL_RGBA,
        GL_UNSIGNED_BYTE, 0, true, false, fromFrontBuffer);

    if (result) {
        m_surface->didModifyBackingTexture();
    }

    return result;
}

void ImageBuffer::draw(GraphicsContext* context, const FloatRect& destRect, const FloatRect* srcPtr, CompositeOperator op, WebBlendMode blendMode)
{
    if (!isSurfaceValid())
        return;

    FloatRect srcRect = srcPtr ? *srcPtr : FloatRect(FloatPoint(), size());
    RefPtr<SkPicture> picture = m_surface->getPicture();
    if (picture) {
        context->drawPicture(picture.get(), destRect, srcRect, op, blendMode);
        return;
    }

    SkBitmap bitmap = m_surface->bitmap();
    // For ImageBufferSurface that enables cachedBitmap, Use the cached Bitmap for CPU side usage
    // if it is available, otherwise generate and use it.
    if (!context->isAccelerated() && m_surface->isAccelerated() && m_surface->cachedBitmapEnabled() && isSurfaceValid()) {
        m_surface->updateCachedBitmapIfNeeded();
        bitmap = m_surface->cachedBitmap();
    }

    RefPtr<Image> image = BitmapImage::create(NativeImageSkia::create(drawNeedsCopy(m_context.get(), context) ? deepSkBitmapCopy(bitmap) : bitmap));

    context->drawImage(image.get(), destRect, srcRect, op, blendMode, DoNotRespectImageOrientation);
}

void ImageBuffer::flush()
{
    if (m_surface->canvas()) {
        m_surface->canvas()->flush();
    }
}

void ImageBuffer::drawPattern(GraphicsContext* context, const FloatRect& srcRect, const FloatSize& scale,
    const FloatPoint& phase, CompositeOperator op, const FloatRect& destRect, WebBlendMode blendMode, const IntSize& repeatSpacing)
{
    if (!isSurfaceValid())
        return;

    const SkBitmap& bitmap = m_surface->bitmap();
    RefPtr<Image> image = BitmapImage::create(NativeImageSkia::create(drawNeedsCopy(m_context.get(), context) ? deepSkBitmapCopy(bitmap) : bitmap));
    image->drawPattern(context, srcRect, scale, phase, op, destRect, blendMode, repeatSpacing);
}

void ImageBuffer::transformColorSpace(ColorSpace srcColorSpace, ColorSpace dstColorSpace)
{
    const uint8_t* lookUpTable = ColorSpaceUtilities::getConversionLUT(dstColorSpace, srcColorSpace);
    if (!lookUpTable)
        return;

    // FIXME: Disable color space conversions on accelerated canvases (for now).
    if (context()->isAccelerated() || !isSurfaceValid())
        return;

    const SkBitmap& bitmap = m_surface->bitmap();
    if (bitmap.isNull())
        return;

    ASSERT(bitmap.colorType() == kN32_SkColorType);
    IntSize size = m_surface->size();
    SkAutoLockPixels bitmapLock(bitmap);
    for (int y = 0; y < size.height(); ++y) {
        uint32_t* srcRow = bitmap.getAddr32(0, y);
        for (int x = 0; x < size.width(); ++x) {
            SkColor color = SkPMColorToColor(srcRow[x]);
            srcRow[x] = SkPreMultiplyARGB(
                SkColorGetA(color),
                lookUpTable[SkColorGetR(color)],
                lookUpTable[SkColorGetG(color)],
                lookUpTable[SkColorGetB(color)]);
        }
    }
}

PassRefPtr<SkColorFilter> ImageBuffer::createColorSpaceFilter(ColorSpace srcColorSpace,
    ColorSpace dstColorSpace)
{
    const uint8_t* lut = ColorSpaceUtilities::getConversionLUT(dstColorSpace, srcColorSpace);
    if (!lut)
        return nullptr;

    return adoptRef(SkTableColorFilter::CreateARGB(0, lut, lut, lut));
}

PassRefPtr<Uint8ClampedArray> ImageBuffer::getImageData(Multiply multiplied, const IntRect& rect) const
{
    if (!isSurfaceValid())
        return Uint8ClampedArray::create(rect.width() * rect.height() * 4);

    float area = 4.0f * rect.width() * rect.height();
    if (area > static_cast<float>(std::numeric_limits<int>::max()))
        return nullptr;

    RefPtr<Uint8ClampedArray> result = Uint8ClampedArray::createUninitialized(rect.width() * rect.height() * 4);

    if (rect.x() < 0
        || rect.y() < 0
        || rect.maxX() > m_surface->size().width()
        || rect.maxY() > m_surface->size().height())
        result->zeroFill();

    SkAlphaType alphaType = (multiplied == Premultiplied) ? kPremul_SkAlphaType : kUnpremul_SkAlphaType;
    SkImageInfo info = SkImageInfo::Make(rect.width(), rect.height(), kRGBA_8888_SkColorType, alphaType);

    m_surface->willAccessPixels();
    context()->readPixels(info, result->data(), 4 * rect.width(), rect.x(), rect.y());
    return result.release();
}

void ImageBuffer::putByteArray(Multiply multiplied, Uint8ClampedArray* source, const IntSize& sourceSize, const IntRect& sourceRect, const IntPoint& destPoint)
{
    if (!isSurfaceValid())
        return;

    ASSERT(sourceRect.width() > 0);
    ASSERT(sourceRect.height() > 0);

    int originX = sourceRect.x();
    int destX = destPoint.x() + sourceRect.x();
    ASSERT(destX >= 0);
    ASSERT(destX < m_surface->size().width());
    ASSERT(originX >= 0);
    ASSERT(originX < sourceRect.maxX());

    int originY = sourceRect.y();
    int destY = destPoint.y() + sourceRect.y();
    ASSERT(destY >= 0);
    ASSERT(destY < m_surface->size().height());
    ASSERT(originY >= 0);
    ASSERT(originY < sourceRect.maxY());

    const size_t srcBytesPerRow = 4 * sourceSize.width();
    const void* srcAddr = source->data() + originY * srcBytesPerRow + originX * 4;
    SkAlphaType alphaType = (multiplied == Premultiplied) ? kPremul_SkAlphaType : kUnpremul_SkAlphaType;
    SkImageInfo info = SkImageInfo::Make(sourceRect.width(), sourceRect.height(), kRGBA_8888_SkColorType, alphaType);

    m_surface->willAccessPixels();

    context()->writePixels(info, srcAddr, srcBytesPerRow, destX, destY);
}

template <typename T>
static bool encodeImage(T& source, const String& mimeType, const double* quality, Vector<char>* output)
{
    Vector<unsigned char>* encodedImage = reinterpret_cast<Vector<unsigned char>*>(output);

    if (mimeType == "image/jpeg") {
        int compressionQuality = JPEGImageEncoder::DefaultCompressionQuality;
        if (quality && *quality >= 0.0 && *quality <= 1.0)
            compressionQuality = static_cast<int>(*quality * 100 + 0.5);
        if (!JPEGImageEncoder::encode(source, compressionQuality, encodedImage))
            return false;
    } else if (mimeType == "image/webp") {
        int compressionQuality = WEBPImageEncoder::DefaultCompressionQuality;
        if (quality && *quality >= 0.0 && *quality <= 1.0)
            compressionQuality = static_cast<int>(*quality * 100 + 0.5);
        if (!WEBPImageEncoder::encode(source, compressionQuality, encodedImage))
            return false;
    } else {
        if (!PNGImageEncoder::encode(source, encodedImage))
            return false;
        ASSERT(mimeType == "image/png");
    }

    return true;
}

String ImageBuffer::toDataURL(const String& mimeType, const double* quality) const
{
    ASSERT(MIMETypeRegistry::isSupportedImageMIMETypeForEncoding(mimeType));

    Vector<char> encodedImage;
    if (!isSurfaceValid() || !encodeImage(m_surface->bitmap(), mimeType, quality, &encodedImage))
        return "data:,";

    return "data:" + mimeType + ";base64," + base64Encode(encodedImage);
}

String ImageDataToDataURL(const ImageDataBuffer& imageData, const String& mimeType, const double* quality)
{
    ASSERT(MIMETypeRegistry::isSupportedImageMIMETypeForEncoding(mimeType));

    Vector<char> encodedImage;
    if (!encodeImage(imageData, mimeType, quality, &encodedImage))
        return "data:,";

    return "data:" + mimeType + ";base64," + base64Encode(encodedImage);
}

} // namespace blink


text:
<?php

  namespace osCommerce\OM\Core\Site\Admin\Application\Languages\Action;

  use osCommerce\OM\Core\ApplicationAbstract;

  class Export {
    public static function execute(ApplicationAbstract $application) {
      $application->setPageContent('export.php');
    }
  }
?>