text:
"""Wire Protocol frontend server to Mongo Orchestration."""

from __future__ import print_function
import argparse

import os
import sys
from io import BytesIO

try:
    # Need simplejson for the object_pairs_hook option in Python 2.6.
    import simplejson as json
except ImportError:
    # Python 2.7+.
    import json

import bottle
import mockupdb
import mongo_orchestration.server
from bson import json_util, SON
from mockupdb import Command

from conduction import __version__

DEFAULT_BIND = os.environ.get('CONDUCTION_HOST', '127.0.0.1')
DEFAULT_PORT = int(os.environ.get('CONDUCTION_PORT', '27017'))

bottle_app = mongo_orchestration.server.get_app()

def parse_args():
    """Return command-line arguments."""
    description = """
Mongo Conduction server.

A wire protocol frontend to Mongo Orchestration, creates and manages MongoDB
configurations on a single host.

THIS PROJECT IS FOR TESTING MONGODB DRIVERS.

http://mongo-conduction.readthedocs.org
"""
    parser = argparse.ArgumentParser(description=description)
    parser.add_argument('-f', '--config',
                        action='store', default=None, type=str, dest='config')
    parser.add_argument('-e', '--env',
                        action='store', type=str, dest='env', default=None)
    parser.add_argument('-b', '--bind',
                        action='store', dest='bind', type=str,
                        default=DEFAULT_BIND)
    parser.add_argument('-p', '--port',
                        action='store', dest='port', type=int,
                        default=DEFAULT_PORT)
    parser.add_argument('-v', '--verbose', dest='verbose',
                        action='store_true', default=False)
    parser.add_argument('--version', action='version',
                        version='Mongo Conduction v' + __version__)

    cli_args = parser.parse_args()

    if cli_args.env and not cli_args.config:
        print("Specified release '%s' without a config file" % cli_args.env)
        sys.exit(1)
    if not cli_args.config:
        return cli_args
    try:
        # Read config.
        with open(cli_args.config, 'r') as fd:
            config = json.loads(fd.read(), object_pairs_hook=SON)
        if 'releases' not in config:
            print("No releases defined in %s" % cli_args.config)
            sys.exit(1)
        releases = config['releases']
        if cli_args.env is not None and cli_args.env not in releases:
            print("Release '%s' is not defined in %s"
                  % (cli_args.env, cli_args.config))
            sys.exit(1)
        cli_args.releases = releases
        return cli_args
    except IOError:
        print("config file not found: %s" % cli_args.config)
        sys.exit(1)

def reply(method, path):
    """Execute request handler and return some JSON."""
    route, args = bottle_app.match({
        'REQUEST_METHOD': method,
        'PATH_INFO': path})

    json_str = route(**args)
    return json.loads(json_str or '{}')

METHODS = set(['get', 'post', 'put', 'delete'])

def main_loop(mockup):
    """Take a running MockupDB server and respond to commands.

    The loop runs forever. Exit with mockup.stop() from another thread.
    """
    assert mockup.port, "Call run() on the MockupDB first"
    for req in mockup:
        if req.matches(Command) and req.command_name.lower() in METHODS:
            try:
                # Request is like: {get: "/servers"}
                # Or: {post: "/servers", body: {preset: "basic.json"}}
                method = req.command_name.lower()
                path = req.doc[req.command_name]
                body = req.doc.get('body', {})

                # Trick Bottle into thinking the wire protocol command's
                # "body" subdocument is a JSON string that is the HTTP
                # POST body.
                body_json_sio = BytesIO(json_util.dumps(body).encode('ascii'))
                environ = {
                    'REQUEST_METHOD': method.upper(),
                    'PATH_INFO': path,
                    'wsgi.input': body_json_sio,
                    'bottle.request.body': body_json_sio
                }
                result = bottle_app._handle(environ)
                if isinstance(result, Exception):
                    raise result
                reply_doc = json.loads(result or '{}')

                if isinstance(reply_doc, list):
                    # Traceback.
                    req.command_err(errmsg='Conduction error',
                                    traceback=reply_doc)
                else:
                    req.ok(reply_doc)
            except bottle.HTTPError as error:
                req.command_err(errmsg=error.status_line)
            except Exception as error:
                req.command_err(errmsg=repr(error))
        else:
            req.command_err(errmsg='unrecognized: %s' % req)

def get_mockup(releases, env, port, verbose):
    mongo_orchestration.server.setup(releases, env)
    mockup = mockupdb.interactive_server(port=port, verbose=verbose,
                                         all_ok=False, name='Conduction')

    # Override the existing buildinfo responder.
    mockup.autoresponds('buildinfo', version='Conduction ' + __version__)
    return mockup

def main():
    args = parse_args()
    mockup = get_mockup(getattr(args, 'releases', {}),
                        args.env,
                        args.port,
                        args.verbose)
    mockup.run()
    print('listening on %s' % mockup.uri)
    try:
        main_loop(mockup)
    except KeyboardInterrupt:
        sys.exit()
    finally:
        print('\nstopping')
        mockup.stop()

if __name__ == '__main__':
    main()


text:
#ifndef __TBA_XSTL_DATA_MESSAGEQUEUE_H
#define __TBA_XSTL_DATA_MESSAGEQUEUE_H

/*
 * messageQueue.h
 *
 * The messageQueue is a component which holds messages for clients.
 * Each client has a unique ID in the system and has messages which link to
 * it. The queue manages the storing and polling of messages.
 *
 * Author: Elad Raz <e@eladraz.com>
 */
#include "xStl/types.h"

/*
 * Holds messages for clients. The program can access the queue, store messages
 * for one or more clients, poll the messages etc.
 * The queue has the following properties:
 *   - Template over the client-ID.
 *   - Template over group-ID
 *   - Saves the queue inside the repository. Can be used for presistance.
 *   - Stores a message for one or more clients.
 *   - Poll a message for a client.
 *   - Set a queue quota for a client (In memory bytes)
 *   - A watch-dog timmer allowing.
 *
 * The messages are stream of bytes.
 *
 * The client-id, which is templated in the name cClientID is a unique identifier
 * for the client. The template must implement the following operator:
 *   bool operator == (const cClientID& other) const;
 *   copy-constructor
 * This operator is in used in order to distinguish different clients.
 *
 * The client-id can be a number coressponding to the user, can be a process-ID
 * which seperates difference process which want to poll message from a shared
 * device. It can be even more complex struct which contain process-ID and a
 * client-ID for allowing multiple instance of device-objects inside a single
 * process...
 *
 * The group-ID has the following operator:
 *   bool isMine(const cClientID& id);
 * This function is in used to seprated clients to
 */
template <cClientID, cGroupID>
class cMessageQueue
{
public:
    /*
     * Constructor. Initialize empty queue.
     */
    cMessageQueue();

    /*
     * Destructor. Free all messages and queue memory.
     */
    ~cMessageQueue();

    /*
     * Stores a message for list of clients.
     *
     * clients - The clients ID list.
     * message - The message to be stored.
     *
     * Throws cMessageQueueException:
     *    ClientNotFound - One or more of the clients is not exist. The other
     *                     clients will contain the message in the queue.
     *    ClientQutaLimit - One or more of the clients has a quta-limit. Other
     *                      clients will contain the message in the queue.
     */
    void storeMessage(const cList<cClientID>& clientsID,
                      cBufferPtr message);

    /*
     * Polls a message for a client.
     *
     * clientID - The client ID
     *
     * Return a stream reference count for the message.
     *
     * Throws cMessageQueueException:
     *    ClientNotFound - The client cannot be found, or it's queue is empty.
     */
    cBufferPtr pollMessage(const cClientID& clientID);

    /*
     * Poll a message for a group.
     *
     * groupID - The group ID
     * clientID - Will be filled with the polled client identification
     *
     * Return a stream reference count for the message.
     */
    cBufferPtr pollMessage(const cGroupID& groupID,
                           cClientID* clientID);

private:
};

/*
 * MessageQueue which the group are irrelevant, use the cNullGroup as the
 * second argument for the cMessageQueue template argument.
 * The cNullGroup doesn't contains any clients.
 */
template <cClientID>
class cNullGroup
{
public:
    bool isMine(const cClientID& other)
    {
        return false;
    }
};

#endif // __TBA_XSTL_DATA_MESSAGEQUEUE_H

redpajama_set_name: RedPajamaGithub


text:
var registry;

module('Registry', {
  setup: function() {
    registry = new Pretender.Registry();
  }
});

test('has a "verbs" property', function() {
  ok(registry.verbs);
});

test('supports all HTTP verbs', function(assert) {
  var verbs = ['GET', 'PUT', 'POST', 'PATCH', 'DELETE', 'OPTIONS', 'HEAD'];
  for (var v = 0; v < verbs.length; v++) {
    assert.ok(registry.verbs[verbs[v]], 'supports ' + verbs[v]);
  }
});


text:
import { action, observable } from 'mobx';

/**
 * Used to track whether any route from blueocean-dashboard is currently active.
 * Managed via mount/unmount in top-level Dashboard component.
 */
class DashboardNavState {
    @observable isActive = false;

    @action
    setActive() {
        this.isActive = true;
    }

    @action
    setInactive() {
        this.isActive = false;
    }
}

export default new DashboardNavState();


text:
/**
 * @name Connection
 * @extends OverlayCapableJsPlumbUIComponent
 * @class
 * @classdesc Models a connection.
 */

 /**
  * @name Connection#Connection
  * @constructor
  * @function
  * @desc Connection constructor. You should not ever create one of these directly. If you make a call to jsPlumb.connect, all of
  * the parameters that you pass in to that function will be passed to the Connection constructor; if your UI
  * uses the various Endpoint-centric methods like addEndpoint/makeSource/makeTarget, along with drag and drop,
  * then the parameters you set on those functions are translated and passed in to the Connection constructor. So
  * you should check the documentation for each of those methods.
  * @param {Object} params Constructor parameters
  * @param {String|Element|Selector|Endpoint} [params.source] Either an element id, a selector for an element, or an Endpoint.
  * @param {String|Element|Selector|Endpoint} [params.target] Either an element id, a selector for an element, or an Endpoint
  * @param {String} [params.scope=`jsPlumb.Defaults.Scope`] Scope descriptor for this connection.
  * @param {String|Element|Selector} [params.container] Optional id, element or selector instructing jsPlumb where to attach all the elements it creates for this connection.  you should read the documentation for a full discussion of this.
  * @param {Boolean} [params.detachable=true] Defines whether or not the connection may be detached using the mouse.
  * @param {Boolean} [params.reattach=false] Defines whether not the connection should be retached if it was dragged off an Endpoint and then dropped in whitespace.
  * @param {Object} [params.endpoint] Optional Endpoint definition to use for both ends of the connection.
  * @param {Object[]} [params.endpoints] Optional array of two Endpoint definitions, one for each end of the Connection. This and 'endpoint' are mutually exclusive parameters.
  * @param {Object} [params.endpointStyle] Endpoint style definition to use for both ends of the Connection.
  * @param {Object[]} [params.endpointStyles] Array of two Endpoint style definitions, one for each end of the Connection. This and 'endpoint' are mutually exclusive parameters.
  * @param {Object} [params.paintStyle] Parameters defining the appearance of the Connection. Optional; jsPlumb will use the defaults if you supply nothing here.
  * @param {Object} [params.hoverPaintStyle] Parameters defining the appearance of the Connection when the mouse is hovering over it. Optional; jsPlumb will use the defaults if you supply nothing here (note that the default hoverPaintStyle is null).
  * @param {String} [params.cssClass] CSS class to set on the display element associated with this Connection.
  * @param {String} [params.hoverClass] CSS class to set on the display element associated with this Connection when it is in hover state.
  * @param {Object[]} [params.overlays] Array of Overlay definitions to appear on this Connection.
  * @param {Boolean} [params.drawEndpoints=true] If false, instructs jsPlumb to not draw the endpoints for this Connection.  Be careful with this: it only really works when you tell jsPlumb to attach elements to the document body. Read the documentation for a full discussion of this.
  * @param {Object} [params.parameters={}] JS object containing parameters to set on the Connection. These parameters are then available via the getParameter method.
  */

  /**
  * @name Connection#sourceId
  * @desc ID of the source element.
  */

  /**
  * @name Connection#targetId
  * @desc ID of the target element.
  */

  /**
  * @name Connection#scope
  * @desc Scope descriptor for the Connection.
  */

  /**
  * @name Connection#source
  * @desc Source element in the Connection.
  */

  /**
  * @name Connection#target
  * @desc Target element in the Connection..
  */

/**
* @name Connection#getConnector
* @function
* @desc Gets the underlying Connector for this Connection (eg. a Bezier connector, straight line connector, flowchart connector etc)
* @returns {Connector} The current Connector
*/

/**
* @name Connection#isDetachable
* @function
* @desc Returns whether or not this connection can be detached from its target/source endpoint.  by default this
* is false; use it in conjunction with the 'reattach' parameter.
* @returns {Boolean} True if can be detached, false otherwise.
*/

/**
* @name Connection#isEditable
* @function
* @desc Returns whether or not the Connection is editable.
* @returns {Boolean} True if editable, false if not.
*/

/**
* @name Connection#isReattach
* @function
* @desc Returns whether or not this connection will be reattached after having been detached via the mouse and dropped.  by default this
* is false; use it in conjunction with the 'detachable' parameter.
* @returns {Boolean} True if will reattach, false if not.
*/

/**
* @name Connection#isVisible
* @function
* @desc Returns whether or not the Connection is currently visible.
* @returns True if visible, false if not.
*/

/**
* @name Connection#setConnector
* @function
* @desc Sets the Connection's connector (eg "Bezier", "Flowchart", etc).  You pass a Connector definition into this method, the same
* thing that you would set as the 'connector' property on a jsPlumb.connect call.
* @param {String|Object} connector Connector definition. See jsPlumb documentation for a discussion.
*/

/**
* @name Connection#setDetachable
* @function
* @desc Sets whether or not this connection is detachable.
* @param {Boolean} detachable Whether or not to set the Connection to be detachable.
*/

/**
* @name Connection#setEditable
* @function
* @desc Sets whether or not the Connection is editable. This will only be honoured if
* the underlying Connector is editable - not all types are.
* @param {Boolean} editable Whether or not to set the Connection to be editable
*/

/**
* @name Connection#setReattach
* @function
* @desc Sets whether or not this connection will reattach after having been detached via the mouse and dropped.
* @param {Boolean} reattach	Whether or not to set the Connection to reattach after drop in whitespace.
*/

/**
* @name Connection#setVisible
* @function
* @desc Sets whether or not the Connection should be visible.
* @param {Boolean} visible Boolean indicating desired visible state.
*/


text:
var getSpreadsheet = require('./getSpreadsheet'),
    e = require('./appErrors'),
    appUtils = require('./appUtils'),
    log = require('./log');

function handleGetSpreadsheetNames(req, res, next) {
    if (! req.params.userId || !req.params.experimentDirFileId)
        return next(new e.HttpBadRequestError());

    // Note that this returns no spreadsheets if user doesn't match file id.
    getSpreadsheet.getSpreadsheetNames(req.params.userId, req.params.experimentDirFileId, function (err, names) {
        if (err) {
            return next(err);
        }
        else if (names == null) {
            appUtils.sendJSON(res, { hasSpreadsheet: false });
        }
        else {
            appUtils.sendJSON(res, { hasSpreadsheet: true, spreadsheetNames: names });
        }
    });
};

function handleGetMySpreadsheet(req, res, next) {
    if (! req.user)
        return next(new appErrors.AuthError());

    let fpath = '/' + req.params.name;
    log.debug("Getting spreadsheet at: " + fpath);

    getSpreadsheet.getSpreadsheet(req.user.userId, fpath, (err, jsonContents) => {
        if (err)
            return next(err);

        if (jsonContents === null)
            return res.status(404).end()

        appUtils.sendJSON(res, jsonContents);
    });
}

exports.handleGetSpreadsheetNames = handleGetSpreadsheetNames;
exports.handleGetMySpreadsheet = handleGetMySpreadsheet;


text:
package mysqldef

import (
	"bytes"
	"fmt"
	"math"
	"strconv"
	"strings"
	"time"
	"unicode"

	"github.com/juju/errors"
)

// Portable analogs of some common call errors.
var (
	ErrInvalidTimeFormat = errors.New("invalid time format")
	ErrInvalidYearFormat = errors.New("invalid year format")
	ErrInvalidYear       = errors.New("invalid year")
)

// Time format without fractional seconds precision.
const (
	DateFormat = "2006-01-02"
	TimeFormat = "2006-01-02 15:04:05"
	// TimeFSPFormat is time format with fractional seconds precision.
	TimeFSPFormat = "2006-01-02 15:04:05.000000"
)

const (
	// MinYear is the minimum for mysql year type.
	MinYear int16 = 1901
	// MaxYear is the maximum for mysql year type.
	MaxYear int16 = 2155

	// MinTime is the minimum for mysql time type.
	MinTime = -time.Duration(838*3600+59*60+59) * time.Second
	// MaxTime is the maximum for mysql time type.
	MaxTime = time.Duration(838*3600+59*60+59) * time.Second

	zeroDatetimeStr  = "0000-00-00 00:00:00"
	zeroTimestampStr = "0000-00-00 00:00:00"
	zeroDateStr      = "0000-00-00"
)

// Zero values for different types.
var (
	// ZeroDuration is the zero value for Duration type.
	ZeroDuration = Duration{Duration: time.Duration(0), Fsp: DefaultFsp}

	// ZeroTime is the zero value for time.Time type.
	ZeroTime = time.Date(0, 0, 0, 0, 0, 0, 0, time.UTC)

	// ZeroDatetime is the zero value for datetime Time.
	ZeroDatetime = Time{
		Time: ZeroTime,
		Type: TypeDatetime,
		Fsp:  DefaultFsp,
	}

	// ZeroTimestamp is the zero value for timestamp Time.
	ZeroTimestamp = Time{
		Time: ZeroTime,
		Type: TypeTimestamp,
		Fsp:  DefaultFsp,
	}

	// ZeroDate is the zero value for date Time.
	ZeroDate = Time{
		Time: ZeroTime,
		Type: TypeDate,
		Fsp:  DefaultFsp,
	}
)

var (
	// MinDatetime is the minimum for mysql datetime type.
	MinDatetime = time.Date(1000, 1, 1, 0, 0, 0, 0, time.Local)
	// MaxDatetime is the maximum for mysql datetime type.
	MaxDatetime = time.Date(9999, 12, 31, 23, 59, 59, 999999, time.Local)

	// MinTimestamp is the minimum for mysql timestamp type.
	MinTimestamp = time.Date(1970, 1, 1, 0, 0, 1, 0, time.UTC)
	// MaxTimestamp is the maximum for mysql timestamp type.
	MaxTimestamp = time.Date(2038, 1, 19, 3, 14, 7, 999999, time.UTC)
)

// Time is the struct for handling datetime, timestamp and date.
// TODO: check if need a NewTime function to set Fsp default value?
type Time struct {
	time.Time
	Type uint8
	// Fsp is short for Fractional Seconds Precision.
	// See http://dev.mysql.com/doc/refman/5.7/en/fractional-seconds.html
	Fsp int
}

func (t Time) String() string {
	if t.IsZero() {
		if t.Type == TypeDate {
			return zeroDateStr
		}

		return zeroDatetimeStr
	}

	if t.Type == TypeDate {
		return t.Time.Format(DateFormat)
	}

	tfStr := TimeFormat
	if t.Fsp > 0 {
		tfStr = fmt.Sprintf("%s.%s", tfStr, strings.Repeat("0", t.Fsp))
	}

	return t.Time.Format(tfStr)
}

// IsZero returns a boolean indicating whether the time is equal to ZeroTime.
func (t Time) IsZero() bool {
	return t.Time.Equal(ZeroTime)
}

// Marshal returns the binary encoding of time.
func (t Time) Marshal() ([]byte, error) {
	var (
		b   []byte
		err error
	)

	switch t.Type {
	case TypeDatetime, TypeDate:
		_, offset := t.Time.Zone()
		// For datetime and date type, we have a trick to marshal.
		// e.g, if local time is 2010-10-10T10:10:10 UTC+8
		// we will change this to 2010-10-10T10:10:10 UTC and then marshal.
		b, err = t.Time.Add(time.Duration(offset) * time.Second).UTC().MarshalBinary()
	case TypeTimestamp:
		b, err = t.Time.UTC().MarshalBinary()
	default:
		err = errors.Errorf("invalid time type %d", t.Type)
	}

	return b, err
}

// Unmarshal decodes the binary data into Time with current local time.
func (t *Time) Unmarshal(b []byte) error {
	return t.UnmarshalInLocation(b, time.Local)
}

// UnmarshalInLocation decodes the binary data
// into Time with a specific time Location.
func (t *Time) UnmarshalInLocation(b []byte, loc *time.Location) error {
	if err := t.Time.UnmarshalBinary(b); err != nil {
		return errors.Trace(err)
	}

	if t.IsZero() {
		return nil
	}

	if t.Type == TypeDatetime || t.Type == TypeDate {
		// e.g, for 2010-10-10T10:10:10 UTC, we will unmarshal to 2010-10-10T10:10:10 location
		_, offset := time.Now().In(loc).Zone()
		t.Time = t.Time.Add(-time.Duration(offset) * time.Second).In(loc)
		if t.Type == TypeDate {
			// for date type ,we will only use year, month and day.
			year, month, day := t.Time.Date()
			t.Time = time.Date(year, month, day, 0, 0, 0, 0, loc)
		}
	} else if t.Type == TypeTimestamp {
		t.Time = t.Time.In(loc)
	} else {
		return errors.Errorf("invalid time type %d", t.Type)
	}

	return nil
}

const numberFormat = "20060102150405"

// ToNumber returns a formatted number.
// e.g,
// 2012-12-12T10:10:10 -> 20121212101010
// 2012-12-12T10:10:10.123456 -> 20121212101010.123456
func (t Time) ToNumber() Decimal {
	if t.IsZero() {
		return ZeroDecimal
	}

	tfStr := numberFormat
	if t.Fsp > 0 {
		tfStr = fmt.Sprintf("%s.%s", tfStr, strings.Repeat("0", t.Fsp))
	}

	s := t.Time.Format(tfStr)
	// We skip checking error here because time formatted string can be parsed certainly.
	d, _ := ParseDecimal(s)
	return d
}

// Convert converts t with type tp.
func (t Time) Convert(tp uint8) (Time, error) {
	if t.Type == tp || t.IsZero() {
		return Time{Time: t.Time, Type: tp, Fsp: t.Fsp}, nil
	}

	switch tp {
	case TypeDatetime:
		return Time{Time: t.Time, Type: TypeDatetime, Fsp: t.Fsp}, nil
	case TypeTimestamp:
		nt := Time{Time: t.Time, Type: TypeTimestamp, Fsp: t.Fsp}
		if !checkTimestamp(nt) {
			return ZeroTimestamp, errors.Trace(ErrInvalidTimeFormat)
		}
		return nt, nil
	case TypeDate:
		year, month, day := t.Time.Date()
		return Time{Time: time.Date(year, month, day, 0, 0, 0, 0, time.Local),
			Type: TypeDate, Fsp: 0}, nil
	default:
		return Time{Time: ZeroTime, Type: tp}, errors.Errorf("invalid time type %d", tp)
	}
}

// ConvertToDuration converts mysql datetime, timestamp and date to mysql time type.
// e.g,
// 2012-12-12T10:10:10 -> 10:10:10
// 2012-12-12 -> 0
func (t Time) ConvertToDuration() (Duration, error) {
	if t.IsZero() {
		return ZeroDuration, nil
	}

	hour, minute, second := t.Clock()
	frac := t.Nanosecond()

	d := time.Duration(hour*3600+minute*60+second)*time.Second + time.Duration(frac)

	// TODO: check convert validation
	return Duration{Duration: time.Duration(d), Fsp: t.Fsp}, nil
}

// Compare returns an integer comparing the time instant t to o.
// If t is after o, return 1, equal o, return 0, before o, return -1.
func (t Time) Compare(o Time) int {
	if t.Time.After(o.Time) {
		return 1
	} else if t.Time.Equal(o.Time) {
		return 0
	} else {
		return -1
	}
}

// CompareString is like Compare,
// but parses string to Time then compares.
func (t Time) CompareString(str string) (int, error) {
	// use MaxFsp to parse the string
	o, err := ParseTime(str, t.Type, MaxFsp)
	if err != nil {
		return 0, errors.Trace(err)
	}

	return t.Compare(o), nil
}

// RoundFrac rounds fractional seconds precision with new fsp and returns a new one.
// We will use the "round half up" rule, e.g, >= 0.5 -> 1, < 0.5 -> 0,
// so 2011:11:11 10:10:10.888888 round 0 -> 2011:11:11 10:10:11
// and 2011:11:11 10:10:10.111111 round 0 -> 2011:11:11 10:10:10
func (t Time) RoundFrac(fsp int) (Time, error) {
	if t.Type == TypeDate {
		// date type has no fsp
		return t, nil
	}

	fsp, err := checkFsp(fsp)
	if err != nil {
		return t, errors.Trace(err)
	}

	if fsp == t.Fsp {
		// have same fsp
		return t, nil
	}

	nt := t.Time.Round(time.Duration(math.Pow10(9-fsp)) * time.Nanosecond)
	return Time{Time: nt, Type: t.Type, Fsp: fsp}, nil
}

func parseDatetime(str string, fsp int) (Time, error) {
	// Try to split str with delimiter.
	// TODO: only punctuation can be the delimiter for date parts or time parts.
	// But only space and T can be the delimiter between the date and time part.
	seps := strings.FieldsFunc(str, func(c rune) bool {
		return !unicode.IsNumber(c)
	})

	var (
		year    int
		month   int
		day     int
		hour    int
		minute  int
		second  int
		frac    int
		fracStr string

		err error
	)
	switch len(seps) {
	case 1:
		// No delimiter.
		if len(str) == 14 {
			// YYYYMMDDHHMMSS
			_, err = fmt.Sscanf(str, "%4d%2d%2d%2d%2d%2d", &year, &month, &day, &hour, &minute, &second)
		} else if len(str) == 12 {
			// YYMMDDHHMMSS
			_, err = fmt.Sscanf(str, "%2d%2d%2d%2d%2d%2d", &year, &month, &day, &hour, &minute, &second)
			year = adjustYear(year)
		} else if len(str) == 8 {
			// YYYYMMDD
			_, err = fmt.Sscanf(str, "%4d%2d%2d", &year, &month, &day)
		} else if len(str) == 6 {
			// YYMMDD
			_, err = fmt.Sscanf(str, "%2d%2d%2d", &year, &month, &day)
			year = adjustYear(year)
		} else {
			return ZeroDatetime, errors.Trace(ErrInvalidTimeFormat)
		}
	case 2:
		s := seps[0]
		fracStr = seps[1]

		if len(s) == 14 {
			// YYYYMMDDHHMMSS.fraction
			_, err = fmt.Sscanf(s, "%4d%2d%2d%2d%2d%2d", &year, &month, &day, &hour, &minute, &second)
		} else if len(s) == 12 {
			// YYMMDDHHMMSS.fraction
			_, err = fmt.Sscanf(s, "%2d%2d%2d%2d%2d%2d", &year, &month, &day, &hour, &minute, &second)
			year = adjustYear(year)
		} else {
			return ZeroDatetime, errors.Trace(ErrInvalidTimeFormat)
		}
	case 3:
		// YYYY-MM-DD
		err = scanTimeArgs(seps, &year, &month, &day)
	case 6:
		// We don't have fractional seconds part.
		// YYYY-MM-DD HH-MM-SS
		err = scanTimeArgs(seps, &year, &month, &day, &hour, &minute, &second)
	case 7:
		// We have fractional seconds part.
		// YYY-MM-DD HH-MM-SS.fraction
		err = scanTimeArgs(seps[0:len(seps)-1], &year, &month, &day, &hour, &minute, &second)
		fracStr = seps[len(seps)-1]
	default:
		return ZeroDatetime, errors.Trace(ErrInvalidTimeFormat)
	}

	if err != nil {
		return ZeroDatetime, errors.Trace(err)
	}

	// If str is sepereated by delimiters, the first one is year, and if the year is 2 digit,
	// we should adjust it.
	// TODO: ajust year is very complex, now we only consider the simplest way.
	if len(seps[0]) == 2 {
		year = adjustYear(year)
	}

	frac, err = parseFrac(fracStr, fsp)
	if err != nil {
		return ZeroDatetime, errors.Trace(err)
	}

	t, err := newTime(year, month, day, hour, minute, second, frac)
	if err != nil {
		return ZeroDatetime, errors.Trace(err)
	}

	nt := Time{
		Time: t,
		Type: TypeDatetime,
		Fsp:  fsp}

	return nt, nil
}

func scanTimeArgs(seps []string, args ...*int) error {
	if len(seps) != len(args) {
		return errors.Trace(ErrInvalidTimeFormat)
	}

	var err error
	for i, s := range seps {
		*args[i], err = strconv.Atoi(s)
		if err != nil {
			return errors.Trace(err)
		}
	}
	return nil
}

// ParseYear parses a formatted string and returns a year number.
func ParseYear(str string) (int16, error) {
	v, err := strconv.ParseInt(str, 10, 16)
	if err != nil {
		return 0, errors.Trace(err)
	}
	y := int16(v)

	if len(str) == 4 {
		// Nothing to do.
	} else if len(str) == 2 || len(str) == 1 {
		y = int16(adjustYear(int(y)))
	} else {
		return 0, errors.Trace(ErrInvalidYearFormat)
	}

	if y < MinYear || y > MaxYear {
		return 0, errors.Trace(ErrInvalidYearFormat)
	}

	return y, nil
}

func newTime(year int, month int, day int, hour int, minute int, second int, frac int) (time.Time, error) {
	if year == 0 && month == 0 && day == 0 && hour == 0 && minute == 0 && second == 0 {
		// Should we check fractional fractional here?
		// But go time.Time can not support zero time 0000-00-00 00:00:00.
		return ZeroTime, nil
	}

	if err := checkTime(year, month, day, hour, minute, second, frac); err != nil {
		return ZeroTime, errors.Trace(err)
	}

	return time.Date(year, time.Month(month), day, hour, minute, second, frac*1000, time.Local), nil
}

// See https://dev.mysql.com/doc/refman/5.7/en/two-digit-years.html
func adjustYear(y int) int {
	if y >= 0 && y <= 69 {
		y = 2000 + y
	} else if y >= 70 && y <= 99 {
		y = 1900 + y
	}
	return y
}

// AdjustYear is used for adjusting year and checking its validation.
func AdjustYear(y int) (int, error) {
	y = adjustYear(y)
	if y < int(MinYear) || y > int(MaxYear) {
		return 0, errors.Trace(ErrInvalidYear)
	}

	return y, nil
}

// Duration is the type for MySQL time type.
type Duration struct {
	time.Duration
	// Fsp is short for Fractional Seconds Precision.
	// See http://dev.mysql.com/doc/refman/5.7/en/fractional-seconds.html
	Fsp int
}

// String returns the time formatted using default TimeFormat and fsp.
func (d Duration) String() string {
	var buf bytes.Buffer

	sign, hours, minutes, seconds, fraction := splitDuration(d.Duration)
	if sign < 0 {
		buf.WriteByte('-')
	}

	fmt.Fprintf(&buf, "%02d:%02d:%02d", hours, minutes, seconds)
	if d.Fsp > 0 {
		buf.WriteString(".")
		buf.WriteString(d.formatFrac(fraction))
	}

	p := buf.String()

	return p
}

func (d Duration) formatFrac(frac int) string {
	format := fmt.Sprintf("%%0%dd", d.Fsp)
	s := fmt.Sprintf(format, frac)
	return s[0:d.Fsp]
}

// ToNumber changes duration to number format.
// e.g,
// 10:10:10 -> 101010
func (d Duration) ToNumber() Decimal {
	sign, hours, minutes, seconds, fraction := splitDuration(time.Duration(d.Duration))
	var (
		s       string
		signStr string
	)

	if sign < 0 {
		signStr = "-"
	}

	if d.Fsp == 0 {
		s = fmt.Sprintf("%s%02d%02d%02d", signStr, hours, minutes, seconds)
	} else {
		s = fmt.Sprintf("%s%02d%02d%02d.%s", signStr, hours, minutes, seconds, d.formatFrac(fraction))
	}

	// We skip checking error here because time formatted string can be parsed certainly.
	v, _ := ParseDecimal(s)
	return v
}

// ConvertToTime converts duration to Time.
// Tp is TypeDatetime, TypeTimestamp and TypeDate.
func (d Duration) ConvertToTime(tp uint8) (Time, error) {
	year, month, day := time.Now().Date()
	// just use current year, month and day.
	n := time.Date(year, month, day, 0, 0, 0, 0, time.Local)
	n = n.Add(d.Duration)

	t := Time{
		Time: n,
		Type: TypeDatetime,
		Fsp:  d.Fsp,
	}

	return t.Convert(tp)
}

// RoundFrac rounds fractional seconds precision with new fsp and returns a new one.
// We will use the "round half up" rule, e.g, >= 0.5 -> 1, < 0.5 -> 0,
// so 10:10:10.999999 round 0 -> 10:10:11
// and 10:10:10.000000 round 0 -> 10:10:10
func (d Duration) RoundFrac(fsp int) (Duration, error) {
	fsp, err := checkFsp(fsp)
	if err != nil {
		return d, errors.Trace(err)
	}

	if fsp == d.Fsp {
		return d, nil
	}

	n := ZeroTime
	nd := n.Add(d.Duration).Round(time.Duration(math.Pow10(9-fsp)) * time.Nanosecond).Sub(n)
	return Duration{Duration: nd, Fsp: fsp}, nil
}

// Compare returns an integer comparing the Duration instant t to o.
// If d is after o, return 1, equal o, return 0, before o, return -1.
func (d Duration) Compare(o Duration) int {
	if d.Duration > o.Duration {
		return 1
	} else if d.Duration == o.Duration {
		return 0
	} else {
		return -1
	}
}

// CompareString is like Compare,
// but parses str to Duration then compares.
func (d Duration) CompareString(str string) (int, error) {
	// use MaxFsp to parse the string
	o, err := ParseDuration(str, MaxFsp)
	if err != nil {
		return 0, err
	}

	return d.Compare(o), nil
}

// Hour returns current hour.
// e.g, hour("11:11:11") -> 11
func (d Duration) Hour() int {
	_, hour, _, _, _ := splitDuration(d.Duration)
	return hour
}

// Minute returns current minute.
// e.g, hour("11:11:11") -> 11
func (d Duration) Minute() int {
	_, _, minute, _, _ := splitDuration(d.Duration)
	return minute
}

// Second returns current second.
// e.g, hour("11:11:11") -> 11
func (d Duration) Second() int {
	_, _, _, second, _ := splitDuration(d.Duration)
	return second
}

// MicroSecond returns current microsecond.
// e.g, hour("11:11:11.11") -> 110000
func (d Duration) MicroSecond() int {
	_, _, _, _, frac := splitDuration(d.Duration)
	return frac
}

// ParseDuration parses the time form a formatted string with a fractional seconds part,
// returns the duration type Time value.
// See: http://dev.mysql.com/doc/refman/5.7/en/fractional-seconds.html
func ParseDuration(str string, fsp int) (Duration, error) {
	var (
		day    int
		hour   int
		minute int
		second int
		frac   int

		err       error
		sign      = 0
		dayExists = false
	)

	fsp, err = checkFsp(fsp)
	if err != nil {
		return ZeroDuration, errors.Trace(err)
	}

	if len(str) == 0 {
		return ZeroDuration, nil
	} else if str[0] == '-' {
		str = str[1:]
		sign = -1
	}

	// Time format may has day.
	if n := strings.IndexByte(str, ' '); n >= 0 {
		if day, err = strconv.Atoi(str[:n]); err == nil {
			dayExists = true
		}
		str = str[n+1:]
	}

	if n := strings.IndexByte(str, '.'); n >= 0 {
		// It has fractional precesion parts.
		fracStr := str[n+1:]
		frac, err = parseFrac(fracStr, fsp)
		if err != nil {
			return ZeroDuration, errors.Trace(err)
		}
		str = str[0:n]
	}

	// It tries to split str with delimiter, time delimiter must be :
	seps := strings.Split(str, ":")

	switch len(seps) {
	case 1:
		if dayExists {
			hour, err = strconv.Atoi(seps[0])
		} else {
			// No delimiter.
			if len(str) == 6 {
				// HHMMSS
				_, err = fmt.Sscanf(str, "%2d%2d%2d", &hour, &minute, &second)
			} else if len(str) == 4 {
				// MMSS
				_, err = fmt.Sscanf(str, "%2d%2d", &minute, &second)
			} else if len(str) == 2 {
				// SS
				_, err = fmt.Sscanf(str, "%2d", &second)
			} else {
				// Maybe only contains date.
				_, err = ParseDate(str)
				if err == nil {
					return ZeroDuration, nil
				}
				return ZeroDuration, errors.Trace(ErrInvalidTimeFormat)
			}
		}
	case 2:
		// HH:MM
		_, err = fmt.Sscanf(str, "%2d:%2d", &hour, &minute)
	case 3:
		// Time format maybe HH:MM:SS or HHH:MM:SS.
		// See: https://dev.mysql.com/doc/refman/5.7/en/time.html
		if !dayExists && len(seps[0]) == 3 {
			_, err = fmt.Sscanf(str, "%3d:%2d:%2d", &hour, &minute, &second)
		} else {
			_, err = fmt.Sscanf(str, "%2d:%2d:%2d", &hour, &minute, &second)
		}
	default:
		return ZeroDuration, errors.Trace(ErrInvalidTimeFormat)
	}

	if err != nil {
		return ZeroDuration, errors.Trace(err)
	}

	d := time.Duration(day*24*3600+hour*3600+minute*60+second)*time.Second + time.Duration(frac)*time.Microsecond
	if sign == -1 {
		d = -d
	}

	if d > MaxTime {
		d = MaxTime
		err = ErrInvalidTimeFormat
	} else if d < MinTime {
		d = MinTime
		err = ErrInvalidTimeFormat
	}
	return Duration{Duration: d, Fsp: fsp}, errors.Trace(err)
}

func splitDuration(t time.Duration) (int, int, int, int, int) {
	sign := 1
	if t < 0 {
		t = -t
		sign = -1
	}

	hours := t / time.Hour
	t -= hours * time.Hour
	minutes := t / time.Minute
	t -= minutes * time.Minute
	seconds := t / time.Second
	t -= seconds * time.Second
	fraction := t / time.Microsecond

	return sign, int(hours), int(minutes), int(seconds), int(fraction)
}

func checkTime(year int, month int, day int, hour int, minute int, second int, frac int) error {
	// Notes: for datetime type, `insert t values("0001-01-01 00:00:00");` is valid
	// so here only check year from 0~9999.
	if (year < 0 || year > 9999) ||
		(month <= 0 || month > 12) ||
		(day <= 0 || day > 31) ||
		(hour < 0 || hour >= 24) ||
		(minute < 0 || minute >= 60) ||
		(second < 0 || second >= 60) ||
		(frac < 0) {
		return errors.Trace(ErrInvalidTimeFormat)
	}

	return nil
}

func getTime(num int64, tp byte) (Time, error) {
	s1 := num / 1000000
	s2 := num - s1*1000000

	year := int(s1 / 10000)
	s1 %= 10000
	month := int(s1 / 100)
	day := int(s1 % 100)

	hour := int(s2 / 10000)
	s2 %= 10000
	minute := int(s2 / 100)
	second := int(s2 % 100)

	if err := checkTime(year, month, day, hour, minute, second, 0); err != nil {
		return Time{
			Time: ZeroTime,
			Type: tp,
			Fsp:  DefaultFsp,
		}, err
	}

	t, err := newTime(year, month, day, hour, minute, second, 0)
	return Time{
		Time: t,
		Type: tp,
		Fsp:  DefaultFsp,
	}, errors.Trace(err)
}

// See number_to_datetime function.
// https://github.com/mysql/mysql-server/blob/5.7/sql-common/my_time.c
func parseDateTimeFromNum(num int64) (Time, error) {
	t := ZeroDate
	// Check zero.
	if num == 0 {
		return t, nil
	}

	// Check datetime type.
	if num >= 10000101000000 {
		return getTime(num, t.Type)
	}

	// Check MMDD.
	if num < 101 {
		return t, errors.Trace(ErrInvalidTimeFormat)
	}

	// Adjust year
	// YYMMDD, year: 2000-2069
	if num <= (70-1)*10000+1231 {
		num = (num + 20000000) * 1000000
		return getTime(num, t.Type)
	}

	// Check YYMMDD.
	if num < 70*10000+101 {
		return t, errors.Trace(ErrInvalidTimeFormat)
	}

	// Adjust year
	// YYMMDD, year: 1970-1999
	if num < 991231 {
		num = (num + 19000000) * 1000000
		return getTime(num, t.Type)
	}

	// Check YYYYMMDD.
	if num < 10000101 {
		return t, errors.Trace(ErrInvalidTimeFormat)
	}

	// Adjust hour/min/second.
	if num < 99991231 {
		num = num * 1000000
		return getTime(num, t.Type)
	}

	// Check MMDDHHMMSS.
	if num < 101000000 {
		return t, errors.Trace(ErrInvalidTimeFormat)
	}

	// Set TypeDatetime type.
	t.Type = TypeDatetime

	// Adjust year
	// YYMMDDHHMMSS, 2000-2069
	if num <= 69*10000000000+1231235959 {
		num = num + 20000000000000
		return getTime(num, t.Type)
	}

	// Check YYYYMMDDHHMMSS.
	if num < 70*10000000000+101000000 {
		return t, errors.Trace(ErrInvalidTimeFormat)
	}

	// Adjust year
	// YYMMDDHHMMSS, 1970-1999
	if num <= 991231235959 {
		num = num + 19000000000000
		return getTime(num, t.Type)
	}

	return getTime(num, t.Type)
}

// ParseTime parses a formatted string with type tp and specific fsp.
// Type is TypeDatetime, TypeTimestamp and TypeDate.
// Fsp is in range [0, 6].
// MySQL supports many valid datatime format, but still has some limitation.
// If delimiter exists, the date part and time part is seperated by a space or T,
// other punctuation character can be used as the delimiter between date parts or time parts.
// If no delimiter, the format must be YYYYMMDDHHMMSS or YYMMDDHHMMSS
// If we have fractional seconds part, we must use decimal points as the delimiter.
// The valid datetime range is from '1000-01-01 00:00:00.000000' to '9999-12-31 23:59:59.999999'.
// The valid timestamp range is from '1970-01-01 00:00:01.000000' to '2038-01-19 03:14:07.999999'.
// The valid date range is from '1000-01-01' to '9999-12-31'
func ParseTime(str string, tp byte, fsp int) (Time, error) {
	fsp, err := checkFsp(fsp)
	if err != nil {
		return Time{Time: ZeroTime, Type: tp}, errors.Trace(err)
	}

	t, err := parseDatetime(str, fsp)
	if err != nil {
		return Time{Time: ZeroTime, Type: tp}, errors.Trace(err)
	}

	return t.Convert(tp)
}

// ParseDatetime is a helper function wrapping ParseTime with datetime type and default fsp.
func ParseDatetime(str string) (Time, error) {
	return ParseTime(str, TypeDatetime, DefaultFsp)
}

// ParseTimestamp is a helper function wrapping ParseTime with timestamp type and default fsp.
func ParseTimestamp(str string) (Time, error) {
	return ParseTime(str, TypeTimestamp, DefaultFsp)
}

// ParseDate is a helper function wrapping ParseTime with date type.
func ParseDate(str string) (Time, error) {
	// date has no fractional seconds precision
	return ParseTime(str, TypeDate, MinFsp)
}

// ParseTimeFromNum parses a formatted int64,
// returns the value which type is tp.
func ParseTimeFromNum(num int64, tp byte, fsp int) (Time, error) {
	fsp, err := checkFsp(fsp)
	if err != nil {
		return Time{Time: ZeroTime, Type: tp}, errors.Trace(err)
	}

	t, err := parseDateTimeFromNum(num)
	if err != nil {
		return Time{Time: ZeroTime, Type: tp}, errors.Trace(err)
	}

	if !checkDatetime(t) {
		return Time{Time: ZeroTime, Type: tp}, ErrInvalidTimeFormat
	}

	t.Fsp = fsp
	return t.Convert(tp)
}

// ParseDatetimeFromNum is a helper function wrapping ParseTimeFromNum with datetime type and default fsp.
func ParseDatetimeFromNum(num int64) (Time, error) {
	return ParseTimeFromNum(num, TypeDatetime, DefaultFsp)
}

// ParseTimestampFromNum is a helper function wrapping ParseTimeFromNum with timestamp type and default fsp.
func ParseTimestampFromNum(num int64) (Time, error) {
	return ParseTimeFromNum(num, TypeTimestamp, DefaultFsp)
}

// ParseDateFromNum is a helper function wrapping ParseTimeFromNum with date type.
func ParseDateFromNum(num int64) (Time, error) {
	// date has no fractional seconds precision
	return ParseTimeFromNum(num, TypeDate, MinFsp)
}

func checkDatetime(t Time) bool {
	if t.IsZero() {
		return true
	}

	if t.Time.After(MaxDatetime) || t.Time.Before(MinDatetime) {
		return false
	}

	return true
}

func checkTimestamp(t Time) bool {
	if t.IsZero() {
		return true
	}

	if t.Time.After(MaxTimestamp) || t.Time.Before(MinTimestamp) {
		return false
	}

	return true
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html
  PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<meta name="copyright" content="(C) Copyright 2005"/>
<meta name="DC.rights.owner" content="(C) Copyright 2005"/>
<meta name="DC.Type" content="reference"/>
<meta name="DC.Title" content="LogConfig object"/>
<meta name="DC.Relation" scheme="URI" content="../topics/svcdef-object.html"/>
<meta name="DC.Format" content="XHTML"/>
<meta name="DC.Identifier" content="referenceid"/>
<link rel="stylesheet" type="text/css" href="../commonltr.css"/>
<title>LogConfig object</title>

LogConfig object

            Atttribute

            Value

            Description

            <samp class="ph codeph">Path</samp>

            String

            The absolute path of a log file on a container's file system. The path
              can be a directory or a file, and bash pathname expansion
              (globbing) is supported.

            <samp class="ph codeph">Type</samp>

            String

            A string that identifies the "types" of logs that come from this source. This
              will be

            <samp class="ph codeph">Filters</samp>

            Array of strings

            A list of filters to apply to the log file. The filters listed here must be
              defined in the LogFilters object of the current service, or a parent service.

            <samp class="ph codeph">LogTags</samp>

            Array of objects

            A list of tags to send to logstash with all log file entries.
              Each object has two members:

<samp class="ph codeph">Name</samp> (string)

The name of the tag to send.

<samp class="ph codeph">Value</samp> (integer)

The value of the tag to send.

Parent topic: ServiceDefinition object


text: Application for A & P budget planning and management


text:
import { WordDocument } from './word-document';
import { DocumentParser } from './document-parser';
import { HtmlRenderer } from './html-renderer';

export interface Options {
    inWrapper: boolean;
    ignoreWidth: boolean;
    ignoreHeight: boolean;
    ignoreFonts: boolean;
    breakPages: boolean;
    debug: boolean;
    experimental: boolean;
    className: string;
    trimXmlDeclaration: boolean;
    renderHeaders: boolean;
    renderFooters: boolean;
    renderFootnotes: boolean;
	renderEndnotes: boolean;
    ignoreLastRenderedPageBreak: boolean;
	useBase64URL: boolean;
	useMathMLPolyfill: boolean;
}

export const defaultOptions: Options = {
    ignoreHeight: false,
    ignoreWidth: false,
    ignoreFonts: false,
    breakPages: true,
    debug: false,
    experimental: false,
    className: "docx",
    inWrapper: true,
    trimXmlDeclaration: true,
    ignoreLastRenderedPageBreak: true,
    renderHeaders: true,
    renderFooters: true,
    renderFootnotes: true,
	renderEndnotes: true,
	useBase64URL: false,
	useMathMLPolyfill: false
}

export function praseAsync(data: Blob | any, userOptions: Partial<Options> = null): Promise<any>  {
    const ops = { ...defaultOptions, ...userOptions };
    return WordDocument.load(data, new DocumentParser(ops), ops);
}

export function renderAsync(data: Blob | any, bodyContainer: HTMLElement, styleContainer: HTMLElement = null, userOptions: Partial<Options> = null): Promise<any> {
    const ops = { ...defaultOptions, ...userOptions };
    const renderer = new HtmlRenderer(window.document);

    return WordDocument
        .load(data, new DocumentParser(ops), ops)
        .then(doc => {
            renderer.render(doc, bodyContainer, styleContainer, ops);
            return doc;
        });
}


text:
<!DOCTYPE html>

        <meta charset="utf-8"/>
        <title>lbtoo helper</title>
        <meta name="revised" value="yanni4night,2015/10/16"/>
        <link rel="stylesheet" href="./styles/bootstrap.min.css"/>
        <link rel="stylesheet" href="./styles/popup.css"/>

萝卜兔职位搜索

            <form action="about:blank" class="form" autocomplete="off">

                    关键字:
                    <input type="text" class="form-control" name="alltext">

                    最大搜索量:
                    <input type="number" min="10" class="form-control" name="countPerPage" value="1000">

                <input type="hidden" name="currentPageNum" value="1">

                    城市:
                    <select name="jobCity" id="jobCity" class="form-control">
                        <option value="北京" selected>北京</option>
                        <option value="上海">上海</option>
                        <option value="广州">广州</option>
                        <option value="深圳">深圳</option>
                        <option value="">所有城市</option>
                    </select>

                    <button class="btn btn-info" type="submit">查询</button>
                    <button class="btn btn-primary last" type="button">上次结果</button>

            </form>


text:
// Low-level functions for atomic operations: m68k version -*- C++ -*-

// Copyright (C) 2001, 2002, 2003, 2004, 2005 Free Software Foundation, Inc.
//
// This file is part of the GNU ISO C++ Library.  This library is free
// software; you can redistribute it and/or modify it under the
// terms of the GNU General Public License as published by the
// Free Software Foundation; either version 2, or (at your option)
// any later version.

// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.

// You should have received a copy of the GNU General Public License along
// with this library; see the file COPYING.  If not, write to the Free
// Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
// USA.

// As a special exception, you may use this file as part of a free software
// library without restriction.  Specifically, if other files instantiate
// templates or use macros or inline functions from this file, or you compile
// this file and link it with other files to produce an executable, this
// file does not by itself cause the resulting executable to be covered by
// the GNU General Public License.  This exception does not however
// invalidate any other reasons why the executable file might be covered by
// the GNU General Public License.

#include <ext/atomicity.h>

_GLIBCXX_BEGIN_NAMESPACE(__gnu_cxx)

#if ( defined(__mc68020__) || defined(__mc68030__) \
      || defined(__mc68040__) || defined(__mc68060__) ) \
    && !defined(__mcpu32__)
  // These variants support compare-and-swap.
  _Atomic_word
  __attribute__ ((__unused__))
  __exchange_and_add(volatile _Atomic_word* __mem, int __val)
  {
    register _Atomic_word __result = *__mem;
    register _Atomic_word __temp;
    __asm__ __volatile__ ("1: move%.l %0,%1\n\t"
			  "add%.l %3,%1\n\t"
			  "cas%.l %0,%1,%2\n\t"
			  "jne 1b"
			  : "=d" (__result), "=&d" (__temp), "=m" (*__mem)
			  : "d" (__val), "0" (__result), "m" (*__mem));
    return __result;
  }

#elif defined(__rtems__)
  // TAS/JBNE is unsafe on systems with strict priority-based scheduling.
  // Disable interrupts, which we can do only from supervisor mode.
  _Atomic_word
  __attribute__ ((__unused__))
  __exchange_and_add(volatile _Atomic_word* __mem, int __val)
  {
    _Atomic_word __result;
    short __level, __tmpsr;
    __asm__ __volatile__ ("move%.w %%sr,%0\n\tor%.l %0,%1\n\tmove%.w %1,%%sr"
			  : "=d"(__level), "=d"(__tmpsr) : "1"(0x700));

    __result = *__mem;
    *__mem = __result + __val;
    __asm__ __volatile__ ("move%.w %0,%%sr" : : "d"(__level));

    return __result;
  }

#else

  template<int __inst>
    struct _Atomicity_lock
    {
      static volatile unsigned char _S_atomicity_lock;
    };

  template<int __inst>
  volatile unsigned char _Atomicity_lock<__inst>::_S_atomicity_lock = 0;

  template volatile unsigned char _Atomicity_lock<0>::_S_atomicity_lock;

  _Atomic_word
  __attribute__ ((__unused__))
  __exchange_and_add(volatile _Atomic_word* __mem, int __val)
  {
    _Atomic_word __result;

    // bset with no immediate addressing (not SMP-safe)
#if defined(__mcf5200__) || defined(__mcf5300__)
    __asm__ __volatile__("1: bset.b #7,%0@\n\tjbne 1b"
			 : /* no outputs */
			 : "a"(&_Atomicity_lock<0>::_S_atomicity_lock)
			 : "cc", "memory");

    // CPU32 and MCF5400 support test-and-set (SMP-safe).
#elif defined(__mcpu32__) || defined(__mcf5400__)
    __asm__ __volatile__("1: tas %0\n\tjbne 1b"
			 : "+m"(_Atomicity_lock<0>::_S_atomicity_lock)
			 : /* none */
			 : "cc");

    // Use bset with immediate addressing for 68000/68010 (not SMP-safe)
    // NOTE: TAS is available on the 68000, but unsupported by some Amiga
    // memory controllers.
#else
    __asm__ __volatile__("1: bset.b #7,%0\n\tjbne 1b"
			 : "+m"(_Atomicity_lock<0>::_S_atomicity_lock)
			 : /* none */
			 : "cc");
#endif

    __result = *__mem;
    *__mem = __result + __val;

    _Atomicity_lock<0>::_S_atomicity_lock = 0;

    return __result;
  }

#endif /* TAS / BSET */

  void
  __attribute__ ((__unused__))
  __atomic_add(volatile _Atomic_word* __mem, int __val)
  {
    // Careful: using add.l with a memory destination is not
    // architecturally guaranteed to be atomic.
    __exchange_and_add(__mem, __val);
  }

_GLIBCXX_END_NAMESPACE


text:
/*
 * Display output of Geiger counter in numeric format
 *
 * @author Edouard Lafargue, ed@lafargue.name
 */

define(function (require) {
    "use strict";

    var $ = require('jquery'),
        _ = require('underscore'),
        Backbone = require('backbone'),
        utils = require('app/utils'),
        template = require('js/tpl/instruments/onyx/OnyxNumView.js');

    return Backbone.View.extend({

        initialize: function (options) {
            this.sessionStartStamp = new Date().getTime();
            this.maxreading = 0;
            this.minreading = -1;
            this.valid = false;
            this.validinit = false;
            linkManager.on('input', this.showInput, this);
        },

        events: {},

        render: function () {
            var self = this;
            console.log('Main render of Onyx numeric view');
            this.$el.html(template());
            // We may need to force the Live view to resize the map at this
            // stage, because we just changed the size of the numview
            if (instrumentManager.liveViewRef() && instrumentManager.liveViewRef().rsc) {
                instrumentManager.liveViewRef().rsc();
            };

            return this;
        },

        onClose: function () {
            console.log("Onyx numeric view closing...");
            linkManager.off('input', this.showInput, this);
        },

        showInput: function (data) {

            if (typeof (data.devicetag) != 'undefined')
                $('#devicetag', this.el).html(data.devicetag);

            if (typeof (data.cpm) == 'undefined')
                return;
            var cpm = parseFloat(data.cpm.value);
            var usv = parseFloat(data.cpm.usv);
            var count = parseInt(data.cpm.count);
            $('#livecpm', this.el).html(cpm.toFixed(0));
            if (usv) {
                $('#liveusvh', this.el).html(usv.toFixed(3) + " μSv/h");
            }

            if (data.loc_status && data.loc_status == 'OK') {
                var coord = utils.coordToString({
                    lat: data.loc.coords.latitude,
                    lng: data.loc.coords.longitude
                });
                $('#lat', this.el).html(coord.lat);
                $('#lon', this.el).html(coord.lng);
            } else if (data.loc_status) {
                $('#lat', this.el).html('GPS: ' + data.loc_status);
                $('#lon', this.el).html('');
            }

            if (data.cpm.valid)
                $('#readingvalid', this.el).removeClass('label-danger').addClass('label-success').html('VALID');
            else
                $('#readingvalid', this.el).removeClass('label-success').addClass('label-danger').html('INVALID');

            if (count) {
                $('#count', this.el).html(count);
            }

            // Update statistics:

            // Removed for now, not very interesting
            /**
            var sessionDuration = (new Date().getTime() - this.sessionStartStamp) / 1000;
            $('#sessionlength', this.el).html(utils.hms(sessionDuration));

            if (cpm > this.maxreading) {
                this.maxreading = cpm;
                $('#maxreading', this.el).html(cpm);
            }
            if (cpm < this.minreading || this.minreading == -1) {
                this.minreading = cpm;
                $('#minreading', this.el).html(cpm);
            }
            **/

        },

    });
});


text:
Toggles

      <input type="checkbox">

      <input type="checkbox">

{% highlight html %}

  <input type="checkbox">

  <input type="checkbox">

{% endhighlight %}


text:
from distutils.core import setup

setup(
    name='telegram_nano',
    version='1.0',
    packages=['telegram_nano'],
    dependency_links=['git+https://github.com/Pasha13666/nano_api.git'],
    license='MIT',
    author='Pasha__kun',
    url='https://github.com/Pasha13666/telegram_nano',
    description='API bindings for telegram.org with nano_api'
)


text:
import * as XrmMock from "../xrm-mock/index";

export default class WebApi {
  public static createApi(clientContext: Xrm.ClientContext): XrmMock.WebApiMock {
    const offlineApi = this.createOfflineApi();
    const onlineApi = this.createOnlineApi(offlineApi);
    const api = new XrmMock.WebApiMock(clientContext, onlineApi, offlineApi);
    return api;
  }

  private static createOfflineApi(): XrmMock.WebApiOfflineMock {
    const offlineApi = new XrmMock.WebApiOfflineMock();
    return offlineApi;
  }

  private static createOnlineApi(offlineApi: Xrm.WebApiOffline): XrmMock.WebApiOnlineMock {
    const onlineApi = new XrmMock.WebApiOnlineMock(offlineApi);
    return onlineApi;
  }
}


text:
// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.

import { IWidgetTracker } from '@jupyterlab/apputils';
import { Token } from '@lumino/coreutils';
import { MarkdownDocument } from './widget';

/**
 * The markdownviewer tracker token.
 */
export const IMarkdownViewerTracker = new Token<IMarkdownViewerTracker>(
  '@jupyterlab/markdownviewer:IMarkdownViewerTracker'
);

/**
 * A class that tracks markdown viewer widgets.
 */
export interface IMarkdownViewerTracker
  extends IWidgetTracker<MarkdownDocument> {}


text:
void CActiveMasternode::ManageStatus()
{
    std::string errorMessage;

    if(!fMasterNode) return;

    if (fDebug) LogPrintf("CActiveMasternode::ManageStatus() - Begin\n");

    //need correct blocks to send ping
    if(Params().NetworkID() != CBaseChainParams::REGTEST && !masternodeSync.IsBlockchainSynced()) {
        status = ACTIVE_MASTERNODE_SYNC_IN_PROCESS;
        LogPrintf("CActiveMasternode::ManageStatus() - %s\n", GetStatus());
        return;
    }

    if(status == ACTIVE_MASTERNODE_SYNC_IN_PROCESS) status = ACTIVE_MASTERNODE_INITIAL;

    if(status == ACTIVE_MASTERNODE_INITIAL) {
        CMasternode *pmn;
        pmn = mnodeman.Find(pubKeyMasternode);
        if(pmn != NULL) {
            pmn->Check();
            if(pmn->IsEnabled() && pmn->protocolVersion == PROTOCOL_VERSION) EnableHotColdMasterNode(pmn->vin, pmn->addr);
        }
    }

    if(status != ACTIVE_MASTERNODE_STARTED) {

        // Set defaults
        status = ACTIVE_MASTERNODE_NOT_CAPABLE;
        notCapableReason = "";

        if(pwalletMain->IsLocked()){
            notCapableReason = "Wallet is locked.";
            LogPrintf("CActiveMasternode::ManageStatus() - not capable: %s\n", notCapableReason);
            return;
        }

        if(pwalletMain->GetBalance() == 0){
            notCapableReason = "Hot node, waiting for remote activation.";
            LogPrintf("CActiveMasternode::ManageStatus() - not capable: %s\n", notCapableReason);
            return;
        }

        if(strMasterNodeAddr.empty()) {
            if(!GetLocal(service)) {
                notCapableReason = "Can't detect external address. Please use the masternodeaddr configuration option.";
                LogPrintf("CActiveMasternode::ManageStatus() - not capable: %s\n", notCapableReason);
                return;
            }
        } else {
            service = CService(strMasterNodeAddr);
        }

        if(Params().NetworkID() == CBaseChainParams::MAIN) {
            if(service.GetPort() != 9340) {
                notCapableReason = strprintf("Invalid port: %u - only 9340 is supported on mainnet.", service.GetPort());
                LogPrintf("CActiveMasternode::ManageStatus() - not capable: %s\n", notCapableReason);
                return;
            }
        } else if(service.GetPort() == 9340) {
            notCapableReason = strprintf("Invalid port: %u - 9340 is only supported on mainnet.", service.GetPort());
            LogPrintf("CActiveMasternode::ManageStatus() - not capable: %s\n", notCapableReason);
            return;
        }

        LogPrintf("CActiveMasternode::ManageStatus() - Checking inbound connection to '%s'\n", service.ToString());

        if(!ConnectNode((CAddress)service, NULL, true)){
            notCapableReason = "Could not connect to " + service.ToString();
            LogPrintf("CActiveMasternode::ManageStatus() - not capable: %s\n", notCapableReason);
            return;
        }

        // Choose coins to use
        CPubKey pubKeyCollateralAddress;
        CKey keyCollateralAddress;

        if(pwalletMain->GetMasternodeVinAndKeys(vin, pubKeyCollateralAddress, keyCollateralAddress)) {

            if(GetInputAge(vin) < MASTERNODE_MIN_CONFIRMATIONS){
                status = ACTIVE_MASTERNODE_INPUT_TOO_NEW;
                notCapableReason = strprintf("%s - %d confirmations", GetStatus(), GetInputAge(vin));
                LogPrintf("CActiveMasternode::ManageStatus() - %s\n", notCapableReason);
                return;
            }

            LOCK(pwalletMain->cs_wallet);
            pwalletMain->LockCoin(vin.prevout);

            // send to all nodes
            CPubKey pubKeyMasternode;
            CKey keyMasternode;

            if(!legacySigner.SetKey(strMasterNodePrivKey, errorMessage, keyMasternode, pubKeyMasternode))
            {
                notCapableReason = "Error upon calling SetKey: " + errorMessage;
                LogPrintf("Register::ManageStatus() - %s\n", notCapableReason);
                return;
            }

            CMasternodeBroadcast mnb;
            if(!CMasternodeBroadcast::Create(vin, service, keyCollateralAddress, pubKeyCollateralAddress, keyMasternode, pubKeyMasternode, errorMessage, mnb)) {
                notCapableReason = "Error on CreateBroadcast: " + errorMessage;
                LogPrintf("Register::ManageStatus() - %s\n", notCapableReason);
                return;
            }

            //update to masternode list
            LogPrintf("CActiveMasternode::ManageStatus() - Update Masternode List\n");
            mnodeman.UpdateMasternodeList(mnb);

            //send to all peers
            LogPrintf("CActiveMasternode::ManageStatus() - Relay broadcast vin = %s\n", vin.ToString());
            mnb.Relay();

            LogPrintf("CActiveMasternode::ManageStatus() - Is capable master node!\n");
            status = ACTIVE_MASTERNODE_STARTED;

            return;
        } else {
            notCapableReason = "Could not find suitable coins!";
            LogPrintf("CActiveMasternode::ManageStatus() - %s\n", notCapableReason);
            return;
        }
    }

    //send to all peers
    if(!SendMasternodePing(errorMessage)) {
        LogPrintf("CActiveMasternode::ManageStatus() - Error on Ping: %s\n", errorMessage);
    }
}

std::string CActiveMasternode::GetStatus() const
{
    switch (status) {
    case ACTIVE_MASTERNODE_INITIAL: return "Node just started, not yet activated";
    case ACTIVE_MASTERNODE_SYNC_IN_PROCESS: return "Sync in progress. Must wait until sync is complete to start Masternode";
    case ACTIVE_MASTERNODE_INPUT_TOO_NEW: return strprintf("Masternode input must have at least %d confirmations", MASTERNODE_MIN_CONFIRMATIONS);
    case ACTIVE_MASTERNODE_NOT_CAPABLE: return "Not capable masternode: " + notCapableReason;
    case ACTIVE_MASTERNODE_STARTED: return "Masternode successfully started";
    default: return "unknown";
    }
}

bool CActiveMasternode::SendMasternodePing(std::string& errorMessage) {
    if(status != ACTIVE_MASTERNODE_STARTED) {
        errorMessage = "Masternode is not in a running status";
        return false;
    }

    CPubKey pubKeyMasternode;
    CKey keyMasternode;

    if(!legacySigner.SetKey(strMasterNodePrivKey, errorMessage, keyMasternode, pubKeyMasternode))
    {
        errorMessage = strprintf("Error upon calling SetKey: %s\n", errorMessage);
        return false;
    }

    LogPrintf("CActiveMasternode::SendMasternodePing() - Relay Masternode Ping vin = %s\n", vin.ToString());

    CMasternodePing mnp(vin);
    if(!mnp.Sign(keyMasternode, pubKeyMasternode))
    {
        errorMessage = "Couldn't sign Masternode Ping";
        return false;
    }

    // Update lastPing for our masternode in Masternode list
    CMasternode* pmn = mnodeman.Find(vin);
    if(pmn != NULL)
    {
        if(pmn->IsPingedWithin(MASTERNODE_PING_SECONDS, mnp.sigTime)){
            errorMessage = "Too early to send Masternode Ping";
            return false;
        }

        pmn->lastPing = mnp;
        mnodeman.mapSeenMasternodePing.insert(make_pair(mnp.GetHash(), mnp));

        //mnodeman.mapSeenMasternodeBroadcast.lastPing is probably outdated, so we'll update it
        CMasternodeBroadcast mnb(*pmn);
        uint256 hash = mnb.GetHash();
        if(mnodeman.mapSeenMasternodeBroadcast.count(hash)) mnodeman.mapSeenMasternodeBroadcast[hash].lastPing = mnp;

        mnp.Relay();

        return true;
    }
    else
    {
        // Seems like we are trying to send a ping while the Masternode is not registered in the network
        errorMessage = "Masternode List doesn't include our Masternode, shutting down Masternode pinging service! " + vin.ToString();
        status = ACTIVE_MASTERNODE_NOT_CAPABLE;
        notCapableReason = errorMessage;
        return false;
    }

}

// when starting a Masternode, this can enable to run as a hot wallet with no funds
bool CActiveMasternode::EnableHotColdMasterNode(const CTxIn& newVin, const CService& newService)
{
    if(!fMasterNode) return false;

    status = ACTIVE_MASTERNODE_STARTED;

    //The values below are needed for signing mnping messages going forward
    vin = newVin;
    service = newService;

    LogPrintf("CActiveMasternode::EnableHotColdMasterNode() - Enabled! You may shut down the cold daemon.\n");

    return true;
}


text:
import socket, time, os, math
from threading import Thread

TCP_IP = 'localhost'
TCP_PORT = 9002
BUFFER_SIZE = 1024

class ClientThread(Thread):

    def __init__(self,ip,port,sock):
        Thread.__init__(self)
        self.ip = ip
        self.port = port
        self.sock = sock
        print("New thread started for "+ ip + ":" + str(port))

    def run(self):
        filename='file.txt'
        filesize = os.path.getsize(filename)
        f = open(filename,'rb')
        count = 0
        print('Sending file size..')
        self.sock.send(str(filesize).encode())
        ack = self.sock.recv(1024) # wait for acknowledgement since send is non-blocking
        if not ack: raise Exception("File Size not received")
        print('Uploading file:')
        while True:
            l = f.read(BUFFER_SIZE)
            if not l:
                print("Uploaded 100%")
                print('Total size: {}'.format(count*BUFFER_SIZE))
                f.close()
                self.sock.close()
                break

            self.sock.send(l)
            count += 1
            if count % 1000 == 0:
                progress = math.ceil(100 * count * BUFFER_SIZE / filesize)
                print("Uploaded {}% to {}".format(progress, self.port))
                time.sleep(0.1) # for presentation purposes only

tcpsock = socket.socket()
tcpsock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
tcpsock.bind((TCP_IP, TCP_PORT))
tcpsock.listen(5)

while True:
    print("Waiting for incoming connections...")
    (conn, (ip,port)) = tcpsock.accept()
    print('Got connection from ', (ip,port))
    newthread = ClientThread(ip,port,conn)
    newthread.start()


text:
package com.zackehh.dotnotes;

import org.testng.annotations.Test;

import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotNull;

public class EscapeTest {

    @Test
    public void escapeUsingABasicKey() throws Exception {
        String escaped = DotNotes.escape("test");

        assertNotNull(escaped);
        assertEquals(escaped, "test");
    }

    @Test
    public void escapeUsingANumericKey() throws Exception {
        String escaped = DotNotes.escape("0");

        assertNotNull(escaped);
        assertEquals(escaped, "[\"0\"]");
    }

    @Test
    public void escapeUsingANumericKeyIndex() throws Exception {
        String escaped = DotNotes.escape(0);

        assertNotNull(escaped);
        assertEquals(escaped, "[0]");
    }

    @Test
    public void escapeUsingASpecialKey() throws Exception {
        String escaped = DotNotes.escape("my-test");

        assertNotNull(escaped);
        assertEquals(escaped, "[\"my-test\"]");
    }

    @Test
    public void escapeUsingASingleQuotedKey() throws Exception {
        String escaped = DotNotes.escape("'test'");

        assertNotNull(escaped);
        assertEquals(escaped, "[\"'test'\"]");
    }

    @Test
    public void escapeUsingADoubleQuotedKey() throws Exception {
        String escaped = DotNotes.escape("\"test\"");

        assertNotNull(escaped);
        assertEquals(escaped, "[\"\\\"test\\\"\"]");
    }

    @Test
    public void escapeUsingAnEmptyString() throws Exception {
        String escaped = DotNotes.escape("");

        assertNotNull(escaped);
        assertEquals(escaped, "[\"\"]");
    }

    @Test(expectedExceptions = ParseException.class, expectedExceptionsMessageRegExp = "Unexpected non-string value provided!")
    public void throwErrorAgainst () throws Exception {
        DotNotes.escape((NotedKey) null);
    }

}


text:
{{'SHIPMENT-CAPTURE-COMPONENT_TITLE' | translate}}

    <form name="form" [formGroup]="shipmentCaptureForm" class="shipment-capture-form">

{{'SHIPMENT-RESOURCE_SENDER' | translate}}

                                <button pButton type="button" (click)="createNewCustomer()"
                                        label="{{'GENERIC_NEW' | translate}}"></button>

{{'SHIPMENT-RESOURCE_SENDER-ADDRESS' | translate}}

                                {{'SHIPMENT-RESOURCE_SENDER-STREET-NUMBER' | translate}}

                                <input pInputText
                                       disabled="true"
                                       [(ngModel)]="senderStreet"
                                       [ngModelOptions]="{standalone: true}"
                                       id="shipment-capture-component_sender-street"
                                >

                                <input pInputText
                                       disabled="true"
                                       id="shipment-capture-component_sender-street_number"
                                       [ngModel]="senderStreetNo"
                                       [ngModelOptions]="{standalone: true}"
                                >

                                {{'SHIPMENT-RESOURCE_SENDER-ZIPCODE-CITY' | translate}}

                                <input pInputText
                                       disabled="true"
                                       [ngModel]="senderZipCode"
                                       [ngModelOptions]="{standalone: true}"
                                       id="shipment-capture-component_sender-zipcode"
                                >

                                <input pInputText
                                       disabled="true"
                                       [ngModel]="senderCity"
                                       [ngModelOptions]="{standalone: true}"
                                       id="shipment-capture-component_sender-city"
                                >

{{'SHIPMENT-RESOURCE_RECEIVER' | translate}}

                                <button pButton type="button" (click)="createNewCustomer()"label="{{'GENERIC_NEW' | translate}}"></button>

{{'SHIPMENT-RESOURCE_RECEIVER-ADDRESS' | translate}}

                                {{'SHIPMENT-RESOURCE_RECEIVER-STREET-NUMBER' | translate}}

                                <input pInputText
                                       [ngModel]="receiverStreet"
                                       disabled="true"
                                       [ngModelOptions]="{standalone: true}"
                                       id="shipment-capture-component_receiver-street"
                                >

                                <input pInputText
                                       disabled="true"
                                       id="shipment-capture-component_receiver-street_number"
                                       [ngModel]="receiverStreetNo"
                                       [ngModelOptions]="{standalone: true}"
                                >

                                {{'SHIPMENT-RESOURCE_RECEIVER-ZIPCODE-CITY' | translate}}

                                <input pInputText
                                       disabled="true"
                                       [ngModel]="receiverZipCode"
                                       [ngModelOptions]="{standalone: true}"
                                       id="shipment-capture-component_receiver-zipcode"
                                >

                                <input pInputText
                                       disabled="true"
                                       [ngModel]="receiverCity"
                                       [ngModelOptions]="{standalone: true}"
                                       id="shipment-capture-component_receiver-city"
                                >

{{'SHIPMENT-RESOURCE_NUMBER-OF_PACKETS' | translate}}

                            <input pInputText formControlName="numberPackages"
                                   id="shipment-capture-component_cargo_amount-packages"
                            >

{{'SHIPMENT-RESOURCE_TOTAL-WEIGHT' | translate}}

                            <input pInputText formControlName=totalWeight
                                   id="shipment-capture-component_cargo_weight"
                            >

{{'SHIPMENT-RESOURCE_TOTAL-VOLUME' | translate}}

                            <input pInputText formControlName="totalCapacity"
                                   id="shipment-capture-component_cargo_volume"
                            >

{{'TASK-RESOURCE_DESCRIPTION' | translate}}

                            <textarea pInputTextarea
                                      rows="10"
                                      cols="45"
                                      formControlName="cargoDescription"
                                      id="shipment-capture-component_cargo_description"></textarea>

{{'SHIPMENT-RESOURCE_DANGEROUS-GOODS' | translate}}

                            {{'SHIPMENT-RESOURCE_PRE-CARRIAGE' | translate}}

                            {{'SHIPMENT-RESOURCE_EXPORT-INSURANCE' | translate}}

                            {{'SHIPMENT-RESOURCE_EXPORT-CUSTOMS' | translate}}

                            {{'SHIPMENT-RESOURCE_FLIGHT' | translate}}

                            {{'SHIPMENT-RESOURCE_ON-CARRIAGE' | translate}}

                            {{'SHIPMENT-RESOURCE_IMPORT-INSURANCE' | translate}}

                            {{'SHIPMENT-RESOURCE_IMPORT-CUSTOMS' | translate}}

                <button pButton type="button" (click)="cancel()" label="{{'GENERIC_CANCEL' | translate}}"></button>

                <button pButton type="button" (click)="createShipment()"
                        label="{{'GENERIC_CREATE' | translate}}" [disabled]="!shipmentCaptureForm.valid"></button>

    </form>


text:
<?php

namespace Pitech\FiltersBundle\Filters;

use Doctrine\ORM\QueryBuilder;

interface FilterInterface
{
    const NUMERIC_FILTER = 'numeric_filter';
    const NUMERIC_INTERVAL_FILTER = 'numeric_interval_filter';
    const STRING_FILTER = 'string_filter';
    const OR_STRING_FILTER = 'or_string_filter';
    const DATE_FILTER = 'date_filter';
    const DATE_INTERVAL_FILTER = 'date_interval_filter';
    const DATE_CHECK_FILTER = 'date_check_filter';
    const CHECK_FILTER = 'check_filter';

    /**
     * Set the entity attribute on which the filter should be applied.
     *
     * @param string $attribute
     */
    public function setAttribute($attribute);

    /**
     * Returns the entity attribute corresponding to the filter.
     *
     * @return string
     */
    public function getAttribute();

    /**
     * Set the filters' expression.
     *
     * @param string $expression
     */
    public function setExpression($expression);

    /**
     * Get the filters' expression.
     *
     * @return string
     */
    public function getExpression();

    /**
     * Set the value to filter by.
     *
     * @param mixed $value
     */
    public function setValue($value);

    /**
     * Get the value to filter by.
     *
     * @return mixed
     */
    public function getValue();

    /**
     * Add a filter option given as string.
     *
     * @param string $option
     */
    public function addOption($option);

    /**
     * Return true if a filter has the option given as string, null otherwise.
     *
     * @param string $option
     *
     * @return bool
     */
    public function hasOption($option);

    /**
     * Retrieve the filter options given as array.
     *
     * @return array $options
     */
    public function getOptions();

    /**
     * Adds a DQL clause to the received query builder object with given
     * parameters, and returns the query builder object.
     *
     * @param QueryBuilder $qb
     * @param string       $alias
     *
     * @return QueryBuilder
     */
    public function getDQLExpression($qb, $alias);

    /**
     * Returns filter type.
     *
     * @return string
     */
    public function getType();
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

  <meta http-equiv="content-type" content="text/html; charset=utf-8" />
  <title>Comment post not allowed (400)</title>
  <meta name="robots" content="NONE,NOARCHIVE" />

Comment post not allowed (400)

        Why:
        {{ why }}

    The comment you tried to post to this view wasn't saved because something
    tampered with the security information in the comment form. The message
    above should explain the problem, or you can check the comment
    documentation for more help.

      You're seeing this error because you have DEBUG = True in
      your Django settings file. Change that to False, and Django
      will display a standard 400 error page.


text:
<!DOCTYPE html>
<!--
- Copyright (C) 2012 David Geary. This code is from the book
- Core HTML5 Canvas, published by Prentice-Hall in 2012.
-
- License:
-
- 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 may not be used to create training material of any sort,
- including courses, books, instructional videos, presentations, etc.
- without the express written consent of David Geary.
-
- 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.
-->

	<head>
	  <title>Scrolling Backgrounds</title>

		<style>
		   body {
				background: #dddddd;
			}

			#canvas {
            position: absolute;
            top: 30px;
            left: 10px;
            background: #ffffff;
            cursor: crosshair;
            margin-left: 10px;
            margin-top: 10px;
            -webkit-box-shadow: 4px 4px 8px rgba(0,0,0,0.5);
            -moz-box-shadow: 4px 4px 8px rgba(0,0,0,0.5);
            box-shadow: 4px 4px 8px rgba(0,0,0,0.5);
			}

         input {
            margin-left: 15px;
			}

		</style>
   </head>

  <body>
    <canvas id='canvas' width='1024' height='512'>
      Canvas not supported
    </canvas>

    <input id='animateButton' type='button' value='Animate'/>

    <script src='../../shared/js/requestNextAnimationFrame.js'></script>
    <script src='example.js'></script>
  </body>
</html>


text:
//
// RemotePhotoTool - remote camera control software
// Copyright (C) 2008-2020 Michael Fink
//
/// \file ViewFinderImageWindow.cpp Viewfinder image window
//
#include "stdafx.h"
#include "ViewFinderImageWindow.hpp"
#include "Viewfinder.hpp"
#include "JpegMemoryReader.hpp"
#include "Logging.hpp"

/// ratio to draw lines for "golden ratio" mode
const double c_dGoldenRatio = 0.618;

/// number of milliseconds until zebra pattern is moved to the right
const unsigned int c_uiZebraPatternMovementInMs = 300;

ViewFinderImageWindow::ViewFinderImageWindow()
:m_uiResX(0),
 m_uiResY(0),
 m_viewfinderImageCount(0),
 m_enLinesMode(linesModeNoLines),
 m_bShowZebraPattern(false),
 m_bShowHistogram(false)
{
   m_zebraPatternTimer.Start();
   SetupZebraBrush();
}

ViewFinderImageWindow::~ViewFinderImageWindow()
{
   m_brushZebraPattern.DeleteObject();
}

void ViewFinderImageWindow::SetOutputType(Viewfinder::T_enOutputType enOutputType)
{
   m_spViewfinder->SetOutputType(enOutputType);
}

void ViewFinderImageWindow::EnableUpdate(bool bEnable)
{
   if (bEnable)
   {
      m_viewfinderImageCount = 0;
      m_frameCountTimer.Reset();
      m_frameCountTimer.Start();

      if (m_spViewfinder != nullptr)
         m_spViewfinder->SetAvailImageHandler(
            std::bind(&ViewFinderImageWindow::OnAvailViewfinderImage, this, std::placeholders::_1));
   }
   else
   {
      m_frameCountTimer.Stop();

      m_spViewfinder->SetAvailImageHandler();
   }
}

void ViewFinderImageWindow::SetViewfinder(std::shared_ptr<Viewfinder> spViewfinder)
{
   if (spViewfinder == nullptr && m_spViewfinder != nullptr)
   {
      m_spViewfinder->SetAvailImageHandler();
      SetBitmap(NULL);
   }

   m_spViewfinder = spViewfinder;

   if (spViewfinder != nullptr)
      EnableUpdate(true);
}

void ViewFinderImageWindow::OnAvailViewfinderImage(const std::vector<BYTE>& vecImage)
{
   if (m_spViewfinder == nullptr)
      return;

   if (vecImage.empty())
      return;

   DecodeJpegImage(vecImage);

   if (IsWindow())
      PostMessage(WM_VIEWFINDER_AVAIL_IMAGE);
}

LRESULT ViewFinderImageWindow::OnMessageViewfinderAvailImage(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)
{
   CBitmapHandle bmp;

   ReadBitmap(bmp);
   SetBitmap(bmp);

   // invalidate control to force redraw
   Invalidate();

   TraceViewfinderFps();

   return 0;
}

void ViewFinderImageWindow::SetupZebraBrush()
{
   const WORD c_bitsZebraPatternBrush[8] = { 0x9f, 0x3f, 0x7e, 0xfc, 0xf9, 0xf3, 0xe7, 0xcf };

   CBitmap bmZebraPattern;
   bmZebraPattern.CreateBitmap(8, 8, 1, 1, c_bitsZebraPatternBrush);

   LOGBRUSH logBrush = { 0 };
   logBrush.lbStyle = BS_PATTERN;
   logBrush.lbHatch = (ULONG_PTR)bmZebraPattern.m_hBitmap;
   logBrush.lbColor = RGB(192, 192, 192);

   m_brushZebraPattern.CreateBrushIndirect(&logBrush);
}

void ViewFinderImageWindow::DecodeJpegImage(const std::vector<BYTE>& vecImage)
{
   //DWORD dwStart = GetTickCount();
   JpegMemoryReader jpegReader(vecImage);

   try
   {
      jpegReader.Read();
   }
   catch (...)
   {
      static bool s_bWarnedAboutJPEG = false;
      if (!s_bWarnedAboutJPEG)
      {
         LOG_TRACE(_T("DecodeJpegImage: failed loading JPEG!\n"));
         s_bWarnedAboutJPEG = true;
      }
      return;
   }

   //DWORD dwEnd = GetTickCount();
   //ATLTRACE(_T("decoding jpg took %u ms\n"), dwEnd - dwStart);

   std::vector<BYTE>& vecBitmapData = jpegReader.BitmapData();

   JpegImageInfo imageInfo = jpegReader.ImageInfo();

   {
      LightweightMutex::LockType lock(m_mtxViewfinderData);
      std::swap(m_vecCurrentViewfinderData, vecBitmapData);

      m_uiResX = imageInfo.Width();
      m_uiResY = imageInfo.Height();
   }
}

void ViewFinderImageWindow::MakeOverexposedTransparent(std::vector<BYTE>& vecBitmapData)
{
   ATLASSERT((vecBitmapData.size() % 3) == 0);

   size_t uiValues = vecBitmapData.size() / 3;

   // 0xff means fully opaque
   std::vector<BYTE> vecTransparentBitmapData(uiValues * 4, 0xff);

   for (size_t ui = 0; ui < uiValues; ui++)
   {
      memcpy(&vecTransparentBitmapData[ui * 4], &vecBitmapData[ui * 3], 3);

      if (vecBitmapData[ui * 3 + 0] == 0xff ||
          vecBitmapData[ui * 3 + 1] == 0xff ||
          vecBitmapData[ui * 3 + 2] == 0xff)
      {
         vecTransparentBitmapData[ui * 4 + 3] = 0; // make transparent
      }
   }

   vecBitmapData.swap(vecTransparentBitmapData);
}

void ViewFinderImageWindow::ReadBitmap(CBitmapHandle& bmp)
{
   BITMAPINFO bi = {0};

   BITMAPINFOHEADER& bih = bi.bmiHeader;
   bih.biSize = sizeof(bih);
   bih.biBitCount = 24;
   bih.biClrUsed = 0;
   bih.biCompression = BI_RGB;
   bih.biPlanes = 1;

   bih.biHeight = -static_cast<LONG>(m_uiResY); // negative, since bytes represent a top-bottom DIB
   bih.biWidth = m_uiResX;

   BITMAPINFOHEADER* lpbmih = &bih;
   BITMAPINFO* lpbmi = &bi;

   {
      LightweightMutex::LockType lock(m_mtxViewfinderData);

      LPCVOID lpDIBBits = m_vecCurrentViewfinderData.data();

      CClientDC dc(m_hWnd);
      bmp.CreateDIBitmap(dc, lpbmih, CBM_INIT, lpDIBBits, lpbmi, DIB_RGB_COLORS);
   }
}

void ViewFinderImageWindow::SetBitmap(CBitmapHandle bmpViewfinder)
{
   m_bmpViewfinder = bmpViewfinder;
}

void ViewFinderImageWindow::TraceViewfinderFps()
{
   m_viewfinderImageCount++;

   if (m_frameCountTimer.Elapsed() > 0.5)
   {
      CString cszText;
      cszText.Format(_T("Viewfinder: %3.1f fps"), m_viewfinderImageCount / m_frameCountTimer.Elapsed());
      ATLTRACE(_T("%s\n"), cszText.GetString());

      m_viewfinderImageCount = 0;

      m_frameCountTimer.Restart();
   }
}

void ViewFinderImageWindow::ScaleBitmapSize(const BITMAP& bm, int& iWidth, int& iHeight)
{
   CRect rcWindow;
   GetClientRect(rcWindow);

   double dRatioWindow = rcWindow.Height() == 0 ? 1.0 : (double(rcWindow.Width()) / rcWindow.Height());
   double dRatioBitmap = bm.bmHeight == 0 ? 1.0 : (double(bm.bmWidth) / bm.bmHeight);

   if (dRatioBitmap < dRatioWindow)
      iWidth = int(iHeight * dRatioBitmap);
   else
      iHeight = int(iWidth / dRatioBitmap);
}

void ViewFinderImageWindow::DrawLines(CDC& dc, int iWidth, int iHeight)
{
   // pen color is the inverse of the background color
   int iLastDrawMode = dc.SetROP2(R2_NOTXORPEN);

   CPen pen;
   pen.CreatePen(PS_DOT, 3, RGB(0, 0, 0));
   CPenHandle oldPen = dc.SelectPen(pen);

   double dRatio1 = 1.0 / 3.0;
   if (m_enLinesMode == linesModeGoldenRatio)
      dRatio1 = c_dGoldenRatio;

   double dRatio2 = 1.0 - dRatio1;

   // horizontal lines
   dc.MoveTo(0, int(iHeight * dRatio1));
   dc.LineTo(iWidth-1, int(iHeight * dRatio1));

   dc.MoveTo(0, int(iHeight * dRatio2));
   dc.LineTo(iWidth-1,int(iHeight * dRatio2));

   // vertical lines
   dc.MoveTo(int(iWidth * dRatio1), 0);
   dc.LineTo(int(iWidth * dRatio1), iHeight-1);

   dc.MoveTo(int(iWidth * dRatio2), 0);
   dc.LineTo(int(iWidth * dRatio2), iHeight-1);

   dc.SelectPen(oldPen);

   dc.SetROP2(iLastDrawMode);
}

void ViewFinderImageWindow::DrawZebraPattern(CDC& dc, int iWidth, int iHeight)
{
   // draw zebra pattern
   HBRUSH hOldBrush = dc.SelectBrush(m_brushZebraPattern);

   dc.SetBkMode(TRANSPARENT);
   dc.SetBkColor(RGB(255, 255, 255));

   // in order to move zebra pattern, set pattern brush origin
   double elapsedMs = m_zebraPatternTimer.Elapsed() * 1000.0;
   int iOffset = (unsigned int)(elapsedMs / c_uiZebraPatternMovementInMs) % 8;
   dc.SetBrushOrg(iOffset, 0);

   CRect rcImage(CPoint(0, 0), CSize(iWidth, iHeight));
   dc.Rectangle(&rcImage);

   dc.SelectBrush(hOldBrush);
}

LRESULT ViewFinderImageWindow::OnEraseBkgnd(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)
{
   // disable erasing
   return FALSE;
}

LRESULT ViewFinderImageWindow::OnPaint(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)
{
   CPaintDC dc(m_hWnd);

   if (m_bmpViewfinder.IsNull())
   {
      dc.FillSolidRect(&dc.m_ps.rcPaint, RGB(0,0,0));
      return 0;
   }

   // calculate bitmap size
   BITMAP bm = {0};
   GetObject(m_bmpViewfinder, sizeof(bm), &bm);

   CRect rcPaint(dc.m_ps.rcPaint);

   int iWidth = rcPaint.Width();
   int iHeight = rcPaint.Height();

   ScaleBitmapSize(bm, iWidth, iHeight);

   rcPaint = CRect(0, 0, iWidth, iHeight);

   // select bitmap into bitmap DC
   CDC bmpDC;
   bmpDC.CreateCompatibleDC();

   HBITMAP hbmT = bmpDC.SelectBitmap(m_bmpViewfinder);

   // draw to memory DC
   CMemoryDC memDC(dc, dc.m_ps.rcPaint);
   memDC.FillSolidRect(&dc.m_ps.rcPaint, ::GetSysColor(COLOR_3DFACE));

   // blit bitmap
   if (m_bShowZebraPattern)
   {
      DrawZebraPattern(memDC, iWidth, iHeight);

      // draw viewfinder bitmap with transparency
      memDC.TransparentBlt(0, 0, iWidth, iHeight, bmpDC, 0, 0, bm.bmWidth, bm.bmHeight, RGB(255,255,255));
   }
   else
   {
      memDC.SetStretchBltMode(COLORONCOLOR);
      memDC.StretchBlt(0, 0, iWidth, iHeight, bmpDC, 0, 0, bm.bmWidth, bm.bmHeight, SRCCOPY);
   }

   bmpDC.SelectBitmap(hbmT);

   // draw lines
   if (m_enLinesMode != linesModeNoLines)
      DrawLines(memDC, iWidth, iHeight);

   return 0;
}

LRESULT ViewFinderImageWindow::OnDestroy(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)
{
   if (m_spViewfinder != nullptr)
   {
      m_spViewfinder->SetAvailImageHandler();
      m_spViewfinder.reset();
   }

   return 0;
}


text:
var LayoutDelegator = (function() {

    var ld = {
            delegate : null
    };

    ld.bind = function(delegate) {
        ld.delegate = delegate;
    }

    ld.draw = function() {
        ld.delegate.draw();
    }

    ld.addOverlay = function(overlay) {
        ld.delegate.addOverlay(overlay);
        ld.delegate.draw();
    }

    ld.removeOverlay = function(overlay) {
        ld.delegate.removeOverlay(overlay);
        ld.delegate.draw();
    }

    return ld;
}());


text: simple content


text:
<?php

namespace ONGR\SettingsBundle\Document;

use JsonSerializable;
use ONGR\ElasticsearchBundle\Annotation as ES;
use ONGR\ElasticsearchBundle\Document\DocumentInterface;
use ONGR\ElasticsearchBundle\Document\DocumentTrait;

/**
 * Stores admin settings.
 *
 * @ES\Document(type="setting")
 */
class Setting implements DocumentInterface, JsonSerializable
{
    use DocumentTrait;

    /**
     * @const TYPE_STRING setting model of string type
     */
    const TYPE_STRING = 'string';

    /**
     * @const TYPE_ARRAY setting model of array type
     */
    const TYPE_ARRAY = 'array';

    /**
     * @const TYPE_BOOLEAN setting model of boolean type
     */
    const TYPE_BOOLEAN = 'bool';

    /**
     * @const TYPE_OBJECT setting model of object type
     */
    const TYPE_OBJECT = 'object';

    /**
     * @var string
     *
     * @ES\Property(name="name", type="string", search_analyzer="standard")
     */
    protected $name;

    /**
     * @var string
     *
     * @ES\Property(name="description", type="string", search_analyzer="standard")
     */
    protected $description;

    /**
     * @var string
     *
     * @ES\Property(name="profile", type="string", search_analyzer="standard")
     */
    protected $profile;

    /**
     * @var string
     *
     * @ES\Property(name="type", type="string", search_analyzer="standard")
     */
    protected $type;

    /**
     * @var string
     *
     * @ES\Property(name="data", type="string", search_analyzer="standard")
     */
    protected $data;

    /**
     * Get data.
     *
     * @return string
     */
    public function getData()
    {
        return $this->data;
    }

    /**
     * Set data.
     *
     * @param string $data
     */
    public function setData($data)
    {
        $this->data = $data;
    }

    /**
     * Get type.
     *
     * @return string
     */
    public function getType()
    {
        return $this->type;
    }

    /**
     * Set type.
     *
     * @param string $type
     */
    public function setType($type)
    {
        $this->type = $type;
    }

    /**
     * Get profile.
     *
     * @return string
     */
    public function getProfile()
    {
        return $this->profile;
    }

    /**
     * Set profile.
     *
     * @param string $profile
     */
    public function setProfile($profile)
    {
        $this->profile = $profile;
    }

    /**
     * Get description.
     *
     * @return string
     */
    public function getDescription()
    {
        return $this->description;
    }

    /**
     * Set description.
     *
     * @param string $description
     */
    public function setDescription($description)
    {
        $this->description = $description;
    }

    /**
     * Get name.
     *
     * @return string
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * Set name.
     *
     * @param string $name
     */
    public function setName($name)
    {
        $this->name = $name;
    }

    /**
     * Specify data which should be serialized to JSON.
     *
     * @return data which can be serialized by <b>json_encode</b>,
     */
    public function jsonSerialize()
    {
        return [
            'name' => $this->getName(),
            'description' => $this->getDescription(),
            'profile' => $this->getProfile(),
            'type' => $this->getType(),
            'data' => $this->getData(),
            'id' => $this->getId(),
            'score' => $this->getScore(),
            'parent' => $this->getParent(),
            'ttl' => $this->getTtl(),
            'highlight' => $this->highlight,
        ];
    }
}


text:
using Catalog.Data;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace Catalog.Service
{
    public class CatalogViewModel
    {
        public Catalogue Catalog { get; set; }
        public Category CurrentCategory { get; set; }
        public List<Product> Products { get; set; }
        public long TotalPages { get; set; }
        public long TotalItems { get; set; }

        public int CurrentPage { get; set; }

        public int ItemsPerPage { get; set; }
    }
}