text:
var datatypes = {};
try{ datatypes = exports } catch(e) {}; // Try to export the lib for node.js
(function(self) {

// Name for special classes that datatypes-js recognise. An objects class can  be
// determind by reading the _dtclass property.
var OPTION = 'option',
    DATATYPE = 'datatype',
    STRUCT = 'struct',
    POINTER = 'pointer';

// Special data sizes.
var FLEX_DATASIZE = -2;
var DEFINED_DATASIZE = -1;

// Collections of datatypes and other constants.
var DATATYPES = {},
    CONSTANTS = {}

// Converts ´´arguments´´ into an array.
function get_array(args) {
    return Array.prototype.slice.call(args);
}

// Defines a new datatype with specified options.
//
//  datasize -  The size of the datatype. Valid values are positive integers
//              or one of the following constants:
//
//              FLEX_DATASIZE
//              The decoder decides when to stop read from buffer
//
//              DEFINED_DATASIZE
//              The size is user defined.
//
//  "choice" -  Optional. This indicates that the following two callbacks are
//              encoder/decoder chooser's rather than a real encoder/decoder. A
//              chooser callback is called takes one argument, the option set,
//              and should return the encoder/decoder based on that.
//
//  encoder  -  The encoder to use for the datatype. The encoder is a callback
//              that takes one argument. The encoder should always return an
//              array with bytes.
//
//              function(value) {
//                  var result = tobytes(value) // Encode value to bytes.
//                  return result;
//              }
//
//  decoder  -  The decoder to use for the datatype. The decoder is a callback
//              that takes two arguments. The first argument is a Buffer Pointer.
//
//              The second argument is the byte buffer to read from.
//
//              The third argument is the size of the datatype. This argument
//              will always contain the fixed datasize, for datatypes with
//              with specified size. The value will be undefined if the
//              datasize is declared as DATASIZE_CUSTOM. The argument has a
//              variable value if the datasize is declared as DATASIZE_DEFINE.
//
//              function(buffer, bp, length) {
//                  var result = 0;
//                  while(!bp.eof()) result += buffer(bp.next());
//                  return result;
//              }
//
function define() {
    var args = get_array(arguments);
    return {
        _dtclass: DATATYPE,
        size: args.shift(),
        choose_callback: args[0] == 'choice' ? args.shift() == 'choice' : false,
        encoder: args.shift(),
        decoder: args.shift()
    }
}

// Helper fucntion for the struct constructor. Returns a new constant field.
function const_field(dt, value, name, opts) {
    var encoder = dt.choose_callback ? dt.encoder(null, opts) : dt.encoder,
        decoder = dt.choose_callback ? dt.decoder(null, null, null, opts) : dt.decoder;
    var decode, bytes = encoder(value, opts);

    var encode = function(values) {
        return bytes;
    }

    if(opts.no_error_check) {
        decode = function(buffer, pt) {
            pt.pos += bytes.length;
        }
    } else {
        decode = function(buffer, pt) {
            var result = decoder(buffer, pt, dt.size, opts);
            if(result != value) throw 'Decoding error: Struct[' + name + '] constant value does not match';
            return result;
        }
    }

    return {
        name: name,
        constant: true,
        encode: encode,
        decode: decode
    }
}

// Helper fucntion for the struct constructor. Returns a new dynamic field.
var DYNAMIC = { _dtstruct: 'custom_field', callback: function(dt, args, opts) {
    var name = args.shift();
    var encoder = dt.choose_callback ? dt.encoder(null, opts) : dt.encoder,
        decoder = dt.choose_callback ? dt.decoder(null, null, null, opts) : dt.decoder;

    var decode = function(buffer, pt) {
        var result = decoder(buffer, pt, dt.size, opts);
        return result;
    }

    return {
        name: name,
        constant: false,
        encode: encoder,
        decode: decode,
    }
}};

// Adds the struct size (in bytes) to the buffer after encoding
var STRUCT_SIZE = { _dtstruct: 'custom_field', callback: function(dt, args, opts) {
    if(dt != DATATYPES['int16'] && dt != DATATYPES['int32'] && dt != DATATYPES['byte']) {
        throw 'STRUCT_SIZE only supports int16, int32 and byte.';
    }
    var encoder = dt.choose_callback ? dt.encoder(null, opts) : dt.encoder,
        decoder = dt.choose_callback ? dt.decoder(null, null, null, opts) : dt.decoder;

    // We are building a temporary buffer spot for this value,
    var encode = function(value, opts) {
        return encoder(0, opts)
    }

    var decode = function(buffer, pt) {
        var result = decoder(buffer, pt, dt.size, opts);
        return result;
    }

    var after = function(buffer, pos) {
        // Calculate the total number of bytes in the generated buffer and
        // encode it to bytes. Then replace the
        var bytes = encoder(buffer.length, opts);
        var l = bytes.length;
        for(var i = 0; i<l; i++) buffer[pos + i] =  bytes[i];
        return buffer;
    }

    return {
        name: 'size',
        constant: true,
        after_encoding: after,
        encode: encode,
        decode: decode,
    }
}};

// Defines a new data structure. A datastructure is a set of datatypes, with
// a compiled call sequence to encoders and decoders.
function struct() {
    var args = get_array(arguments);
    var first, second, options = {}, fields = [];
    while(args.length) {
        first = args.shift();
        switch(first._dtclass) {
            case OPTION:
                first.callback(options, 'struct');
                break;
            case DATATYPE:
            case STRUCT:
                second = args.shift();
                if(second._dtstruct == 'custom_field') {
                    fields.push(second.callback(first, args, options));
                } else {
                    fields.push(const_field(first, second, '_index' + fields.length, options));
                }
                break;
            default:
                throw "Unexpected value at " + fields.length;
        }
    }

    function datastruct() {
        var args = get_array(arguments);
        return args.length == 1 && args[0].constructor != Array ?
               datastruct.from_dict(args[0]) :
               datastruct.from_array(args);
    }

    datastruct.from_array = function(values) {
        var result = [], l = fields.length, after_callbacks = [];
        for(var i = 0; i < l; i++) {
            var field = fields[i];
            var value = field.constant ? null : values.shift();
            var current_size  = result.length;
            result = result.concat(field.encode(value));
            if(field.after_encoding) {
                after_callbacks.push({ field: field, pos: current_size});
            }
        }
        if(after_callbacks.length) {
            var old_result = result.slice(0);
            result = [];
            for(var i=0; i<after_callbacks.length; i++) {
                var o = after_callbacks[i];
                result = result.concat(o.field.after_encoding(old_result, o.pos));
            }
        }
        return result;
    }

    datastruct.from_dict = function(values) {
        var result = [], l = fields.length, after_callbacks = [];
        for(var i = 0; i < l; i++) {
            var field = fields[i];
            var value = values[field.name];
            var current_size  = result.length;
            result = result.concat(field.encode(value));
            if(field.after_encoding) {
                after_callbacks.push({ field: field, pos: current_size});
            }
        }
        if(after_callbacks.length) {
            var old_result = result.slice(0);
            result = [];
            for(var i=0; i<after_callbacks.length; i++) {
                var o = after_callbacks[i];
                result = result.concat(o.field.after_encoding(old_result, o.pos));
            }
        }
        return result;
    }

    datastruct.to_array = function(buffer, pt) {
        var pt = pt || new BufferPointer(0, buffer.length),
            result = [],l = fields.length;
        for(var i = 0; i < l; i++) {
            result.push(fields[i].decode(buffer, pt));
        }
        return result;
    }

    datastruct.to_dict = function(buffer, pt) {
        var pt = pt || new BufferPointer(0, buffer.length),
            result = {}, field, l = fields.length;
        for(var i = 0; i < l; i++) {
            field = fields[i];
            result[field.name] = field.decode(buffer, pt);
        }
        return result;
    }

    return datastruct;
}

// Defines a new option. An option can give user-defined instructions while
// encoding and decoding datatypes. The option function takes one callback
// function.
//
// The callback function takes two arguments. The first argument is an option
// set, used by current encoder/decoder. The second argument is a String that
// represents the current mode. There is three modes: ´´encode´´, ´´decode´´ and
// ´´struct´´. THe option parser can choose to handle the request differently
// based on which mode.
//
//      function(options, mode) {
//          options.my_option = 1234
//      }
//
// Each datatype encoder and decoder function get's the generated option set.
//
// Built-in datatype's encoder's/decoder's ignores this option set.
//
function option(callback) {
    return {
        _dtclass: OPTION,
        callback: callback
    }
}

// Define's the BIG_ENDIAN option. This option sets the buffer byte-order to
// big-endian.
var BIG_ENDIAN = option( function(opts) { opts.little_endian = false } );

// Define's the LITTLE_ENDIAN option. This option sets the buffer byte-order to
// little-endian.
var LITTLE_ENDIAN = option( function(opts) { opts.little_endian = true } );

// Define's the NO_ERROR_CHECK option. This options is only valid on STRUCTS.
// This option will ignore to read all constant fields. The fields will not
// be matched against the original value. This option makes reading faster but
// less accurate.
var NO_ERROR_CHECK = option(
    function(opts, mode) {
        if(mode == 'struct') opts.no_error_check = true;
    }
);

// Define's the DICT option. This option tell's the decoder to return a dict
// with the decoded values.
var DICT = option(
    function(opts, mode) {
        if(mode == 'decode') opts.array_result = false;
    }
);

// Define's the ARRAY option. This option tell's the decoder to return an array
// with decoded values.
var ARRAY = option(
    function(opts, mode) {
        if(mode == 'decode') opts.array_result = true;
    }
);

// Initializes a new BufferPoint instance.
function BufferPointer(pos, buffer_length) {
    this.pos = pos;
    this.length = buffer_length;
}

BufferPointer.prototype = {
    _dtclass: POINTER,
    eof: function() { return !(this.pos < this.length) },
    next: function() { return this.pos++ },
}

// Define built-in encoders. An encoder takes two arguments: value and
// (optional) options. The value argument represents the Javascript object. The
// option argument is optional and contains a dict with user-defined options.
// It's possible to create new option handles by calling the option
// function.
//
// All built-in encoders can be accessd through the ENCODERS member in the
// exported module.
var ENCODERS = {

    // Encodes bytes. If the v argument is a number, then the number is wrapped
    // within an array. If not, the v argument is asumed to be an array with bytes.
    bytes: function(v) {
        return v.constructor === Number ? [v] : v;
    },

    // Returns an int16 encoder based on the bigendian option
    get_int16: function(v, opts) {
        return opts.little_endian ? ENCODERS.int16l : ENCODERS.int16;
    },

    // Encodes an Int16 into big-endian format.
    int16: function(v) {
        return [(v >> 8) & 0xff, (v & 0xff)];
    },

    // Encodes an Int16 into little-endian format.
    int16l: function(v) {
        return [(v & 0xff), (v >> 8) & 0xff];
    },

    // Returns an int32 encoder based on the bigendian option
    get_int32: function(v, opts) {
        return opts.little_endian ? ENCODERS.int32l : ENCODERS.int32;
    },

    // Encodes an Int32 into big-endian format.
    int32: function(v) {
        return [ (v >> 24) & 0xff, (v >> 16) & 0xff, (v >> 8) & 0xff, (v & 0xff) ];
    },

    // Encodes an Int32 into little-endian format.
    int32l: function (v) {
        return [ (v & 0xff), (v >> 8) & 0xff, (v >> 16) & 0xff, (v >> 24) & 0xff ];
    },

    // Encodes an 8-bit char-string.
    string8: function(v) {
        var result = [], l = v.length;
        for(var i = 0; i < l; i++) result.push(v.charCodeAt(i));
        return result;
    },

    // Encodes an 8-bit char null-terminated string.
    cstring: function(v) {
        return ENCODERS.string8(v).concat([0]);
    }

}

//  Define built-in decoders. A decoder is a callback for specified dataype. The
//  callback takes three arguments: buffer, pointer and length.
//
//      buffer  - The buffer is an Array with 1 or more bytes.
//      pointer - A BufferPointer instance. The instance points to the buffer
//                position to read from.
//      length  - The total length of the datatype. This argument SHOULD be
//                ignored by Datatypes with a fixed size.
//      options - OPTIONAL. A dict with user-defined options.
//
// All built-in decoders can be accessd through the ENCODERS member in the
// exported module.
var DECODERS = {

    // Decodes an byte array.
    bytes: function(buffer, pointer, length) {
        if(length == 1) return buffer[pointer.pos++];
        var pos = pointer.pos;
        pointer.pos += length;
        return buffer.slice(pos, length);
    },

    // Returns an int16 decoder based on the bigendian option
    get_int16: function(b, pt, l, opts) {
        return opts.little_endian ? DECODERS.int16l : DECODERS.int16;
    },

    // Decodes an Int16 in big-endian format.
    int16: function(b, pt) {
        return (b[pt.pos++] << 8) | (b[pt.pos++]);
    },

    // Decodes an Int16 in little-endian format.
    int16l: function(b, pt) {
        return (b[pt.pos++]) | (b[pt.pos++] << 8);
    },

    // Returns an int32 decoder based on the bigendian option
    get_int32: function(b, pt, l, opts) {
        return opts.little_endian ? DECODERS.int32l : DECODERS.int32;
    },

    // Decodes an Int32 in big-endian format.
    int32: function(b, pt) {
        return (b[pt.pos++] << 24) |  (b[pt.pos++] << 16) | (b[pt.pos++] << 8) | (b[pt.pos++]);
    },

    // Decodes an Int32 in little-endian format.
    int32l: function(b, pt) {
        return (b[pt.pos++]) | (b[pt.pos++] << 8) |  (b[pt.pos++] << 16) | (b[pt.pos++] << 24);
    },

    // Decodes an 8-bit char-string.
    string8: function(b, pt, l) {
        var result = [], i = index, bl = b.length, v;
        while(pt.pos < l && pt.pos < bl) {
            result.push(String.fromCharCode(v));
            pt.pos++;
        }
        return result.join('');
    },

    // Decodes an 8-bit char null-terminated string.
    cstring: function(b, pt) {
        var result = [], bl = b.length, v;
        while(pt.pos < bl && (v = b[pt.pos++]) != 0) {
            result.push(String.fromCharCode(v));
        }
        return result.join('');
    }
}

// Encodes Javascript objects into a byte-array.
function encode() {
    var args = get_array(arguments), result = [], options = { };
    while(args.length > 0) {
        var first = args.shift(), second, encoder;
        switch(first._dtclass) {
            case OPTION:
                first.callback(options, 'encode');
                break;
            case DATATYPE:
                second = args.shift();
                encoder = first.choose_callback ?
                          first.encoder(second, options) :
                          first.encoder;
                result = result.concat(encoder(second, options));
                break;
            case STRUCT:
                result = result.concat(first(second.shift()));
                break;
            default:
                throw "Expected datatype, struct or option: " + first._dtclass;
                break;
        }
    }
    return result;
}

// Decodes a set of bytes into a javascript object.
function decode_dt(dt, buffer, pt, length, opts) {
    var decoder = dt.choose_callback ?
                  dt.decoder(buffer, pt, length, opts) :
                  dt.decoder;
    return decoder(buffer, pt, length, opts);
}

// Decodes an byte-array into Javascript objects.
function decode() {
    var args = get_array(arguments), result = {}, options = {};
    var buffer = args.shift(), pt = new BufferPointer(0, buffer.length);
    while(args.length > 0) {
        var first = args.shift(), second, field, decoder, dtresult;
        switch(first._dtclass) {
            case POINTER:
                pt = first;
                continue;
            case OPTION:
                var array_result = options.array_result;
                first.callback(options, 'decode');
                if(options.array_result != array_result) {
                    result = options.array_result ? [] : {};
                }
                continue;
            case STRUCT:
                dtresult = options.array_result ?
                                first.to_array(buffer, pt) :
                                first.to_dict(buffer, pt);
                break;
            case DATATYPE:
            default:
                if(args[0] !== undefined && args[0].size == DEFINED_DATASIZE) {
                    // Expect a number representing the size
                    // of the datatype
                    if(first._dtclass == DATATYPE) {
                        // Parse size from member
                        first = decode_dt(first, buffer, pt, length, options);
                    }
                    second = args.shift();
                    dtresult = decode_dt(second, buffer, pt, first, options);
                } else {
                    dtresult = decode_dt(first, buffer, pt, first.size, options);
                }
                break;
        }
        if(options.array_result) {
            result.push(dtresult);
        } else {
            field = args.shift();
            if(field.constructor !== String) throw "Expected named field";
            result[field] = dtresult;
        }
    }
    return result;
}

// Predefined datatype definitions
var defs = [
    ['byte'     , 1],
    ['bytes'    , DEFINED_DATASIZE],
    ['int16'    , 2, 'choice'],
    ['int32'    , 4, 'choice'],
    ['string8'  , DEFINED_DATASIZE],
    ['cstring'  , FLEX_DATASIZE]
];

// Contants and members that should be exported to the public.
var constants = [
    ['FLEX_DATASIZE', FLEX_DATASIZE], ['DEFINED_DATASIZE', DEFINED_DATASIZE],
    ['DATATYPES', DATATYPES], ['CONSTANTS', CONSTANTS],
    ['BIG_ENDIAN', BIG_ENDIAN], ['LITTLE_ENDIAN', LITTLE_ENDIAN],
    ['ARRAY', ARRAY], ['DICT', DICT], ['ENCODERS', ENCODERS],
    ['DECODERS', DECODERS], ['dynamic', DYNAMIC], ['struct_size', STRUCT_SIZE],
    ['NO_ERROR_CHECK', NO_ERROR_CHECK]
];

// Export constants and objects to the public scope.
(function() {
    var dtindex = defs.length, cindex = constants.length;
    while(dtindex-- > 0) {
        var type = defs[dtindex];
        var name = type[0];
        var uname = name;
        var size = type[1];
        var prefix = '';
        var ctor_args = [size];
        if(type[2] == 'choice') {
            prefix = 'get_';
            ctor_args.push('choice');
        }
        ctor_args.push(ENCODERS[prefix + name]);
        ctor_args.push(DECODERS[prefix + name]);
        DATATYPES[uname] = self[uname] = define.apply(null, ctor_args);
    }
    while(cindex-- > 0) {
        var name = constants[cindex][0];
        var val = constants[cindex][1];
        CONSTANTS[name] = self[name] = val;
    }
})();

// Exports all constants such as datatypes and options to the provided scope.
(function(to) {
    for(var name in DATATYPES) to[name] = DATATYPES[name];
    for(var name in CONSTANTS) to[name] = CONSTANTS[name];
})(self);

// Export functions
self.define = define;
self.option = option;
self.encode = encode;
self.decode = decode;
self.struct = struct;
self.BufferPointer = BufferPointer;
self.DATATYPES = DATATYPES;
self.CONSTANTS = CONSTANTS;

})(datatypes);


text:
package org.colorcoding.ibas.bobas.rule;

import java.util.List;

import org.colorcoding.ibas.bobas.bo.IBusinessObject;
import org.colorcoding.ibas.bobas.core.IPropertyInfo;
import org.colorcoding.ibas.bobas.data.ArrayList;

/**
 * 业务规则抽象
 *
 * @author Niuren.Zhu
 *
 */
public abstract class BusinessRule implements IBusinessRule {

	protected static final String MSG_RULES_EXECUTING = "rules: executing rule [%s - %s].";

	private String name;

	public final String getName() {
		if (this.name == null || this.name.isEmpty()) {
			this.name = this.getClass().getSimpleName();
		}
		return name;
	}

	public final void setName(String name) {
		this.name = name;
	}

	private ArrayList<IPropertyInfo<?>> inputProperties;

	@Override
	public final List<IPropertyInfo<?>> getInputProperties() {
		if (this.inputProperties == null) {
			this.inputProperties = new ArrayList<>();
		}
		return this.inputProperties;
	}

	private ArrayList<IPropertyInfo<?>> affectedProperties;

	@Override
	public final List<IPropertyInfo<?>> getAffectedProperties() {
		if (this.affectedProperties == null) {
			this.affectedProperties = new ArrayList<>();
		}
		return this.affectedProperties;
	}

	@Override
	public final void execute(IBusinessObject bo) throws BusinessRuleException {
		this.execute(bo, null);
	}

	@Override
	public String toString() {
		return String.format("{business rule: %s}", this.getName());
	}
}

redpajama_set_name: RedPajamaGithub


text:
namespace AntMe.Serialization
{
    /// <summary>
    /// List of Package Types within a Frame.
    /// </summary>
    internal enum LevelStateSerializerPackageV2
    {
        // 0   >  Type (0) or Instance (1)
        // 1   >  Base (0) or Property (1)
        // 2   \  Operation: Insert = 01, Update = 10, Delete = 11
        // 3   /
        // 4   \
        // 5    \ Category: Level = 0x01, Map = 0x02, MapTile = 0x03, Material = 0x04, Faction = 0x05, Item = 0x06
        // 6    /
        // 7   /

        /* First 4 Bits (Operation)
         * =========================
         *
         * 0x0* -
         * 0x1* (Insert Base Type)
         * 0x2* (Update Base Type)
         * 0x3* (Delete Base Type)
         * 0x4* -
         * 0x5* (Insert Property Type)
         * 0x6* (Update Property Type)
         * 0x7* (Delete Property Type)
         * 0x8* -
         * 0x9* (Insert Base Instance)
         * 0xA* (Update Base Instance)
         * 0xB* (Delete Base Instance)
         * 0xC* -
         * 0xD* (Insert Property Instance)
         * 0xE* (Update Property Instance)
         * 0xF* (Delete Property Instance)
         *
         */

        /* Last 4 Bits (Type)
         * ===================
         *
         * 0x*0 -
         * 0x*1 Level
         * 0x*2 Map
         * 0x*3 MapTile
         * 0x*4 Material
         * 0x*5 Faction
         * 0x*6 Item
         * 0x*7 FactionItem
         * 0x*8 -
         * 0x*9 -
         * 0x*A -
         * 0x*B -
         * 0x*C -
         * 0x*D -
         * 0x*E -
         * 0x*F -
         *
         */

        // Frame Terminator
        FrameEnd = 0x00,

        // Level
        LevelInsert = 0x91,
        LevelUpdate = 0xA1,
        // LevelDelete = 0xB1,
        // LevelTypeInsert = 0x11,
        // LevelTypeUpdate = 0x21,
        // LevelTypeDelete = 0x31,
        LevelPropertyInsert = 0xD1,
        LevelPropertyUpdate = 0xE1,
        // LevelPropertyDelete = 0xF1,
        LevelPropertyTypeInsert = 0x51,
        // LevelPropertyTypeUpdate = 0x61,
        // LevelPropertyTypeDelete = 0x71,

        // Map
        MapInsert = 0x92,
        MapUpdate = 0xA2,
        // MapDelete = 0xB2,
        // MapTypeInsert = 0x12,
        // MapTypeUpdate = 0x22,
        // MapTypeDelete = 0x32,
        MapPropertyInsert = 0xD2,
        MapPropertyUpdate = 0xE2,
        // MapPropertyDelete = 0xF2,
        MapPropertyTypeInsert = 0x52,
        // MapPropertyTypeUpdate = 0x62,
        // MapPropertyTypeDelete = 0x72,

        // MapTile
        MapTileInsert = 0x93,
        MapTileUpdate = 0xA3,
        // MapTileDelete = 0xB3,
        MapTileTypeInsert = 0x13,
        // MapTileTypeUpdate = 0x23,
        // MapTileTypeDelete = 0x33,
        MapTilePropertyInsert = 0xD3,
        MapTilePropertyUpdate = 0xE3,
        // MapTilePropertyDelete = 0xF3,
        MapTilePropertyTypeInsert = 0x53,
        // MapTilePropertyTypeUpdate = 0x63,
        // MapTilePropertyTypeDelete = 0x73,

        // Material
        MaterialInsert = 0x94,
        MaterialUpdate = 0xA4,
        // MaterialDelete = 0xB4,
        MaterialTypeInsert = 0x14,
        // MaterialTypeUpdate = 0x24,
        // MaterialTypeDelete = 0x34,
        // MaterialPropertyInsert = 0xD4,
        // MaterialPropertyUpdate = 0xE4,
        // MaterialPropertyDelete = 0xF4,
        // MaterialPropertyTypeInsert = 0x54,
        // MaterialPropertyTypeUpdate = 0x64,
        // MaterialPropertyTypeDelete = 0x74,

        // Faction
        FactionInsert = 0x95,
        FactionUpdate = 0xA5,
        // FactionDelete = 0xB5,
        FactionTypeInsert = 0x15,
        // FactionTypeUpdate = 0x25,
        // FactionTypeDelete = 0x35,
        FactionPropertyInsert = 0xD5,
        FactionPropertyUpdate = 0xE5,
        // FactionPropertyDelete = 0xF5,
        FactionPropertyTypeInsert = 0x55,
        // FactionPropertyTypeUpdate = 0x65,
        // FactionPropertyTypeDelete = 0x75,

        // Item
        ItemInsert = 0x96,
        ItemUpdate = 0xA6,
        ItemDelete = 0xB6,
        ItemTypeInsert = 0x16,
        // ItemTypeUpdate = 0x26,
        // ItemTypeDelete = 0x36,
        ItemPropertyInsert = 0xD6,
        ItemPropertyUpdate = 0xE6,
        // ItemPropertyDelete = 0xF6,
        ItemPropertyTypeInsert = 0x56,
        // ItemPropertyTypeUpdate = 0x66,
        // ItemPropertyTypeDelete = 0x76,

        // FactionItem
        FactionItemInsert = 0x97,
        // FactionItemUpdate = 0xA7,
        // FactionItemDelete = 0xB7,
        // FactionItemTypeInsert = 0x17,
        // FactionItemTypeUpdate = 0x27,
        // FactionItemTypeDelete = 0x37,
        // FactionItemPropertyInsert = 0xD7,
        // FactionItemPropertyUpdate = 0xE7,
        // FactionItemPropertyDelete = 0xF7,
        // FactionItemPropertyTypeInsert = 0x57,
        // FactionItemPropertyTypeUpdate = 0x67,
        // FactionItemPropertyTypeDelete = 0x77,
    }
}


text:
"""Provide the RedditorListingMixin class."""
from typing import Any, Dict, Generator, TypeVar, Union
from urllib.parse import urljoin

from ....util.cache import cachedproperty
from ..generator import ListingGenerator
from .base import BaseListingMixin
from .gilded import GildedListingMixin

Reddit = TypeVar("Reddit")

class SubListing(BaseListingMixin):
    """Helper class for generating :class:`.ListingGenerator` objects."""

    def __init__(self, reddit: Reddit, base_path: str, subpath: str):
        """Initialize a SubListing instance.

        :param reddit: An instance of :class:`.Reddit`.
        :param base_path: The path to the object up to this point.
        :param subpath: The additional path to this sublisting.

        """
        super().__init__(reddit, _data=None)
        self._listing_use_sort = True
        self._reddit = reddit
        self._path = urljoin(base_path, subpath)

class RedditorListingMixin(BaseListingMixin, GildedListingMixin):
    """Adds additional methods pertaining to Redditor instances."""

    @cachedproperty
    def comments(self) -> SubListing:
        r"""Provide an instance of :class:`.SubListing` for comment access.

        For example, to output the first line of all new comments by
        ``/u/spez`` try:

        .. code-block:: python

           for comment in reddit.redditor('spez').comments.new(limit=None):
               print(comment.body.split('\n', 1)[0][:79])

        """
        return SubListing(self._reddit, self._path, "comments")

    @cachedproperty
    def submissions(self) -> SubListing:
        """Provide an instance of :class:`.SubListing` for submission access.

        For example, to output the title's of top 100 of all time submissions
        for ``/u/spez`` try:

        .. code-block:: python

           for submission in reddit.redditor('spez').submissions.top('all'):
               print(submission.title)

        """
        return SubListing(self._reddit, self._path, "submitted")

    def downvoted(
        self, **generator_kwargs: Union[str, int, Dict[str, str]]
    ) -> Generator[Any, None, None]:
        """Return a :class:`.ListingGenerator` for items the user has downvoted.

        May raise ``prawcore.Forbidden`` after issuing the request if the user
        is not authorized to access the list. Note that because this function
        returns a :class:`.ListingGenerator` the exception may not occur until
        sometime after this function has returned.

        Additional keyword arguments are passed in the initialization of
        :class:`.ListingGenerator`.

        For example, to get all downvoted items of the authenticated user:

        .. code-block:: python

            for item in reddit.user.me().downvoted():
                print(item.id)

        """
        return ListingGenerator(
            self._reddit, urljoin(self._path, "downvoted"), **generator_kwargs
        )

    def gildings(
        self, **generator_kwargs: Union[str, int, Dict[str, str]]
    ) -> Generator[Any, None, None]:
        """Return a :class:`.ListingGenerator` for items the user has gilded.

        May raise ``prawcore.Forbidden`` after issuing the request if the user
        is not authorized to access the list. Note that because this function
        returns a :class:`.ListingGenerator` the exception may not occur until
        sometime after this function has returned.

        Additional keyword arguments are passed in the initialization of
        :class:`.ListingGenerator`.

        For example, to get all gilded items of the authenticated user:

        .. code-block:: python

            for item in reddit.user.me().gildings():
                print(item.id)

        """
        return ListingGenerator(
            self._reddit,
            urljoin(self._path, "gilded/given"),
            **generator_kwargs
        )

    def hidden(
        self, **generator_kwargs: Union[str, int, Dict[str, str]]
    ) -> Generator[Any, None, None]:
        """Return a :class:`.ListingGenerator` for items the user has hidden.

        May raise ``prawcore.Forbidden`` after issuing the request if the user
        is not authorized to access the list. Note that because this function
        returns a :class:`.ListingGenerator` the exception may not occur until
        sometime after this function has returned.

        Additional keyword arguments are passed in the initialization of
        :class:`.ListingGenerator`.

        For example, to get all hidden items of the authenticated user:

        .. code-block:: python

            for item in reddit.user.me().hidden():
                print(item.id)

        """
        return ListingGenerator(
            self._reddit, urljoin(self._path, "hidden"), **generator_kwargs
        )

    def saved(
        self, **generator_kwargs: Union[str, int, Dict[str, str]]
    ) -> Generator[Any, None, None]:
        """Return a :class:`.ListingGenerator` for items the user has saved.

        May raise ``prawcore.Forbidden`` after issuing the request if the user
        is not authorized to access the list. Note that because this function
        returns a :class:`.ListingGenerator` the exception may not occur until
        sometime after this function has returned.

        Additional keyword arguments are passed in the initialization of
        :class:`.ListingGenerator`.

        For example, to get all saved items of the authenticated user:

        .. code-block:: python

            for item in reddit.user.me().saved():
                print(item.id)

        """
        return ListingGenerator(
            self._reddit, urljoin(self._path, "saved"), **generator_kwargs
        )

    def upvoted(
        self, **generator_kwargs: Union[str, int, Dict[str, str]]
    ) -> Generator[Any, None, None]:
        """Return a :class:`.ListingGenerator` for items the user has upvoted.

        May raise ``prawcore.Forbidden`` after issuing the request if the user
        is not authorized to access the list. Note that because this function
        returns a :class:`.ListingGenerator` the exception may not occur until
        sometime after this function has returned.

        Additional keyword arguments are passed in the initialization of
        :class:`.ListingGenerator`.

        For example, to get all upvoted items of the authenticated user:

        .. code-block:: python

            for item in reddit.user.me().upvoted():
                print(item.id)

        """
        return ListingGenerator(
            self._reddit, urljoin(self._path, "upvoted"), **generator_kwargs
        )


text:
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------

using System.Net;

namespace Microsoft.WindowsAzure.Management.ServiceManagement.HostedServices
{
    using System;
    using System.Management.Automation;
    using System.ServiceModel;
    using Microsoft.WindowsAzure.Management.Utilities.Common;
    using WindowsAzure.ServiceManagement;

    /// <summary>
    /// Create a new deployment. Note that there shouldn't be a deployment
    /// of the same name or in the same slot when executing this command.
    /// </summary>
    [Cmdlet(VerbsCommon.New, "AzureDeployment", DefaultParameterSetName = "PaaS"), OutputType(typeof(ManagementOperationContext))]
    public class NewAzureDeploymentCommand : ServiceManagementBaseCmdlet
    {
        public NewAzureDeploymentCommand()
        {
        }

        public NewAzureDeploymentCommand(IServiceManagement channel)
        {
            Channel = channel;
        }

        [Parameter(Position = 0, Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "Cloud service name.")]
        [ValidateNotNullOrEmpty]
        public string ServiceName
        {
            get;
            set;
        }

        [Parameter(Position = 1, Mandatory = true, HelpMessage = "Package location. This parameter specifies the path or URI to a .cspkg in blob storage. The storage account must belong to the same subscription as the deployment.")]
        [ValidateNotNullOrEmpty]
        public string Package
        {
            get;
            set;
        }

        [Parameter(Position = 2, Mandatory = true,  HelpMessage = "Configuration file path. This parameter should specifiy a .cscfg file on disk.")]
        [ValidateNotNullOrEmpty]
        public string Configuration
        {
            get;
            set;
        }

        [Parameter(Position = 3, Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "Deployment slot [Staging | Production].")]
        [ValidateSet("Staging", "Production", IgnoreCase = true)]
        public string Slot
        {
            get;
            set;
        }

        [Parameter(Position = 4, Mandatory = false, HelpMessage = "Label for the new deployment.")]
        [ValidateNotNullOrEmpty]
        public string Label
        {
            get;
            set;
        }

        [Parameter(Position = 5, HelpMessage = "Deployment name.")]
        [Alias("DeploymentName")]
        [ValidateNotNullOrEmpty]
        public string Name
        {
            get;
            set;
        }

        [Parameter(Mandatory = false, HelpMessage = "Do not start deployment upon creation.")]
        public SwitchParameter DoNotStart
        {
            get;
            set;
        }

        [Parameter(Mandatory = false, HelpMessage = "Indicates whether to treat package validation warnings as errors.")]
        public SwitchParameter TreatWarningsAsError
        {
            get;
            set;
        }

        public void NewPaaSDeploymentProcess()
        {
            bool removePackage = false;

            AssertNoPersistenVmRoleExistsInDeployment(DeploymentSlotType.Production);
            AssertNoPersistenVmRoleExistsInDeployment(DeploymentSlotType.Staging);

            var storageName = CurrentSubscription.CurrentStorageAccount;

            Uri packageUrl;
            if (this.Package.StartsWith(Uri.UriSchemeHttp, StringComparison.OrdinalIgnoreCase) ||
                this.Package.StartsWith(Uri.UriSchemeHttps, StringComparison.OrdinalIgnoreCase))
            {
                packageUrl = new Uri(this.Package);
            }
            else
            {
                var progress = new ProgressRecord(0, "Please wait...", "Uploading package to blob storage");
                WriteProgress(progress);
                removePackage = true;
                packageUrl = this.RetryCall(s =>
                    AzureBlob.UploadPackageToBlob(
                    this.Channel,
                    storageName,
                    s,
                    this.Package,
                    null));
            }

            var deploymentInput = new CreateDeploymentInput
            {
                PackageUrl = packageUrl,
                Configuration = General.GetConfiguration(this.Configuration),
                Label = this.Label,
                Name = this.Name,
                StartDeployment = !this.DoNotStart.IsPresent,
                TreatWarningsAsError = this.TreatWarningsAsError.IsPresent
            };

            using (new OperationContextScope(Channel.ToContextChannel()))
            {
                try
                {
                    var progress = new ProgressRecord(0, "Please wait...", "Creating the new deployment");
                    WriteProgress(progress);

                    ExecuteClientAction(deploymentInput, CommandRuntime.ToString(), s => this.Channel.CreateOrUpdateDeployment(s, this.ServiceName, this.Slot, deploymentInput));

                    if (removePackage == true)
                    {
                        this.RetryCall(s =>
                        AzureBlob.DeletePackageFromBlob(
                                this.Channel,
                                storageName,
                                s,
                                packageUrl));
                    }
                }
                catch (ServiceManagementClientException ex)
                {
                    this.WriteErrorDetails(ex);
                }
            }
        }

        private void AssertNoPersistenVmRoleExistsInDeployment(string slot)
        {
            using (new OperationContextScope(Channel.ToContextChannel()))
            {
                try
                {
                    Deployment currentDeployment = this.RetryCall(s => this.Channel.GetDeploymentBySlot(s, this.ServiceName, slot));
                    if (currentDeployment.RoleList != null)
                    {
                        if (string.Compare(currentDeployment.RoleList[0].RoleType, "PersistentVMRole", StringComparison.OrdinalIgnoreCase) == 0)
                        {
                            throw new ArgumentException(String.Format("Cannot Create New Deployment with Virtual Machines Present in {0} Slot", slot));
                        }
                    }
                }
                catch (ServiceManagementClientException ex)
                {
                    if (ex.HttpStatus != HttpStatusCode.NotFound && IsVerbose() == false)
                    {
                        this.WriteErrorDetails(ex);
                    }
                }
            }
        }

        protected override void OnProcessRecord()
        {
            this.ValidateParameters();
            this.NewPaaSDeploymentProcess();
        }

        private void ValidateParameters()
        {
            if (string.IsNullOrEmpty(this.Slot))
            {
                this.Slot = "Production";
            }

            if (string.IsNullOrEmpty(this.Name))
            {
                 this.Name = Guid.NewGuid().ToString();
            }

            if (string.IsNullOrEmpty(this.Label))
            {
                this.Label = this.Name;
            }

            if (string.IsNullOrEmpty(this.CurrentSubscription.CurrentStorageAccount))
            {
                throw new ArgumentException("CurrentStorageAccount is not set. Use Set-AzureSubscription subname -CurrentStorageAccount storageaccount to set it.");
            }
        }
    }
}


text:
package com.microsoft.azure.management.iothub.v2018_04_01;

import org.joda.time.Period;
import com.fasterxml.jackson.annotation.JsonProperty;

/**
 * The properties of the feedback queue for cloud-to-device messages.
 */
public class FeedbackProperties {
    /**
     * The lock duration for the feedback queue. See:
     * https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-messaging#cloud-to-device-messages.
     */
    @JsonProperty(value = "lockDurationAsIso8601")
    private Period lockDurationAsIso8601;

    /**
     * The period of time for which a message is available to consume before it
     * is expired by the IoT hub. See:
     * https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-messaging#cloud-to-device-messages.
     */
    @JsonProperty(value = "ttlAsIso8601")
    private Period ttlAsIso8601;

    /**
     * The number of times the IoT hub attempts to deliver a message on the
     * feedback queue. See:
     * https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-messaging#cloud-to-device-messages.
     */
    @JsonProperty(value = "maxDeliveryCount")
    private Integer maxDeliveryCount;

    /**
     * Get the lock duration for the feedback queue. See: https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-messaging#cloud-to-device-messages.
     *
     * @return the lockDurationAsIso8601 value
     */
    public Period lockDurationAsIso8601() {
        return this.lockDurationAsIso8601;
    }

    /**
     * Set the lock duration for the feedback queue. See: https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-messaging#cloud-to-device-messages.
     *
     * @param lockDurationAsIso8601 the lockDurationAsIso8601 value to set
     * @return the FeedbackProperties object itself.
     */
    public FeedbackProperties withLockDurationAsIso8601(Period lockDurationAsIso8601) {
        this.lockDurationAsIso8601 = lockDurationAsIso8601;
        return this;
    }

    /**
     * Get the period of time for which a message is available to consume before it is expired by the IoT hub. See: https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-messaging#cloud-to-device-messages.
     *
     * @return the ttlAsIso8601 value
     */
    public Period ttlAsIso8601() {
        return this.ttlAsIso8601;
    }

    /**
     * Set the period of time for which a message is available to consume before it is expired by the IoT hub. See: https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-messaging#cloud-to-device-messages.
     *
     * @param ttlAsIso8601 the ttlAsIso8601 value to set
     * @return the FeedbackProperties object itself.
     */
    public FeedbackProperties withTtlAsIso8601(Period ttlAsIso8601) {
        this.ttlAsIso8601 = ttlAsIso8601;
        return this;
    }

    /**
     * Get the number of times the IoT hub attempts to deliver a message on the feedback queue. See: https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-messaging#cloud-to-device-messages.
     *
     * @return the maxDeliveryCount value
     */
    public Integer maxDeliveryCount() {
        return this.maxDeliveryCount;
    }

    /**
     * Set the number of times the IoT hub attempts to deliver a message on the feedback queue. See: https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-messaging#cloud-to-device-messages.
     *
     * @param maxDeliveryCount the maxDeliveryCount value to set
     * @return the FeedbackProperties object itself.
     */
    public FeedbackProperties withMaxDeliveryCount(Integer maxDeliveryCount) {
        this.maxDeliveryCount = maxDeliveryCount;
        return this;
    }

}


text:
package main

const glpHelp = `glp -- dependency pinning for Go
Usage:
    %s COMMAND [OPTIONS]...
glp provides several builtin commands. All other subcommands are delegated to
the go tool using a modified $GOPATH for the glp project.

glp commands:

help
    Show this help.
path
    Print the GOPATH with which glp calls the Go tool.
sync
    Synchronize the project dependencies (from the source), the pinned
    versions (in glp/deps.json), and the cache (glp/_cache).

For more information, see https://github.com/cespare/glp.
`


text:
Parallel Random Number Generation
=================================

There are three strategies implemented that can be used to produce
repeatable pseudo-random numbers across multiple processes (local
or distributed).

.. currentmodule:: numpy.random

.. _seedsequence-spawn:

`~SeedSequence` spawning
------------------------

`~SeedSequence` `implements an algorithm`_ to process a user-provided seed,
typically as an integer of some size, and to convert it into an initial state for
a `~BitGenerator`. It uses hashing techniques to ensure that low-quality seeds
are turned into high quality initial states (at least, with very high
probability).

For example, `MT19937` has a state consisting of 624
`uint32` integers. A naive way to take a 32-bit integer seed would be to just set
the last element of the state to the 32-bit seed and leave the rest 0s. This is
a valid state for `MT19937`, but not a good one. The Mersenne Twister
algorithm `suffers if there are too many 0s`_. Similarly, two adjacent 32-bit
integer seeds (i.e. ``12345`` and ``12346``) would produce very similar
streams.

`~SeedSequence` avoids these problems by using successions of integer hashes
with good `avalanche properties`_ to ensure that flipping any bit in the input
input has about a 50% chance of flipping any bit in the output. Two input seeds
that are very close to each other will produce initial states that are very far
from each other (with very high probability). It is also constructed in such
a way that you can provide arbitrary-sized integers or lists of integers.
`~SeedSequence` will take all of the bits that you provide and mix them
together to produce however many bits the consuming `~BitGenerator` needs to
initialize itself.

These properties together mean that we can safely mix together the usual
user-provided seed with simple incrementing counters to get `~BitGenerator`
states that are (to very high probability) independent of each other. We can
wrap this together into an API that is easy to use and difficult to misuse.

.. code-block:: python

  from numpy.random import SeedSequence, default_rng

  ss = SeedSequence(12345)

  # Spawn off 10 child SeedSequences to pass to child processes.
  child_seeds = ss.spawn(10)
  streams = [default_rng(s) for s in child_seeds]

.. end_block

Child `~SeedSequence` objects can also spawn to make grandchildren, and so on.
Each `~SeedSequence` has its position in the tree of spawned `~SeedSequence`
objects mixed in with the user-provided seed to generate independent (with very
high probability) streams.

.. code-block:: python

  grandchildren = child_seeds[0].spawn(4)
  grand_streams = [default_rng(s) for s in grandchildren]

.. end_block

This feature lets you make local decisions about when and how to split up
streams without coordination between processes. You do not have to preallocate
space to avoid overlapping or request streams from a common global service. This
general "tree-hashing" scheme is `not unique to numpy`_ but not yet widespread.
Python has increasingly-flexible mechanisms for parallelization available, and
this scheme fits in very well with that kind of use.

Using this scheme, an upper bound on the probability of a collision can be
estimated if one knows the number of streams that you derive. `~SeedSequence`
hashes its inputs, both the seed and the spawn-tree-path, down to a 128-bit
pool by default. The probability that there is a collision in
that pool, pessimistically-estimated ([1]_), will be about :math:`n^2*2^{-128}` where
`n` is the number of streams spawned. If a program uses an aggressive million
streams, about :math:`2^{20}`, then the probability that at least one pair of
them are identical is about :math:`2^{-88}`, which is in solidly-ignorable
territory ([2]_).

.. [1] The algorithm is carefully designed to eliminate a number of possible
       ways to collide. For example, if one only does one level of spawning, it
       is guaranteed that all states will be unique. But it's easier to
       estimate the naive upper bound on a napkin and take comfort knowing
       that the probability is actually lower.

.. [2] In this calculation, we can mostly ignore the amount of numbers drawn from each
       stream. See :ref:`upgrading-pcg64` for the technical details about
       `PCG64`. The other PRNGs we provide have some extra protection built in
       that avoids overlaps if the `~SeedSequence` pools differ in the
       slightest bit. `PCG64DXSM` has :math:`2^{127}` separate cycles
       determined by the seed in addition to the position in the
       :math:`2^{128}` long period for each cycle, so one has to both get on or
       near the same cycle *and* seed a nearby position in the cycle.
       `Philox` has completely independent cycles determined by the seed.
       `SFC64` incorporates a 64-bit counter so every unique seed is at
       least :math:`2^{64}` iterations away from any other seed. And
       finally, `MT19937` has just an unimaginably huge period. Getting
       a collision internal to `SeedSequence` is the way a failure would be
       observed.

.. _`implements an algorithm`: http://www.pcg-random.org/posts/developing-a-seed_seq-alternative.html
.. _`suffers if there are too many 0s`: http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/MT2002/emt19937ar.html
.. _`avalanche properties`: https://en.wikipedia.org/wiki/Avalanche_effect
.. _`not unique to numpy`: https://www.iro.umontreal.ca/~lecuyer/myftp/papers/parallel-rng-imacs.pdf

.. _independent-streams:

Independent Streams
-------------------

`Philox` is a counter-based RNG based which generates values by
encrypting an incrementing counter using weak cryptographic primitives. The
seed determines the key that is used for the encryption. Unique keys create
unique, independent streams. `Philox` lets you bypass the
seeding algorithm to directly set the 128-bit key. Similar, but different, keys
will still create independent streams.

.. code-block:: python

  import secrets
  from numpy.random import Philox

  # 128-bit number as a seed
  root_seed = secrets.getrandbits(128)
  streams = [Philox(key=root_seed + stream_id) for stream_id in range(10)]

.. end_block

This scheme does require that you avoid reusing stream IDs. This may require
coordination between the parallel processes.

.. _parallel-jumped:

Jumping the BitGenerator state
------------------------------

``jumped`` advances the state of the BitGenerator *as-if* a large number of
random numbers have been drawn, and returns a new instance with this state.
The specific number of draws varies by BitGenerator, and ranges from
:math:`2^{64}` to :math:`2^{128}`.  Additionally, the *as-if* draws also depend
on the size of the default random number produced by the specific BitGenerator.
The BitGenerators that support ``jumped``, along with the period of the
BitGenerator, the size of the jump and the bits in the default unsigned random
are listed below.

+-----------------+-------------------------+-------------------------+-------------------------+
| BitGenerator    | Period                  |  Jump Size              | Bits per Draw           |
+=================+=========================+=========================+=========================+
| MT19937         | :math:`2^{19937}-1`     | :math:`2^{128}`         | 32                      |
+-----------------+-------------------------+-------------------------+-------------------------+
| PCG64           | :math:`2^{128}`         | :math:`~2^{127}` ([3]_) | 64                      |
+-----------------+-------------------------+-------------------------+-------------------------+
| PCG64DXSM       | :math:`2^{128}`         | :math:`~2^{127}` ([3]_) | 64                      |
+-----------------+-------------------------+-------------------------+-------------------------+
| Philox          | :math:`2^{256}`         | :math:`2^{128}`         | 64                      |
+-----------------+-------------------------+-------------------------+-------------------------+

.. [3] The jump size is :math:`(\phi-1)*2^{128}` where :math:`\phi` is the
       golden ratio. As the jumps wrap around the period, the actual distances
       between neighboring streams will slowly grow smaller than the jump size,
       but using the golden ratio this way is a classic method of constructing
       a low-discrepancy sequence that spreads out the states around the period
       optimally. You will not be able to jump enough to make those distances
       small enough to overlap in your lifetime.

``jumped`` can be used to produce long blocks which should be long enough to not
overlap.

.. code-block:: python

  import secrets
  from numpy.random import PCG64

  seed = secrets.getrandbits(128)
  blocked_rng = []
  rng = PCG64(seed)
  for i in range(10):
      blocked_rng.append(rng.jumped(i))

.. end_block

When using ``jumped``, one does have to take care not to jump to a stream that
was already used. In the above example, one could not later use
``blocked_rng[0].jumped()`` as it would overlap with ``blocked_rng[1]``. Like
with the independent streams, if the main process here wants to split off 10
more streams by jumping, then it needs to start with ``range(10, 20)``,
otherwise it would recreate the same streams. On the other hand, if you
carefully construct the streams, then you are guaranteed to have streams that
do not overlap.


text:
	<title>Peter Ainsworth's panel show appearances</title>

	<link rel="stylesheet" media="all" href="../style.css" type="text/css"/>

Peter Ainsworth's panel show appearances

Peter Ainsworth (born 1956-11-16[ref]) has appeared in 2 episodes between 2001-2002.  Peter Ainsworth on Wikipedia.

2001

2002

2002-04-25 / Question Time

2001-04-26 / Question Time


text:
<?php

namespace OcraDiCompilerTest\TestAsset;

/**
 * Instance to be injected into DumperTestDummyInstanceWithDefinitions through its definitions
 */
class DumperTestDummyDependencyFromDefinitions
{
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>LeetCode | Gray Code in Python - Java, Python, Machine Learning, LeetCode</title>
    <meta name="keywords" content="Java, Python, Machine Learning, LeetCode">
    <meta name="description" content="The personal site of Alain, MLer and programmer. I write about Java, Python, Machine Learning and my code on LeetCode Here.">
    <meta name="author" content="Alain">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href="/static/favicon.ico" rel="shortcut icon">
    <link href="/static/css/bootstrap.css" rel="stylesheet" type="text/css" media="all">
    <link href="/static/css/font-awesome.css" rel="stylesheet" type="text/css" media="all">
    <link href="/static/google-code-prettify/prettify.css" rel="stylesheet" type="text/css" media="all">
    <link href="/static/css/application.css" rel="stylesheet" type="text/css" media="all">

Alain

Java Intermediate, Python Beginner, Machine Learning Fan

Home

Categories

Tags

Archives

        LeetCode | Gray Code in Python

            category:

            leetcode

            tag:

            Python

'''
Question:
    The gray code is a binary numeral system where two successive values differ in only one bit. Given a non-negative integer n representing the total number of bits in the code, print the sequence of gray code. A gray code sequence must begin with 0.

Algorithm:
    DFS
    when we get the result for n-1 denoted as "sub", we can get that for n as "res" in the following way:
    1. "res" = "sub"
    2. reverse "sub"
    3. put 1 at the beginning of each element of the reversed "sub" and get "temp"
    4. "res" += "temp"
'''

class Solution:
    # @return a list of integers
    def grayCode(self, n):
        if n == 0:
            return [0]
        else:
            sub = self.grayCode(n-1)
            return sub + [(sub[i] | (1 << (n-1))) for i in xrange(len(sub)-1, -1, -1)]

← previous post

next post →

        Please enable JavaScript to view the comments powered by Disqus.

             Powered by Jekyll
             | Hosted by Github.com
             | 11/03/2014


text:
<!DOCTYPE html>

Lorem ipsum


text:
<?php

declare(strict_types=1);

namespace DCarbone\PHPConsulAPI\KV;

use DCarbone\PHPConsulAPI\AbstractValuedQueryResponse;
use DCarbone\PHPConsulAPI\UnmarshalledResponseInterface;

/**
 * Class KVPairResponse
 */
class KVPairResponse extends AbstractValuedQueryResponse implements UnmarshalledResponseInterface
{
    /** @var \DCarbone\PHPConsulAPI\KV\KVPair|null */
    public ?KVPair $KVPair = null;

    /**
     * @return \DCarbone\PHPConsulAPI\KV\KVPair|null
     */
    public function getValue(): ?KVPair
    {
        return $this->KVPair;
    }

    /**
     * @param mixed $decodedData
     */
    public function unmarshalValue($decodedData): void
    {
        $this->KVPair = new KVPair((array)$decodedData, true);
    }
}


text:
package com.microsoft.azure.management.notificationhubs.v2014_09_01.implementation;

import com.fasterxml.jackson.annotation.JsonProperty;

/**
 * Namespace/NotificationHub Connection String.
 */
public class ResourceListKeysInner {
    /**
     * Gets or sets the primaryConnectionString of the created Namespace
     * AuthorizationRule.
     */
    @JsonProperty(value = "primaryConnectionString")
    private String primaryConnectionString;

    /**
     * Gets or sets the secondaryConnectionString of the created Namespace
     * AuthorizationRule.
     */
    @JsonProperty(value = "secondaryConnectionString")
    private String secondaryConnectionString;

    /**
     * Get gets or sets the primaryConnectionString of the created Namespace AuthorizationRule.
     *
     * @return the primaryConnectionString value
     */
    public String primaryConnectionString() {
        return this.primaryConnectionString;
    }

    /**
     * Set gets or sets the primaryConnectionString of the created Namespace AuthorizationRule.
     *
     * @param primaryConnectionString the primaryConnectionString value to set
     * @return the ResourceListKeysInner object itself.
     */
    public ResourceListKeysInner withPrimaryConnectionString(String primaryConnectionString) {
        this.primaryConnectionString = primaryConnectionString;
        return this;
    }

    /**
     * Get gets or sets the secondaryConnectionString of the created Namespace AuthorizationRule.
     *
     * @return the secondaryConnectionString value
     */
    public String secondaryConnectionString() {
        return this.secondaryConnectionString;
    }

    /**
     * Set gets or sets the secondaryConnectionString of the created Namespace AuthorizationRule.
     *
     * @param secondaryConnectionString the secondaryConnectionString value to set
     * @return the ResourceListKeysInner object itself.
     */
    public ResourceListKeysInner withSecondaryConnectionString(String secondaryConnectionString) {
        this.secondaryConnectionString = secondaryConnectionString;
        return this;
    }

}


text:
// ==================================================================
// ZMachine.NET / Jason Follas  (http://zmachine.codeplex.com)
// ==================================================================

using System;
using System.Collections.Generic;

namespace ZMachine.v5
{
    /// <summary>
    /// Reads and caches a Dictionary from the story file.
    /// </summary>
    [Serializable]
    public class ZDictionary : IZDictionary
    {
        // Holds the reference to the current ZMemory object
        protected ZMemory m_memory = null;

        // Number of Word Separators as read from the dictionary header
        protected byte numWordSeparators = 0;

        // Char array containing the declared Word Separators
        protected char[] wordSeparatorChars;

        // Number of dictionary entries
        protected int numEntries = 0;

        // Length of each dictionary entry
        protected byte entryLength = 0;

        // Typed Dictionary collection (.NET definition, not Infocom definition) that caches the story file
        // words and memory addresses, which is used during parsing
        protected Dictionary<string, int> entries = null;

        /// <summary>
        /// Constructor.  Initializes the ZDictionary to the default story file's dictionary location.
        /// </summary>
        /// <param name="mem">Active ZMemory object</param>
        public ZDictionary(ZMemory mem)
        {
            m_memory = mem;
            Initialize(m_memory.Header.DictionaryLocation);
        }

        /// <summary>
        /// Constructor.  Initializes the ZDictionary to the specified story file's dictionary location.  (Supposedly, some
        /// games can have multiple dictionaries).
        /// </summary>
        /// <param name="mem">Active ZMemory object</param>
        /// <param name="dictionaryAddress">Address location of the specified dictionary</param>
        public ZDictionary(ZMemory mem, int dictionaryAddress)
        {
            m_memory = mem;
            Initialize(dictionaryAddress);
        }

        /// <summary>
        /// Populates the object from values read from the ZMemory
        /// </summary>
        /// <param name="dictAddr">Address of the dictionary</param>
        protected virtual void Initialize(int dictAddr)
        {
            // Dictionary header starts with a byte declaring the number of Word Separators
            numWordSeparators = m_memory.GetByte(dictAddr);

            // Immediately followed by that number of character codes (ZSCII, but close enough to ASCII to not worry about for now)
            wordSeparatorChars = new char[numWordSeparators];

            for (int i = 0; i < numWordSeparators; i++)
            {
                wordSeparatorChars[i] = (char)m_memory.GetByte(dictAddr + i + 1);
            }

            // Next header byte declares the entry length
            entryLength = m_memory.GetByte(dictAddr + numWordSeparators + 1);

            //Next header word declares the number of entries
            numEntries = m_memory.GetWord(dictAddr + numWordSeparators + 2);

            // Create a new typed Dictionary object using string keys and int values.
            entries = new Dictionary<string, int>();

            // Address of first byte past the header
            int startOfEntries = dictAddr + numWordSeparators + 4;

            // Get each story file dictionary entry, decode the text, and store in our typed Dictionary object using the
            // text as the key, and the story file address as the value
            for (int i = 0; i < numEntries; i++)
            {
                entries.Add(ZMachine.Common.ZText.PrintZString(m_memory, startOfEntries + (i * entryLength)), startOfEntries + (i * entryLength));
            }
        }

        /// <summary>
        /// Returns the story file address for the given word (text)
        /// </summary>
        /// <param name="entry">Word (text) entered by the user</param>
        /// <returns>Address of dictionary entry for the given text, or 0 if the word does not exist in the story file</returns>
        public virtual int GetAddressForEntry(string entry)
        {
            // Version 3: All words are truncated at 6 characters
            if (entry.Length > 6)
                entry = entry.Substring(0, 6);

            int ret = 0;
            if (entries.TryGetValue(entry, out ret))
                return ret;
            else
                return 0;
        }

        /// <summary>
        /// Concatenates all of the Word Separator characters into a single string
        /// </summary>
        /// <returns>String</returns>
        public virtual string GetWordSeparatorsAsString()
        {
            return new string(wordSeparatorChars);
        }
    }
}


text:
<?php

namespace Oro\Bundle\AttachmentBundle\DependencyInjection;

use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;

use Oro\Bundle\ConfigBundle\DependencyInjection\SettingsBuilder;

class Configuration implements ConfigurationInterface
{
    /**
     * {@inheritdoc}
     */
    public function getConfigTreeBuilder()
    {
        $treeBuilder = new TreeBuilder();
        $rootNode    = $treeBuilder->root('oro_attachment');

        /**
         * See file types list -> http://www.freeformatter.com/mime-types-list.html
         */
        $mimeTypes
            = <<<EOF
application/msword
application/vnd.ms-excel
application/pdf
application/zip
EOF;
        $mimeTypesImage
            = <<<EOF
image/gif
image/jpeg
image/png
EOF;

        SettingsBuilder::append(
            $rootNode,
            [
                'upload_file_mime_types'  => ['value' => $mimeTypes],
                'upload_image_mime_types' => ['value' => $mimeTypesImage]
            ]
        );

        return $treeBuilder;
    }
}


text:
define('employee-forms-auth/serializers/application', ['exports', 'active-model-adapter'], function (exports, _activeModelAdapter) {
  'use strict';
  exports['default'] = _activeModelAdapter.ActiveModelSerializer.extend({});
});


text:
package com.swfarm.biz.wish.web;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

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

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.swfarm.biz.oa.bo.User;
import com.swfarm.biz.salechannel.srv.SaleChannelService;
import com.swfarm.biz.wish.dto.SearchWishProductTemplatesCriteria;
import com.swfarm.biz.wish.srv.WishService;
import com.swfarm.pub.framework.AppContext;
import com.swfarm.pub.framework.PaginationSupport;

@Controller
public class ShowWishProductTemplatesController {

	Logger logger = Logger.getLogger(ShowWishProductTemplatesController.class);

	@Autowired
	private WishService wishService;

	@Autowired
	private SaleChannelService saleChannelService;

	@RequestMapping("/wish/wishproducttemplates.shtml")
	public ModelAndView showWishProductTemplates(HttpServletRequest req, HttpServletResponse resp) throws Exception {
		SearchWishProductTemplatesCriteria criteria = (SearchWishProductTemplatesCriteria) req
				.getAttribute("criteria");
		String startIndexStr = req.getParameter("startIndex");
		int startIndex = 0;
		int pageSize = 50;
		if (StringUtils.isNotEmpty(startIndexStr)) {
			startIndex = new Integer(startIndexStr).intValue();
		} else {
			String pageStr = req.getParameter("page");
			if (StringUtils.isNotEmpty(pageStr)) {
				startIndex = PaginationSupport.getPageStartIndex(new Integer(pageStr), pageSize);
			}
		}
		Map<String, Object> dataMap = new HashMap<String, Object>(6);
		if (criteria == null) {
			criteria = new SearchWishProductTemplatesCriteria();
		}
		PaginationSupport pagination = this.wishService.searchWishProductTemplates(criteria, pageSize, startIndex);
		int page = pagination.getPage(startIndex);
		int[] pageRange = pagination.getPageRange(page);
		dataMap.put("pagination", pagination);
		dataMap.put("currentPage", page);
		dataMap.put("pageRange", pageRange);
		List languages = new ArrayList();
		languages.add(new String[] { "en", "英语" });
		languages.add(new String[] { "de", "德语" });
		languages.add(new String[] { "fr", "法语" });
		languages.add(new String[] { "es", "西班牙语" });
		languages.add(new String[] { "it", "意大利语" });
		dataMap.put("languages", languages);

		User currentUser = AppContext.getContextData().getCurrentUser();
		if (currentUser.isAdmin()) {
			List wishAccounts = this.wishService.findWishAccounts();
			dataMap.put("wishAccounts", wishAccounts);
		} else {
			List wishAccounts = this.saleChannelService.getResponsibleWishAccounts(currentUser.getUsername());
			dataMap.put("wishAccounts", wishAccounts);
		}

		return new ModelAndView("wish/wishproducttemplates", dataMap);
	}

}


text:
import Control.Monad ((<=<))
import Data.Default (Default(def))
import Data.Maybe (fromMaybe)
import Data.Time.Calendar (fromGregorian)
import Data.Time.LocalTime (LocalTime(..), TimeOfDay(..))
import Paths_clippings (getDataFileName)
import Test.Assert (runAssertions)
import Text.Kindle.Clippings.Reader (readClipping)
import Text.Kindle.Clippings.Types (Clipping(..),Interval(..),Document(..),Position(..),Content(..))
import Text.Kindle.Clippings.Writer ()
import Text.Parsec (parse)

fromMaybeEither :: Default b => Either a (Maybe b) -> b
fromMaybeEither = fromMaybe def .$  either (Just . const def) id

(.$) :: (b -> c) -> (a -> b) -> a -> c
(.$) = ((.) $)

getClipping :: String -> Clipping
getClipping = fromMaybeEither . parse readClipping "tests/Reader.hs"

inFixture :: Clipping
inFixture = Clipping
  { date     = LocalTime (fromGregorian 2013 06 10) (TimeOfDay 6 58 17)
  , document = Document "Haskell Monoids and their Uses" (Just "sigfpe")
  , position = Position Nothing . Just $ Proper 3 4
  , content  = Highlight "Haskell is a great language for constructing code modularly from small but orthogonal building blocks."
  }

inPw2Fixture :: Clipping
inPw2Fixture = Clipping
  { date     = LocalTime (fromGregorian 2014 06 08) (TimeOfDay 20 36 53)
  , document = Document "Stand on Zanzibar" (Just "John Brunner")
  , position = Position Nothing . Just $ Proper 4607 4607
  , content  = Highlight "Shinka will"
  }

inPw2pdfFixture :: Clipping
inPw2pdfFixture = Clipping
  { date     = LocalTime (fromGregorian 2014 07 29) (TimeOfDay 07 53 28)
  , document = Document "Tyler Cowen-Creative Destruction_ How Globalization Is Changing the World's Cultures-Princeton University Press (2002)_k2opt" Nothing
  , position = Position (Just $ Proper 303 303) Nothing
  , content  = Highlight "The fundamental story about consumer taste, in modern times, is not one of dumbing down or of producers seeking to satisfy a homogeneous least common denominator at the expense of quality. Rather, the basic trend is of increasing variety and diversity, at all levels of quality, high and low"
  }

getTitle :: Clipping -> String
getTitle = title . document

getAuthor :: Clipping -> Maybe String
getAuthor = author . document

main :: IO ()
main = do
  [clipping, brackets, nested, pw2, pw2pdf] <- mapM (readFile <=< getDataFileName)
    [ "tests/fixtures/clipping.txt"
    , "tests/fixtures/brackets.txt"
    , "tests/fixtures/nested_brackets.txt"
    , "tests/fixtures/pw2clipping.txt"
    , "tests/fixtures/pw2pdfclipping.txt"
    ]
  runAssertions $
    [ ("Fixture should parse to sigfpe clipping.", getClipping clipping == inFixture)
    , ("Brackets in clippings' titles should be preserved." , getTitle (getClipping brackets) == "An Introduction to Statistical Learning: with Applications in R (Springer Texts in Statistics)")
    , ("Nested brackets in clippings' authors should be preserved.", getAuthor (getClipping nested) == Just "G. K. (Gilbert Keith) Chesterton")
    , ("Pw2Fixture should parse to Zanzibar clipping", getClipping pw2 == inPw2Fixture)
    , ("Pw2pdfFixture should parse to Tyler clipping", getClipping pw2pdf == inPw2pdfFixture)
    ]


text:
<?xml version="1.0" encoding="UTF-8"?>
<bookmap xmlns:ditaarch="http://dita.oasis-open.org/architecture/2005/"
    xmlns:opentopic-index="http://www.idiominc.com/opentopic/index"
    class="- map/map bookmap/bookmap " collection-type="sequence">
    <ot-placeholder:toc xmlns:ot-placeholder="http://suite-sol.com/namespaces/ot-placeholder"/>
    <topic class="- topic/topic ">
        <title class="- topic/title ">Level 1 - 1</title>

            <topic class="- topic/topic ">
                <title class="- topic/title ">Level 2 - 1</title>

            </topic>
            <topic class="- topic/topic ">
                <title class="- topic/title ">Level 2 - 2</title>

            </topic>

    </topic>
    <topic class="- topic/topic ">
        <title class="- topic/title ">Level 1 - 2</title>

            <topic class="- topic/topic ">
                <title class="- topic/title ">Level 2 - 1</title>

            </topic>
            <topic class="- topic/topic ">
                <title class="- topic/title ">Level 2 - 2</title>

            </topic>

    </topic>

    <topic class="- topic/topic ">
        <title class="- topic/title ">Level 1 - 3</title>

            <topic class="- topic/topic ">
                <title class="- topic/title ">Level 2 - 1</title>

            </topic>
            <topic class="- topic/topic ">
                <title class="- topic/title ">Level 2 - 2</title>

            </topic>

    </topic>
</bookmap>


text:
package com.spacetimecat.java.lang.callback;

public abstract class AbstractCallbackFunction<A, B> implements CallbackFunction<A, B>
{
    /**
     * <p>
     *     Returns a function that feeds the output of this to that;
     *     roughly {@code f.compose(g) = x -> g(f(x))}.
     * </p>
     *
     * @param that
     * takes the output of this
     *
     * @param <C>
     * return type
     *
     * @return
     * see description
     */
    public final <C> CallbackFunction<A, C> then (CallbackFunction<B, C> that)
    {
        return (a, c) -> this.apply(a, b -> that.apply(b, c));
    }
}


text:
function(e, $select) {
    $$(this).registerItemsSelect($select);
}


text:
package com.dougkoellmer.server.homecells;

import swarm.shared.structs.CellSize;

import com.dougkoellmer.server.homecells.FileBasedHomeCellContent.Type;
import com.dougkoellmer.server.homecells.YouTubeContent.E_Thumb;
import com.dougkoellmer.shared.homecells.E_HomeCell;
import com.dougkoellmer.shared.homecells.S_HomeCell;

//--- DRK > Doing this rather inefficiently with giant switch cases (assuming java doesn't
//---		optimize them and they're just if/else chains under the hood) in the interest
//---		of keeping everything readable and easily adjustable relative to other home cell data.
public class U_HomeCellMeta
{
	public static String getDescription(E_HomeCell homeCell)
	{
		switch(homeCell)
		{
			case HOME:							return "";

			case PRECIOUSES:					return "";
			case SWORD:							return 	"Ceremonial sword from
Papua New Guinea";
			case WOODEN_CUP:					return 	"Cup machined from
white oak sapling";
			case HATCHET:						return 	"Multipurpose hatchet
handcrafted in Sweden";
			case MITER_SAW:						return 	"Precision hand miter
saw made in Sweden";
			case CARVING_TOOLS:					return 	"Wood carving tools
made in Japan";
			case VACUUM_SEALER:					return 	"Vacuum sealer
for mason jars";
			case LIGHTER:						return 	"Waterproof wick-style
survival lighter";

			case ABILITIES:						return "";
			case FOOT_JUGGLING:					return 	"Juggling tennis
ball with only feet";
			case JUGGLING:						return 	"Juggling three tennis
balls, various tricks";
			case FAST_SHUFFLE:					return 	"Shuffling cards as
fast as possible";
			case CARD_DECK_SPLIT:				return 	"Splitting deck of
cards with one hand";
			case CARD_THROW:					return 	"Throwing playing cards
into and through things";
			case PEN_TWIRL:						return 	"Twirling pen
through four fingers";
			case BOTTLE_OPENING:				return 	"Opening beer bottles
with everyday items";
			case FAST_SHOE_TIE:					return 	"Tying shoelaces as
fast as possible";
			case ONE_HAND_MATCH_LIGHT:			return 	"Lighting match from
matchbook one-handed";
			case FAST_SHIRT_SWAP:				return 	"T-shirt on/off as
fast as possible";

			case SOFTWARE:						return "";
			case FOR_COMPUTERS:					return "";
			case PRESSURE:						return "Air pressure simulation
& molecular movement";
			case PRESSURE_AND_HEAT:				return "Air pressure simulation
with heat effects";
			case RADIOACTIVE_DECAY:				return "Radioactive decay and
half-life simulation";
			case CORROSION_CELL:				return "Metal corrosion &
electricity simulation";
			case FEED_THE_BEAR:					return "Game with polar bear
hunting like crocodile";
			case SWARM:							return "Open-source HTML5
content engine";
			case B33HIVE:						return "Open-source HTML5
application platform";
			case QUICKPHYX:						return "Open-source physics
engine for games";
			case CORROSION_GAME:				return "Training module for the
Department of Defense";
			case GLUE:							return "2d heightfield-based
viscous fluid simulation";
			case WHIP_THE_RAGDOLL:				return "Evil stress reliever
with ragdoll beatdown";
			case TOUCH_TONE_HERO:				return "Rhythm-based iOS game
using touch-tone keypad";
			case BALANCE_THING_GAME:			return "Physics game where you
balance crazy objects";
			case FIREWORKS:						return "Fireworks for end-game
celebration screen";
			case GRAVITATION:					return "Physics simulation
of planetary gravity";

			case FOR_BIOTICS:					return "";
			case RESUME:						return "Experimenting with new
kind of resume format";
			case PORTFOLIO:						return "Programmer-friendly
work portfolio";
			case POLISH_FOREST_ADVENTURE:		return "Disturbing walk in cold
misty forest in Poland";
			case SPANISH_OPERA_ADVENTURE:		return "Fantastical experience
travelling in Spain";
			case OLD_FRIEND:					return "Poem about passing old
friend from childhood";
			case GRAND_IDEAS:					return "Grand societal changes
that will never happen";
			case MUSINGS:						return "Random musings on life
and nature of reality";
			case WHAT_IS_CORROSION:				return "Essay for the layman on
how corrosion works";
			case PERFECT_COFFEE:				return "How to make the
perfect cup of coffee";

			case CREATIONS:						return "";
			case USEFUL:						return "";
			case INVENTIONS:					return "";
			case BIKE_CARD_THING:				return "Polite alternative to
annoying bicycle bells";
			case DOWEL_HOLDER:					return "Easy way to store long
thin pieces of material";
			case OUTDOOR_TOOL_HOLDER:			return "Easy way to store
assorted outdoor tools";
			case GUITAR_CASE:					return "Guitar case that can
survive nuclear bombs";
			case FLASHLIGHT_LAMP:				return "Converts flashlight
into diffuse lamp";
			case SLING_SHOT:					return "Primitive take on
wrist-braced slingshots";
			case BREAKAWAY_KNOT:				return "Lanyard knot that unties
upon abrupt force";
			case SANDER_HOLDER:					return "Holder for running
electric sander";
			case RASP_HANDLE:					return "Easy wood handle
for rat-tailed tools";
			case HANGING_CRATES:				return "Hanging garage storage
using milk crates";
			case LIFE_HACKS:					return "Quick hacks with
everyday items";
			case TORSION_KNOT:					return "Knot that gets crazy
tight using torsion";

			case SUNDRY:						return "";
			case TERMINATOR_GLASSES:			return "Glasses that make you
look like Terminator";
			case CANVAS_BAG:					return "Hand-sewn canvas
draw-string pouch";
			case CANVAS_WRAP:					return "Hand-sewn canvas
needle file holder";
			case SANTOKU_SHEATH:				return "Sturdy leather sheath
for santoku knife";
			case F1_SHEATH_MOD:					return "Modification of F1
survival knife sheath";
			case SAW_SHEATH:					return "Magnetic sheath for
rip and crosscut saws";
			case BROOM:							return "Stiff-bristle broom for
cleaning wood shop";
			case FIRE_POI:						return "Fire poi with kevlar
monkey-fist knots";
			case JUGGLING_TORCHES:				return "Juggling torches made
from various pipes";
			case THROWING_KNIVES:				return "Throwing knives ground
from steel blanks";
			case STONE_CUP:						return "Caveman cup hewn from
block of solid granite";
			case FIRE_POKER:					return "Oaken-handled fire
poker with steel dowel";

			case WOOD:							return "";
			case TILLER_TREE:					return "Tiller tree to assist
in making wooden bows";
			case THROWING_KNIFE_TARGET:			return "Portable target for
throwing knife practice";
			case WOOD_MALLET:					return "Big hickory mallet
for rough woodworking";
			case COASTERS:						return "Coasters made from
poplar cross sections";
			case KITCHEN_UTENSILS:				return "Set of cooking utensils
made from white oak";
			case SHAKERS:						return "Set of salt and pepper
shakers from white oak";
			case BIKE_RACK:						return "Mounted bike rack
made from white oak";
			case BACKSCRATCHER_1:				return "Graceful backscratcher
made from sugar maple";
			case BACKSCRATCHER_2:				return "Manly backscratcher
made from red oak";
			case CUTTING_BOARD_STAND:			return "Cutting board stand
using no metal fasteners";
			case CUTTING_BOARD:					return "Massive cutting board
made from rock maple";
			case BOW_1:							return "Recurved maple flat bow
with canvas backing";
			case BOW_2:							return "Red oak long bow
with canvas backing";
			case DOORSTOP:						return "Doorstop made from
length of poplar sapling";
			case DOGGIE_RAMP:					return "Ramp for little doggies
to get to high places";
			case OAR:							return "Oar carved from
solid log of hickory";
			case BOOMERANG:						return "Boomerang made from
strips of various woods";
			case COASTER_HOLDER:				return "Decorative holder for
circular drink coasters";
			case RED_OAK_SPOON:					return "Head-thumping spoon
made from red oak";
			case PLYWOOD_PUNISHER:				return "3-person sled made
of steam-bent plywood";

			case ART:							return "";
			case ROSE:							return "Realistic rose drawn
with colored pencils";
			case DRAGON:						return "Muscular dragon cast
from liquid plastic";
			case SOLAR_SYSTEM:					return "Alien solar system from
acid-etched zinc plate";
			case BANANA:						return "Realistic banana
drawn with pencil";
			case PEACEFUL_MAN:					return "Peaceful man & flowers
sculpted with clay";
			case LADY:							return "Mysterious lady painted
with limited colors";
			case BLACKHOLE:						return "Linoleum print block
of singularity";
			case INFINITE_TOLERANCE:			return "Sketch supporting
diversity & tolerance";
			case SAVE_ANIMALS:					return "Sketch supporting
all the animals";
			case DINOSAURS:						return "Sketch supporting
dinosaurs taking over";
			case QUICKB2_LOGO:					return "Logo for open
source physics engine";
			case B33HIVE_LOGO:					return "Logo & icons for open
source content engine";
			case MILKMAN:						return "Basswood carving of
1950s-era milkman";
			case MOTHER_AND_CHILD:				return "Ironwood carving of
a mother & child";
			case WOOD_CHAIN:					return "Chain carved from
solid rock maple";
			case GLASSES_HOLDER:				return "Rock maple holder
for reading glasses ";
		}

		return null;
	}

	public static I_HomeCellContent getContent(E_HomeCell cell)
	{
		switch(cell)
		{
			case HOME:							return new FileBasedHomeCellContent("home", Type.RAW);

			case PRECIOUSES:					return new ThumbnailHomeCellContent();
			case SWORD:							return new StripContent(cell);
			case WOODEN_CUP:					return new CellComingSoonContent();
			case HATCHET:						return new CellComingSoonContent();
			case MITER_SAW:						return new CellComingSoonContent();
			case CARVING_TOOLS:					return new CellComingSoonContent();
			case VACUUM_SEALER:					return new CellComingSoonContent();
			case LIGHTER:						return new CellComingSoonContent();

			case ABILITIES:						return new ThumbnailHomeCellContent();
//			case FOOT_JUGGLING:					return new CellComingSoonContent();
//			case JUGGLING:						return new CellComingSoonContent();
//			case FAST_SHUFFLE:					return new CellComingSoonContent();
//			case CARD_DECK_SPLIT:				return new CellComingSoonContent();
//			case CARD_THROW:					return new CellComingSoonContent();
//			case PEN_TWIRL:						return new CellComingSoonContent();
//			case BOTTLE_OPENING:				return new CellComingSoonContent();
//			case FAST_SHOE_TIE:					return new CellComingSoonContent();
//			case ONE_HAND_MATCH_LIGHT:			return new CellComingSoonContent();
//			case FAST_SHIRT_SWAP:				return new CellComingSoonContent();

			case SOFTWARE:						return new FileBasedHomeCellContent("software", Type.RAW);
			case FOR_COMPUTERS:					return new ThumbnailHomeCellContent();
			case PRESSURE:						return new IFrameContent(cell, "/games/pressure", true, "center");
			case PRESSURE_AND_HEAT:				return new IFrameContent(cell, "/games/pressure_and_heat", true, "center");
			case RADIOACTIVE_DECAY:				return new IFrameContent(cell, "/games/radioactive_decay", true, "center");
			case CORROSION_CELL:				return new CellComingSoonContent();
			case FEED_THE_BEAR:					return new IFrameContent(cell, "/games/feed_the_bear", false, "right");
			case SWARM:							return new CellComingSoonContent();
			case B33HIVE:						return new CellComingSoonContent();
			case QUICKPHYX:						return new CellComingSoonContent();
			case CORROSION_GAME:				return new CellComingSoonContent();
			case GLUE:							return new CellComingSoonContent();
			case WHIP_THE_RAGDOLL:				return new CellComingSoonContent();
			case TOUCH_TONE_HERO:				return new CellComingSoonContent();
			case BALANCE_THING_GAME:			return new CellComingSoonContent();
			case FIREWORKS:						return new CellComingSoonContent();
			case GRAVITATION:					return new CellComingSoonContent();

			case FOR_BIOTICS:					return new ThumbnailHomeCellContent();
			case RESUME:						return new ResumeContent();
			case PORTFOLIO:						return new PortfolioContent();
			case POLISH_FOREST_ADVENTURE:		return new FileBasedHomeCellContent("polish_forest", Type.RAW);
			case SPANISH_OPERA_ADVENTURE:		return new FileBasedHomeCellContent("spanish_adventure", Type.RAW);
			case OLD_FRIEND:					return new FileBasedHomeCellContent("old_friend", Type.RAW);
			case GRAND_IDEAS:					return new ListContent(cell, Lists.GRAND_IDEAS, ListContent.Type.TITLED);
			case MUSINGS:						return new ListContent(cell, Lists.MUSINGS, ListContent.Type.RAW);
			case WHAT_IS_CORROSION:				return new FileBasedHomeCellContent("corrosion", Type.RAW);
			case PERFECT_COFFEE:				return new FileBasedHomeCellContent("coffee", Type.RAW);

			case CREATIONS:						return new FileBasedHomeCellContent("creations", Type.RAW);
			case USEFUL:						return new FileBasedHomeCellContent("useful", Type.RAW);
			case INVENTIONS:					return new ThumbnailHomeCellContent();
			case BIKE_CARD_THING:				return new CellComingSoonContent();
			case DOWEL_HOLDER:					return new CellComingSoonContent();
			case OUTDOOR_TOOL_HOLDER:			return new CellComingSoonContent();
			case GUITAR_CASE:					return new YouTubeAndStripContent(cell, E_Thumb.SDDEFAULT);
			case FLASHLIGHT_LAMP:				return new StripContent(cell);
			case SLING_SHOT:					return new CellComingSoonContent();
			case BREAKAWAY_KNOT:				return new CellComingSoonContent();
			case SANDER_HOLDER:					return new CellComingSoonContent();//StripContent(cell);
			case RASP_HANDLE:					return new StripContent(cell);
			case HANGING_CRATES:				return new CellComingSoonContent();
			case LIFE_HACKS:					return new ListContent(cell, List_LifeHacks.LIST, ListContent.Type.TITLED);
			case TORSION_KNOT:					return new CellComingSoonContent();

			case SUNDRY:						return new ThumbnailHomeCellContent();
			case TERMINATOR_GLASSES:			return new StripContent(cell);
			case CANVAS_BAG:					return new SingleImageContent(cell);
			case CANVAS_WRAP:					return new StripContent(cell);
			case SANTOKU_SHEATH:				return new StripContent(cell);
			case F1_SHEATH_MOD:					return new CellComingSoonContent();
			case SAW_SHEATH:					return new StripContent(cell);
			case BROOM:							return new CellComingSoonContent();
			case FIRE_POI:						return new StripContent(cell, "center");
			case JUGGLING_TORCHES:				return new SingleImageContent(cell);
			case THROWING_KNIVES:				return new SingleImageContent(cell);
			case STONE_CUP:						return new SingleImageContent(cell);
			case FIRE_POKER:					return new StripContent(cell, "center");

			case WOOD:							return new ThumbnailHomeCellContent();
			case TILLER_TREE:					return new CellComingSoonContent();
			case THROWING_KNIFE_TARGET:			return new CellComingSoonContent();
			case WOOD_MALLET:					return new CellComingSoonContent();
			case COASTERS:						return new CellComingSoonContent();
			case KITCHEN_UTENSILS:				return new SingleImageContent(cell);
			case SHAKERS:						return new SingleImageContent(cell);
			case BIKE_RACK:						return new CellComingSoonContent();
			case BACKSCRATCHER_1:				return new StripContent(cell, "right");
			case BACKSCRATCHER_2:				return new SingleImageContent(cell);
			case CUTTING_BOARD_STAND:			return new CellComingSoonContent();
			case CUTTING_BOARD:					return new CellComingSoonContent();
			case BOW_1:							return new StripContent(cell, "bottom");
			case BOW_2:							return new SingleImageContent(cell, "top");
			case DOORSTOP:						return new SingleImageContent(cell, "center");
			case DOGGIE_RAMP:					return new CellComingSoonContent();
			case OAR:							return new StripContent(cell);
			case BOOMERANG:						return new StripContent(cell);
			case COASTER_HOLDER:				return new StripContent(cell);
			case RED_OAK_SPOON:					return new StripContent(cell);
//			case PLYWOOD_PUNISHER:				return new YouTubeContent(cell);

			case ART:							return new ThumbnailHomeCellContent();
			case ROSE:							return new SingleImageContent(cell, "left");
			case DRAGON:						return new StripContent(cell, "center");
			case SOLAR_SYSTEM:					return new SingleImageContent(cell, "center");
			case BANANA:						return new SingleImageContent(cell, "center");
			case PEACEFUL_MAN:					return new SingleImageContent(cell, "center");
			case LADY:							return new SingleImageContent(cell, "top");
			case BLACKHOLE:						return new SingleImageContent(cell, "center");
			case INFINITE_TOLERANCE:			return new SingleImageContent(cell, "center");
			case SAVE_ANIMALS:					return new SingleImageContent(cell, "center");
			case DINOSAURS:						return new SingleImageContent(cell, "center");
			case QUICKB2_LOGO:					return new SingleImageContent(cell, "center");
			case B33HIVE_LOGO:					return new SingleImageContent(cell, "center");
			case MILKMAN:						return new StripContent(cell, "center");
			case MOTHER_AND_CHILD:				return new SingleImageContent(cell, "top");
			case WOOD_CHAIN:					return new StripContent(cell, "center");
			case GLASSES_HOLDER:				return new StripContent(cell, "center");
		}

		if( getVideoId(cell) != null )
		{
			return new YouTubeContent(cell,  E_Thumb.MAXRESDEFAULT);
		}

		return new CellComingSoonContent();
	}

	static String getVideoId(E_HomeCell cell)
	{
		switch(cell)
		{
			case PLYWOOD_PUNISHER:			return "f_SfUpol2Ok";
			case GUITAR_CASE:				return "tkmwiwan8-M";
		}

		return null;
	}

}


text:
<?php
return [
    'require' => 'there\'s missing data !',
    'name1' => 'role english name can\'t be empty !',
    'name2' => 'chosen english name already exist !',
    'name3' => 'role arabic name can\'t be empty !',
    'name4' => 'chosen arabic name already exist !',
    'access1' => 'select access',
    'access2' => 'this access already exist !',
    'basic-roles' => 'you can\'t delete this role',
    'delete' => 'role successfully deleted',
    'no-change' => 'you don\'t change anything',
    'update' => 'your successfully update the role
you will be redirect automatically .',
    'done' => 'your successfully create the role
you will be redirect automatically .',
];


text:
using System.Collections.Generic;
using Azure.Core;

namespace Azure.ResourceManager.Compute.Models
{
    /// <summary> The DedicatedHostGroupInstanceView. </summary>
    public partial class DedicatedHostGroupInstanceView
    {
        /// <summary> Initializes a new instance of DedicatedHostGroupInstanceView. </summary>
        internal DedicatedHostGroupInstanceView()
        {
            Hosts = new ChangeTrackingList<DedicatedHostInstanceViewWithName>();
        }

        /// <summary> Initializes a new instance of DedicatedHostGroupInstanceView. </summary>
        /// <param name="hosts"> List of instance view of the dedicated hosts under the dedicated host group. </param>
        internal DedicatedHostGroupInstanceView(IReadOnlyList<DedicatedHostInstanceViewWithName> hosts)
        {
            Hosts = hosts;
        }

        /// <summary> List of instance view of the dedicated hosts under the dedicated host group. </summary>
        public IReadOnlyList<DedicatedHostInstanceViewWithName> Hosts { get; }
    }
}


text:
//CakeJS.Database.Statement.MysqlStatement

//Types
import {PDOStatement} from './PDOStatement';

export class MysqlStatement extends PDOStatement
{
	_results = [];
	_cursor = 0;
	_statementInfo = null;
	async execute(params = null)
	{
		var results = await this._driver.execute(this._statement, this._columns);
		if(typeof results[0] === 'object' && results[0] instanceof Array){
			for(var mysqlRow of results[0]){
				this._results.push(Object.cast(mysqlRow));
			}
		}else if(results[0] !== null && typeof results[0] === 'object'){
			this._statementInfo = Object.cast(results[0]);
		}
		return this;
	}

	rowCount()
	{
		if ('affectedRows' in this._statementInfo) {
			return this._statementInfo.affectedRows;
		}

		return this._results.length;
	}

	lastInsertId(table = null, column = null)
	{
		if ('insertId' in this._statementInfo) {
			return this._statementInfo.insertId;
		}

		throw new Exception('No insert id was found');
	}

	fetch(type = 'num')
	{
		if(!(this._cursor in this._results)){
			return false;
		}
		var item = this._results[this._cursor];
		this._cursor++;
		if(type === 'num'){
			return Object.values(item);
		}
		return item;
	}

	fetchAll(type = 'num')
	{
		var items = [];
		do{
			var item = this.fetch(type);
			if(item !== false){
				items.push(item);
			}
		}while(item !== false);
		return items;
	}

	get results()
	{
		return this._results;
	}

}


text: COMMENT ON TABLE person IS 'A String';


text:
'use strict';

/**
 * Module dependencies.
 */

const mongoose = require('mongoose');
const { wrap: async } = require('co');
const express = require('express');
const router = express.Router();
const only = require('only');
const { respond, respondOrRedirect } = require('../utils');
const Article = mongoose.model('Article');
const assign = Object.assign;

var base = require('./base').configure(Article, "articles");

router.param('_id', base.findOne);

router.get('/index', base.index);
router.get('/datatable', base.datatable);

router.get('/edit/:_id?', base.edit);
router.post('/create',   base.post);
router.post('/edit/:_id',   base.put);
router.delete('/delete/:_id',   base.delete);

router.param('id', async(function* (req, res, next, id) {
  try {
    req.article = yield Article.load(id);
    if (!req.article) return next(new Error('Article not found'));
  } catch (err) {
    return next(err);
  }
  next();
}));

router.get('/new', function (req, res) {
  res.render('articles/new', {
    title: 'New Article',
    article: new Article()
  });
});

router.post('/', async(function* (req, res) {
  const article = new Article(only(req.body, 'title body tags'));
  article.user = req.user;
  try {
    yield article.uploadAndSave(req.file);
    respondOrRedirect({ req, res }, `/articles/${article._id}`, article, {
      type: 'success',
      text: 'Successfully created article!'
    });
  } catch (err) {
    respond(res, 'articles/new', {
      title: article.title || 'New Article',
      errors: [err.toString()],
      article
    }, 422);
  }
}));

router.get('/:id/edit', function (req, res) {
  res.render('articles/edit', {
    title: 'Edit ' + req.article.title,
    article: req.article
  });
});

router.put('/', async(function* (req, res) {
  const article = req.article;
  assign(article, only(req.body, 'title body tags'));
  try {
    yield article.uploadAndSave(req.file);
    respondOrRedirect({ res }, `/articles/${article._id}`, article);
  } catch (err) {
    respond(res, 'articles/edit', {
      title: 'Edit ' + article.title,
      errors: [err.toString()],
      article
    }, 422);
  }
}));

router.get('/:id', function (req, res) {
  respond(res, 'articles/show', {
    title: req.article.title,
    article: req.article
  });
});

router.delete('/:id', async(function* (req, res) {
  yield req.article.remove();
  respondOrRedirect({ req, res }, '/articles', {}, {
    type: 'info',
    text: 'Deleted successfully'
  });
}));

 module.exports = router;