file_name
large_stringlengths
4
140
prefix
large_stringlengths
0
39k
suffix
large_stringlengths
0
36.1k
middle
large_stringlengths
0
29.4k
fim_type
large_stringclasses
4 values
GoogleSource.js
/** * Copyright (c) 2008-2011 The Open Planning Project * * Published under the BSD license. * See https://github.com/opengeo/gxp/raw/master/license.txt for the full text * of the license. */ /** * @requires plugins/LayerSource.js */ /** api: (define) * module = gxp.plugins * class = GoogleSource */ /** api: (extends) * plugins/LayerSource.js */ Ext.namespace("gxp.plugins");
/** api: constructor * .. class:: GoolgeSource(config) * * Plugin for using Google layers with :class:`gxp.Viewer` instances. The * plugin uses the GMaps v3 API and also takes care of loading the * required Google resources. * * Available layer names for this source are "ROADMAP", "SATELLITE", * "HYBRID" and "TERRAIN" */ /** api: example * The configuration in the ``sources`` property of the :class:`gxp.Viewer` is * straightforward: * * .. code-block:: javascript * * "google": { * ptype: "gxp_google" * } * * A typical configuration for a layer from this source (in the ``layers`` * array of the viewer's ``map`` config option would look like this: * * .. code-block:: javascript * * { * source: "google", * name: "TERRAIN" * } * */ gxp.plugins.GoogleSource = Ext.extend(gxp.plugins.LayerSource, { /** api: ptype = gxp_googlesource */ ptype: "gxp_googlesource", /** config: config[timeout] * ``Number`` * The time (in milliseconds) to wait before giving up on the Google Maps * script loading. This layer source will not be availble if the script * does not load within the given timeout. Default is 7000 (seven seconds). */ timeout: 7000, /** api: property[store] * ``GeoExt.data.LayerStore`` containing records with "ROADMAP", * "SATELLITE", "HYBRID" and "TERRAIN" name fields. */ /** api: config[title] * ``String`` * A descriptive title for this layer source (i18n). */ title: "Google Layers", /** api: config[roadmapAbstract] * ``String`` * Description of the ROADMAP layer (i18n). */ roadmapAbstract: "Show street map", /** api: config[satelliteAbstract] * ``String`` * Description of the SATELLITE layer (i18n). */ satelliteAbstract: "Show satellite imagery", /** api: config[hybridAbstract] * ``String`` * Description of the HYBRID layer (i18n). */ hybridAbstract: "Show imagery with street names", /** api: config[terrainAbstract] * ``String`` * Description of the TERRAIN layer (i18n). */ terrainAbstract: "Show street map with terrain", constructor: function(config) { this.config = config; gxp.plugins.GoogleSource.superclass.constructor.apply(this, arguments); }, /** api: method[createStore] * * Creates a store of layer records. Fires "ready" when store is loaded. */ createStore: function() { gxp.plugins.GoogleSource.loader.onLoad({ timeout: this.timeout, callback: this.syncCreateStore, errback: function() { delete this.store; this.fireEvent( "failure", this, "The Google Maps script failed to load within the provided timeout (" + (this.timeout / 1000) + " s)." ); }, scope: this }); }, /** private: method[syncCreateStore] * * Creates a store of layers. This requires that the API script has already * loaded. Fires the "ready" event when the store is loaded. */ syncCreateStore: function() { // TODO: The abstracts ("alt" properties) should be derived from the // MapType objects themselves. It doesn't look like there is currently // a way to get the default map types before creating a map object. // http://code.google.com/p/gmaps-api-issues/issues/detail?id=2562 // TODO: We may also be able to determine the MAX_ZOOM_LEVEL for each // layer type. If not, consider setting them on the OpenLayers level. var mapTypes = { "ROADMAP": {"abstract": this.roadmapAbstract, MAX_ZOOM_LEVEL: 20}, "SATELLITE": {"abstract": this.satelliteAbstract}, "HYBRID": {"abstract": this.hybridAbstract}, "TERRAIN": {"abstract": this.terrainAbstract, MAX_ZOOM_LEVEL: 15} }; var layers = []; var name, mapType; for (name in mapTypes) { mapType = google.maps.MapTypeId[name]; layers.push(new OpenLayers.Layer.Google( // TODO: get MapType object name // http://code.google.com/p/gmaps-api-issues/issues/detail?id=2562 "Google " + mapType.replace(/\w/, function(c) {return c.toUpperCase();}), { type: mapType, typeName: name, MAX_ZOOM_LEVEL: mapTypes[name].MAX_ZOOM_LEVEL, maxExtent: new OpenLayers.Bounds(-20037508.34,-20037508.34,20037508.34,20037508.34), restrictedExtent: new OpenLayers.Bounds(-20037508.34,-20037508.34,20037508.34,20037508.34), projection: this.projection } )); } this.store = new GeoExt.data.LayerStore({ layers: layers, fields: [ {name: "source", type: "string"}, {name: "name", type: "string", mapping: "typeName"}, {name: "abstract", type: "string"}, {name: "group", type: "string", defaultValue: "background"}, {name: "fixed", type: "boolean", defaultValue: true}, {name: "selected", type: "boolean"} ] }); this.store.each(function(l) { l.set("abstract", mapTypes[l.get("name")]["abstract"]); }); this.fireEvent("ready", this); }, /** api: method[createLayerRecord] * :arg config: ``Object`` The application config for this layer. * :returns: ``GeoExt.data.LayerRecord`` * * Create a layer record given the config. */ createLayerRecord: function(config) { var record; var cmp = function(l) { return l.get("name") === config.name; }; // only return layer if app does not have it already if (this.target.mapPanel.layers.findBy(cmp) == -1) { // records can be in only one store record = this.store.getAt(this.store.findBy(cmp)).clone(); var layer = record.getLayer(); // set layer title from config if (config.title) { /** * Because the layer title data is duplicated, we have * to set it in both places. After records have been * added to the store, the store handles this * synchronization. */ layer.setName(config.title); record.set("title", config.title); } // set visibility from config if ("visibility" in config) { layer.visibility = config.visibility; } record.set("selected", config.selected || false); record.set("source", config.source); record.set("name", config.name); if ("group" in config) { record.set("group", config.group); } record.commit(); } return record; } }); /** * Create a loader singleton that all plugin instances can use. */ gxp.plugins.GoogleSource.loader = new (Ext.extend(Ext.util.Observable, { /** private: property[ready] * ``Boolean`` * This plugin type is ready to use. */ ready: !!(window.google && google.maps), /** private: property[loading] * ``Boolean`` * The resources for this plugin type are loading. */ loading: false, constructor: function() { this.addEvents( /** private: event[ready] * Fires when this plugin type is ready. */ "ready", /** private: event[failure] * Fires when script loading fails. */ "failure" ); return Ext.util.Observable.prototype.constructor.apply(this, arguments); }, /** private: method[onScriptLoad] * Called when all resources required by this plugin type have loaded. */ onScriptLoad: function() { // the google loader calls this in the window scope var monitor = gxp.plugins.GoogleSource.loader; if (!monitor.ready) { monitor.ready = true; monitor.loading = false; monitor.fireEvent("ready"); } }, /** api: method[gxp.plugins.GoogleSource.loader.onLoad] * :arg options: ``Object`` * * Options: * * * callback - ``Function`` Called when script loads. * * errback - ``Function`` Called if loading fails. * * timeout - ``Number`` Time to wait before deciding that loading failed * (in milliseconds). * * scope - ``Object`` The ``this`` object for callbacks. */ onLoad: function(options) { if (this.ready) { // call this in the next turn for consistent return before callback window.setTimeout(function() { options.callback.call(options.scope); }, 0); } else if (!this.loading) { this.loadScript(options); } else { this.on({ ready: options.callback, failure: options.errback || Ext.emptyFn, scope: options.scope }); } }, /** private: method[onScriptLoad] * Called when all resources required by this plugin type have loaded. */ loadScript: function(options) { var params = { autoload: Ext.encode({ modules: [{ name: "maps", version: 3.3, nocss: "true", callback: "gxp.plugins.GoogleSource.loader.onScriptLoad", other_params: "sensor=false" }] }) }; var script = document.createElement("script"); script.src = "http://www.google.com/jsapi?" + Ext.urlEncode(params); // cancel loading if monitor is not ready within timeout var errback = options.errback || Ext.emptyFn; var timeout = options.timeout || gxp.plugins.GoogleSource.prototype.timeout; window.setTimeout((function() { if (!gxp.plugins.GoogleSource.loader.ready) { this.loading = false; this.ready = false; document.getElementsByTagName("head")[0].removeChild(script); errback.call(options.scope); this.fireEvent("failure"); this.purgeListeners(); } }).createDelegate(this), timeout); // register callback for ready this.on({ ready: options.callback, scope: options.scope }); this.loading = true; document.getElementsByTagName("head")[0].appendChild(script); } }))(); Ext.preg(gxp.plugins.GoogleSource.prototype.ptype, gxp.plugins.GoogleSource);
random_line_split
migration.py
# Copyright 2010 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import os from migrate import exceptions as versioning_exceptions from migrate.versioning import api as versioning_api from migrate.versioning.repository import Repository import sqlalchemy from nova.db.sqlalchemy import api as db_session from nova import exception from nova.openstack.common.gettextutils import _ INIT_VERSION = 215 _REPOSITORY = None get_engine = db_session.get_engine def db_sync(version=None): if version is not None: try: version = int(version) except ValueError: raise exception.NovaException(_("version should be an integer")) current_version = db_version() repository = _find_migrate_repo() if version is None or version > current_version: return versioning_api.upgrade(get_engine(), repository, version) else: return versioning_api.downgrade(get_engine(), repository, version) def
(): repository = _find_migrate_repo() try: return versioning_api.db_version(get_engine(), repository) except versioning_exceptions.DatabaseNotControlledError: meta = sqlalchemy.MetaData() engine = get_engine() meta.reflect(bind=engine) tables = meta.tables if len(tables) == 0: db_version_control(INIT_VERSION) return versioning_api.db_version(get_engine(), repository) else: # Some pre-Essex DB's may not be version controlled. # Require them to upgrade using Essex first. raise exception.NovaException( _("Upgrade DB using Essex release first.")) def db_initial_version(): return INIT_VERSION def db_version_control(version=None): repository = _find_migrate_repo() versioning_api.version_control(get_engine(), repository, version) return version def _find_migrate_repo(): """Get the path for the migrate repository.""" global _REPOSITORY path = os.path.join(os.path.abspath(os.path.dirname(__file__)), 'migrate_repo') assert os.path.exists(path) if _REPOSITORY is None: _REPOSITORY = Repository(path) return _REPOSITORY
db_version
identifier_name
migration.py
# Copyright 2010 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import os from migrate import exceptions as versioning_exceptions from migrate.versioning import api as versioning_api from migrate.versioning.repository import Repository import sqlalchemy from nova.db.sqlalchemy import api as db_session from nova import exception from nova.openstack.common.gettextutils import _ INIT_VERSION = 215 _REPOSITORY = None get_engine = db_session.get_engine def db_sync(version=None): if version is not None: try: version = int(version) except ValueError: raise exception.NovaException(_("version should be an integer")) current_version = db_version() repository = _find_migrate_repo() if version is None or version > current_version: return versioning_api.upgrade(get_engine(), repository, version) else: return versioning_api.downgrade(get_engine(), repository, version) def db_version(): repository = _find_migrate_repo() try: return versioning_api.db_version(get_engine(), repository) except versioning_exceptions.DatabaseNotControlledError: meta = sqlalchemy.MetaData() engine = get_engine() meta.reflect(bind=engine) tables = meta.tables if len(tables) == 0: db_version_control(INIT_VERSION) return versioning_api.db_version(get_engine(), repository) else: # Some pre-Essex DB's may not be version controlled. # Require them to upgrade using Essex first. raise exception.NovaException( _("Upgrade DB using Essex release first.")) def db_initial_version(): return INIT_VERSION def db_version_control(version=None): repository = _find_migrate_repo() versioning_api.version_control(get_engine(), repository, version) return version
assert os.path.exists(path) if _REPOSITORY is None: _REPOSITORY = Repository(path) return _REPOSITORY
def _find_migrate_repo(): """Get the path for the migrate repository.""" global _REPOSITORY path = os.path.join(os.path.abspath(os.path.dirname(__file__)), 'migrate_repo')
random_line_split
migration.py
# Copyright 2010 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import os from migrate import exceptions as versioning_exceptions from migrate.versioning import api as versioning_api from migrate.versioning.repository import Repository import sqlalchemy from nova.db.sqlalchemy import api as db_session from nova import exception from nova.openstack.common.gettextutils import _ INIT_VERSION = 215 _REPOSITORY = None get_engine = db_session.get_engine def db_sync(version=None): if version is not None: try: version = int(version) except ValueError: raise exception.NovaException(_("version should be an integer")) current_version = db_version() repository = _find_migrate_repo() if version is None or version > current_version: return versioning_api.upgrade(get_engine(), repository, version) else: return versioning_api.downgrade(get_engine(), repository, version) def db_version(): repository = _find_migrate_repo() try: return versioning_api.db_version(get_engine(), repository) except versioning_exceptions.DatabaseNotControlledError: meta = sqlalchemy.MetaData() engine = get_engine() meta.reflect(bind=engine) tables = meta.tables if len(tables) == 0: db_version_control(INIT_VERSION) return versioning_api.db_version(get_engine(), repository) else: # Some pre-Essex DB's may not be version controlled. # Require them to upgrade using Essex first. raise exception.NovaException( _("Upgrade DB using Essex release first.")) def db_initial_version():
def db_version_control(version=None): repository = _find_migrate_repo() versioning_api.version_control(get_engine(), repository, version) return version def _find_migrate_repo(): """Get the path for the migrate repository.""" global _REPOSITORY path = os.path.join(os.path.abspath(os.path.dirname(__file__)), 'migrate_repo') assert os.path.exists(path) if _REPOSITORY is None: _REPOSITORY = Repository(path) return _REPOSITORY
return INIT_VERSION
identifier_body
migration.py
# Copyright 2010 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import os from migrate import exceptions as versioning_exceptions from migrate.versioning import api as versioning_api from migrate.versioning.repository import Repository import sqlalchemy from nova.db.sqlalchemy import api as db_session from nova import exception from nova.openstack.common.gettextutils import _ INIT_VERSION = 215 _REPOSITORY = None get_engine = db_session.get_engine def db_sync(version=None): if version is not None: try: version = int(version) except ValueError: raise exception.NovaException(_("version should be an integer")) current_version = db_version() repository = _find_migrate_repo() if version is None or version > current_version: return versioning_api.upgrade(get_engine(), repository, version) else:
def db_version(): repository = _find_migrate_repo() try: return versioning_api.db_version(get_engine(), repository) except versioning_exceptions.DatabaseNotControlledError: meta = sqlalchemy.MetaData() engine = get_engine() meta.reflect(bind=engine) tables = meta.tables if len(tables) == 0: db_version_control(INIT_VERSION) return versioning_api.db_version(get_engine(), repository) else: # Some pre-Essex DB's may not be version controlled. # Require them to upgrade using Essex first. raise exception.NovaException( _("Upgrade DB using Essex release first.")) def db_initial_version(): return INIT_VERSION def db_version_control(version=None): repository = _find_migrate_repo() versioning_api.version_control(get_engine(), repository, version) return version def _find_migrate_repo(): """Get the path for the migrate repository.""" global _REPOSITORY path = os.path.join(os.path.abspath(os.path.dirname(__file__)), 'migrate_repo') assert os.path.exists(path) if _REPOSITORY is None: _REPOSITORY = Repository(path) return _REPOSITORY
return versioning_api.downgrade(get_engine(), repository, version)
conditional_block
S11.8.3_A3.2_T1.2.js
// Copyright 2009 the Sputnik authors. All rights reserved. // This code is governed by the BSD license found in the LICENSE file. /*--- info: > Operator x <= y returns ToString(x) <= ToString(y), if Type(Primitive(x)) is String and Type(Primitive(y)) is String es5id: 11.8.3_A3.2_T1.2 description: > Type(Primitive(x)) and Type(Primitive(y)) vary between Object object and Function object ---*/ //CHECK#1 if (({} <= function(){return 1}) !== ({}.toString() <= function(){return 1}.toString()))
//CHECK#2 if ((function(){return 1} <= {}) !== (function(){return 1}.toString() <= {}.toString())) { $ERROR('#2: (function(){return 1} <= {}) === (function(){return 1}.toString() <= {}.toString())'); } //CHECK#3 if ((function(){return 1} <= function(){return 1}) !== (function(){return 1}.toString() <= function(){return 1}.toString())) { $ERROR('#3: (function(){return 1} <= function(){return 1}) === (function(){return 1}.toString() <= function(){return 1}.toString())'); } //CHECK#4 if (({} <= {}) !== ({}.toString() <= {}.toString())) { $ERROR('#4: ({} <= {}) === ({}.toString() <= {}.toString())'); }
{ $ERROR('#1: ({} <= function(){return 1}) === ({}.toString() <= function(){return 1}.toString())'); }
conditional_block
S11.8.3_A3.2_T1.2.js
// Copyright 2009 the Sputnik authors. All rights reserved. // This code is governed by the BSD license found in the LICENSE file. /*--- info: > Operator x <= y returns ToString(x) <= ToString(y), if Type(Primitive(x)) is String and Type(Primitive(y)) is String es5id: 11.8.3_A3.2_T1.2 description: > Type(Primitive(x)) and Type(Primitive(y)) vary between Object object and Function object ---*/
$ERROR('#1: ({} <= function(){return 1}) === ({}.toString() <= function(){return 1}.toString())'); } //CHECK#2 if ((function(){return 1} <= {}) !== (function(){return 1}.toString() <= {}.toString())) { $ERROR('#2: (function(){return 1} <= {}) === (function(){return 1}.toString() <= {}.toString())'); } //CHECK#3 if ((function(){return 1} <= function(){return 1}) !== (function(){return 1}.toString() <= function(){return 1}.toString())) { $ERROR('#3: (function(){return 1} <= function(){return 1}) === (function(){return 1}.toString() <= function(){return 1}.toString())'); } //CHECK#4 if (({} <= {}) !== ({}.toString() <= {}.toString())) { $ERROR('#4: ({} <= {}) === ({}.toString() <= {}.toString())'); }
//CHECK#1 if (({} <= function(){return 1}) !== ({}.toString() <= function(){return 1}.toString())) {
random_line_split
SZGooglePlusComments.js
// Definizione variabile principale per contenere // le funzioni che verranno richiamate da popup var SZGoogleDialog = { local_ed:'ed', // Funzione init per le operazioni iniziali del // componente da eseguire in questo stesso file init: function(ed) { SZGoogleDialog.local_ed = ed; tinyMCEPopup.resizeToInnerSize(); }, // Funzione cancel associata al bottone di fine // schermata presente in ogni popup di shortcode cancel: function(ed) { tinyMCEPopup.close(); }, // Funzione insert per la creazione del codice // shortcode con tutti le opzioni preimpostate insert: function(ed) { tinyMCEPopup.execCommand('mceRemoveNode',false,null); // Calcolo i valori delle variabili direttamente // dai campi del form senza sottomissione standard var output = ''; var url = jQuery('#ID_url' ).val(); var width = jQuery('#ID_width').val(); var align = jQuery('#ID_align').val(); if (jQuery('#ID_method').val() == '1') url = ''; if (jQuery('#ID_width_auto').is(':checked')) width = 'auto';
if (url != '') output += 'url="' + url + '" '; if (width != '') output += 'width="' + width + '" '; if (align != '') output += 'align="' + align + '" '; output += '/]'; // Una volta eseguita la composizione del comando shotcode // richiamo i metodi di tinyMCE per inserimento in editor tinyMCEPopup.execCommand('mceReplaceContent',false,output); tinyMCEPopup.close(); } }; // Inizializzo il dialogo tinyMCE e richiamo // anche la routine init per le operazioni iniziali tinyMCEPopup.onInit.add(SZGoogleDialog.init,SZGoogleDialog);
// Composizione shortcode selezionato con elenco // delle opzioni disponibili e valore associato output = '[sz-gplus-comments ';
random_line_split
dbFunctions.ts
/* Copyright 2021 Google LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ require("dotenv").config(); import low from "lowdb"; import FileSync from "lowdb/adapters/FileSync";
export const insertUserRecord = ( req: Request, looker_id: string, external_id: string, email: string ) => { const adapter = new FileSync<Schema>(process.env.PATH_TO_DB!); const dbUser = low(adapter) .get("users") .push({ looker_id: looker_id, external_id: external_id, email: email, }) .write(); Logger.info( `${req.method} ${req.baseUrl} User written to scim db {"id":"${looker_id}", "externalId":"${external_id}", "email":"${email}"}` ); return dbUser; }; // get user record from scim db export const getUserRecord = (looker_id: string) => { const adapter = new FileSync<Schema>(process.env.PATH_TO_DB!); const dbUser = low(adapter) .get("users") .find({ looker_id: looker_id }) .value(); return dbUser; }; // get user record by email and external id from scim db export const getUserRecordByEmail = (email: string, externalId?: string) => { const adapter = new FileSync<Schema>(process.env.PATH_TO_DB!); const dbUser = low(adapter) .get("users") .find((u) => u.external_id === externalId || u.email === email) .value(); return dbUser; }; // update user record into scim db export const updateUserRecord = ( req: Request, looker_id: string, column: "email" | "external_id", value: string ) => { const adapter = new FileSync<Schema>(process.env.PATH_TO_DB!); const dbUser = low(adapter) .get("users") .find({ looker_id: looker_id }) .assign({ [column]: value, }) .write(); Logger.info( `${req.method} ${req.baseUrl}/${looker_id} User ${column} updated in scim db` ); return dbUser; }; // remove user record into scim db export const deleteUserRecord = (req: Request, looker_id: string) => { const adapter = new FileSync<Schema>(process.env.PATH_TO_DB!); const dbUser = low(adapter) .get("users") .remove({ looker_id: looker_id }) .write(); Logger.info( `${req.method} ${req.baseUrl}/${looker_id} User deleted in scim db` ); return dbUser; };
import { Users, Schema, ScimUser, ScimErrorSchema } from "../types"; import { Request, Response } from "express-serve-static-core/index"; import Logger from "./logger"; // insert user record into scim db
random_line_split
log_reader.py
import time import asyncio from aiokafka import AIOKafkaProducer from settings import KAFKA_SERVERS, SAVEPOINT, LOG_FILE, KAFKA_TOPIC class LogStreamer: def __init__(self, KAFKA_SERVERS, KAFKA_TOPIC, loop, savepoint_file, log_file): self.KAFKA_TOPIC = KAFKA_TOPIC self.loop = loop self.producer = AIOKafkaProducer(loop=self.loop, bootstrap_servers=KAFKA_SERVERS) self.savepoint_file = savepoint_file self.log_file = log_file async def produce(self, finite=False): last = self.savepoint_file.read() if last: self.log_file.seek(int(last)) skip_first_empty = True while True: line = self.log_file.readline() line = line.strip(' \t\n\r') if not line: if finite and not skip_first_empty:
skip_first_empty = False time.sleep(0.1) current_position = self.log_file.tell() if last != current_position: self.savepoint_file.seek(0) self.savepoint_file.write(str(current_position)) continue ''' Here we can convert our data to JSON. But I because JSON performance is not extremely good with standart libraries, and because we use asynchronous non-blocking model here, I think it's best to just pass data as is. I want to create as little as possible overhead here. We want to stream data as fast as possible. ''' await self.producer.send_and_wait(self.KAFKA_TOPIC, line.encode()) def start(self): self.loop.run_until_complete(self.producer.start()) self.loop.run_until_complete(self.produce()) self.loop.run_until_complete(self.producer.stop()) self.loop.close() if __name__ == '__main__': with open(SAVEPOINT, 'r+') as savepoint_file, open(LOG_FILE, 'r') as log_file: streamer = LogStreamer(KAFKA_SERVERS, KAFKA_TOPIC, asyncio.get_event_loop(), savepoint_file, log_file) streamer.start()
return
random_line_split
log_reader.py
import time import asyncio from aiokafka import AIOKafkaProducer from settings import KAFKA_SERVERS, SAVEPOINT, LOG_FILE, KAFKA_TOPIC class LogStreamer: def
(self, KAFKA_SERVERS, KAFKA_TOPIC, loop, savepoint_file, log_file): self.KAFKA_TOPIC = KAFKA_TOPIC self.loop = loop self.producer = AIOKafkaProducer(loop=self.loop, bootstrap_servers=KAFKA_SERVERS) self.savepoint_file = savepoint_file self.log_file = log_file async def produce(self, finite=False): last = self.savepoint_file.read() if last: self.log_file.seek(int(last)) skip_first_empty = True while True: line = self.log_file.readline() line = line.strip(' \t\n\r') if not line: if finite and not skip_first_empty: return skip_first_empty = False time.sleep(0.1) current_position = self.log_file.tell() if last != current_position: self.savepoint_file.seek(0) self.savepoint_file.write(str(current_position)) continue ''' Here we can convert our data to JSON. But I because JSON performance is not extremely good with standart libraries, and because we use asynchronous non-blocking model here, I think it's best to just pass data as is. I want to create as little as possible overhead here. We want to stream data as fast as possible. ''' await self.producer.send_and_wait(self.KAFKA_TOPIC, line.encode()) def start(self): self.loop.run_until_complete(self.producer.start()) self.loop.run_until_complete(self.produce()) self.loop.run_until_complete(self.producer.stop()) self.loop.close() if __name__ == '__main__': with open(SAVEPOINT, 'r+') as savepoint_file, open(LOG_FILE, 'r') as log_file: streamer = LogStreamer(KAFKA_SERVERS, KAFKA_TOPIC, asyncio.get_event_loop(), savepoint_file, log_file) streamer.start()
__init__
identifier_name
log_reader.py
import time import asyncio from aiokafka import AIOKafkaProducer from settings import KAFKA_SERVERS, SAVEPOINT, LOG_FILE, KAFKA_TOPIC class LogStreamer: def __init__(self, KAFKA_SERVERS, KAFKA_TOPIC, loop, savepoint_file, log_file):
async def produce(self, finite=False): last = self.savepoint_file.read() if last: self.log_file.seek(int(last)) skip_first_empty = True while True: line = self.log_file.readline() line = line.strip(' \t\n\r') if not line: if finite and not skip_first_empty: return skip_first_empty = False time.sleep(0.1) current_position = self.log_file.tell() if last != current_position: self.savepoint_file.seek(0) self.savepoint_file.write(str(current_position)) continue ''' Here we can convert our data to JSON. But I because JSON performance is not extremely good with standart libraries, and because we use asynchronous non-blocking model here, I think it's best to just pass data as is. I want to create as little as possible overhead here. We want to stream data as fast as possible. ''' await self.producer.send_and_wait(self.KAFKA_TOPIC, line.encode()) def start(self): self.loop.run_until_complete(self.producer.start()) self.loop.run_until_complete(self.produce()) self.loop.run_until_complete(self.producer.stop()) self.loop.close() if __name__ == '__main__': with open(SAVEPOINT, 'r+') as savepoint_file, open(LOG_FILE, 'r') as log_file: streamer = LogStreamer(KAFKA_SERVERS, KAFKA_TOPIC, asyncio.get_event_loop(), savepoint_file, log_file) streamer.start()
self.KAFKA_TOPIC = KAFKA_TOPIC self.loop = loop self.producer = AIOKafkaProducer(loop=self.loop, bootstrap_servers=KAFKA_SERVERS) self.savepoint_file = savepoint_file self.log_file = log_file
identifier_body
log_reader.py
import time import asyncio from aiokafka import AIOKafkaProducer from settings import KAFKA_SERVERS, SAVEPOINT, LOG_FILE, KAFKA_TOPIC class LogStreamer: def __init__(self, KAFKA_SERVERS, KAFKA_TOPIC, loop, savepoint_file, log_file): self.KAFKA_TOPIC = KAFKA_TOPIC self.loop = loop self.producer = AIOKafkaProducer(loop=self.loop, bootstrap_servers=KAFKA_SERVERS) self.savepoint_file = savepoint_file self.log_file = log_file async def produce(self, finite=False): last = self.savepoint_file.read() if last:
skip_first_empty = True while True: line = self.log_file.readline() line = line.strip(' \t\n\r') if not line: if finite and not skip_first_empty: return skip_first_empty = False time.sleep(0.1) current_position = self.log_file.tell() if last != current_position: self.savepoint_file.seek(0) self.savepoint_file.write(str(current_position)) continue ''' Here we can convert our data to JSON. But I because JSON performance is not extremely good with standart libraries, and because we use asynchronous non-blocking model here, I think it's best to just pass data as is. I want to create as little as possible overhead here. We want to stream data as fast as possible. ''' await self.producer.send_and_wait(self.KAFKA_TOPIC, line.encode()) def start(self): self.loop.run_until_complete(self.producer.start()) self.loop.run_until_complete(self.produce()) self.loop.run_until_complete(self.producer.stop()) self.loop.close() if __name__ == '__main__': with open(SAVEPOINT, 'r+') as savepoint_file, open(LOG_FILE, 'r') as log_file: streamer = LogStreamer(KAFKA_SERVERS, KAFKA_TOPIC, asyncio.get_event_loop(), savepoint_file, log_file) streamer.start()
self.log_file.seek(int(last))
conditional_block
FunctionReturnType.py
from typing import Optional, List def a(x): # type: (List[int]) -> List[str] return <warning descr="Expected type 'List[str]', got 'List[List[int]]' instead">[x]</warning> def b(x): # type: (int) -> List[str] return <warning descr="Expected type 'List[str]', got 'List[int]' instead">[1,2]</warning> def c(): # type: () -> int return <warning descr="Expected type 'int', got 'str' instead">'abc'</warning> def d(x): # type: (x: int) -> List[str] return [str(x)] def e(): # type: () -> int pass def f(): # type: () -> Optional[str] x = int(input()) if x > 0: return <warning descr="Expected type 'Optional[str]', got 'int' instead">42</warning> elif x == 0: return 'abc' else: return def
(x): # type: (Any) -> int if x: return <warning descr="Expected type 'int', got 'str' instead">'abc'</warning> else: return <warning descr="Expected type 'int', got 'dict' instead">{}</warning>
g
identifier_name
FunctionReturnType.py
from typing import Optional, List def a(x): # type: (List[int]) -> List[str] return <warning descr="Expected type 'List[str]', got 'List[List[int]]' instead">[x]</warning> def b(x): # type: (int) -> List[str] return <warning descr="Expected type 'List[str]', got 'List[int]' instead">[1,2]</warning> def c(): # type: () -> int return <warning descr="Expected type 'int', got 'str' instead">'abc'</warning> def d(x): # type: (x: int) -> List[str] return [str(x)] def e(): # type: () -> int pass def f(): # type: () -> Optional[str] x = int(input())
return 'abc' else: return def g(x): # type: (Any) -> int if x: return <warning descr="Expected type 'int', got 'str' instead">'abc'</warning> else: return <warning descr="Expected type 'int', got 'dict' instead">{}</warning>
if x > 0: return <warning descr="Expected type 'Optional[str]', got 'int' instead">42</warning> elif x == 0:
random_line_split
FunctionReturnType.py
from typing import Optional, List def a(x): # type: (List[int]) -> List[str] return <warning descr="Expected type 'List[str]', got 'List[List[int]]' instead">[x]</warning> def b(x): # type: (int) -> List[str] return <warning descr="Expected type 'List[str]', got 'List[int]' instead">[1,2]</warning> def c(): # type: () -> int return <warning descr="Expected type 'int', got 'str' instead">'abc'</warning> def d(x): # type: (x: int) -> List[str] return [str(x)] def e(): # type: () -> int pass def f(): # type: () -> Optional[str] x = int(input()) if x > 0: return <warning descr="Expected type 'Optional[str]', got 'int' instead">42</warning> elif x == 0: return 'abc' else: return def g(x): # type: (Any) -> int if x: return <warning descr="Expected type 'int', got 'str' instead">'abc'</warning> else: return <warning descr="Expected type 'int', got 'dict' instead">{}</warning>
conditional_block
FunctionReturnType.py
from typing import Optional, List def a(x): # type: (List[int]) -> List[str] return <warning descr="Expected type 'List[str]', got 'List[List[int]]' instead">[x]</warning> def b(x): # type: (int) -> List[str] return <warning descr="Expected type 'List[str]', got 'List[int]' instead">[1,2]</warning> def c(): # type: () -> int return <warning descr="Expected type 'int', got 'str' instead">'abc'</warning> def d(x): # type: (x: int) -> List[str] return [str(x)] def e(): # type: () -> int pass def f(): # type: () -> Optional[str] x = int(input()) if x > 0: return <warning descr="Expected type 'Optional[str]', got 'int' instead">42</warning> elif x == 0: return 'abc' else: return def g(x): # type: (Any) -> int
if x: return <warning descr="Expected type 'int', got 'str' instead">'abc'</warning> else: return <warning descr="Expected type 'int', got 'dict' instead">{}</warning>
identifier_body
format.service.ts
import { Regex, RegexType } from 'ws-regex'; import { Subject } from 'rxjs/Subject'; import { Observable } from 'rxjs/Observable'; import { FormatTime } from 'ws-format-time'; import { ServerService } from './../server/server.service'; import { IdentityService } from './../identity/identity.service'; import { Logger } from 'ws-logger'; import { Injectable } from '@angular/core'; import { AsyncableServiceBase } from '../base/service.base'; import { ISticker } from '../../model/app.model'; @Injectable() export class FormatService extends AsyncableServiceBase { private logger: Logger<FormatService>; public get ImageSrcRoot() { return this.server.ServerStaticRoot; } constructor( private identity: IdentityService, private server: ServerService)
public readonly ImageConnect = (path: string): string => { if (!path) { return ""; } if (!path.startsWith("/")) { return path; } return this.ImageSrcRoot + path; } public readonly ImageTickParse = (str: string, coll: ISticker[], size: number = null): string => { if (!coll || coll.length === 0) { return str; } const reg = Regex.Create(/\[#\(.+?\)\]/, RegexType.IgnoreCase); str = this.goRegex(reg, str, coll, size); return str; } private goRegex = (reg: Regex, str: string, ticks: ISticker[], size: number): string => { const coll = reg.Matches(str); if (coll[0] && coll[0] !== '') { const target = ticks.find(i => `[${i.key}]` === coll[0]); if (target) { str = str.replace(coll[0], `</span><img class="tassel-sticker" ${size ? 'width="' + size + '"' : ''}src="${this.ImageSrcRoot}${target.value}" />&nbsp;<span>`); } return this.goRegex(reg, str, ticks, size); } else { return `<span>${str}</span>`; } } }
{ super(); this.logger = this.logsrv.GetLogger('FormatService').SetModule('service'); }
identifier_body
format.service.ts
import { Regex, RegexType } from 'ws-regex'; import { Subject } from 'rxjs/Subject'; import { Observable } from 'rxjs/Observable'; import { FormatTime } from 'ws-format-time'; import { ServerService } from './../server/server.service'; import { IdentityService } from './../identity/identity.service'; import { Logger } from 'ws-logger'; import { Injectable } from '@angular/core'; import { AsyncableServiceBase } from '../base/service.base'; import { ISticker } from '../../model/app.model'; @Injectable() export class FormatService extends AsyncableServiceBase { private logger: Logger<FormatService>; public get ImageSrcRoot() { return this.server.ServerStaticRoot; } constructor( private identity: IdentityService, private server: ServerService) { super(); this.logger = this.logsrv.GetLogger('FormatService').SetModule('service'); } public readonly ImageConnect = (path: string): string => { if (!path) { return ""; } if (!path.startsWith("/")) { return path; } return this.ImageSrcRoot + path; } public readonly ImageTickParse = (str: string, coll: ISticker[], size: number = null): string => { if (!coll || coll.length === 0)
const reg = Regex.Create(/\[#\(.+?\)\]/, RegexType.IgnoreCase); str = this.goRegex(reg, str, coll, size); return str; } private goRegex = (reg: Regex, str: string, ticks: ISticker[], size: number): string => { const coll = reg.Matches(str); if (coll[0] && coll[0] !== '') { const target = ticks.find(i => `[${i.key}]` === coll[0]); if (target) { str = str.replace(coll[0], `</span><img class="tassel-sticker" ${size ? 'width="' + size + '"' : ''}src="${this.ImageSrcRoot}${target.value}" />&nbsp;<span>`); } return this.goRegex(reg, str, ticks, size); } else { return `<span>${str}</span>`; } } }
{ return str; }
conditional_block
format.service.ts
import { Regex, RegexType } from 'ws-regex'; import { Subject } from 'rxjs/Subject'; import { Observable } from 'rxjs/Observable'; import { FormatTime } from 'ws-format-time'; import { ServerService } from './../server/server.service'; import { IdentityService } from './../identity/identity.service'; import { Logger } from 'ws-logger'; import { Injectable } from '@angular/core'; import { AsyncableServiceBase } from '../base/service.base'; import { ISticker } from '../../model/app.model'; @Injectable() export class FormatService extends AsyncableServiceBase { private logger: Logger<FormatService>; public get ImageSrcRoot() { return this.server.ServerStaticRoot; } constructor( private identity: IdentityService, private server: ServerService) { super(); this.logger = this.logsrv.GetLogger('FormatService').SetModule('service'); } public readonly ImageConnect = (path: string): string => { if (!path) { return ""; } if (!path.startsWith("/")) { return path; } return this.ImageSrcRoot + path; } public readonly ImageTickParse = (str: string, coll: ISticker[], size: number = null): string => { if (!coll || coll.length === 0) { return str; } const reg = Regex.Create(/\[#\(.+?\)\]/, RegexType.IgnoreCase);
const coll = reg.Matches(str); if (coll[0] && coll[0] !== '') { const target = ticks.find(i => `[${i.key}]` === coll[0]); if (target) { str = str.replace(coll[0], `</span><img class="tassel-sticker" ${size ? 'width="' + size + '"' : ''}src="${this.ImageSrcRoot}${target.value}" />&nbsp;<span>`); } return this.goRegex(reg, str, ticks, size); } else { return `<span>${str}</span>`; } } }
str = this.goRegex(reg, str, coll, size); return str; } private goRegex = (reg: Regex, str: string, ticks: ISticker[], size: number): string => {
random_line_split
format.service.ts
import { Regex, RegexType } from 'ws-regex'; import { Subject } from 'rxjs/Subject'; import { Observable } from 'rxjs/Observable'; import { FormatTime } from 'ws-format-time'; import { ServerService } from './../server/server.service'; import { IdentityService } from './../identity/identity.service'; import { Logger } from 'ws-logger'; import { Injectable } from '@angular/core'; import { AsyncableServiceBase } from '../base/service.base'; import { ISticker } from '../../model/app.model'; @Injectable() export class FormatService extends AsyncableServiceBase { private logger: Logger<FormatService>; public get
() { return this.server.ServerStaticRoot; } constructor( private identity: IdentityService, private server: ServerService) { super(); this.logger = this.logsrv.GetLogger('FormatService').SetModule('service'); } public readonly ImageConnect = (path: string): string => { if (!path) { return ""; } if (!path.startsWith("/")) { return path; } return this.ImageSrcRoot + path; } public readonly ImageTickParse = (str: string, coll: ISticker[], size: number = null): string => { if (!coll || coll.length === 0) { return str; } const reg = Regex.Create(/\[#\(.+?\)\]/, RegexType.IgnoreCase); str = this.goRegex(reg, str, coll, size); return str; } private goRegex = (reg: Regex, str: string, ticks: ISticker[], size: number): string => { const coll = reg.Matches(str); if (coll[0] && coll[0] !== '') { const target = ticks.find(i => `[${i.key}]` === coll[0]); if (target) { str = str.replace(coll[0], `</span><img class="tassel-sticker" ${size ? 'width="' + size + '"' : ''}src="${this.ImageSrcRoot}${target.value}" />&nbsp;<span>`); } return this.goRegex(reg, str, ticks, size); } else { return `<span>${str}</span>`; } } }
ImageSrcRoot
identifier_name
generate_bnmf.py
""" Generate a toy dataset for the matrix factorisation case, and store it. We use dimensions 100 by 50 for the dataset, and 10 latent factors. As the prior for U and V we take value 1 for all entries (so exp 1). As a result, each value in R has a value of around 20, and a variance of 100-120. For contrast, the Sanger dataset of 705 by 140 shifted to nonnegative has mean 31.522999753779082 and variance 243.2427345740027. We add Gaussian noise of precision tau = 1 (prior for gamma: alpha=1,beta=1). (Simply using the expectation of our Gamma distribution over tau) """ import sys, os project_location = os.path.dirname(__file__)+"/../../../" sys.path.append(project_location)
from BNMTF.code.models.distributions.exponential import exponential_draw from BNMTF.code.models.distributions.normal import normal_draw from BNMTF.code.cross_validation.mask import generate_M import numpy, itertools, matplotlib.pyplot as plt def generate_dataset(I,J,K,lambdaU,lambdaV,tau): # Generate U, V U = numpy.zeros((I,K)) for i,k in itertools.product(xrange(0,I),xrange(0,K)): U[i,k] = exponential_draw(lambdaU[i,k]) V = numpy.zeros((J,K)) for j,k in itertools.product(xrange(0,J),xrange(0,K)): V[j,k] = exponential_draw(lambdaV[j,k]) # Generate R true_R = numpy.dot(U,V.T) R = add_noise(true_R,tau) return (U,V,tau,true_R,R) def add_noise(true_R,tau): if numpy.isinf(tau): return numpy.copy(true_R) (I,J) = true_R.shape R = numpy.zeros((I,J)) for i,j in itertools.product(xrange(0,I),xrange(0,J)): R[i,j] = normal_draw(true_R[i,j],tau) return R def try_generate_M(I,J,fraction_unknown,attempts): for attempt in range(1,attempts+1): try: M = generate_M(I,J,fraction_unknown) sums_columns = M.sum(axis=0) sums_rows = M.sum(axis=1) for i,c in enumerate(sums_rows): assert c != 0, "Fully unobserved row in M, row %s. Fraction %s." % (i,fraction_unknown) for j,c in enumerate(sums_columns): assert c != 0, "Fully unobserved column in M, column %s. Fraction %s." % (j,fraction_unknown) print "Took %s attempts to generate M." % attempt return M except AssertionError: pass raise Exception("Tried to generate M %s times, with I=%s, J=%s, fraction=%s, but failed." % (attempts,I,J,fraction_unknown)) ########## if __name__ == "__main__": output_folder = project_location+"BNMTF/data_toy/bnmf/" I,J,K = 100, 80, 10 #20, 10, 5 # fraction_unknown = 0.1 alpha, beta = 1., 1. lambdaU = numpy.ones((I,K)) lambdaV = numpy.ones((I,K)) tau = alpha / beta (U,V,tau,true_R,R) = generate_dataset(I,J,K,lambdaU,lambdaV,tau) # Try to generate M M = try_generate_M(I,J,fraction_unknown,attempts=1000) # Store all matrices in text files numpy.savetxt(open(output_folder+"U.txt",'w'),U) numpy.savetxt(open(output_folder+"V.txt",'w'),V) numpy.savetxt(open(output_folder+"R_true.txt",'w'),true_R) numpy.savetxt(open(output_folder+"R.txt",'w'),R) numpy.savetxt(open(output_folder+"M.txt",'w'),M) print "Mean R: %s. Variance R: %s. Min R: %s. Max R: %s." % (numpy.mean(R),numpy.var(R),R.min(),R.max()) fig = plt.figure() plt.hist(R.flatten(),bins=range(0,int(R.max())+1)) plt.show()
random_line_split
generate_bnmf.py
""" Generate a toy dataset for the matrix factorisation case, and store it. We use dimensions 100 by 50 for the dataset, and 10 latent factors. As the prior for U and V we take value 1 for all entries (so exp 1). As a result, each value in R has a value of around 20, and a variance of 100-120. For contrast, the Sanger dataset of 705 by 140 shifted to nonnegative has mean 31.522999753779082 and variance 243.2427345740027. We add Gaussian noise of precision tau = 1 (prior for gamma: alpha=1,beta=1). (Simply using the expectation of our Gamma distribution over tau) """ import sys, os project_location = os.path.dirname(__file__)+"/../../../" sys.path.append(project_location) from BNMTF.code.models.distributions.exponential import exponential_draw from BNMTF.code.models.distributions.normal import normal_draw from BNMTF.code.cross_validation.mask import generate_M import numpy, itertools, matplotlib.pyplot as plt def generate_dataset(I,J,K,lambdaU,lambdaV,tau): # Generate U, V U = numpy.zeros((I,K)) for i,k in itertools.product(xrange(0,I),xrange(0,K)): U[i,k] = exponential_draw(lambdaU[i,k]) V = numpy.zeros((J,K)) for j,k in itertools.product(xrange(0,J),xrange(0,K)): V[j,k] = exponential_draw(lambdaV[j,k]) # Generate R true_R = numpy.dot(U,V.T) R = add_noise(true_R,tau) return (U,V,tau,true_R,R) def add_noise(true_R,tau): if numpy.isinf(tau): return numpy.copy(true_R) (I,J) = true_R.shape R = numpy.zeros((I,J)) for i,j in itertools.product(xrange(0,I),xrange(0,J)): R[i,j] = normal_draw(true_R[i,j],tau) return R def
(I,J,fraction_unknown,attempts): for attempt in range(1,attempts+1): try: M = generate_M(I,J,fraction_unknown) sums_columns = M.sum(axis=0) sums_rows = M.sum(axis=1) for i,c in enumerate(sums_rows): assert c != 0, "Fully unobserved row in M, row %s. Fraction %s." % (i,fraction_unknown) for j,c in enumerate(sums_columns): assert c != 0, "Fully unobserved column in M, column %s. Fraction %s." % (j,fraction_unknown) print "Took %s attempts to generate M." % attempt return M except AssertionError: pass raise Exception("Tried to generate M %s times, with I=%s, J=%s, fraction=%s, but failed." % (attempts,I,J,fraction_unknown)) ########## if __name__ == "__main__": output_folder = project_location+"BNMTF/data_toy/bnmf/" I,J,K = 100, 80, 10 #20, 10, 5 # fraction_unknown = 0.1 alpha, beta = 1., 1. lambdaU = numpy.ones((I,K)) lambdaV = numpy.ones((I,K)) tau = alpha / beta (U,V,tau,true_R,R) = generate_dataset(I,J,K,lambdaU,lambdaV,tau) # Try to generate M M = try_generate_M(I,J,fraction_unknown,attempts=1000) # Store all matrices in text files numpy.savetxt(open(output_folder+"U.txt",'w'),U) numpy.savetxt(open(output_folder+"V.txt",'w'),V) numpy.savetxt(open(output_folder+"R_true.txt",'w'),true_R) numpy.savetxt(open(output_folder+"R.txt",'w'),R) numpy.savetxt(open(output_folder+"M.txt",'w'),M) print "Mean R: %s. Variance R: %s. Min R: %s. Max R: %s." % (numpy.mean(R),numpy.var(R),R.min(),R.max()) fig = plt.figure() plt.hist(R.flatten(),bins=range(0,int(R.max())+1)) plt.show()
try_generate_M
identifier_name
generate_bnmf.py
""" Generate a toy dataset for the matrix factorisation case, and store it. We use dimensions 100 by 50 for the dataset, and 10 latent factors. As the prior for U and V we take value 1 for all entries (so exp 1). As a result, each value in R has a value of around 20, and a variance of 100-120. For contrast, the Sanger dataset of 705 by 140 shifted to nonnegative has mean 31.522999753779082 and variance 243.2427345740027. We add Gaussian noise of precision tau = 1 (prior for gamma: alpha=1,beta=1). (Simply using the expectation of our Gamma distribution over tau) """ import sys, os project_location = os.path.dirname(__file__)+"/../../../" sys.path.append(project_location) from BNMTF.code.models.distributions.exponential import exponential_draw from BNMTF.code.models.distributions.normal import normal_draw from BNMTF.code.cross_validation.mask import generate_M import numpy, itertools, matplotlib.pyplot as plt def generate_dataset(I,J,K,lambdaU,lambdaV,tau): # Generate U, V U = numpy.zeros((I,K)) for i,k in itertools.product(xrange(0,I),xrange(0,K)): U[i,k] = exponential_draw(lambdaU[i,k]) V = numpy.zeros((J,K)) for j,k in itertools.product(xrange(0,J),xrange(0,K)): V[j,k] = exponential_draw(lambdaV[j,k]) # Generate R true_R = numpy.dot(U,V.T) R = add_noise(true_R,tau) return (U,V,tau,true_R,R) def add_noise(true_R,tau): if numpy.isinf(tau): return numpy.copy(true_R) (I,J) = true_R.shape R = numpy.zeros((I,J)) for i,j in itertools.product(xrange(0,I),xrange(0,J)): R[i,j] = normal_draw(true_R[i,j],tau) return R def try_generate_M(I,J,fraction_unknown,attempts): for attempt in range(1,attempts+1): try: M = generate_M(I,J,fraction_unknown) sums_columns = M.sum(axis=0) sums_rows = M.sum(axis=1) for i,c in enumerate(sums_rows): assert c != 0, "Fully unobserved row in M, row %s. Fraction %s." % (i,fraction_unknown) for j,c in enumerate(sums_columns): assert c != 0, "Fully unobserved column in M, column %s. Fraction %s." % (j,fraction_unknown) print "Took %s attempts to generate M." % attempt return M except AssertionError: pass raise Exception("Tried to generate M %s times, with I=%s, J=%s, fraction=%s, but failed." % (attempts,I,J,fraction_unknown)) ########## if __name__ == "__main__":
output_folder = project_location+"BNMTF/data_toy/bnmf/" I,J,K = 100, 80, 10 #20, 10, 5 # fraction_unknown = 0.1 alpha, beta = 1., 1. lambdaU = numpy.ones((I,K)) lambdaV = numpy.ones((I,K)) tau = alpha / beta (U,V,tau,true_R,R) = generate_dataset(I,J,K,lambdaU,lambdaV,tau) # Try to generate M M = try_generate_M(I,J,fraction_unknown,attempts=1000) # Store all matrices in text files numpy.savetxt(open(output_folder+"U.txt",'w'),U) numpy.savetxt(open(output_folder+"V.txt",'w'),V) numpy.savetxt(open(output_folder+"R_true.txt",'w'),true_R) numpy.savetxt(open(output_folder+"R.txt",'w'),R) numpy.savetxt(open(output_folder+"M.txt",'w'),M) print "Mean R: %s. Variance R: %s. Min R: %s. Max R: %s." % (numpy.mean(R),numpy.var(R),R.min(),R.max()) fig = plt.figure() plt.hist(R.flatten(),bins=range(0,int(R.max())+1)) plt.show()
conditional_block
generate_bnmf.py
""" Generate a toy dataset for the matrix factorisation case, and store it. We use dimensions 100 by 50 for the dataset, and 10 latent factors. As the prior for U and V we take value 1 for all entries (so exp 1). As a result, each value in R has a value of around 20, and a variance of 100-120. For contrast, the Sanger dataset of 705 by 140 shifted to nonnegative has mean 31.522999753779082 and variance 243.2427345740027. We add Gaussian noise of precision tau = 1 (prior for gamma: alpha=1,beta=1). (Simply using the expectation of our Gamma distribution over tau) """ import sys, os project_location = os.path.dirname(__file__)+"/../../../" sys.path.append(project_location) from BNMTF.code.models.distributions.exponential import exponential_draw from BNMTF.code.models.distributions.normal import normal_draw from BNMTF.code.cross_validation.mask import generate_M import numpy, itertools, matplotlib.pyplot as plt def generate_dataset(I,J,K,lambdaU,lambdaV,tau): # Generate U, V U = numpy.zeros((I,K)) for i,k in itertools.product(xrange(0,I),xrange(0,K)): U[i,k] = exponential_draw(lambdaU[i,k]) V = numpy.zeros((J,K)) for j,k in itertools.product(xrange(0,J),xrange(0,K)): V[j,k] = exponential_draw(lambdaV[j,k]) # Generate R true_R = numpy.dot(U,V.T) R = add_noise(true_R,tau) return (U,V,tau,true_R,R) def add_noise(true_R,tau): if numpy.isinf(tau): return numpy.copy(true_R) (I,J) = true_R.shape R = numpy.zeros((I,J)) for i,j in itertools.product(xrange(0,I),xrange(0,J)): R[i,j] = normal_draw(true_R[i,j],tau) return R def try_generate_M(I,J,fraction_unknown,attempts):
########## if __name__ == "__main__": output_folder = project_location+"BNMTF/data_toy/bnmf/" I,J,K = 100, 80, 10 #20, 10, 5 # fraction_unknown = 0.1 alpha, beta = 1., 1. lambdaU = numpy.ones((I,K)) lambdaV = numpy.ones((I,K)) tau = alpha / beta (U,V,tau,true_R,R) = generate_dataset(I,J,K,lambdaU,lambdaV,tau) # Try to generate M M = try_generate_M(I,J,fraction_unknown,attempts=1000) # Store all matrices in text files numpy.savetxt(open(output_folder+"U.txt",'w'),U) numpy.savetxt(open(output_folder+"V.txt",'w'),V) numpy.savetxt(open(output_folder+"R_true.txt",'w'),true_R) numpy.savetxt(open(output_folder+"R.txt",'w'),R) numpy.savetxt(open(output_folder+"M.txt",'w'),M) print "Mean R: %s. Variance R: %s. Min R: %s. Max R: %s." % (numpy.mean(R),numpy.var(R),R.min(),R.max()) fig = plt.figure() plt.hist(R.flatten(),bins=range(0,int(R.max())+1)) plt.show()
for attempt in range(1,attempts+1): try: M = generate_M(I,J,fraction_unknown) sums_columns = M.sum(axis=0) sums_rows = M.sum(axis=1) for i,c in enumerate(sums_rows): assert c != 0, "Fully unobserved row in M, row %s. Fraction %s." % (i,fraction_unknown) for j,c in enumerate(sums_columns): assert c != 0, "Fully unobserved column in M, column %s. Fraction %s." % (j,fraction_unknown) print "Took %s attempts to generate M." % attempt return M except AssertionError: pass raise Exception("Tried to generate M %s times, with I=%s, J=%s, fraction=%s, but failed." % (attempts,I,J,fraction_unknown))
identifier_body
MovieCollection.js
import PropTypes from 'prop-types'; import React, { Component } from 'react'; import MonitorToggleButton from 'Components/MonitorToggleButton'; import EditImportListModalConnector from 'Settings/ImportLists/ImportLists/EditImportListModalConnector'; import styles from './MovieCollection.css'; class MovieCollection extends Component { // // Lifecycle constructor(props, context) { super(props, context); this.state = { hasPosterError: false, isEditImportListModalOpen: false }; } onAddImportListPress = (monitored) => { if (this.props.collectionList) { this.props.onMonitorTogglePress(monitored); } else
} onEditImportListModalClose = () => { this.setState({ isEditImportListModalOpen: false }); } render() { const { name, collectionList, isSaving } = this.props; const monitored = collectionList !== undefined && collectionList.enabled && collectionList.enableAuto; const importListId = collectionList ? collectionList.id : 0; return ( <div> <MonitorToggleButton className={styles.monitorToggleButton} monitored={monitored} isSaving={isSaving} size={15} onPress={this.onAddImportListPress} /> {name} <EditImportListModalConnector id={importListId} isOpen={this.state.isEditImportListModalOpen} onModalClose={this.onEditImportListModalClose} onDeleteImportListPress={this.onDeleteImportListPress} /> </div> ); } } MovieCollection.propTypes = { tmdbId: PropTypes.number.isRequired, name: PropTypes.string.isRequired, collectionList: PropTypes.object, isSaving: PropTypes.bool.isRequired, onMonitorTogglePress: PropTypes.func.isRequired }; export default MovieCollection;
{ this.props.onMonitorTogglePress(monitored); this.setState({ isEditImportListModalOpen: true }); }
conditional_block
MovieCollection.js
import PropTypes from 'prop-types'; import React, { Component } from 'react'; import MonitorToggleButton from 'Components/MonitorToggleButton'; import EditImportListModalConnector from 'Settings/ImportLists/ImportLists/EditImportListModalConnector'; import styles from './MovieCollection.css'; class MovieCollection extends Component { // // Lifecycle constructor(props, context) { super(props, context); this.state = { hasPosterError: false, isEditImportListModalOpen: false }; } onAddImportListPress = (monitored) => { if (this.props.collectionList) { this.props.onMonitorTogglePress(monitored); } else { this.props.onMonitorTogglePress(monitored); this.setState({ isEditImportListModalOpen: true }); } } onEditImportListModalClose = () => { this.setState({ isEditImportListModalOpen: false }); }
() { const { name, collectionList, isSaving } = this.props; const monitored = collectionList !== undefined && collectionList.enabled && collectionList.enableAuto; const importListId = collectionList ? collectionList.id : 0; return ( <div> <MonitorToggleButton className={styles.monitorToggleButton} monitored={monitored} isSaving={isSaving} size={15} onPress={this.onAddImportListPress} /> {name} <EditImportListModalConnector id={importListId} isOpen={this.state.isEditImportListModalOpen} onModalClose={this.onEditImportListModalClose} onDeleteImportListPress={this.onDeleteImportListPress} /> </div> ); } } MovieCollection.propTypes = { tmdbId: PropTypes.number.isRequired, name: PropTypes.string.isRequired, collectionList: PropTypes.object, isSaving: PropTypes.bool.isRequired, onMonitorTogglePress: PropTypes.func.isRequired }; export default MovieCollection;
render
identifier_name
MovieCollection.js
import PropTypes from 'prop-types'; import React, { Component } from 'react'; import MonitorToggleButton from 'Components/MonitorToggleButton'; import EditImportListModalConnector from 'Settings/ImportLists/ImportLists/EditImportListModalConnector'; import styles from './MovieCollection.css'; class MovieCollection extends Component { // // Lifecycle constructor(props, context) { super(props, context); this.state = { hasPosterError: false, isEditImportListModalOpen: false }; } onAddImportListPress = (monitored) => { if (this.props.collectionList) { this.props.onMonitorTogglePress(monitored); } else { this.props.onMonitorTogglePress(monitored); this.setState({ isEditImportListModalOpen: true }); } } onEditImportListModalClose = () => { this.setState({ isEditImportListModalOpen: false }); } render() { const { name, collectionList, isSaving } = this.props; const monitored = collectionList !== undefined && collectionList.enabled && collectionList.enableAuto; const importListId = collectionList ? collectionList.id : 0; return ( <div> <MonitorToggleButton className={styles.monitorToggleButton} monitored={monitored} isSaving={isSaving} size={15}
<EditImportListModalConnector id={importListId} isOpen={this.state.isEditImportListModalOpen} onModalClose={this.onEditImportListModalClose} onDeleteImportListPress={this.onDeleteImportListPress} /> </div> ); } } MovieCollection.propTypes = { tmdbId: PropTypes.number.isRequired, name: PropTypes.string.isRequired, collectionList: PropTypes.object, isSaving: PropTypes.bool.isRequired, onMonitorTogglePress: PropTypes.func.isRequired }; export default MovieCollection;
onPress={this.onAddImportListPress} /> {name}
random_line_split
MovieCollection.js
import PropTypes from 'prop-types'; import React, { Component } from 'react'; import MonitorToggleButton from 'Components/MonitorToggleButton'; import EditImportListModalConnector from 'Settings/ImportLists/ImportLists/EditImportListModalConnector'; import styles from './MovieCollection.css'; class MovieCollection extends Component { // // Lifecycle constructor(props, context) { super(props, context); this.state = { hasPosterError: false, isEditImportListModalOpen: false }; } onAddImportListPress = (monitored) => { if (this.props.collectionList) { this.props.onMonitorTogglePress(monitored); } else { this.props.onMonitorTogglePress(monitored); this.setState({ isEditImportListModalOpen: true }); } } onEditImportListModalClose = () => { this.setState({ isEditImportListModalOpen: false }); } render()
} MovieCollection.propTypes = { tmdbId: PropTypes.number.isRequired, name: PropTypes.string.isRequired, collectionList: PropTypes.object, isSaving: PropTypes.bool.isRequired, onMonitorTogglePress: PropTypes.func.isRequired }; export default MovieCollection;
{ const { name, collectionList, isSaving } = this.props; const monitored = collectionList !== undefined && collectionList.enabled && collectionList.enableAuto; const importListId = collectionList ? collectionList.id : 0; return ( <div> <MonitorToggleButton className={styles.monitorToggleButton} monitored={monitored} isSaving={isSaving} size={15} onPress={this.onAddImportListPress} /> {name} <EditImportListModalConnector id={importListId} isOpen={this.state.isEditImportListModalOpen} onModalClose={this.onEditImportListModalClose} onDeleteImportListPress={this.onDeleteImportListPress} /> </div> ); }
identifier_body
upload.service.ts
import { Injectable } from '@angular/core'; import { Subject } from 'rxjs/Subject'; import { Observable } from 'rxjs/Observable'; import { AngularFireDatabase, FirebaseListObservable } from 'angularfire2/database'; import { Http, Headers } from '@angular/http'; import { FirebaseApp } from 'angularfire2'; // for methods import { AngularFireAuth } from 'angularfire2/auth'; import { Jersey, UniformStyle, Ifile,FileObj } from '../app/admin/models/upload' import * as firebase from 'firebase/app'; import 'rxjs/add/operator/map'; @Injectable() export class UploadService { constructor(private fb: FirebaseApp, private db: AngularFireDatabase) { console.log("Upload service started"); } basePath: string = '/jersey-styles'; uploadJersey: any; uploads: FirebaseListObservable<any[]>; //takes in an upload object and folder name saveNewStyle(newJersey: UniformStyle) { debugger let storageRef = firebase.storage().ref(); let ref = storageRef.child(`${this.basePath}/${newJersey.name}`) var dbRef = this.db.object(`${this.basePath}/${newJersey.name}/`); let self=this; Object.keys(newJersey).map(function (key, index) { if (key == "files") { console.log("About to upload") console.log(newJersey[key]); for (var index = 0; index < newJersey.files.length; index++) { //var index=newJersey.files.length; self.apiHit(newJersey,index,key) } } }); }
(newJersey:UniformStyle,index,key) { debugger let storageRef = firebase.storage().ref(); let ref = storageRef.child(`${this.basePath}/${newJersey.name}`) var dbRef = this.db.object(`${this.basePath}/${newJersey.name}/`); if(index>=0) { let uploadTask1 = storageRef.child(`${'/jersey-styles'}/${newJersey.name}/${newJersey[key][index].img_url.name}`).put(newJersey[key][index].img_url); uploadTask1.on(firebase.storage.TaskEvent.STATE_CHANGED, (snapshot) => { // upload in progress newJersey.progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100 }, (error) => { // upload failed console.log(error) }, () => { // upload success var downloadPath = uploadTask1.snapshot.downloadURL; //console.log(uploadTask.snapshot); //console.log(uploadTask.snapshot.downloadURL); delete newJersey.files[index].img_url; newJersey.files[index].img_url = downloadPath; dbRef.set(newJersey); // index=index-1; // this.apiHit(newJersey,index,key) } ); } } saveFileData(newJersey: any) { debugger this.db.list(`${this.basePath}`).push(newJersey); } // deleteUpload(upload: Upload) { // this.deleteFileData(upload.$key) // .then( () => { // this.deleteFileStorage(upload.name) // }) // .catch(error => console.log(error)) // } // Deletes the file details from the realtime db private deleteFileData(key: string) { return this.db.list(`${this.basePath}/`).remove(key); } // Firebase files must have unique names in their respective storage dir // So the name serves as a unique key private deleteFileStorage(name: string) { let storageRef = firebase.storage().ref(); storageRef.child(`${this.basePath}/${name}`).delete() } }
apiHit
identifier_name
upload.service.ts
import { Injectable } from '@angular/core'; import { Subject } from 'rxjs/Subject'; import { Observable } from 'rxjs/Observable'; import { AngularFireDatabase, FirebaseListObservable } from 'angularfire2/database'; import { Http, Headers } from '@angular/http'; import { FirebaseApp } from 'angularfire2'; // for methods import { AngularFireAuth } from 'angularfire2/auth'; import { Jersey, UniformStyle, Ifile,FileObj } from '../app/admin/models/upload' import * as firebase from 'firebase/app'; import 'rxjs/add/operator/map'; @Injectable() export class UploadService { constructor(private fb: FirebaseApp, private db: AngularFireDatabase) { console.log("Upload service started"); } basePath: string = '/jersey-styles'; uploadJersey: any; uploads: FirebaseListObservable<any[]>; //takes in an upload object and folder name saveNewStyle(newJersey: UniformStyle) { debugger let storageRef = firebase.storage().ref(); let ref = storageRef.child(`${this.basePath}/${newJersey.name}`) var dbRef = this.db.object(`${this.basePath}/${newJersey.name}/`); let self=this; Object.keys(newJersey).map(function (key, index) { if (key == "files") { console.log("About to upload") console.log(newJersey[key]); for (var index = 0; index < newJersey.files.length; index++) { //var index=newJersey.files.length; self.apiHit(newJersey,index,key) } } }); } apiHit(newJersey:UniformStyle,index,key) { debugger let storageRef = firebase.storage().ref(); let ref = storageRef.child(`${this.basePath}/${newJersey.name}`) var dbRef = this.db.object(`${this.basePath}/${newJersey.name}/`); if(index>=0) { let uploadTask1 = storageRef.child(`${'/jersey-styles'}/${newJersey.name}/${newJersey[key][index].img_url.name}`).put(newJersey[key][index].img_url); uploadTask1.on(firebase.storage.TaskEvent.STATE_CHANGED, (snapshot) => { // upload in progress newJersey.progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100 }, (error) => { // upload failed console.log(error) }, () => { // upload success var downloadPath = uploadTask1.snapshot.downloadURL; //console.log(uploadTask.snapshot); //console.log(uploadTask.snapshot.downloadURL); delete newJersey.files[index].img_url; newJersey.files[index].img_url = downloadPath; dbRef.set(newJersey); // index=index-1; // this.apiHit(newJersey,index,key) } ); } } saveFileData(newJersey: any) { debugger this.db.list(`${this.basePath}`).push(newJersey); } // deleteUpload(upload: Upload) { // this.deleteFileData(upload.$key) // .then( () => { // this.deleteFileStorage(upload.name) // }) // .catch(error => console.log(error)) // } // Deletes the file details from the realtime db private deleteFileData(key: string) { return this.db.list(`${this.basePath}/`).remove(key); } // Firebase files must have unique names in their respective storage dir // So the name serves as a unique key private deleteFileStorage(name: string)
}
{ let storageRef = firebase.storage().ref(); storageRef.child(`${this.basePath}/${name}`).delete() }
identifier_body
upload.service.ts
import { Injectable } from '@angular/core'; import { Subject } from 'rxjs/Subject'; import { Observable } from 'rxjs/Observable'; import { AngularFireDatabase, FirebaseListObservable } from 'angularfire2/database'; import { Http, Headers } from '@angular/http'; import { FirebaseApp } from 'angularfire2'; // for methods import { AngularFireAuth } from 'angularfire2/auth'; import { Jersey, UniformStyle, Ifile,FileObj } from '../app/admin/models/upload' import * as firebase from 'firebase/app'; import 'rxjs/add/operator/map'; @Injectable() export class UploadService { constructor(private fb: FirebaseApp, private db: AngularFireDatabase) { console.log("Upload service started"); } basePath: string = '/jersey-styles'; uploadJersey: any; uploads: FirebaseListObservable<any[]>; //takes in an upload object and folder name saveNewStyle(newJersey: UniformStyle) { debugger let storageRef = firebase.storage().ref(); let ref = storageRef.child(`${this.basePath}/${newJersey.name}`) var dbRef = this.db.object(`${this.basePath}/${newJersey.name}/`); let self=this; Object.keys(newJersey).map(function (key, index) { if (key == "files")
}); } apiHit(newJersey:UniformStyle,index,key) { debugger let storageRef = firebase.storage().ref(); let ref = storageRef.child(`${this.basePath}/${newJersey.name}`) var dbRef = this.db.object(`${this.basePath}/${newJersey.name}/`); if(index>=0) { let uploadTask1 = storageRef.child(`${'/jersey-styles'}/${newJersey.name}/${newJersey[key][index].img_url.name}`).put(newJersey[key][index].img_url); uploadTask1.on(firebase.storage.TaskEvent.STATE_CHANGED, (snapshot) => { // upload in progress newJersey.progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100 }, (error) => { // upload failed console.log(error) }, () => { // upload success var downloadPath = uploadTask1.snapshot.downloadURL; //console.log(uploadTask.snapshot); //console.log(uploadTask.snapshot.downloadURL); delete newJersey.files[index].img_url; newJersey.files[index].img_url = downloadPath; dbRef.set(newJersey); // index=index-1; // this.apiHit(newJersey,index,key) } ); } } saveFileData(newJersey: any) { debugger this.db.list(`${this.basePath}`).push(newJersey); } // deleteUpload(upload: Upload) { // this.deleteFileData(upload.$key) // .then( () => { // this.deleteFileStorage(upload.name) // }) // .catch(error => console.log(error)) // } // Deletes the file details from the realtime db private deleteFileData(key: string) { return this.db.list(`${this.basePath}/`).remove(key); } // Firebase files must have unique names in their respective storage dir // So the name serves as a unique key private deleteFileStorage(name: string) { let storageRef = firebase.storage().ref(); storageRef.child(`${this.basePath}/${name}`).delete() } }
{ console.log("About to upload") console.log(newJersey[key]); for (var index = 0; index < newJersey.files.length; index++) { //var index=newJersey.files.length; self.apiHit(newJersey,index,key) } }
conditional_block
upload.service.ts
import { Injectable } from '@angular/core'; import { Subject } from 'rxjs/Subject'; import { Observable } from 'rxjs/Observable'; import { AngularFireDatabase, FirebaseListObservable } from 'angularfire2/database'; import { Http, Headers } from '@angular/http'; import { FirebaseApp } from 'angularfire2'; // for methods import { AngularFireAuth } from 'angularfire2/auth'; import { Jersey, UniformStyle, Ifile,FileObj } from '../app/admin/models/upload' import * as firebase from 'firebase/app'; import 'rxjs/add/operator/map'; @Injectable() export class UploadService { constructor(private fb: FirebaseApp, private db: AngularFireDatabase) { console.log("Upload service started"); } basePath: string = '/jersey-styles'; uploadJersey: any; uploads: FirebaseListObservable<any[]>; //takes in an upload object and folder name saveNewStyle(newJersey: UniformStyle) { debugger let storageRef = firebase.storage().ref(); let ref = storageRef.child(`${this.basePath}/${newJersey.name}`) var dbRef = this.db.object(`${this.basePath}/${newJersey.name}/`); let self=this; Object.keys(newJersey).map(function (key, index) { if (key == "files") { console.log("About to upload") console.log(newJersey[key]); for (var index = 0; index < newJersey.files.length; index++) {
} apiHit(newJersey:UniformStyle,index,key) { debugger let storageRef = firebase.storage().ref(); let ref = storageRef.child(`${this.basePath}/${newJersey.name}`) var dbRef = this.db.object(`${this.basePath}/${newJersey.name}/`); if(index>=0) { let uploadTask1 = storageRef.child(`${'/jersey-styles'}/${newJersey.name}/${newJersey[key][index].img_url.name}`).put(newJersey[key][index].img_url); uploadTask1.on(firebase.storage.TaskEvent.STATE_CHANGED, (snapshot) => { // upload in progress newJersey.progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100 }, (error) => { // upload failed console.log(error) }, () => { // upload success var downloadPath = uploadTask1.snapshot.downloadURL; //console.log(uploadTask.snapshot); //console.log(uploadTask.snapshot.downloadURL); delete newJersey.files[index].img_url; newJersey.files[index].img_url = downloadPath; dbRef.set(newJersey); // index=index-1; // this.apiHit(newJersey,index,key) } ); } } saveFileData(newJersey: any) { debugger this.db.list(`${this.basePath}`).push(newJersey); } // deleteUpload(upload: Upload) { // this.deleteFileData(upload.$key) // .then( () => { // this.deleteFileStorage(upload.name) // }) // .catch(error => console.log(error)) // } // Deletes the file details from the realtime db private deleteFileData(key: string) { return this.db.list(`${this.basePath}/`).remove(key); } // Firebase files must have unique names in their respective storage dir // So the name serves as a unique key private deleteFileStorage(name: string) { let storageRef = firebase.storage().ref(); storageRef.child(`${this.basePath}/${name}`).delete() } }
//var index=newJersey.files.length; self.apiHit(newJersey,index,key) } } });
random_line_split
move-side-effects-to-legacy.ts
// Copyright 2019 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import { parse, print, types } from 'recast'; import fs, { stat } from 'fs'; import path from 'path'; import { promisify } from 'util'; import { IdentifierKind, MemberExpressionKind, ExpressionKind, CommentKind } from 'ast-types/gen/kinds'; const readDir = promisify(fs.readdir); const readFile = promisify(fs.readFile); const writeFile = promisify(fs.writeFile); const b = types.builders; const FRONT_END_FOLDER = path.join(__dirname, '..', '..', 'front_end') let legacyStatements: any[] = []; let legacyTypeDefs: any[] = []; let targetNamespace = ''; function rewriteSource(source: string, fileName: string) { const ast = parse(source); const statements: any[] = []; const typeDefs: any[] = []; ast.program.body = ast.program.body.map((statement: any) => { try { switch (statement.type) { case 'ExpressionStatement': if (statement.expression.type === 'CallExpression') { break; } // Remove Foo = Foo || {} if (statement.expression.type === 'AssignmentExpression') { if (statement.expression.left.name === targetNamespace) { return b.emptyStatement(); } } // Remove typedefs of the type Foo.ThingName; if (statement.expression.type === 'MemberExpression') { // Keep going to the left of namespaces to check the leftmost, // and if it is the target namespace, pull it. let current = statement.expression.object; while (current.object) { current = current.object; } if (current.name === targetNamespace) { typeDefs.push(statement); return b.emptyStatement(); } } if (statement.expression.left.type === 'MemberExpression') { // Remove self.Foo = self.Foo || {} if (statement.expression.left.object.name === 'self') { // Grab the namespace from the RHS of self.[Namespace]
} return b.emptyStatement(); } // Keep going to the left of namespaces to check the leftmost, // and if it is the target namespace, pull it. let current = statement.expression.left.object; while (current.object) { current = current.object; } if (current.name === targetNamespace) { statements.push(statement); return b.emptyStatement(); } } break; } } catch (e) { console.warn(`Unexpected expression in ${fileName}:`); console.warn(print(statement).code); console.log(statement); process.exit(1); } return statement; }); // Rewrite legacy RHS to use module name. const remappedStatements = statements.map(statement => { if (statement.expression.type === 'AssignmentExpression') { const { name } = statement.expression.right; const innerNamespace = capitalizeFirstLetter(fileName).replace(/.js$/, ''); statement.expression.right.name = `${targetNamespace}Module.${innerNamespace}.${name}`; } return statement; }); legacyStatements = [...legacyStatements, ...remappedStatements]; legacyTypeDefs = [...legacyTypeDefs, ...typeDefs]; return print(ast).code; } function createLegacy() { const ast = parse(''); ast.program.body = legacyStatements.concat(legacyTypeDefs); return print(ast).code; } function capitalizeFirstLetter(string: string) { return string.charAt(0).toUpperCase() + string.slice(1); } async function main(folder: string) { const pathName = path.join(FRONT_END_FOLDER, folder); const srcDir = await readDir(pathName); for (const srcFile of srcDir) { if (srcFile !== 'ARIAUtils.js' && !srcFile.endsWith('.js')) { continue; } const filePath = path.join(pathName, srcFile); const srcFileContents = await readFile(filePath, { encoding: 'utf-8' }); const dstFileContents = rewriteSource(srcFileContents, srcFile); await writeFile(filePath, dstFileContents); } // Create a foo-legacy.js file const dstLegacy = path.join(pathName, `${folder}-legacy.js`); const legacyContents = `// Copyright 2019 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import * as ${targetNamespace}Module from './${folder}.js'; self.${targetNamespace} = self.${targetNamespace} || {}; ${targetNamespace} = ${targetNamespace} || {}; ${createLegacy()} `; await writeFile(dstLegacy, legacyContents); } if (!process.argv[2]) { console.error(`No arguments specified. Run this script with "<folder-name>". For example: "ui"`); process.exit(1); } main(process.argv[2]);
if (statement.expression.right.type === 'LogicalExpression') { targetNamespace = statement.expression.right.left.property.name;
random_line_split
move-side-effects-to-legacy.ts
// Copyright 2019 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import { parse, print, types } from 'recast'; import fs, { stat } from 'fs'; import path from 'path'; import { promisify } from 'util'; import { IdentifierKind, MemberExpressionKind, ExpressionKind, CommentKind } from 'ast-types/gen/kinds'; const readDir = promisify(fs.readdir); const readFile = promisify(fs.readFile); const writeFile = promisify(fs.writeFile); const b = types.builders; const FRONT_END_FOLDER = path.join(__dirname, '..', '..', 'front_end') let legacyStatements: any[] = []; let legacyTypeDefs: any[] = []; let targetNamespace = ''; function rewriteSource(source: string, fileName: string)
function createLegacy() { const ast = parse(''); ast.program.body = legacyStatements.concat(legacyTypeDefs); return print(ast).code; } function capitalizeFirstLetter(string: string) { return string.charAt(0).toUpperCase() + string.slice(1); } async function main(folder: string) { const pathName = path.join(FRONT_END_FOLDER, folder); const srcDir = await readDir(pathName); for (const srcFile of srcDir) { if (srcFile !== 'ARIAUtils.js' && !srcFile.endsWith('.js')) { continue; } const filePath = path.join(pathName, srcFile); const srcFileContents = await readFile(filePath, { encoding: 'utf-8' }); const dstFileContents = rewriteSource(srcFileContents, srcFile); await writeFile(filePath, dstFileContents); } // Create a foo-legacy.js file const dstLegacy = path.join(pathName, `${folder}-legacy.js`); const legacyContents = `// Copyright 2019 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import * as ${targetNamespace}Module from './${folder}.js'; self.${targetNamespace} = self.${targetNamespace} || {}; ${targetNamespace} = ${targetNamespace} || {}; ${createLegacy()} `; await writeFile(dstLegacy, legacyContents); } if (!process.argv[2]) { console.error(`No arguments specified. Run this script with "<folder-name>". For example: "ui"`); process.exit(1); } main(process.argv[2]);
{ const ast = parse(source); const statements: any[] = []; const typeDefs: any[] = []; ast.program.body = ast.program.body.map((statement: any) => { try { switch (statement.type) { case 'ExpressionStatement': if (statement.expression.type === 'CallExpression') { break; } // Remove Foo = Foo || {} if (statement.expression.type === 'AssignmentExpression') { if (statement.expression.left.name === targetNamespace) { return b.emptyStatement(); } } // Remove typedefs of the type Foo.ThingName; if (statement.expression.type === 'MemberExpression') { // Keep going to the left of namespaces to check the leftmost, // and if it is the target namespace, pull it. let current = statement.expression.object; while (current.object) { current = current.object; } if (current.name === targetNamespace) { typeDefs.push(statement); return b.emptyStatement(); } } if (statement.expression.left.type === 'MemberExpression') { // Remove self.Foo = self.Foo || {} if (statement.expression.left.object.name === 'self') { // Grab the namespace from the RHS of self.[Namespace] if (statement.expression.right.type === 'LogicalExpression') { targetNamespace = statement.expression.right.left.property.name; } return b.emptyStatement(); } // Keep going to the left of namespaces to check the leftmost, // and if it is the target namespace, pull it. let current = statement.expression.left.object; while (current.object) { current = current.object; } if (current.name === targetNamespace) { statements.push(statement); return b.emptyStatement(); } } break; } } catch (e) { console.warn(`Unexpected expression in ${fileName}:`); console.warn(print(statement).code); console.log(statement); process.exit(1); } return statement; }); // Rewrite legacy RHS to use module name. const remappedStatements = statements.map(statement => { if (statement.expression.type === 'AssignmentExpression') { const { name } = statement.expression.right; const innerNamespace = capitalizeFirstLetter(fileName).replace(/.js$/, ''); statement.expression.right.name = `${targetNamespace}Module.${innerNamespace}.${name}`; } return statement; }); legacyStatements = [...legacyStatements, ...remappedStatements]; legacyTypeDefs = [...legacyTypeDefs, ...typeDefs]; return print(ast).code; }
identifier_body
move-side-effects-to-legacy.ts
// Copyright 2019 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import { parse, print, types } from 'recast'; import fs, { stat } from 'fs'; import path from 'path'; import { promisify } from 'util'; import { IdentifierKind, MemberExpressionKind, ExpressionKind, CommentKind } from 'ast-types/gen/kinds'; const readDir = promisify(fs.readdir); const readFile = promisify(fs.readFile); const writeFile = promisify(fs.writeFile); const b = types.builders; const FRONT_END_FOLDER = path.join(__dirname, '..', '..', 'front_end') let legacyStatements: any[] = []; let legacyTypeDefs: any[] = []; let targetNamespace = ''; function rewriteSource(source: string, fileName: string) { const ast = parse(source); const statements: any[] = []; const typeDefs: any[] = []; ast.program.body = ast.program.body.map((statement: any) => { try { switch (statement.type) { case 'ExpressionStatement': if (statement.expression.type === 'CallExpression') { break; } // Remove Foo = Foo || {} if (statement.expression.type === 'AssignmentExpression') { if (statement.expression.left.name === targetNamespace) { return b.emptyStatement(); } } // Remove typedefs of the type Foo.ThingName; if (statement.expression.type === 'MemberExpression') { // Keep going to the left of namespaces to check the leftmost, // and if it is the target namespace, pull it. let current = statement.expression.object; while (current.object) { current = current.object; } if (current.name === targetNamespace)
} if (statement.expression.left.type === 'MemberExpression') { // Remove self.Foo = self.Foo || {} if (statement.expression.left.object.name === 'self') { // Grab the namespace from the RHS of self.[Namespace] if (statement.expression.right.type === 'LogicalExpression') { targetNamespace = statement.expression.right.left.property.name; } return b.emptyStatement(); } // Keep going to the left of namespaces to check the leftmost, // and if it is the target namespace, pull it. let current = statement.expression.left.object; while (current.object) { current = current.object; } if (current.name === targetNamespace) { statements.push(statement); return b.emptyStatement(); } } break; } } catch (e) { console.warn(`Unexpected expression in ${fileName}:`); console.warn(print(statement).code); console.log(statement); process.exit(1); } return statement; }); // Rewrite legacy RHS to use module name. const remappedStatements = statements.map(statement => { if (statement.expression.type === 'AssignmentExpression') { const { name } = statement.expression.right; const innerNamespace = capitalizeFirstLetter(fileName).replace(/.js$/, ''); statement.expression.right.name = `${targetNamespace}Module.${innerNamespace}.${name}`; } return statement; }); legacyStatements = [...legacyStatements, ...remappedStatements]; legacyTypeDefs = [...legacyTypeDefs, ...typeDefs]; return print(ast).code; } function createLegacy() { const ast = parse(''); ast.program.body = legacyStatements.concat(legacyTypeDefs); return print(ast).code; } function capitalizeFirstLetter(string: string) { return string.charAt(0).toUpperCase() + string.slice(1); } async function main(folder: string) { const pathName = path.join(FRONT_END_FOLDER, folder); const srcDir = await readDir(pathName); for (const srcFile of srcDir) { if (srcFile !== 'ARIAUtils.js' && !srcFile.endsWith('.js')) { continue; } const filePath = path.join(pathName, srcFile); const srcFileContents = await readFile(filePath, { encoding: 'utf-8' }); const dstFileContents = rewriteSource(srcFileContents, srcFile); await writeFile(filePath, dstFileContents); } // Create a foo-legacy.js file const dstLegacy = path.join(pathName, `${folder}-legacy.js`); const legacyContents = `// Copyright 2019 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import * as ${targetNamespace}Module from './${folder}.js'; self.${targetNamespace} = self.${targetNamespace} || {}; ${targetNamespace} = ${targetNamespace} || {}; ${createLegacy()} `; await writeFile(dstLegacy, legacyContents); } if (!process.argv[2]) { console.error(`No arguments specified. Run this script with "<folder-name>". For example: "ui"`); process.exit(1); } main(process.argv[2]);
{ typeDefs.push(statement); return b.emptyStatement(); }
conditional_block
move-side-effects-to-legacy.ts
// Copyright 2019 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import { parse, print, types } from 'recast'; import fs, { stat } from 'fs'; import path from 'path'; import { promisify } from 'util'; import { IdentifierKind, MemberExpressionKind, ExpressionKind, CommentKind } from 'ast-types/gen/kinds'; const readDir = promisify(fs.readdir); const readFile = promisify(fs.readFile); const writeFile = promisify(fs.writeFile); const b = types.builders; const FRONT_END_FOLDER = path.join(__dirname, '..', '..', 'front_end') let legacyStatements: any[] = []; let legacyTypeDefs: any[] = []; let targetNamespace = ''; function
(source: string, fileName: string) { const ast = parse(source); const statements: any[] = []; const typeDefs: any[] = []; ast.program.body = ast.program.body.map((statement: any) => { try { switch (statement.type) { case 'ExpressionStatement': if (statement.expression.type === 'CallExpression') { break; } // Remove Foo = Foo || {} if (statement.expression.type === 'AssignmentExpression') { if (statement.expression.left.name === targetNamespace) { return b.emptyStatement(); } } // Remove typedefs of the type Foo.ThingName; if (statement.expression.type === 'MemberExpression') { // Keep going to the left of namespaces to check the leftmost, // and if it is the target namespace, pull it. let current = statement.expression.object; while (current.object) { current = current.object; } if (current.name === targetNamespace) { typeDefs.push(statement); return b.emptyStatement(); } } if (statement.expression.left.type === 'MemberExpression') { // Remove self.Foo = self.Foo || {} if (statement.expression.left.object.name === 'self') { // Grab the namespace from the RHS of self.[Namespace] if (statement.expression.right.type === 'LogicalExpression') { targetNamespace = statement.expression.right.left.property.name; } return b.emptyStatement(); } // Keep going to the left of namespaces to check the leftmost, // and if it is the target namespace, pull it. let current = statement.expression.left.object; while (current.object) { current = current.object; } if (current.name === targetNamespace) { statements.push(statement); return b.emptyStatement(); } } break; } } catch (e) { console.warn(`Unexpected expression in ${fileName}:`); console.warn(print(statement).code); console.log(statement); process.exit(1); } return statement; }); // Rewrite legacy RHS to use module name. const remappedStatements = statements.map(statement => { if (statement.expression.type === 'AssignmentExpression') { const { name } = statement.expression.right; const innerNamespace = capitalizeFirstLetter(fileName).replace(/.js$/, ''); statement.expression.right.name = `${targetNamespace}Module.${innerNamespace}.${name}`; } return statement; }); legacyStatements = [...legacyStatements, ...remappedStatements]; legacyTypeDefs = [...legacyTypeDefs, ...typeDefs]; return print(ast).code; } function createLegacy() { const ast = parse(''); ast.program.body = legacyStatements.concat(legacyTypeDefs); return print(ast).code; } function capitalizeFirstLetter(string: string) { return string.charAt(0).toUpperCase() + string.slice(1); } async function main(folder: string) { const pathName = path.join(FRONT_END_FOLDER, folder); const srcDir = await readDir(pathName); for (const srcFile of srcDir) { if (srcFile !== 'ARIAUtils.js' && !srcFile.endsWith('.js')) { continue; } const filePath = path.join(pathName, srcFile); const srcFileContents = await readFile(filePath, { encoding: 'utf-8' }); const dstFileContents = rewriteSource(srcFileContents, srcFile); await writeFile(filePath, dstFileContents); } // Create a foo-legacy.js file const dstLegacy = path.join(pathName, `${folder}-legacy.js`); const legacyContents = `// Copyright 2019 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import * as ${targetNamespace}Module from './${folder}.js'; self.${targetNamespace} = self.${targetNamespace} || {}; ${targetNamespace} = ${targetNamespace} || {}; ${createLegacy()} `; await writeFile(dstLegacy, legacyContents); } if (!process.argv[2]) { console.error(`No arguments specified. Run this script with "<folder-name>". For example: "ui"`); process.exit(1); } main(process.argv[2]);
rewriteSource
identifier_name
urls.py
from django.urls import url, include, path from rest_framework import routers from users import views # router = routers.DefaultRouter() # router.register(r'users', views.UserViewSet) # router.register(r'groups', views.GroupViewSet) # # # Wire up our API using automatic URL routing. # # Additionally, we include login URLs for the browsable API. # urlpatterns = [ # path('', include(router.urls)), # path('api-auth/', include('rest_framework.urls', namespace='rest_framework')) # ] # -*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals urlpatterns = [ url( regex=r'^$', view=views.UserListView.as_view(), name='list' ), url( regex=r'^~redirect/$', view=views.UserRedirectView.as_view(), name='redirect' ),
url( regex=r'^~update/$', view=views.UserUpdateView.as_view(), name='update' ), ]
url( regex=r'^(?P<username>[\w.@+-]+)/$', view=views.UserDetailView.as_view(), name='detail' ),
random_line_split
jquery.ui.dialog.minmax.js
/* * jQuery UI Dialog 1.8.16 * w/ Minimize & Maximize Support * by Elijah Horton (fieryprophet@yahoo.com) * * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about) * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license * * http://docs.jquery.com/UI/Dialog * * Depends: * jquery.ui.core.js * jquery.ui.widget.js * jquery.ui.button.js * jquery.ui.draggable.js * jquery.ui.mouse.js * jquery.ui.position.js * jquery.ui.resizable.js * * Modified by André Roberge to remove some IE support which is irrelevant for me. */ (function( $, undefined ) { var uiDialogClasses = 'ui-dialog ' + 'ui-widget ' + 'ui-widget-content ' + 'ui-corner-all ', sizeRelatedOptions = { buttons: true, height: true, maxHeight: true, maxWidth: true, minHeight: true, minWidth: true, width: true }, resizableRelatedOptions = { maxHeight: true, maxWidth: true, minHeight: true, minWidth: true }, // support for jQuery 1.3.2 - handle common attrFn methods for dialog attrFn = $.attrFn || { val: true, css: true, html: true, text: true, data: true, width: true, height: true, offset: true, click: true }; $.widget("ui.dialog", { options: { autoOpen: true, buttons: {}, closeOnEscape: true, closeText: 'close', dialogClass: '', draggable: true, hide: null, height: 'auto', maxHeight: false, maxWidth: false, minHeight: 150, minWidth: 300, minimizeText: 'minimize', maximizeText: 'maximize', minimize: true, maximize: true, modal: false, position: { my: 'center', at: 'center', collision: 'fit', // ensure that the titlebar is never outside the document using: function(pos) { var topOffset = $(this).css(pos).offset().top; if (topOffset < 0) { $(this).css('top', pos.top - topOffset); } } }, resizable: true, show: null, stack: true, title: '', width: 300, zIndex: 1000 }, _create: function() { this.originalTitle = this.element.attr('title'); // #5742 - .attr() might return a DOMElement if ( typeof this.originalTitle !== "string" ) { this.originalTitle = ""; } this.options.title = this.options.title || this.originalTitle; var self = this, options = self.options, title = options.title || '&#160;', titleId = $.ui.dialog.getTitleId(self.element), uiDialog = (self.uiDialog = $('<div></div>')) .appendTo(document.body) .hide() .addClass(uiDialogClasses + options.dialogClass) .css({ zIndex: options.zIndex }) // setting tabIndex makes the div focusable // setting outline to 0 prevents a border on focus in Mozilla .attr('tabIndex', -1).css('outline', 0).keydown(function(event) { if (options.closeOnEscape && !event.isDefaultPrevented() && event.keyCode && event.keyCode === $.ui.keyCode.ESCAPE) { self.close(event); event.preventDefault(); } }) .attr({ role: 'dialog', 'aria-labelledby': titleId }) .mousedown(function(event) { self.moveToTop(false, event); }), uiDialogContent = self.element .show() .removeAttr('title') .addClass( 'ui-dialog-content ' + 'ui-widget-content') .appendTo(uiDialog), uiDialogTitlebar = (self.uiDialogTitlebar = $('<div></div>')) .addClass( 'ui-dialog-titlebar ' + 'ui-widget-header ' + 'ui-corner-all ' + 'ui-helper-clearfix' ) .prependTo(uiDialog); if(options.minimize && !options.modal){ //cannot use this option with modal var uiDialogTitlebarMinimize = $('<a href="#"></a>') .addClass( 'ui-dialog-titlebar-minimize ' + 'ui-corner-all' ) .attr('role', 'button') .hover( function() { uiDialogTitlebarMinimize.addClass('ui-state-hover'); }, function() { uiDialogTitlebarMinimize.removeClass('ui-state-hover'); } ) .focus(function() { uiDialogTitlebarMinimize.addClass('ui-state-focus'); }) .blur(function() { uiDialogTitlebarMinimize.removeClass('ui-state-focus'); }) .click(function(event) { self.minimize(event); return false; }) .appendTo(uiDialogTitlebar), uiDialogTitlebarMinimizeText = (self.uiDialogTitlebarMinimizeText = $('<span></span>')) .addClass( 'ui-icon ' + 'ui-icon-minusthick' ) .text(options.minimizeText) .appendTo(uiDialogTitlebarMinimize); } if(options.maximize && !options.modal){ //cannot use this option with modal var uiDialogTitlebarMaximize = $('<a href="#"></a>') .addClass( 'ui-dialog-titlebar-maximize ' + 'ui-corner-all' ) .attr('role', 'button') .hover( function() { uiDialogTitlebarMaximize.addClass('ui-state-hover'); }, function() { uiDialogTitlebarMaximize.removeClass('ui-state-hover'); } ) .focus(function() { uiDialogTitlebarMaximize.addClass('ui-state-focus'); }) .blur(function() { uiDialogTitlebarMaximize.removeClass('ui-state-focus'); }) .click(function(event) { self.maximize(event); return false; }) .appendTo(uiDialogTitlebar), uiDialogTitlebarMaximizeText = (self.uiDialogTitlebarMaximizeText = $('<span></span>')) .addClass( 'ui-icon ' + 'ui-icon-plusthick' ) .text(options.maximizeText) .appendTo(uiDialogTitlebarMaximize); $(uiDialogTitlebar).dblclick(function(event) { self.maximize(event); return false; }); } if(options.close !== false){ var uiDialogTitlebarClose = $('<a href="#"></a>') .addClass( 'ui-dialog-titlebar-close ' + 'ui-corner-all' ) .attr('role', 'button') .hover( function() { uiDialogTitlebarClose.addClass('ui-state-hover'); }, function() { uiDialogTitlebarClose.removeClass('ui-state-hover'); } ) .focus(function() { uiDialogTitlebarClose.addClass('ui-state-focus'); }) .blur(function() { uiDialogTitlebarClose.removeClass('ui-state-focus'); }) .click(function(event) { self.close(event); return false; }) .appendTo(uiDialogTitlebar), uiDialogTitlebarCloseText = (self.uiDialogTitlebarCloseText = $('<span></span>')) .addClass( 'ui-icon ' + 'ui-icon-closethick' ) .text(options.closeText) .appendTo(uiDialogTitlebarClose); } uiDialogTitle = $('<span></span>') .addClass('ui-dialog-title') .attr('id', titleId) .html(title) .prependTo(uiDialogTitlebar); //handling of deprecated beforeclose (vs beforeClose) option //Ticket #4669 http://dev.jqueryui.com/ticket/4669 //TODO: remove in 1.9pre if ($.isFunction(options.beforeclose) && !$.isFunction(options.beforeClose)) { options.beforeClose = options.beforeclose; } uiDialogTitlebar.find("*").add(uiDialogTitlebar).disableSelection(); if (options.draggable && $.fn.draggable) { self._makeDraggable(); } if (options.resizable && $.fn.resizable) { self._makeResizable(); } self._createButtons(options.buttons); self._isOpen = false; self._min = false; if ($.fn.bgiframe) { uiDialog.bgiframe(); } }, _init: function() { if ( this.options.autoOpen ) { this.open(); } }, destroy: function() { var self = this; if (self.overlay) { self.overlay.destroy(); } self.uiDialog.hide(); self.element .unbind('.dialog') .removeData('dialog') .removeClass('ui-dialog-content ui-widget-content') .hide().appendTo('body'); self.uiDialog.remove(); if (self.originalTitle) { self.element.attr('title', self.originalTitle); } return self; }, widget: function() { return this.uiDialog; }, minimize: function(event) { var self = this, ui = self.uiDialog; if(false === self._trigger('beforeMinimize', event)) { return; } if(!ui.data('is-minimized')){ if(self.options.minimize && typeof self.options.minimize !== "boolean" && $(self.options.minimize).length > 0){ self._min = $('<a>' + (ui.find('span.ui-dialog-title').html().replace(/&nbsp;/, '') || 'Untitled Dialog') + '</a>') .attr('title', 'Click to restore dialog').addClass('ui-corner-all ui-button').click(function(event){self.unminimize(event);}); $(self.options.minimize).append(self._min); ui.data('is-minimized', true).hide(); } else { if(ui.is( ":data(resizable)" )) { ui.data('was-resizable', true).resizable('destroy'); } else { ui.data('was-resizable', false) } ui.data('minimized-height', ui.height()); ui.find('.ui-dialog-content').hide(); ui.find('.ui-dialog-titlebar-maximize').hide(); ui.find('.ui-dialog-titlebar-minimize').css('right', '1.8em').removeClass('ui-icon-minusthick').addClass('ui-icon-arrowthickstop-1-s') .find('span').removeClass('ui-icon-minusthick').addClass('ui-icon-arrowthickstop-1-s').click(function(event){self.unminimize(event); return false;});; ui.data('is-minimized', true).height('auto'); } } return self; }, unminimize: function(event) { var self = this, ui = self.uiDialog; if(false === self._trigger('beforeUnminimize', event)) { return; } if(ui.data('is-minimized')){ if(self._min){ self._min.unbind().remove(); self._min = false; ui.data('is-minimized', false).show(); self.moveToTop(); } else { ui.height(ui.data('minimized-height')).data('is-minimized', false).removeData('minimized-height').find('.ui-dialog-content').show(); ui.find('.ui-dialog-titlebar-maximize').show(); ui.find('.ui-dialog-titlebar-minimize').css('right', '3.3em').removeClass('ui-icon-arrowthickstop-1-s').addClass('ui-icon-minusthick') .find('span').removeClass('ui-icon-arrowthickstop-1-s').addClass('ui-icon-minusthick').click(function(event){self.minimize(event); return false;}); if(ui.data('was-resizable') == true) { self._makeResizable(true); } } } return self; }, maximize: function(event) { var self = this, ui = self.uiDialog; if(false === self._trigger('beforeMaximize', event)) { return; } if(!ui.data('is-maximized')){ if(ui.is( ":data(draggable)" )) { ui.data('was-draggable', true).draggable('destroy'); } else { ui.data('was-draggable', false) } if(ui.is( ":data(resizable)" )) { ui.data('was-resizable', true).resizable('destroy'); } else { ui.data('was-resizable', false) } ui.data('maximized-height', ui.height()).data('maximized-width', ui.width()).data('maximized-top', ui.css('top')).data('maximized-left', ui.css('left')) .data('is-maximized', true).height($(window).height()-8).width($(window).width()+9).css({"top":0, "left": 0}).find('.ui-dialog-titlebar-minimize').hide(); ui.find('.ui-dialog-titlebar-maximize').removeClass('ui-icon-plusthick').addClass('ui-icon-arrowthick-1-sw') .find('span').removeClass('ui-icon-plusthick').addClass('ui-icon-arrowthick-1-sw').click(function(event){self.unmaximize(event); return false;}); ui.find('.ui-dialog-titlebar').dblclick(function(event){self.unmaximize(event); return false;}); } return self; }, unmaximize: function(event) { var self = this, ui = self.uiDialog; if(false === self._trigger('beforeUnmaximize', event)) { return; } if(ui.data('is-maximized')){ ui.height(ui.data('maximized-height')).width(ui.data('maximized-width')).css({"top":ui.data('maximized-top'), "left":ui.data('maximized-left')}) .data('is-maximized', false).removeData('maximized-height').removeData('maximized-width').removeData('maximized-top').removeData('maximized-left').find('.ui-dialog-titlebar-minimize').show(); ui.find('.ui-dialog-titlebar-maximize').removeClass('ui-icon-arrowthick-1-sw').addClass('ui-icon-plusthick') .find('span').removeClass('ui-icon-arrowthick-1-sw').addClass('ui-icon-plusthick').click(function(){self.maximize(event); return false;}); ui.find('.ui-dialog-titlebar').dblclick(function(event){self.maximize(event); return false;}); if(ui.data('was-draggable') == true) { self._makeDraggable(true); } if(ui.data('was-resizable') == true) { self._makeResizable(true); } } return self; }, close: function(event) { var self = this, maxZ, thisZ; if (false === self._trigger('beforeClose', event)) { return; } if (self.overlay) { self.overlay.destroy(); } self.uiDialog.unbind('keypress.ui-dialog'); self._isOpen = false; if (self.options.hide) { self.uiDialog.hide(self.options.hide, function() { self._trigger('close', event); }); } else { self.uiDialog.hide(); self._trigger('close', event); } $.ui.dialog.overlay.resize(); // adjust the maxZ to allow other modal dialogs to continue to work (see #4309) if (self.options.modal) { maxZ = 0; $('.ui-dialog').each(function() { if (this !== self.uiDialog[0]) { thisZ = $(this).css('z-index'); if(!isNaN(thisZ)) { maxZ = Math.max(maxZ, thisZ); } } }); $.ui.dialog.maxZ = maxZ; } return self; }, isOpen: function() { return this._isOpen; }, // the force parameter allows us to move modal dialogs to their correct // position on open moveToTop: function(force, event) { var self = this, options = self.options, saveScroll; if ((options.modal && !force) || (!options.stack && !options.modal)) { return self._trigger('focus', event); } if (options.zIndex > $.ui.dialog.maxZ) { $.ui.dialog.maxZ = options.zIndex; } if (self.overlay) { $.ui.dialog.maxZ += 1; self.overlay.$el.css('z-index', $.ui.dialog.overlay.maxZ = $.ui.dialog.maxZ); } //Save and then restore scroll since Opera 9.5+ resets when parent z-Index is changed. // http://ui.jquery.com/bugs/ticket/3193 saveScroll = { scrollTop: self.element.scrollTop(), scrollLeft: self.element.scrollLeft() }; $.ui.dialog.maxZ += 1; self.uiDialog.css('z-index', $.ui.dialog.maxZ); self.element.attr(saveScroll); self._trigger('focus', event); return self; }, open: function() { if (this._isOpen) { return; } var self = this, options = self.options, uiDialog = self.uiDialog; self.overlay = options.modal ? new $.ui.dialog.overlay(self) : null; self._size(); self._position(options.position); uiDialog.show(options.show); self.moveToTop(true); // prevent tabbing out of modal dialogs if (options.modal) { uiDialog.bind('keypress.ui-dialog', function(event) { if (event.keyCode !== $.ui.keyCode.TAB) { return; } var tabbables = $(':tabbable', this), first = tabbables.filter(':first'), last = tabbables.filter(':last'); if (event.target === last[0] && !event.shiftKey) { first.focus(1); return false; } else if (event.target === first[0] && event.shiftKey) { last.focus(1); return false; } }); } // set focus to the first tabbable element in the content area or the first button // if there are no tabbable elements, set focus on the dialog itself $(self.element.find(':tabbable').get().concat( uiDialog.find('.ui-dialog-buttonpane :tabbable').get().concat( uiDialog.get()))).eq(0).focus(); self._isOpen = true; self._trigger('open'); return self; }, _createButtons: function(buttons) { var self = this, hasButtons = false, uiDialogButtonPane = $('<div></div>') .addClass( 'ui-dialog-buttonpane ' + 'ui-widget-content ' + 'ui-helper-clearfix' ), uiButtonSet = $( "<div></div>" ) .addClass( "ui-dialog-buttonset" ) .appendTo( uiDialogButtonPane ); // if we already have a button pane, remove it self.uiDialog.find('.ui-dialog-buttonpane').remove(); if (typeof buttons === 'object' && buttons !== null) { $.each(buttons, function() { return !(hasButtons = true); }); } if (hasButtons) { $.each(buttons, function(name, props) { props = $.isFunction( props ) ? { click: props, text: name } : props; var button = $('<button type="button"></button>') .click(function() { props.click.apply(self.element[0], arguments); }) .appendTo(uiButtonSet); // can't use .attr( props, true ) with jQuery 1.3.2. $.each( props, function( key, value ) { if ( key === "click" ) { return; } if ( key in attrFn ) { button[ key ]( value ); } else { button.attr( key, value ); } }); if ($.fn.button) { button.button(); } }); uiDialogButtonPane.appendTo(self.uiDialog); } }, _makeDraggable: function() { var self = this, options = self.options, doc = $(document), heightBeforeDrag; function f
ui) { return { position: ui.position, offset: ui.offset }; } self.uiDialog.draggable({ cancel: '.ui-dialog-content, .ui-dialog-titlebar-close', handle: '.ui-dialog-titlebar', containment: 'document', start: function(event, ui) { heightBeforeDrag = options.height === "auto" ? "auto" : $(this).height(); $(this).height($(this).height()).addClass("ui-dialog-dragging"); self._trigger('dragStart', event, filteredUi(ui)); }, drag: function(event, ui) { self._trigger('drag', event, filteredUi(ui)); }, stop: function(event, ui) { options.position = [ui.position.left - doc.scrollLeft(), ui.position.top - doc.scrollTop()]; $(this).removeClass("ui-dialog-dragging").height(heightBeforeDrag); self._trigger('dragStop', event, filteredUi(ui)); $.ui.dialog.overlay.resize(); } }); }, _makeResizable: function(handles) { handles = (handles === undefined ? this.options.resizable : handles); var self = this, options = self.options, // .ui-resizable has position: relative defined in the stylesheet // but dialogs have to use absolute or fixed positioning position = self.uiDialog.css('position'), resizeHandles = (typeof handles === 'string' ? handles : 'n,e,s,w,se,sw,ne,nw' ); function filteredUi(ui) { return { originalPosition: ui.originalPosition, originalSize: ui.originalSize, position: ui.position, size: ui.size }; } self.uiDialog.resizable({ cancel: '.ui-dialog-content', containment: 'document', alsoResize: self.element, maxWidth: options.maxWidth, maxHeight: options.maxHeight, minWidth: options.minWidth, minHeight: self._minHeight(), handles: resizeHandles, start: function(event, ui) { $(this).addClass("ui-dialog-resizing"); self._trigger('resizeStart', event, filteredUi(ui)); }, resize: function(event, ui){ self._trigger('resize', event, filteredUi(ui)); }, stop: function(event, ui) { $(this).removeClass("ui-dialog-resizing"); options.height = $(this).height(); options.width = $(this).width(); self._trigger('resizeStop', event, filteredUi(ui)); $.ui.dialog.overlay.resize(); } }) .css('position', position) .find('.ui-resizable-se').addClass('ui-icon ui-icon-grip-diagonal-se'); }, _minHeight: function() { var options = this.options; if (options.height === 'auto') { return options.minHeight; } else { return Math.min(options.minHeight, options.height); } }, _position: function(position) { var myAt = [], offset = [0, 0], isVisible; if (position) { // deep extending converts arrays to objects in jQuery <= 1.3.2 :-( // if (typeof position == 'string' || $.isArray(position)) { // myAt = $.isArray(position) ? position : position.split(' '); if (typeof position === 'string' || (typeof position === 'object' && '0' in position)) { myAt = position.split ? position.split(' ') : [position[0], position[1]]; if (myAt.length === 1) { myAt[1] = myAt[0]; } $.each(['left', 'top'], function(i, offsetPosition) { if (+myAt[i] === myAt[i]) { offset[i] = myAt[i]; myAt[i] = offsetPosition; } }); position = { my: myAt.join(" "), at: myAt.join(" "), offset: offset.join(" ") }; } position = $.extend({}, $.ui.dialog.prototype.options.position, position); } else { position = $.ui.dialog.prototype.options.position; } // need to show the dialog to get the actual offset in the position plugin isVisible = this.uiDialog.is(':visible'); if (!isVisible) { this.uiDialog.show(); } this.uiDialog // workaround for jQuery bug #5781 http://dev.jquery.com/ticket/5781 //.css({ top: 0, left: 0 }) .position($.extend({ of: window }, position)); if (!isVisible) { this.uiDialog.hide(); } }, _setOptions: function( options ) { var self = this, resizableOptions = {}, resize = false; $.each( options, function( key, value ) { self._setOption( key, value ); if ( key in sizeRelatedOptions ) { resize = true; } if ( key in resizableRelatedOptions ) { resizableOptions[ key ] = value; } }); if ( resize ) { this._size(); } if ( this.uiDialog.is( ":data(resizable)" ) ) { this.uiDialog.resizable( "option", resizableOptions ); } }, _setOption: function(key, value){ var self = this, uiDialog = self.uiDialog; switch (key) { //handling of deprecated beforeclose (vs beforeClose) option //Ticket #4669 http://dev.jqueryui.com/ticket/4669 //TODO: remove in 1.9pre case "beforeclose": key = "beforeClose"; break; case "buttons": self._createButtons(value); break; case "closeText": // ensure that we always pass a string self.uiDialogTitlebarCloseText.text("" + value); break; case "dialogClass": uiDialog .removeClass(self.options.dialogClass) .addClass(uiDialogClasses + value); break; case "disabled": if (value) { uiDialog.addClass('ui-dialog-disabled'); } else { uiDialog.removeClass('ui-dialog-disabled'); } break; case "draggable": var isDraggable = uiDialog.is( ":data(draggable)" ); if ( isDraggable && !value ) { uiDialog.draggable( "destroy" ); } if ( !isDraggable && value ) { self._makeDraggable(); } break; case "position": self._position(value); break; case "resizable": // currently resizable, becoming non-resizable var isResizable = uiDialog.is( ":data(resizable)" ); if (isResizable && !value) { uiDialog.resizable('destroy'); } // currently resizable, changing handles if (isResizable && typeof value === 'string') { uiDialog.resizable('option', 'handles', value); } // currently non-resizable, becoming resizable if (!isResizable && value !== false) { self._makeResizable(value); } break; case "title": // convert whatever was passed in o a string, for html() to not throw up $(".ui-dialog-title", self.uiDialogTitlebar).html("" + (value || '&#160;')); break; } $.Widget.prototype._setOption.apply(self, arguments); }, _size: function() { /* If the user has resized the dialog, the .ui-dialog and .ui-dialog-content * divs will both have width and height set, so we need to reset them */ var options = this.options, nonContentHeight, minContentHeight, isVisible = this.uiDialog.is( ":visible" ); // reset content sizing this.element.show().css({ width: 'auto', minHeight: 0, height: 0 }); if (options.minWidth > options.width) { options.width = options.minWidth; } // reset wrapper sizing // determine the height of all the non-content elements nonContentHeight = this.uiDialog.css({ height: 'auto', width: options.width }) .height(); minContentHeight = Math.max( 0, options.minHeight - nonContentHeight ); if ( options.height === "auto" ) { // only needed for IE6 support if ( $.support.minHeight ) { this.element.css({ minHeight: minContentHeight, height: "auto" }); } else { this.uiDialog.show(); var autoHeight = this.element.css( "height", "auto" ).height(); if ( !isVisible ) { this.uiDialog.hide(); } this.element.height( Math.max( autoHeight, minContentHeight ) ); } } else { this.element.height( Math.max( options.height - nonContentHeight, 0 ) ); } if (this.uiDialog.is(':data(resizable)')) { this.uiDialog.resizable('option', 'minHeight', this._minHeight()); } } }); $.extend($.ui.dialog, { version: "1.8.16", uuid: 0, maxZ: 0, getTitleId: function($el) { var id = $el.attr('id'); if (!id) { this.uuid += 1; id = this.uuid; } return 'ui-dialog-title-' + id; }, overlay: function(dialog) { this.$el = $.ui.dialog.overlay.create(dialog); } }); $.extend($.ui.dialog.overlay, { instances: [], // reuse old instances due to IE memory leak with alpha transparency (see #5185) oldInstances: [], maxZ: 0, events: $.map('focus,mousedown,mouseup,keydown,keypress,click'.split(','), function(event) { return event + '.dialog-overlay'; }).join(' '), create: function(dialog) { if (this.instances.length === 0) { // prevent use of anchors and inputs // we use a setTimeout in case the overlay is created from an // event that we're going to be cancelling (see #2804) setTimeout(function() { // handle $(el).dialog().dialog('close') (see #4065) if ($.ui.dialog.overlay.instances.length) { $(document).bind($.ui.dialog.overlay.events, function(event) { // stop events if the z-index of the target is < the z-index of the overlay // we cannot return true when we don't want to cancel the event (#3523) if ($(event.target).zIndex() < $.ui.dialog.overlay.maxZ) { return false; } }); } }, 1); // allow closing by pressing the escape key $(document).bind('keydown.dialog-overlay', function(event) { if (dialog.options.closeOnEscape && !event.isDefaultPrevented() && event.keyCode && event.keyCode === $.ui.keyCode.ESCAPE) { dialog.close(event); event.preventDefault(); } }); // handle window resize $(window).bind('resize.dialog-overlay', $.ui.dialog.overlay.resize); } var $el = (this.oldInstances.pop() || $('<div></div>').addClass('ui-widget-overlay')) .appendTo(document.body) .css({ width: this.width(), height: this.height() }); if ($.fn.bgiframe) { $el.bgiframe(); } this.instances.push($el); return $el; }, destroy: function($el) { var indexOf = $.inArray($el, this.instances); if (indexOf != -1){ this.oldInstances.push(this.instances.splice(indexOf, 1)[0]); } if (this.instances.length === 0) { $([document, window]).unbind('.dialog-overlay'); } $el.remove(); // adjust the maxZ to allow other modal dialogs to continue to work (see #4309) var maxZ = 0; $.each(this.instances, function() { maxZ = Math.max(maxZ, this.css('z-index')); }); this.maxZ = maxZ; }, height: function() { return $(document).height() + 'px'; }, width: function() { return $(document).width() + 'px'; }, resize: function() { /* If the dialog is draggable and the user drags it past the * right edge of the window, the document becomes wider so we * need to stretch the overlay. If the user then drags the * dialog back to the left, the document will become narrower, * so we need to shrink the overlay to the appropriate size. * This is handled by shrinking the overlay before setting it * to the full document size. */ var $overlays = $([]); $.each($.ui.dialog.overlay.instances, function() { $overlays = $overlays.add(this); }); $overlays.css({ width: 0, height: 0 }).css({ width: $.ui.dialog.overlay.width(), height: $.ui.dialog.overlay.height() }); } }); $.extend($.ui.dialog.overlay.prototype, { destroy: function() { $.ui.dialog.overlay.destroy(this.$el); } }); }(jQuery));
ilteredUi(
identifier_name
jquery.ui.dialog.minmax.js
/* * jQuery UI Dialog 1.8.16 * w/ Minimize & Maximize Support * by Elijah Horton (fieryprophet@yahoo.com) * * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about) * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license * * http://docs.jquery.com/UI/Dialog * * Depends: * jquery.ui.core.js * jquery.ui.widget.js * jquery.ui.button.js * jquery.ui.draggable.js * jquery.ui.mouse.js * jquery.ui.position.js * jquery.ui.resizable.js * * Modified by André Roberge to remove some IE support which is irrelevant for me. */ (function( $, undefined ) { var uiDialogClasses = 'ui-dialog ' + 'ui-widget ' + 'ui-widget-content ' + 'ui-corner-all ', sizeRelatedOptions = { buttons: true, height: true, maxHeight: true, maxWidth: true, minHeight: true, minWidth: true, width: true }, resizableRelatedOptions = { maxHeight: true, maxWidth: true, minHeight: true, minWidth: true }, // support for jQuery 1.3.2 - handle common attrFn methods for dialog attrFn = $.attrFn || { val: true, css: true, html: true, text: true, data: true, width: true, height: true, offset: true, click: true }; $.widget("ui.dialog", { options: { autoOpen: true, buttons: {}, closeOnEscape: true, closeText: 'close', dialogClass: '', draggable: true, hide: null, height: 'auto', maxHeight: false, maxWidth: false, minHeight: 150, minWidth: 300, minimizeText: 'minimize', maximizeText: 'maximize', minimize: true, maximize: true, modal: false, position: { my: 'center', at: 'center', collision: 'fit', // ensure that the titlebar is never outside the document using: function(pos) { var topOffset = $(this).css(pos).offset().top; if (topOffset < 0) { $(this).css('top', pos.top - topOffset); } } }, resizable: true, show: null, stack: true, title: '', width: 300, zIndex: 1000 }, _create: function() { this.originalTitle = this.element.attr('title'); // #5742 - .attr() might return a DOMElement if ( typeof this.originalTitle !== "string" ) { this.originalTitle = ""; } this.options.title = this.options.title || this.originalTitle; var self = this, options = self.options, title = options.title || '&#160;', titleId = $.ui.dialog.getTitleId(self.element), uiDialog = (self.uiDialog = $('<div></div>')) .appendTo(document.body) .hide() .addClass(uiDialogClasses + options.dialogClass) .css({ zIndex: options.zIndex }) // setting tabIndex makes the div focusable // setting outline to 0 prevents a border on focus in Mozilla .attr('tabIndex', -1).css('outline', 0).keydown(function(event) { if (options.closeOnEscape && !event.isDefaultPrevented() && event.keyCode && event.keyCode === $.ui.keyCode.ESCAPE) { self.close(event); event.preventDefault(); } }) .attr({ role: 'dialog', 'aria-labelledby': titleId }) .mousedown(function(event) { self.moveToTop(false, event); }), uiDialogContent = self.element .show() .removeAttr('title') .addClass( 'ui-dialog-content ' + 'ui-widget-content') .appendTo(uiDialog), uiDialogTitlebar = (self.uiDialogTitlebar = $('<div></div>')) .addClass( 'ui-dialog-titlebar ' + 'ui-widget-header ' + 'ui-corner-all ' + 'ui-helper-clearfix' ) .prependTo(uiDialog); if(options.minimize && !options.modal){ //cannot use this option with modal var uiDialogTitlebarMinimize = $('<a href="#"></a>') .addClass( 'ui-dialog-titlebar-minimize ' + 'ui-corner-all' ) .attr('role', 'button') .hover( function() { uiDialogTitlebarMinimize.addClass('ui-state-hover'); }, function() { uiDialogTitlebarMinimize.removeClass('ui-state-hover'); } ) .focus(function() { uiDialogTitlebarMinimize.addClass('ui-state-focus'); }) .blur(function() { uiDialogTitlebarMinimize.removeClass('ui-state-focus'); }) .click(function(event) { self.minimize(event); return false; }) .appendTo(uiDialogTitlebar), uiDialogTitlebarMinimizeText = (self.uiDialogTitlebarMinimizeText = $('<span></span>')) .addClass( 'ui-icon ' + 'ui-icon-minusthick' ) .text(options.minimizeText) .appendTo(uiDialogTitlebarMinimize); } if(options.maximize && !options.modal){ //cannot use this option with modal var uiDialogTitlebarMaximize = $('<a href="#"></a>') .addClass( 'ui-dialog-titlebar-maximize ' + 'ui-corner-all' ) .attr('role', 'button') .hover( function() { uiDialogTitlebarMaximize.addClass('ui-state-hover'); }, function() { uiDialogTitlebarMaximize.removeClass('ui-state-hover'); } ) .focus(function() { uiDialogTitlebarMaximize.addClass('ui-state-focus'); }) .blur(function() { uiDialogTitlebarMaximize.removeClass('ui-state-focus'); }) .click(function(event) { self.maximize(event); return false; }) .appendTo(uiDialogTitlebar), uiDialogTitlebarMaximizeText = (self.uiDialogTitlebarMaximizeText = $('<span></span>')) .addClass( 'ui-icon ' + 'ui-icon-plusthick' ) .text(options.maximizeText) .appendTo(uiDialogTitlebarMaximize); $(uiDialogTitlebar).dblclick(function(event) { self.maximize(event); return false; }); } if(options.close !== false){ var uiDialogTitlebarClose = $('<a href="#"></a>') .addClass( 'ui-dialog-titlebar-close ' + 'ui-corner-all' ) .attr('role', 'button') .hover( function() { uiDialogTitlebarClose.addClass('ui-state-hover'); }, function() { uiDialogTitlebarClose.removeClass('ui-state-hover'); } ) .focus(function() { uiDialogTitlebarClose.addClass('ui-state-focus'); }) .blur(function() { uiDialogTitlebarClose.removeClass('ui-state-focus'); }) .click(function(event) { self.close(event); return false; }) .appendTo(uiDialogTitlebar), uiDialogTitlebarCloseText = (self.uiDialogTitlebarCloseText = $('<span></span>')) .addClass( 'ui-icon ' + 'ui-icon-closethick' ) .text(options.closeText) .appendTo(uiDialogTitlebarClose); } uiDialogTitle = $('<span></span>') .addClass('ui-dialog-title') .attr('id', titleId) .html(title) .prependTo(uiDialogTitlebar); //handling of deprecated beforeclose (vs beforeClose) option //Ticket #4669 http://dev.jqueryui.com/ticket/4669 //TODO: remove in 1.9pre if ($.isFunction(options.beforeclose) && !$.isFunction(options.beforeClose)) { options.beforeClose = options.beforeclose; } uiDialogTitlebar.find("*").add(uiDialogTitlebar).disableSelection(); if (options.draggable && $.fn.draggable) { self._makeDraggable(); } if (options.resizable && $.fn.resizable) { self._makeResizable(); } self._createButtons(options.buttons); self._isOpen = false; self._min = false; if ($.fn.bgiframe) { uiDialog.bgiframe(); } }, _init: function() { if ( this.options.autoOpen ) { this.open(); } }, destroy: function() { var self = this; if (self.overlay) { self.overlay.destroy(); } self.uiDialog.hide(); self.element .unbind('.dialog') .removeData('dialog') .removeClass('ui-dialog-content ui-widget-content') .hide().appendTo('body'); self.uiDialog.remove(); if (self.originalTitle) { self.element.attr('title', self.originalTitle); } return self; }, widget: function() { return this.uiDialog; }, minimize: function(event) { var self = this, ui = self.uiDialog; if(false === self._trigger('beforeMinimize', event)) { return; } if(!ui.data('is-minimized')){ if(self.options.minimize && typeof self.options.minimize !== "boolean" && $(self.options.minimize).length > 0){ self._min = $('<a>' + (ui.find('span.ui-dialog-title').html().replace(/&nbsp;/, '') || 'Untitled Dialog') + '</a>') .attr('title', 'Click to restore dialog').addClass('ui-corner-all ui-button').click(function(event){self.unminimize(event);}); $(self.options.minimize).append(self._min); ui.data('is-minimized', true).hide(); } else { if(ui.is( ":data(resizable)" )) { ui.data('was-resizable', true).resizable('destroy'); } else { ui.data('was-resizable', false) } ui.data('minimized-height', ui.height()); ui.find('.ui-dialog-content').hide(); ui.find('.ui-dialog-titlebar-maximize').hide(); ui.find('.ui-dialog-titlebar-minimize').css('right', '1.8em').removeClass('ui-icon-minusthick').addClass('ui-icon-arrowthickstop-1-s') .find('span').removeClass('ui-icon-minusthick').addClass('ui-icon-arrowthickstop-1-s').click(function(event){self.unminimize(event); return false;});; ui.data('is-minimized', true).height('auto'); } } return self; }, unminimize: function(event) { var self = this, ui = self.uiDialog; if(false === self._trigger('beforeUnminimize', event)) { return; } if(ui.data('is-minimized')){ if(self._min){ self._min.unbind().remove(); self._min = false; ui.data('is-minimized', false).show(); self.moveToTop(); } else { ui.height(ui.data('minimized-height')).data('is-minimized', false).removeData('minimized-height').find('.ui-dialog-content').show(); ui.find('.ui-dialog-titlebar-maximize').show(); ui.find('.ui-dialog-titlebar-minimize').css('right', '3.3em').removeClass('ui-icon-arrowthickstop-1-s').addClass('ui-icon-minusthick') .find('span').removeClass('ui-icon-arrowthickstop-1-s').addClass('ui-icon-minusthick').click(function(event){self.minimize(event); return false;}); if(ui.data('was-resizable') == true) { self._makeResizable(true); } } } return self; }, maximize: function(event) { var self = this, ui = self.uiDialog; if(false === self._trigger('beforeMaximize', event)) { return; } if(!ui.data('is-maximized')){ if(ui.is( ":data(draggable)" )) { ui.data('was-draggable', true).draggable('destroy'); } else { ui.data('was-draggable', false) } if(ui.is( ":data(resizable)" )) { ui.data('was-resizable', true).resizable('destroy'); } else { ui.data('was-resizable', false) } ui.data('maximized-height', ui.height()).data('maximized-width', ui.width()).data('maximized-top', ui.css('top')).data('maximized-left', ui.css('left')) .data('is-maximized', true).height($(window).height()-8).width($(window).width()+9).css({"top":0, "left": 0}).find('.ui-dialog-titlebar-minimize').hide(); ui.find('.ui-dialog-titlebar-maximize').removeClass('ui-icon-plusthick').addClass('ui-icon-arrowthick-1-sw') .find('span').removeClass('ui-icon-plusthick').addClass('ui-icon-arrowthick-1-sw').click(function(event){self.unmaximize(event); return false;}); ui.find('.ui-dialog-titlebar').dblclick(function(event){self.unmaximize(event); return false;}); } return self; }, unmaximize: function(event) { var self = this, ui = self.uiDialog; if(false === self._trigger('beforeUnmaximize', event)) { return; } if(ui.data('is-maximized')){ ui.height(ui.data('maximized-height')).width(ui.data('maximized-width')).css({"top":ui.data('maximized-top'), "left":ui.data('maximized-left')}) .data('is-maximized', false).removeData('maximized-height').removeData('maximized-width').removeData('maximized-top').removeData('maximized-left').find('.ui-dialog-titlebar-minimize').show(); ui.find('.ui-dialog-titlebar-maximize').removeClass('ui-icon-arrowthick-1-sw').addClass('ui-icon-plusthick') .find('span').removeClass('ui-icon-arrowthick-1-sw').addClass('ui-icon-plusthick').click(function(){self.maximize(event); return false;}); ui.find('.ui-dialog-titlebar').dblclick(function(event){self.maximize(event); return false;}); if(ui.data('was-draggable') == true) { self._makeDraggable(true); } if(ui.data('was-resizable') == true) { self._makeResizable(true); } } return self; }, close: function(event) { var self = this, maxZ, thisZ; if (false === self._trigger('beforeClose', event)) { return; } if (self.overlay) { self.overlay.destroy(); } self.uiDialog.unbind('keypress.ui-dialog'); self._isOpen = false; if (self.options.hide) { self.uiDialog.hide(self.options.hide, function() { self._trigger('close', event); }); } else { self.uiDialog.hide(); self._trigger('close', event); } $.ui.dialog.overlay.resize(); // adjust the maxZ to allow other modal dialogs to continue to work (see #4309) if (self.options.modal) { maxZ = 0; $('.ui-dialog').each(function() { if (this !== self.uiDialog[0]) { thisZ = $(this).css('z-index'); if(!isNaN(thisZ)) { maxZ = Math.max(maxZ, thisZ); } } }); $.ui.dialog.maxZ = maxZ; } return self; }, isOpen: function() { return this._isOpen; }, // the force parameter allows us to move modal dialogs to their correct // position on open moveToTop: function(force, event) { var self = this, options = self.options, saveScroll; if ((options.modal && !force) || (!options.stack && !options.modal)) { return self._trigger('focus', event); } if (options.zIndex > $.ui.dialog.maxZ) { $.ui.dialog.maxZ = options.zIndex; } if (self.overlay) { $.ui.dialog.maxZ += 1; self.overlay.$el.css('z-index', $.ui.dialog.overlay.maxZ = $.ui.dialog.maxZ); } //Save and then restore scroll since Opera 9.5+ resets when parent z-Index is changed. // http://ui.jquery.com/bugs/ticket/3193 saveScroll = { scrollTop: self.element.scrollTop(), scrollLeft: self.element.scrollLeft() }; $.ui.dialog.maxZ += 1; self.uiDialog.css('z-index', $.ui.dialog.maxZ); self.element.attr(saveScroll); self._trigger('focus', event); return self; }, open: function() { if (this._isOpen) { return; } var self = this, options = self.options, uiDialog = self.uiDialog; self.overlay = options.modal ? new $.ui.dialog.overlay(self) : null; self._size(); self._position(options.position); uiDialog.show(options.show); self.moveToTop(true); // prevent tabbing out of modal dialogs if (options.modal) { uiDialog.bind('keypress.ui-dialog', function(event) { if (event.keyCode !== $.ui.keyCode.TAB) { return; } var tabbables = $(':tabbable', this), first = tabbables.filter(':first'), last = tabbables.filter(':last'); if (event.target === last[0] && !event.shiftKey) { first.focus(1); return false; } else if (event.target === first[0] && event.shiftKey) { last.focus(1); return false; } }); } // set focus to the first tabbable element in the content area or the first button // if there are no tabbable elements, set focus on the dialog itself $(self.element.find(':tabbable').get().concat( uiDialog.find('.ui-dialog-buttonpane :tabbable').get().concat( uiDialog.get()))).eq(0).focus(); self._isOpen = true; self._trigger('open'); return self; }, _createButtons: function(buttons) { var self = this, hasButtons = false, uiDialogButtonPane = $('<div></div>') .addClass( 'ui-dialog-buttonpane ' + 'ui-widget-content ' + 'ui-helper-clearfix' ), uiButtonSet = $( "<div></div>" ) .addClass( "ui-dialog-buttonset" ) .appendTo( uiDialogButtonPane ); // if we already have a button pane, remove it self.uiDialog.find('.ui-dialog-buttonpane').remove(); if (typeof buttons === 'object' && buttons !== null) { $.each(buttons, function() { return !(hasButtons = true); }); } if (hasButtons) { $.each(buttons, function(name, props) { props = $.isFunction( props ) ? { click: props, text: name } : props; var button = $('<button type="button"></button>') .click(function() { props.click.apply(self.element[0], arguments); }) .appendTo(uiButtonSet); // can't use .attr( props, true ) with jQuery 1.3.2. $.each( props, function( key, value ) { if ( key === "click" ) { return; } if ( key in attrFn ) { button[ key ]( value ); } else { button.attr( key, value ); } }); if ($.fn.button) { button.button(); } }); uiDialogButtonPane.appendTo(self.uiDialog); } }, _makeDraggable: function() { var self = this, options = self.options, doc = $(document), heightBeforeDrag; function filteredUi(ui) { return { position: ui.position, offset: ui.offset }; } self.uiDialog.draggable({ cancel: '.ui-dialog-content, .ui-dialog-titlebar-close', handle: '.ui-dialog-titlebar', containment: 'document', start: function(event, ui) { heightBeforeDrag = options.height === "auto" ? "auto" : $(this).height(); $(this).height($(this).height()).addClass("ui-dialog-dragging"); self._trigger('dragStart', event, filteredUi(ui)); }, drag: function(event, ui) { self._trigger('drag', event, filteredUi(ui)); }, stop: function(event, ui) { options.position = [ui.position.left - doc.scrollLeft(), ui.position.top - doc.scrollTop()]; $(this).removeClass("ui-dialog-dragging").height(heightBeforeDrag); self._trigger('dragStop', event, filteredUi(ui)); $.ui.dialog.overlay.resize(); } }); }, _makeResizable: function(handles) { handles = (handles === undefined ? this.options.resizable : handles); var self = this, options = self.options, // .ui-resizable has position: relative defined in the stylesheet // but dialogs have to use absolute or fixed positioning position = self.uiDialog.css('position'), resizeHandles = (typeof handles === 'string' ? handles : 'n,e,s,w,se,sw,ne,nw' ); function filteredUi(ui) {
self.uiDialog.resizable({ cancel: '.ui-dialog-content', containment: 'document', alsoResize: self.element, maxWidth: options.maxWidth, maxHeight: options.maxHeight, minWidth: options.minWidth, minHeight: self._minHeight(), handles: resizeHandles, start: function(event, ui) { $(this).addClass("ui-dialog-resizing"); self._trigger('resizeStart', event, filteredUi(ui)); }, resize: function(event, ui){ self._trigger('resize', event, filteredUi(ui)); }, stop: function(event, ui) { $(this).removeClass("ui-dialog-resizing"); options.height = $(this).height(); options.width = $(this).width(); self._trigger('resizeStop', event, filteredUi(ui)); $.ui.dialog.overlay.resize(); } }) .css('position', position) .find('.ui-resizable-se').addClass('ui-icon ui-icon-grip-diagonal-se'); }, _minHeight: function() { var options = this.options; if (options.height === 'auto') { return options.minHeight; } else { return Math.min(options.minHeight, options.height); } }, _position: function(position) { var myAt = [], offset = [0, 0], isVisible; if (position) { // deep extending converts arrays to objects in jQuery <= 1.3.2 :-( // if (typeof position == 'string' || $.isArray(position)) { // myAt = $.isArray(position) ? position : position.split(' '); if (typeof position === 'string' || (typeof position === 'object' && '0' in position)) { myAt = position.split ? position.split(' ') : [position[0], position[1]]; if (myAt.length === 1) { myAt[1] = myAt[0]; } $.each(['left', 'top'], function(i, offsetPosition) { if (+myAt[i] === myAt[i]) { offset[i] = myAt[i]; myAt[i] = offsetPosition; } }); position = { my: myAt.join(" "), at: myAt.join(" "), offset: offset.join(" ") }; } position = $.extend({}, $.ui.dialog.prototype.options.position, position); } else { position = $.ui.dialog.prototype.options.position; } // need to show the dialog to get the actual offset in the position plugin isVisible = this.uiDialog.is(':visible'); if (!isVisible) { this.uiDialog.show(); } this.uiDialog // workaround for jQuery bug #5781 http://dev.jquery.com/ticket/5781 //.css({ top: 0, left: 0 }) .position($.extend({ of: window }, position)); if (!isVisible) { this.uiDialog.hide(); } }, _setOptions: function( options ) { var self = this, resizableOptions = {}, resize = false; $.each( options, function( key, value ) { self._setOption( key, value ); if ( key in sizeRelatedOptions ) { resize = true; } if ( key in resizableRelatedOptions ) { resizableOptions[ key ] = value; } }); if ( resize ) { this._size(); } if ( this.uiDialog.is( ":data(resizable)" ) ) { this.uiDialog.resizable( "option", resizableOptions ); } }, _setOption: function(key, value){ var self = this, uiDialog = self.uiDialog; switch (key) { //handling of deprecated beforeclose (vs beforeClose) option //Ticket #4669 http://dev.jqueryui.com/ticket/4669 //TODO: remove in 1.9pre case "beforeclose": key = "beforeClose"; break; case "buttons": self._createButtons(value); break; case "closeText": // ensure that we always pass a string self.uiDialogTitlebarCloseText.text("" + value); break; case "dialogClass": uiDialog .removeClass(self.options.dialogClass) .addClass(uiDialogClasses + value); break; case "disabled": if (value) { uiDialog.addClass('ui-dialog-disabled'); } else { uiDialog.removeClass('ui-dialog-disabled'); } break; case "draggable": var isDraggable = uiDialog.is( ":data(draggable)" ); if ( isDraggable && !value ) { uiDialog.draggable( "destroy" ); } if ( !isDraggable && value ) { self._makeDraggable(); } break; case "position": self._position(value); break; case "resizable": // currently resizable, becoming non-resizable var isResizable = uiDialog.is( ":data(resizable)" ); if (isResizable && !value) { uiDialog.resizable('destroy'); } // currently resizable, changing handles if (isResizable && typeof value === 'string') { uiDialog.resizable('option', 'handles', value); } // currently non-resizable, becoming resizable if (!isResizable && value !== false) { self._makeResizable(value); } break; case "title": // convert whatever was passed in o a string, for html() to not throw up $(".ui-dialog-title", self.uiDialogTitlebar).html("" + (value || '&#160;')); break; } $.Widget.prototype._setOption.apply(self, arguments); }, _size: function() { /* If the user has resized the dialog, the .ui-dialog and .ui-dialog-content * divs will both have width and height set, so we need to reset them */ var options = this.options, nonContentHeight, minContentHeight, isVisible = this.uiDialog.is( ":visible" ); // reset content sizing this.element.show().css({ width: 'auto', minHeight: 0, height: 0 }); if (options.minWidth > options.width) { options.width = options.minWidth; } // reset wrapper sizing // determine the height of all the non-content elements nonContentHeight = this.uiDialog.css({ height: 'auto', width: options.width }) .height(); minContentHeight = Math.max( 0, options.minHeight - nonContentHeight ); if ( options.height === "auto" ) { // only needed for IE6 support if ( $.support.minHeight ) { this.element.css({ minHeight: minContentHeight, height: "auto" }); } else { this.uiDialog.show(); var autoHeight = this.element.css( "height", "auto" ).height(); if ( !isVisible ) { this.uiDialog.hide(); } this.element.height( Math.max( autoHeight, minContentHeight ) ); } } else { this.element.height( Math.max( options.height - nonContentHeight, 0 ) ); } if (this.uiDialog.is(':data(resizable)')) { this.uiDialog.resizable('option', 'minHeight', this._minHeight()); } } }); $.extend($.ui.dialog, { version: "1.8.16", uuid: 0, maxZ: 0, getTitleId: function($el) { var id = $el.attr('id'); if (!id) { this.uuid += 1; id = this.uuid; } return 'ui-dialog-title-' + id; }, overlay: function(dialog) { this.$el = $.ui.dialog.overlay.create(dialog); } }); $.extend($.ui.dialog.overlay, { instances: [], // reuse old instances due to IE memory leak with alpha transparency (see #5185) oldInstances: [], maxZ: 0, events: $.map('focus,mousedown,mouseup,keydown,keypress,click'.split(','), function(event) { return event + '.dialog-overlay'; }).join(' '), create: function(dialog) { if (this.instances.length === 0) { // prevent use of anchors and inputs // we use a setTimeout in case the overlay is created from an // event that we're going to be cancelling (see #2804) setTimeout(function() { // handle $(el).dialog().dialog('close') (see #4065) if ($.ui.dialog.overlay.instances.length) { $(document).bind($.ui.dialog.overlay.events, function(event) { // stop events if the z-index of the target is < the z-index of the overlay // we cannot return true when we don't want to cancel the event (#3523) if ($(event.target).zIndex() < $.ui.dialog.overlay.maxZ) { return false; } }); } }, 1); // allow closing by pressing the escape key $(document).bind('keydown.dialog-overlay', function(event) { if (dialog.options.closeOnEscape && !event.isDefaultPrevented() && event.keyCode && event.keyCode === $.ui.keyCode.ESCAPE) { dialog.close(event); event.preventDefault(); } }); // handle window resize $(window).bind('resize.dialog-overlay', $.ui.dialog.overlay.resize); } var $el = (this.oldInstances.pop() || $('<div></div>').addClass('ui-widget-overlay')) .appendTo(document.body) .css({ width: this.width(), height: this.height() }); if ($.fn.bgiframe) { $el.bgiframe(); } this.instances.push($el); return $el; }, destroy: function($el) { var indexOf = $.inArray($el, this.instances); if (indexOf != -1){ this.oldInstances.push(this.instances.splice(indexOf, 1)[0]); } if (this.instances.length === 0) { $([document, window]).unbind('.dialog-overlay'); } $el.remove(); // adjust the maxZ to allow other modal dialogs to continue to work (see #4309) var maxZ = 0; $.each(this.instances, function() { maxZ = Math.max(maxZ, this.css('z-index')); }); this.maxZ = maxZ; }, height: function() { return $(document).height() + 'px'; }, width: function() { return $(document).width() + 'px'; }, resize: function() { /* If the dialog is draggable and the user drags it past the * right edge of the window, the document becomes wider so we * need to stretch the overlay. If the user then drags the * dialog back to the left, the document will become narrower, * so we need to shrink the overlay to the appropriate size. * This is handled by shrinking the overlay before setting it * to the full document size. */ var $overlays = $([]); $.each($.ui.dialog.overlay.instances, function() { $overlays = $overlays.add(this); }); $overlays.css({ width: 0, height: 0 }).css({ width: $.ui.dialog.overlay.width(), height: $.ui.dialog.overlay.height() }); } }); $.extend($.ui.dialog.overlay.prototype, { destroy: function() { $.ui.dialog.overlay.destroy(this.$el); } }); }(jQuery));
return { originalPosition: ui.originalPosition, originalSize: ui.originalSize, position: ui.position, size: ui.size }; }
identifier_body
jquery.ui.dialog.minmax.js
/* * jQuery UI Dialog 1.8.16 * w/ Minimize & Maximize Support * by Elijah Horton (fieryprophet@yahoo.com) * * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about) * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license * * http://docs.jquery.com/UI/Dialog * * Depends: * jquery.ui.core.js * jquery.ui.widget.js * jquery.ui.button.js * jquery.ui.draggable.js * jquery.ui.mouse.js * jquery.ui.position.js * jquery.ui.resizable.js * * Modified by André Roberge to remove some IE support which is irrelevant for me. */ (function( $, undefined ) { var uiDialogClasses = 'ui-dialog ' + 'ui-widget ' + 'ui-widget-content ' + 'ui-corner-all ', sizeRelatedOptions = { buttons: true, height: true, maxHeight: true, maxWidth: true, minHeight: true, minWidth: true, width: true }, resizableRelatedOptions = { maxHeight: true, maxWidth: true, minHeight: true, minWidth: true }, // support for jQuery 1.3.2 - handle common attrFn methods for dialog attrFn = $.attrFn || { val: true, css: true, html: true, text: true, data: true, width: true, height: true, offset: true, click: true }; $.widget("ui.dialog", { options: { autoOpen: true, buttons: {}, closeOnEscape: true, closeText: 'close', dialogClass: '', draggable: true, hide: null, height: 'auto', maxHeight: false, maxWidth: false, minHeight: 150, minWidth: 300, minimizeText: 'minimize', maximizeText: 'maximize', minimize: true, maximize: true, modal: false, position: { my: 'center', at: 'center', collision: 'fit', // ensure that the titlebar is never outside the document using: function(pos) { var topOffset = $(this).css(pos).offset().top; if (topOffset < 0) { $(this).css('top', pos.top - topOffset); } } }, resizable: true, show: null, stack: true, title: '', width: 300, zIndex: 1000 }, _create: function() { this.originalTitle = this.element.attr('title'); // #5742 - .attr() might return a DOMElement if ( typeof this.originalTitle !== "string" ) { this.originalTitle = ""; } this.options.title = this.options.title || this.originalTitle; var self = this, options = self.options, title = options.title || '&#160;', titleId = $.ui.dialog.getTitleId(self.element), uiDialog = (self.uiDialog = $('<div></div>')) .appendTo(document.body) .hide() .addClass(uiDialogClasses + options.dialogClass) .css({ zIndex: options.zIndex }) // setting tabIndex makes the div focusable // setting outline to 0 prevents a border on focus in Mozilla .attr('tabIndex', -1).css('outline', 0).keydown(function(event) { if (options.closeOnEscape && !event.isDefaultPrevented() && event.keyCode && event.keyCode === $.ui.keyCode.ESCAPE) { self.close(event); event.preventDefault(); } }) .attr({ role: 'dialog', 'aria-labelledby': titleId }) .mousedown(function(event) { self.moveToTop(false, event); }), uiDialogContent = self.element .show() .removeAttr('title') .addClass( 'ui-dialog-content ' + 'ui-widget-content') .appendTo(uiDialog), uiDialogTitlebar = (self.uiDialogTitlebar = $('<div></div>')) .addClass( 'ui-dialog-titlebar ' + 'ui-widget-header ' + 'ui-corner-all ' + 'ui-helper-clearfix' ) .prependTo(uiDialog); if(options.minimize && !options.modal){ //cannot use this option with modal var uiDialogTitlebarMinimize = $('<a href="#"></a>') .addClass( 'ui-dialog-titlebar-minimize ' + 'ui-corner-all' ) .attr('role', 'button') .hover( function() { uiDialogTitlebarMinimize.addClass('ui-state-hover'); }, function() { uiDialogTitlebarMinimize.removeClass('ui-state-hover'); } ) .focus(function() { uiDialogTitlebarMinimize.addClass('ui-state-focus'); }) .blur(function() { uiDialogTitlebarMinimize.removeClass('ui-state-focus'); }) .click(function(event) { self.minimize(event); return false; }) .appendTo(uiDialogTitlebar), uiDialogTitlebarMinimizeText = (self.uiDialogTitlebarMinimizeText = $('<span></span>')) .addClass( 'ui-icon ' + 'ui-icon-minusthick' ) .text(options.minimizeText) .appendTo(uiDialogTitlebarMinimize); } if(options.maximize && !options.modal){ //cannot use this option with modal var uiDialogTitlebarMaximize = $('<a href="#"></a>') .addClass( 'ui-dialog-titlebar-maximize ' + 'ui-corner-all' ) .attr('role', 'button') .hover( function() { uiDialogTitlebarMaximize.addClass('ui-state-hover'); }, function() { uiDialogTitlebarMaximize.removeClass('ui-state-hover'); } ) .focus(function() { uiDialogTitlebarMaximize.addClass('ui-state-focus'); }) .blur(function() { uiDialogTitlebarMaximize.removeClass('ui-state-focus'); }) .click(function(event) { self.maximize(event); return false; }) .appendTo(uiDialogTitlebar), uiDialogTitlebarMaximizeText = (self.uiDialogTitlebarMaximizeText = $('<span></span>')) .addClass( 'ui-icon ' + 'ui-icon-plusthick' ) .text(options.maximizeText) .appendTo(uiDialogTitlebarMaximize); $(uiDialogTitlebar).dblclick(function(event) { self.maximize(event); return false; }); } if(options.close !== false){ var uiDialogTitlebarClose = $('<a href="#"></a>') .addClass( 'ui-dialog-titlebar-close ' + 'ui-corner-all' ) .attr('role', 'button') .hover( function() { uiDialogTitlebarClose.addClass('ui-state-hover'); }, function() { uiDialogTitlebarClose.removeClass('ui-state-hover'); } ) .focus(function() { uiDialogTitlebarClose.addClass('ui-state-focus'); }) .blur(function() { uiDialogTitlebarClose.removeClass('ui-state-focus'); }) .click(function(event) { self.close(event); return false; }) .appendTo(uiDialogTitlebar), uiDialogTitlebarCloseText = (self.uiDialogTitlebarCloseText = $('<span></span>')) .addClass( 'ui-icon ' + 'ui-icon-closethick' ) .text(options.closeText) .appendTo(uiDialogTitlebarClose); } uiDialogTitle = $('<span></span>') .addClass('ui-dialog-title') .attr('id', titleId) .html(title) .prependTo(uiDialogTitlebar); //handling of deprecated beforeclose (vs beforeClose) option //Ticket #4669 http://dev.jqueryui.com/ticket/4669 //TODO: remove in 1.9pre if ($.isFunction(options.beforeclose) && !$.isFunction(options.beforeClose)) { options.beforeClose = options.beforeclose; } uiDialogTitlebar.find("*").add(uiDialogTitlebar).disableSelection(); if (options.draggable && $.fn.draggable) { self._makeDraggable(); } if (options.resizable && $.fn.resizable) { self._makeResizable(); } self._createButtons(options.buttons); self._isOpen = false; self._min = false; if ($.fn.bgiframe) { uiDialog.bgiframe(); } }, _init: function() { if ( this.options.autoOpen ) { this.open(); } }, destroy: function() { var self = this; if (self.overlay) { self.overlay.destroy(); } self.uiDialog.hide(); self.element .unbind('.dialog') .removeData('dialog') .removeClass('ui-dialog-content ui-widget-content') .hide().appendTo('body'); self.uiDialog.remove(); if (self.originalTitle) { self.element.attr('title', self.originalTitle); } return self; }, widget: function() { return this.uiDialog; }, minimize: function(event) { var self = this, ui = self.uiDialog; if(false === self._trigger('beforeMinimize', event)) { return; } if(!ui.data('is-minimized')){ if(self.options.minimize && typeof self.options.minimize !== "boolean" && $(self.options.minimize).length > 0){ self._min = $('<a>' + (ui.find('span.ui-dialog-title').html().replace(/&nbsp;/, '') || 'Untitled Dialog') + '</a>') .attr('title', 'Click to restore dialog').addClass('ui-corner-all ui-button').click(function(event){self.unminimize(event);}); $(self.options.minimize).append(self._min); ui.data('is-minimized', true).hide(); } else { if(ui.is( ":data(resizable)" )) { ui.data('was-resizable', true).resizable('destroy'); } else { ui.data('was-resizable', false) } ui.data('minimized-height', ui.height()); ui.find('.ui-dialog-content').hide(); ui.find('.ui-dialog-titlebar-maximize').hide(); ui.find('.ui-dialog-titlebar-minimize').css('right', '1.8em').removeClass('ui-icon-minusthick').addClass('ui-icon-arrowthickstop-1-s') .find('span').removeClass('ui-icon-minusthick').addClass('ui-icon-arrowthickstop-1-s').click(function(event){self.unminimize(event); return false;});; ui.data('is-minimized', true).height('auto'); } } return self; }, unminimize: function(event) { var self = this, ui = self.uiDialog; if(false === self._trigger('beforeUnminimize', event)) { return; } if(ui.data('is-minimized')){ if(self._min){ self._min.unbind().remove(); self._min = false; ui.data('is-minimized', false).show(); self.moveToTop(); } else { ui.height(ui.data('minimized-height')).data('is-minimized', false).removeData('minimized-height').find('.ui-dialog-content').show(); ui.find('.ui-dialog-titlebar-maximize').show(); ui.find('.ui-dialog-titlebar-minimize').css('right', '3.3em').removeClass('ui-icon-arrowthickstop-1-s').addClass('ui-icon-minusthick') .find('span').removeClass('ui-icon-arrowthickstop-1-s').addClass('ui-icon-minusthick').click(function(event){self.minimize(event); return false;}); if(ui.data('was-resizable') == true) { self._makeResizable(true); } } } return self; }, maximize: function(event) { var self = this, ui = self.uiDialog; if(false === self._trigger('beforeMaximize', event)) { return; } if(!ui.data('is-maximized')){ if(ui.is( ":data(draggable)" )) { ui.data('was-draggable', true).draggable('destroy'); } else { ui.data('was-draggable', false) } if(ui.is( ":data(resizable)" )) { ui.data('was-resizable', true).resizable('destroy'); } else { ui.data('was-resizable', false) } ui.data('maximized-height', ui.height()).data('maximized-width', ui.width()).data('maximized-top', ui.css('top')).data('maximized-left', ui.css('left')) .data('is-maximized', true).height($(window).height()-8).width($(window).width()+9).css({"top":0, "left": 0}).find('.ui-dialog-titlebar-minimize').hide(); ui.find('.ui-dialog-titlebar-maximize').removeClass('ui-icon-plusthick').addClass('ui-icon-arrowthick-1-sw') .find('span').removeClass('ui-icon-plusthick').addClass('ui-icon-arrowthick-1-sw').click(function(event){self.unmaximize(event); return false;}); ui.find('.ui-dialog-titlebar').dblclick(function(event){self.unmaximize(event); return false;}); } return self; }, unmaximize: function(event) { var self = this, ui = self.uiDialog; if(false === self._trigger('beforeUnmaximize', event)) { return; } if(ui.data('is-maximized')){ ui.height(ui.data('maximized-height')).width(ui.data('maximized-width')).css({"top":ui.data('maximized-top'), "left":ui.data('maximized-left')}) .data('is-maximized', false).removeData('maximized-height').removeData('maximized-width').removeData('maximized-top').removeData('maximized-left').find('.ui-dialog-titlebar-minimize').show(); ui.find('.ui-dialog-titlebar-maximize').removeClass('ui-icon-arrowthick-1-sw').addClass('ui-icon-plusthick') .find('span').removeClass('ui-icon-arrowthick-1-sw').addClass('ui-icon-plusthick').click(function(){self.maximize(event); return false;}); ui.find('.ui-dialog-titlebar').dblclick(function(event){self.maximize(event); return false;}); if(ui.data('was-draggable') == true) { self._makeDraggable(true); } if(ui.data('was-resizable') == true) { self._makeResizable(true); } } return self; }, close: function(event) { var self = this, maxZ, thisZ; if (false === self._trigger('beforeClose', event)) { return; } if (self.overlay) { self.overlay.destroy(); } self.uiDialog.unbind('keypress.ui-dialog'); self._isOpen = false; if (self.options.hide) { self.uiDialog.hide(self.options.hide, function() { self._trigger('close', event); }); } else { self.uiDialog.hide(); self._trigger('close', event); } $.ui.dialog.overlay.resize(); // adjust the maxZ to allow other modal dialogs to continue to work (see #4309) if (self.options.modal) { maxZ = 0; $('.ui-dialog').each(function() { if (this !== self.uiDialog[0]) { thisZ = $(this).css('z-index'); if(!isNaN(thisZ)) { maxZ = Math.max(maxZ, thisZ); } } }); $.ui.dialog.maxZ = maxZ; } return self; }, isOpen: function() { return this._isOpen; }, // the force parameter allows us to move modal dialogs to their correct // position on open moveToTop: function(force, event) { var self = this, options = self.options, saveScroll; if ((options.modal && !force) || (!options.stack && !options.modal)) { return self._trigger('focus', event); } if (options.zIndex > $.ui.dialog.maxZ) { $.ui.dialog.maxZ = options.zIndex; } if (self.overlay) { $.ui.dialog.maxZ += 1; self.overlay.$el.css('z-index', $.ui.dialog.overlay.maxZ = $.ui.dialog.maxZ); } //Save and then restore scroll since Opera 9.5+ resets when parent z-Index is changed. // http://ui.jquery.com/bugs/ticket/3193 saveScroll = { scrollTop: self.element.scrollTop(), scrollLeft: self.element.scrollLeft() }; $.ui.dialog.maxZ += 1; self.uiDialog.css('z-index', $.ui.dialog.maxZ); self.element.attr(saveScroll); self._trigger('focus', event); return self; }, open: function() { if (this._isOpen) { return; } var self = this, options = self.options, uiDialog = self.uiDialog; self.overlay = options.modal ? new $.ui.dialog.overlay(self) : null; self._size(); self._position(options.position); uiDialog.show(options.show); self.moveToTop(true); // prevent tabbing out of modal dialogs if (options.modal) { uiDialog.bind('keypress.ui-dialog', function(event) { if (event.keyCode !== $.ui.keyCode.TAB) { return; } var tabbables = $(':tabbable', this), first = tabbables.filter(':first'), last = tabbables.filter(':last'); if (event.target === last[0] && !event.shiftKey) { first.focus(1); return false; } else if (event.target === first[0] && event.shiftKey) { last.focus(1); return false; } }); } // set focus to the first tabbable element in the content area or the first button // if there are no tabbable elements, set focus on the dialog itself $(self.element.find(':tabbable').get().concat( uiDialog.find('.ui-dialog-buttonpane :tabbable').get().concat( uiDialog.get()))).eq(0).focus(); self._isOpen = true; self._trigger('open'); return self; }, _createButtons: function(buttons) { var self = this, hasButtons = false, uiDialogButtonPane = $('<div></div>') .addClass( 'ui-dialog-buttonpane ' + 'ui-widget-content ' + 'ui-helper-clearfix' ), uiButtonSet = $( "<div></div>" ) .addClass( "ui-dialog-buttonset" ) .appendTo( uiDialogButtonPane ); // if we already have a button pane, remove it self.uiDialog.find('.ui-dialog-buttonpane').remove(); if (typeof buttons === 'object' && buttons !== null) { $.each(buttons, function() { return !(hasButtons = true); }); } if (hasButtons) { $.each(buttons, function(name, props) { props = $.isFunction( props ) ? { click: props, text: name } : props; var button = $('<button type="button"></button>') .click(function() { props.click.apply(self.element[0], arguments); }) .appendTo(uiButtonSet); // can't use .attr( props, true ) with jQuery 1.3.2. $.each( props, function( key, value ) { if ( key === "click" ) { return; } if ( key in attrFn ) { button[ key ]( value ); } else { button.attr( key, value ); } }); if ($.fn.button) { button.button(); } }); uiDialogButtonPane.appendTo(self.uiDialog); } }, _makeDraggable: function() { var self = this, options = self.options, doc = $(document), heightBeforeDrag; function filteredUi(ui) { return { position: ui.position, offset: ui.offset }; } self.uiDialog.draggable({ cancel: '.ui-dialog-content, .ui-dialog-titlebar-close', handle: '.ui-dialog-titlebar', containment: 'document', start: function(event, ui) { heightBeforeDrag = options.height === "auto" ? "auto" : $(this).height(); $(this).height($(this).height()).addClass("ui-dialog-dragging"); self._trigger('dragStart', event, filteredUi(ui)); }, drag: function(event, ui) { self._trigger('drag', event, filteredUi(ui)); }, stop: function(event, ui) { options.position = [ui.position.left - doc.scrollLeft(), ui.position.top - doc.scrollTop()]; $(this).removeClass("ui-dialog-dragging").height(heightBeforeDrag); self._trigger('dragStop', event, filteredUi(ui)); $.ui.dialog.overlay.resize(); } }); }, _makeResizable: function(handles) { handles = (handles === undefined ? this.options.resizable : handles); var self = this, options = self.options, // .ui-resizable has position: relative defined in the stylesheet // but dialogs have to use absolute or fixed positioning position = self.uiDialog.css('position'), resizeHandles = (typeof handles === 'string' ? handles : 'n,e,s,w,se,sw,ne,nw' ); function filteredUi(ui) { return { originalPosition: ui.originalPosition, originalSize: ui.originalSize, position: ui.position, size: ui.size }; } self.uiDialog.resizable({ cancel: '.ui-dialog-content', containment: 'document', alsoResize: self.element, maxWidth: options.maxWidth, maxHeight: options.maxHeight, minWidth: options.minWidth, minHeight: self._minHeight(), handles: resizeHandles, start: function(event, ui) { $(this).addClass("ui-dialog-resizing"); self._trigger('resizeStart', event, filteredUi(ui)); }, resize: function(event, ui){ self._trigger('resize', event, filteredUi(ui)); }, stop: function(event, ui) { $(this).removeClass("ui-dialog-resizing"); options.height = $(this).height(); options.width = $(this).width(); self._trigger('resizeStop', event, filteredUi(ui)); $.ui.dialog.overlay.resize(); } }) .css('position', position) .find('.ui-resizable-se').addClass('ui-icon ui-icon-grip-diagonal-se'); }, _minHeight: function() { var options = this.options; if (options.height === 'auto') { return options.minHeight; } else { return Math.min(options.minHeight, options.height); } }, _position: function(position) { var myAt = [], offset = [0, 0], isVisible; if (position) { // deep extending converts arrays to objects in jQuery <= 1.3.2 :-( // if (typeof position == 'string' || $.isArray(position)) { // myAt = $.isArray(position) ? position : position.split(' '); if (typeof position === 'string' || (typeof position === 'object' && '0' in position)) { myAt = position.split ? position.split(' ') : [position[0], position[1]]; if (myAt.length === 1) { myAt[1] = myAt[0]; } $.each(['left', 'top'], function(i, offsetPosition) { if (+myAt[i] === myAt[i]) { offset[i] = myAt[i]; myAt[i] = offsetPosition; } }); position = { my: myAt.join(" "), at: myAt.join(" "), offset: offset.join(" ") }; } position = $.extend({}, $.ui.dialog.prototype.options.position, position); } else { position = $.ui.dialog.prototype.options.position; } // need to show the dialog to get the actual offset in the position plugin isVisible = this.uiDialog.is(':visible'); if (!isVisible) { this.uiDialog.show(); } this.uiDialog // workaround for jQuery bug #5781 http://dev.jquery.com/ticket/5781 //.css({ top: 0, left: 0 }) .position($.extend({ of: window }, position)); if (!isVisible) { this.uiDialog.hide(); } }, _setOptions: function( options ) { var self = this, resizableOptions = {}, resize = false; $.each( options, function( key, value ) { self._setOption( key, value ); if ( key in sizeRelatedOptions ) { resize = true; } if ( key in resizableRelatedOptions ) { resizableOptions[ key ] = value; } }); if ( resize ) { this._size(); } if ( this.uiDialog.is( ":data(resizable)" ) ) { this.uiDialog.resizable( "option", resizableOptions ); } }, _setOption: function(key, value){ var self = this, uiDialog = self.uiDialog; switch (key) { //handling of deprecated beforeclose (vs beforeClose) option //Ticket #4669 http://dev.jqueryui.com/ticket/4669 //TODO: remove in 1.9pre case "beforeclose": key = "beforeClose"; break; case "buttons": self._createButtons(value); break; case "closeText": // ensure that we always pass a string self.uiDialogTitlebarCloseText.text("" + value); break; case "dialogClass": uiDialog .removeClass(self.options.dialogClass) .addClass(uiDialogClasses + value); break; case "disabled": if (value) { uiDialog.addClass('ui-dialog-disabled'); } else { uiDialog.removeClass('ui-dialog-disabled'); } break; case "draggable": var isDraggable = uiDialog.is( ":data(draggable)" ); if ( isDraggable && !value ) { uiDialog.draggable( "destroy" ); } if ( !isDraggable && value ) { self._makeDraggable(); } break; case "position": self._position(value); break; case "resizable": // currently resizable, becoming non-resizable var isResizable = uiDialog.is( ":data(resizable)" ); if (isResizable && !value) { uiDialog.resizable('destroy'); } // currently resizable, changing handles if (isResizable && typeof value === 'string') { uiDialog.resizable('option', 'handles', value); } // currently non-resizable, becoming resizable if (!isResizable && value !== false) { self._makeResizable(value); } break; case "title": // convert whatever was passed in o a string, for html() to not throw up $(".ui-dialog-title", self.uiDialogTitlebar).html("" + (value || '&#160;')); break; } $.Widget.prototype._setOption.apply(self, arguments); }, _size: function() { /* If the user has resized the dialog, the .ui-dialog and .ui-dialog-content * divs will both have width and height set, so we need to reset them */ var options = this.options, nonContentHeight, minContentHeight, isVisible = this.uiDialog.is( ":visible" ); // reset content sizing this.element.show().css({ width: 'auto', minHeight: 0, height: 0 }); if (options.minWidth > options.width) { options.width = options.minWidth; } // reset wrapper sizing // determine the height of all the non-content elements nonContentHeight = this.uiDialog.css({ height: 'auto', width: options.width }) .height(); minContentHeight = Math.max( 0, options.minHeight - nonContentHeight ); if ( options.height === "auto" ) { // only needed for IE6 support if ( $.support.minHeight ) { this.element.css({ minHeight: minContentHeight, height: "auto" }); } else { this.uiDialog.show(); var autoHeight = this.element.css( "height", "auto" ).height(); if ( !isVisible ) { this.uiDialog.hide(); } this.element.height( Math.max( autoHeight, minContentHeight ) ); } } else { this.element.height( Math.max( options.height - nonContentHeight, 0 ) ); } if (this.uiDialog.is(':data(resizable)')) { this.uiDialog.resizable('option', 'minHeight', this._minHeight()); } } }); $.extend($.ui.dialog, { version: "1.8.16", uuid: 0, maxZ: 0, getTitleId: function($el) { var id = $el.attr('id'); if (!id) { this.uuid += 1; id = this.uuid; } return 'ui-dialog-title-' + id; }, overlay: function(dialog) { this.$el = $.ui.dialog.overlay.create(dialog); } }); $.extend($.ui.dialog.overlay, { instances: [], // reuse old instances due to IE memory leak with alpha transparency (see #5185) oldInstances: [], maxZ: 0, events: $.map('focus,mousedown,mouseup,keydown,keypress,click'.split(','), function(event) { return event + '.dialog-overlay'; }).join(' '), create: function(dialog) { if (this.instances.length === 0) { // prevent use of anchors and inputs // we use a setTimeout in case the overlay is created from an // event that we're going to be cancelling (see #2804) setTimeout(function() { // handle $(el).dialog().dialog('close') (see #4065) if ($.ui.dialog.overlay.instances.length) { $(document).bind($.ui.dialog.overlay.events, function(event) { // stop events if the z-index of the target is < the z-index of the overlay // we cannot return true when we don't want to cancel the event (#3523) if ($(event.target).zIndex() < $.ui.dialog.overlay.maxZ) { return false; } }); } }, 1); // allow closing by pressing the escape key $(document).bind('keydown.dialog-overlay', function(event) { if (dialog.options.closeOnEscape && !event.isDefaultPrevented() && event.keyCode && event.keyCode === $.ui.keyCode.ESCAPE) { dialog.close(event); event.preventDefault(); } }); // handle window resize $(window).bind('resize.dialog-overlay', $.ui.dialog.overlay.resize); } var $el = (this.oldInstances.pop() || $('<div></div>').addClass('ui-widget-overlay')) .appendTo(document.body) .css({ width: this.width(), height: this.height() }); if ($.fn.bgiframe) { $el.bgiframe(); } this.instances.push($el); return $el; }, destroy: function($el) { var indexOf = $.inArray($el, this.instances); if (indexOf != -1){ this.oldInstances.push(this.instances.splice(indexOf, 1)[0]); } if (this.instances.length === 0) {
$el.remove(); // adjust the maxZ to allow other modal dialogs to continue to work (see #4309) var maxZ = 0; $.each(this.instances, function() { maxZ = Math.max(maxZ, this.css('z-index')); }); this.maxZ = maxZ; }, height: function() { return $(document).height() + 'px'; }, width: function() { return $(document).width() + 'px'; }, resize: function() { /* If the dialog is draggable and the user drags it past the * right edge of the window, the document becomes wider so we * need to stretch the overlay. If the user then drags the * dialog back to the left, the document will become narrower, * so we need to shrink the overlay to the appropriate size. * This is handled by shrinking the overlay before setting it * to the full document size. */ var $overlays = $([]); $.each($.ui.dialog.overlay.instances, function() { $overlays = $overlays.add(this); }); $overlays.css({ width: 0, height: 0 }).css({ width: $.ui.dialog.overlay.width(), height: $.ui.dialog.overlay.height() }); } }); $.extend($.ui.dialog.overlay.prototype, { destroy: function() { $.ui.dialog.overlay.destroy(this.$el); } }); }(jQuery));
$([document, window]).unbind('.dialog-overlay'); }
conditional_block
jquery.ui.dialog.minmax.js
/* * jQuery UI Dialog 1.8.16 * w/ Minimize & Maximize Support * by Elijah Horton (fieryprophet@yahoo.com) * * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about) * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license * * http://docs.jquery.com/UI/Dialog * * Depends: * jquery.ui.core.js * jquery.ui.widget.js * jquery.ui.button.js * jquery.ui.draggable.js * jquery.ui.mouse.js * jquery.ui.position.js * jquery.ui.resizable.js * * Modified by André Roberge to remove some IE support which is irrelevant for me. */ (function( $, undefined ) { var uiDialogClasses = 'ui-dialog ' + 'ui-widget ' + 'ui-widget-content ' + 'ui-corner-all ', sizeRelatedOptions = { buttons: true, height: true, maxHeight: true, maxWidth: true, minHeight: true, minWidth: true, width: true }, resizableRelatedOptions = { maxHeight: true, maxWidth: true, minHeight: true, minWidth: true }, // support for jQuery 1.3.2 - handle common attrFn methods for dialog attrFn = $.attrFn || { val: true, css: true, html: true, text: true, data: true, width: true, height: true, offset: true, click: true }; $.widget("ui.dialog", { options: { autoOpen: true, buttons: {}, closeOnEscape: true, closeText: 'close', dialogClass: '', draggable: true, hide: null, height: 'auto', maxHeight: false, maxWidth: false, minHeight: 150, minWidth: 300, minimizeText: 'minimize', maximizeText: 'maximize', minimize: true, maximize: true, modal: false, position: { my: 'center', at: 'center', collision: 'fit', // ensure that the titlebar is never outside the document using: function(pos) { var topOffset = $(this).css(pos).offset().top; if (topOffset < 0) {
$(this).css('top', pos.top - topOffset); } } }, resizable: true, show: null, stack: true, title: '', width: 300, zIndex: 1000 }, _create: function() { this.originalTitle = this.element.attr('title'); // #5742 - .attr() might return a DOMElement if ( typeof this.originalTitle !== "string" ) { this.originalTitle = ""; } this.options.title = this.options.title || this.originalTitle; var self = this, options = self.options, title = options.title || '&#160;', titleId = $.ui.dialog.getTitleId(self.element), uiDialog = (self.uiDialog = $('<div></div>')) .appendTo(document.body) .hide() .addClass(uiDialogClasses + options.dialogClass) .css({ zIndex: options.zIndex }) // setting tabIndex makes the div focusable // setting outline to 0 prevents a border on focus in Mozilla .attr('tabIndex', -1).css('outline', 0).keydown(function(event) { if (options.closeOnEscape && !event.isDefaultPrevented() && event.keyCode && event.keyCode === $.ui.keyCode.ESCAPE) { self.close(event); event.preventDefault(); } }) .attr({ role: 'dialog', 'aria-labelledby': titleId }) .mousedown(function(event) { self.moveToTop(false, event); }), uiDialogContent = self.element .show() .removeAttr('title') .addClass( 'ui-dialog-content ' + 'ui-widget-content') .appendTo(uiDialog), uiDialogTitlebar = (self.uiDialogTitlebar = $('<div></div>')) .addClass( 'ui-dialog-titlebar ' + 'ui-widget-header ' + 'ui-corner-all ' + 'ui-helper-clearfix' ) .prependTo(uiDialog); if(options.minimize && !options.modal){ //cannot use this option with modal var uiDialogTitlebarMinimize = $('<a href="#"></a>') .addClass( 'ui-dialog-titlebar-minimize ' + 'ui-corner-all' ) .attr('role', 'button') .hover( function() { uiDialogTitlebarMinimize.addClass('ui-state-hover'); }, function() { uiDialogTitlebarMinimize.removeClass('ui-state-hover'); } ) .focus(function() { uiDialogTitlebarMinimize.addClass('ui-state-focus'); }) .blur(function() { uiDialogTitlebarMinimize.removeClass('ui-state-focus'); }) .click(function(event) { self.minimize(event); return false; }) .appendTo(uiDialogTitlebar), uiDialogTitlebarMinimizeText = (self.uiDialogTitlebarMinimizeText = $('<span></span>')) .addClass( 'ui-icon ' + 'ui-icon-minusthick' ) .text(options.minimizeText) .appendTo(uiDialogTitlebarMinimize); } if(options.maximize && !options.modal){ //cannot use this option with modal var uiDialogTitlebarMaximize = $('<a href="#"></a>') .addClass( 'ui-dialog-titlebar-maximize ' + 'ui-corner-all' ) .attr('role', 'button') .hover( function() { uiDialogTitlebarMaximize.addClass('ui-state-hover'); }, function() { uiDialogTitlebarMaximize.removeClass('ui-state-hover'); } ) .focus(function() { uiDialogTitlebarMaximize.addClass('ui-state-focus'); }) .blur(function() { uiDialogTitlebarMaximize.removeClass('ui-state-focus'); }) .click(function(event) { self.maximize(event); return false; }) .appendTo(uiDialogTitlebar), uiDialogTitlebarMaximizeText = (self.uiDialogTitlebarMaximizeText = $('<span></span>')) .addClass( 'ui-icon ' + 'ui-icon-plusthick' ) .text(options.maximizeText) .appendTo(uiDialogTitlebarMaximize); $(uiDialogTitlebar).dblclick(function(event) { self.maximize(event); return false; }); } if(options.close !== false){ var uiDialogTitlebarClose = $('<a href="#"></a>') .addClass( 'ui-dialog-titlebar-close ' + 'ui-corner-all' ) .attr('role', 'button') .hover( function() { uiDialogTitlebarClose.addClass('ui-state-hover'); }, function() { uiDialogTitlebarClose.removeClass('ui-state-hover'); } ) .focus(function() { uiDialogTitlebarClose.addClass('ui-state-focus'); }) .blur(function() { uiDialogTitlebarClose.removeClass('ui-state-focus'); }) .click(function(event) { self.close(event); return false; }) .appendTo(uiDialogTitlebar), uiDialogTitlebarCloseText = (self.uiDialogTitlebarCloseText = $('<span></span>')) .addClass( 'ui-icon ' + 'ui-icon-closethick' ) .text(options.closeText) .appendTo(uiDialogTitlebarClose); } uiDialogTitle = $('<span></span>') .addClass('ui-dialog-title') .attr('id', titleId) .html(title) .prependTo(uiDialogTitlebar); //handling of deprecated beforeclose (vs beforeClose) option //Ticket #4669 http://dev.jqueryui.com/ticket/4669 //TODO: remove in 1.9pre if ($.isFunction(options.beforeclose) && !$.isFunction(options.beforeClose)) { options.beforeClose = options.beforeclose; } uiDialogTitlebar.find("*").add(uiDialogTitlebar).disableSelection(); if (options.draggable && $.fn.draggable) { self._makeDraggable(); } if (options.resizable && $.fn.resizable) { self._makeResizable(); } self._createButtons(options.buttons); self._isOpen = false; self._min = false; if ($.fn.bgiframe) { uiDialog.bgiframe(); } }, _init: function() { if ( this.options.autoOpen ) { this.open(); } }, destroy: function() { var self = this; if (self.overlay) { self.overlay.destroy(); } self.uiDialog.hide(); self.element .unbind('.dialog') .removeData('dialog') .removeClass('ui-dialog-content ui-widget-content') .hide().appendTo('body'); self.uiDialog.remove(); if (self.originalTitle) { self.element.attr('title', self.originalTitle); } return self; }, widget: function() { return this.uiDialog; }, minimize: function(event) { var self = this, ui = self.uiDialog; if(false === self._trigger('beforeMinimize', event)) { return; } if(!ui.data('is-minimized')){ if(self.options.minimize && typeof self.options.minimize !== "boolean" && $(self.options.minimize).length > 0){ self._min = $('<a>' + (ui.find('span.ui-dialog-title').html().replace(/&nbsp;/, '') || 'Untitled Dialog') + '</a>') .attr('title', 'Click to restore dialog').addClass('ui-corner-all ui-button').click(function(event){self.unminimize(event);}); $(self.options.minimize).append(self._min); ui.data('is-minimized', true).hide(); } else { if(ui.is( ":data(resizable)" )) { ui.data('was-resizable', true).resizable('destroy'); } else { ui.data('was-resizable', false) } ui.data('minimized-height', ui.height()); ui.find('.ui-dialog-content').hide(); ui.find('.ui-dialog-titlebar-maximize').hide(); ui.find('.ui-dialog-titlebar-minimize').css('right', '1.8em').removeClass('ui-icon-minusthick').addClass('ui-icon-arrowthickstop-1-s') .find('span').removeClass('ui-icon-minusthick').addClass('ui-icon-arrowthickstop-1-s').click(function(event){self.unminimize(event); return false;});; ui.data('is-minimized', true).height('auto'); } } return self; }, unminimize: function(event) { var self = this, ui = self.uiDialog; if(false === self._trigger('beforeUnminimize', event)) { return; } if(ui.data('is-minimized')){ if(self._min){ self._min.unbind().remove(); self._min = false; ui.data('is-minimized', false).show(); self.moveToTop(); } else { ui.height(ui.data('minimized-height')).data('is-minimized', false).removeData('minimized-height').find('.ui-dialog-content').show(); ui.find('.ui-dialog-titlebar-maximize').show(); ui.find('.ui-dialog-titlebar-minimize').css('right', '3.3em').removeClass('ui-icon-arrowthickstop-1-s').addClass('ui-icon-minusthick') .find('span').removeClass('ui-icon-arrowthickstop-1-s').addClass('ui-icon-minusthick').click(function(event){self.minimize(event); return false;}); if(ui.data('was-resizable') == true) { self._makeResizable(true); } } } return self; }, maximize: function(event) { var self = this, ui = self.uiDialog; if(false === self._trigger('beforeMaximize', event)) { return; } if(!ui.data('is-maximized')){ if(ui.is( ":data(draggable)" )) { ui.data('was-draggable', true).draggable('destroy'); } else { ui.data('was-draggable', false) } if(ui.is( ":data(resizable)" )) { ui.data('was-resizable', true).resizable('destroy'); } else { ui.data('was-resizable', false) } ui.data('maximized-height', ui.height()).data('maximized-width', ui.width()).data('maximized-top', ui.css('top')).data('maximized-left', ui.css('left')) .data('is-maximized', true).height($(window).height()-8).width($(window).width()+9).css({"top":0, "left": 0}).find('.ui-dialog-titlebar-minimize').hide(); ui.find('.ui-dialog-titlebar-maximize').removeClass('ui-icon-plusthick').addClass('ui-icon-arrowthick-1-sw') .find('span').removeClass('ui-icon-plusthick').addClass('ui-icon-arrowthick-1-sw').click(function(event){self.unmaximize(event); return false;}); ui.find('.ui-dialog-titlebar').dblclick(function(event){self.unmaximize(event); return false;}); } return self; }, unmaximize: function(event) { var self = this, ui = self.uiDialog; if(false === self._trigger('beforeUnmaximize', event)) { return; } if(ui.data('is-maximized')){ ui.height(ui.data('maximized-height')).width(ui.data('maximized-width')).css({"top":ui.data('maximized-top'), "left":ui.data('maximized-left')}) .data('is-maximized', false).removeData('maximized-height').removeData('maximized-width').removeData('maximized-top').removeData('maximized-left').find('.ui-dialog-titlebar-minimize').show(); ui.find('.ui-dialog-titlebar-maximize').removeClass('ui-icon-arrowthick-1-sw').addClass('ui-icon-plusthick') .find('span').removeClass('ui-icon-arrowthick-1-sw').addClass('ui-icon-plusthick').click(function(){self.maximize(event); return false;}); ui.find('.ui-dialog-titlebar').dblclick(function(event){self.maximize(event); return false;}); if(ui.data('was-draggable') == true) { self._makeDraggable(true); } if(ui.data('was-resizable') == true) { self._makeResizable(true); } } return self; }, close: function(event) { var self = this, maxZ, thisZ; if (false === self._trigger('beforeClose', event)) { return; } if (self.overlay) { self.overlay.destroy(); } self.uiDialog.unbind('keypress.ui-dialog'); self._isOpen = false; if (self.options.hide) { self.uiDialog.hide(self.options.hide, function() { self._trigger('close', event); }); } else { self.uiDialog.hide(); self._trigger('close', event); } $.ui.dialog.overlay.resize(); // adjust the maxZ to allow other modal dialogs to continue to work (see #4309) if (self.options.modal) { maxZ = 0; $('.ui-dialog').each(function() { if (this !== self.uiDialog[0]) { thisZ = $(this).css('z-index'); if(!isNaN(thisZ)) { maxZ = Math.max(maxZ, thisZ); } } }); $.ui.dialog.maxZ = maxZ; } return self; }, isOpen: function() { return this._isOpen; }, // the force parameter allows us to move modal dialogs to their correct // position on open moveToTop: function(force, event) { var self = this, options = self.options, saveScroll; if ((options.modal && !force) || (!options.stack && !options.modal)) { return self._trigger('focus', event); } if (options.zIndex > $.ui.dialog.maxZ) { $.ui.dialog.maxZ = options.zIndex; } if (self.overlay) { $.ui.dialog.maxZ += 1; self.overlay.$el.css('z-index', $.ui.dialog.overlay.maxZ = $.ui.dialog.maxZ); } //Save and then restore scroll since Opera 9.5+ resets when parent z-Index is changed. // http://ui.jquery.com/bugs/ticket/3193 saveScroll = { scrollTop: self.element.scrollTop(), scrollLeft: self.element.scrollLeft() }; $.ui.dialog.maxZ += 1; self.uiDialog.css('z-index', $.ui.dialog.maxZ); self.element.attr(saveScroll); self._trigger('focus', event); return self; }, open: function() { if (this._isOpen) { return; } var self = this, options = self.options, uiDialog = self.uiDialog; self.overlay = options.modal ? new $.ui.dialog.overlay(self) : null; self._size(); self._position(options.position); uiDialog.show(options.show); self.moveToTop(true); // prevent tabbing out of modal dialogs if (options.modal) { uiDialog.bind('keypress.ui-dialog', function(event) { if (event.keyCode !== $.ui.keyCode.TAB) { return; } var tabbables = $(':tabbable', this), first = tabbables.filter(':first'), last = tabbables.filter(':last'); if (event.target === last[0] && !event.shiftKey) { first.focus(1); return false; } else if (event.target === first[0] && event.shiftKey) { last.focus(1); return false; } }); } // set focus to the first tabbable element in the content area or the first button // if there are no tabbable elements, set focus on the dialog itself $(self.element.find(':tabbable').get().concat( uiDialog.find('.ui-dialog-buttonpane :tabbable').get().concat( uiDialog.get()))).eq(0).focus(); self._isOpen = true; self._trigger('open'); return self; }, _createButtons: function(buttons) { var self = this, hasButtons = false, uiDialogButtonPane = $('<div></div>') .addClass( 'ui-dialog-buttonpane ' + 'ui-widget-content ' + 'ui-helper-clearfix' ), uiButtonSet = $( "<div></div>" ) .addClass( "ui-dialog-buttonset" ) .appendTo( uiDialogButtonPane ); // if we already have a button pane, remove it self.uiDialog.find('.ui-dialog-buttonpane').remove(); if (typeof buttons === 'object' && buttons !== null) { $.each(buttons, function() { return !(hasButtons = true); }); } if (hasButtons) { $.each(buttons, function(name, props) { props = $.isFunction( props ) ? { click: props, text: name } : props; var button = $('<button type="button"></button>') .click(function() { props.click.apply(self.element[0], arguments); }) .appendTo(uiButtonSet); // can't use .attr( props, true ) with jQuery 1.3.2. $.each( props, function( key, value ) { if ( key === "click" ) { return; } if ( key in attrFn ) { button[ key ]( value ); } else { button.attr( key, value ); } }); if ($.fn.button) { button.button(); } }); uiDialogButtonPane.appendTo(self.uiDialog); } }, _makeDraggable: function() { var self = this, options = self.options, doc = $(document), heightBeforeDrag; function filteredUi(ui) { return { position: ui.position, offset: ui.offset }; } self.uiDialog.draggable({ cancel: '.ui-dialog-content, .ui-dialog-titlebar-close', handle: '.ui-dialog-titlebar', containment: 'document', start: function(event, ui) { heightBeforeDrag = options.height === "auto" ? "auto" : $(this).height(); $(this).height($(this).height()).addClass("ui-dialog-dragging"); self._trigger('dragStart', event, filteredUi(ui)); }, drag: function(event, ui) { self._trigger('drag', event, filteredUi(ui)); }, stop: function(event, ui) { options.position = [ui.position.left - doc.scrollLeft(), ui.position.top - doc.scrollTop()]; $(this).removeClass("ui-dialog-dragging").height(heightBeforeDrag); self._trigger('dragStop', event, filteredUi(ui)); $.ui.dialog.overlay.resize(); } }); }, _makeResizable: function(handles) { handles = (handles === undefined ? this.options.resizable : handles); var self = this, options = self.options, // .ui-resizable has position: relative defined in the stylesheet // but dialogs have to use absolute or fixed positioning position = self.uiDialog.css('position'), resizeHandles = (typeof handles === 'string' ? handles : 'n,e,s,w,se,sw,ne,nw' ); function filteredUi(ui) { return { originalPosition: ui.originalPosition, originalSize: ui.originalSize, position: ui.position, size: ui.size }; } self.uiDialog.resizable({ cancel: '.ui-dialog-content', containment: 'document', alsoResize: self.element, maxWidth: options.maxWidth, maxHeight: options.maxHeight, minWidth: options.minWidth, minHeight: self._minHeight(), handles: resizeHandles, start: function(event, ui) { $(this).addClass("ui-dialog-resizing"); self._trigger('resizeStart', event, filteredUi(ui)); }, resize: function(event, ui){ self._trigger('resize', event, filteredUi(ui)); }, stop: function(event, ui) { $(this).removeClass("ui-dialog-resizing"); options.height = $(this).height(); options.width = $(this).width(); self._trigger('resizeStop', event, filteredUi(ui)); $.ui.dialog.overlay.resize(); } }) .css('position', position) .find('.ui-resizable-se').addClass('ui-icon ui-icon-grip-diagonal-se'); }, _minHeight: function() { var options = this.options; if (options.height === 'auto') { return options.minHeight; } else { return Math.min(options.minHeight, options.height); } }, _position: function(position) { var myAt = [], offset = [0, 0], isVisible; if (position) { // deep extending converts arrays to objects in jQuery <= 1.3.2 :-( // if (typeof position == 'string' || $.isArray(position)) { // myAt = $.isArray(position) ? position : position.split(' '); if (typeof position === 'string' || (typeof position === 'object' && '0' in position)) { myAt = position.split ? position.split(' ') : [position[0], position[1]]; if (myAt.length === 1) { myAt[1] = myAt[0]; } $.each(['left', 'top'], function(i, offsetPosition) { if (+myAt[i] === myAt[i]) { offset[i] = myAt[i]; myAt[i] = offsetPosition; } }); position = { my: myAt.join(" "), at: myAt.join(" "), offset: offset.join(" ") }; } position = $.extend({}, $.ui.dialog.prototype.options.position, position); } else { position = $.ui.dialog.prototype.options.position; } // need to show the dialog to get the actual offset in the position plugin isVisible = this.uiDialog.is(':visible'); if (!isVisible) { this.uiDialog.show(); } this.uiDialog // workaround for jQuery bug #5781 http://dev.jquery.com/ticket/5781 //.css({ top: 0, left: 0 }) .position($.extend({ of: window }, position)); if (!isVisible) { this.uiDialog.hide(); } }, _setOptions: function( options ) { var self = this, resizableOptions = {}, resize = false; $.each( options, function( key, value ) { self._setOption( key, value ); if ( key in sizeRelatedOptions ) { resize = true; } if ( key in resizableRelatedOptions ) { resizableOptions[ key ] = value; } }); if ( resize ) { this._size(); } if ( this.uiDialog.is( ":data(resizable)" ) ) { this.uiDialog.resizable( "option", resizableOptions ); } }, _setOption: function(key, value){ var self = this, uiDialog = self.uiDialog; switch (key) { //handling of deprecated beforeclose (vs beforeClose) option //Ticket #4669 http://dev.jqueryui.com/ticket/4669 //TODO: remove in 1.9pre case "beforeclose": key = "beforeClose"; break; case "buttons": self._createButtons(value); break; case "closeText": // ensure that we always pass a string self.uiDialogTitlebarCloseText.text("" + value); break; case "dialogClass": uiDialog .removeClass(self.options.dialogClass) .addClass(uiDialogClasses + value); break; case "disabled": if (value) { uiDialog.addClass('ui-dialog-disabled'); } else { uiDialog.removeClass('ui-dialog-disabled'); } break; case "draggable": var isDraggable = uiDialog.is( ":data(draggable)" ); if ( isDraggable && !value ) { uiDialog.draggable( "destroy" ); } if ( !isDraggable && value ) { self._makeDraggable(); } break; case "position": self._position(value); break; case "resizable": // currently resizable, becoming non-resizable var isResizable = uiDialog.is( ":data(resizable)" ); if (isResizable && !value) { uiDialog.resizable('destroy'); } // currently resizable, changing handles if (isResizable && typeof value === 'string') { uiDialog.resizable('option', 'handles', value); } // currently non-resizable, becoming resizable if (!isResizable && value !== false) { self._makeResizable(value); } break; case "title": // convert whatever was passed in o a string, for html() to not throw up $(".ui-dialog-title", self.uiDialogTitlebar).html("" + (value || '&#160;')); break; } $.Widget.prototype._setOption.apply(self, arguments); }, _size: function() { /* If the user has resized the dialog, the .ui-dialog and .ui-dialog-content * divs will both have width and height set, so we need to reset them */ var options = this.options, nonContentHeight, minContentHeight, isVisible = this.uiDialog.is( ":visible" ); // reset content sizing this.element.show().css({ width: 'auto', minHeight: 0, height: 0 }); if (options.minWidth > options.width) { options.width = options.minWidth; } // reset wrapper sizing // determine the height of all the non-content elements nonContentHeight = this.uiDialog.css({ height: 'auto', width: options.width }) .height(); minContentHeight = Math.max( 0, options.minHeight - nonContentHeight ); if ( options.height === "auto" ) { // only needed for IE6 support if ( $.support.minHeight ) { this.element.css({ minHeight: minContentHeight, height: "auto" }); } else { this.uiDialog.show(); var autoHeight = this.element.css( "height", "auto" ).height(); if ( !isVisible ) { this.uiDialog.hide(); } this.element.height( Math.max( autoHeight, minContentHeight ) ); } } else { this.element.height( Math.max( options.height - nonContentHeight, 0 ) ); } if (this.uiDialog.is(':data(resizable)')) { this.uiDialog.resizable('option', 'minHeight', this._minHeight()); } } }); $.extend($.ui.dialog, { version: "1.8.16", uuid: 0, maxZ: 0, getTitleId: function($el) { var id = $el.attr('id'); if (!id) { this.uuid += 1; id = this.uuid; } return 'ui-dialog-title-' + id; }, overlay: function(dialog) { this.$el = $.ui.dialog.overlay.create(dialog); } }); $.extend($.ui.dialog.overlay, { instances: [], // reuse old instances due to IE memory leak with alpha transparency (see #5185) oldInstances: [], maxZ: 0, events: $.map('focus,mousedown,mouseup,keydown,keypress,click'.split(','), function(event) { return event + '.dialog-overlay'; }).join(' '), create: function(dialog) { if (this.instances.length === 0) { // prevent use of anchors and inputs // we use a setTimeout in case the overlay is created from an // event that we're going to be cancelling (see #2804) setTimeout(function() { // handle $(el).dialog().dialog('close') (see #4065) if ($.ui.dialog.overlay.instances.length) { $(document).bind($.ui.dialog.overlay.events, function(event) { // stop events if the z-index of the target is < the z-index of the overlay // we cannot return true when we don't want to cancel the event (#3523) if ($(event.target).zIndex() < $.ui.dialog.overlay.maxZ) { return false; } }); } }, 1); // allow closing by pressing the escape key $(document).bind('keydown.dialog-overlay', function(event) { if (dialog.options.closeOnEscape && !event.isDefaultPrevented() && event.keyCode && event.keyCode === $.ui.keyCode.ESCAPE) { dialog.close(event); event.preventDefault(); } }); // handle window resize $(window).bind('resize.dialog-overlay', $.ui.dialog.overlay.resize); } var $el = (this.oldInstances.pop() || $('<div></div>').addClass('ui-widget-overlay')) .appendTo(document.body) .css({ width: this.width(), height: this.height() }); if ($.fn.bgiframe) { $el.bgiframe(); } this.instances.push($el); return $el; }, destroy: function($el) { var indexOf = $.inArray($el, this.instances); if (indexOf != -1){ this.oldInstances.push(this.instances.splice(indexOf, 1)[0]); } if (this.instances.length === 0) { $([document, window]).unbind('.dialog-overlay'); } $el.remove(); // adjust the maxZ to allow other modal dialogs to continue to work (see #4309) var maxZ = 0; $.each(this.instances, function() { maxZ = Math.max(maxZ, this.css('z-index')); }); this.maxZ = maxZ; }, height: function() { return $(document).height() + 'px'; }, width: function() { return $(document).width() + 'px'; }, resize: function() { /* If the dialog is draggable and the user drags it past the * right edge of the window, the document becomes wider so we * need to stretch the overlay. If the user then drags the * dialog back to the left, the document will become narrower, * so we need to shrink the overlay to the appropriate size. * This is handled by shrinking the overlay before setting it * to the full document size. */ var $overlays = $([]); $.each($.ui.dialog.overlay.instances, function() { $overlays = $overlays.add(this); }); $overlays.css({ width: 0, height: 0 }).css({ width: $.ui.dialog.overlay.width(), height: $.ui.dialog.overlay.height() }); } }); $.extend($.ui.dialog.overlay.prototype, { destroy: function() { $.ui.dialog.overlay.destroy(this.$el); } }); }(jQuery));
random_line_split
align_of.rs
#![feature(core)] extern crate core; #[cfg(test)] mod tests { use core::mem::align_of; // pub fn align_of<T>() -> usize { // unsafe { intrinsics::min_align_of::<T>() } // } macro_rules! align_of_test { ($T:ty, $size:expr) => ({ let size: usize = align_of::<$T>(); assert_eq!(size, $size); }) } #[test] fn
() { struct A; align_of_test!( A, 1 ); } #[test] fn align_of_test2() { align_of_test!( u8, 1 ); align_of_test!( u16, 2 ); align_of_test!( u32, 4 ); align_of_test!( u64, 8 ); align_of_test!( i8, 1 ); align_of_test!( i16, 2 ); align_of_test!( i32, 4 ); align_of_test!( i64, 8 ); align_of_test!( f32, 4 ); align_of_test!( f64, 8 ); align_of_test!( [u8; 0], 1 ); align_of_test!( [u8; 68], 1 ); align_of_test!( [u32; 0], 4 ); align_of_test!( [u32; 68], 4 ); align_of_test!( (u8,), 1 ); align_of_test!( (u8, u16), 2 ); align_of_test!( (u8, u16, u32), 4 ); align_of_test!( (u8, u16, u32, u64), 8 ); } }
align_of_test1
identifier_name
align_of.rs
#![feature(core)] extern crate core; #[cfg(test)] mod tests { use core::mem::align_of; // pub fn align_of<T>() -> usize { // unsafe { intrinsics::min_align_of::<T>() } // }
let size: usize = align_of::<$T>(); assert_eq!(size, $size); }) } #[test] fn align_of_test1() { struct A; align_of_test!( A, 1 ); } #[test] fn align_of_test2() { align_of_test!( u8, 1 ); align_of_test!( u16, 2 ); align_of_test!( u32, 4 ); align_of_test!( u64, 8 ); align_of_test!( i8, 1 ); align_of_test!( i16, 2 ); align_of_test!( i32, 4 ); align_of_test!( i64, 8 ); align_of_test!( f32, 4 ); align_of_test!( f64, 8 ); align_of_test!( [u8; 0], 1 ); align_of_test!( [u8; 68], 1 ); align_of_test!( [u32; 0], 4 ); align_of_test!( [u32; 68], 4 ); align_of_test!( (u8,), 1 ); align_of_test!( (u8, u16), 2 ); align_of_test!( (u8, u16, u32), 4 ); align_of_test!( (u8, u16, u32, u64), 8 ); } }
macro_rules! align_of_test { ($T:ty, $size:expr) => ({
random_line_split
align_of.rs
#![feature(core)] extern crate core; #[cfg(test)] mod tests { use core::mem::align_of; // pub fn align_of<T>() -> usize { // unsafe { intrinsics::min_align_of::<T>() } // } macro_rules! align_of_test { ($T:ty, $size:expr) => ({ let size: usize = align_of::<$T>(); assert_eq!(size, $size); }) } #[test] fn align_of_test1()
#[test] fn align_of_test2() { align_of_test!( u8, 1 ); align_of_test!( u16, 2 ); align_of_test!( u32, 4 ); align_of_test!( u64, 8 ); align_of_test!( i8, 1 ); align_of_test!( i16, 2 ); align_of_test!( i32, 4 ); align_of_test!( i64, 8 ); align_of_test!( f32, 4 ); align_of_test!( f64, 8 ); align_of_test!( [u8; 0], 1 ); align_of_test!( [u8; 68], 1 ); align_of_test!( [u32; 0], 4 ); align_of_test!( [u32; 68], 4 ); align_of_test!( (u8,), 1 ); align_of_test!( (u8, u16), 2 ); align_of_test!( (u8, u16, u32), 4 ); align_of_test!( (u8, u16, u32, u64), 8 ); } }
{ struct A; align_of_test!( A, 1 ); }
identifier_body
color.ts
import Vue from 'vue'; import Component from 'vue-class-component'; import { Prop } from 'vue-property-decorator'; import WithRender from './color.html?style=./color.scss'; import { CompleterResult } from 'readline'; @WithRender @Component export class MColor extends Vue { @Prop() public hex: string; @Prop() public name: string; private get
(): string[] { let shorthandRegex: any = /^#?([a-f\d])([a-f\d])([a-f\d])$/i; let hex: string = this.hex.replace(shorthandRegex, (m, r, g, b) => { return r + r + g + g + b + b; }); return /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex); } private get red(): number { return parseInt(this.hexArray[1], 16); } private get green(): number { return parseInt(this.hexArray[2], 16); } private get blue(): number { return parseInt(this.hexArray[3], 16); } private get rgb(): string { return this.hexArray ? this.red + ', ' + this.green + ', ' + this.blue : undefined; } private get textColor(): string { let yiq = ((this.red * 299) + (this.green * 587) + (this.blue * 114)) / 1000; return (yiq >= 128) ? '#000' : '#fff'; } private get cmyk(): string { let r: number = this.red / 255; let g: number = this.green / 255; let b: number = this.blue / 255; let k: number = Math.round(Math.min(1 - r, 1 - g, 1 - b) * 100); let c: number = Math.round(((1 - r - k) / (1 - k)) * 100); let m: number = Math.round(((1 - g - k) / (1 - k)) * 100); let y: number = Math.round(((1 - b - k) / (1 - k)) * 100); return c + ', ' + m + ', ' + y + ', ' + k; } } export const COLOR_NAME: string = 'modul-color';
hexArray
identifier_name
color.ts
import Vue from 'vue'; import Component from 'vue-class-component'; import { Prop } from 'vue-property-decorator'; import WithRender from './color.html?style=./color.scss'; import { CompleterResult } from 'readline'; @WithRender @Component export class MColor extends Vue { @Prop() public hex: string; @Prop() public name: string; private get hexArray(): string[] { let shorthandRegex: any = /^#?([a-f\d])([a-f\d])([a-f\d])$/i; let hex: string = this.hex.replace(shorthandRegex, (m, r, g, b) => { return r + r + g + g + b + b; }); return /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex); } private get red(): number { return parseInt(this.hexArray[1], 16); }
return parseInt(this.hexArray[2], 16); } private get blue(): number { return parseInt(this.hexArray[3], 16); } private get rgb(): string { return this.hexArray ? this.red + ', ' + this.green + ', ' + this.blue : undefined; } private get textColor(): string { let yiq = ((this.red * 299) + (this.green * 587) + (this.blue * 114)) / 1000; return (yiq >= 128) ? '#000' : '#fff'; } private get cmyk(): string { let r: number = this.red / 255; let g: number = this.green / 255; let b: number = this.blue / 255; let k: number = Math.round(Math.min(1 - r, 1 - g, 1 - b) * 100); let c: number = Math.round(((1 - r - k) / (1 - k)) * 100); let m: number = Math.round(((1 - g - k) / (1 - k)) * 100); let y: number = Math.round(((1 - b - k) / (1 - k)) * 100); return c + ', ' + m + ', ' + y + ', ' + k; } } export const COLOR_NAME: string = 'modul-color';
private get green(): number {
random_line_split
color.ts
import Vue from 'vue'; import Component from 'vue-class-component'; import { Prop } from 'vue-property-decorator'; import WithRender from './color.html?style=./color.scss'; import { CompleterResult } from 'readline'; @WithRender @Component export class MColor extends Vue { @Prop() public hex: string; @Prop() public name: string; private get hexArray(): string[] { let shorthandRegex: any = /^#?([a-f\d])([a-f\d])([a-f\d])$/i; let hex: string = this.hex.replace(shorthandRegex, (m, r, g, b) => { return r + r + g + g + b + b; }); return /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex); } private get red(): number
private get green(): number { return parseInt(this.hexArray[2], 16); } private get blue(): number { return parseInt(this.hexArray[3], 16); } private get rgb(): string { return this.hexArray ? this.red + ', ' + this.green + ', ' + this.blue : undefined; } private get textColor(): string { let yiq = ((this.red * 299) + (this.green * 587) + (this.blue * 114)) / 1000; return (yiq >= 128) ? '#000' : '#fff'; } private get cmyk(): string { let r: number = this.red / 255; let g: number = this.green / 255; let b: number = this.blue / 255; let k: number = Math.round(Math.min(1 - r, 1 - g, 1 - b) * 100); let c: number = Math.round(((1 - r - k) / (1 - k)) * 100); let m: number = Math.round(((1 - g - k) / (1 - k)) * 100); let y: number = Math.round(((1 - b - k) / (1 - k)) * 100); return c + ', ' + m + ', ' + y + ', ' + k; } } export const COLOR_NAME: string = 'modul-color';
{ return parseInt(this.hexArray[1], 16); }
identifier_body
ContentStylePositionTest.ts
import { Assertions, Pipeline, Step } from '@ephox/agar'; import { Arr } from '@ephox/katamari'; import { TinyLoader } from '@ephox/mcagar'; import { Element, Node } from '@ephox/sugar'; import Theme from 'tinymce/themes/silver/Theme'; import { UnitTest } from '@ephox/bedrock'; UnitTest.asynctest('browser.tinymce.core.init.ContentStylePositionTest', function () { const success = arguments[arguments.length - 2]; const failure = arguments[arguments.length - 1]; Theme(); const contentStyle = '.class {color: blue;}'; TinyLoader.setupLight(function (editor, onSuccess, onFailure) { Pipeline.async({}, [ Step.sync(function () { const headStuff = editor.getDoc().head.querySelectorAll('link, style'); const linkIndex = Arr.findIndex(headStuff, function (elm) { return Node.name(Element.fromDom(elm)) === 'link'; }).getOrDie('could not find link elemnt'); const styleIndex = Arr.findIndex(headStuff, function (elm) { return elm.innerText === contentStyle;
}) ], onSuccess, onFailure); }, { content_style: contentStyle, base_url: '/project/tinymce/js/tinymce' }, success, failure); });
}).getOrDie('could not find content style tag'); Assertions.assertEq('style tag should be after link tag', linkIndex < styleIndex, true);
random_line_split
persistentid.py
# -*- coding: utf-8 -*- # # This file is part of Zenodo. # Copyright (C) 2016 CERN. # # Zenodo is free software; you can redistribute it # and/or modify it under the terms of the GNU General Public License as # published by the Free Software Foundation; either version 2 of the # License, or (at your option) any later version. # # Zenodo is distributed in the hope that it will be # useful, but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Zenodo; if not, write to the # Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, # MA 02111-1307, USA. # # In applying this license, CERN does not # waive the privileges and immunities granted to it by virtue of its status # as an Intergovernmental Organization or submit itself to any jurisdiction. """Persistent identifier field.""" from __future__ import absolute_import, print_function import idutils from flask_babelex import lazy_gettext as _ from marshmallow import missing from .sanitizedunicode import SanitizedUnicode class PersistentId(SanitizedUnicode):
"""Special DOI field.""" default_error_messages = { 'invalid_scheme': _('Not a valid {scheme} identifier.'), 'invalid_pid': _('Not a valid persistent identifier.'), } def __init__(self, scheme=None, normalize=True, *args, **kwargs): """Initialize field.""" super(PersistentId, self).__init__(*args, **kwargs) self.scheme = scheme self.normalize = normalize def _serialize(self, value, attr, obj): """Serialize persistent identifier value.""" if not value: return missing return value def _deserialize(self, value, attr, data): """Deserialize persistent identifier value.""" value = super(PersistentId, self)._deserialize(value, attr, data) value = value.strip() schemes = idutils.detect_identifier_schemes(value) if self.scheme and self.scheme.lower() not in schemes: self.fail('invalid_scheme', scheme=self.scheme) if not schemes: self.fail('invalid_pid') return idutils.normalize_pid(value, schemes[0]) \ if self.normalize else value
identifier_body
persistentid.py
# -*- coding: utf-8 -*- # # This file is part of Zenodo. # Copyright (C) 2016 CERN. # # Zenodo is free software; you can redistribute it # and/or modify it under the terms of the GNU General Public License as # published by the Free Software Foundation; either version 2 of the # License, or (at your option) any later version. # # Zenodo is distributed in the hope that it will be # useful, but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Zenodo; if not, write to the # Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, # MA 02111-1307, USA. # # In applying this license, CERN does not # waive the privileges and immunities granted to it by virtue of its status # as an Intergovernmental Organization or submit itself to any jurisdiction. """Persistent identifier field.""" from __future__ import absolute_import, print_function
import idutils from flask_babelex import lazy_gettext as _ from marshmallow import missing from .sanitizedunicode import SanitizedUnicode class PersistentId(SanitizedUnicode): """Special DOI field.""" default_error_messages = { 'invalid_scheme': _('Not a valid {scheme} identifier.'), 'invalid_pid': _('Not a valid persistent identifier.'), } def __init__(self, scheme=None, normalize=True, *args, **kwargs): """Initialize field.""" super(PersistentId, self).__init__(*args, **kwargs) self.scheme = scheme self.normalize = normalize def _serialize(self, value, attr, obj): """Serialize persistent identifier value.""" if not value: return missing return value def _deserialize(self, value, attr, data): """Deserialize persistent identifier value.""" value = super(PersistentId, self)._deserialize(value, attr, data) value = value.strip() schemes = idutils.detect_identifier_schemes(value) if self.scheme and self.scheme.lower() not in schemes: self.fail('invalid_scheme', scheme=self.scheme) if not schemes: self.fail('invalid_pid') return idutils.normalize_pid(value, schemes[0]) \ if self.normalize else value
random_line_split
persistentid.py
# -*- coding: utf-8 -*- # # This file is part of Zenodo. # Copyright (C) 2016 CERN. # # Zenodo is free software; you can redistribute it # and/or modify it under the terms of the GNU General Public License as # published by the Free Software Foundation; either version 2 of the # License, or (at your option) any later version. # # Zenodo is distributed in the hope that it will be # useful, but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Zenodo; if not, write to the # Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, # MA 02111-1307, USA. # # In applying this license, CERN does not # waive the privileges and immunities granted to it by virtue of its status # as an Intergovernmental Organization or submit itself to any jurisdiction. """Persistent identifier field.""" from __future__ import absolute_import, print_function import idutils from flask_babelex import lazy_gettext as _ from marshmallow import missing from .sanitizedunicode import SanitizedUnicode class PersistentId(SanitizedUnicode): """Special DOI field.""" default_error_messages = { 'invalid_scheme': _('Not a valid {scheme} identifier.'), 'invalid_pid': _('Not a valid persistent identifier.'), } def __init__(self, scheme=None, normalize=True, *args, **kwargs): """Initialize field.""" super(PersistentId, self).__init__(*args, **kwargs) self.scheme = scheme self.normalize = normalize def
(self, value, attr, obj): """Serialize persistent identifier value.""" if not value: return missing return value def _deserialize(self, value, attr, data): """Deserialize persistent identifier value.""" value = super(PersistentId, self)._deserialize(value, attr, data) value = value.strip() schemes = idutils.detect_identifier_schemes(value) if self.scheme and self.scheme.lower() not in schemes: self.fail('invalid_scheme', scheme=self.scheme) if not schemes: self.fail('invalid_pid') return idutils.normalize_pid(value, schemes[0]) \ if self.normalize else value
_serialize
identifier_name
persistentid.py
# -*- coding: utf-8 -*- # # This file is part of Zenodo. # Copyright (C) 2016 CERN. # # Zenodo is free software; you can redistribute it # and/or modify it under the terms of the GNU General Public License as # published by the Free Software Foundation; either version 2 of the # License, or (at your option) any later version. # # Zenodo is distributed in the hope that it will be # useful, but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Zenodo; if not, write to the # Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, # MA 02111-1307, USA. # # In applying this license, CERN does not # waive the privileges and immunities granted to it by virtue of its status # as an Intergovernmental Organization or submit itself to any jurisdiction. """Persistent identifier field.""" from __future__ import absolute_import, print_function import idutils from flask_babelex import lazy_gettext as _ from marshmallow import missing from .sanitizedunicode import SanitizedUnicode class PersistentId(SanitizedUnicode): """Special DOI field.""" default_error_messages = { 'invalid_scheme': _('Not a valid {scheme} identifier.'), 'invalid_pid': _('Not a valid persistent identifier.'), } def __init__(self, scheme=None, normalize=True, *args, **kwargs): """Initialize field.""" super(PersistentId, self).__init__(*args, **kwargs) self.scheme = scheme self.normalize = normalize def _serialize(self, value, attr, obj): """Serialize persistent identifier value.""" if not value: return missing return value def _deserialize(self, value, attr, data): """Deserialize persistent identifier value.""" value = super(PersistentId, self)._deserialize(value, attr, data) value = value.strip() schemes = idutils.detect_identifier_schemes(value) if self.scheme and self.scheme.lower() not in schemes: self.fail('invalid_scheme', scheme=self.scheme) if not schemes:
return idutils.normalize_pid(value, schemes[0]) \ if self.normalize else value
self.fail('invalid_pid')
conditional_block
popstateevent.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ use crate::dom::bindings::codegen::Bindings::EventBinding::EventMethods; use crate::dom::bindings::codegen::Bindings::PopStateEventBinding; use crate::dom::bindings::codegen::Bindings::PopStateEventBinding::PopStateEventMethods; use crate::dom::bindings::error::Fallible; use crate::dom::bindings::inheritance::Castable; use crate::dom::bindings::reflector::reflect_dom_object; use crate::dom::bindings::root::DomRoot; use crate::dom::bindings::str::DOMString; use crate::dom::bindings::trace::RootedTraceableBox; use crate::dom::event::Event; use crate::dom::eventtarget::EventTarget; use crate::dom::window::Window; use crate::script_runtime::JSContext; use dom_struct::dom_struct; use js::jsapi::Heap; use js::jsval::JSVal; use js::rust::HandleValue; use servo_atoms::Atom; // https://html.spec.whatwg.org/multipage/#the-popstateevent-interface #[dom_struct] pub struct PopStateEvent { event: Event, #[ignore_malloc_size_of = "Defined in rust-mozjs"] state: Heap<JSVal>, } impl PopStateEvent { fn new_inherited() -> PopStateEvent { PopStateEvent { event: Event::new_inherited(), state: Heap::default(), } } pub fn
(window: &Window) -> DomRoot<PopStateEvent> { reflect_dom_object(Box::new(PopStateEvent::new_inherited()), window) } pub fn new( window: &Window, type_: Atom, bubbles: bool, cancelable: bool, state: HandleValue, ) -> DomRoot<PopStateEvent> { let ev = PopStateEvent::new_uninitialized(window); ev.state.set(state.get()); { let event = ev.upcast::<Event>(); event.init_event(type_, bubbles, cancelable); } ev } #[allow(non_snake_case)] pub fn Constructor( window: &Window, type_: DOMString, init: RootedTraceableBox<PopStateEventBinding::PopStateEventInit>, ) -> Fallible<DomRoot<PopStateEvent>> { Ok(PopStateEvent::new( window, Atom::from(type_), init.parent.bubbles, init.parent.cancelable, init.state.handle(), )) } pub fn dispatch_jsval(target: &EventTarget, window: &Window, state: HandleValue) { let event = PopStateEvent::new(window, atom!("popstate"), false, false, state); event.upcast::<Event>().fire(target); } } impl PopStateEventMethods for PopStateEvent { // https://html.spec.whatwg.org/multipage/#dom-popstateevent-state fn State(&self, _cx: JSContext) -> JSVal { self.state.get() } // https://dom.spec.whatwg.org/#dom-event-istrusted fn IsTrusted(&self) -> bool { self.event.IsTrusted() } }
new_uninitialized
identifier_name
popstateevent.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ use crate::dom::bindings::codegen::Bindings::EventBinding::EventMethods; use crate::dom::bindings::codegen::Bindings::PopStateEventBinding; use crate::dom::bindings::codegen::Bindings::PopStateEventBinding::PopStateEventMethods; use crate::dom::bindings::error::Fallible; use crate::dom::bindings::inheritance::Castable; use crate::dom::bindings::reflector::reflect_dom_object; use crate::dom::bindings::root::DomRoot; use crate::dom::bindings::str::DOMString; use crate::dom::bindings::trace::RootedTraceableBox; use crate::dom::event::Event; use crate::dom::eventtarget::EventTarget; use crate::dom::window::Window; use crate::script_runtime::JSContext; use dom_struct::dom_struct; use js::jsapi::Heap; use js::jsval::JSVal;
// https://html.spec.whatwg.org/multipage/#the-popstateevent-interface #[dom_struct] pub struct PopStateEvent { event: Event, #[ignore_malloc_size_of = "Defined in rust-mozjs"] state: Heap<JSVal>, } impl PopStateEvent { fn new_inherited() -> PopStateEvent { PopStateEvent { event: Event::new_inherited(), state: Heap::default(), } } pub fn new_uninitialized(window: &Window) -> DomRoot<PopStateEvent> { reflect_dom_object(Box::new(PopStateEvent::new_inherited()), window) } pub fn new( window: &Window, type_: Atom, bubbles: bool, cancelable: bool, state: HandleValue, ) -> DomRoot<PopStateEvent> { let ev = PopStateEvent::new_uninitialized(window); ev.state.set(state.get()); { let event = ev.upcast::<Event>(); event.init_event(type_, bubbles, cancelable); } ev } #[allow(non_snake_case)] pub fn Constructor( window: &Window, type_: DOMString, init: RootedTraceableBox<PopStateEventBinding::PopStateEventInit>, ) -> Fallible<DomRoot<PopStateEvent>> { Ok(PopStateEvent::new( window, Atom::from(type_), init.parent.bubbles, init.parent.cancelable, init.state.handle(), )) } pub fn dispatch_jsval(target: &EventTarget, window: &Window, state: HandleValue) { let event = PopStateEvent::new(window, atom!("popstate"), false, false, state); event.upcast::<Event>().fire(target); } } impl PopStateEventMethods for PopStateEvent { // https://html.spec.whatwg.org/multipage/#dom-popstateevent-state fn State(&self, _cx: JSContext) -> JSVal { self.state.get() } // https://dom.spec.whatwg.org/#dom-event-istrusted fn IsTrusted(&self) -> bool { self.event.IsTrusted() } }
use js::rust::HandleValue; use servo_atoms::Atom;
random_line_split
popstateevent.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ use crate::dom::bindings::codegen::Bindings::EventBinding::EventMethods; use crate::dom::bindings::codegen::Bindings::PopStateEventBinding; use crate::dom::bindings::codegen::Bindings::PopStateEventBinding::PopStateEventMethods; use crate::dom::bindings::error::Fallible; use crate::dom::bindings::inheritance::Castable; use crate::dom::bindings::reflector::reflect_dom_object; use crate::dom::bindings::root::DomRoot; use crate::dom::bindings::str::DOMString; use crate::dom::bindings::trace::RootedTraceableBox; use crate::dom::event::Event; use crate::dom::eventtarget::EventTarget; use crate::dom::window::Window; use crate::script_runtime::JSContext; use dom_struct::dom_struct; use js::jsapi::Heap; use js::jsval::JSVal; use js::rust::HandleValue; use servo_atoms::Atom; // https://html.spec.whatwg.org/multipage/#the-popstateevent-interface #[dom_struct] pub struct PopStateEvent { event: Event, #[ignore_malloc_size_of = "Defined in rust-mozjs"] state: Heap<JSVal>, } impl PopStateEvent { fn new_inherited() -> PopStateEvent
pub fn new_uninitialized(window: &Window) -> DomRoot<PopStateEvent> { reflect_dom_object(Box::new(PopStateEvent::new_inherited()), window) } pub fn new( window: &Window, type_: Atom, bubbles: bool, cancelable: bool, state: HandleValue, ) -> DomRoot<PopStateEvent> { let ev = PopStateEvent::new_uninitialized(window); ev.state.set(state.get()); { let event = ev.upcast::<Event>(); event.init_event(type_, bubbles, cancelable); } ev } #[allow(non_snake_case)] pub fn Constructor( window: &Window, type_: DOMString, init: RootedTraceableBox<PopStateEventBinding::PopStateEventInit>, ) -> Fallible<DomRoot<PopStateEvent>> { Ok(PopStateEvent::new( window, Atom::from(type_), init.parent.bubbles, init.parent.cancelable, init.state.handle(), )) } pub fn dispatch_jsval(target: &EventTarget, window: &Window, state: HandleValue) { let event = PopStateEvent::new(window, atom!("popstate"), false, false, state); event.upcast::<Event>().fire(target); } } impl PopStateEventMethods for PopStateEvent { // https://html.spec.whatwg.org/multipage/#dom-popstateevent-state fn State(&self, _cx: JSContext) -> JSVal { self.state.get() } // https://dom.spec.whatwg.org/#dom-event-istrusted fn IsTrusted(&self) -> bool { self.event.IsTrusted() } }
{ PopStateEvent { event: Event::new_inherited(), state: Heap::default(), } }
identifier_body
mining.py
#!/usr/bin/env python3 # Copyright (c) 2014-2016 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test mining RPCs - getmininginfo - getblocktemplate proposal mode - submitblock""" import copy from binascii import b2a_hex from decimal import Decimal from test_framework.blocktools import create_coinbase from test_framework.mininode import CBlock from test_framework.test_framework import IoPTestFramework from test_framework.util import assert_equal, assert_raises_rpc_error def b2x(b): return b2a_hex(b).decode('ascii') def assert_template(node, block, expect, rehash=True): if rehash: block.hashMerkleRoot = block.calc_merkle_root() rsp = node.getblocktemplate({'data': b2x(block.serialize()), 'mode': 'proposal'}) assert_equal(rsp, expect) class MiningTest(IoPTestFramework):
if __name__ == '__main__': MiningTest().main()
def set_test_params(self): self.num_nodes = 2 self.setup_clean_chain = False def run_test(self): node = self.nodes[0] self.log.info('getmininginfo') mining_info = node.getmininginfo() assert_equal(mining_info['blocks'], 200) assert_equal(mining_info['chain'], 'regtest') assert_equal(mining_info['currentblocktx'], 0) assert_equal(mining_info['currentblockweight'], 0) assert_equal(mining_info['difficulty'], Decimal('4.656542373906925E-10')) assert_equal(mining_info['networkhashps'], Decimal('0.003333333333333334')) assert_equal(mining_info['pooledtx'], 0) # Mine a block to leave initial block download node.generate(1) tmpl = node.getblocktemplate() self.log.info("getblocktemplate: Test capability advertised") assert 'proposal' in tmpl['capabilities'] assert 'coinbasetxn' not in tmpl coinbase_tx = create_coinbase(height=int(tmpl["height"]) + 1) # sequence numbers must not be max for nLockTime to have effect coinbase_tx.vin[0].nSequence = 2 ** 32 - 2 coinbase_tx.rehash() block = CBlock() block.nVersion = tmpl["version"] block.hashPrevBlock = int(tmpl["previousblockhash"], 16) block.nTime = tmpl["curtime"] block.nBits = int(tmpl["bits"], 16) block.nNonce = 0 block.vtx = [coinbase_tx] self.log.info("getblocktemplate: Test valid block") assert_template(node, block, None) self.log.info("submitblock: Test block decode failure") assert_raises_rpc_error(-22, "Block decode failed", node.submitblock, b2x(block.serialize()[:-15])) self.log.info("getblocktemplate: Test bad input hash for coinbase transaction") bad_block = copy.deepcopy(block) bad_block.vtx[0].vin[0].prevout.hash += 1 bad_block.vtx[0].rehash() assert_template(node, bad_block, 'bad-cb-missing') self.log.info("submitblock: Test invalid coinbase transaction") assert_raises_rpc_error(-22, "Block does not start with a coinbase", node.submitblock, b2x(bad_block.serialize())) self.log.info("getblocktemplate: Test truncated final transaction") assert_raises_rpc_error(-22, "Block decode failed", node.getblocktemplate, {'data': b2x(block.serialize()[:-1]), 'mode': 'proposal'}) self.log.info("getblocktemplate: Test duplicate transaction") bad_block = copy.deepcopy(block) bad_block.vtx.append(bad_block.vtx[0]) assert_template(node, bad_block, 'bad-txns-duplicate') self.log.info("getblocktemplate: Test invalid transaction") bad_block = copy.deepcopy(block) bad_tx = copy.deepcopy(bad_block.vtx[0]) bad_tx.vin[0].prevout.hash = 255 bad_tx.rehash() bad_block.vtx.append(bad_tx) assert_template(node, bad_block, 'bad-txns-inputs-missingorspent') self.log.info("getblocktemplate: Test nonfinal transaction") bad_block = copy.deepcopy(block) bad_block.vtx[0].nLockTime = 2 ** 32 - 1 bad_block.vtx[0].rehash() assert_template(node, bad_block, 'bad-txns-nonfinal') self.log.info("getblocktemplate: Test bad tx count") # The tx count is immediately after the block header TX_COUNT_OFFSET = 80 bad_block_sn = bytearray(block.serialize()) assert_equal(bad_block_sn[TX_COUNT_OFFSET], 1) bad_block_sn[TX_COUNT_OFFSET] += 1 assert_raises_rpc_error(-22, "Block decode failed", node.getblocktemplate, {'data': b2x(bad_block_sn), 'mode': 'proposal'}) self.log.info("getblocktemplate: Test bad bits") bad_block = copy.deepcopy(block) bad_block.nBits = 469762303 # impossible in the real world assert_template(node, bad_block, 'bad-diffbits') self.log.info("getblocktemplate: Test bad merkle root") bad_block = copy.deepcopy(block) bad_block.hashMerkleRoot += 1 assert_template(node, bad_block, 'bad-txnmrklroot', False) self.log.info("getblocktemplate: Test bad timestamps") bad_block = copy.deepcopy(block) bad_block.nTime = 2 ** 31 - 1 assert_template(node, bad_block, 'time-too-new') bad_block.nTime = 0 assert_template(node, bad_block, 'time-too-old') self.log.info("getblocktemplate: Test not best block") bad_block = copy.deepcopy(block) bad_block.hashPrevBlock = 123 assert_template(node, bad_block, 'inconclusive-not-best-prevblk')
identifier_body
mining.py
#!/usr/bin/env python3 # Copyright (c) 2014-2016 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test mining RPCs - getmininginfo - getblocktemplate proposal mode - submitblock""" import copy from binascii import b2a_hex from decimal import Decimal from test_framework.blocktools import create_coinbase from test_framework.mininode import CBlock from test_framework.test_framework import IoPTestFramework from test_framework.util import assert_equal, assert_raises_rpc_error def b2x(b): return b2a_hex(b).decode('ascii') def assert_template(node, block, expect, rehash=True): if rehash: block.hashMerkleRoot = block.calc_merkle_root() rsp = node.getblocktemplate({'data': b2x(block.serialize()), 'mode': 'proposal'}) assert_equal(rsp, expect) class
(IoPTestFramework): def set_test_params(self): self.num_nodes = 2 self.setup_clean_chain = False def run_test(self): node = self.nodes[0] self.log.info('getmininginfo') mining_info = node.getmininginfo() assert_equal(mining_info['blocks'], 200) assert_equal(mining_info['chain'], 'regtest') assert_equal(mining_info['currentblocktx'], 0) assert_equal(mining_info['currentblockweight'], 0) assert_equal(mining_info['difficulty'], Decimal('4.656542373906925E-10')) assert_equal(mining_info['networkhashps'], Decimal('0.003333333333333334')) assert_equal(mining_info['pooledtx'], 0) # Mine a block to leave initial block download node.generate(1) tmpl = node.getblocktemplate() self.log.info("getblocktemplate: Test capability advertised") assert 'proposal' in tmpl['capabilities'] assert 'coinbasetxn' not in tmpl coinbase_tx = create_coinbase(height=int(tmpl["height"]) + 1) # sequence numbers must not be max for nLockTime to have effect coinbase_tx.vin[0].nSequence = 2 ** 32 - 2 coinbase_tx.rehash() block = CBlock() block.nVersion = tmpl["version"] block.hashPrevBlock = int(tmpl["previousblockhash"], 16) block.nTime = tmpl["curtime"] block.nBits = int(tmpl["bits"], 16) block.nNonce = 0 block.vtx = [coinbase_tx] self.log.info("getblocktemplate: Test valid block") assert_template(node, block, None) self.log.info("submitblock: Test block decode failure") assert_raises_rpc_error(-22, "Block decode failed", node.submitblock, b2x(block.serialize()[:-15])) self.log.info("getblocktemplate: Test bad input hash for coinbase transaction") bad_block = copy.deepcopy(block) bad_block.vtx[0].vin[0].prevout.hash += 1 bad_block.vtx[0].rehash() assert_template(node, bad_block, 'bad-cb-missing') self.log.info("submitblock: Test invalid coinbase transaction") assert_raises_rpc_error(-22, "Block does not start with a coinbase", node.submitblock, b2x(bad_block.serialize())) self.log.info("getblocktemplate: Test truncated final transaction") assert_raises_rpc_error(-22, "Block decode failed", node.getblocktemplate, {'data': b2x(block.serialize()[:-1]), 'mode': 'proposal'}) self.log.info("getblocktemplate: Test duplicate transaction") bad_block = copy.deepcopy(block) bad_block.vtx.append(bad_block.vtx[0]) assert_template(node, bad_block, 'bad-txns-duplicate') self.log.info("getblocktemplate: Test invalid transaction") bad_block = copy.deepcopy(block) bad_tx = copy.deepcopy(bad_block.vtx[0]) bad_tx.vin[0].prevout.hash = 255 bad_tx.rehash() bad_block.vtx.append(bad_tx) assert_template(node, bad_block, 'bad-txns-inputs-missingorspent') self.log.info("getblocktemplate: Test nonfinal transaction") bad_block = copy.deepcopy(block) bad_block.vtx[0].nLockTime = 2 ** 32 - 1 bad_block.vtx[0].rehash() assert_template(node, bad_block, 'bad-txns-nonfinal') self.log.info("getblocktemplate: Test bad tx count") # The tx count is immediately after the block header TX_COUNT_OFFSET = 80 bad_block_sn = bytearray(block.serialize()) assert_equal(bad_block_sn[TX_COUNT_OFFSET], 1) bad_block_sn[TX_COUNT_OFFSET] += 1 assert_raises_rpc_error(-22, "Block decode failed", node.getblocktemplate, {'data': b2x(bad_block_sn), 'mode': 'proposal'}) self.log.info("getblocktemplate: Test bad bits") bad_block = copy.deepcopy(block) bad_block.nBits = 469762303 # impossible in the real world assert_template(node, bad_block, 'bad-diffbits') self.log.info("getblocktemplate: Test bad merkle root") bad_block = copy.deepcopy(block) bad_block.hashMerkleRoot += 1 assert_template(node, bad_block, 'bad-txnmrklroot', False) self.log.info("getblocktemplate: Test bad timestamps") bad_block = copy.deepcopy(block) bad_block.nTime = 2 ** 31 - 1 assert_template(node, bad_block, 'time-too-new') bad_block.nTime = 0 assert_template(node, bad_block, 'time-too-old') self.log.info("getblocktemplate: Test not best block") bad_block = copy.deepcopy(block) bad_block.hashPrevBlock = 123 assert_template(node, bad_block, 'inconclusive-not-best-prevblk') if __name__ == '__main__': MiningTest().main()
MiningTest
identifier_name
mining.py
#!/usr/bin/env python3 # Copyright (c) 2014-2016 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test mining RPCs - getmininginfo - getblocktemplate proposal mode - submitblock""" import copy from binascii import b2a_hex from decimal import Decimal from test_framework.blocktools import create_coinbase from test_framework.mininode import CBlock from test_framework.test_framework import IoPTestFramework from test_framework.util import assert_equal, assert_raises_rpc_error def b2x(b): return b2a_hex(b).decode('ascii') def assert_template(node, block, expect, rehash=True): if rehash: block.hashMerkleRoot = block.calc_merkle_root() rsp = node.getblocktemplate({'data': b2x(block.serialize()), 'mode': 'proposal'}) assert_equal(rsp, expect) class MiningTest(IoPTestFramework): def set_test_params(self): self.num_nodes = 2 self.setup_clean_chain = False def run_test(self): node = self.nodes[0]
mining_info = node.getmininginfo() assert_equal(mining_info['blocks'], 200) assert_equal(mining_info['chain'], 'regtest') assert_equal(mining_info['currentblocktx'], 0) assert_equal(mining_info['currentblockweight'], 0) assert_equal(mining_info['difficulty'], Decimal('4.656542373906925E-10')) assert_equal(mining_info['networkhashps'], Decimal('0.003333333333333334')) assert_equal(mining_info['pooledtx'], 0) # Mine a block to leave initial block download node.generate(1) tmpl = node.getblocktemplate() self.log.info("getblocktemplate: Test capability advertised") assert 'proposal' in tmpl['capabilities'] assert 'coinbasetxn' not in tmpl coinbase_tx = create_coinbase(height=int(tmpl["height"]) + 1) # sequence numbers must not be max for nLockTime to have effect coinbase_tx.vin[0].nSequence = 2 ** 32 - 2 coinbase_tx.rehash() block = CBlock() block.nVersion = tmpl["version"] block.hashPrevBlock = int(tmpl["previousblockhash"], 16) block.nTime = tmpl["curtime"] block.nBits = int(tmpl["bits"], 16) block.nNonce = 0 block.vtx = [coinbase_tx] self.log.info("getblocktemplate: Test valid block") assert_template(node, block, None) self.log.info("submitblock: Test block decode failure") assert_raises_rpc_error(-22, "Block decode failed", node.submitblock, b2x(block.serialize()[:-15])) self.log.info("getblocktemplate: Test bad input hash for coinbase transaction") bad_block = copy.deepcopy(block) bad_block.vtx[0].vin[0].prevout.hash += 1 bad_block.vtx[0].rehash() assert_template(node, bad_block, 'bad-cb-missing') self.log.info("submitblock: Test invalid coinbase transaction") assert_raises_rpc_error(-22, "Block does not start with a coinbase", node.submitblock, b2x(bad_block.serialize())) self.log.info("getblocktemplate: Test truncated final transaction") assert_raises_rpc_error(-22, "Block decode failed", node.getblocktemplate, {'data': b2x(block.serialize()[:-1]), 'mode': 'proposal'}) self.log.info("getblocktemplate: Test duplicate transaction") bad_block = copy.deepcopy(block) bad_block.vtx.append(bad_block.vtx[0]) assert_template(node, bad_block, 'bad-txns-duplicate') self.log.info("getblocktemplate: Test invalid transaction") bad_block = copy.deepcopy(block) bad_tx = copy.deepcopy(bad_block.vtx[0]) bad_tx.vin[0].prevout.hash = 255 bad_tx.rehash() bad_block.vtx.append(bad_tx) assert_template(node, bad_block, 'bad-txns-inputs-missingorspent') self.log.info("getblocktemplate: Test nonfinal transaction") bad_block = copy.deepcopy(block) bad_block.vtx[0].nLockTime = 2 ** 32 - 1 bad_block.vtx[0].rehash() assert_template(node, bad_block, 'bad-txns-nonfinal') self.log.info("getblocktemplate: Test bad tx count") # The tx count is immediately after the block header TX_COUNT_OFFSET = 80 bad_block_sn = bytearray(block.serialize()) assert_equal(bad_block_sn[TX_COUNT_OFFSET], 1) bad_block_sn[TX_COUNT_OFFSET] += 1 assert_raises_rpc_error(-22, "Block decode failed", node.getblocktemplate, {'data': b2x(bad_block_sn), 'mode': 'proposal'}) self.log.info("getblocktemplate: Test bad bits") bad_block = copy.deepcopy(block) bad_block.nBits = 469762303 # impossible in the real world assert_template(node, bad_block, 'bad-diffbits') self.log.info("getblocktemplate: Test bad merkle root") bad_block = copy.deepcopy(block) bad_block.hashMerkleRoot += 1 assert_template(node, bad_block, 'bad-txnmrklroot', False) self.log.info("getblocktemplate: Test bad timestamps") bad_block = copy.deepcopy(block) bad_block.nTime = 2 ** 31 - 1 assert_template(node, bad_block, 'time-too-new') bad_block.nTime = 0 assert_template(node, bad_block, 'time-too-old') self.log.info("getblocktemplate: Test not best block") bad_block = copy.deepcopy(block) bad_block.hashPrevBlock = 123 assert_template(node, bad_block, 'inconclusive-not-best-prevblk') if __name__ == '__main__': MiningTest().main()
self.log.info('getmininginfo')
random_line_split
mining.py
#!/usr/bin/env python3 # Copyright (c) 2014-2016 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test mining RPCs - getmininginfo - getblocktemplate proposal mode - submitblock""" import copy from binascii import b2a_hex from decimal import Decimal from test_framework.blocktools import create_coinbase from test_framework.mininode import CBlock from test_framework.test_framework import IoPTestFramework from test_framework.util import assert_equal, assert_raises_rpc_error def b2x(b): return b2a_hex(b).decode('ascii') def assert_template(node, block, expect, rehash=True): if rehash: block.hashMerkleRoot = block.calc_merkle_root() rsp = node.getblocktemplate({'data': b2x(block.serialize()), 'mode': 'proposal'}) assert_equal(rsp, expect) class MiningTest(IoPTestFramework): def set_test_params(self): self.num_nodes = 2 self.setup_clean_chain = False def run_test(self): node = self.nodes[0] self.log.info('getmininginfo') mining_info = node.getmininginfo() assert_equal(mining_info['blocks'], 200) assert_equal(mining_info['chain'], 'regtest') assert_equal(mining_info['currentblocktx'], 0) assert_equal(mining_info['currentblockweight'], 0) assert_equal(mining_info['difficulty'], Decimal('4.656542373906925E-10')) assert_equal(mining_info['networkhashps'], Decimal('0.003333333333333334')) assert_equal(mining_info['pooledtx'], 0) # Mine a block to leave initial block download node.generate(1) tmpl = node.getblocktemplate() self.log.info("getblocktemplate: Test capability advertised") assert 'proposal' in tmpl['capabilities'] assert 'coinbasetxn' not in tmpl coinbase_tx = create_coinbase(height=int(tmpl["height"]) + 1) # sequence numbers must not be max for nLockTime to have effect coinbase_tx.vin[0].nSequence = 2 ** 32 - 2 coinbase_tx.rehash() block = CBlock() block.nVersion = tmpl["version"] block.hashPrevBlock = int(tmpl["previousblockhash"], 16) block.nTime = tmpl["curtime"] block.nBits = int(tmpl["bits"], 16) block.nNonce = 0 block.vtx = [coinbase_tx] self.log.info("getblocktemplate: Test valid block") assert_template(node, block, None) self.log.info("submitblock: Test block decode failure") assert_raises_rpc_error(-22, "Block decode failed", node.submitblock, b2x(block.serialize()[:-15])) self.log.info("getblocktemplate: Test bad input hash for coinbase transaction") bad_block = copy.deepcopy(block) bad_block.vtx[0].vin[0].prevout.hash += 1 bad_block.vtx[0].rehash() assert_template(node, bad_block, 'bad-cb-missing') self.log.info("submitblock: Test invalid coinbase transaction") assert_raises_rpc_error(-22, "Block does not start with a coinbase", node.submitblock, b2x(bad_block.serialize())) self.log.info("getblocktemplate: Test truncated final transaction") assert_raises_rpc_error(-22, "Block decode failed", node.getblocktemplate, {'data': b2x(block.serialize()[:-1]), 'mode': 'proposal'}) self.log.info("getblocktemplate: Test duplicate transaction") bad_block = copy.deepcopy(block) bad_block.vtx.append(bad_block.vtx[0]) assert_template(node, bad_block, 'bad-txns-duplicate') self.log.info("getblocktemplate: Test invalid transaction") bad_block = copy.deepcopy(block) bad_tx = copy.deepcopy(bad_block.vtx[0]) bad_tx.vin[0].prevout.hash = 255 bad_tx.rehash() bad_block.vtx.append(bad_tx) assert_template(node, bad_block, 'bad-txns-inputs-missingorspent') self.log.info("getblocktemplate: Test nonfinal transaction") bad_block = copy.deepcopy(block) bad_block.vtx[0].nLockTime = 2 ** 32 - 1 bad_block.vtx[0].rehash() assert_template(node, bad_block, 'bad-txns-nonfinal') self.log.info("getblocktemplate: Test bad tx count") # The tx count is immediately after the block header TX_COUNT_OFFSET = 80 bad_block_sn = bytearray(block.serialize()) assert_equal(bad_block_sn[TX_COUNT_OFFSET], 1) bad_block_sn[TX_COUNT_OFFSET] += 1 assert_raises_rpc_error(-22, "Block decode failed", node.getblocktemplate, {'data': b2x(bad_block_sn), 'mode': 'proposal'}) self.log.info("getblocktemplate: Test bad bits") bad_block = copy.deepcopy(block) bad_block.nBits = 469762303 # impossible in the real world assert_template(node, bad_block, 'bad-diffbits') self.log.info("getblocktemplate: Test bad merkle root") bad_block = copy.deepcopy(block) bad_block.hashMerkleRoot += 1 assert_template(node, bad_block, 'bad-txnmrklroot', False) self.log.info("getblocktemplate: Test bad timestamps") bad_block = copy.deepcopy(block) bad_block.nTime = 2 ** 31 - 1 assert_template(node, bad_block, 'time-too-new') bad_block.nTime = 0 assert_template(node, bad_block, 'time-too-old') self.log.info("getblocktemplate: Test not best block") bad_block = copy.deepcopy(block) bad_block.hashPrevBlock = 123 assert_template(node, bad_block, 'inconclusive-not-best-prevblk') if __name__ == '__main__':
MiningTest().main()
conditional_block
config.py
# -*- coding: utf-8 -*- ''' .. module:: genomics.config :synopsis: library configuration :noindex: :copyright: Copyright 2014 by Tiago Antao :license: GNU Affero, see LICENSE for details .. moduleauthor:: Tiago Antao <tra@popgen.net> ''' import os import configparser as cp config_file = os.path.expanduser('~/.config/pygenomics/main.conf') # This can be configured before loading of the main module to read another file class Config(object): '''Configuration object :param config_file: The config file to use The default config file is defined above and can be changed before doing import genomics Configuration parameters are separated by section **Section main** * **mr_dir** Directory where temporary map_reduce communication is stored * **grid** Grid type (Local) **Section grid.local** The parameters for grid type Local. Currently limit (see :py:class:`genomics.parallel.executor.Local`) ''' def __init__(self, config_file=config_file): self.config_file = config_file def load_config(self): config = cp.ConfigParser() config.read(self.config_file) try: self.mr_dir = config.get('main', 'mr_dir') self.grid = config.get('main', 'grid') if self.grid == 'Local': self.grid_limit = config.get('grid.local', 'limit') if self.grid_limit.find('.') > -1: self.grid_limit = float(self.grid_limit) else:
except cp.NoSectionError: self.mr_dir = '/tmp' self.grid = 'Local' self.grid_limit = 1.0
self.grid_limit = int(self.grid_limit)
conditional_block
config.py
# -*- coding: utf-8 -*- ''' .. module:: genomics.config :synopsis: library configuration :noindex: :copyright: Copyright 2014 by Tiago Antao :license: GNU Affero, see LICENSE for details .. moduleauthor:: Tiago Antao <tra@popgen.net> ''' import os import configparser as cp config_file = os.path.expanduser('~/.config/pygenomics/main.conf') # This can be configured before loading of the main module to read another file class Config(object): '''Configuration object :param config_file: The config file to use The default config file is defined above and can be changed before doing import genomics Configuration parameters are separated by section **Section main** * **mr_dir** Directory where temporary map_reduce communication is stored * **grid** Grid type (Local) **Section grid.local** The parameters for grid type Local. Currently limit (see :py:class:`genomics.parallel.executor.Local`) ''' def
(self, config_file=config_file): self.config_file = config_file def load_config(self): config = cp.ConfigParser() config.read(self.config_file) try: self.mr_dir = config.get('main', 'mr_dir') self.grid = config.get('main', 'grid') if self.grid == 'Local': self.grid_limit = config.get('grid.local', 'limit') if self.grid_limit.find('.') > -1: self.grid_limit = float(self.grid_limit) else: self.grid_limit = int(self.grid_limit) except cp.NoSectionError: self.mr_dir = '/tmp' self.grid = 'Local' self.grid_limit = 1.0
__init__
identifier_name
config.py
# -*- coding: utf-8 -*- ''' .. module:: genomics.config :synopsis: library configuration :noindex: :copyright: Copyright 2014 by Tiago Antao :license: GNU Affero, see LICENSE for details .. moduleauthor:: Tiago Antao <tra@popgen.net> ''' import os import configparser as cp config_file = os.path.expanduser('~/.config/pygenomics/main.conf') # This can be configured before loading of the main module to read another file class Config(object): '''Configuration object :param config_file: The config file to use The default config file is defined above and can be changed before doing import genomics Configuration parameters are separated by section **Section main** * **mr_dir** Directory where temporary map_reduce communication is stored * **grid** Grid type (Local) **Section grid.local** The parameters for grid type Local. Currently limit (see :py:class:`genomics.parallel.executor.Local`) ''' def __init__(self, config_file=config_file):
def load_config(self): config = cp.ConfigParser() config.read(self.config_file) try: self.mr_dir = config.get('main', 'mr_dir') self.grid = config.get('main', 'grid') if self.grid == 'Local': self.grid_limit = config.get('grid.local', 'limit') if self.grid_limit.find('.') > -1: self.grid_limit = float(self.grid_limit) else: self.grid_limit = int(self.grid_limit) except cp.NoSectionError: self.mr_dir = '/tmp' self.grid = 'Local' self.grid_limit = 1.0
self.config_file = config_file
identifier_body
config.py
# -*- coding: utf-8 -*- ''' .. module:: genomics.config :synopsis: library configuration :noindex: :copyright: Copyright 2014 by Tiago Antao :license: GNU Affero, see LICENSE for details .. moduleauthor:: Tiago Antao <tra@popgen.net> ''' import os import configparser as cp config_file = os.path.expanduser('~/.config/pygenomics/main.conf') # This can be configured before loading of the main module to read another file class Config(object): '''Configuration object
Configuration parameters are separated by section **Section main** * **mr_dir** Directory where temporary map_reduce communication is stored * **grid** Grid type (Local) **Section grid.local** The parameters for grid type Local. Currently limit (see :py:class:`genomics.parallel.executor.Local`) ''' def __init__(self, config_file=config_file): self.config_file = config_file def load_config(self): config = cp.ConfigParser() config.read(self.config_file) try: self.mr_dir = config.get('main', 'mr_dir') self.grid = config.get('main', 'grid') if self.grid == 'Local': self.grid_limit = config.get('grid.local', 'limit') if self.grid_limit.find('.') > -1: self.grid_limit = float(self.grid_limit) else: self.grid_limit = int(self.grid_limit) except cp.NoSectionError: self.mr_dir = '/tmp' self.grid = 'Local' self.grid_limit = 1.0
:param config_file: The config file to use The default config file is defined above and can be changed before doing import genomics
random_line_split
dy.js
// This is the base browser library for dy.js. It is all that is needed in the // browser for modules written for dy.js to work. // // In development you'd probably also want to include the dy/ext/reload // extension to add dynamic reloading functionality. However, in production // this is the *only* code you need (plus a `dy.load()` somewhere) for your // dy.js-compatible code to work. (function (window) { var dy = function (name, dependencies, initializer) { var self = dy.retrieveOrCreateModule(name) // Ensure all the dependencies exist dependencies = dependencies.map(function (dep) { return dy.retrieveOrCreateModule(dep) }) initializer.apply(self, dependencies) } // Registry of all active modules dy.modules = {} dy.retrieveOrCreateModule = function (name) { if (dy.modules[name] === undefined) { // Set up new instance dy.modules[name] = {} } // Retrieve the instance of the module return dy.modules[name] } // Trigger _load() hook on all loaded modules dy.load = function () { for (var name in dy.modules) { if (dy.modules.hasOwnProperty(name) && dy.modules[name]._load !== undefined)
} } if (window) { window.dy = dy; } })(window);
{ dy.modules[name]._load() }
conditional_block
dy.js
// This is the base browser library for dy.js. It is all that is needed in the // browser for modules written for dy.js to work. // // In development you'd probably also want to include the dy/ext/reload // extension to add dynamic reloading functionality. However, in production // this is the *only* code you need (plus a `dy.load()` somewhere) for your // dy.js-compatible code to work. (function (window) { var dy = function (name, dependencies, initializer) { var self = dy.retrieveOrCreateModule(name) // Ensure all the dependencies exist dependencies = dependencies.map(function (dep) { return dy.retrieveOrCreateModule(dep)
initializer.apply(self, dependencies) } // Registry of all active modules dy.modules = {} dy.retrieveOrCreateModule = function (name) { if (dy.modules[name] === undefined) { // Set up new instance dy.modules[name] = {} } // Retrieve the instance of the module return dy.modules[name] } // Trigger _load() hook on all loaded modules dy.load = function () { for (var name in dy.modules) { if (dy.modules.hasOwnProperty(name) && dy.modules[name]._load !== undefined) { dy.modules[name]._load() } } } if (window) { window.dy = dy; } })(window);
})
random_line_split
test_auto_MRISPreproc.py
# AUTO-GENERATED by tools/checkspecs.py - DO NOT EDIT from ....testing import assert_equal from ..model import MRISPreproc
input_map = dict(args=dict(argstr='%s', ), environ=dict(nohash=True, usedefault=True, ), fsgd_file=dict(argstr='--fsgd %s', xor=(u'subjects', u'fsgd_file', u'subject_file'), ), fwhm=dict(argstr='--fwhm %f', xor=[u'num_iters'], ), fwhm_source=dict(argstr='--fwhm-src %f', xor=[u'num_iters_source'], ), hemi=dict(argstr='--hemi %s', mandatory=True, ), ignore_exception=dict(nohash=True, usedefault=True, ), num_iters=dict(argstr='--niters %d', xor=[u'fwhm'], ), num_iters_source=dict(argstr='--niterssrc %d', xor=[u'fwhm_source'], ), out_file=dict(argstr='--out %s', genfile=True, ), proj_frac=dict(argstr='--projfrac %s', ), smooth_cortex_only=dict(argstr='--smooth-cortex-only', ), source_format=dict(argstr='--srcfmt %s', ), subject_file=dict(argstr='--f %s', xor=(u'subjects', u'fsgd_file', u'subject_file'), ), subjects=dict(argstr='--s %s...', xor=(u'subjects', u'fsgd_file', u'subject_file'), ), subjects_dir=dict(), surf_area=dict(argstr='--area %s', xor=(u'surf_measure', u'surf_measure_file', u'surf_area'), ), surf_dir=dict(argstr='--surfdir %s', ), surf_measure=dict(argstr='--meas %s', xor=(u'surf_measure', u'surf_measure_file', u'surf_area'), ), surf_measure_file=dict(argstr='--is %s...', xor=(u'surf_measure', u'surf_measure_file', u'surf_area'), ), target=dict(argstr='--target %s', mandatory=True, ), terminal_output=dict(nohash=True, ), vol_measure_file=dict(argstr='--iv %s %s...', ), ) inputs = MRISPreproc.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): yield assert_equal, getattr(inputs.traits()[key], metakey), value def test_MRISPreproc_outputs(): output_map = dict(out_file=dict(), ) outputs = MRISPreproc.output_spec() for key, metadata in list(output_map.items()): for metakey, value in list(metadata.items()): yield assert_equal, getattr(outputs.traits()[key], metakey), value
def test_MRISPreproc_inputs():
random_line_split
test_auto_MRISPreproc.py
# AUTO-GENERATED by tools/checkspecs.py - DO NOT EDIT from ....testing import assert_equal from ..model import MRISPreproc def
(): input_map = dict(args=dict(argstr='%s', ), environ=dict(nohash=True, usedefault=True, ), fsgd_file=dict(argstr='--fsgd %s', xor=(u'subjects', u'fsgd_file', u'subject_file'), ), fwhm=dict(argstr='--fwhm %f', xor=[u'num_iters'], ), fwhm_source=dict(argstr='--fwhm-src %f', xor=[u'num_iters_source'], ), hemi=dict(argstr='--hemi %s', mandatory=True, ), ignore_exception=dict(nohash=True, usedefault=True, ), num_iters=dict(argstr='--niters %d', xor=[u'fwhm'], ), num_iters_source=dict(argstr='--niterssrc %d', xor=[u'fwhm_source'], ), out_file=dict(argstr='--out %s', genfile=True, ), proj_frac=dict(argstr='--projfrac %s', ), smooth_cortex_only=dict(argstr='--smooth-cortex-only', ), source_format=dict(argstr='--srcfmt %s', ), subject_file=dict(argstr='--f %s', xor=(u'subjects', u'fsgd_file', u'subject_file'), ), subjects=dict(argstr='--s %s...', xor=(u'subjects', u'fsgd_file', u'subject_file'), ), subjects_dir=dict(), surf_area=dict(argstr='--area %s', xor=(u'surf_measure', u'surf_measure_file', u'surf_area'), ), surf_dir=dict(argstr='--surfdir %s', ), surf_measure=dict(argstr='--meas %s', xor=(u'surf_measure', u'surf_measure_file', u'surf_area'), ), surf_measure_file=dict(argstr='--is %s...', xor=(u'surf_measure', u'surf_measure_file', u'surf_area'), ), target=dict(argstr='--target %s', mandatory=True, ), terminal_output=dict(nohash=True, ), vol_measure_file=dict(argstr='--iv %s %s...', ), ) inputs = MRISPreproc.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): yield assert_equal, getattr(inputs.traits()[key], metakey), value def test_MRISPreproc_outputs(): output_map = dict(out_file=dict(), ) outputs = MRISPreproc.output_spec() for key, metadata in list(output_map.items()): for metakey, value in list(metadata.items()): yield assert_equal, getattr(outputs.traits()[key], metakey), value
test_MRISPreproc_inputs
identifier_name
test_auto_MRISPreproc.py
# AUTO-GENERATED by tools/checkspecs.py - DO NOT EDIT from ....testing import assert_equal from ..model import MRISPreproc def test_MRISPreproc_inputs(): input_map = dict(args=dict(argstr='%s', ), environ=dict(nohash=True, usedefault=True, ), fsgd_file=dict(argstr='--fsgd %s', xor=(u'subjects', u'fsgd_file', u'subject_file'), ), fwhm=dict(argstr='--fwhm %f', xor=[u'num_iters'], ), fwhm_source=dict(argstr='--fwhm-src %f', xor=[u'num_iters_source'], ), hemi=dict(argstr='--hemi %s', mandatory=True, ), ignore_exception=dict(nohash=True, usedefault=True, ), num_iters=dict(argstr='--niters %d', xor=[u'fwhm'], ), num_iters_source=dict(argstr='--niterssrc %d', xor=[u'fwhm_source'], ), out_file=dict(argstr='--out %s', genfile=True, ), proj_frac=dict(argstr='--projfrac %s', ), smooth_cortex_only=dict(argstr='--smooth-cortex-only', ), source_format=dict(argstr='--srcfmt %s', ), subject_file=dict(argstr='--f %s', xor=(u'subjects', u'fsgd_file', u'subject_file'), ), subjects=dict(argstr='--s %s...', xor=(u'subjects', u'fsgd_file', u'subject_file'), ), subjects_dir=dict(), surf_area=dict(argstr='--area %s', xor=(u'surf_measure', u'surf_measure_file', u'surf_area'), ), surf_dir=dict(argstr='--surfdir %s', ), surf_measure=dict(argstr='--meas %s', xor=(u'surf_measure', u'surf_measure_file', u'surf_area'), ), surf_measure_file=dict(argstr='--is %s...', xor=(u'surf_measure', u'surf_measure_file', u'surf_area'), ), target=dict(argstr='--target %s', mandatory=True, ), terminal_output=dict(nohash=True, ), vol_measure_file=dict(argstr='--iv %s %s...', ), ) inputs = MRISPreproc.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): yield assert_equal, getattr(inputs.traits()[key], metakey), value def test_MRISPreproc_outputs(): output_map = dict(out_file=dict(), ) outputs = MRISPreproc.output_spec() for key, metadata in list(output_map.items()):
for metakey, value in list(metadata.items()): yield assert_equal, getattr(outputs.traits()[key], metakey), value
conditional_block
test_auto_MRISPreproc.py
# AUTO-GENERATED by tools/checkspecs.py - DO NOT EDIT from ....testing import assert_equal from ..model import MRISPreproc def test_MRISPreproc_inputs(): input_map = dict(args=dict(argstr='%s', ), environ=dict(nohash=True, usedefault=True, ), fsgd_file=dict(argstr='--fsgd %s', xor=(u'subjects', u'fsgd_file', u'subject_file'), ), fwhm=dict(argstr='--fwhm %f', xor=[u'num_iters'], ), fwhm_source=dict(argstr='--fwhm-src %f', xor=[u'num_iters_source'], ), hemi=dict(argstr='--hemi %s', mandatory=True, ), ignore_exception=dict(nohash=True, usedefault=True, ), num_iters=dict(argstr='--niters %d', xor=[u'fwhm'], ), num_iters_source=dict(argstr='--niterssrc %d', xor=[u'fwhm_source'], ), out_file=dict(argstr='--out %s', genfile=True, ), proj_frac=dict(argstr='--projfrac %s', ), smooth_cortex_only=dict(argstr='--smooth-cortex-only', ), source_format=dict(argstr='--srcfmt %s', ), subject_file=dict(argstr='--f %s', xor=(u'subjects', u'fsgd_file', u'subject_file'), ), subjects=dict(argstr='--s %s...', xor=(u'subjects', u'fsgd_file', u'subject_file'), ), subjects_dir=dict(), surf_area=dict(argstr='--area %s', xor=(u'surf_measure', u'surf_measure_file', u'surf_area'), ), surf_dir=dict(argstr='--surfdir %s', ), surf_measure=dict(argstr='--meas %s', xor=(u'surf_measure', u'surf_measure_file', u'surf_area'), ), surf_measure_file=dict(argstr='--is %s...', xor=(u'surf_measure', u'surf_measure_file', u'surf_area'), ), target=dict(argstr='--target %s', mandatory=True, ), terminal_output=dict(nohash=True, ), vol_measure_file=dict(argstr='--iv %s %s...', ), ) inputs = MRISPreproc.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): yield assert_equal, getattr(inputs.traits()[key], metakey), value def test_MRISPreproc_outputs():
output_map = dict(out_file=dict(), ) outputs = MRISPreproc.output_spec() for key, metadata in list(output_map.items()): for metakey, value in list(metadata.items()): yield assert_equal, getattr(outputs.traits()[key], metakey), value
identifier_body
debug.rs
// Copyright (c) 2017 Chef Software Inc. and/or applicable contributors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use std::collections::{HashMap, HashSet}; use std::fmt::Debug; use std::path::PathBuf; use std::ffi::OsString; pub trait IndentedToString { fn indented_to_string(&self, spaces: &str, repeat: usize) -> String; } // indented to string macro_rules! its( {$value:expr, $spaces:expr, $repeat:expr} => { { $value.indented_to_string($spaces, $repeat) } }; ); // default indented to string macro_rules! dits( {$value:expr} => { its!($value, " ", 0) }; ); pub struct IndentedStructFormatter { name: String, fields: Vec<(String, String)>, spaces: String, repeat: usize, } impl IndentedStructFormatter { pub fn new(name: &str, spaces: &str, repeat: usize) -> Self { Self { name: name.to_string(), fields: Vec::new(), spaces: spaces.to_string(), repeat: repeat, } } pub fn add_string(&mut self, field_name: &str, field_value: String) { self.fields.push((field_name.to_string(), field_value)); } pub fn
<T: Debug>(&mut self, field_name: &str, field_value: &T) { self.add_string(field_name, format!("{:?}", field_value)); } pub fn add<T: IndentedToString>(&mut self, field_name: &str, field_value: &T) { let spaces = self.spaces.to_string(); let repeat = self.repeat + 1; self.add_string(field_name, its!(field_value, &spaces, repeat)); } pub fn fmt(&mut self) -> String { let indent = self.spaces.repeat(self.repeat); let field_indent = self.spaces.repeat(self.repeat + 1); /* 5 - space between name and opening brace, opening brace, newline * after opening brace, closing brace, terminating zero */ let mut capacity = self.name.len() + 5 + indent.len(); for pair in &self.fields { /* 4 - colon after name, space, comma, newline after value */ capacity += field_indent.len() + pair.0.len() + 4 + pair.1.len(); } let mut str = String::with_capacity(capacity); str.push_str(&format!("{} {{\n", self.name,)); for pair in &self.fields { str.push_str(&format!("{}{}: {},\n", field_indent, pair.0, pair.1)); } str.push_str(&format!("{}}}", indent)); str } } impl IndentedToString for u32 { fn indented_to_string(&self, _: &str, _: usize) -> String { self.to_string() } } impl IndentedToString for PathBuf { fn indented_to_string(&self, _: &str, _: usize) -> String { self.display().to_string() } } impl IndentedToString for OsString { fn indented_to_string(&self, _: &str, _: usize) -> String { self.to_string_lossy().to_string() } } impl<T: IndentedToString> IndentedToString for Option<T> { fn indented_to_string(&self, spaces: &str, repeat: usize) -> String { match self { &Some(ref v) => format!("Some({})", its!(v, spaces, repeat)), &None => "None".to_string(), } } } impl<V: IndentedToString> IndentedToString for HashMap<PathBuf, V> { fn indented_to_string(&self, spaces: &str, repeat: usize) -> String { let mut paths = self.keys().collect::<Vec<&PathBuf>>(); paths.sort(); let indent = spaces.repeat(repeat + 1); let mut str = String::new(); str.push_str("{\n"); for path in paths { str.push_str(&format!( "{}{}: {},\n", indent, path.display(), its!(self.get(path).unwrap(), spaces, repeat + 1), )); } str.push_str(&format!("{}}}", spaces.repeat(repeat))); str } } impl IndentedToString for HashSet<PathBuf> { fn indented_to_string(&self, spaces: &str, repeat: usize) -> String { let mut paths = self.iter().collect::<Vec<&PathBuf>>(); paths.sort(); let indent = spaces.repeat(repeat + 1); let mut str = String::new(); str.push_str("{\n"); for path in paths { str.push_str(&format!( "{}{},\n", indent, path.display(), )); } str.push_str(&format!("{}}}", spaces.repeat(repeat))); str } }
add_debug
identifier_name
debug.rs
// Copyright (c) 2017 Chef Software Inc. and/or applicable contributors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use std::collections::{HashMap, HashSet}; use std::fmt::Debug; use std::path::PathBuf; use std::ffi::OsString; pub trait IndentedToString { fn indented_to_string(&self, spaces: &str, repeat: usize) -> String; } // indented to string macro_rules! its( {$value:expr, $spaces:expr, $repeat:expr} => { { $value.indented_to_string($spaces, $repeat) } }; ); // default indented to string macro_rules! dits( {$value:expr} => {
pub struct IndentedStructFormatter { name: String, fields: Vec<(String, String)>, spaces: String, repeat: usize, } impl IndentedStructFormatter { pub fn new(name: &str, spaces: &str, repeat: usize) -> Self { Self { name: name.to_string(), fields: Vec::new(), spaces: spaces.to_string(), repeat: repeat, } } pub fn add_string(&mut self, field_name: &str, field_value: String) { self.fields.push((field_name.to_string(), field_value)); } pub fn add_debug<T: Debug>(&mut self, field_name: &str, field_value: &T) { self.add_string(field_name, format!("{:?}", field_value)); } pub fn add<T: IndentedToString>(&mut self, field_name: &str, field_value: &T) { let spaces = self.spaces.to_string(); let repeat = self.repeat + 1; self.add_string(field_name, its!(field_value, &spaces, repeat)); } pub fn fmt(&mut self) -> String { let indent = self.spaces.repeat(self.repeat); let field_indent = self.spaces.repeat(self.repeat + 1); /* 5 - space between name and opening brace, opening brace, newline * after opening brace, closing brace, terminating zero */ let mut capacity = self.name.len() + 5 + indent.len(); for pair in &self.fields { /* 4 - colon after name, space, comma, newline after value */ capacity += field_indent.len() + pair.0.len() + 4 + pair.1.len(); } let mut str = String::with_capacity(capacity); str.push_str(&format!("{} {{\n", self.name,)); for pair in &self.fields { str.push_str(&format!("{}{}: {},\n", field_indent, pair.0, pair.1)); } str.push_str(&format!("{}}}", indent)); str } } impl IndentedToString for u32 { fn indented_to_string(&self, _: &str, _: usize) -> String { self.to_string() } } impl IndentedToString for PathBuf { fn indented_to_string(&self, _: &str, _: usize) -> String { self.display().to_string() } } impl IndentedToString for OsString { fn indented_to_string(&self, _: &str, _: usize) -> String { self.to_string_lossy().to_string() } } impl<T: IndentedToString> IndentedToString for Option<T> { fn indented_to_string(&self, spaces: &str, repeat: usize) -> String { match self { &Some(ref v) => format!("Some({})", its!(v, spaces, repeat)), &None => "None".to_string(), } } } impl<V: IndentedToString> IndentedToString for HashMap<PathBuf, V> { fn indented_to_string(&self, spaces: &str, repeat: usize) -> String { let mut paths = self.keys().collect::<Vec<&PathBuf>>(); paths.sort(); let indent = spaces.repeat(repeat + 1); let mut str = String::new(); str.push_str("{\n"); for path in paths { str.push_str(&format!( "{}{}: {},\n", indent, path.display(), its!(self.get(path).unwrap(), spaces, repeat + 1), )); } str.push_str(&format!("{}}}", spaces.repeat(repeat))); str } } impl IndentedToString for HashSet<PathBuf> { fn indented_to_string(&self, spaces: &str, repeat: usize) -> String { let mut paths = self.iter().collect::<Vec<&PathBuf>>(); paths.sort(); let indent = spaces.repeat(repeat + 1); let mut str = String::new(); str.push_str("{\n"); for path in paths { str.push_str(&format!( "{}{},\n", indent, path.display(), )); } str.push_str(&format!("{}}}", spaces.repeat(repeat))); str } }
its!($value, " ", 0) }; );
random_line_split
debug.rs
// Copyright (c) 2017 Chef Software Inc. and/or applicable contributors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use std::collections::{HashMap, HashSet}; use std::fmt::Debug; use std::path::PathBuf; use std::ffi::OsString; pub trait IndentedToString { fn indented_to_string(&self, spaces: &str, repeat: usize) -> String; } // indented to string macro_rules! its( {$value:expr, $spaces:expr, $repeat:expr} => { { $value.indented_to_string($spaces, $repeat) } }; ); // default indented to string macro_rules! dits( {$value:expr} => { its!($value, " ", 0) }; ); pub struct IndentedStructFormatter { name: String, fields: Vec<(String, String)>, spaces: String, repeat: usize, } impl IndentedStructFormatter { pub fn new(name: &str, spaces: &str, repeat: usize) -> Self { Self { name: name.to_string(), fields: Vec::new(), spaces: spaces.to_string(), repeat: repeat, } } pub fn add_string(&mut self, field_name: &str, field_value: String) { self.fields.push((field_name.to_string(), field_value)); } pub fn add_debug<T: Debug>(&mut self, field_name: &str, field_value: &T)
pub fn add<T: IndentedToString>(&mut self, field_name: &str, field_value: &T) { let spaces = self.spaces.to_string(); let repeat = self.repeat + 1; self.add_string(field_name, its!(field_value, &spaces, repeat)); } pub fn fmt(&mut self) -> String { let indent = self.spaces.repeat(self.repeat); let field_indent = self.spaces.repeat(self.repeat + 1); /* 5 - space between name and opening brace, opening brace, newline * after opening brace, closing brace, terminating zero */ let mut capacity = self.name.len() + 5 + indent.len(); for pair in &self.fields { /* 4 - colon after name, space, comma, newline after value */ capacity += field_indent.len() + pair.0.len() + 4 + pair.1.len(); } let mut str = String::with_capacity(capacity); str.push_str(&format!("{} {{\n", self.name,)); for pair in &self.fields { str.push_str(&format!("{}{}: {},\n", field_indent, pair.0, pair.1)); } str.push_str(&format!("{}}}", indent)); str } } impl IndentedToString for u32 { fn indented_to_string(&self, _: &str, _: usize) -> String { self.to_string() } } impl IndentedToString for PathBuf { fn indented_to_string(&self, _: &str, _: usize) -> String { self.display().to_string() } } impl IndentedToString for OsString { fn indented_to_string(&self, _: &str, _: usize) -> String { self.to_string_lossy().to_string() } } impl<T: IndentedToString> IndentedToString for Option<T> { fn indented_to_string(&self, spaces: &str, repeat: usize) -> String { match self { &Some(ref v) => format!("Some({})", its!(v, spaces, repeat)), &None => "None".to_string(), } } } impl<V: IndentedToString> IndentedToString for HashMap<PathBuf, V> { fn indented_to_string(&self, spaces: &str, repeat: usize) -> String { let mut paths = self.keys().collect::<Vec<&PathBuf>>(); paths.sort(); let indent = spaces.repeat(repeat + 1); let mut str = String::new(); str.push_str("{\n"); for path in paths { str.push_str(&format!( "{}{}: {},\n", indent, path.display(), its!(self.get(path).unwrap(), spaces, repeat + 1), )); } str.push_str(&format!("{}}}", spaces.repeat(repeat))); str } } impl IndentedToString for HashSet<PathBuf> { fn indented_to_string(&self, spaces: &str, repeat: usize) -> String { let mut paths = self.iter().collect::<Vec<&PathBuf>>(); paths.sort(); let indent = spaces.repeat(repeat + 1); let mut str = String::new(); str.push_str("{\n"); for path in paths { str.push_str(&format!( "{}{},\n", indent, path.display(), )); } str.push_str(&format!("{}}}", spaces.repeat(repeat))); str } }
{ self.add_string(field_name, format!("{:?}", field_value)); }
identifier_body
python_move_group_ns.py
#!/usr/bin/env python # Software License Agreement (BSD License) # # Copyright (c) 2012, Willow Garage, Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following # disclaimer in the documentation and/or other materials provided # with the distribution. # * Neither the name of Willow Garage, Inc. nor the names of its # contributors may be used to endorse or promote products derived # from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # # Author: William Baker # # This test is used to ensure planning with a MoveGroupInterface is # possbile if the robot's move_group node is in a different namespace import unittest import numpy as np import rospy import rostest import os from moveit_ros_planning_interface._moveit_move_group_interface import MoveGroupInterface class PythonMoveGroupNsTest(unittest.TestCase): PLANNING_GROUP = "manipulator" PLANNING_NS = "test_ns/" @classmethod def setUpClass(self): self.group = MoveGroupInterface(self.PLANNING_GROUP, "%srobot_description"%self.PLANNING_NS, self.PLANNING_NS) @classmethod def tearDown(self): pass def check_target_setting(self, expect, *args): if len(args) == 0: args = [expect] self.group.set_joint_value_target(*args) res = self.group.get_joint_value_target() self.assertTrue(np.all(np.asarray(res) == np.asarray(expect)), "Setting failed for %s, values: %s" % (type(args[0]), res)) def test_target_setting(self): n = self.group.get_variable_count() self.check_target_setting([0.1] * n) self.check_target_setting((0.2,) * n) self.check_target_setting(np.zeros(n)) self.check_target_setting([0.3] * n, {name: 0.3 for name in self.group.get_active_joints()}) self.check_target_setting([0.5] + [0.3]*(n-1), "joint_1", 0.5)
self.group.set_joint_value_target(target) return self.group.compute_plan() def test_validation(self): current = np.asarray(self.group.get_current_joint_values()) plan1 = self.plan(current + 0.2) plan2 = self.plan(current + 0.2) # first plan should execute self.assertTrue(self.group.execute(plan1)) # second plan should be invalid now (due to modified start point) and rejected self.assertFalse(self.group.execute(plan2)) # newly planned trajectory should execute again plan3 = self.plan(current) self.assertTrue(self.group.execute(plan3)) if __name__ == '__main__': PKGNAME = 'moveit_ros_planning_interface' NODENAME = 'moveit_test_python_move_group' rospy.init_node(NODENAME) rostest.rosrun(PKGNAME, NODENAME, PythonMoveGroupNsTest)
def plan(self, target):
random_line_split
python_move_group_ns.py
#!/usr/bin/env python # Software License Agreement (BSD License) # # Copyright (c) 2012, Willow Garage, Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following # disclaimer in the documentation and/or other materials provided # with the distribution. # * Neither the name of Willow Garage, Inc. nor the names of its # contributors may be used to endorse or promote products derived # from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # # Author: William Baker # # This test is used to ensure planning with a MoveGroupInterface is # possbile if the robot's move_group node is in a different namespace import unittest import numpy as np import rospy import rostest import os from moveit_ros_planning_interface._moveit_move_group_interface import MoveGroupInterface class PythonMoveGroupNsTest(unittest.TestCase): PLANNING_GROUP = "manipulator" PLANNING_NS = "test_ns/" @classmethod def setUpClass(self): self.group = MoveGroupInterface(self.PLANNING_GROUP, "%srobot_description"%self.PLANNING_NS, self.PLANNING_NS) @classmethod def tearDown(self): pass def check_target_setting(self, expect, *args): if len(args) == 0:
self.group.set_joint_value_target(*args) res = self.group.get_joint_value_target() self.assertTrue(np.all(np.asarray(res) == np.asarray(expect)), "Setting failed for %s, values: %s" % (type(args[0]), res)) def test_target_setting(self): n = self.group.get_variable_count() self.check_target_setting([0.1] * n) self.check_target_setting((0.2,) * n) self.check_target_setting(np.zeros(n)) self.check_target_setting([0.3] * n, {name: 0.3 for name in self.group.get_active_joints()}) self.check_target_setting([0.5] + [0.3]*(n-1), "joint_1", 0.5) def plan(self, target): self.group.set_joint_value_target(target) return self.group.compute_plan() def test_validation(self): current = np.asarray(self.group.get_current_joint_values()) plan1 = self.plan(current + 0.2) plan2 = self.plan(current + 0.2) # first plan should execute self.assertTrue(self.group.execute(plan1)) # second plan should be invalid now (due to modified start point) and rejected self.assertFalse(self.group.execute(plan2)) # newly planned trajectory should execute again plan3 = self.plan(current) self.assertTrue(self.group.execute(plan3)) if __name__ == '__main__': PKGNAME = 'moveit_ros_planning_interface' NODENAME = 'moveit_test_python_move_group' rospy.init_node(NODENAME) rostest.rosrun(PKGNAME, NODENAME, PythonMoveGroupNsTest)
args = [expect]
conditional_block
python_move_group_ns.py
#!/usr/bin/env python # Software License Agreement (BSD License) # # Copyright (c) 2012, Willow Garage, Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following # disclaimer in the documentation and/or other materials provided # with the distribution. # * Neither the name of Willow Garage, Inc. nor the names of its # contributors may be used to endorse or promote products derived # from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # # Author: William Baker # # This test is used to ensure planning with a MoveGroupInterface is # possbile if the robot's move_group node is in a different namespace import unittest import numpy as np import rospy import rostest import os from moveit_ros_planning_interface._moveit_move_group_interface import MoveGroupInterface class PythonMoveGroupNsTest(unittest.TestCase): PLANNING_GROUP = "manipulator" PLANNING_NS = "test_ns/" @classmethod def setUpClass(self): self.group = MoveGroupInterface(self.PLANNING_GROUP, "%srobot_description"%self.PLANNING_NS, self.PLANNING_NS) @classmethod def tearDown(self): pass def check_target_setting(self, expect, *args): if len(args) == 0: args = [expect] self.group.set_joint_value_target(*args) res = self.group.get_joint_value_target() self.assertTrue(np.all(np.asarray(res) == np.asarray(expect)), "Setting failed for %s, values: %s" % (type(args[0]), res)) def test_target_setting(self): n = self.group.get_variable_count() self.check_target_setting([0.1] * n) self.check_target_setting((0.2,) * n) self.check_target_setting(np.zeros(n)) self.check_target_setting([0.3] * n, {name: 0.3 for name in self.group.get_active_joints()}) self.check_target_setting([0.5] + [0.3]*(n-1), "joint_1", 0.5) def
(self, target): self.group.set_joint_value_target(target) return self.group.compute_plan() def test_validation(self): current = np.asarray(self.group.get_current_joint_values()) plan1 = self.plan(current + 0.2) plan2 = self.plan(current + 0.2) # first plan should execute self.assertTrue(self.group.execute(plan1)) # second plan should be invalid now (due to modified start point) and rejected self.assertFalse(self.group.execute(plan2)) # newly planned trajectory should execute again plan3 = self.plan(current) self.assertTrue(self.group.execute(plan3)) if __name__ == '__main__': PKGNAME = 'moveit_ros_planning_interface' NODENAME = 'moveit_test_python_move_group' rospy.init_node(NODENAME) rostest.rosrun(PKGNAME, NODENAME, PythonMoveGroupNsTest)
plan
identifier_name
python_move_group_ns.py
#!/usr/bin/env python # Software License Agreement (BSD License) # # Copyright (c) 2012, Willow Garage, Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following # disclaimer in the documentation and/or other materials provided # with the distribution. # * Neither the name of Willow Garage, Inc. nor the names of its # contributors may be used to endorse or promote products derived # from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # # Author: William Baker # # This test is used to ensure planning with a MoveGroupInterface is # possbile if the robot's move_group node is in a different namespace import unittest import numpy as np import rospy import rostest import os from moveit_ros_planning_interface._moveit_move_group_interface import MoveGroupInterface class PythonMoveGroupNsTest(unittest.TestCase):
if __name__ == '__main__': PKGNAME = 'moveit_ros_planning_interface' NODENAME = 'moveit_test_python_move_group' rospy.init_node(NODENAME) rostest.rosrun(PKGNAME, NODENAME, PythonMoveGroupNsTest)
PLANNING_GROUP = "manipulator" PLANNING_NS = "test_ns/" @classmethod def setUpClass(self): self.group = MoveGroupInterface(self.PLANNING_GROUP, "%srobot_description"%self.PLANNING_NS, self.PLANNING_NS) @classmethod def tearDown(self): pass def check_target_setting(self, expect, *args): if len(args) == 0: args = [expect] self.group.set_joint_value_target(*args) res = self.group.get_joint_value_target() self.assertTrue(np.all(np.asarray(res) == np.asarray(expect)), "Setting failed for %s, values: %s" % (type(args[0]), res)) def test_target_setting(self): n = self.group.get_variable_count() self.check_target_setting([0.1] * n) self.check_target_setting((0.2,) * n) self.check_target_setting(np.zeros(n)) self.check_target_setting([0.3] * n, {name: 0.3 for name in self.group.get_active_joints()}) self.check_target_setting([0.5] + [0.3]*(n-1), "joint_1", 0.5) def plan(self, target): self.group.set_joint_value_target(target) return self.group.compute_plan() def test_validation(self): current = np.asarray(self.group.get_current_joint_values()) plan1 = self.plan(current + 0.2) plan2 = self.plan(current + 0.2) # first plan should execute self.assertTrue(self.group.execute(plan1)) # second plan should be invalid now (due to modified start point) and rejected self.assertFalse(self.group.execute(plan2)) # newly planned trajectory should execute again plan3 = self.plan(current) self.assertTrue(self.group.execute(plan3))
identifier_body
issue_371.rs
//! Checks that `executor.look_ahead().field_name()` is correct in presence of //! multiple query fields. //! See [#371](https://github.com/graphql-rust/juniper/issues/371) for details. //! //! Original author of this test is [@davidpdrsn](https://github.com/davidpdrsn). use juniper::{ graphql_object, graphql_vars, EmptyMutation, EmptySubscription, Executor, LookAheadMethods as _, RootNode, ScalarValue, }; pub struct Context; impl juniper::Context for Context {} pub struct Query; #[graphql_object(context = Context)] impl Query { fn users<__S: ScalarValue>(executor: &Executor<'_, '_, Context, __S>) -> Vec<User> { let lh = executor.look_ahead(); assert_eq!(lh.field_name(), "users"); vec![User] } fn countries<__S: ScalarValue>(executor: &Executor<'_, '_, Context, __S>) -> Vec<Country> { let lh = executor.look_ahead(); assert_eq!(lh.field_name(), "countries"); vec![Country] } } #[derive(Clone)] pub struct User; #[graphql_object(context = Context)] impl User { fn id() -> i32 { 1 } } #[derive(Clone)] pub struct Country; #[graphql_object] impl Country { fn id() -> i32 { 2 } } type Schema = RootNode<'static, Query, EmptyMutation<Context>, EmptySubscription<Context>>; #[tokio::test] async fn users() { let query = "{ users { id } }"; let schema = Schema::new(Query, EmptyMutation::new(), EmptySubscription::new()); let (_, errors) = juniper::execute(query, None, &schema, &graphql_vars! {}, &Context) .await .unwrap(); assert_eq!(errors.len(), 0); } #[tokio::test] async fn
() { let query = "{ countries { id } }"; let schema = Schema::new(Query, EmptyMutation::new(), EmptySubscription::new()); let (_, errors) = juniper::execute(query, None, &schema, &graphql_vars! {}, &Context) .await .unwrap(); assert_eq!(errors.len(), 0); } #[tokio::test] async fn both() { let query = "{ countries { id } users { id } }"; let schema = Schema::new(Query, EmptyMutation::new(), EmptySubscription::new()); let (_, errors) = juniper::execute(query, None, &schema, &graphql_vars! {}, &Context) .await .unwrap(); assert_eq!(errors.len(), 0); } #[tokio::test] async fn both_in_different_order() { let query = "{ users { id } countries { id } }"; let schema = Schema::new(Query, EmptyMutation::new(), EmptySubscription::new()); let (_, errors) = juniper::execute(query, None, &schema, &graphql_vars! {}, &Context) .await .unwrap(); assert_eq!(errors.len(), 0); }
countries
identifier_name
issue_371.rs
//! Checks that `executor.look_ahead().field_name()` is correct in presence of //! multiple query fields. //! See [#371](https://github.com/graphql-rust/juniper/issues/371) for details. //! //! Original author of this test is [@davidpdrsn](https://github.com/davidpdrsn). use juniper::{ graphql_object, graphql_vars, EmptyMutation, EmptySubscription, Executor, LookAheadMethods as _, RootNode, ScalarValue, }; pub struct Context; impl juniper::Context for Context {} pub struct Query; #[graphql_object(context = Context)] impl Query { fn users<__S: ScalarValue>(executor: &Executor<'_, '_, Context, __S>) -> Vec<User> { let lh = executor.look_ahead(); assert_eq!(lh.field_name(), "users"); vec![User] } fn countries<__S: ScalarValue>(executor: &Executor<'_, '_, Context, __S>) -> Vec<Country> { let lh = executor.look_ahead(); assert_eq!(lh.field_name(), "countries"); vec![Country] } } #[derive(Clone)] pub struct User; #[graphql_object(context = Context)] impl User { fn id() -> i32 { 1 } } #[derive(Clone)] pub struct Country; #[graphql_object] impl Country { fn id() -> i32 { 2 } } type Schema = RootNode<'static, Query, EmptyMutation<Context>, EmptySubscription<Context>>; #[tokio::test] async fn users() { let query = "{ users { id } }"; let schema = Schema::new(Query, EmptyMutation::new(), EmptySubscription::new()); let (_, errors) = juniper::execute(query, None, &schema, &graphql_vars! {}, &Context) .await .unwrap();
#[tokio::test] async fn countries() { let query = "{ countries { id } }"; let schema = Schema::new(Query, EmptyMutation::new(), EmptySubscription::new()); let (_, errors) = juniper::execute(query, None, &schema, &graphql_vars! {}, &Context) .await .unwrap(); assert_eq!(errors.len(), 0); } #[tokio::test] async fn both() { let query = "{ countries { id } users { id } }"; let schema = Schema::new(Query, EmptyMutation::new(), EmptySubscription::new()); let (_, errors) = juniper::execute(query, None, &schema, &graphql_vars! {}, &Context) .await .unwrap(); assert_eq!(errors.len(), 0); } #[tokio::test] async fn both_in_different_order() { let query = "{ users { id } countries { id } }"; let schema = Schema::new(Query, EmptyMutation::new(), EmptySubscription::new()); let (_, errors) = juniper::execute(query, None, &schema, &graphql_vars! {}, &Context) .await .unwrap(); assert_eq!(errors.len(), 0); }
assert_eq!(errors.len(), 0); }
random_line_split
colour.rs
use super::request::*; use std::cmp::Ordering; /// HSB colour representation - hue, saturation, brightness (aka value). /// Aka HSV (LIFX terminology) - hue, saturation, value. /// This is not the same as HSL as used in CSS. /// LIFX uses HSB aka HSV, not HSL. #[derive(Debug)] pub struct HSB { pub hue: u16, pub saturation: u8, pub brightness: u8, } /// RGB colour representation - red, green, blue. pub struct RGB { pub red: u8, pub green: u8, pub blue: u8, } /// HSBK colour representation - hue, saturation, brightness, kelvin. /// Kelvin seems to be relevant only to whites - temperature of white. #[derive(Debug)] pub struct HSBK { pub hue: u16, pub saturation: u8, pub brightness: u8, pub kelvin: u16, } impl HSB { pub fn new(h: u16, s: u8, b: u8) -> HSB { HSB { hue: h, saturation: s, brightness: b, } } } impl From<HSBK> for HSB { fn from(c: HSBK) -> HSB { HSB::new(c.hue, c.saturation, c.brightness) } } /// The max value of the two byte representation of colour element as used in the protocol. const WORD_SIZE: usize = 65535; const DEGREES_UBOUND: usize = 360; const PERCENT_UBOUND: usize = 100; // (WORD_SIZE / DEGREES_UBOUND) is ~182.0417 // The two-byte represenation only represents integers, so decimals will be truncated. // This can result in a get_state returning a slightly different result from the // preceding set_state for hue, saturation, and brightness. pub fn hue_degrees_to_word(degrees: u16) -> [u8; 2] { let f = degrees as f64 * WORD_SIZE as f64 / DEGREES_UBOUND as f64; let b = RequestBin::u16_to_u8_array(f.round() as u16); [b[0], b[1]] } pub fn hue_word_to_degrees(word: u16) -> u16 { (word as usize * 360 / WORD_SIZE) as u16 } pub fn saturation_percent_to_word(percent: u8) -> [u8; 2] { let f: f64 = percent as f64 * WORD_SIZE as f64 / 100.0; let b = RequestBin::u16_to_u8_array(f.round() as u16); [b[0], b[1]] } pub fn saturation_word_to_percent(word: u16) -> u8 { (word as usize * 100 / WORD_SIZE) as u8 } pub fn brightness_percent_to_word(percent: u8) -> [u8; 2] { saturation_percent_to_word(percent) } pub fn brightness_word_to_percent(word: u16) -> u8 { (word as usize * 100 / WORD_SIZE) as u8 } pub fn rgb_to_hsv(rgb: RGB) -> HSB { let r1 = rgb.red as f32 / 255.0; let g1 = rgb.green as f32 / 255.0; let b1 = rgb.blue as f32 / 255.0; let mut floats: Vec<f32> = vec![r1, g1, b1]; floats.sort_by(|a, b| a.partial_cmp(b).unwrap_or(Ordering::Equal)); let cmax = floats[2]; let cmin = floats[0]; let d = cmax - cmin; // Hue. let h = match cmax { _ if r1 == cmax => (((g1 - b1) / d) % 6.0) * 60.0, _ if g1 == cmax => (((b1 - r1) / d) + 2.0) * 60.0, _ if b1 == cmax => (((r1 - g1) / d) + 4.0) * 60.0, _ => 0.0, }; // Saturation. let s = match cmax { 0.0 => 0.0, _ => d / cmax, }; // Value / brightness. let v = cmax; HSB { hue: h as u16, saturation: (s * 100.0) as u8, brightness: (v * 100.0) as u8, } } #[cfg(test)] mod tests { use colour::*; #[test] fn test_hue_degrees_to_word() { assert_eq!([0x55, 0x55], hue_degrees_to_word(120)); assert_eq!([0x47, 0x1C], hue_degrees_to_word(100)); assert_eq!([0x44, 0x44], hue_degrees_to_word(96)); assert_eq!([0x43, 0x8E], hue_degrees_to_word(95)); } #[test] fn
() { assert_eq!(360, hue_word_to_degrees(65535)); assert_eq!(0, hue_word_to_degrees(0)); assert_eq!(180, hue_word_to_degrees(32768)); } #[test] fn test_saturation_percent_to_word() { assert_eq!([0x80, 0x00], saturation_percent_to_word(50)); } #[test] fn test_rgb_to_hsv() { struct Test { rgb: RGB, hsb: HSB, }; let tests = vec![ Test { rgb: RGB { // olive red: 128, green: 128, blue: 0, }, hsb: HSB { hue: 60, saturation: 100, brightness: 50, }, }, Test { rgb: RGB { // chartreuse red: 127, green: 255, blue: 0, }, hsb: HSB { hue: 90, saturation: 100, brightness: 100, }, }, ]; for t in tests { let res = rgb_to_hsv(t.rgb); assert_eq!(res.hue, t.hsb.hue); assert_eq!(res.saturation, t.hsb.saturation); assert_eq!(res.brightness, t.hsb.brightness); } } } pub fn named_colours() -> Vec<String> { vec!( "beige".to_string(), "blue".to_string(), "chartreuse".to_string(), "coral".to_string(), "cornflower".to_string(), "crimson".to_string(), "deep_sky_blue".to_string(), "green".to_string(), "red".to_string(), "slate_gray".to_string(), ) } pub fn get_colour(s: &str) -> HSB { let colour: &str = &(s.to_lowercase()); match colour { "beige" => { HSB { hue: 60, saturation: 56, brightness: 91, } } "blue" => { HSB { hue: 240, saturation: 100, brightness: 50, } } "chartreuse" => { HSB { hue: 90, saturation: 100, brightness: 50, } } "coral" => { HSB { hue: 16, saturation: 100, brightness: 66, } } "cornflower" => { HSB { hue: 219, saturation: 79, brightness: 66, } } "crimson" => { HSB { hue: 348, saturation: 83, brightness: 47, } } "deep_sky_blue" => { HSB { hue: 195, saturation: 100, brightness: 50, } } "green" => { HSB { hue: 120, saturation: 100, brightness: 50, } } "red" => { HSB { hue: 0, saturation: 100, brightness: 50, } } "slate_gray" => { HSB { hue: 210, saturation: 13, brightness: 50, } } _ => panic!("no such colour."), } }
test_hue_word_to_degrees
identifier_name
colour.rs
use super::request::*; use std::cmp::Ordering; /// HSB colour representation - hue, saturation, brightness (aka value). /// Aka HSV (LIFX terminology) - hue, saturation, value. /// This is not the same as HSL as used in CSS. /// LIFX uses HSB aka HSV, not HSL. #[derive(Debug)] pub struct HSB { pub hue: u16, pub saturation: u8, pub brightness: u8, } /// RGB colour representation - red, green, blue. pub struct RGB { pub red: u8, pub green: u8, pub blue: u8, } /// HSBK colour representation - hue, saturation, brightness, kelvin. /// Kelvin seems to be relevant only to whites - temperature of white. #[derive(Debug)] pub struct HSBK { pub hue: u16, pub saturation: u8, pub brightness: u8, pub kelvin: u16, } impl HSB { pub fn new(h: u16, s: u8, b: u8) -> HSB { HSB { hue: h, saturation: s, brightness: b, } } } impl From<HSBK> for HSB { fn from(c: HSBK) -> HSB { HSB::new(c.hue, c.saturation, c.brightness) } } /// The max value of the two byte representation of colour element as used in the protocol. const WORD_SIZE: usize = 65535; const DEGREES_UBOUND: usize = 360; const PERCENT_UBOUND: usize = 100; // (WORD_SIZE / DEGREES_UBOUND) is ~182.0417 // The two-byte represenation only represents integers, so decimals will be truncated. // This can result in a get_state returning a slightly different result from the // preceding set_state for hue, saturation, and brightness. pub fn hue_degrees_to_word(degrees: u16) -> [u8; 2] { let f = degrees as f64 * WORD_SIZE as f64 / DEGREES_UBOUND as f64; let b = RequestBin::u16_to_u8_array(f.round() as u16); [b[0], b[1]] } pub fn hue_word_to_degrees(word: u16) -> u16 { (word as usize * 360 / WORD_SIZE) as u16 } pub fn saturation_percent_to_word(percent: u8) -> [u8; 2] { let f: f64 = percent as f64 * WORD_SIZE as f64 / 100.0; let b = RequestBin::u16_to_u8_array(f.round() as u16); [b[0], b[1]] } pub fn saturation_word_to_percent(word: u16) -> u8 { (word as usize * 100 / WORD_SIZE) as u8 } pub fn brightness_percent_to_word(percent: u8) -> [u8; 2] { saturation_percent_to_word(percent) } pub fn brightness_word_to_percent(word: u16) -> u8 { (word as usize * 100 / WORD_SIZE) as u8 } pub fn rgb_to_hsv(rgb: RGB) -> HSB { let r1 = rgb.red as f32 / 255.0; let g1 = rgb.green as f32 / 255.0; let b1 = rgb.blue as f32 / 255.0; let mut floats: Vec<f32> = vec![r1, g1, b1]; floats.sort_by(|a, b| a.partial_cmp(b).unwrap_or(Ordering::Equal)); let cmax = floats[2]; let cmin = floats[0]; let d = cmax - cmin; // Hue. let h = match cmax { _ if r1 == cmax => (((g1 - b1) / d) % 6.0) * 60.0, _ if g1 == cmax => (((b1 - r1) / d) + 2.0) * 60.0, _ if b1 == cmax => (((r1 - g1) / d) + 4.0) * 60.0, _ => 0.0, }; // Saturation. let s = match cmax { 0.0 => 0.0, _ => d / cmax, }; // Value / brightness. let v = cmax; HSB { hue: h as u16, saturation: (s * 100.0) as u8, brightness: (v * 100.0) as u8, } } #[cfg(test)] mod tests { use colour::*; #[test] fn test_hue_degrees_to_word() { assert_eq!([0x55, 0x55], hue_degrees_to_word(120)); assert_eq!([0x47, 0x1C], hue_degrees_to_word(100)); assert_eq!([0x44, 0x44], hue_degrees_to_word(96)); assert_eq!([0x43, 0x8E], hue_degrees_to_word(95)); } #[test] fn test_hue_word_to_degrees() { assert_eq!(360, hue_word_to_degrees(65535)); assert_eq!(0, hue_word_to_degrees(0)); assert_eq!(180, hue_word_to_degrees(32768)); } #[test] fn test_saturation_percent_to_word() { assert_eq!([0x80, 0x00], saturation_percent_to_word(50)); } #[test] fn test_rgb_to_hsv() { struct Test { rgb: RGB, hsb: HSB, }; let tests = vec![ Test { rgb: RGB { // olive red: 128, green: 128, blue: 0, }, hsb: HSB { hue: 60, saturation: 100, brightness: 50, }, }, Test { rgb: RGB { // chartreuse red: 127, green: 255, blue: 0, }, hsb: HSB { hue: 90, saturation: 100, brightness: 100, }, }, ]; for t in tests { let res = rgb_to_hsv(t.rgb); assert_eq!(res.hue, t.hsb.hue); assert_eq!(res.saturation, t.hsb.saturation); assert_eq!(res.brightness, t.hsb.brightness); } } } pub fn named_colours() -> Vec<String> { vec!( "beige".to_string(), "blue".to_string(), "chartreuse".to_string(), "coral".to_string(), "cornflower".to_string(), "crimson".to_string(), "deep_sky_blue".to_string(), "green".to_string(), "red".to_string(), "slate_gray".to_string(), ) } pub fn get_colour(s: &str) -> HSB
{ let colour: &str = &(s.to_lowercase()); match colour { "beige" => { HSB { hue: 60, saturation: 56, brightness: 91, } } "blue" => { HSB { hue: 240, saturation: 100, brightness: 50, } } "chartreuse" => { HSB { hue: 90, saturation: 100, brightness: 50, } } "coral" => { HSB { hue: 16, saturation: 100, brightness: 66, } } "cornflower" => { HSB { hue: 219, saturation: 79, brightness: 66, } } "crimson" => { HSB { hue: 348, saturation: 83, brightness: 47, } } "deep_sky_blue" => { HSB { hue: 195, saturation: 100, brightness: 50, } } "green" => { HSB { hue: 120, saturation: 100, brightness: 50, } } "red" => { HSB { hue: 0, saturation: 100, brightness: 50, } } "slate_gray" => { HSB { hue: 210, saturation: 13, brightness: 50, } } _ => panic!("no such colour."), } }
identifier_body
colour.rs
use super::request::*; use std::cmp::Ordering; /// HSB colour representation - hue, saturation, brightness (aka value). /// Aka HSV (LIFX terminology) - hue, saturation, value. /// This is not the same as HSL as used in CSS. /// LIFX uses HSB aka HSV, not HSL. #[derive(Debug)] pub struct HSB { pub hue: u16, pub saturation: u8, pub brightness: u8, } /// RGB colour representation - red, green, blue. pub struct RGB { pub red: u8, pub green: u8, pub blue: u8, } /// HSBK colour representation - hue, saturation, brightness, kelvin. /// Kelvin seems to be relevant only to whites - temperature of white. #[derive(Debug)] pub struct HSBK { pub hue: u16, pub saturation: u8, pub brightness: u8, pub kelvin: u16, } impl HSB { pub fn new(h: u16, s: u8, b: u8) -> HSB { HSB { hue: h, saturation: s, brightness: b, } } } impl From<HSBK> for HSB { fn from(c: HSBK) -> HSB { HSB::new(c.hue, c.saturation, c.brightness) } } /// The max value of the two byte representation of colour element as used in the protocol. const WORD_SIZE: usize = 65535; const DEGREES_UBOUND: usize = 360; const PERCENT_UBOUND: usize = 100; // (WORD_SIZE / DEGREES_UBOUND) is ~182.0417 // The two-byte represenation only represents integers, so decimals will be truncated. // This can result in a get_state returning a slightly different result from the // preceding set_state for hue, saturation, and brightness. pub fn hue_degrees_to_word(degrees: u16) -> [u8; 2] { let f = degrees as f64 * WORD_SIZE as f64 / DEGREES_UBOUND as f64; let b = RequestBin::u16_to_u8_array(f.round() as u16); [b[0], b[1]] } pub fn hue_word_to_degrees(word: u16) -> u16 { (word as usize * 360 / WORD_SIZE) as u16 } pub fn saturation_percent_to_word(percent: u8) -> [u8; 2] { let f: f64 = percent as f64 * WORD_SIZE as f64 / 100.0; let b = RequestBin::u16_to_u8_array(f.round() as u16); [b[0], b[1]] } pub fn saturation_word_to_percent(word: u16) -> u8 { (word as usize * 100 / WORD_SIZE) as u8 } pub fn brightness_percent_to_word(percent: u8) -> [u8; 2] { saturation_percent_to_word(percent) } pub fn brightness_word_to_percent(word: u16) -> u8 { (word as usize * 100 / WORD_SIZE) as u8 } pub fn rgb_to_hsv(rgb: RGB) -> HSB { let r1 = rgb.red as f32 / 255.0; let g1 = rgb.green as f32 / 255.0; let b1 = rgb.blue as f32 / 255.0; let mut floats: Vec<f32> = vec![r1, g1, b1]; floats.sort_by(|a, b| a.partial_cmp(b).unwrap_or(Ordering::Equal)); let cmax = floats[2]; let cmin = floats[0]; let d = cmax - cmin; // Hue. let h = match cmax { _ if r1 == cmax => (((g1 - b1) / d) % 6.0) * 60.0, _ if g1 == cmax => (((b1 - r1) / d) + 2.0) * 60.0, _ if b1 == cmax => (((r1 - g1) / d) + 4.0) * 60.0, _ => 0.0, }; // Saturation. let s = match cmax { 0.0 => 0.0, _ => d / cmax, }; // Value / brightness. let v = cmax; HSB { hue: h as u16, saturation: (s * 100.0) as u8, brightness: (v * 100.0) as u8, } } #[cfg(test)] mod tests { use colour::*; #[test] fn test_hue_degrees_to_word() { assert_eq!([0x55, 0x55], hue_degrees_to_word(120)); assert_eq!([0x47, 0x1C], hue_degrees_to_word(100)); assert_eq!([0x44, 0x44], hue_degrees_to_word(96)); assert_eq!([0x43, 0x8E], hue_degrees_to_word(95)); } #[test] fn test_hue_word_to_degrees() { assert_eq!(360, hue_word_to_degrees(65535)); assert_eq!(0, hue_word_to_degrees(0)); assert_eq!(180, hue_word_to_degrees(32768)); } #[test] fn test_saturation_percent_to_word() { assert_eq!([0x80, 0x00], saturation_percent_to_word(50)); } #[test] fn test_rgb_to_hsv() { struct Test { rgb: RGB, hsb: HSB, }; let tests = vec![ Test { rgb: RGB { // olive red: 128, green: 128, blue: 0, }, hsb: HSB { hue: 60, saturation: 100, brightness: 50, }, }, Test { rgb: RGB { // chartreuse red: 127, green: 255, blue: 0, }, hsb: HSB { hue: 90, saturation: 100, brightness: 100, }, }, ]; for t in tests { let res = rgb_to_hsv(t.rgb); assert_eq!(res.hue, t.hsb.hue); assert_eq!(res.saturation, t.hsb.saturation); assert_eq!(res.brightness, t.hsb.brightness); } } } pub fn named_colours() -> Vec<String> { vec!( "beige".to_string(), "blue".to_string(), "chartreuse".to_string(), "coral".to_string(), "cornflower".to_string(), "crimson".to_string(), "deep_sky_blue".to_string(), "green".to_string(), "red".to_string(), "slate_gray".to_string(), ) } pub fn get_colour(s: &str) -> HSB { let colour: &str = &(s.to_lowercase()); match colour { "beige" => { HSB { hue: 60, saturation: 56, brightness: 91, } } "blue" => { HSB { hue: 240, saturation: 100, brightness: 50, } } "chartreuse" => { HSB { hue: 90, saturation: 100, brightness: 50, } } "coral" => { HSB { hue: 16, saturation: 100, brightness: 66, } } "cornflower" => { HSB { hue: 219, saturation: 79, brightness: 66, } } "crimson" => { HSB { hue: 348, saturation: 83, brightness: 47, } } "deep_sky_blue" => { HSB { hue: 195, saturation: 100,
HSB { hue: 120, saturation: 100, brightness: 50, } } "red" => { HSB { hue: 0, saturation: 100, brightness: 50, } } "slate_gray" => { HSB { hue: 210, saturation: 13, brightness: 50, } } _ => panic!("no such colour."), } }
brightness: 50, } } "green" => {
random_line_split
AppFilesCommandBar.tsx
import React, { useEffect, useContext } from 'react'; import { ICommandBarItemProps, CommandBar } from 'office-ui-fabric-react'; import { useTranslation } from 'react-i18next'; import { PortalContext } from '../../../../PortalContext'; import { CustomCommandBarButton } from '../../../../components/CustomCommandBarButton'; import { CommandBarStyles } from '../../../../theme/CustomOfficeFabric/AzurePortal/CommandBar.styles'; interface AppFilesCommandBarProps { saveFile: () => void; resetFile: () => void; refreshFunction: () => void; dirty: boolean; disabled: boolean; } const AppFilesCommandBar: React.FC<AppFilesCommandBarProps> = props => { const { saveFile, resetFile, dirty, disabled, refreshFunction } = props; const { t } = useTranslation(); const portalCommunicator = useContext(PortalContext); const getItems = (): ICommandBarItemProps[] => { return [ { key: 'save', name: t('save'), iconProps: { iconName: 'Save', }, disabled: !dirty || disabled, ariaLabel: t('functionEditorSaveAriaLabel'), onClick: saveFile, }, { key: 'discard', name: t('discard'), iconProps: { iconName: 'ChromeClose', }, disabled: !dirty || disabled, ariaLabel: t('functionEditorDiscardAriaLabel'), onClick: resetFile, }, { key: 'refresh', name: t('refresh'), iconProps: { iconName: 'refresh', },
}, ]; }; useEffect(() => { portalCommunicator.updateDirtyState(dirty); }, [dirty, portalCommunicator]); return ( <> <CommandBar items={getItems()} role="nav" styles={CommandBarStyles} ariaLabel={t('functionEditorCommandBarAriaLabel')} buttonAs={CustomCommandBarButton} /> </> ); }; export default AppFilesCommandBar;
disabled: disabled, ariaLabel: t('appFilesSaveAriaLabel'), onClick: refreshFunction,
random_line_split
catall.py
#!/usr/bin/python # -*- coding: utf-8 -*- """ This script shows the categories on each page and lets you change them. For each page in the target wiki: * If the page contains no categories, you can specify a list of categories to add to the page. * If the page already contains one or more categories, you can specify a new list of categories to replace the current list of categories of the page. Usage: python pwb.py catall [start] If no starting name is provided, the bot starts at 'A'. Options: -onlynew : Only run on pages that do not yet have a category. """ # # (C) Rob W.W. Hooft, Andre Engels, 2004 # (C) Pywikibot team, 2004-2014 # # Distributed under the terms of the MIT license. # from __future__ import absolute_import, unicode_literals __version__ = '$Id$' # import pywikibot from pywikibot import i18n, textlib from pywikibot.bot import QuitKeyboardInterrupt def choosecats(pagetext): """Coose categories.""" chosen = [] done = False length = 1000 # TODO: → input_choice pywikibot.output("""Give the new categories, one per line. Empty line: if the first, don't change. Otherwise: Ready. -: I made a mistake, let me start over. ?: Give the text of the page with GUI. ??: Give the text of the page in console. xx: if the first, remove all categories and add no new. q: quit.""") while not done: choice = pywikibot.input(u"?") if choice == "": done = True elif choice == "-": chosen = choosecats(pagetext) done = True elif choice == "?": from pywikibot import editor as editarticle editor = editarticle.TextEditor() editor.edit(pagetext) elif choice == "??": pywikibot.output(pagetext[0:length]) length = length + 500 elif choice == "xx" and chosen == []: chosen = None done = True elif choice == "q": raise QuitKeyboardInterrupt else: chosen.append(choice) return chosen def make_categories(page, list, site=None): """Make categories.""" if site is None: site = pywikibot.Site() pllist = [] for p in list: cattitle = "%s:%s" % (site.namespaces.CATEGORY, p) pllist.append(pywikibot.Page(site, cattitle)) page.put_async(textlib.replaceCategoryLinks(page.get(), pllist, site=page.site), summary=i18n.twtranslate(site, 'catall-changing')) def main(*args): """ Process command line arguments and perform task. If args is an empty list, sys.argv is used. @param args: command line arguments @type args: list of unicode """ docorrections = True start = 'A' local_args = pywikibot.handle_args(args) for arg in local_args: if arg == '-onlynew': docorrections = False else: start = arg mysite = pywikibot.Site() for p in mysite.allpages(start=start): try: text = p.get() cats = p.categories() if not cats: pywikibot.output(u"========== %s ==========" % p.title()) pywikibot.output('No categories') pywikibot.output('-' * 40) newcats = choosecats(text) if newcats != [] and newcats is not None: make_categories(p, newcats, mysite) elif docorrections: pywikibot.output(u"========== %s ==========" % p.title()) for c in cats: pywikibot.output(c.title()) pywikibot.output('-' * 40) newcats = choosecats(text) if newcats is None: make_categories(p, [], mysite) elif newcats != []: make_categories(p, newcats, mysite) except pywikibot.IsRedirectPage: pywikibot.output(u'%s is a redirect' % p.title()) if __name__ == "__main__": tr
y: main() except KeyboardInterrupt: pywikibot.output('\nQuitting program...')
conditional_block
catall.py
#!/usr/bin/python # -*- coding: utf-8 -*- """ This script shows the categories on each page and lets you change them. For each page in the target wiki: * If the page contains no categories, you can specify a list of categories to add to the page. * If the page already contains one or more categories, you can specify a new list of categories to replace the current list of categories of the page. Usage: python pwb.py catall [start] If no starting name is provided, the bot starts at 'A'. Options: -onlynew : Only run on pages that do not yet have a category. """ # # (C) Rob W.W. Hooft, Andre Engels, 2004 # (C) Pywikibot team, 2004-2014 # # Distributed under the terms of the MIT license. # from __future__ import absolute_import, unicode_literals __version__ = '$Id$' # import pywikibot from pywikibot import i18n, textlib from pywikibot.bot import QuitKeyboardInterrupt def choosecats(pagetext): """Coose categories.""" chosen = [] done = False length = 1000 # TODO: → input_choice pywikibot.output("""Give the new categories, one per line. Empty line: if the first, don't change. Otherwise: Ready. -: I made a mistake, let me start over. ?: Give the text of the page with GUI. ??: Give the text of the page in console. xx: if the first, remove all categories and add no new. q: quit.""") while not done: choice = pywikibot.input(u"?") if choice == "": done = True elif choice == "-": chosen = choosecats(pagetext) done = True elif choice == "?": from pywikibot import editor as editarticle editor = editarticle.TextEditor() editor.edit(pagetext) elif choice == "??": pywikibot.output(pagetext[0:length]) length = length + 500 elif choice == "xx" and chosen == []: chosen = None done = True elif choice == "q": raise QuitKeyboardInterrupt else: chosen.append(choice) return chosen def make_categories(page, list, site=None): ""
def main(*args): """ Process command line arguments and perform task. If args is an empty list, sys.argv is used. @param args: command line arguments @type args: list of unicode """ docorrections = True start = 'A' local_args = pywikibot.handle_args(args) for arg in local_args: if arg == '-onlynew': docorrections = False else: start = arg mysite = pywikibot.Site() for p in mysite.allpages(start=start): try: text = p.get() cats = p.categories() if not cats: pywikibot.output(u"========== %s ==========" % p.title()) pywikibot.output('No categories') pywikibot.output('-' * 40) newcats = choosecats(text) if newcats != [] and newcats is not None: make_categories(p, newcats, mysite) elif docorrections: pywikibot.output(u"========== %s ==========" % p.title()) for c in cats: pywikibot.output(c.title()) pywikibot.output('-' * 40) newcats = choosecats(text) if newcats is None: make_categories(p, [], mysite) elif newcats != []: make_categories(p, newcats, mysite) except pywikibot.IsRedirectPage: pywikibot.output(u'%s is a redirect' % p.title()) if __name__ == "__main__": try: main() except KeyboardInterrupt: pywikibot.output('\nQuitting program...')
"Make categories.""" if site is None: site = pywikibot.Site() pllist = [] for p in list: cattitle = "%s:%s" % (site.namespaces.CATEGORY, p) pllist.append(pywikibot.Page(site, cattitle)) page.put_async(textlib.replaceCategoryLinks(page.get(), pllist, site=page.site), summary=i18n.twtranslate(site, 'catall-changing'))
identifier_body
catall.py
#!/usr/bin/python # -*- coding: utf-8 -*- """ This script shows the categories on each page and lets you change them. For each page in the target wiki: * If the page contains no categories, you can specify a list of categories to add to the page. * If the page already contains one or more categories, you can specify a new list of categories to replace the current list of categories of the page. Usage: python pwb.py catall [start] If no starting name is provided, the bot starts at 'A'. Options: -onlynew : Only run on pages that do not yet have a category. """ # # (C) Rob W.W. Hooft, Andre Engels, 2004 # (C) Pywikibot team, 2004-2014 # # Distributed under the terms of the MIT license. #
__version__ = '$Id$' # import pywikibot from pywikibot import i18n, textlib from pywikibot.bot import QuitKeyboardInterrupt def choosecats(pagetext): """Coose categories.""" chosen = [] done = False length = 1000 # TODO: → input_choice pywikibot.output("""Give the new categories, one per line. Empty line: if the first, don't change. Otherwise: Ready. -: I made a mistake, let me start over. ?: Give the text of the page with GUI. ??: Give the text of the page in console. xx: if the first, remove all categories and add no new. q: quit.""") while not done: choice = pywikibot.input(u"?") if choice == "": done = True elif choice == "-": chosen = choosecats(pagetext) done = True elif choice == "?": from pywikibot import editor as editarticle editor = editarticle.TextEditor() editor.edit(pagetext) elif choice == "??": pywikibot.output(pagetext[0:length]) length = length + 500 elif choice == "xx" and chosen == []: chosen = None done = True elif choice == "q": raise QuitKeyboardInterrupt else: chosen.append(choice) return chosen def make_categories(page, list, site=None): """Make categories.""" if site is None: site = pywikibot.Site() pllist = [] for p in list: cattitle = "%s:%s" % (site.namespaces.CATEGORY, p) pllist.append(pywikibot.Page(site, cattitle)) page.put_async(textlib.replaceCategoryLinks(page.get(), pllist, site=page.site), summary=i18n.twtranslate(site, 'catall-changing')) def main(*args): """ Process command line arguments and perform task. If args is an empty list, sys.argv is used. @param args: command line arguments @type args: list of unicode """ docorrections = True start = 'A' local_args = pywikibot.handle_args(args) for arg in local_args: if arg == '-onlynew': docorrections = False else: start = arg mysite = pywikibot.Site() for p in mysite.allpages(start=start): try: text = p.get() cats = p.categories() if not cats: pywikibot.output(u"========== %s ==========" % p.title()) pywikibot.output('No categories') pywikibot.output('-' * 40) newcats = choosecats(text) if newcats != [] and newcats is not None: make_categories(p, newcats, mysite) elif docorrections: pywikibot.output(u"========== %s ==========" % p.title()) for c in cats: pywikibot.output(c.title()) pywikibot.output('-' * 40) newcats = choosecats(text) if newcats is None: make_categories(p, [], mysite) elif newcats != []: make_categories(p, newcats, mysite) except pywikibot.IsRedirectPage: pywikibot.output(u'%s is a redirect' % p.title()) if __name__ == "__main__": try: main() except KeyboardInterrupt: pywikibot.output('\nQuitting program...')
from __future__ import absolute_import, unicode_literals
random_line_split
catall.py
#!/usr/bin/python # -*- coding: utf-8 -*- """ This script shows the categories on each page and lets you change them. For each page in the target wiki: * If the page contains no categories, you can specify a list of categories to add to the page. * If the page already contains one or more categories, you can specify a new list of categories to replace the current list of categories of the page. Usage: python pwb.py catall [start] If no starting name is provided, the bot starts at 'A'. Options: -onlynew : Only run on pages that do not yet have a category. """ # # (C) Rob W.W. Hooft, Andre Engels, 2004 # (C) Pywikibot team, 2004-2014 # # Distributed under the terms of the MIT license. # from __future__ import absolute_import, unicode_literals __version__ = '$Id$' # import pywikibot from pywikibot import i18n, textlib from pywikibot.bot import QuitKeyboardInterrupt def choosecats(pagetext): """Coose categories.""" chosen = [] done = False length = 1000 # TODO: → input_choice pywikibot.output("""Give the new categories, one per line. Empty line: if the first, don't change. Otherwise: Ready. -: I made a mistake, let me start over. ?: Give the text of the page with GUI. ??: Give the text of the page in console. xx: if the first, remove all categories and add no new. q: quit.""") while not done: choice = pywikibot.input(u"?") if choice == "": done = True elif choice == "-": chosen = choosecats(pagetext) done = True elif choice == "?": from pywikibot import editor as editarticle editor = editarticle.TextEditor() editor.edit(pagetext) elif choice == "??": pywikibot.output(pagetext[0:length]) length = length + 500 elif choice == "xx" and chosen == []: chosen = None done = True elif choice == "q": raise QuitKeyboardInterrupt else: chosen.append(choice) return chosen def ma
age, list, site=None): """Make categories.""" if site is None: site = pywikibot.Site() pllist = [] for p in list: cattitle = "%s:%s" % (site.namespaces.CATEGORY, p) pllist.append(pywikibot.Page(site, cattitle)) page.put_async(textlib.replaceCategoryLinks(page.get(), pllist, site=page.site), summary=i18n.twtranslate(site, 'catall-changing')) def main(*args): """ Process command line arguments and perform task. If args is an empty list, sys.argv is used. @param args: command line arguments @type args: list of unicode """ docorrections = True start = 'A' local_args = pywikibot.handle_args(args) for arg in local_args: if arg == '-onlynew': docorrections = False else: start = arg mysite = pywikibot.Site() for p in mysite.allpages(start=start): try: text = p.get() cats = p.categories() if not cats: pywikibot.output(u"========== %s ==========" % p.title()) pywikibot.output('No categories') pywikibot.output('-' * 40) newcats = choosecats(text) if newcats != [] and newcats is not None: make_categories(p, newcats, mysite) elif docorrections: pywikibot.output(u"========== %s ==========" % p.title()) for c in cats: pywikibot.output(c.title()) pywikibot.output('-' * 40) newcats = choosecats(text) if newcats is None: make_categories(p, [], mysite) elif newcats != []: make_categories(p, newcats, mysite) except pywikibot.IsRedirectPage: pywikibot.output(u'%s is a redirect' % p.title()) if __name__ == "__main__": try: main() except KeyboardInterrupt: pywikibot.output('\nQuitting program...')
ke_categories(p
identifier_name
vec_conversion.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ extern crate js; use js::conversions::ConversionBehavior; use js::conversions::FromJSValConvertible; use js::conversions::ToJSValConvertible; use js::jsapi::CompartmentOptions; use js::jsapi::JSAutoCompartment; use js::jsapi::JS_Init; use js::jsapi::JS_InitStandardClasses; use js::jsapi::JS_NewGlobalObject; use js::jsapi::OnNewGlobalHookOption; use js::jsapi::Rooted; use js::jsapi::RootedValue; use js::jsval::UndefinedValue; use js::rust::{Runtime, SIMPLE_GLOBAL_CLASS}; use std::ptr; #[test] fn vec_conversion() { unsafe { assert!(JS_Init()); let rt = Runtime::new(ptr::null_mut());
ptr::null_mut(), h_option, &c_option); let global_root = Rooted::new(cx, global); let global = global_root.handle(); let _ac = JSAutoCompartment::new(cx, global.get()); assert!(JS_InitStandardClasses(cx, global)); let mut rval = RootedValue::new(cx, UndefinedValue()); let orig_vec: Vec<f32> = vec![1.0, 2.9, 3.0]; orig_vec.to_jsval(cx, rval.handle_mut()); let converted = Vec::<f32>::from_jsval(cx, rval.handle(), ()).unwrap(); assert_eq!(orig_vec, converted); let orig_vec: Vec<i32> = vec![1, 2, 3]; orig_vec.to_jsval(cx, rval.handle_mut()); let converted = Vec::<i32>::from_jsval(cx, rval.handle(), ConversionBehavior::Default).unwrap(); assert_eq!(orig_vec, converted); rt.evaluate_script(global, "new Set([1, 2, 3])", "test", 1, rval.handle_mut()).unwrap(); let converted = Vec::<i32>::from_jsval(cx, rval.handle(), ConversionBehavior::Default).unwrap(); assert_eq!(orig_vec, converted); } }
let cx = rt.cx(); let h_option = OnNewGlobalHookOption::FireOnNewGlobalHook; let c_option = CompartmentOptions::default(); let global = JS_NewGlobalObject(cx, &SIMPLE_GLOBAL_CLASS,
random_line_split
vec_conversion.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ extern crate js; use js::conversions::ConversionBehavior; use js::conversions::FromJSValConvertible; use js::conversions::ToJSValConvertible; use js::jsapi::CompartmentOptions; use js::jsapi::JSAutoCompartment; use js::jsapi::JS_Init; use js::jsapi::JS_InitStandardClasses; use js::jsapi::JS_NewGlobalObject; use js::jsapi::OnNewGlobalHookOption; use js::jsapi::Rooted; use js::jsapi::RootedValue; use js::jsval::UndefinedValue; use js::rust::{Runtime, SIMPLE_GLOBAL_CLASS}; use std::ptr; #[test] fn vec_conversion()
{ unsafe { assert!(JS_Init()); let rt = Runtime::new(ptr::null_mut()); let cx = rt.cx(); let h_option = OnNewGlobalHookOption::FireOnNewGlobalHook; let c_option = CompartmentOptions::default(); let global = JS_NewGlobalObject(cx, &SIMPLE_GLOBAL_CLASS, ptr::null_mut(), h_option, &c_option); let global_root = Rooted::new(cx, global); let global = global_root.handle(); let _ac = JSAutoCompartment::new(cx, global.get()); assert!(JS_InitStandardClasses(cx, global)); let mut rval = RootedValue::new(cx, UndefinedValue()); let orig_vec: Vec<f32> = vec![1.0, 2.9, 3.0]; orig_vec.to_jsval(cx, rval.handle_mut()); let converted = Vec::<f32>::from_jsval(cx, rval.handle(), ()).unwrap(); assert_eq!(orig_vec, converted); let orig_vec: Vec<i32> = vec![1, 2, 3]; orig_vec.to_jsval(cx, rval.handle_mut()); let converted = Vec::<i32>::from_jsval(cx, rval.handle(), ConversionBehavior::Default).unwrap(); assert_eq!(orig_vec, converted); rt.evaluate_script(global, "new Set([1, 2, 3])", "test", 1, rval.handle_mut()).unwrap(); let converted = Vec::<i32>::from_jsval(cx, rval.handle(), ConversionBehavior::Default).unwrap(); assert_eq!(orig_vec, converted); } }
identifier_body
vec_conversion.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ extern crate js; use js::conversions::ConversionBehavior; use js::conversions::FromJSValConvertible; use js::conversions::ToJSValConvertible; use js::jsapi::CompartmentOptions; use js::jsapi::JSAutoCompartment; use js::jsapi::JS_Init; use js::jsapi::JS_InitStandardClasses; use js::jsapi::JS_NewGlobalObject; use js::jsapi::OnNewGlobalHookOption; use js::jsapi::Rooted; use js::jsapi::RootedValue; use js::jsval::UndefinedValue; use js::rust::{Runtime, SIMPLE_GLOBAL_CLASS}; use std::ptr; #[test] fn
() { unsafe { assert!(JS_Init()); let rt = Runtime::new(ptr::null_mut()); let cx = rt.cx(); let h_option = OnNewGlobalHookOption::FireOnNewGlobalHook; let c_option = CompartmentOptions::default(); let global = JS_NewGlobalObject(cx, &SIMPLE_GLOBAL_CLASS, ptr::null_mut(), h_option, &c_option); let global_root = Rooted::new(cx, global); let global = global_root.handle(); let _ac = JSAutoCompartment::new(cx, global.get()); assert!(JS_InitStandardClasses(cx, global)); let mut rval = RootedValue::new(cx, UndefinedValue()); let orig_vec: Vec<f32> = vec![1.0, 2.9, 3.0]; orig_vec.to_jsval(cx, rval.handle_mut()); let converted = Vec::<f32>::from_jsval(cx, rval.handle(), ()).unwrap(); assert_eq!(orig_vec, converted); let orig_vec: Vec<i32> = vec![1, 2, 3]; orig_vec.to_jsval(cx, rval.handle_mut()); let converted = Vec::<i32>::from_jsval(cx, rval.handle(), ConversionBehavior::Default).unwrap(); assert_eq!(orig_vec, converted); rt.evaluate_script(global, "new Set([1, 2, 3])", "test", 1, rval.handle_mut()).unwrap(); let converted = Vec::<i32>::from_jsval(cx, rval.handle(), ConversionBehavior::Default).unwrap(); assert_eq!(orig_vec, converted); } }
vec_conversion
identifier_name
writer.rs
use schema::{Schema, Field, Document}; use fastfield::FastFieldSerializer; use std::io; use schema::Value; use DocId; use schema::FieldType; use common; use common::VInt; use common::BinarySerializable; /// The fastfieldswriter regroup all of the fast field writers. pub struct FastFieldsWriter { field_writers: Vec<IntFastFieldWriter>, } impl FastFieldsWriter { /// Create all `FastFieldWriter` required by the schema. pub fn from_schema(schema: &Schema) -> FastFieldsWriter { let field_writers: Vec<IntFastFieldWriter> = schema .fields() .iter() .enumerate() .flat_map(|(field_id, field_entry)| { let field = Field(field_id as u32); match *field_entry.field_type() { FieldType::I64(ref int_options) => { if int_options.is_fast() { let mut fast_field_writer = IntFastFieldWriter::new(field); fast_field_writer.set_val_if_missing(common::i64_to_u64(0i64)); Some(fast_field_writer) } else { None } } FieldType::U64(ref int_options) => { if int_options.is_fast() { Some(IntFastFieldWriter::new(field)) } else { None } } _ => None, } }) .collect(); FastFieldsWriter { field_writers: field_writers } } /// Returns a `FastFieldsWriter` /// with a `IntFastFieldWriter` for each /// of the field given in argument. pub fn new(fields: Vec<Field>) -> FastFieldsWriter { FastFieldsWriter { field_writers: fields.into_iter().map(IntFastFieldWriter::new).collect(), } } /// Get the `FastFieldWriter` associated to a field. pub fn get_field_writer(&mut self, field: Field) -> Option<&mut IntFastFieldWriter> { // TODO optimize self.field_writers .iter_mut() .find(|field_writer| field_writer.field == field) } /// Indexes all of the fastfields of a new document. pub fn add_document(&mut self, doc: &Document) { for field_writer in &mut self.field_writers { field_writer.add_document(doc); } } /// Serializes all of the `FastFieldWriter`s by pushing them in /// order to the fast field serializer. pub fn serialize(&self, serializer: &mut FastFieldSerializer) -> io::Result<()> { for field_writer in &self.field_writers { field_writer.serialize(serializer)?; } Ok(()) } /// Ensures all of the fast field writers have /// reached `doc`. (included) /// /// The missing values will be filled with 0. pub fn fill_val_up_to(&mut self, doc: DocId) { for field_writer in &mut self.field_writers { field_writer.fill_val_up_to(doc); } } } /// Fast field writer for ints.
/// method. /// /// We cannot serialize earlier as the values are /// bitpacked and the number of bits required for bitpacking /// can only been known once we have seen all of the values. /// /// Both u64, and i64 use the same writer. /// i64 are just remapped to the `0..2^64 - 1` /// using `common::i64_to_u64`. pub struct IntFastFieldWriter { field: Field, vals: Vec<u8>, val_count: usize, val_if_missing: u64, val_min: u64, val_max: u64, } impl IntFastFieldWriter { /// Creates a new `IntFastFieldWriter` pub fn new(field: Field) -> IntFastFieldWriter { IntFastFieldWriter { field: field, vals: Vec::new(), val_count: 0, val_if_missing: 0u64, val_min: u64::max_value(), val_max: 0, } } /// Sets the default value. /// /// This default value is recorded for documents if /// a document does not have any value. fn set_val_if_missing(&mut self, val_if_missing: u64) { self.val_if_missing = val_if_missing; } /// Ensures all of the fast field writer have /// reached `doc`. (included) /// /// The missing values will be filled with 0. fn fill_val_up_to(&mut self, doc: DocId) { let target = doc as usize + 1; debug_assert!(self.val_count <= target); let val_if_missing = self.val_if_missing; while self.val_count < target { self.add_val(val_if_missing); } } /// Records a new value. /// /// The n-th value being recorded is implicitely /// associated to the document with the `DocId` n. /// (Well, `n-1` actually because of 0-indexing) pub fn add_val(&mut self, val: u64) { VInt(val) .serialize(&mut self.vals) .expect("unable to serialize VInt to Vec"); if val > self.val_max { self.val_max = val; } if val < self.val_min { self.val_min = val; } self.val_count += 1; } /// Extract the value associated to the fast field for /// this document. /// /// i64 are remapped to u64 using the logic /// in `common::i64_to_u64`. /// /// If the value is missing, then the default value is used /// instead. /// If the document has more than one value for the given field, /// only the first one is taken in account. fn extract_val(&self, doc: &Document) -> u64 { match doc.get_first(self.field) { Some(v) => { match *v { Value::U64(ref val) => *val, Value::I64(ref val) => common::i64_to_u64(*val), _ => panic!("Expected a u64field, got {:?} ", v), } } None => self.val_if_missing, } } /// Extract the fast field value from the document /// (or use the default value) and records it. pub fn add_document(&mut self, doc: &Document) { let val = self.extract_val(doc); self.add_val(val); } /// Push the fast fields value to the `FastFieldWriter`. pub fn serialize(&self, serializer: &mut FastFieldSerializer) -> io::Result<()> { let (min, max) = if self.val_min > self.val_max { (0, 0) } else { (self.val_min, self.val_max) }; serializer.new_u64_fast_field(self.field, min, max)?; let mut cursor = self.vals.as_slice(); while let Ok(VInt(val)) = VInt::deserialize(&mut cursor) { serializer.add_val(val)?; } serializer.close_field() } }
/// The fast field writer just keeps the values in memory. /// /// Only when the segment writer can be closed and /// persisted on disc, the fast field writer is /// sent to a `FastFieldSerializer` via the `.serialize(...)`
random_line_split
writer.rs
use schema::{Schema, Field, Document}; use fastfield::FastFieldSerializer; use std::io; use schema::Value; use DocId; use schema::FieldType; use common; use common::VInt; use common::BinarySerializable; /// The fastfieldswriter regroup all of the fast field writers. pub struct FastFieldsWriter { field_writers: Vec<IntFastFieldWriter>, } impl FastFieldsWriter { /// Create all `FastFieldWriter` required by the schema. pub fn from_schema(schema: &Schema) -> FastFieldsWriter { let field_writers: Vec<IntFastFieldWriter> = schema .fields() .iter() .enumerate() .flat_map(|(field_id, field_entry)| { let field = Field(field_id as u32); match *field_entry.field_type() { FieldType::I64(ref int_options) => { if int_options.is_fast() { let mut fast_field_writer = IntFastFieldWriter::new(field); fast_field_writer.set_val_if_missing(common::i64_to_u64(0i64)); Some(fast_field_writer) } else { None } } FieldType::U64(ref int_options) => { if int_options.is_fast() { Some(IntFastFieldWriter::new(field)) } else { None } } _ => None, } }) .collect(); FastFieldsWriter { field_writers: field_writers } } /// Returns a `FastFieldsWriter` /// with a `IntFastFieldWriter` for each /// of the field given in argument. pub fn new(fields: Vec<Field>) -> FastFieldsWriter { FastFieldsWriter { field_writers: fields.into_iter().map(IntFastFieldWriter::new).collect(), } } /// Get the `FastFieldWriter` associated to a field. pub fn get_field_writer(&mut self, field: Field) -> Option<&mut IntFastFieldWriter> { // TODO optimize self.field_writers .iter_mut() .find(|field_writer| field_writer.field == field) } /// Indexes all of the fastfields of a new document. pub fn add_document(&mut self, doc: &Document) { for field_writer in &mut self.field_writers { field_writer.add_document(doc); } } /// Serializes all of the `FastFieldWriter`s by pushing them in /// order to the fast field serializer. pub fn serialize(&self, serializer: &mut FastFieldSerializer) -> io::Result<()> { for field_writer in &self.field_writers { field_writer.serialize(serializer)?; } Ok(()) } /// Ensures all of the fast field writers have /// reached `doc`. (included) /// /// The missing values will be filled with 0. pub fn fill_val_up_to(&mut self, doc: DocId) { for field_writer in &mut self.field_writers { field_writer.fill_val_up_to(doc); } } } /// Fast field writer for ints. /// The fast field writer just keeps the values in memory. /// /// Only when the segment writer can be closed and /// persisted on disc, the fast field writer is /// sent to a `FastFieldSerializer` via the `.serialize(...)` /// method. /// /// We cannot serialize earlier as the values are /// bitpacked and the number of bits required for bitpacking /// can only been known once we have seen all of the values. /// /// Both u64, and i64 use the same writer. /// i64 are just remapped to the `0..2^64 - 1` /// using `common::i64_to_u64`. pub struct IntFastFieldWriter { field: Field, vals: Vec<u8>, val_count: usize, val_if_missing: u64, val_min: u64, val_max: u64, } impl IntFastFieldWriter { /// Creates a new `IntFastFieldWriter` pub fn new(field: Field) -> IntFastFieldWriter { IntFastFieldWriter { field: field, vals: Vec::new(), val_count: 0, val_if_missing: 0u64, val_min: u64::max_value(), val_max: 0, } } /// Sets the default value. /// /// This default value is recorded for documents if /// a document does not have any value. fn set_val_if_missing(&mut self, val_if_missing: u64) { self.val_if_missing = val_if_missing; } /// Ensures all of the fast field writer have /// reached `doc`. (included) /// /// The missing values will be filled with 0. fn fill_val_up_to(&mut self, doc: DocId) { let target = doc as usize + 1; debug_assert!(self.val_count <= target); let val_if_missing = self.val_if_missing; while self.val_count < target { self.add_val(val_if_missing); } } /// Records a new value. /// /// The n-th value being recorded is implicitely /// associated to the document with the `DocId` n. /// (Well, `n-1` actually because of 0-indexing) pub fn add_val(&mut self, val: u64) { VInt(val) .serialize(&mut self.vals) .expect("unable to serialize VInt to Vec"); if val > self.val_max { self.val_max = val; } if val < self.val_min { self.val_min = val; } self.val_count += 1; } /// Extract the value associated to the fast field for /// this document. /// /// i64 are remapped to u64 using the logic /// in `common::i64_to_u64`. /// /// If the value is missing, then the default value is used /// instead. /// If the document has more than one value for the given field, /// only the first one is taken in account. fn extract_val(&self, doc: &Document) -> u64 { match doc.get_first(self.field) { Some(v) => { match *v { Value::U64(ref val) => *val, Value::I64(ref val) => common::i64_to_u64(*val), _ => panic!("Expected a u64field, got {:?} ", v), } } None => self.val_if_missing, } } /// Extract the fast field value from the document /// (or use the default value) and records it. pub fn
(&mut self, doc: &Document) { let val = self.extract_val(doc); self.add_val(val); } /// Push the fast fields value to the `FastFieldWriter`. pub fn serialize(&self, serializer: &mut FastFieldSerializer) -> io::Result<()> { let (min, max) = if self.val_min > self.val_max { (0, 0) } else { (self.val_min, self.val_max) }; serializer.new_u64_fast_field(self.field, min, max)?; let mut cursor = self.vals.as_slice(); while let Ok(VInt(val)) = VInt::deserialize(&mut cursor) { serializer.add_val(val)?; } serializer.close_field() } }
add_document
identifier_name
Histogram.tsx
/* * SonarQube * Copyright (C) 2009-2022 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ import { max } from 'd3-array'; import { scaleBand, ScaleBand, scaleLinear, ScaleLinear } from 'd3-scale'; import * as React from 'react'; import Tooltip from '../controls/Tooltip'; import './BarChart.css'; import './Histogram.css'; interface Props { alignTicks?: boolean; bars: number[]; height: number; padding?: [number, number, number, number]; yTicks?: string[]; yTooltips?: string[]; yValues?: string[]; width: number; } const BAR_HEIGHT = 10; const DEFAULT_PADDING = [10, 10, 10, 10]; type XScale = ScaleLinear<number, number>; type YScale = ScaleBand<number>; export default class Histogram extends React.PureComponent<Props> { renderBar(d: number, index: number, xScale: XScale, yScale: YScale) { const { alignTicks, padding = DEFAULT_PADDING } = this.props; const width = Math.round(xScale(d)) + /* minimum bar width */ 1; const x = xScale.range()[0] + (alignTicks ? padding[3] : 0); const y = Math.round((yScale(index) || 0) + yScale.bandwidth() / 2); return <rect className="bar-chart-bar" height={BAR_HEIGHT} width={width} x={x} y={y} />; } renderValue(d: number, index: number, xScale: XScale, yScale: YScale) { const { alignTicks, padding = DEFAULT_PADDING, yValues } = this.props; const value = yValues && yValues[index]; if (!value) { return null; } const x = xScale(d) + (alignTicks ? padding[3] : 0); const y = Math.round((yScale(index) || 0) + yScale.bandwidth() / 2 + BAR_HEIGHT / 2); return ( <Tooltip overlay={this.props.yTooltips && this.props.yTooltips[index]}> <text className="bar-chart-tick histogram-value" dx="1em" dy="0.3em" x={x} y={y}> {value} </text> </Tooltip> ); } renderTick(index: number, xScale: XScale, yScale: YScale) { const { alignTicks, yTicks } = this.props; const tick = yTicks && yTicks[index]; if (!tick) {
const x = xScale.range()[0]; const y = Math.round((yScale(index) || 0) + yScale.bandwidth() / 2 + BAR_HEIGHT / 2); const historyTickClass = alignTicks ? 'histogram-tick-start' : 'histogram-tick'; return ( <text className={'bar-chart-tick ' + historyTickClass} dx={alignTicks ? 0 : '-1em'} dy="0.3em" x={x} y={y}> {tick} </text> ); } renderBars(xScale: XScale, yScale: YScale) { return ( <g> {this.props.bars.map((d, index) => { return ( // eslint-disable-next-line react/no-array-index-key <g key={index}> {this.renderBar(d, index, xScale, yScale)} {this.renderValue(d, index, xScale, yScale)} {this.renderTick(index, xScale, yScale)} </g> ); })} </g> ); } render() { const { bars, width, height, padding = DEFAULT_PADDING } = this.props; const availableWidth = width - padding[1] - padding[3]; const xScale: XScale = scaleLinear() .domain([0, max(bars)!]) .range([0, availableWidth]); const availableHeight = height - padding[0] - padding[2]; const yScale: YScale = scaleBand<number>() .domain(bars.map((_, index) => index)) .rangeRound([0, availableHeight]); return ( <svg className="bar-chart" height={this.props.height} width={this.props.width}> <g transform={`translate(${this.props.alignTicks ? 4 : padding[3]}, ${padding[0]})`}> {this.renderBars(xScale, yScale)} </g> </svg> ); } }
return null; }
random_line_split
Histogram.tsx
/* * SonarQube * Copyright (C) 2009-2022 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ import { max } from 'd3-array'; import { scaleBand, ScaleBand, scaleLinear, ScaleLinear } from 'd3-scale'; import * as React from 'react'; import Tooltip from '../controls/Tooltip'; import './BarChart.css'; import './Histogram.css'; interface Props { alignTicks?: boolean; bars: number[]; height: number; padding?: [number, number, number, number]; yTicks?: string[]; yTooltips?: string[]; yValues?: string[]; width: number; } const BAR_HEIGHT = 10; const DEFAULT_PADDING = [10, 10, 10, 10]; type XScale = ScaleLinear<number, number>; type YScale = ScaleBand<number>; export default class Histogram extends React.PureComponent<Props> { renderBar(d: number, index: number, xScale: XScale, yScale: YScale) { const { alignTicks, padding = DEFAULT_PADDING } = this.props; const width = Math.round(xScale(d)) + /* minimum bar width */ 1; const x = xScale.range()[0] + (alignTicks ? padding[3] : 0); const y = Math.round((yScale(index) || 0) + yScale.bandwidth() / 2); return <rect className="bar-chart-bar" height={BAR_HEIGHT} width={width} x={x} y={y} />; } renderValue(d: number, index: number, xScale: XScale, yScale: YScale) { const { alignTicks, padding = DEFAULT_PADDING, yValues } = this.props; const value = yValues && yValues[index]; if (!value)
const x = xScale(d) + (alignTicks ? padding[3] : 0); const y = Math.round((yScale(index) || 0) + yScale.bandwidth() / 2 + BAR_HEIGHT / 2); return ( <Tooltip overlay={this.props.yTooltips && this.props.yTooltips[index]}> <text className="bar-chart-tick histogram-value" dx="1em" dy="0.3em" x={x} y={y}> {value} </text> </Tooltip> ); } renderTick(index: number, xScale: XScale, yScale: YScale) { const { alignTicks, yTicks } = this.props; const tick = yTicks && yTicks[index]; if (!tick) { return null; } const x = xScale.range()[0]; const y = Math.round((yScale(index) || 0) + yScale.bandwidth() / 2 + BAR_HEIGHT / 2); const historyTickClass = alignTicks ? 'histogram-tick-start' : 'histogram-tick'; return ( <text className={'bar-chart-tick ' + historyTickClass} dx={alignTicks ? 0 : '-1em'} dy="0.3em" x={x} y={y}> {tick} </text> ); } renderBars(xScale: XScale, yScale: YScale) { return ( <g> {this.props.bars.map((d, index) => { return ( // eslint-disable-next-line react/no-array-index-key <g key={index}> {this.renderBar(d, index, xScale, yScale)} {this.renderValue(d, index, xScale, yScale)} {this.renderTick(index, xScale, yScale)} </g> ); })} </g> ); } render() { const { bars, width, height, padding = DEFAULT_PADDING } = this.props; const availableWidth = width - padding[1] - padding[3]; const xScale: XScale = scaleLinear() .domain([0, max(bars)!]) .range([0, availableWidth]); const availableHeight = height - padding[0] - padding[2]; const yScale: YScale = scaleBand<number>() .domain(bars.map((_, index) => index)) .rangeRound([0, availableHeight]); return ( <svg className="bar-chart" height={this.props.height} width={this.props.width}> <g transform={`translate(${this.props.alignTicks ? 4 : padding[3]}, ${padding[0]})`}> {this.renderBars(xScale, yScale)} </g> </svg> ); } }
{ return null; }
conditional_block
Histogram.tsx
/* * SonarQube * Copyright (C) 2009-2022 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ import { max } from 'd3-array'; import { scaleBand, ScaleBand, scaleLinear, ScaleLinear } from 'd3-scale'; import * as React from 'react'; import Tooltip from '../controls/Tooltip'; import './BarChart.css'; import './Histogram.css'; interface Props { alignTicks?: boolean; bars: number[]; height: number; padding?: [number, number, number, number]; yTicks?: string[]; yTooltips?: string[]; yValues?: string[]; width: number; } const BAR_HEIGHT = 10; const DEFAULT_PADDING = [10, 10, 10, 10]; type XScale = ScaleLinear<number, number>; type YScale = ScaleBand<number>; export default class Histogram extends React.PureComponent<Props> { renderBar(d: number, index: number, xScale: XScale, yScale: YScale) { const { alignTicks, padding = DEFAULT_PADDING } = this.props; const width = Math.round(xScale(d)) + /* minimum bar width */ 1; const x = xScale.range()[0] + (alignTicks ? padding[3] : 0); const y = Math.round((yScale(index) || 0) + yScale.bandwidth() / 2); return <rect className="bar-chart-bar" height={BAR_HEIGHT} width={width} x={x} y={y} />; } renderValue(d: number, index: number, xScale: XScale, yScale: YScale)
renderTick(index: number, xScale: XScale, yScale: YScale) { const { alignTicks, yTicks } = this.props; const tick = yTicks && yTicks[index]; if (!tick) { return null; } const x = xScale.range()[0]; const y = Math.round((yScale(index) || 0) + yScale.bandwidth() / 2 + BAR_HEIGHT / 2); const historyTickClass = alignTicks ? 'histogram-tick-start' : 'histogram-tick'; return ( <text className={'bar-chart-tick ' + historyTickClass} dx={alignTicks ? 0 : '-1em'} dy="0.3em" x={x} y={y}> {tick} </text> ); } renderBars(xScale: XScale, yScale: YScale) { return ( <g> {this.props.bars.map((d, index) => { return ( // eslint-disable-next-line react/no-array-index-key <g key={index}> {this.renderBar(d, index, xScale, yScale)} {this.renderValue(d, index, xScale, yScale)} {this.renderTick(index, xScale, yScale)} </g> ); })} </g> ); } render() { const { bars, width, height, padding = DEFAULT_PADDING } = this.props; const availableWidth = width - padding[1] - padding[3]; const xScale: XScale = scaleLinear() .domain([0, max(bars)!]) .range([0, availableWidth]); const availableHeight = height - padding[0] - padding[2]; const yScale: YScale = scaleBand<number>() .domain(bars.map((_, index) => index)) .rangeRound([0, availableHeight]); return ( <svg className="bar-chart" height={this.props.height} width={this.props.width}> <g transform={`translate(${this.props.alignTicks ? 4 : padding[3]}, ${padding[0]})`}> {this.renderBars(xScale, yScale)} </g> </svg> ); } }
{ const { alignTicks, padding = DEFAULT_PADDING, yValues } = this.props; const value = yValues && yValues[index]; if (!value) { return null; } const x = xScale(d) + (alignTicks ? padding[3] : 0); const y = Math.round((yScale(index) || 0) + yScale.bandwidth() / 2 + BAR_HEIGHT / 2); return ( <Tooltip overlay={this.props.yTooltips && this.props.yTooltips[index]}> <text className="bar-chart-tick histogram-value" dx="1em" dy="0.3em" x={x} y={y}> {value} </text> </Tooltip> ); }
identifier_body
Histogram.tsx
/* * SonarQube * Copyright (C) 2009-2022 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ import { max } from 'd3-array'; import { scaleBand, ScaleBand, scaleLinear, ScaleLinear } from 'd3-scale'; import * as React from 'react'; import Tooltip from '../controls/Tooltip'; import './BarChart.css'; import './Histogram.css'; interface Props { alignTicks?: boolean; bars: number[]; height: number; padding?: [number, number, number, number]; yTicks?: string[]; yTooltips?: string[]; yValues?: string[]; width: number; } const BAR_HEIGHT = 10; const DEFAULT_PADDING = [10, 10, 10, 10]; type XScale = ScaleLinear<number, number>; type YScale = ScaleBand<number>; export default class Histogram extends React.PureComponent<Props> { renderBar(d: number, index: number, xScale: XScale, yScale: YScale) { const { alignTicks, padding = DEFAULT_PADDING } = this.props; const width = Math.round(xScale(d)) + /* minimum bar width */ 1; const x = xScale.range()[0] + (alignTicks ? padding[3] : 0); const y = Math.round((yScale(index) || 0) + yScale.bandwidth() / 2); return <rect className="bar-chart-bar" height={BAR_HEIGHT} width={width} x={x} y={y} />; } renderValue(d: number, index: number, xScale: XScale, yScale: YScale) { const { alignTicks, padding = DEFAULT_PADDING, yValues } = this.props; const value = yValues && yValues[index]; if (!value) { return null; } const x = xScale(d) + (alignTicks ? padding[3] : 0); const y = Math.round((yScale(index) || 0) + yScale.bandwidth() / 2 + BAR_HEIGHT / 2); return ( <Tooltip overlay={this.props.yTooltips && this.props.yTooltips[index]}> <text className="bar-chart-tick histogram-value" dx="1em" dy="0.3em" x={x} y={y}> {value} </text> </Tooltip> ); }
(index: number, xScale: XScale, yScale: YScale) { const { alignTicks, yTicks } = this.props; const tick = yTicks && yTicks[index]; if (!tick) { return null; } const x = xScale.range()[0]; const y = Math.round((yScale(index) || 0) + yScale.bandwidth() / 2 + BAR_HEIGHT / 2); const historyTickClass = alignTicks ? 'histogram-tick-start' : 'histogram-tick'; return ( <text className={'bar-chart-tick ' + historyTickClass} dx={alignTicks ? 0 : '-1em'} dy="0.3em" x={x} y={y}> {tick} </text> ); } renderBars(xScale: XScale, yScale: YScale) { return ( <g> {this.props.bars.map((d, index) => { return ( // eslint-disable-next-line react/no-array-index-key <g key={index}> {this.renderBar(d, index, xScale, yScale)} {this.renderValue(d, index, xScale, yScale)} {this.renderTick(index, xScale, yScale)} </g> ); })} </g> ); } render() { const { bars, width, height, padding = DEFAULT_PADDING } = this.props; const availableWidth = width - padding[1] - padding[3]; const xScale: XScale = scaleLinear() .domain([0, max(bars)!]) .range([0, availableWidth]); const availableHeight = height - padding[0] - padding[2]; const yScale: YScale = scaleBand<number>() .domain(bars.map((_, index) => index)) .rangeRound([0, availableHeight]); return ( <svg className="bar-chart" height={this.props.height} width={this.props.width}> <g transform={`translate(${this.props.alignTicks ? 4 : padding[3]}, ${padding[0]})`}> {this.renderBars(xScale, yScale)} </g> </svg> ); } }
renderTick
identifier_name
BernoulliNBJSTest.py
# -*- coding: utf-8 -*- import unittest from unittest import TestCase from sklearn.naive_bayes import BernoulliNB from tests.estimator.classifier.Classifier import Classifier from tests.language.JavaScript import JavaScript class BernoulliNBJSTest(JavaScript, Classifier, TestCase): def setUp(self):
def tearDown(self): super(BernoulliNBJSTest, self).tearDown() @unittest.skip('BernoulliNB is just suitable for discrete data.') def test_random_features__iris_data__default(self): pass @unittest.skip('BernoulliNB is just suitable for discrete data.') def test_existing_features__binary_data__default(self): pass @unittest.skip('BernoulliNB is just suitable for discrete data.') def test_random_features__binary_data__default(self): pass @unittest.skip('BernoulliNB is just suitable for discrete data.') def test_random_features__digits_data__default(self): pass @unittest.skip('BernoulliNB is just suitable for discrete data.') def test_existing_features__digits_data__default(self): pass
super(BernoulliNBJSTest, self).setUp() self.estimator = BernoulliNB()
identifier_body
BernoulliNBJSTest.py
# -*- coding: utf-8 -*- import unittest from unittest import TestCase from sklearn.naive_bayes import BernoulliNB from tests.estimator.classifier.Classifier import Classifier from tests.language.JavaScript import JavaScript class BernoulliNBJSTest(JavaScript, Classifier, TestCase): def
(self): super(BernoulliNBJSTest, self).setUp() self.estimator = BernoulliNB() def tearDown(self): super(BernoulliNBJSTest, self).tearDown() @unittest.skip('BernoulliNB is just suitable for discrete data.') def test_random_features__iris_data__default(self): pass @unittest.skip('BernoulliNB is just suitable for discrete data.') def test_existing_features__binary_data__default(self): pass @unittest.skip('BernoulliNB is just suitable for discrete data.') def test_random_features__binary_data__default(self): pass @unittest.skip('BernoulliNB is just suitable for discrete data.') def test_random_features__digits_data__default(self): pass @unittest.skip('BernoulliNB is just suitable for discrete data.') def test_existing_features__digits_data__default(self): pass
setUp
identifier_name
BernoulliNBJSTest.py
# -*- coding: utf-8 -*- import unittest from unittest import TestCase from sklearn.naive_bayes import BernoulliNB from tests.estimator.classifier.Classifier import Classifier from tests.language.JavaScript import JavaScript class BernoulliNBJSTest(JavaScript, Classifier, TestCase): def setUp(self): super(BernoulliNBJSTest, self).setUp() self.estimator = BernoulliNB() def tearDown(self): super(BernoulliNBJSTest, self).tearDown() @unittest.skip('BernoulliNB is just suitable for discrete data.') def test_random_features__iris_data__default(self): pass @unittest.skip('BernoulliNB is just suitable for discrete data.') def test_existing_features__binary_data__default(self): pass @unittest.skip('BernoulliNB is just suitable for discrete data.') def test_random_features__binary_data__default(self): pass
@unittest.skip('BernoulliNB is just suitable for discrete data.') def test_existing_features__digits_data__default(self): pass
@unittest.skip('BernoulliNB is just suitable for discrete data.') def test_random_features__digits_data__default(self): pass
random_line_split
rpc_mock.py
from bitcoingraph.bitcoind import BitcoinProxy, BitcoindException from pathlib import Path import json TEST_DATA_PATH = "tests/data" class BitcoinProxyMock(BitcoinProxy): def __init__(self, host=None, port=None): super().__init__(host, port) self.heights = {} self.blocks = {} self.txs = {} self.load_testdata() # Load test data into local dicts def load_testdata(self): p = Path(TEST_DATA_PATH) files = [x for x in p.iterdir() if x.is_file() and x.name.endswith('json')] for f in files: if f.name.startswith("block"):
elif f.name.startswith("tx"): tx_hash = f.name[3:-5] with f.open() as jf: raw_block = json.load(jf) self.txs[tx_hash] = raw_block # Override production proxy methods def getblock(self, block_hash): if block_hash not in self.blocks: raise BitcoindException("Unknown block", block_hash) else: return self.blocks[block_hash] def getblockcount(self): return max(self.heights.keys()) def getblockhash(self, block_height): if block_height not in self.heights: raise BitcoindException("Unknown height", block_height) else: return self.heights[block_height] def getinfo(self): print("No info") def getrawtransaction(self, tx_id, verbose=1): if tx_id not in self.txs: raise BitcoindException("Unknown transaction", tx_id) else: return self.txs[tx_id] def getrawtransactions(self, tx_ids, verbose=1): results = [] for tx_id in tx_ids: results.append(self.getrawtransaction(tx_id, verbose)) return results
height = f.name[6:-5] with f.open() as jf: raw_block = json.load(jf) block_hash = raw_block['hash'] self.heights[int(height)] = block_hash self.blocks[block_hash] = raw_block
conditional_block