text:
/*
 * This page defines Buttons for Data Entry Tasks and Requests.
 */
(function() {
    var getReturnURL = function() {
        return LABKEY.ActionURL.getParameter('srcURL') || LABKEY.ActionURL.getParameter('returnUrl') || LABKEY.ActionURL.getParameter('returnURL') || LABKEY.ActionURL.buildURL('project', 'start');
    };

    var registerBtn = function(name, config) {
        _.extend(config, {
            itemId: name + "-formButton"
        });

        return EHR.DataEntryUtils.registerDataEntryFormButton(name, config);
    };
    var getBtn = function(name) {
        return EHR.DataEntryUtils.getDataEntryFormButton(name);
    };

    /*
     *  This button saves the form to the database, without changing QCStates
     *  at all, and stays on the same page
     */
    var SaveButtonName = "WNPRC_SAVE";
    registerBtn(SaveButtonName, {
        text:           "Save",
        successURL:     false, // don't navigate page
        disabled:       false,
        errorThreshold: "ERROR",
        tooltip:        "Save changes to this record and remain on this page.",
        handler: function(btn) {
            this.onSubmit(btn);
        }
    });

    /*
     *  This button saves the form to the database, without changing QCStates
     *  at all, and returns to whatever page sent it here.
     */
    var SaveAndExitButtonName = "WNPRC_SAVE_AND_EXIT";
    registerBtn(SaveAndExitButtonName, _.extend(getBtn(SaveButtonName), {
        text:       "Save & Exit",
        successURL: getReturnURL(),
        tooltip:    "Save changes to this record, and then leave this page."
    }));

    /*
     * This can take an existing record and change it back to a scheduled state.
     */
    var SaveAsScheduledButtonName = "WNPRC_SAVE_AS_SCHEDULED";
    registerBtn(SaveAsScheduledButtonName, _.extend(getBtn(SaveButtonName), {
        text:          "Save As Scheduled",
        targetQC:      "Scheduled",
        hideOnQCState: "Scheduled"
    }));

    /*
     * This takes all the records on the page and sets their QCState to the value
     * on the task record, should one exist.
     */
    var FixQCStateButtonName = "WNPRC_FIX_QCSTATE";
    registerBtn(FixQCStateButtonName, _.extend(getBtn(SaveButtonName), {
        text: "Fix QCState on Records",
        handler: function(btn) {
            var storeCollection = this.storeCollection;
            var taskStore = storeCollection.getServerStoreForQuery("ehr", "Tasks");
            var taskRecord = taskStore.getAt(0);

            if (taskRecord) {
                var qcstate = taskRecord.get('qcstate');

                jQuery.each(storeCollection.serverStores.getRange(), function(i, store) {
                    if (store !== taskStore) {
                        jQuery.each(store.getRange(), function(i, rec) {
                            rec.set('QCState', qcstate);
                        })
                    }
                });
            }

            this.onSubmit(btn);
        }
    }));

    /*
     * This takes a scheduled task and puts it In Progress, and then refreshes the page.
     */
    var StartTaskButtonName = "WNPRC_START_TASK";
    registerBtn(StartTaskButtonName, {
        text:              "Start Task",
        requiredQC:        "In Progress",  // Button only shows if user has permission for this QCState
        targetQC:          "In Progress",
        onlyShowOnQCState: "Scheduled",
        errorThreshold:    "ERROR",
        successURL:        false,
        tooltip:           "Set the status of this record to \"In Progress\", and refresh the page.",
        handler: function(btn) {
            this.onSubmit(btn);
        }
    });

    /*
     * This is a wrapper on the Submit For Review button to add the tooltip and change the success URL
     * to the WNPRC data entry page, instead of the EHR one.
     */
    let SubmitForReviewButtonName = "WNPRC_REVIEW";
    registerBtn(SubmitForReviewButtonName, _.extend(getBtn("REVIEW"), {
        successURL:    getReturnURL() || LABKEY.ActionURL.buildURL('wnprc_ehr', 'dataEntry.view'),
        tooltip:       "Set the status of this record to Review Required, save the record, and leave this page."
    }));

    /*
     * This is a wrapper on the Submit Final button to add the tooltip and change the success URL to
     * the WNPRC data entry page, instead of the EHR one.
     */
    var SubmitFinalButtonName = 'WNPRC_SUBMIT_FINAL';
    registerBtn(SubmitFinalButtonName, _.extend(getBtn("SUBMIT"), {
        successURL:    getReturnURL() || LABKEY.ActionURL.buildURL('wnprc_ehr', 'dataEntry.view'),
        hideOnQCState: "Scheduled",
        tooltip:       "Set the status of this record to Complete, save the record, and leave this page."
    }));

    /*
     * Prompt the user for a yes or no answer.  Resolves on "yes" and rejects with an error with a
     * message of "canceled" if "no" is selected.
     */
    var when$userConfirms = function(title, message) {
        return new Promise(function(resolve, reject) {
            Ext4.Msg.confirm(title, message, function(answer) {
                if (answer == 'yes') {
                    resolve();
                }
                else {
                    reject(new Error("canceled"));
                }
            });
        });
    };

    // For some reason, the JS parser doesn't like "study" sometimes, so we'll store it in a variable
    // to prevent the syntax highlighter from breaking
    var study = "study";

    var promptForDeathData = function(deathData) {
        /*
         * Check for demographic data
         */
        return WebUtils.API.selectRows(study, "demographics", {
            'Id~eq': deathData.deathRec.Id
        }).then(function(data) {
            if (!data || !data.rows || data.rows.length == 0) {
                throw new Error("There is no demographics record for this animal.  Please contact " +
                        "Colony Records to add one.")
            }

            return Promise.resolve(deathData)
        }).then(function(deathData) {
            var rec = deathData.record;
            var VM = {
                form: {
                    remark: ko.observable(rec.remark),
                    notAtCenter: ko.observable(rec.notAtCenter)
                }
            };

            return WNPRC.ExtUtils.loadWindow("DeathFormWindow", VM).then(function(window) {
                return window.display().then(function(VM) {
                    window.destroy();
                    return Promise.resolve(VM);
                });
            });
        });
    };

    var promptForPrenatalDeathData = function(deathData) {
        var rec = deathData.deathRec;

        // Initialize the VM
        var VM = {
            form: {
                dam:        ko.observable(rec.dam),
                gender:     ko.observable(rec.gender),
                species:    ko.observable(rec.species),
                conception: ko.observable(rec.conception),
                remark:     ko.observable(rec.remark),
                cage:       ko.observable(rec.cage),
                room:       ko.observable(rec.room),
                sire:       ko.observable(rec.sire)
            },
            errors:           ko.observableArray(),
            availableSpecies: ko.observableArray(),
            availableGenders: ko.observableArray()
        };

        // Subscribe the dam to automatically update the species, since dams should always
        // yield young of the same species.
        var updateSpeciesFromDam = function(val) {
            WebUtils.API.selectRows(study, "demographics", {
                'Id~eq': val
            }).then(function(data) {
                if (data.rows && data.rows.length > 0) {
                    VM.form.species(data.rows[0].species);
                }
            });
        };

        VM.form.dam.subscribe(updateSpeciesFromDam);
        if (VM.form.dam()) {
            updateSpeciesFromDam(VM.form.dam());
        }

        VM.errorMessage = ko.computed(function() {
            if (!(VM.form.dam() && VM.form.species() && VM.form.gender())) {
                return "You must specify a dam, species, and gender for all prenatal deaths.";
            }

            return "";
        });

        // Define a observable to disable the submit button when the user hasn't supplied all of the
        // required fields.
        VM.submitDisabled = ko.computed(function() {
            return !!VM.errorMessage();
        });

        // Grab the data needed to display the modal.
        return Promise.all([
            WNPRC.ExtUtils.loadWindow("PrenatalDeathFormWindow", VM),
            WebUtils.API.selectRows("ehr_lookups", "species"),
            WebUtils.API.selectRows("ehr_lookups", "gender_codes")
        ]).then(function(values) {
            var window = values[0];

            // Populate the selection lists with the lookup tables
            VM.availableSpecies(values[1].rows);
            VM.availableGenders(values[2].rows);

            var triggerChange = function($el) {
                $el.change();
            };

            // Apply typeahead to the dam field.
            var $damField = window.$modal.find('.dam-field').typeahead({ minLength: 4 }, {
                name: 'dams',
                source: function(q, syncCallback, cb) {
                    WebUtils.API.executeSql(study, "SELECT * FROM study.demographics WHERE gender.code = 'f' AND Id LIKE '%" + q + "%'").then(function(data) {
                        cb(data.rows);
                    });
                },
                display: function(record) {
                    return record.Id;
                },
                templates: {
                    suggestion: function(record) {
                        return '
' + record.Id + '
'
                    }
                }
            });

            $damField.on("typeahead:selected",      function() { triggerChange($damField) });
            $damField.on("typeahead:autocompleted", function() { triggerChange($damField) });

            // Apply typeahead to the sire field.
            var $sireField = window.$modal.find('.sire-field').typeahead({ minLength: 4 }, {
                name: 'sires',
                source: function(q, syncCallback, cb) {
                    WebUtils.API.executeSql(study, "SELECT * FROM study.demographics WHERE gender.code = 'm' AND Id LIKE '%" + q + "%'").then(function(data) {
                        cb(data.rows);
                    });
                },
                display: function(record) {
                    return record.Id;
                },
                templates: {
                    suggestion: function(record) {
                        return '
' + record.Id + '
'
                    }
                }
            });

            $sireField.on("typeahead:selected",      function() { triggerChange($sireField) });
            $sireField.on("typeahead:autocompleted", function() { triggerChange($sireField) });

            // Typeahead screws with the display, adding "inline-block" to the element itself, so this
            // switches it back to be full width
            $('.twitter-typeahead').css('display', '');

            return window.display().then(function(VM) {
                window.destroy();
                return Promise.resolve(VM);
            });
        });
    };

    /*
     * This promise presents the user with a modal form to edit some extra demographic information
     * for a death record.  It resolves when the user hits submit, and rejects with an error whose
     * message contains "canceled" if the user presses cancel.  If it rejects with any other error,
     * that indicates an unexpected exception.
     */

    var updateDeathTable = function(btn, callback) {
        return Promise.resolve().then(function() {
            var panel       = btn.up('ehr-dataentrypanel');
            var deathRec    = {};

            var necropsyStore = panel.storeCollection.getClientStoreByName("Necropsies");
            var necropsyRec = necropsyStore.getAt(0);

            var weightStore = panel.storeCollection.getClientStoreByName("Weight");
            var weightRec = weightStore.getAt(0);

            // Grab required info from the record
            try {
                _.extend(deathRec, {
                    Id:      necropsyRec.get('Id'),
                    date:    necropsyRec.get('timeofdeath'),
                    cause:   necropsyRec.get('causeofdeath'),
                    project: necropsyRec.get('project')
                });

                if (!deathRec.Id || !deathRec.date || !deathRec.cause || !deathRec.project) {
                    throw new Error();
                }
            }
            catch(e) {
                throw new Error("Must provide Id, project, type of death, and time of death");
            }

            // Determine whether this is a prenatal death
            var isPrenatalDeath = deathRec.Id.match(/^pd/);
            var queryName = isPrenatalDeath ? 'Prenatal Deaths' : 'Deaths';

            // Grab the weight for prenatal deaths (there is no weight column for death records).
            try {
                deathRec.weight = weightRec.get('weight');
            }
            catch(e) {
                if (isPrenatalDeath) {
                    deathRec.weight = null;
                }
            }

            // Even though weights are not in Death records, the triggered email needs
            // this field to be filled out.
            if (!isPrenatalDeath && !Ext4.isNumber(deathRec.weight)) {
                throw new Error("You must provide a weight.");
            }

            // Grab the other info.
            var getNecropsyValue = function(columnName) {
                try {
                    return necropsyRec.get(columnName);
                }
                catch(e) {
                    return "";
                }
            };
            _.extend(deathRec, {
                manner:       getNecropsyValue('mannerofdeath'),
                necropsy:     getNecropsyValue('caseno'),
                parentid:     getNecropsyValue('objectid'),
                necropsyDate: getNecropsyValue('date')
            });

            // Determine whether this is a prenatal death
            var isPrenatalDeath = deathRec.Id.match(/^pd/);
            var queryName = isPrenatalDeath ? 'Prenatal Deaths' : 'Deaths';

            var cols = ['lsid', 'Id', 'date', 'remark', 'QCState', 'taskid'];
            if (isPrenatalDeath) {
                cols.push('species', 'gender', 'dam', 'sire', 'room', 'cage', 'conception');
            }
            else {
                cols.push('tattoo', 'cause', 'manner', 'necropsy', 'remark', 'performedby', 'notAtCenter');
            }

            // Grab the weight for prenatal deaths (there is no weight column for death records).
            if (isPrenatalDeath) {
                try {
                    deathRec.weight = weightRec.get('weight');
                }
                catch(e) {
                    deathRec.weight = null;
                }
                _.extend(deathRec, {
                    dam: getNecropsyValue('dam')
                });
            }

            return Promise.all([
                Promise.resolve({
                    deathRec: deathRec,
                    queryName: queryName,
                    isPrenatalDeath: isPrenatalDeath
                }),
                WebUtils.API.selectRows('study', queryName, {'Id~eq': deathRec.Id, columns: cols })
            ]);
        }).then(function(data) {
            var deathData = data[0];
            deathData.recordExists = data[1] && data[1].rows && data[1].rows.length;
            deathData.record = deathData.recordExists ? data[1].rows[0] : {};

            if (deathData.recordExists) {
                deathData.deathRec.lsid = data[1].rows[0].lsid;

                return when$userConfirms("Update Death Record", "Death record already exists.  Do you want to update it?").then(function() {
                    return when$userConfirms("", "Do you want to resend the death notification email?").then(function () {
                        deathData.resendEmail = true;
                        return Promise.resolve(deathData);
                    })['catch'](function () {
                        return Promise.resolve(deathData);
                    });
                });
            }
            else {
                return when$userConfirms('Finalize Death', 'You are about to finalize this death record on this animal.  This will end all treatments, problems, assignments and housing. BE ABSOLUTELY SURE YOU WANT TO DO THIS BEFORE CLICKING YES.').then(function() {
                    return Promise.resolve(deathData);
                });
            }
        }).then(function(deathData) {
            return (deathData.isPrenatalDeath ? promptForPrenatalDeathData(deathData) : promptForDeathData(deathData)).then(function(VM) {
                _.extend(deathData.deathRec, ko.mapping.toJS(VM.form));

                return Promise.resolve(deathData);
            });
        }).then(function(deathData) {
            // Actually submit the record
            Ext4.Msg.wait('Saving...');
            var savePromise;
            var config = {
                extraContext: {
                    resendEmail: deathData.resendEmail
                }
            };

            if (deathData.recordExists) {
                savePromise = WebUtils.API.updateRows('study', deathData.queryName, [deathData.deathRec], config);
            }
            else {
                savePromise = WebUtils.API.insertRows('study', deathData.queryName, [deathData.deathRec], config);
            }

            return Promise.all([
                Promise.resolve(deathData),
                savePromise
            ]);
        }).then(function(data) {
            var deathData = data[0];

            // Inform the user of our success
            var verb = deathData.recordExists ? 'updated' : 'inserted';
            Ext4.Msg.hide();
            Ext4.Msg.alert("", "Successfully " + verb + " " + deathData.queryName + " from necropsy for " + deathData.deathRec.Id);

            return new Promise(function(resolve, reject) {
                Ext4.Msg.on("hide", function() {
                    resolve();
                }, null, {single: true});
            });
        });
    };

    var cancelErrorHandler = function(e) {
        if (Ext4.Msg.isVisible()) {
            Ext4.Msg.hide();
        }

        if (e && e.message != "canceled") {
            Ext4.Msg.alert("ERROR", "An error occurred: " + (e.message) ? e.message : e.exception);
        }
    };

    /*
     *  This inserts into or updates either the Prenatal Deaths or the regular Deaths table with
     *  information from the necropsy.  The insertion will cause the trigger scripts to
     *  close treatments, housing, etc., and will send a Death Notification email out.
     */
    registerBtn('FINALIZE_DEATH', {
        text:           'Finalize Death',
        requiredQC:     'In Progress',
        targetQC:       'In Progress',
        errorThreshold: 'INFO',
        successURL:     false,
        disabled:       true,
        disableOn:      'ERROR',
        tooltip:        "This starts the task and inserts into or updates either the Prenatal Deaths or the regular Deaths table with information from the necropsy.  The insertion will cause any assigned treatments, housing, etc. to be closed, and will send a Death Notification email out.",
        handler: function(btn) {
            this.saveRecords(btn).then(function() {
                return updateDeathTable(btn).then(function() {
                    window.location.reload();
                });
            })['catch'](cancelErrorHandler);
        },
        shouldHide: function(buttonConfig) {
            var taskDataEntryPanel = this;
            var necropsyStore = this.storeCollection.getServerStoreForQuery('study', 'necropsy');
            var necropsyRecord = _.isDefined(necropsyStore) ? necropsyStore.getAt(0) : undefined;

            if (_.isDefined(necropsyRecord)) {
                var Id = necropsyRecord.get('Id');

                Promise.resolve().then(function() {
                    if (Id.match(/^pd/i)) {
                        return WebUtils.API.selectRows('study', 'prenatal', {
                            'Id~eq': Id
                        });
                    }
                    else {
                        return WebUtils.API.selectRows('study', 'deaths', {
                            'Id~eq': Id
                        });
                    }
                }).then(function(data) {
                    var panel = taskDataEntryPanel;
                    var btn = panel.queryById(buttonConfig.itemId);

                    if (_.isDefined(btn)) {
                        if (data && data.rows && data.rows.length > 0) {
                            btn.hide();
                        }
                        else {
                            btn.show();
                        }
                    }
                })
            }

            // Hide until we confirm we should show.
            return true;
        }
    });

    registerBtn('UPDATE_DEATH', {
        text:           'Update Death',
        errorThreshold: 'INFO',
        successURL:     false, // don't navigate away from page.
        disabled:       true,
        disableOn:      'ERROR',
        tooltip:        "This inserts into or updates either the Prenatal Deaths or the regular Deaths table with information from the necropsy.  The insertion will cause any assigned treatments, housing, etc. to be closed, and will send a Death Notification email out.",
        handler: function(btn) {
            this.saveRecords(btn).then(function() {
                return updateDeathTable(btn)
            })['catch'](cancelErrorHandler);
        },
        shouldHide: function(buttonConfig) {
            var taskDataEntryPanel = this;
            var necropsyStore = taskDataEntryPanel.storeCollection.getServerStoreForQuery('study', 'necropsy');
            var necropsyRecord = _.isDefined(necropsyStore) ? necropsyStore.getAt(0) : undefined;

            if (_.isDefined(necropsyRecord)) {
                var Id = necropsyRecord.get('Id');

                Promise.resolve().then(function() {
                    if (Id.match(/^pd/i)) {
                        return WebUtils.API.selectRows('study', 'prenatal', {
                            'Id~eq': Id
                        });
                    }
                    else {
                        return WebUtils.API.selectRows('study', 'deaths', {
                            'Id~eq': Id
                        });
                    }
                }).then(function(data) {
                    var panel = taskDataEntryPanel;
                    var btn = panel.queryById(buttonConfig.itemId);

                    if (_.isDefined(btn)) {
                        if (data && data.rows && data.rows.length > 0) {
                            btn.show();
                        }
                        else {
                            btn.hide();
                        }
                    }
                })
            }

            // Hide until we get our callback;
            return true;
        }
    });

    /*
     *  Leaves the page without saving the form.
     */
    var CancelButtonName = "WNPRC_CANCEL";
    registerBtn(CancelButtonName, {
        text:       "Cancel",
        successURL: getReturnURL() || LABKEY.ActionURL.buildURL('wnprc_ehr', 'dataEntry.view'),
        tooltip:    "This will discard changes not yet saved to the database and exit the page.",
        handler: function(btn) {
            window.location = btn.successURL;
        }
    });

    /*
     * This is a wrapper on the Request button to allow .
     */
    var RequestButtonName = 'WNPRC_REQUEST';
    registerBtn(RequestButtonName, _.extend(getBtn("REQUEST"), {
        disableOn: 'ERROR'
    }));

    /*
     * Enable the save template button for all users.
     */
    var saveTemplateButtonName = "TEMPLATE";
    var saveTemplateButton = EHR.DataEntryUtils.getGridButton(saveTemplateButtonName);
    jQuery.each(saveTemplateButton.menu.items, function(i, item) {
        if (item.text.match(/save as template/i)) {
            delete item.hidden;
        }
    });
    EHR.DataEntryUtils.registerGridButton(saveTemplateButtonName, function(config) {
        return Ext4.apply(saveTemplateButton, config);
    });

    EHR.DataEntryUtils.registerGridButton('WNPRC_AUTO_ASSIGN_ORDER', function(config){
        return Ext4.Object.merge({
            text: 'Auto Assign Order',
            xtype: 'button',
            tooltip: 'This will automatically add order numbers to every row in this grid in the current order they display on screen',
            handler: function() {
                var self = this;
                var grid = this.up('grid');

                if (!grid) {
                    return;
                }

                var store = grid.getStore();
                if (!store) {
                    return;
                }

                Ext4.suspendLayouts();
                _.each(store.getRange(), function(rec, i) {
                    rec.set("collection_order", i * 10);
                });
                Ext4.resumeLayouts(true);
            }
        });
    });
})();


text:
package org.eclipse.gemini.management.permissionadmin;

import java.io.IOException;

import org.osgi.jmx.service.permissionadmin.PermissionAdminMBean;
import org.osgi.service.permissionadmin.PermissionAdmin;
import org.osgi.service.permissionadmin.PermissionInfo;

/**
 *
 */
public final class PermissionManager implements PermissionAdminMBean {

	private PermissionAdmin admin;

	public PermissionManager(PermissionAdmin admin) {
		this.admin = admin;
	}

	/**
	 * {@inheritDoc}
	 */
	public String[] listLocations() throws IOException {
		return admin.getLocations();
	}

	/**
	 * {@inheritDoc}
	 */
	public String[] getPermissions(String location) throws IOException {
		if (location == null) {
			throw new IOException("Locatin must not be null");
		}
		PermissionInfo[] permissions = admin.getPermissions(location);
		if (permissions == null) {
			return null;
		}
		String[] encodedPermissions = new String[permissions.length];
		int i = 0;
		for (PermissionInfo permission : permissions) {
			encodedPermissions[i++] = permission.getEncoded();
		}
		return encodedPermissions;
	}

	/**
	 * {@inheritDoc}
	 */
	public void setDefaultPermissions(String[] encodedPermissions) throws IOException {
		if (encodedPermissions == null) {
			throw new IOException("Encoded permissions must not be null");
		}
		PermissionInfo[] permissions = new PermissionInfo[encodedPermissions.length];
		int i = 0;
		for (String encodedPermission : encodedPermissions) {
			try {
				permissions[i] = new PermissionInfo(encodedPermission);
			} catch (Throwable e) {
				IOException iox = new IOException("Invalid encoded permission: " + encodedPermission);
				iox.initCause(e);
				throw iox;
			}
		}
		admin.setDefaultPermissions(permissions);
	}

	/**
	 * {@inheritDoc}
	 */
	public String[] listDefaultPermissions() throws IOException {
		PermissionInfo[] permissions = admin.getDefaultPermissions();
		if (permissions == null) {
			return null;
		}
		String[] encodedPermissions = new String[permissions.length];
		int i = 0;
		for (PermissionInfo permission : permissions) {
			encodedPermissions[i++] = permission.getEncoded();
		}
		return encodedPermissions;
	}

	/**
	 * {@inheritDoc}
	 */
	public void setPermissions(String location, String[] encodedPermissions) throws IOException {
		if (location == null) {
			throw new IOException("Location must not be null");
		}
		if (encodedPermissions == null) {
			throw new IOException("Encoded permissions must not be null");
		}
		PermissionInfo[] permissions = new PermissionInfo[encodedPermissions.length];
		int i = 0;
		for (String encodedPermission : encodedPermissions) {
			try {
				permissions[i] = new PermissionInfo(encodedPermission);
			} catch (Throwable e) {
				IOException iox = new IOException("Invalid encoded permission: " + encodedPermission);
				iox.initCause(e);
				throw iox;
			}
		}
		admin.setPermissions(location, permissions);
	}

}

redpajama_set_name: RedPajamaGithub


text:
<bill session="110" type="s" number="3539" updated="2009-01-09T19:16:02-05:00">
	<status><introduced date="1222142400" datetime="2008-09-23"/></status>

	<introduced date="1222142400" datetime="2008-09-23"/>
	<titles>
		<title type="short" as="introduced">Girl Scouts USA Centennial Commemorative Coin Act</title>
		<title type="official" as="introduced">A bill to require the Secretary of the Treasury to mint coins in commemoration of the centennial of the establishment of the Girl Scouts of the United States of America.</title>
	</titles>
	<sponsor id="300025"/>
	<cosponsors>
		<cosponsor id="300011" joined="2008-09-23"/>
		<cosponsor id="412251" joined="2008-09-30"/>
		<cosponsor id="300093" joined="2008-09-23"/>
		<cosponsor id="300073" joined="2008-09-23"/>
		<cosponsor id="300068" joined="2008-09-23"/>
		<cosponsor id="300054" joined="2008-09-23"/>
		<cosponsor id="300091" joined="2008-11-19"/>
		<cosponsor id="300076" joined="2008-09-26"/>
		<cosponsor id="300075" joined="2008-09-25"/>
		<cosponsor id="300063" joined="2008-09-23"/>
		<cosponsor id="412248" joined="2008-11-19"/>
		<cosponsor id="400194" joined="2008-10-02"/>
	</cosponsors>
	<actions>
		<action date="1222142400" datetime="2008-09-23"><text>Read twice and referred to the Committee on Banking, Housing, and Urban Affairs.</text></action>
	</actions>
	<committees>

	</committees>
	<relatedbills>

	</relatedbills>
	<subjects>

	</subjects>
	<amendments>

	</amendments>

	9/23/2008--Introduced.
Girl Scouts USA Centennial Commemorative Coin Act - Directs the Secretary of the Treasury to mint and issue up to 350,000 $1 coins in commemoration of the centennial of the Girl Scouts of the United States of America.
Requires the coin design to be emblematic of such centennial.
Requires such coins to be issued in uncirculated and proof qualities, from only one U.S. Mint facility.
Declares the sense of Congress that such facility should be the U.S. Mint at West Point, New York, to the greatest extent possible.
Authorizes the Secretary to issue such coins only during calendar 2011.
Applies a $10 per coin surcharge to all coin sales. Requires all surcharges received to be paid to the Girl Scouts of the United States of America for efforts involved in marking it centennial, which may include efforts to preserve the birthplace of founder Juliette Gordon Low.

</bill>


text:
public class Program {
    public Program() : base() {

    }
}


text:
package com.github.gunmetal313.ohdv1.utils;

import static org.junit.Assert.*;

public class IntMapTest {

}


text:
import {
  faCog,
  faTimesCircle,
  faChevronUp,
  faChevronDown,
} from '@fortawesome/free-solid-svg-icons';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import classNames from 'classnames';
import * as React from 'react';
import { useDispatch } from 'react-redux';
import Switch from 'react-switch';

import {
  filteredThreadIDsSelector,
  includeDeletedSelector,
} from 'lib/selectors/calendar-filter-selectors';
import SearchIndex from 'lib/shared/search-index';
import {
  calendarThreadFilterTypes,
  type FilterThreadInfo,
  updateCalendarThreadFilter,
  clearCalendarThreadFilter,
  setCalendarDeletedFilter,
} from 'lib/types/filter-types';
import type { Dispatch } from 'lib/types/redux-types';

import ThreadSettingsModal from '../modals/threads/thread-settings-modal.react';
import { useSelector } from '../redux/redux-utils';
import {
  webFilterThreadInfos,
  webFilterThreadSearchIndex,
} from '../selectors/calendar-selectors';
import { MagnifyingGlass } from '../vectors.react';
import css from './filter-panel.css';

type BaseProps = {
  +setModal: (modal: ?React.Node) => void,
};
type Props = {
  ...BaseProps,
  +filterThreadInfos: () => $ReadOnlyArray<FilterThreadInfo>,
  +filterThreadSearchIndex: () => SearchIndex,
  +filteredThreadIDs: ?$ReadOnlySet<string>,
  +includeDeleted: boolean,
  +dispatch: Dispatch,
};
type State = {
  +query: string,
  +searchResults: $ReadOnlyArray<FilterThreadInfo>,
  +collapsed: boolean,
};
class FilterPanel extends React.PureComponent<Props, State> {
  state: State = {
    query: '',
    searchResults: [],
    collapsed: false,
  };

  currentlySelected(threadID: string): boolean {
    if (!this.props.filteredThreadIDs) {
      return true;
    }
    return this.props.filteredThreadIDs.has(threadID);
  }

  render() {
    const filterThreadInfos = this.state.query
      ? this.state.searchResults
      : this.props.filterThreadInfos();

    let filters = [];
    if (!this.state.query || filterThreadInfos.length > 0) {
      filters.push(
        <Category
          numThreads={filterThreadInfos.length}
          onToggle={this.onToggleAll}
          collapsed={this.state.collapsed}
          onCollapse={this.onCollapse}
          selected={!this.props.filteredThreadIDs}
          key="all"
        />,
      );
    } else {
      filters.push(

          No results

,
      );
    }
    if (!this.state.collapsed) {
      const options = filterThreadInfos.map(filterThreadInfo => (
        <Item
          filterThreadInfo={filterThreadInfo}
          onToggle={this.onToggle}
          onClickOnly={this.onClickOnly}
          onClickSettings={this.onClickSettings}
          selected={this.currentlySelected(filterThreadInfo.threadInfo.id)}
          key={filterThreadInfo.threadInfo.id}
        />
      ));
      filters = [...filters, ...options];
    }

    let clearQueryButton = null;
    if (this.state.query) {
      clearQueryButton = (

          <FontAwesomeIcon icon={faTimesCircle} className={css.clearQuery} />

      );
    }

    return (

            <MagnifyingGlass className={css.searchVector} />
            <input
              type="text"
              placeholder="Search"
              value={this.state.query}
              onChange={this.onChangeQuery}
            />
            {clearQueryButton}

{filters}

            <Switch
              checked={this.props.includeDeleted}
              onChange={this.onChangeIncludeDeleted}
              checkedIcon={false}
              uncheckedIcon={false}
              height={20}
              width={40}
              id="include-deleted-switch"
            />
            Include deleted entries

    );
  }

  onToggle = (threadID: string, value: boolean) => {
    let newThreadIDs;
    const selectedThreadIDs = this.props.filteredThreadIDs;
    if (!selectedThreadIDs && value) {
      // No thread filter exists and thread is being added
      return;
    } else if (!selectedThreadIDs) {
      // No thread filter exists and thread is being removed
      newThreadIDs = this.props
        .filterThreadInfos()
        .map(filterThreadInfo => filterThreadInfo.threadInfo.id)
        .filter(id => id !== threadID);
    } else if (selectedThreadIDs.has(threadID) && value) {
      // Thread filter already includes thread being added
      return;
    } else if (selectedThreadIDs.has(threadID)) {
      // Thread being removed from current thread filter
      newThreadIDs = [...selectedThreadIDs].filter(id => id !== threadID);
    } else if (!value) {
      // Thread filter doesn't include thread being removed
      return;
    } else if (
      selectedThreadIDs.size + 1 ===
      this.props.filterThreadInfos().length
    ) {
      // Thread filter exists and thread being added is the only one missing
      newThreadIDs = null;
    } else {
      // Thread filter exists and thread is being added
      newThreadIDs = [...selectedThreadIDs, threadID];
    }
    this.setFilterThreads(newThreadIDs);
  };

  onToggleAll = (value: boolean) => {
    this.setFilterThreads(value ? null : []);
  };

  onClickOnly = (threadID: string) => {
    this.setFilterThreads([threadID]);
  };

  setFilterThreads(threadIDs: ?$ReadOnlyArray<string>) {
    if (!threadIDs) {
      this.props.dispatch({
        type: clearCalendarThreadFilter,
      });
    } else {
      this.props.dispatch({
        type: updateCalendarThreadFilter,
        payload: {
          type: calendarThreadFilterTypes.THREAD_LIST,
          threadIDs,
        },
      });
    }
  }

  onClickSettings = (threadID: string) => {
    this.props.setModal(
      <ThreadSettingsModal threadID={threadID} onClose={this.clearModal} />,
    );
  };

  onChangeQuery = (event: SyntheticEvent<HTMLInputElement>) => {
    const query = event.currentTarget.value;
    const searchIndex = this.props.filterThreadSearchIndex();
    const resultIDs = new Set(searchIndex.getSearchResults(query));
    const results = this.props
      .filterThreadInfos()
      .filter(filterThreadInfo =>
        resultIDs.has(filterThreadInfo.threadInfo.id),
      );
    this.setState({ query, searchResults: results, collapsed: false });
  };

  clearQuery = (event: SyntheticEvent<HTMLAnchorElement>) => {
    event.preventDefault();
    this.setState({ query: '', searchResults: [], collapsed: false });
  };

  onCollapse = (value: boolean) => {
    this.setState({ collapsed: value });
  };

  onChangeIncludeDeleted = (includeDeleted: boolean) => {
    this.props.dispatch({
      type: setCalendarDeletedFilter,
      payload: {
        includeDeleted,
      },
    });
  };

  clearModal = () => {
    this.props.setModal(null);
  };
}

type ItemProps = {
  +filterThreadInfo: FilterThreadInfo,
  +onToggle: (threadID: string, value: boolean) => void,
  +onClickOnly: (threadID: string) => void,
  +onClickSettings: (threadID: string) => void,
  +selected: boolean,
};
class Item extends React.PureComponent<ItemProps> {
  render() {
    const threadInfo = this.props.filterThreadInfo.threadInfo;
    const beforeCheckStyles = { borderColor: `#${threadInfo.color}` };
    let afterCheck = null;
    if (this.props.selected) {
      const afterCheckStyles = { backgroundColor: `#${threadInfo.color}` };
      afterCheck = (

      );
    }
    const details =
      this.props.filterThreadInfo.numVisibleEntries === 1
        ? '1 entry'
        : `${this.props.filterThreadInfo.numVisibleEntries} entries`;
    return (

          <input
            type="checkbox"
            checked={this.props.selected}
            onChange={this.onChange}
          />

            {threadInfo.uiName}
            {afterCheck}

            only

            <FontAwesomeIcon icon={faCog} />

{details}

    );
  }

  onChange = (event: SyntheticEvent<HTMLInputElement>) => {
    this.props.onToggle(
      this.props.filterThreadInfo.threadInfo.id,
      event.currentTarget.checked,
    );
  };

  onClickOnly = (event: SyntheticEvent<HTMLAnchorElement>) => {
    event.preventDefault();
    this.props.onClickOnly(this.props.filterThreadInfo.threadInfo.id);
  };

  onClickSettings = (event: SyntheticEvent<HTMLAnchorElement>) => {
    event.preventDefault();
    this.props.onClickSettings(this.props.filterThreadInfo.threadInfo.id);
  };
}

type CategoryProps = {
  +numThreads: number,
  +onToggle: (value: boolean) => void,
  +collapsed: boolean,
  +onCollapse: (value: boolean) => void,
  +selected: boolean,
};
class Category extends React.PureComponent<CategoryProps> {
  render() {
    const beforeCheckStyles = { borderColor: 'white' };
    let afterCheck = null;
    if (this.props.selected) {
      const afterCheckStyles = { backgroundColor: 'white' };
      afterCheck = (

      );
    }
    const icon = this.props.collapsed ? faChevronUp : faChevronDown;
    const details =
      this.props.numThreads === 1
        ? '1 thread'
        : `${this.props.numThreads} threads`;
    return (

          <input
            type="checkbox"
            checked={this.props.selected}
            onChange={this.onChange}
          />

            Your threads
            {afterCheck}

            <FontAwesomeIcon icon={icon} />

{details}

    );
  }

  onChange = (event: SyntheticEvent<HTMLInputElement>) => {
    this.props.onToggle(event.currentTarget.checked);
  };

  onCollapse = (event: SyntheticEvent<HTMLAnchorElement>) => {
    event.preventDefault();
    this.props.onCollapse(!this.props.collapsed);
  };
}

const ConnectedFilterPanel: React.ComponentType<BaseProps> = React.memo<BaseProps>(
  function ConnectedFilterPanel(props) {
    const filteredThreadIDs = useSelector(filteredThreadIDsSelector);
    const filterThreadInfos = useSelector(webFilterThreadInfos);
    const filterThreadSearchIndex = useSelector(webFilterThreadSearchIndex);
    const includeDeleted = useSelector(includeDeletedSelector);
    const dispatch = useDispatch();

    return (
      <FilterPanel
        {...props}
        filteredThreadIDs={filteredThreadIDs}
        filterThreadInfos={filterThreadInfos}
        filterThreadSearchIndex={filterThreadSearchIndex}
        includeDeleted={includeDeleted}
        dispatch={dispatch}
      />
    );
  },
);

export default ConnectedFilterPanel;


text:
import { connectScreenSize } from 'react-screen-size';
import { Container } from './common/RepoContainer';
import { countries } from '../../../../assets/dropdowns/countries';
import { Dropdown } from 'semantic-ui-react';
import FormField from './common/FormField';
import { isEqual } from 'lodash';
import ListItem from '../../common/ListItem';
import { mapScreenSizeToProps } from '../../../Navbar';
import React from 'react';
import Ribbon from './common/RibbonHeader';
import { TransitionContainer } from '../../../../styles/style-utils';

const INPUT_OPTIONS = 'small left icon';
const INFO_MESSAGE = `The FCCAN team may or may not send you emails in the
                      future (nothing for now). If so, we will give you
                      the option to opt-in to any email-related
                      features or regular newsletters.`;

class PersonalInfo extends React.Component {
  shouldComponentUpdate(nextProps) {
    return !isEqual(this.props, nextProps);
  }
  render() {
    const {
      bio,
      country,
      displayName,
      email,
      errors,
      handleCountryChange,
      handleInputChange,
      isPrivate,
      location,
      saveSection,
      screen: { isMobile, isTablet },
      showPopUp,
      showProfile,
      toggle,
      toggleEmailVisibilty,
    } = this.props;
    return (

        <Ribbon
          content="Personal Info"
          id="personalPopUp"
          onClick={() => toggle('showProfile')}
          saveSection={saveSection}
          showPopUp={showPopUp}
          showSave={showProfile} />
        <TransitionContainer className="ui form" isExpanded={showProfile}>
          <Container className="ui list">
            <ListItem>
              <FormField
                errors={errors}
                icon='user icon'
                inputOptions={INPUT_OPTIONS}
                name="displayName"
                onChange={handleInputChange}
                placeholder="Enter Display Name"
                tooltip="Display Name"
                value={displayName} />
            </ListItem>
            <ListItem>
              <FormField
                errors={errors}
                icon="mail icon"
                infoMessage={INFO_MESSAGE}
                inputOptions={INPUT_OPTIONS}
                isEmail={!errors.email && true}
                isPrivate={isPrivate}
                name="email"
                onChange={handleInputChange}
                placeholder="Enter Email"
                toggleEmailVisibilty={toggleEmailVisibilty}
                tooltip="Email"
                type="email"
                value={email} />
            </ListItem>
            <ListItem>
              <FormField
                errors={errors}
                icon="marker icon"
                inputOptions={INPUT_OPTIONS}
                name="location"
                onChange={handleInputChange}
                placeholder="Enter Location"
                tooltip="Location"
                value={location} />
            </ListItem>
            <ListItem>

                <Dropdown
                  onChange={handleCountryChange}
                  options={countries}
                  placeholder='Select Country'
                  search
                  selection
                  value={country} />
                { errors.country &&

                  {errors.country}

 }

            </ListItem>
            <ListItem>

                <textarea
                  name='bio'
                  onChange={handleInputChange}
                  placeholder="Enter a short bio here"
                  rows="3"
                  value={bio} />

              { errors.bio &&

                  {errors.bio}

 }
            </ListItem>
          </Container>
        </TransitionContainer>

    );
  }
}

export default connectScreenSize(mapScreenSizeToProps)(PersonalInfo);


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>graph</title>
<meta name="date" content="2015-12-04">
<link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style">

graph

Interfaces

TSP

Classes

Graph

IteratorSeq

TemplateTSP

TSP1


text:
package backup

import (
	"github.com/prometheus/client_golang/prometheus"
)

var (
	backupRegionCounters = prometheus.NewCounterVec(
		prometheus.CounterOpts{
			Namespace: "br",
			Subsystem: "raw",
			Name:      "backup_region",
			Help:      "Backup region statistic.",
		}, []string{"type"})

	backupRegionHistogram = prometheus.NewHistogram(
		prometheus.HistogramOpts{
			Namespace: "br",
			Subsystem: "raw",
			Name:      "backup_region_seconds",
			Help:      "Backup region latency distributions.",
			Buckets:   prometheus.ExponentialBuckets(0.05, 2, 16),
		})
)

func init() { // nolint:gochecknoinits
	prometheus.MustRegister(backupRegionCounters)
	prometheus.MustRegister(backupRegionHistogram)
}


text:
This document describes how to set up your development environment to build and test Angular, both
JS and Dart versions. It also explains the basic mechanics of using `git`, `node`, and `npm`.

* [Prerequisite Software](#prerequisite-software)
* [Getting the Sources](#getting-the-sources)
* [Environment Variable Setup](#environment-variable-setup)
* [Installing NPM Modules and Dart Packages](#installing-npm-modules-and-dart-packages)
* [Build commands](#build-commands)
* [Running Tests Locally](#running-tests-locally)
* [Code Style](#code-style)
* [Project Information](#project-information)
* [CI using Travis](#ci-using-travis)
* [Transforming Dart code](#transforming-dart-code)
* [Debugging](#debugging)

See the [contribution guidelines](https://github.com/angular/angular/blob/master/CONTRIBUTING.md)
if you'd like to contribute to Angular.

## Prerequisite Software

Before you can build and test Angular, you must install and configure the
following products on your development machine:

* [Git](http://git-scm.com) and/or the **GitHub app** (for [Mac](http://mac.github.com) or
  [Windows](http://windows.github.com)); [GitHub's Guide to Installing
  Git](https://help.github.com/articles/set-up-git) is a good source of information.

* [Node.js](http://nodejs.org), (version `>=5.4.1 <6`) which is used to run a development web server,
  run tests, and generate distributable files. We also use Node's Package Manager, `npm`
  (version `>=3.5.3 <4.0`), which comes with Node. Depending on your system, you can install Node either from
  source or as a pre-packaged bundle.

* *Optional*: [Dart](https://www.dartlang.org) (version ` >=1.13.2 <2.0.0`), specifically the Dart-SDK and
  Dartium (a version of [Chromium](http://www.chromium.org) with native support for Dart through
  the Dart VM). One of the **simplest** ways to get both is to install the **Dart Editor bundle**,
  which includes the editor, SDK and Dartium. See the [Dart tools](https://www.dartlang.org/tools)
  download [page for instructions](https://www.dartlang.org/tools/download.html).
  You can also download both **stable** and **dev** channel versions from the [download
  archive](https://www.dartlang.org/tools/download-archive). In that case, on Windows, Dart must be added
  to the `Path` (e.g. `path-to-dart-sdk-folder\bin`) and a new `DARTIUM_BIN` environment variable must be
  created, pointing to the executable (e.g. `path-to-dartium-folder\chrome.exe).`

## Getting the Sources

Fork and clone the Angular repository:

1. Login to your GitHub account or create one by following the instructions given
   [here](https://github.com/signup/free).
2. [Fork](http://help.github.com/forking) the [main Angular
   repository](https://github.com/angular/angular).
3. Clone your fork of the Angular repository and define an `upstream` remote pointing back to
   the Angular repository that you forked in the first place.

```shell
# Clone your GitHub repository:
git clone git@github.com:<github username>/angular.git

# Go to the Angular directory:
cd angular

# Add the main Angular repository as an upstream remote to your repository:
git remote add upstream https://github.com/angular/angular.git
```

## Environment Variable Setup

Define the environment variables listed below. These are mainly needed for the testing. The
notation shown here is for [`bash`](http://www.gnu.org/software/bash); adapt as appropriate for
your favorite shell.

Examples given below of possible values for initializing the environment variables assume **Mac OS
X** and that you have installed the Dart Editor in the directory named by
`DART_EDITOR_DIR=/Applications/dart`. This is only for illustrative purposes.

```shell
# DARTIUM_BIN: path to a Dartium browser executable; used by Karma to run Dart tests
export DARTIUM_BIN="$DART_EDITOR_DIR/chromium/Chromium.app/Contents/MacOS/Chromium"
```

Add the Dart SDK `bin` directory to your path and/or define `DART_SDK` (this is also detailed
[here](https://www.dartlang.org/tools/pub/installing.html)):

```shell
# DART_SDK: path to a Dart SDK directory
export DART_SDK="$DART_EDITOR_DIR/dart-sdk"

# Update PATH to include the Dart SDK bin directory
PATH+=":$DART_SDK/bin"
```

And specify where the pub's dependencies are downloaded. By default, this directory is located under .pub_cache
in your home directory (on Mac and Linux), or in AppData\Roaming\Pub\Cache (on Windows).

```shell
# PUB_CACHE: location of pub dependencies
export PUB_CACHE="/Users/<user>/.pub-cache"
```

## Installing NPM Modules and Dart Packages

Next, install the JavaScript modules and Dart packages needed to build and test Angular:

```shell
# Install Angular project dependencies (package.json)
npm install
```

**Optional**: In this document, we make use of project local `npm` package scripts and binaries
(stored under `./node_modules/.bin`) by prefixing these command invocations with `$(npm bin)`; in
particular `gulp` and `protractor` commands. If you prefer, you can drop this path prefix by either:

*Option 1*: globally installing these two packages as follows:

* `npm install -g gulp` (you might need to prefix this command with `sudo`)
* `npm install -g protractor` (you might need to prefix this command with `sudo`)

Since global installs can become stale, and required versions can vary by project, we avoid their
use in these instructions.

*Option 2*: defining a bash alias like `alias nbin='PATH=$(npm bin):$PATH'` as detailed in this
[Stackoverflow answer](http://stackoverflow.com/questions/9679932/how-to-use-package-installed-locally-in-node-modules/15157360#15157360) and used like this: e.g., `nbin gulp build`.

## Build commands

To build Angular and prepare tests, run:

```shell
$(npm bin)/gulp build
```

Notes:
* Results are put in the `dist` folder.
* This will also run `pub get` for the subfolders in `modules` and run `dartanalyzer` for
  every file that matches `<module>/src/<module>.dart`, e.g. `di/src/di.dart`.

You can selectively build either the JS or Dart versions as follows:

* `$(npm bin)/gulp build.js`
* `$(npm bin)/gulp build.dart`

To clean out the `dist` folder, run:

```shell
$(npm bin)/gulp clean
```

## Running Tests Locally

### Full test suite

* `npm test`: full test suite for both JS and Dart versions of Angular. These are the same tests
  that run on Travis.

You can selectively run either the JS or Dart versions as follows:

* `$(npm bin)/gulp test.all.js`
* `$(npm bin)/gulp test.all.dart`

### Unit tests

You can run just the unit tests as follows:

* `$(npm bin)/gulp test.unit.js`: JS tests in a browser; runs in **watch mode** (i.e.
   watches the test files for changes and re-runs tests when files are updated).
* `$(npm bin)/gulp test.unit.cjs`: JS tests in NodeJS; runs in **watch mode**.
* `$(npm bin)/gulp test.unit.dart`: Dart tests in Dartium; runs in **watch mode**.

If you prefer running tests in "single-run" mode rather than watch mode use:

* `$(npm bin)/gulp test.unit.js/ci`
* `$(npm bin)/gulp test.unit.cjs/ci`
* `$(npm bin)/gulp test.unit.dart/ci`

The task updates the dist folder with transpiled code whenever a source or test file changes, and
Karma is run against the new output.

**Note**: If you want to only run a single test you can alter the test you wish to run by changing
`it` to `iit` or `describe` to `ddescribe`. This will only run that individual test and make it
much easier to debug. `xit` and `xdescribe` can also be useful to exclude a test and a group of
tests respectively.

**Note**: **watch mode** needs symlinks to work, so if you're using windows, ensure you have the
rights to built them in your operating system.

### Unit tests with Sauce Labs or Browser Stack

First, in a terminal, create a tunnel with [Sauce Connect](https://docs.saucelabs.com/reference/sauce-connect/) or [Browser Stack Local](https://www.browserstack.com/local-testing#command-line), and valid credentials.

Then, in another terminal:
 - Define the credentials as environment variables, e.g.:
```
export SAUCE_USERNAME='my_user'; export SAUCE_ACCESS_KEY='my_key';
export BROWSER_STACK_USERNAME='my_user'; export BROWSER_STACK_ACCESS_KEY='my_key';
```
 - Then run `gulp test.unit.js.(sauce|browserstack) --browsers=option1,option2,..,optionN`
The options are any mix of browsers and aliases which are defined in the [browser-providers.conf.js](https://github.com/angular/angular/blob/master/browser-providers.conf.js) file.
They are case insensitive, and the `SL_` or `BS_` prefix must not be added for browsers.

Some examples of commands:
```
gulp test.unit.js.sauce --browsers=Safari8,ie11  //run in Sauce Labs with Safari 8 and IE11
gulp test.unit.js.browserstack --browsers=Safari,IE  //run in Browser Stack with Safari 7, Safari 8, Safari 9, IE 9, IE 10 and IE 11
gulp test.unit.js.sauce --browsers=IOS,safari8,android5.1  //run in Sauce Labs with iOS 7, iOS 8, iOs 9, Safari 8 and Android 5.1
```

### E2E tests

1. `$(npm bin)/gulp build.js.cjs` (builds benchpress and tests into `dist/js/cjs` folder).
2. `$(npm bin)/gulp serve.js.prod serve.dart` (runs a local webserver).
3. `$(npm bin)/protractor protractor-js.conf.js`: JS e2e tests.
4. `$(npm bin)/protractor protractor-dart2js.conf.js`: dart2js e2e tests.

Angular specific command line options when running protractor:
  - `$(npm bin)/protractor protractor-{js|dart2js}-conf.js --ng-help`

### Performance tests

1. `$(npm bin)/gulp build.js.cjs` (builds benchpress and tests into `dist/js/cjs` folder)
2. `$(npm bin)/gulp serve.js.prod serve.dart` (runs a local webserver)
3. `$(npm bin)/protractor protractor-js.conf.js --benchmark`: JS performance tests
4. `$(npm bin)/protractor protractor-dart2js.conf.js --benchmark`: dart2js performance tests

Angular specific command line options when running protractor (e.g. force gc, ...):
`$(npm bin)/protractor protractor-{js|dart2js}-conf.js --ng-help`

## Code Style

### Formatting with clang-format

We use [clang-format](http://clang.llvm.org/docs/ClangFormat.html) to automatically enforce code
style for our TypeScript code. This allows us to focus our code reviews more on the content, and
less on style nit-picking. It also lets us encode our style guide in the `.clang-format` file in the
repository, allowing many tools and editors to share our settings.

To check the formatting of your code, run

    gulp check-format

Note that the continuous build on Travis runs `gulp enforce-format`. Unlike the `check-format` task,
this will actually fail the build if files aren't formatted according to the style guide.

Your life will be easier if you include the formatter in your standard workflow. Otherwise, you'll
likely forget to check the formatting, and waste time waiting for a build on Travis that fails due
to some whitespace difference.

* Use `$(npm bin)/clang-format -i [file name]` to format a file (or multiple).
* Use `gulp enforce-format` to check if your code is `clang-format` clean. This also gives
  you a command line to format your code.
* `clang-format` also includes a git hook, run `git clang-format` to format all files you
  touched.
* You can run this as a **git pre-commit hook** to automatically format your delta regions when you
  commit a change. In the angular repo, run

```
    $ echo -e '#!/bin/sh\nexec git clang-format' > .git/hooks/pre-commit
    $ chmod u+x !$
```

**NOTE**: To use ```git clang-format``` use have to make sure that ```git-clang-format``` is in your
```PATH```. The easiest way is probably to just ```npm install -g clang-format``` as it comes with
```git-clang-format```.

* **WebStorm** can run clang-format on the current file.
  1. Under Preferences, open Tools > External Tools.
  1. Plus icon to Create Tool
  1. Fill in the form:
    - Name: clang-format
    - Description: Format
    - Synchronize files after execution: checked
    - Open console: not checked
    - Show in: Editor menu
    - Program: `$ProjectFileDir$/node_modules/.bin/clang-format`
    - Parameters: `-i -style=file $FilePath$`
    - Working directory: `$ProjectFileDir$`
* `clang-format` integrations are also available for many popular editors (`vim`, `emacs`,
  `Sublime Text`, etc.).

### Linting

We use [tslint](https://github.com/palantir/tslint) for linting. See linting rules in [gulpfile](gulpfile.js). To lint, run

```shell
$ gulp lint
```

## Generating the API documentation

The following gulp task will generate the API docs in the `dist/angular.io/partials/api/angular2`:

```shell
$(npm bin)/gulp docs/angular.io
```

You can serve the generated documentation to check how it would render on [angular.io](https://angular.io/):
- check out the [angular.io repo](https://github.com/angular/angular.io) locally,
- install dependencies as described in the [angular.io README](https://github.com/angular/angular.io/blob/master/README.md),
- copy the generated documentation from your local angular repo at `angular/dist/angular.io/partials/api/angular2` to your local angular.io repo at `angular.io/public/docs/js/latest/api`,
- run `harp compile` at the root of the angular.io repo to check the generated documentation for errors,
- run `harp server` and open a browser at `http://localhost:9000/docs/js/latest/api/` to check the rendered documentation.

## Project Information

### Folder structure

* `modules/*`: modules that will be loaded in the browser
* `tools/*`: tools that are needed to build Angular
* `dist/*`: build files are placed here.

### File suffixes

* `*.ts`: TypeScript files that get transpiled to Dart and EcmaScript 5/6
* `*.dart`: Dart files that don't get transpiled

## CI using Travis

For instructions on setting up Continuous Integration using Travis, see the instructions given
[here](https://github.com/angular/angular.dart/blob/master/travis.md).

## Transforming Dart code

See the [wiki](//github.com/angular/angular/wiki/Angular-2-Dart-Transformer).

## Debugging

### Debug the transpiler

If you need to debug the transpiler:

- add a `debugger;` statement in the transpiler code,
- from the root folder, execute `node debug $(npm bin)/gulp build` to enter the node
  debugger
- press "c" to execute the program until you reach the `debugger;` statement,
- you can then type "repl" to enter the REPL and inspect variables in the context.

See the [Node.js manual](http://nodejs.org/api/debugger.html) for more information.

Notes:
- You can also execute `node $(npm bin)/karma start karma-dart.conf.js` depending on which
  code you want to debug (the former will process the "modules" folder while the later processes
  the transpiler specs).
- You can also add `debugger;` statements in the specs (JavaScript). The execution will halt when
  the developer tools are opened in the browser running Karma.

### Debug the tests

If you need to debug the tests:

- add a `debugger;` statement to the test you want to debug (or the source code),
- execute karma `$(npm bin)/gulp test.js`,
- press the top right "DEBUG" button,
- open the DevTools and press F5,
- the execution halts at the `debugger;` statement

**Note (WebStorm users)**:

1. Create a Karma run config from WebStorm.
2. Then in the "Run" menu, press "Debug 'karma-js.conf.js'", and WebStorm will stop in the generated
   code on the `debugger;` statement.
3. You can then step into the code and add watches.

The `debugger;` statement is needed because WebStorm will stop in a transpiled file. Breakpoints in
the original source files are not supported at the moment.


text:
namespace {

// Class used to maintain a mapping from top-level windows to ChromeFrameActivex
// instances.
class TopLevelWindowMapping {
 public:
  typedef std::vector<HWND> WindowList;

  static TopLevelWindowMapping* GetInstance() {
    return Singleton<TopLevelWindowMapping>::get();
  }

  // Add |cf_window| to the set of windows registered under |top_window|.
  void AddMapping(HWND top_window, HWND cf_window) {
    top_window_map_lock_.Lock();
    top_window_map_[top_window].push_back(cf_window);
    top_window_map_lock_.Unlock();
  }

  // Return the set of Chrome-Frame instances under |window|.
  WindowList GetInstances(HWND window) {
    top_window_map_lock_.Lock();
    WindowList list = top_window_map_[window];
    top_window_map_lock_.Unlock();
    return list;
  }

 private:
  // Constructor is private as this class it to be used as a singleton.
  // See static method instance().
  TopLevelWindowMapping() {}

  friend struct DefaultSingletonTraits<TopLevelWindowMapping>;

  typedef std::map<HWND, WindowList> TopWindowMap;
  TopWindowMap top_window_map_;

  CComAutoCriticalSection top_window_map_lock_;

  DISALLOW_COPY_AND_ASSIGN(TopLevelWindowMapping);
};

// Message pump hook function that monitors for WM_MOVE and WM_MOVING
// messages on a top-level window, and passes notification to the appropriate
// Chrome-Frame instances.
LRESULT CALLBACK TopWindowProc(int code, WPARAM wparam, LPARAM lparam) {
  CWPSTRUCT *info = reinterpret_cast<CWPSTRUCT*>(lparam);
  const UINT &message = info->message;
  const HWND &message_hwnd = info->hwnd;

  switch (message) {
    case WM_MOVE:
    case WM_MOVING: {
      TopLevelWindowMapping::WindowList cf_instances =
          TopLevelWindowMapping::GetInstance()->GetInstances(message_hwnd);
      TopLevelWindowMapping::WindowList::iterator
          iter(cf_instances.begin()), end(cf_instances.end());
      for (;iter != end; ++iter) {
        PostMessage(*iter, WM_HOST_MOVED_NOTIFICATION, NULL, NULL);
      }
      break;
    }
    default:
      break;
  }

  return CallNextHookEx(0, code, wparam, lparam);
}

HHOOK InstallLocalWindowHook(HWND window) {
  if (!window)
    return NULL;

  DWORD proc_thread = ::GetWindowThreadProcessId(window, NULL);
  if (!proc_thread)
    return NULL;

  // Note that this hook is installed as a LOCAL hook.
  return  ::SetWindowsHookEx(WH_CALLWNDPROC,
                             TopWindowProc,
                             NULL,
                             proc_thread);
}

}  // unnamed namespace

namespace chrome_frame {
std::string ActiveXCreateUrl(const GURL& parsed_url,
                             const AttachExternalTabParams& params) {
  return base::StringPrintf(
      "%hs?attach_external_tab&%I64u&%d&%d&%d&%d&%d&%hs",
      parsed_url.GetOrigin().spec().c_str(),
      params.cookie,
      params.disposition,
      params.dimensions.x(),
      params.dimensions.y(),
      params.dimensions.width(),
      params.dimensions.height(),
      params.profile_name.c_str());
}

int GetDisposition(const AttachExternalTabParams& params) {
  return params.disposition;
}

void GetMiniContextMenuData(UINT cmd,
                            const MiniContextMenuParams& params,
                            GURL* referrer,
                            GURL* url) {
  *referrer = params.frame_url.is_empty() ? params.page_url : params.frame_url;
  *url = (cmd == IDS_CONTENT_CONTEXT_SAVELINKAS ?
      params.link_url : params.src_url);
}

}  // namespace chrome_frame

ChromeFrameActivex::ChromeFrameActivex()
    : chrome_wndproc_hook_(NULL),
      attaching_to_existing_cf_tab_(false) {
  TRACE_EVENT_BEGIN_ETW("chromeframe.createactivex", this, "");
}

HRESULT ChromeFrameActivex::FinalConstruct() {
  HRESULT hr = Base::FinalConstruct();
  if (FAILED(hr))
    return hr;

  // No need to call FireOnChanged at this point since nobody will be listening.
  ready_state_ = READYSTATE_LOADING;
  return S_OK;
}

ChromeFrameActivex::~ChromeFrameActivex() {
  // We expect these to be released during a call to SetClientSite(NULL).
  DCHECK_EQ(0u, onmessage_.size());
  DCHECK_EQ(0u, onloaderror_.size());
  DCHECK_EQ(0u, onload_.size());
  DCHECK_EQ(0u, onreadystatechanged_.size());
  DCHECK_EQ(0u, onextensionready_.size());

  if (chrome_wndproc_hook_) {
    BOOL unhook_success = ::UnhookWindowsHookEx(chrome_wndproc_hook_);
    DCHECK(unhook_success);
  }

  // ChromeFramePlugin::Uninitialize()
  Base::Uninitialize();

  TRACE_EVENT_END_ETW("chromeframe.createactivex", this, "");
}

LRESULT ChromeFrameActivex::OnCreate(UINT message, WPARAM wparam, LPARAM lparam,
                                     BOOL& handled) {
  Base::OnCreate(message, wparam, lparam, handled);
  // Install the notification hook on the top-level window, so that we can
  // be notified on move events.  Note that the return value is not checked.
  // This hook is installed here, as opposed to during IOleObject_SetClientSite
  // because m_hWnd has not yet been assigned during the SetSite call.
  InstallTopLevelHook(m_spClientSite);
  return 0;
}

LRESULT ChromeFrameActivex::OnHostMoved(UINT message, WPARAM wparam,
                                        LPARAM lparam, BOOL& handled) {
  Base::OnHostMoved();
  return 0;
}

HRESULT ChromeFrameActivex::GetContainingDocument(IHTMLDocument2** doc) {
  base::win::ScopedComPtr<IOleContainer> container;
  HRESULT hr = m_spClientSite->GetContainer(container.Receive());
  if (container)
    hr = container.QueryInterface(doc);
  return hr;
}

HRESULT ChromeFrameActivex::GetDocumentWindow(IHTMLWindow2** window) {
  base::win::ScopedComPtr<IHTMLDocument2> document;
  HRESULT hr = GetContainingDocument(document.Receive());
  if (document)
    hr = document->get_parentWindow(window);
  return hr;
}

void ChromeFrameActivex::OnLoad(const GURL& gurl) {
  base::win::ScopedComPtr<IDispatch> event;
  std::string url = gurl.spec();
  if (SUCCEEDED(CreateDomEvent("event", url, "", event.Receive())))
    Fire_onload(event);

  FireEvent(onload_, url);
  Base::OnLoad(gurl);
}

void ChromeFrameActivex::OnLoadFailed(int error_code, const std::string& url) {
  base::win::ScopedComPtr<IDispatch> event;
  if (SUCCEEDED(CreateDomEvent("event", url, "", event.Receive())))
    Fire_onloaderror(event);

  FireEvent(onloaderror_, url);
  Base::OnLoadFailed(error_code, url);
}

void ChromeFrameActivex::OnMessageFromChromeFrame(const std::string& message,
                                                  const std::string& origin,
                                                  const std::string& target) {
  DVLOG(1) << __FUNCTION__;

  if (target.compare("*") != 0) {
    bool drop = true;

    if (is_privileged()) {
      // Forward messages if the control is in privileged mode.
      base::win::ScopedComPtr<IDispatch> message_event;
      if (SUCCEEDED(CreateDomEvent("message", message, origin,
                                   message_event.Receive()))) {
        base::win::ScopedBstr target_bstr(UTF8ToWide(target).c_str());
        Fire_onprivatemessage(message_event, target_bstr);

        FireEvent(onprivatemessage_, message_event, target_bstr);
      }
    } else {
      if (HaveSameOrigin(target, document_url_)) {
        drop = false;
      } else {
        DLOG(WARNING) << "Dropping posted message since target doesn't match "
            "the current document's origin. target=" << target;
      }
    }

    if (drop)
      return;
  }

  base::win::ScopedComPtr<IDispatch> message_event;
  if (SUCCEEDED(CreateDomEvent("message", message, origin,
                               message_event.Receive()))) {
    Fire_onmessage(message_event);

    FireEvent(onmessage_, message_event);

    base::win::ScopedVariant event_var;
    event_var.Set(static_cast<IDispatch*>(message_event));
    InvokeScriptFunction(onmessage_handler_, event_var.AsInput());
  }
}

bool ChromeFrameActivex::ShouldShowVersionMismatchDialog(
    bool is_privileged,
    IOleClientSite* client_site) {
  if (!is_privileged) {
    return true;
  }

  if (client_site) {
    base::win::ScopedComPtr<IChromeFramePrivileged> service;
    HRESULT hr = DoQueryService(SID_ChromeFramePrivileged,
                                client_site,
                                service.Receive());
    if (SUCCEEDED(hr) && service) {
      return (S_FALSE != service->ShouldShowVersionMismatchDialog());
    }
  }

  NOTREACHED();
  return true;
}

void ChromeFrameActivex::OnAutomationServerLaunchFailed(
    AutomationLaunchResult reason, const std::string& server_version) {
  Base::OnAutomationServerLaunchFailed(reason, server_version);

  if (reason == AUTOMATION_VERSION_MISMATCH &&
      ShouldShowVersionMismatchDialog(is_privileged(), m_spClientSite)) {
    UMA_HISTOGRAM_COUNTS("ChromeFrame.VersionMismatchDisplayed", 1);
    DisplayVersionMismatchWarning(m_hWnd, server_version);
  }
}

void ChromeFrameActivex::OnChannelError() {
  Fire_onchannelerror();
}

HRESULT ChromeFrameActivex::OnDraw(ATL_DRAWINFO& draw_info) {  // NOLINT
  HRESULT hr = S_OK;
  int dc_type = ::GetObjectType(draw_info.hicTargetDev);
  if (dc_type == OBJ_ENHMETADC) {
    RECT print_bounds = {0};
    print_bounds.left = draw_info.prcBounds->left;
    print_bounds.right = draw_info.prcBounds->right;
    print_bounds.top = draw_info.prcBounds->top;
    print_bounds.bottom = draw_info.prcBounds->bottom;

    automation_client_->Print(draw_info.hdcDraw, print_bounds);
  } else {
    hr = Base::OnDraw(draw_info);
  }

  return hr;
}

STDMETHODIMP ChromeFrameActivex::Load(IPropertyBag* bag, IErrorLog* error_log) {
  DCHECK(bag);

  const wchar_t* event_props[] = {
    (L"onload"),
    (L"onloaderror"),
    (L"onmessage"),
    (L"onreadystatechanged"),
  };

  base::win::ScopedComPtr<IHTMLObjectElement> obj_element;
  GetObjectElement(obj_element.Receive());

  base::win::ScopedBstr object_id;
  GetObjectScriptId(obj_element, object_id.Receive());

  base::win::ScopedComPtr<IHTMLElement2> element;
  element.QueryFrom(obj_element);
  HRESULT hr = S_OK;

  for (int i = 0; SUCCEEDED(hr) && i < arraysize(event_props); ++i) {
    base::win::ScopedBstr prop(event_props[i]);
    base::win::ScopedVariant value;
    if (SUCCEEDED(bag->Read(prop, value.Receive(), error_log))) {
      if (value.type() != VT_BSTR ||
          FAILED(hr = CreateScriptBlockForEvent(element, object_id,
                                                V_BSTR(&value), prop))) {
        DLOG(ERROR) << "Failed to create script block for " << prop
                    << base::StringPrintf(L"hr=0x%08X, vt=%i", hr,
                                         value.type());
      } else {
        DVLOG(1) << "script block created for event " << prop
                 << base::StringPrintf(" (0x%08X)", hr) << " connections: " <<
            ProxyDIChromeFrameEvents<ChromeFrameActivex>::m_vec.GetSize();
      }
    } else {
      DVLOG(1) << "event property " << prop << " not in property bag";
    }
  }

  base::win::ScopedVariant src;
  if (SUCCEEDED(bag->Read(base::win::ScopedBstr(L"src"), src.Receive(),
                          error_log))) {
    if (src.type() == VT_BSTR) {
      hr = put_src(V_BSTR(&src));
      DCHECK(hr != E_UNEXPECTED);
    }
  }

  base::win::ScopedVariant use_chrome_network;
  if (SUCCEEDED(bag->Read(base::win::ScopedBstr(L"useChromeNetwork"),
                          use_chrome_network.Receive(), error_log))) {
    VariantChangeType(use_chrome_network.AsInput(),
                      use_chrome_network.AsInput(),
                      0, VT_BOOL);
    if (use_chrome_network.type() == VT_BOOL) {
      hr = put_useChromeNetwork(V_BOOL(&use_chrome_network));
      DCHECK(hr != E_UNEXPECTED);
    }
  }

  DLOG_IF(ERROR, FAILED(hr))
      << base::StringPrintf("Failed to load property bag: 0x%08X", hr);

  return hr;
}

const wchar_t g_activex_insecure_content_error[] = {
    L"data:text/html,ChromeFrame Security Error

"
    L"Cannot navigate to HTTP url when document URL is HTTPS"};

STDMETHODIMP ChromeFrameActivex::put_src(BSTR src) {
  GURL document_url(GetDocumentUrl());
  if (document_url.SchemeIsSecure()) {
    GURL source_url(src);
    if (!source_url.SchemeIsSecure()) {
      Base::put_src(base::win::ScopedBstr(g_activex_insecure_content_error));
      return E_ACCESSDENIED;
    }
  }
  HRESULT hr = S_OK;
  // If we are connecting to an existing ExternalTabContainer instance in
  // Chrome then we should wait for Chrome to initiate the navigation.
  if (!attaching_to_existing_cf_tab_) {
    hr = Base::put_src(src);
  } else {
    url_.Reset(::SysAllocString(src));
    attaching_to_existing_cf_tab_ = false;
  }
  return S_OK;
}

HRESULT ChromeFrameActivex::IOleObject_SetClientSite(
    IOleClientSite* client_site) {
  HRESULT hr = Base::IOleObject_SetClientSite(client_site);
  if (FAILED(hr) || !client_site) {
    EventHandlers* handlers[] = {
      &onmessage_,
      &onloaderror_,
      &onload_,
      &onreadystatechanged_,
      &onextensionready_,
    };

    for (int i = 0; i < arraysize(handlers); ++i)
      handlers[i]->clear();

    // Drop privileged mode on uninitialization.
    set_is_privileged(false);
  } else {
    base::win::ScopedComPtr<IHTMLDocument2> document;
    GetContainingDocument(document.Receive());
    if (document) {
      base::win::ScopedBstr url;
      if (SUCCEEDED(document->get_URL(url.Receive())))
        WideToUTF8(url, url.Length(), &document_url_);
    }

    // Probe to see whether the host implements the privileged service.
    base::win::ScopedComPtr<IChromeFramePrivileged> service;
    HRESULT service_hr = DoQueryService(SID_ChromeFramePrivileged,
                                        m_spClientSite,
                                        service.Receive());
    if (SUCCEEDED(service_hr) && service) {
      // Does the host want privileged mode?
      boolean wants_privileged = false;
      service_hr = service->GetWantsPrivileged(&wants_privileged);

      if (SUCCEEDED(service_hr) && wants_privileged)
        set_is_privileged(true);

      url_fetcher_->set_privileged_mode(is_privileged());
    }

    std::wstring profile_name(GetHostProcessName(false));
    if (is_privileged()) {
      base::win::ScopedBstr profile_name_arg;
      service_hr = service->GetChromeProfileName(profile_name_arg.Receive());
      if (S_OK == service_hr && profile_name_arg)
        profile_name.assign(profile_name_arg, profile_name_arg.Length());
    }

    std::string utf8_url;
    if (url_.Length()) {
      WideToUTF8(url_, url_.Length(), &utf8_url);
    }

    InitializeAutomationSettings();

    if (service) {
      base::win::ScopedBstr navigation_url;
      service->GetNavigationUrl(navigation_url.Receive());
      if (navigation_url.Length()) {
        ChromeFrameUrl cf_url;
        cf_url.Parse(navigation_url.operator BSTR());
        if (cf_url.attach_to_external_tab()) {
          automation_client_->AttachExternalTab(cf_url.cookie());
          attaching_to_existing_cf_tab_ = true;
        }
      }
    }
    url_fetcher_->set_frame_busting(!is_privileged());
    automation_client_->SetUrlFetcher(url_fetcher_.get());
    if (!InitializeAutomation(profile_name, IsIEInPrivate(), true,
                              GURL(utf8_url), GURL(), false)) {
      DLOG(ERROR) << "Failed to navigate to url:" << utf8_url;
      return E_FAIL;
    }

    // Log a metric that Chrome Frame is being used in Widget mode
    UMA_LAUNCH_TYPE_COUNT(RENDERER_TYPE_CHROME_WIDGET);
  }

  return hr;
}

HRESULT ChromeFrameActivex::GetObjectScriptId(IHTMLObjectElement* object_elem,
                                              BSTR* id) {
  DCHECK(object_elem != NULL);
  DCHECK(id != NULL);

  HRESULT hr = E_FAIL;
  if (object_elem) {
    base::win::ScopedComPtr<IHTMLElement> elem;
    hr = elem.QueryFrom(object_elem);
    if (elem) {
      hr = elem->get_id(id);
    }
  }

  return hr;
}

HRESULT ChromeFrameActivex::GetObjectElement(IHTMLObjectElement** element) {
  DCHECK(m_spClientSite);
  if (!m_spClientSite)
    return E_UNEXPECTED;

  base::win::ScopedComPtr<IOleControlSite> site;
  HRESULT hr = site.QueryFrom(m_spClientSite);
  if (site) {
    base::win::ScopedComPtr<IDispatch> disp;
    hr = site->GetExtendedControl(disp.Receive());
    if (disp) {
      hr = disp.QueryInterface(element);
    } else {
      DCHECK(FAILED(hr));
    }
  }

  return hr;
}

HRESULT ChromeFrameActivex::CreateScriptBlockForEvent(
    IHTMLElement2* insert_after, BSTR instance_id, BSTR script,
    BSTR event_name) {
  DCHECK(insert_after);
  DCHECK_GT(::SysStringLen(event_name), 0UL);  // should always have this

  // This might be 0 if not specified in the HTML document.
  if (!::SysStringLen(instance_id)) {
    // TODO(tommi): Should we give ourselves an ID if this happens?
    NOTREACHED() << "Need to handle this";
    return E_INVALIDARG;
  }

  base::win::ScopedComPtr<IHTMLDocument2> document;
  HRESULT hr = GetContainingDocument(document.Receive());
  if (SUCCEEDED(hr)) {
    base::win::ScopedComPtr<IHTMLElement> element, new_element;
    document->createElement(base::win::ScopedBstr(L"script"),
                            element.Receive());
    if (element) {
      base::win::ScopedComPtr<IHTMLScriptElement> script_element;
      if (SUCCEEDED(hr = script_element.QueryFrom(element))) {
        script_element->put_htmlFor(instance_id);
        script_element->put_event(event_name);
        script_element->put_text(script);

        hr = insert_after->insertAdjacentElement(
            base::win::ScopedBstr(L"afterEnd"),
            element,
            new_element.Receive());
      }
    }
  }

  return hr;
}

void ChromeFrameActivex::FireEvent(const EventHandlers& handlers,
                                   const std::string& arg) {
  if (handlers.size()) {
    base::win::ScopedComPtr<IDispatch> event;
    if (SUCCEEDED(CreateDomEvent("event", arg, "", event.Receive()))) {
      FireEvent(handlers, event);
    }
  }
}

void ChromeFrameActivex::FireEvent(const EventHandlers& handlers,
                                   IDispatch* event) {
  DCHECK(event != NULL);
  VARIANT arg = { VT_DISPATCH };
  arg.pdispVal = event;
  DISPPARAMS params = { &arg, NULL, 1, 0 };
  for (EventHandlers::const_iterator it = handlers.begin();
       it != handlers.end();
       ++it) {
    HRESULT hr = (*it)->Invoke(DISPID_VALUE, IID_NULL, LOCALE_USER_DEFAULT,
                               DISPATCH_METHOD, &params, NULL, NULL, NULL);
    // 0x80020101 == SCRIPT_E_REPORTED.
    // When the script we're invoking has an error, we get this error back.
    DLOG_IF(ERROR, FAILED(hr) && hr != 0x80020101)
        << base::StringPrintf(L"Failed to invoke script: 0x%08X", hr);
  }
}

void ChromeFrameActivex::FireEvent(const EventHandlers& handlers,
                                   IDispatch* event, BSTR target) {
  DCHECK(event != NULL);
  // Arguments in reverse order to event handler function declaration,
  // because that's what DISPPARAMS requires.
  VARIANT args[2] = { { VT_BSTR }, { VT_DISPATCH }, };
  args[0].bstrVal = target;
  args[1].pdispVal = event;
  DISPPARAMS params = { args, NULL, arraysize(args), 0 };
  for (EventHandlers::const_iterator it = handlers.begin();
       it != handlers.end();
       ++it) {
    HRESULT hr = (*it)->Invoke(DISPID_VALUE, IID_NULL, LOCALE_USER_DEFAULT,
                               DISPATCH_METHOD, &params, NULL, NULL, NULL);
    // 0x80020101 == SCRIPT_E_REPORTED.
    // When the script we're invoking has an error, we get this error back.
    DLOG_IF(ERROR, FAILED(hr) && hr != 0x80020101)
        << base::StringPrintf(L"Failed to invoke script: 0x%08X", hr);
  }
}

HRESULT ChromeFrameActivex::InstallTopLevelHook(IOleClientSite* client_site) {
  // Get the parent window of the site, and install our hook on the topmost
  // window of the parent.
  base::win::ScopedComPtr<IOleWindow> ole_window;
  HRESULT hr = ole_window.QueryFrom(client_site);
  if (FAILED(hr))
    return hr;

  HWND parent_wnd;
  hr = ole_window->GetWindow(&parent_wnd);
  if (FAILED(hr))
    return hr;

  HWND top_window = ::GetAncestor(parent_wnd, GA_ROOT);
  chrome_wndproc_hook_ = InstallLocalWindowHook(top_window);
  if (chrome_wndproc_hook_)
    TopLevelWindowMapping::GetInstance()->AddMapping(top_window, m_hWnd);

  return chrome_wndproc_hook_ ? S_OK : E_FAIL;
}

HRESULT ChromeFrameActivex::registerBhoIfNeeded() {
  if (!m_spUnkSite) {
    NOTREACHED() << "Invalid client site";
    return E_FAIL;
  }

  if (NavigationManager::GetThreadInstance() != NULL) {
    DVLOG(1) << "BHO already loaded";
    return S_OK;
  }

  base::win::ScopedComPtr<IWebBrowser2> web_browser2;
  HRESULT hr = DoQueryService(SID_SWebBrowserApp, m_spUnkSite,
                              web_browser2.Receive());
  if (FAILED(hr) || web_browser2.get() == NULL) {
    DLOG(WARNING) << "Failed to get IWebBrowser2 from client site. Error:"
                  << base::StringPrintf(" 0x%08X", hr);
    return hr;
  }

  wchar_t bho_class_id_as_string[MAX_PATH] = {0};
  StringFromGUID2(CLSID_ChromeFrameBHO, bho_class_id_as_string,
                  arraysize(bho_class_id_as_string));

  base::win::ScopedComPtr<IObjectWithSite> bho;
  hr = bho.CreateInstance(CLSID_ChromeFrameBHO, NULL, CLSCTX_INPROC_SERVER);
  if (FAILED(hr)) {
    NOTREACHED() << "Failed to register ChromeFrame BHO. Error:"
                 << base::StringPrintf(" 0x%08X", hr);
    return hr;
  }

  hr = UrlMkSetSessionOption(URLMON_OPTION_USERAGENT_REFRESH, NULL, 0, 0);
  if (FAILED(hr)) {
    DLOG(ERROR) << "Failed to refresh user agent string from registry. "
                << "UrlMkSetSessionOption returned "
                << base::StringPrintf("0x%08x", hr);
    return hr;
  }

  hr = bho->SetSite(web_browser2);
  if (FAILED(hr)) {
    NOTREACHED() << "ChromeFrame BHO SetSite failed. Error:"
                 << base::StringPrintf(" 0x%08X", hr);
    return hr;
  }

  web_browser2->PutProperty(base::win::ScopedBstr(bho_class_id_as_string),
                            base::win::ScopedVariant(bho));
  return S_OK;
}


text:
package net.runelite.client.plugins.xptracker;

import java.time.Duration;
import java.time.Instant;
import java.time.LocalTime;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import net.runelite.api.Experience;
import net.runelite.api.Skill;

@Data
@Slf4j
class SkillXPInfo
{
	private final Skill skill;
	private Instant skillTimeStart = null;
	private int startXp = -1;
	private int xpGained = 0;
	private int actions = 0;
	private int nextLevelExp = 0;
	private int startLevelExp = 0;
	private int level = 0;
	private boolean initialized = false;
	private int[] actionExps = new int[10];
	private int actionExpIndex = 0;

	int getXpHr()
	{
		return toHourly(xpGained);
	}

	int getXpSec()
	{
		return getXpHr() / 3600;
	}

	int getActionsHr()
	{
		return toHourly(actions);
	}

	private int toHourly(int value)
	{
		if (skillTimeStart == null)
		{
			return 0;
		}

		long timeElapsedInSeconds = Duration.between(skillTimeStart, Instant.now()).getSeconds();
		return (int) ((1.0 / (timeElapsedInSeconds / 3600.0)) * value);
	}

	int getXpRemaining()
	{
		return nextLevelExp - (startXp + xpGained);
	}

	int getActionsRemaining()
	{
		if (initialized)
		{
			long xpRemaining = getXpRemaining() * actionExps.length;
			long actionExp = 0;

			for (int i = 0; i < actionExps.length; i++)
			{
				actionExp += actionExps[i];
			}

			return Math.toIntExact(xpRemaining / actionExp);
		}

		return Integer.MAX_VALUE;
	}

	int getSkillProgress()
	{
		int currentXp = startXp + xpGained;

		double xpGained = currentXp - startLevelExp;
		double xpGoal = nextLevelExp - startLevelExp;
		return (int) ((xpGained / xpGoal) * 100);
	}

	String getTimeTillLevel()
	{
		if (getXpSec() > 0)
		{
			return LocalTime.MIN.plusSeconds( getXpRemaining() / getXpSec() ).toString();
		}
		return "\u221e";
	}

	void reset(int currentXp)
	{
		if (startXp != -1)
		{
			startXp = currentXp;
		}

		xpGained = 0;
		actions = 0;
		skillTimeStart = null;
	}

	boolean update(int currentXp)
	{
		if (startXp == -1)
		{
			return false;
		}

		int originalXp = xpGained + startXp;

		if (originalXp >= currentXp)
		{
			return false;
		}

		int actionExp = currentXp - originalXp;

		if (initialized)
		{
			actionExps[actionExpIndex] = actionExp;
		}
		else
		{
			// So we have a decent average off the bat, lets populate all values with what we see.
			for (int i = 0; i < actionExps.length; i++)
			{
				actionExps[i] = actionExp;
			}

			initialized = true;
		}

		actionExpIndex = (actionExpIndex + 1) % actionExps.length;

		actions++;
		xpGained = currentXp - startXp;
		startLevelExp = Experience.getXpForLevel(Experience.getLevelForXp(currentXp));

		int currentLevel = Experience.getLevelForXp(currentXp);

		level = currentLevel;

		nextLevelExp = currentLevel + 1 <= Experience.MAX_VIRT_LEVEL ? Experience.getXpForLevel(currentLevel + 1) : -1;

		if (skillTimeStart == null)
		{
			skillTimeStart = Instant.now();
		}

		return true;
	}
}


text:
// ReSharper disable All

namespace OpenTl.Schema.Account
{
	using System;
	using System.Collections;
	using System.Text;

	using OpenTl.Schema;
	using OpenTl.Schema.Serialization.Attributes;

	[Serialize(0x5cbea590)]
    public sealed class RequestRegisterDevice : IRequest<bool>
    {
       [SerializationOrder(0)]
       public int TokenType {get; set;}

       /// <summary>Binary representation for the 'Token' property</summary>
       [SerializationOrder(1)]
       public byte[] TokenAsBinary { get => _TokenAsBinary; set { _Token = Encoding.UTF8.GetString(value); _TokenAsBinary = value; }}
       private byte[] _TokenAsBinary;
       private string _Token;
       public string Token { get => _Token; set { TokenAsBinary = Encoding.UTF8.GetBytes(value); _Token = value; }}

       [SerializationOrder(2)]
       public bool AppSandbox {get; set;}

       [SerializationOrder(3)]
       public byte[] Secret {get; set;}

       [SerializationOrder(4)]
       public OpenTl.Schema.TVector<int> OtherUids {get; set;}

    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<!-- @formatter:off -->
<resources>

    <!-- API specific theme attributes 21+ -->
    <declare-styleable name="AppThemeAttributes">
        <attr name="selectableDrawableColorDefault" format="reference|color"/>
        <attr name="selectableDrawableColorInverse" format="reference|color"/>
        <attr name="selectableDrawableColor" format="reference|color"/>
    </declare-styleable>

</resources>


text:
package com.vsked.dao;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.log4j.Logger;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import com.vsked.test.TestMyBatis;

public class SysDictionaryTypeDaoTest extends TestMyBatis{

	private static Logger log = Logger.getLogger(SysDictionaryTypeDaoTest.class);

	@Autowired
	SysDictionaryTypeDao sysDictionaryTypeDao;

//	@Test
	public void getSysDictionaryTypeBySdtId(){
		String sdtId="sysDictionaryType000000000000001";
		Map<String, Object> data=sysDictionaryTypeDao.getSysDictionaryTypeBySdtId(sdtId);
		log.debug(data);
	}

//	@Test
	public void getSysDictionaryTypeCount(){
		Map<String, Object> m=new HashMap<String, Object>();
//		m.put("sdtName", "性别");
		int count=sysDictionaryTypeDao.getSysDictionaryTypeCount(m);
		log.debug(count);
	}

//	@Test
	public void getSysDictionaryTypeList(){
		Map<String, Object> m=new HashMap<String, Object>();
//		m.put("sdtName", "性别");
		List<Map<String, Object>> dataList=sysDictionaryTypeDao.getSysDictionaryTypeList(m);
		log.debug(dataList);
		log.debug(dataList.size());
	}

//	@Test
	public void sysDictionaryTypeAdd(){
		Map<String, Object> m=new HashMap<String, Object>();
//		m.put("sdtName", "tmptest测试junit");
		int effectLine=sysDictionaryTypeDao.sysDictionaryTypeAdd(m);
		log.debug(effectLine);
	}

//	@Test
	public void sysDictionaryTypeEdit(){
		Map<String, Object> m=new HashMap<String, Object>();
		m.put("sdtId", "B01D300EB18B4B56B64DC6F455E5F7B0");
		m.put("sdtName", "测试junit");
		int effectLine=sysDictionaryTypeDao.sysDictionaryTypeEdit(m);
		log.debug(effectLine);
	}

}


text:
import wx
import armid
import ARM
from Borg import Borg
from PersonaImpactDialog import PersonaImpactDialog

class PersonaImpactListCtrl(wx.ListCtrl):
  def __init__(self,parent,winId,cvName,envName):
    wx.ListCtrl.__init__(self,parent,winId,size=wx.DefaultSize,style=wx.LC_REPORT)
    self.theCvName = cvName
    self.theEnvironmentName = envName
    self.InsertColumn(0,'Persona')
    self.SetColumnWidth(0,150)
    self.InsertColumn(1,'Impact')
    self.SetColumnWidth(1,100)
    self.theSelectedIdx = -1
    self.Bind(wx.EVT_LIST_ITEM_SELECTED,self.OnItemSelected)
    self.Bind(wx.EVT_LIST_ITEM_DESELECTED,self.OnItemDeselected)
    self.Bind(wx.EVT_LIST_ITEM_ACTIVATED,self.onPersonaActivated)

    b = Borg()
    for pName,pImpact in b.dbProxy.personasImpact(cvName,envName):
      idx = self.GetItemCount()
      self.InsertStringItem(idx,pName)
      self.SetStringItem(idx,1,pImpact)

  def OnItemSelected(self,evt):
    self.theSelectedIdx = evt.GetIndex()

  def OnItemDeselected(self,evt):
    self.theSelectedIdx = -1

  def onPersonaActivated(self,evt):
    personaName = evt.GetLabel()
    dlg = PersonaImpactDialog(self,self.theCvName,personaName,self.theEnvironmentName)
    dlg.ShowModal()
    dlg.Destroy()


text:
[Snapup][1] is an Android application for posting photos to [Meetup][2].

[1]: http://github.com/meetup/snapup
[2]: http://www.meetup.com/


text:
'use strict';

import AudiobookModel from 'AudiobookModel';
import AudiobooksCollection from 'AudiobooksCollection';

describe('AudiobooksCollection', function() {

	const audiobooksCollection = new AudiobooksCollection();
	const audiobook1 = new AudiobookModel({
		'id': 1,
		'title': 'Example title',
	});

	it('should be defined', () => {
		expect(AudiobooksCollection).toBeDefined();
	});

	it('can be instantiated', () => {
		expect(audiobooksCollection).not.toBe(null);
	});

	it('can return audiobook by id', () => {
		audiobooksCollection.add(audiobook1);
		expect(audiobook1).toEqual(audiobooksCollection.getModelById(1));
	});

});


text: Proyecto final de primer cuatrimestre


text:
@class NotificationWindow;
@class UpdateWindow;
@class MessagesWindow;
@class Reachability;

@class AppController;

@interface AppDelegate : NSObject <NSApplicationDelegate> {
    AppController *controller;

    NSStatusItem *statusItem;
    NSArray *ipAddresses;
    NSArray *interfaces;
    Reachability *reachability;
}

@property (weak) IBOutlet NSMenu *statusMenu;

@property BOOL initialUse;
@property NSString *username;
@property NSString *server;
@property NSString *entry;
@property NSArray *entries;
@property NSString *interface;
@property NSString *ip;
@property (readonly) NSString *mac;
@property (readonly) BOOL ipManual;
@property BOOL shouldUseKeychain;
@property BOOL shouldShowStatusBarMenu;
@property (readonly) NSArray *ipAddresses;
@property (readonly) NSArray *interfaces;

- (IBAction)showMainWindow:(id)sender;
- (IBAction)showPreferencesWindow:(id)sender;
- (IBAction)showAccount:(id)sender;
- (IBAction)showMessagesWindow:(id)sender;
- (IBAction)logout:(id)sender;

@end


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" >

       <TextView
		android:layout_width="50dp"
		android:layout_height="50dp"
        android:id="@+id/grid_dice_item"
        android:layout_gravity="center"
        android:gravity="center"
        android:textColor="@color/white"
        android:textSize="20sp"
        android:clickable="false"
        android:focusable="false"/>

</LinearLayout>


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>ComponentManager (JasperReports 5.6.0 API)</title>
<meta name="date" content="2014-05-27">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

net.sf.jasperreports.engine.component

Interface ComponentManager

All Known Implementing Classes:

ComponentsManager, DefaultComponentManager, IconLabelComponentManager

public interface ComponentManager

A component manager is the entry point through which the handlers for a
 single component type can be accessed.

Version:

$Id: ComponentManager.java 6929 2014-02-25 15:46:46Z teodord $

Author:

Lucian Chirita (lucianc@users.sourceforge.net)

See Also:

ComponentsEnvironment.getManager(ComponentKey),
ComponentsBundle.getComponentManager(String)

Method Summary

Methods

Modifier and Type
Method and Description

ComponentCompiler
getComponentCompiler(JasperReportsContext jasperReportsContext)

Returns the component compiler.

ComponentFillFactory
getComponentFillFactory(JasperReportsContext jasperReportsContext)

Returns the factory of fill component instances.

ComponentXmlWriter
getComponentXmlWriter(JasperReportsContext jasperReportsContext)

Returns the component XML writer.

ComponentDesignConverter
getDesignConverter(JasperReportsContext jasperReportsContext)

Returns the design component preview converter.

Method Detail

getComponentCompiler

ComponentCompiler getComponentCompiler(JasperReportsContext jasperReportsContext)

Returns the component compiler.

Returns:

the component compiler

getComponentXmlWriter

ComponentXmlWriter getComponentXmlWriter(JasperReportsContext jasperReportsContext)

Returns the component XML writer.

Returns:

the component XML writer

getComponentFillFactory

ComponentFillFactory getComponentFillFactory(JasperReportsContext jasperReportsContext)

Returns the factory of fill component instances.

Returns:

the factory of fill component instances

getDesignConverter

ComponentDesignConverter getDesignConverter(JasperReportsContext jasperReportsContext)

Returns the design component preview converter.

 May be null, in which case a static icon is used when
 previewing a report that contains an instance of the component.

Returns:

the design component preview converter, or null
 if no such converter exists for the component.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

© 2001-2010 Jaspersoft Corporation www.jaspersoft.com


text:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.thinkgem.jeesite.modules.ftc.dao.product.CategoryDao">

	<sql id="categoryColumns">
		a.name AS "name",
		a.type AS "type",
		a.status AS "status",
		a.sort AS "sort",
		a.show_in_nav AS "showInNav",
		a.create_date AS "createDate",
		a.remarks AS "remarks",
		a.id AS "id",
		a.del_flag AS "delFlag",
		a.parent_id AS "parent.id",
		a.parent_ids AS "parentIds",
		a.show_in_hot AS "showInHot",
		a.show_in_top AS "showInTop",
		a.create_by AS "createBy.id",
		a.update_date AS "updateDate",
		a.update_by AS "updateBy.id",
		a.page_title AS "pageTitle",
		a.page_description AS "pageDescription",
		a.page_keyword AS "pageKeyword"
	</sql>

	<sql id="categoryJoins">
	</sql>

	<select id="get" resultType="Category">
		SELECT
			<include refid="categoryColumns"/>
		FROM os_category a
		<include refid="categoryJoins"/>
		WHERE a.id = #{id}
	</select>

	<select id="findList" resultType="Category">
		SELECT
			<include refid="categoryColumns"/>
		FROM os_category a
		<include refid="categoryJoins"/>
		<where>
			a.del_flag = #{DEL_FLAG_NORMAL}
			<if test="name != null and name != ''">
				AND a.name LIKE
					<if test="dbName == 'oracle'">'%'||#{name}||'%'</if>
					<if test="dbName == 'mssql'">'%'+#{name}+'%'</if>
					<if test="dbName == 'mysql'">concat('%',#{name},'%')</if>
			</if>
			<if test="parent != null and parent.id != null and parent.id != ''">
				AND a.parent_id = #{parent.id}
			</if>
		</where>
		ORDER BY a.sort ASC
	</select>

	<select id="findAllList" resultType="Category">
		SELECT
			<include refid="categoryColumns"/>
		FROM os_category a
		<include refid="categoryJoins"/>
		<where>
			a.del_flag = #{DEL_FLAG_NORMAL}
		</where>
		ORDER BY a.sort ASC
	</select>

	<select id="findByParentIdsLike" resultType="Category">
		SELECT
			a.id,
			a.parent_id AS "parent.id",
			a.parent_ids
		FROM os_category a
		<include refid="categoryJoins"/>
		<where>

			AND a.parent_ids LIKE #{parentIds}
		</where>
		ORDER BY a.sort ASC
	</select>

	<insert id="insert">
		INSERT INTO os_category(
			name,
			type,
			status,
			sort,
			show_in_nav,
			create_date,
			remarks,
			id,
			parent_id,
			parent_ids,
			show_in_hot,
			show_in_top,
			create_by,
			update_date,
			update_by,
			page_title,
			page_description,
			page_keyword,
			del_flag
		) VALUES (
			#{name},
			#{type},
			#{status},
			#{sort},
			#{showInNav},
			#{createDate},
			#{remarks},
			#{id},
			#{parent.id},
			#{parentIds},
			#{showInHot},
			#{showInTop},
			#{createBy.id},
			#{updateDate},
			#{updateBy.id},
			#{pageTitle},
			#{pageDescription},
			#{pageKeyword},
			#{delFlag}
		)
	</insert>

	<update id="update">
		UPDATE os_category SET
			name = #{name},
			type = #{type},
			status = #{status},
			sort = #{sort},
			show_in_nav = #{showInNav},
			create_Date = #{createDate},
			remarks = #{remarks},
			parent_id = #{parent.id},
			parent_ids=#{parentIds},
			show_in_hot = #{showInHot},
			show_in_top = #{showInTop},
			update_date = #{updateDate},
			update_by = #{updateBy.id},
			page_title = #{pageTitle},
			page_description = #{pageDescription},
			page_keyword = #{pageKeyword}
		WHERE id = #{id}
	</update>

	<update id="updateParentIds">
		UPDATE os_category SET
			parent_id = #{parent.id},
			parent_ids = #{parentIds}
		WHERE id = #{id}
	</update>

	<update id="delete">
		update os_category set del_flag=#{DEL_FLAG_DELETE}
		WHERE id = #{id} OR parent_ids LIKE concat('%',#{id},'%')
	</update>

</mapper>