code stringlengths 2 1.05M | repo_name stringlengths 5 114 | path stringlengths 4 991 | language stringclasses 1 value | license stringclasses 15 values | size int32 2 1.05M |
|---|---|---|---|---|---|
jsonp({"cep":"69901040","logradouro":"Travessa Vera Cruz","bairro":"Morada do Sol","cidade":"Rio Branco","uf":"AC","estado":"Acre"});
| lfreneda/cepdb | api/v1/69901040.jsonp.js | JavaScript | cc0-1.0 | 134 |
jsonp({"cep":"89260387","logradouro":"Servid\u00e3o Germano Karsten","bairro":"Barra do Rio Cerro","cidade":"Jaragu\u00e1 do Sul","uf":"SC","estado":"Santa Catarina"});
| lfreneda/cepdb | api/v1/89260387.jsonp.js | JavaScript | cc0-1.0 | 169 |
jsonp({"cep":"72850715","logradouro":"Rua Rio de Janeiro","bairro":"Jardim J\u00f3ckei Clube","cidade":"Luzi\u00e2nia","uf":"GO","estado":"Goi\u00e1s"});
| lfreneda/cepdb | api/v1/72850715.jsonp.js | JavaScript | cc0-1.0 | 154 |
jsonp({"cep":"74870250","logradouro":"Rua DF 24","bairro":"Ch\u00e1cara do Governador","cidade":"Goi\u00e2nia","uf":"GO","estado":"Goi\u00e1s"});
| lfreneda/cepdb | api/v1/74870250.jsonp.js | JavaScript | cc0-1.0 | 146 |
jsonp({"cep":"79071360","logradouro":"Rua Odorico Mendes","bairro":"N\u00facleo Habitacional Universit\u00e1rias","cidade":"Campo Grande","uf":"MS","estado":"Mato Grosso do Sul"});
| lfreneda/cepdb | api/v1/79071360.jsonp.js | JavaScript | cc0-1.0 | 181 |
jsonp({"cep":"49015470","logradouro":"Travessa David Bitencourt Luduvice","bairro":"S\u00e3o Jos\u00e9","cidade":"Aracaju","uf":"SE","estado":"Sergipe"});
| lfreneda/cepdb | api/v1/49015470.jsonp.js | JavaScript | cc0-1.0 | 155 |
jsonp({"cep":"41235130","logradouro":"Avenida Janda\u00edra","bairro":"Pau da Lima","cidade":"Salvador","uf":"BA","estado":"Bahia"});
| lfreneda/cepdb | api/v1/41235130.jsonp.js | JavaScript | cc0-1.0 | 134 |
var library = require('./library.js');
var check_cond = function(num, div, start)
{
var n = '';
for(var i = start; i < start + 3; i++)
{
n = n + num.toString().charAt(i - 1);
}
if(parseInt(n) % div === 0)
{
return true;
}
return false;
}
var check_all = function(num)
{
var all = [2, 3, 5, 7, 11, 13, 17];
for(var i = 0; i < all.length; i += 1)
{
if(!check_cond(num, all[i], i + 2))
{
return false;
}
}
return true;
}
var solve = function ()
{
var sum = 0;
var start = 1234567890;
var end = 9876543210;
for(var i = start, count = 0; i <= end; i += 1, count += 1)
{
if(count % 1000000 == 0)
{
console.log("\$i : " + i);
}
if(!library.is_pandigital(i, 0))
{
continue;
}
if(!check_all(i))
{
continue;
}
console.log("OK : " + i);
sum += i;
}
};
var check_all_2 = function(num)
{
var y = num.toString();
var n = [0];
for(var i = 0; i < y.length; i += 1)
{
n.push(parseInt(y[i]));
}
if(n[4] % 2 != 0)
{
return false;
}
var a = n[3] + n[4] + n[5];
if(a % 3 != 0)
{
return false;
}
if(n[6] % 5 != 0)
{
return false;
}
var b = n[5] * 10 + n[6] - 2 * n[7];
if(b % 7 != 0)
{
return false;
}
var c = n[6] * 10 + n[7] - n[8];
if(c % 11 != 0)
{
return false;
}
var d = n[7] * 10 + n[8] + 4 * n[9];
if(d % 13 != 0)
{
return false;
}
var e = n[8] * 10 + n[9] - 5 * n[10];
if(e % 17 != 0)
{
return false;
}
return true;
}
var solve_2 = function ()
{
var sum = 0;
var start = 1234567890;
var end = 9876543210;
for(var i = start, count = 0; i <= end; i += 1, count += 1)
{
if(count % 1000000 == 0)
{
console.log("\$i : " + i);
}
if(!check_all_2(i))
{
continue;
}
if(!library.is_pandigital_v2(i, 0))
{
continue;
}
console.log("OK : " + i);
sum += i;
}
};
var sum = solve_2();
console.log(sum);
//var num = process.argv[2];
//console.log(check_all_2(num));
| xitkov/projecteuler | other-lang/js/solve0043.js | JavaScript | epl-1.0 | 2,372 |
var gulp = require('gulp');
var sourcemaps = require('gulp-sourcemaps');
var source = require('vinyl-source-stream');
var buffer = require('vinyl-buffer');
var browserify = require('browserify');
var watchify = require('watchify');
var babel = require('babelify');
var jade = require('gulp-jade');
var connect = require('gulp-connect');
var uglify = require('gulp-uglify');
var envify = require('envify/custom');
var file = require('gulp-file');
var buildDir = 'build';
var devBuildDir = 'dev_build';
function handleError(err) {
console.error(err); // eslint-disable-line no-console
this.emit('end');
}
function templates(outDir) {
return function() {
return gulp.src('public/*.jade')
.pipe(jade())
.pipe(gulp.dest(outDir));
};
}
function styles(outDir) {
return function() {
return gulp.src('public/*.css')
.pipe(gulp.dest(outDir))
.pipe(connect.reload());
};
}
function vendor(outDir) {
return function() {
return gulp.src('public/vendor/**')
.pipe(gulp.dest(outDir + '/vendor'));
};
}
function icons(outDir) {
return function() {
return gulp.src('public/icons/**')
.pipe(gulp.dest(outDir + '/icons'));
};
}
gulp.task('templates', templates(devBuildDir));
gulp.task('styles', styles(devBuildDir));
gulp.task('vendor', vendor(devBuildDir));
gulp.task('icons', icons(devBuildDir));
function compile(opts) {
var bundler = watchify(
browserify('./public/main.js', { debug: true })
.transform(babel)
.transform(envify({
NODE_ENV: 'development'
}), {global: true})
);
function rebundle() {
return bundler.bundle()
.on('error', handleError)
.pipe(source('main.js'))
.pipe(buffer())
.pipe(sourcemaps.init({ loadMaps: true }))
.pipe(sourcemaps.write('./'))
.pipe(gulp.dest(devBuildDir))
.pipe(connect.reload());
}
if (opts.watch) {
bundler.on('update', function() {
console.log('-> bundling...'); // eslint-disable-line no-console
return rebundle();
});
}
return rebundle();
}
gulp.task('connect', function() {
return connect.server({
root: devBuildDir,
livereload: true
});
});
gulp.task('watch', function() {
gulp.watch('public/*.css', ['styles']);
return compile({watch: true});
});
gulp.task('build', function() {
templates(buildDir)();
styles(buildDir)();
vendor(buildDir)();
icons(buildDir)();
file('CNAME', 'circuits.im', { src: true })
.pipe(gulp.dest(buildDir));
return browserify('./public/main.js')
.transform(envify({
NODE_ENV: 'production'
}), {global: true})
.transform(babel.configure({
optional: [
'optimisation.react.constantElements',
'optimisation.react.inlineElements'
]
}))
.bundle().on('error', handleError)
.pipe(source('main.js'))
.pipe(buffer())
.pipe(uglify())
.pipe(gulp.dest(buildDir));
});
gulp.task('default', ['templates', 'vendor', 'styles', 'icons', 'connect', 'watch']);
| circuitsim/circuit-simulator | gulpfile.js | JavaScript | epl-1.0 | 2,998 |
/* Updates fields based on checkbox changes
*/
var PRFtoggleEnabled = function(cbox, id, type) {
oldval = cbox.checked ? 0 : 1;
var dataS = {
"action" : "toggleEnabled",
"id": id,
"type": type,
"oldval": oldval,
};
data = $.param(dataS);
$.ajax({
type: "POST",
dataType: "json",
url: site_admin_url + "/plugins/profile/ajax.php",
data: data,
success: function(result) {
cbox.checked = result.newval == 1 ? true : false;
try {
if (result.newval == oldval) {
icon = "<i class='uk-icon-exclamation-triangle'></i> ";
} else {
icon = "<i class='uk-icon-check'></i> ";
}
$.UIkit.notify(icon + result.statusMessage, {timeout: 1000,pos:'top-center'});
}
catch(err) {
$.UIkit.notify("<i class='uk-icon-exclamation-triangle'></i> " + result.statusMessage, {timeout: 1000,pos:'top-center'});
alert(result.statusMessage);
}
}
});
return false;
};
/**
* Not a toggle function; this updates the 3-part date field with data
* from the datepicker.
* @param Date d Date object
* @param string fld Field Name
* @param integer tm_type 12- or 24-hour indicator, 0 = no time field
*/
function PRF_updateDate(d, fld, tm_type)
{
document.getElementById(fld + "_month").selectedIndex = d.getMonth() + 1;
document.getElementById(fld + "_day").selectedIndex = d.getDate();
document.getElementById(fld + "_year").value = d.getFullYear();
// Update the time, if time fields are present.
if (tm_type != 0) {
var hour = d.getHours();
var ampm = 0;
if (tm_type == "12") {
if (hour == 0) {
hour = 12;
} else if (hour > 12) {
hour -= 12;
ampm = 1;
}
document.getElementById(fld + "_ampm").selectedIndex = ampm;
}
document.getElementById(fld + "_hour").selectedIndex = hour;
document.getElementById(fld + "_minute").selectedIndex = d.getMinutes();
}
}
| leegarner-glfusion/profile | js/toggleEnabled.js | JavaScript | gpl-2.0 | 2,241 |
var aux={sort:function(){}};var excSorter={enabled:false,sBundle:'',button:'',init:function(){var bs=Components.classes["@mozilla.org/intl/stringbundle;1"].getService(Components.interfaces.nsIStringBundleService);this.sBundle=bs.createBundle("chrome://sortexceptions/locale/sortexceptions.properties");var elems=document.getElementsByTagName("hbox");var father=elems[elems.length-1];elems=father.getElementsByTagName("spacer");var child=elems[0];this.button=document.createElement("button");this.button.setAttribute("label",this.sBundle.GetStringFromName("labelEnab"));this.button.setAttribute("oncommand","excSorter.toggle();");father.insertBefore(this.button,child);},flipDomains:function(aString){var str="";var arrayOfStrings=aString.split(".");for(var i=0;i<arrayOfStrings.length;i++){str=arrayOfStrings[i]+"."+str;}
return str;},toggle:function(){if(this.enabled){this.disable();this.enabled=false;this.button.label=this.sBundle.GetStringFromName("labelEnab");}
else{this.enable();this.enabled=true;this.button.label=this.sBundle.GetStringFromName("labelDisab");};},enable:function(){aux.sort=gTreeUtils.sort;gTreeUtils.sort=this.sort;gPermissionManager.onPermissionSort('rawHost');},disable:function(){gTreeUtils.sort=aux.sort;gPermissionManager.onPermissionSort('rawHost');},sort:function(aTree,aView,aDataSet,aColumn,aLastSortColumn,aLastSortAscending){if(aColumn!='rawHost'){return aux.sort(aTree,aView,aDataSet,aColumn,aLastSortColumn,aLastSortAscending);}
else{var ascending=(aColumn==aLastSortColumn)?!aLastSortAscending:true;aDataSet.sort(function(a,b){var aa=excSorter.flipDomains(a[aColumn].toLowerCase());var bb=excSorter.flipDomains(b[aColumn].toLowerCase());return aa.localeCompare(bb);});if(!ascending)
aDataSet.reverse();aTree.view.selection.select(-1);aTree.view.selection.select(0);aTree.treeBoxObject.invalidate();aTree.treeBoxObject.ensureRowIsVisible(0);return ascending;}}}; | TPS/SortExceptions | XPI/chrome/content/sortexceptions.js | JavaScript | gpl-2.0 | 1,907 |
jQuery(document).ready(function(){
jQuery("#ResponsiveContactForm").validate({
submitHandler: function(form)
{
jQuery.ajax({
type: "POST",
dataType: "json",
url:MyAjax,
data:{
action: 'ai_action',
fdata : jQuery(document.formValidate).serialize()
},
success:function(response) {
if(response == 1){
jQuery("#smsg").slideDown(function(){
jQuery('html, body').animate({scrollTop: jQuery("#smsg").offset().top},'fast');
jQuery(this).show().delay(8000).slideUp("fast")});
document.getElementById('ResponsiveContactForm').reset();
refreshCaptcha();
jQuery(".input-xlarge").removeClass("valid");
jQuery(".input-xlarge").next('label.valid').remove();
}else if(response == 2){
jQuery("#fmsg").slideDown(function(){
jQuery(this).show().delay(8000).slideUp("fast")});
jQuery("#captcha").removeClass("valid").addClass("error");
jQuery("#captcha").next('label.valid').removeClass("valid").addClass("error");
jQuery('#captcha').val('');
refreshCaptcha();
}else{
alert(response);
}
}
});
}
});
}); | andile-admin/new_election | wp-content/plugins/responsive-contact-form/js/ajax.js | JavaScript | gpl-2.0 | 1,183 |
(function ($) {
$(document).ready(function() {
var highestCol = Math.max($('.first-menu .pane-content').height(),$('.middle-menu .pane-content').height(),$('.last-menu .pane-content').height());
/*.first-menu .pane-content, .middle-menu .pane-content, .last-menu .pane-content
$('.elements').height(highestCol);*/
alert(highestCol);
});
})(jQuery);
| l0c0/consulados | sites/all/themes/embajada/equals_height.js | JavaScript | gpl-2.0 | 372 |
var events = require("events"),
util = require("util"),
colors = require("colors"),
Firmata = require("firmata").Board,
_ = require("lodash"),
__ = require("../lib/fn.js"),
Repl = require("../lib/repl.js"),
serialport = require("serialport"),
Pins = require("../lib/board.pins.js"),
Options = require("../lib/board.options.js"),
// temporal = require("temporal"),
board,
boards,
rport,
Serial;
boards = [];
rport = /usb|acm|^com/i;
/**
* Process Codes
* SIGHUP 1 Term Hangup detected on controlling terminal
or death of controlling process
* SIGINT 2 Term Interrupt from keyboard
* SIGQUIT 3 Core Quit from keyboard
* SIGILL 4 Core Illegal Instruction
* SIGABRT 6 Core Abort signal from abort(3)
* SIGFPE 8 Core Floating point exception
* SIGKILL 9 Term Kill signal
* SIGSEGV 11 Core Invalid memory reference
* SIGPIPE 13 Term Broken pipe: write to pipe with no readers
* SIGALRM 14 Term Timer signal from alarm(2)
* SIGTERM 15 Term Termination signal
*
*
*
* http://www.slac.stanford.edu/BFROOT/www/Computing/Environment/Tools/Batch/exitcode.html
*
*/
Serial = {
used: [],
detect: function( callback ) {
this.info( "Board", "Connecting..." );
// If a |port| was explicitly provided to the Board constructor,
// invoke the detection callback and return immediately
if ( this.port ) {
callback.call( this, this.port );
return;
}
serialport.list(function(err, result) {
var ports,
length;
ports = result.filter(function(val) {
var available = true;
// Match only ports that Arduino cares about
// ttyUSB#, cu.usbmodem#, COM#
if ( !rport.test(val.comName) ) {
available = false;
}
// Don't allow already used/encountered usb device paths
if ( Serial.used.indexOf(val.comName) > -1 ) {
available = false;
}
return available;
}).map(function(val) {
return val.comName;
});
length = ports.length;
// If no ports are detected when scanning /dev/, then there is
// nothing left to do and we can safely exit the program
if ( !length ) {
// Alert user that no devices were detected
this.error( "Board", "No USB devices detected" );
// Exit the program by sending SIGABRT
process.exit(3);
// Return (not that it matters, but this is a good way
// to indicate to readers of the code that nothing else
// will happen in this function)
return;
}
// Continue with connection routine attempts
this.info(
"Serial",
"Found possible serial port" + ( length > 1 ? "s" : "" ),
ports.toString().grey
);
// Get the first available device path from the list of
// detected ports
callback.call( this, ports[0] );
}.bind(this));
},
connect: function( usb, callback ) {
var err, found, connected, eventType;
// Add the usb device path to the list of device paths that
// are currently in use - this is used by the filter function
// above to remove any device paths that we've already encountered
// or used to avoid blindly attempting to reconnect on them.
Serial.used.push( usb );
try {
found = new Firmata( usb, function( error ) {
if ( error !== undefined ) {
err = error;
}
// Execute "ready" callback
callback.call( this, err, "ready", found );
}.bind(this));
// Made this far, safely connected
connected = true;
} catch ( error ) {
err = error;
}
if ( err ) {
err = err.message || err;
}
// Determine the type of event that will be passed on to
// the board emitter in the callback passed to Serial.detect(...)
eventType = connected ? "connected" : "error";
// Execute "connected" callback
callback.call( this, err, eventType, found );
}
};
/**
* Board
* @constructor
*
* @param {Object} opts
*/
function Board( opts ) {
if ( !(this instanceof Board) ) {
return new Board( opts );
}
// Ensure opts is an object
opts = opts || {};
var inject, timer;
inject = {};
// Initialize this Board instance with
// param specified properties.
_.assign( this, opts );
// Easily track state of hardware
this.ready = false;
// Initialize instance property to reference firmata board
this.firmata = null;
// Registry of devices by pin address
this.register = [];
// Identify for connected hardware cache
if ( !this.id ) {
this.id = __.uid();
}
// If no debug flag, default to false
// TODO: Remove override
this.debug = true;
if ( !("debug" in this) ) {
this.debug = false;
}
if ( !("repl" in this) ) {
this.repl = true;
}
// Specially processed pin capabilities object
// assigned when board is initialized and ready
this.pins = null;
// Human readable name (if one can be detected)
this.type = '';
// Create a Repl instance and store as
// instance property of this firmata/board.
// This will reduce the amount of boilerplate
// code required to _always_ have a Repl
// session available.
//
// If a sesssion exists, use it
// (instead of creating a new session)
//
if ( this.repl ) {
if ( Repl.ref ) {
inject[ this.id ] = this;
Repl.ref.on( "ready", function() {
Repl.ref.inject( inject );
});
this.repl = Repl.ref;
} else {
inject[ this.id ] = inject.board = this;
this.repl = new Repl( inject );
}
}
// Used for testing only
if ( this.mock ) {
this.ready = true;
this.firmata = new Firmata( this.mock, function() {} );
// NEED A DUMMY OF THE PINS OBJECT
//
//
this.pins = Board.Pins( this );
// Execute "connected" and "ready" callbacks
this.emit( "connected", null );
this.emit( "ready", null );
} else if ( opts.firmata ) {
// If you already have a connected firmata instance
this.firmata = opts.firmata;
this.ready = true;
this.pins = Board.Pins( this );
this.emit( "connected", null );
this.emit( "ready", null );
} else {
Serial.detect.call( this, function( port ) {
Serial.connect.call( this, port, function( err, type, firmata ) {
if ( err ) {
this.error( "Board", err );
} else {
// Assign found firmata to instance
this.firmata = firmata;
this.info(
"Board " + ( type === "connected" ? "->" : "<-" ) + " Serialport",
type,
port.grey
);
}
if ( type === "connected" ) {
// 10 Second timeout...
//
// If "ready" hasn't fired and cleared the timer within
// 10 seconds of the connected event, then it's likely
// that Firmata simply isn't loaded onto the board.
timer = setTimeout(function() {
this.error(
"StandardFirmata",
"A timeout occurred while connecting to the Board. \n" +
"Please check that you've properly loaded StandardFirmata onto the Arduino"
);
process.emit("SIGINT");
}.bind(this), 1e5);
process.on( "SIGINT", function() {
this.warn( "Board", "Closing: firmata, serialport" );
// On ^c, make sure we close the process after the
// firmata and serialport are closed. Approx 100ms
// TODO: this sucks, need better solution
setTimeout(function() {
process.exit();
}, 100);
}.bind(this));
}
if ( type === "ready" ) {
clearTimeout( timer );
// Update instance `ready` flag
this.ready = true;
this.port = port;
this.pins = Board.Pins( this );
// In multi-board mode, block the REPL from
// activation. This will be started directly
// by the Board.Array constructor.
if ( !Repl.isBlocked ) {
process.stdin.emit( "data", 1 );
}
}
// emit connect|ready event
this.emit( type, err );
});
});
}
// Cache instance to allow access from module constructors
boards.push( this );
}
// Inherit event api
util.inherits( Board, events.EventEmitter );
/**
* pinMode, analogWrite, analogRead, digitalWrite, digitalRead
*
* Pass through methods
*/
[
"pinMode",
"analogWrite", "analogRead",
"digitalWrite", "digitalRead"
].forEach(function( method ) {
Board.prototype[ method ] = function( pin, arg ) {
this.firmata[ method ]( pin, arg );
return this;
};
});
Board.prototype.serialize = function( filter ) {
var blacklist, special;
blacklist = this.serialize.blacklist;
special = this.serialize.special;
return JSON.stringify(
this.register.map(function( device ) {
return Object.getOwnPropertyNames( device ).reduce(function( data, prop ) {
var value = device[ prop ];
if ( blacklist.indexOf(prop) === -1 &&
typeof value !== "function" ) {
data[ prop ] = special[ prop ] ?
special[ prop ]( value ) : value;
if ( filter ) {
data[ prop ] = filter( prop, data[ prop ], device );
}
}
return data;
}, {});
}, this)
);
};
Board.prototype.serialize.blacklist = [
"board", "firmata", "_events"
];
Board.prototype.serialize.special = {
mode: function(value) {
return [ "INPUT", "OUTPUT", "ANALOG", "PWM", "SERVO" ][ value ] || "unknown";
}
};
/**
* shiftOut
*
*/
Board.prototype.shiftOut = function( dataPin, clockPin, isBigEndian, value ) {
var mask, write;
write = function( value, mask ) {
this.digitalWrite( clockPin, this.firmata.LOW );
this.digitalWrite(
dataPin, this.firmata[ value & mask ? "HIGH" : "LOW" ]
);
this.digitalWrite( clockPin, this.firmata.HIGH );
}.bind(this);
if ( arguments.length === 3 ) {
value = arguments[2];
isBigEndian = true;
}
if ( isBigEndian ) {
for ( mask = 128; mask > 0; mask = mask >> 1 ) {
write( value, mask );
}
} else {
for ( mask = 0; mask < 128; mask = mask << 1 ) {
write( value, mask );
}
}
};
Board.prototype.log = function( /* type, module, message [, long description] */ ) {
var args = [].slice.call( arguments ),
type = args.shift(),
module = args.shift(),
message = args.shift(),
color = Board.prototype.log.types[ type ];
if ( this.debug ) {
console.log([
// Timestamp
String(+new Date()).grey,
// Module, color matches type of log
module.magenta,
// Message
message[ color ],
// Miscellaneous args
args.join(", ")
].join(" "));
}
};
Board.prototype.log.types = {
error: "red",
fail: "orange",
warn: "yellow",
info: "cyan"
};
// Make shortcuts to all logging methods
Object.keys( Board.prototype.log.types ).forEach(function( type ) {
Board.prototype[ type ] = function() {
var args = [].slice.call( arguments );
args.unshift( type );
this.log.apply( this, args );
};
});
/**
* delay, loop, queue
*
* Pass through methods to temporal
*/
/*
[
"delay", "loop", "queue"
].forEach(function( method ) {
Board.prototype[ method ] = function( time, callback ) {
temporal[ method ]( time, callback );
return this;
};
});
// Alias wait to delay to match existing Johnny-five API
Board.prototype.wait = Board.prototype.delay;
*/
// -----THIS IS A TEMPORARY FIX UNTIL THE ISSUES WITH TEMPORAL ARE RESOLVED-----
// Aliasing.
// (temporary, while ironing out API details)
// The idea is to match existing hardware programming apis
// or simply find the words that are most intuitive.
// Eventually, there should be a queuing process
// for all new callbacks added
//
// TODO: Repalce with temporal or compulsive API
Board.prototype.wait = function( time, callback ) {
setTimeout( callback.bind(this), time );
return this;
};
Board.prototype.loop = function( time, callback ) {
setInterval( callback.bind(this), time );
return this;
};
// ----------
// Static API
// ----------
// Board.map( val, fromLow, fromHigh, toLow, toHigh )
//
// Re-maps a number from one range to another.
// Based on arduino map()
Board.map = __.map;
// Board.constrain( val, lower, upper )
//
// Constrains a number to be within a range.
// Based on arduino constrain()
Board.constrain = __.constrain;
// Board.range( upper )
// Board.range( lower, upper )
// Board.range( lower, upper, tick )
//
// Returns a new array range
//
Board.range = __.range;
// Board.range.prefixed( prefix, upper )
// Board.range.prefixed( prefix, lower, upper )
// Board.range.prefixed( prefix, lower, upper, tick )
//
// Returns a new array range, each value prefixed
//
Board.range.prefixed = __.range.prefixed;
// Board.uid()
//
// Returns a reasonably unique id string
//
Board.uid = __.uid;
// Board.mount()
// Board.mount( index )
// Board.mount( object )
//
// Return hardware instance, based on type of param:
// @param {arg}
// object, user specified
// number/index, specified in cache
// none, defaults to first in cache
//
// Notes:
// Used to reduce the amount of boilerplate
// code required in any given module or program, by
// giving the developer the option of omitting an
// explicit Board reference in a module
// constructor's options
Board.mount = function( arg ) {
var index = typeof arg === "number" && arg,
hardware;
// board was explicitly provided
if ( arg && arg.board ) {
return arg.board;
}
// index specified, attempt to return
// hardware instance. Return null if not
// found or not available
if ( index ) {
hardware = boards[ index ];
return hardware && hardware || null;
}
// If no arg specified and hardware instances
// exist in the cache
if ( boards.length ) {
return boards[ 0 ];
}
// No mountable hardware
return null;
};
/**
* Board.Device
*
* Initialize a new device instance
*
* Board.Device is a |this| senstive constructor,
* and must be called as:
*
* Board.Device.call( this, opts );
*
*
*
* TODO: Migrate all constructors to use this
* to avoid boilerplate
*/
Board.Device = function( opts ) {
// Board specific properties
this.board = Board.mount( opts );
this.firmata = this.board.firmata;
// Device/Module instance properties
this.id = opts.id || null;
// Pin or Pins address(es)
opts = Board.Pins.normalize( opts, this.board );
if ( typeof opts.pins !== "undefined" ) {
this.pins = opts.pins || [];
}
if ( typeof opts.pin !== "undefined" ) {
this.pin = opts.pin || 0;
}
this.board.register.push( this );
};
/**
* Pin Capability Signature Mapping
*/
Board.Pins = Pins;
Board.Options = Options;
// Define a user-safe, unwritable hardware cache access
Object.defineProperty( Board, "cache", {
get: function() {
return boards;
}
});
/**
* Board event constructor.
* opts:
* type - event type. eg: "read", "change", "up" etc.
* target - the instance for which the event fired.
* 0..* other properties
*/
Board.Event = function( opts ) {
if ( !(this instanceof Board.Event) ) {
return new Board.Event( opts );
}
opts = opts || {};
// default event is read
this.type = opts.type || "read";
// actual target instance
this.target = opts.target || null;
// Initialize this Board instance with
// param specified properties.
_.assign( this, opts );
};
/**
* Boards or Board.Array; Used when the program must connect to
* more then one board.
*
* @memberof Board
*
* @param {Array} ports List of port objects { id: ..., port: ... }
* List of id strings (initialized in order)
*
* @return {Boards} board object references
*/
Board.Array = function( ports ) {
if ( !(this instanceof Board.Array) ) {
return new Board.Array( ports );
}
if ( !Array.isArray(ports) ) {
throw new Error("Expected ports to be an array");
}
Array.call( this, ports.length );
var initialized, count;
initialized = {};
count = ports.length;
// Block initialization of the program's
// REPL until all boards are ready.
Repl.isBlocked = true;
ports.forEach(function( port, k ) {
var opts;
if ( typeof port === "string" ) {
opts = {
id: port
};
} else {
opts = port;
}
this[ k ] = initialized[ opts.id ] = new Board( opts );
this[ k ].on("ready", function() {
this[ k ].info( "Board ID: ", opts.id.green );
this.length++;
if ( !--count ) {
Repl.isBlocked = false;
process.stdin.emit( "data", 1 );
this.emit( "ready", initialized );
}
}.bind(this));
}, this);
};
util.inherits( Board.Array, events.EventEmitter );
Board.Array.prototype.each = Array.prototype.forEach;
module.exports = Board;
// References:
// http://arduino.cc/en/Main/arduinoBoardUno
| pmark/Proboscis | node_modules/johnny-five/lib/board.js | JavaScript | gpl-2.0 | 17,276 |
/* thePlatform Video Manager Wordpress Plugin
Copyright (C) 2013-2014 thePlatform for Media Inc.
This program 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.
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 General Public License for more details.
You should have received a copy of the GNU 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.
Changes
========================================
qaz2wsx3@uw.edu: changed the icon on the post editor's toolbar
*/
tinymce.PluginManager.add( 'theplatform', function( editor, url ) {
// Add a button that opens a window
editor.addButton( 'theplatform', {
tooltip: 'Embed MPX Media',
image: url.substring( 0, url.lastIndexOf( '/js' ) ) + '/images/MediaAMP_button_icon.png',
onclick: function() {
// Open window
var iframeUrl = ajaxurl + "?action=theplatform_media&embed=true&_wpnonce=" + editor.settings.theplatform_media_nonce;
tinyMCE.activeEditor = editor;
if ( window.innerHeight < 1200 )
height = window.innerHeight - 50;
else
height = 1024;
if ( tinyMCE.majorVersion > 3 ) {
editor.windowManager.open( {
width: 1220,
height: height,
url: iframeUrl
} );
}
else {
if ( jQuery( "#tp-embed-dialog" ).length == 0 ) {
jQuery( 'body' ).append( '<div id="tp-embed-dialog"></div>' );
}
jQuery( "#tp-embed-dialog" ).html( '<iframe src="' + iframeUrl + '" height="100%" width="100%">' ).dialog( { dialogClass: "wp-dialog", modal: true, resizable: true, minWidth: 1024, width: 1220, height: height } ).css( "overflow-y", "hidden" );
}
}
} );
} );
tinymce.init( {
plugins: 'theplatform'
} ); | uw-it-aca/MediaAMP-video-manager | js/theplatform.tinymce.plugin.js | JavaScript | gpl-2.0 | 2,087 |
import F2 from '@antv/f2';
fetch('https://gw.alipayobjects.com/os/antfincdn/N81gEpw2Ef/income.json')
.then(res => res.json())
.then(data => {
const chart = new F2.Chart({
id: 'container',
pixelRatio: window.devicePixelRatio
});
chart.source(data, {
time: {
type: 'timeCat',
range: [ 0, 1 ],
tickCount: 3
}
});
chart.axis('time', {
label: function label(text, index, total) {
const textCfg = {};
if (index === 0) {
textCfg.textAlign = 'left';
} else if (index === total - 1) {
textCfg.textAlign = 'right';
}
return textCfg;
}
});
chart.guide().point({
position: [ '2014-01-03', 6.763 ]
});
chart.guide().text({
position: [ '2014-01-03', 6.763 ],
content: '受稳健货币政策影响,协定存款利\n率居高不下,收益率达6.763%',
style: {
textAlign: 'left',
lineHeight: 16,
fontSize: 10
},
offsetX: 10
});
chart.guide().point({
position: [ '2013-05-31', 2.093 ]
});
chart.guide().text({
position: [ '2013-05-31', 2.093 ],
content: '余额宝刚成立时,并未达到\n目标资产配置,故收益率较低',
style: {
textAlign: 'left',
lineHeight: 16,
fontSize: 10
},
offsetX: 10,
offsetY: -10
});
chart.guide().point({
position: [ '2016-09-04', 2.321 ]
});
chart.guide().text({
position: [ '2016-09-04', 2.321 ],
content: '受积极货币政策的影响,收益率降\n到历史最低2.321%',
style: {
textBaseline: 'bottom',
lineHeight: 16,
fontSize: 10
},
offsetY: -20
});
chart.line().position('time*rate');
chart.render();
});
| antvis/g2-mobile | examples/component/guide/demo/point.js | JavaScript | gpl-2.0 | 1,844 |
/**
A data model representing a list of Invites
@class InviteList
@extends Discourse.Model
@namespace Discourse
@module Discourse
**/
Discourse.InviteList = Discourse.Model.extend({
empty: (function() {
return this.blank('pending') && this.blank('redeemed');
}).property('pending.@each', 'redeemed.@each')
});
Discourse.InviteList.reopenClass({
findInvitedBy: function(user) {
var promise;
promise = new RSVP.Promise();
$.ajax({
url: "/users/" + (user.get('username_lower')) + "/invited.json",
success: function(result) {
var invitedList;
invitedList = result.invited_list;
if (invitedList.pending) {
invitedList.pending = invitedList.pending.map(function(i) {
return Discourse.Invite.create(i);
});
}
if (invitedList.redeemed) {
invitedList.redeemed = invitedList.redeemed.map(function(i) {
return Discourse.Invite.create(i);
});
}
invitedList.user = user;
return promise.resolve(Discourse.InviteList.create(invitedList));
}
});
return promise;
}
});
| SuperSonicDesignINC/FXDD | app/assets/javascripts/discourse/models/invite_list.js | JavaScript | gpl-2.0 | 1,146 |
(function( window, undefined ) {
kendo.cultures["ur-PK"] = {
name: "ur-PK",
numberFormat: {
pattern: ["-n"],
decimals: 2,
",": ",",
".": ".",
groupSize: [3],
percent: {
pattern: ["-n %","n %"],
decimals: 2,
",": ",",
".": ".",
groupSize: [3],
symbol: "%"
},
currency: {
pattern: ["$n-","$n"],
decimals: 2,
",": ",",
".": ".",
groupSize: [3],
symbol: "Rs"
}
},
calendars: {
standard: {
days: {
names: ["اتوار","پير","منگل","بدھ","جمعرات","جمعه","هفته"],
namesAbbr: ["اتوار","پير","منگل","بدھ","جمعرات","جمعه","هفته"],
namesShort: ["ا","پ","م","ب","ج","ج","ه"]
},
months: {
names: ["جنوری","فروری","مارچ","اپریل","مئی","جون","جولائی","اگست","ستمبر","اکتوبر","نومبر","دسمبر"],
namesAbbr: ["جنوری","فروری","مارچ","اپریل","مئی","جون","جولائی","اگست","ستمبر","اکتوبر","نومبر","دسمبر"]
},
AM: ["AM","am","AM"],
PM: ["PM","pm","PM"],
patterns: {
d: "dd/MM/yyyy",
D: "dd MMMM, yyyy",
F: "dd MMMM, yyyy h:mm:ss tt",
g: "dd/MM/yyyy h:mm tt",
G: "dd/MM/yyyy h:mm:ss tt",
m: "dd MMMM",
M: "dd MMMM",
s: "yyyy'-'MM'-'dd'T'HH':'mm':'ss",
t: "h:mm tt",
T: "h:mm:ss tt",
u: "yyyy'-'MM'-'dd HH':'mm':'ss'Z'",
y: "MMMM, yyyy",
Y: "MMMM, yyyy"
},
"/": "/",
":": ":",
firstDay: 1
}
}
}
})(this);
| cuongnd/test_pro | media/kendo-ui-core-master/src/cultures/kendo.culture.ur-PK.js | JavaScript | gpl-2.0 | 2,263 |
/**
* @license BitSet.js v4.0.1 14/08/2015
* http://www.xarg.org/2014/03/javascript-bit-array/
*
* Copyright (c) 2016, Robert Eisele (robert@xarg.org)
* Dual licensed under the MIT or GPL Version 2 licenses.
**/
(function(root) {
'use strict';
/**
* The number of bits of a word
* @const
* @type number
*/
var WORD_LENGTH = 32;
/**
* The log base 2 of WORD_LENGTH
* @const
* @type number
*/
var WORD_LOG = 5;
/**
* Calculates the number of set bits
*
* @param {number} v
* @returns {number}
*/
function popCount(v) {
// Warren, H. (2009). Hacker`s Delight. New York, NY: Addison-Wesley
v -= ((v >>> 1) & 0x55555555);
v = (v & 0x33333333) + ((v >>> 2) & 0x33333333);
return (((v + (v >>> 4) & 0xF0F0F0F) * 0x1010101) >>> 24);
}
/**
* Divide a number in base two by B
*
* @param {Array} arr
* @param {number} B
* @returns {number}
*/
function divide(arr, B) {
var r = 0;
var d;
var i = 0;
for (; i < arr.length; i++) {
r *= 2;
d = (arr[i] + r) / B | 0;
r = (arr[i] + r) % B;
arr[i] = d;
}
return r;
}
/**
* Parses the parameters and set variable P
*
* @param {Object} P
* @param {string|BitSet|Array|Uint8Array|number=} val
*/
function parse(P, val) {
if (val == null) {
P['data'] = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
P['_'] = 0;
return;
}
if (val instanceof BitSet) {
P['data'] = val['data'];
P['_'] = val['_'];
return;
}
switch (typeof val) {
case 'number':
P['data'] = [val | 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
P['_'] = 0;
break;
case 'string':
var base = 2;
var len = WORD_LENGTH;
if (val.indexOf('0b') === 0) {
val = val.substr(2);
} else if (val.indexOf('0x') === 0) {
val = val.substr(2);
base = 16;
len = 8;
}
P['data'] = [];
P['_'] = 0;
var a = val.length - len;
var b = val.length;
do {
var num = parseInt(val.slice(a > 0 ? a : 0, b), base);
if (isNaN(num)) {
throw SyntaxError('Invalid param');
}
P['data'].push(num | 0);
if (a <= 0)
break;
a -= len;
b -= len;
} while (1);
break;
default:
P['data'] = [0];
var data = P['data'];
if (val instanceof Array) {
for (var i = val.length - 1; i >= 0; i--) {
var ndx = val[i];
if (ndx === Infinity) {
P['_'] = -1;
} else {
scale(P, ndx);
data[ndx >>> WORD_LOG] |= 1 << ndx;
}
}
break;
}
if (Uint8Array && val instanceof Uint8Array) {
var bits = 8;
scale(P, val.length * bits);
for (var i = 0; i < val.length; i++) {
var n = val[i];
for (var j = 0; j < bits; j++) {
var k = i * bits + j;
data[k >>> WORD_LOG] |= (n >> j & 1) << k;
}
}
break;
}
throw SyntaxError('Invalid param');
}
}
/**
* Module entry point
*
* @constructor
* @param {string|BitSet|number=} param
* @returns {BitSet}
*/
function BitSet(param) {
if (!(this instanceof BitSet)) {
return new BitSet(param);
}
parse(this, param);
this['data'] = this['data'].slice();
}
function scale(dst, ndx) {
var l = ndx >>> WORD_LOG;
var d = dst['data'];
var v = dst['_'];
for (var i = d.length; l >= i; l--) {
d[l] = v;
}
}
var P = {
'data': [],
'_': 0
};
BitSet.prototype = {
'data': [],
'_': 0,
/**
* Set a single bit flag
*
* Ex:
* bs1 = new BitSet(10);
*
* bs1.set(3, 1);
*
* @param {number} ndx The index of the bit to be set
* @param {number=} value Optional value that should be set on the index (0 or 1)
* @returns {BitSet} this
*/
'set': function(ndx, value) {
ndx |= 0;
scale(this, ndx);
if (value === undefined || value) {
this['data'][ndx >>> WORD_LOG] |= (1 << ndx);
} else {
this['data'][ndx >>> WORD_LOG] &= ~(1 << ndx);
}
return this;
},
/**
* Get a single bit flag of a certain bit position
*
* Ex:
* bs1 = new BitSet();
* var isValid = bs1.get(12);
*
* @param {number} ndx the index to be fetched
* @returns {number|null} The binary flag
*/
'get': function(ndx) {
ndx |= 0;
var d = this['data'];
var n = ndx >>> WORD_LOG;
if (n > d.length) {
return this['_'] & 1;
}
return (d[n] >>> ndx) & 1;
},
/**
* Creates the bitwise AND of two sets. The result is stored in-place.
*
* Ex:
* bs1 = new BitSet(10);
* bs2 = new BitSet(10);
*
* bs1.and(bs2);
*
* @param {BitSet} value A bitset object
* @returns {BitSet} this
*/
'and': function(value) {// intersection
parse(P, value);
var t = this['data'];
var p = P['data'];
var p_ = P['_'];
var pl = p.length - 1;
var tl = t.length - 1;
if (p_ == 0) {
// clear any bits set:
for (var i = tl; i > pl; i--) {
t[i] = 0;
}
}
for (; i >= 0; i--) {
t[i] &= p[i];
}
this['_'] &= P['_'];
return this;
},
/**
* Creates the bitwise OR of two sets. The result is stored in-place.
*
* Ex:
* bs1 = new BitSet(10);
* bs2 = new BitSet(10);
*
* bs1.or(bs2);
*
* @param {BitSet} val A bitset object
* @returns {BitSet} this
*/
'or': function(val) { // union
parse(P, val);
var t = this['data'];
var p = P['data'];
var pl = p.length - 1;
var tl = t.length - 1;
var minLength = Math.min(tl, pl);
// Append backwards, extend array only once
for (var i = pl; i > minLength; i--) {
t[i] = p[i];
}
for (; i >= 0; i--) {
t[i] |= p[i];
}
this['_'] |= P['_'];
return this;
},
/**
* Creates the bitwise NOT of a set. The result is stored in-place.
*
* Ex:
* bs1 = new BitSet(10);
*
* bs1.not();
*
* @returns {BitSet} this
*/
'not': function() { // invert()
var d = this['data'];
for (var i = 0; i < d.length; i++) {
d[i] = ~d[i];
}
this['_'] = ~this['_'];
return this;
},
/**
* Creates the bitwise XOR of two sets. The result is stored in-place.
*
* Ex:
* bs1 = new BitSet(10);
* bs2 = new BitSet(10);
*
* bs1.xor(bs2);
*
* @param {BitSet} val A bitset object
* @returns {BitSet} this
*/
'xor': function(val) { // symmetric difference
parse(P, val);
var t = this['data'];
var p = P['data'];
var t_ = this['_'];
var p_ = P['_'];
var i = 0;
var tl = t.length - 1;
var pl = p.length - 1;
// Cut if tl > pl
for (i = tl; i > pl; i--) {
t[i] ^= p_;
}
// Cut if pl > tl
for (i = pl; i > tl; i--) {
t[i] = t_ ^ p[i];
}
// XOR the rest
for (; i >= 0; i--) {
t[i] ^= p[i];
}
// XOR infinity
this['_'] ^= p_;
return this;
},
/**
* Flip/Invert a range of bits by setting
*
* Ex:
* bs1 = new BitSet();
* bs1.flip(); // Flip entire set
* bs1.flip(5); // Flip single bit
* bs1.flip(3,10); // Flip a bit range
*
* @param {number=} from The start index of the range to be flipped
* @param {number=} to The end index of the range to be flipped
* @returns {BitSet} this
*/
'flip': function(from, to) {
if (from === undefined) {
return this['not']();
} else if (to === undefined) {
from |= 0;
scale(this, from);
this['data'][from >>> WORD_LOG] ^= (1 << from);
} else if (from <= to && 0 <= from) {
scale(this, to);
for (var i = from; i <= to; i++) {
this['data'][i >>> WORD_LOG] ^= (1 << i);
}
}
return this;
},
/**
* Creates the bitwise AND NOT (not confuse with NAND!) of two sets. The result is stored in-place.
*
* Ex:
* bs1 = new BitSet(10);
* bs2 = new BitSet(10);
*
* bs1.notAnd(bs2);
*
* @param {BitSet} val A bitset object
* @returns {BitSet} this
*/
'andNot': function(val) { // difference
parse(P, val);
var t = this['data'];
var p = P['data'];
var t_ = this['_'];
var p_ = P['_'];
var l = Math.min(t.length, p.length);
for (var k = 0; k < l; k++) {
t[k] &= ~p[k];
}
this['_'] &= ~p_;
return this;
},
/**
* Clear a range of bits by setting it to 0
*
* Ex:
* bs1 = new BitSet();
* bs1.clear(); // Clear entire set
* bs1.clear(5); // Clear single bit
* bs1.clar(3,10); // Clear a bit range
*
* @param {number=} from The start index of the range to be cleared
* @param {number=} to The end index of the range to be cleared
* @returns {BitSet} this
*/
'clear': function(from, to) {
var data = this['data'];
if (from === undefined) {
for (var i = data.length - 1; i >= 0; i--) {
data[i] = 0;
}
this['_'] = 0;
} else if (to === undefined) {
from |= 0;
scale(this, from);
data[from >>> WORD_LOG] &= ~(1 << from);
} else if (from <= to) {
scale(this, to);
for (var i = from; i <= to; i++) {
data[i >>> WORD_LOG] &= ~(1 << i);
}
}
return this;
},
/**
* Gets an entire range as a new bitset object
*
* Ex:
* bs1 = new BitSet();
* bs1.slice(4, 8);
*
* @param {number=} from The start index of the range to be get
* @param {number=} to The end index of the range to be get
* @returns {BitSet|Object} A new smaller bitset object, containing the extracted range
*/
'slice': function(from, to) {
if (from === undefined) {
return this['clone']();
} else if (to === undefined) {
to = this['data'].length * WORD_LENGTH;
var im = Object.create(BitSet.prototype);
im['_'] = this['_'];
im['data'] = [0];
for (var i = from; i <= to; i++) {
im['set'](i - from, this['get'](i));
}
return im;
} else if (from <= to && 0 <= from) {
var im = Object.create(BitSet.prototype);
im['data'] = [0];
for (var i = from; i <= to; i++) {
im['set'](i - from, this['get'](i));
}
return im;
}
return null;
},
/**
* Set a range of bits
*
* Ex:
* bs1 = new BitSet();
*
* bs1.setRange(10, 15, 1);
*
* @param {number} from The start index of the range to be set
* @param {number} to The end index of the range to be set
* @param {number} value Optional value that should be set on the index (0 or 1)
* @returns {BitSet} this
*/
'setRange': function(from, to, value) {
for (var i = from; i <= to; i++) {
this['set'](i, value);
}
return this;
},
/**
* Clones the actual object
*
* Ex:
* bs1 = new BitSet(10);
* bs2 = bs1.clone();
*
* @returns {BitSet|Object} A new BitSet object, containing a copy of the actual object
*/
'clone': function() {
var im = Object.create(BitSet.prototype);
im['data'] = this['data'].slice();
im['_'] = this['_'];
return im;
},
/**
* Gets a list of set bits
*
* @returns {Array|number}
*/
'toArray': Math['clz32'] ?
function() {
var ret = [];
var data = this['data'];
for (var i = data.length - 1; i >= 0; i--) {
var num = data[i];
while (num !== 0) {
var t = 31 - Math['clz32'](num);
num ^= 1 << t;
ret.unshift((i * WORD_LENGTH) + t);
}
}
if (this['_'] !== 0)
ret.push(Infinity);
return ret;
} :
function() {
var ret = [];
var data = this['data'];
for (var i = 0; i < data.length; i++) {
var num = data[i];
while (num !== 0) {
var t = num & -num;
num ^= t;
ret.push((i * WORD_LENGTH) + popCount(t - 1));
}
}
if (this['_'] !== 0)
ret.push(Infinity);
return ret;
},
/**
* Overrides the toString method to get a binary representation of the BitSet
*
* @param {number=} base
* @returns string A binary string
*/
'toString': function(base) {
var data = this['data'];
if (!base)
base = 2;
// If base is power of two
if ((base & (base - 1)) === 0 && base < 36) {
var ret = '';
var len = 2 + Math.log(4294967295/*Math.pow(2, WORD_LENGTH)-1*/) / Math.log(base) | 0;
for (var i = data.length - 1; i >= 0; i--) {
var cur = data[i];
// Make the number unsigned
if (cur < 0)
cur += 4294967296 /*Math.pow(2, WORD_LENGTH)*/;
var tmp = cur.toString(base);
if (ret !== '') {
// Fill small positive numbers with leading zeros. The +1 for array creation is added outside already
ret += new Array(len - tmp.length).join('0');
}
ret += tmp;
}
if (this['_'] === 0) {
ret = ret.replace(/^0+/, '');
if (ret === '')
ret = '0';
return ret;
} else {
// Pad the string with ones
ret = '1111' + ret;
return ret.replace(/^1+/, '...1111');
}
} else {
if ((2 > base || base > 36))
throw 'Invalid base';
var ret = [];
var arr = [];
// Copy every single bit to a new array
for (var i = data.length; i--; ) {
for (var j = WORD_LENGTH; j--; ) {
arr.push(data[i] >>> j & 1);
}
}
do {
ret.unshift(divide(arr, base).toString(base));
} while (!arr.every(function(x) {
return x === 0;
}));
return ret.join('');
}
},
/**
* Check if the BitSet is empty, means all bits are unset
*
* Ex:
* bs1 = new BitSet(10);
*
* bs1.isEmpty() ? 'yes' : 'no'
*
* @returns {boolean} Whether the bitset is empty
*/
'isEmpty': function() {
if (this['_'] !== 0)
return false;
var d = this['data'];
for (var i = d.length - 1; i >= 0; i--) {
if (d[i] !== 0)
return false;
}
return true;
},
/**
* Calculates the number of bits set
*
* Ex:
* bs1 = new BitSet(10);
*
* var num = bs1.cardinality();
*
* @returns {number} The number of bits set
*/
'cardinality': function() {
if (this['_'] !== 0) {
return Infinity;
}
var s = 0;
var d = this['data'];
for (var i = 0; i < d.length; i++) {
var n = d[i];
if (n !== 0)
s += popCount(n);
}
return s;
},
/**
* Calculates the Most Significant Bit / log base two
*
* Ex:
* bs1 = new BitSet(10);
*
* var logbase2 = bs1.msb();
*
* var truncatedTwo = Math.pow(2, logbase2); // May overflow!
*
* @returns {number} The index of the highest bit set
*/
'msb': Math['clz32'] ?
function() {
if (this['_'] !== 0) {
return Infinity;
}
var data = this['data'];
for (var i = data.length; i-- > 0; ) {
var c = Math['clz32'](data[i]);
if (c !== WORD_LENGTH) {
return (i * WORD_LENGTH) + WORD_LENGTH - 1 - c;
}
}
return Infinity;
} :
function() {
if (this['_'] !== 0) {
return Infinity;
}
var data = this['data'];
for (var i = data.length; i-- > 0; ) {
var v = data[i];
var c = 0;
if (v) {
for (; (v >>>= 1) > 0; c++) {
}
return (i * WORD_LENGTH) + c;
}
}
return Infinity;
},
/**
* Calculates the number of trailing zeros
*
* Ex:
* bs1 = new BitSet(10);
*
* var ntz = bs1.ntz();
*
* @returns {number} The index of the lowest bit set
*/
'ntz': function() {
var data = this['data'];
for (var j = 0; j < data.length; j++) {
var v = data[j];
if (v !== 0) {
v = (v ^ (v - 1)) >>> 1; // Set v's trailing 0s to 1s and zero rest
return (j * WORD_LENGTH) + popCount(v);
}
}
return Infinity;
},
/**
* Calculates the Least Significant Bit
*
* Ex:
* bs1 = new BitSet(10);
*
* var lsb = bs1.lsb();
*
* @returns {number} The index of the lowest bit set
*/
'lsb': function() {
var data = this['data'];
for (var i = 0; i < data.length; i++) {
var v = data[i];
var c = 0;
if (v) {
var bit = (v & -v);
for (; (bit >>>= 1); c++) {
}
return WORD_LENGTH * i + c;
}
}
return this['_'] & 1;
},
/**
* Compares two BitSet objects
*
* Ex:
* bs1 = new BitSet(10);
* bs2 = new BitSet(10);
*
* bs1.equals(bs2) ? 'yes' : 'no'
*
* @param {BitSet} val A bitset object
* @returns {boolean} Whether the two BitSets are similar
*/
'equals': function(val) {
parse(P, val);
var t = this['data'];
var p = P['data'];
var t_ = this['_'];
var p_ = P['_'];
var tl = t.length - 1;
var pl = p.length - 1;
if (p_ !== t_) {
return false;
}
var minLength = tl < pl ? tl : pl;
for (var i = 0; i <= minLength; i++) {
if (t[i] !== p[i])
return false;
}
for (i = tl; i > pl; i--) {
if (t[i] !== p_)
return false;
}
for (i = pl; i > tl; i--) {
if (p[i] !== t_)
return false;
}
return true;
}
};
BitSet.fromBinaryString = function(str) {
return new BitSet('0b' + str);
};
BitSet.fromHexString = function(str) {
return new BitSet('0x' + str);
};
if (typeof define === 'function' && define['amd']) {
define([], function() {
return BitSet;
});
} else if (typeof exports === 'object') {
module['exports'] = BitSet;
} else {
root['BitSet'] = BitSet;
}
})(this); | dashuo556/pkbitmap | bitset.js | JavaScript | gpl-2.0 | 19,561 |
angular.module('app.controllers.ForgotPasswordCtrl', ['ngRoute'])
.controller('ForgotPasswordCtrl', ['$scope', '$http', '$modalInstance', 'forgotPasswordService', function($scope, $http, $modalInstance, forgotPasswordService) {
$scope.forgot_data = {
email: ""
};
$scope.ok = function () {
forgotPasswordService.save($scope.forgot_data);
$modalInstance.close($scope.forgot_data.email);
};
$scope.cancel = function () {
$modalInstance.dismiss('cancel');
};
}]);
| DazzleWorks/Premi | public/app/controllers/home/ForgotPasswordCtrl.js | JavaScript | gpl-2.0 | 570 |
import React from 'react'
import { connect } from 'react-redux'
import ItemSelectInput from './ItemSelectInput'
import sectionsActions from '../../../actions/SectionsActions'
class SectionSelectInputComponent extends React.Component {
listSections(query) {
let queryObj = {}
if (query) {
queryObj['q'] = query
}
this.props.listSections(this.props.token, queryObj)
}
render() {
return (
<ItemSelectInput
many={false}
value={this.props.value}
inline={this.props.inline}
showSortableList={this.props.showSortableList}
results={this.props.sections.ids}
entities={this.props.entities.sections}
onChange={(value) => this.props.update(value)}
fetchResults={(query) => this.listSections(query)}
attribute='name'
editMessage={this.props.value ? 'Edit section' : 'Add section'} />
)
}
}
const mapStateToProps = (state) => {
return {
sections: state.app.sections.list,
entities: {
sections: state.app.entities.sections
},
token: state.app.auth.token
}
}
const mapDispatchToProps = (dispatch) => {
return {
listSections: (token, query) => {
dispatch(sectionsActions.list(token, query))
}
}
}
const SectionSelectInput = connect(
mapStateToProps,
mapDispatchToProps
)(SectionSelectInputComponent)
export default SectionSelectInput
| ubyssey/dispatch | dispatch/static/manager/src/js/components/inputs/selects/SectionSelectInput.js | JavaScript | gpl-2.0 | 1,402 |
! function(factory) {
if (typeof require === 'function' && typeof exports === 'object' && typeof module === 'object') {
var target = module['exports'] || exports;
factory(target);
} else if (typeof define === 'function' && define['amd']) {
//define(['exports'],function(exports){
// exports.abc = function(){}
//});
define(['exports'], factory);
} else {
factory(window['NC'] = {});
}
}(function(exports) {
function reMarker(templ, data, type) {
var _type = type || 'JavaScript';
if (arguments.length === 1 ||(!data && type)) {
var _templ = reMarker[_type].parse(templ);
return _templ;
/* return function(data) {
return reMarker[_type].proc(_templ, data);
}*/
}
data = data || {};
return reMarker[_type].proc(reMarker[_type].parse(templ), data);
}
/**
* 工具方法
* @type {Object}
*/
var _utils = {
trim: function(str) {
return str.replace(/(^\s*)|(\s*$)/g, "");
},
lTrim: function(str) {
return str.replace(/(^\s*)/g, "");
},
rTrim: function(str) {
return str.replace(/(\s*$)/g, "");
},
removeEmpty: function(arr) {
var splitStr = _separator(arr);
var REMOVE_REGEX = new RegExp(splitStr + splitStr);
var REMOVE_HEAD_REGEX = new RegExp('^' + splitStr);
return arr.join(splitStr).replace(REMOVE_REGEX, splitStr).replace(REMOVE_HEAD_REGEX, '').split(splitStr);
},
filter: function(str) {
return str.replace('<', '<').replace('>', '>');
}
};
/**
* 设定分隔符
* @param {String} str 字符串源
* @return {String} 分隔符
*/
function _separator(str) {
var separator = '';
do {
separator = String.fromCharCode(Math.random(0, 1) * 100 + 255);
}
while (str.indexOf(separator) >= 0);
return separator;
};
/**
* 移除不安全代码
* @param html
* @returns {*|void}
*/
function removeUnsafe(html) {
var _templ = html.replace(/[\r|\n|\t]/ig, '').replace(/\s{2,}/ig, ' ').replace(/\'/ig, "\\\'");
return _templ;
}
/**
* 找出匹配的键值对
* @param {Array} value 数组
* @returns {Array}
*/
function findPairs(value) {
var cache = [];
if (Object.prototype.toString.call(value) === '[object Array]') {
var KEY_REGEX = /\b(\w+)\s*?=/g;
var commandStr = value.join(' ');
var _sp = _separator(commandStr);
commandStr = commandStr.replace(KEY_REGEX, _sp + "$1" + _sp);
value = _utils.removeEmpty(commandStr.split(_sp));
if (value.length % 2 == 0) {
for (var i = 0; i < value.length; i = i + 2) {
var _pair = [value[i], value[i + 1]];
cache = cache.concat(_pair);
}
}
}
return cache;
}
var VAR_REGEX=/^[a-zA-Z_][a-zA-Z0-9_]*$/im;
function _setVarToken(arr){
return arr.map(function(value){
if(VAR_REGEX.test(value)===true){
value='$'+value;
}
return value;
});
}
reMarker.PHP = (function() {
var Ruler = {
guid: 0
};
/**
* 匹配语法规则处理
* @type {{ruler: Function, rulerAssign: Function, rulerEndSwitch: Function, rulerCase: Function, rulerDefault: Function, rulerSwitch: Function, rulerElseIf: Function, rulerBreak: Function, rulerElse: Function, rulerEndIf: Function, rulerIf: Function, rulerEndList: Function, rulerList: Function}}
*/
Ruler.regRuler = {
ruler: function(str) {
var listArr = Ruler.util.removeEmpty(str.split(' '));
//import,include
var ruler = {
"list": this.rulerList,
"if": this.rulerIf,
"break": this.rulerBreak,
'/#list': this.rulerEndList,
'else': this.rulerElse,
"/#if": this.rulerEndIf,
'elseif': this.rulerElseIf,
'switch': this.rulerSwitch,
'case': this.rulerCase,
'default': this.rulerDefault,
'/#switch': this.rulerEndSwitch,
'assign': this.rulerAssign,
'return': this.rulerReturn
};
return (ruler[listArr[0]]).call(this, listArr);
},
rulerReturn: function() {
return 'return;';
},
/**
* 定义变量
* @param arr
* @returns {string}
*/
rulerAssign: function(arr) {
var result = [],
count;
var rt = findPairs(arr.slice(1));
count = rt.length;
for (j = 0; j < count; j += 2) {
var name = rt[j];
result.push('$' + name + '=' + rt[j + 1] + ';');
}
return result.join('');
},
rulerEndSwitch: function(arr) {
return '}';
},
rulerCase: function(arr) {
return ('case ' + arr[1] + ':');
},
rulerDefault: function() {
return 'default:';
},
rulerSwitch: function(arr) {
arr= _setVarToken(arr);
return 'switch(' + arr.join('').replace('switch', '') + '){';
},
rulerElseIf: function(arr) {
if (arr.length < 2) {
return false;
}
arr=_setVarToken(arr.slice(1));
return '}else if(' + Ruler.util.filter(arr.join('')) + '){';
},
rulerBreak: function() {
return 'break;';
},
rulerElse: function(arr) {
return '}else{';
},
rulerEndIf: function(arr) {
return '}';
},
rulerIf: function(arr) {
if (arr.length < 2) {
return false;
}
arr=_setVarToken(arr.slice(1));
return 'if(' + Ruler.util.filter(arr.join('')) + '){';
},
rulerEndList: function(arr) {
return '}';
},
/**
* 循环列表方法
* @param arr
* @returns {string}
*/
rulerList: function(arr) {
var listName, loopName, loopIndexName, loopHasNextName, result = [];
if (arr.length != 4) {
return;
}
var _guid = Ruler.guid++;
loopName = arr[3];
listName = arr[1];
loopIndexName = loopName + '_index';
loopHasNextName = loopName + '_has_next';
//如果变量名不是传统的字母或数字
if (!/^\w+$/.test(listName)) {
if (listName.indexOf('$') !== 0) {
listName = '$' + listName;
}
var _listName = '$_list' + _guid;
result.push(_listName + '=' + listName + ';');
listName = _listName;
} else {
listName = '$' + listName;
}
loopName = '$' + loopName;
loopIndexName = '$' + loopIndexName;
loopHasNextName = '$' + loopHasNextName;
result.push([
'$_i{guid}=0',
'$count{guid}=count(' + listName + ')',
loopName,
loopIndexName,
loopHasNextName + ';'
].join(';'));
result.push('for(;$_i{guid}<$count{guid};$_i{guid}++){');
result.push(loopName + '=' + listName + '[$_i{guid}];');
result.push(loopIndexName + '=$_i{guid};');
result.push(loopHasNextName + '=$_i{guid}!==$count{guid}-1;');
return result.join('').replace(/\{guid\}/ig, _guid);
}
};
/**
* 内嵌函数,待扩展
* @type {{trim: Function, lTrim: Function, rTrim: Function, removeEmpty: Function, filter: Function}}
*/
Ruler.util = {
trim: function(str) {
return str.replace(/(^\s*)|(\s*$)/g, "");
},
lTrim: function(str) {
return str.replace(/(^\s*)/g, "");
},
rTrim: function(str) {
return str.replace(/(\s*$)/g, "");
},
removeEmpty: function(arr) {
var splitStr = _separator(arr);
var REMOVE_REGEX = new RegExp(splitStr + splitStr);
var REMOVE_HEAD_REGEX = new RegExp('^' + splitStr);
return arr.join(splitStr).replace(REMOVE_REGEX, splitStr).replace(REMOVE_HEAD_REGEX, '').split(splitStr);
},
filter: function(str) {
return str.replace('<', '<').replace('>', '>');
}
};
/**
* 将模板语法解释为JS语法
* @param _templ 模板字符串
* @returns {String} 语法解析后的
* @private
*/
function _parse(_templ) {
var chunks = [],
replaced = [],
compiled;
var printPrefix = "$__buf__.=";
var lastIndex = 0;
var ss = /<#.+?>|\${.+?}|<\/#.+?>|<@.+?>/ig;
/**
* 将模块中的匹配替换为相应语言的语法
* @param {String} str 输入
* @param {Number} type 0普通字符 1变量 2表达式
* @return {Null}
*/
function _pushStr(str, type) {
if (str !== '') {
if (type == 2) {
replaced.push(str)
} else {
if (type == 1) {
replaced.push(printPrefix + str + ';')
} else {
str = str.replace(/"/ig, "\\\"");
replaced.push(printPrefix + '"' + str + '";')
}
}
}
}
//移除不安全代码
_templ = removeUnsafe(_templ);
_templ.replace(ss, function repalceHandler(match, index) {
if (lastIndex != index) {
var _temp_ = _templ.substring(lastIndex, index);
if (Ruler.util.trim(_temp_) != '')
_pushStr(_templ.substring(lastIndex, index));
chunks.push(_temp_);
}
if (match[0] == '$') {
_pushStr('$' + match.substring(2, match.length - 1), 1);
} else {
//是注释,暂时不处理
if (match[0] == '<' && match[1] == '#' && match[2] == '-') {
} else {
if (match[0] == '<' && match[1] == '#') {
_pushStr(Ruler.regRuler.ruler(match.substring(2, match.length - 1)), 2);
} else if (match[1] == '/' && match[2] == '#') {
_pushStr(Ruler.regRuler.ruler(match.substring(1, match.length - 1)), 2);
}
chunks.push(match);
}
}
//set the last match index as current match index plus matched value length
lastIndex = index + match.length;
});
//add the end string for replaced string
if (lastIndex < _templ.length) {
_pushStr(_templ.substring(lastIndex));
}
//if no matched replace
if (!replaced.length) {
_pushStr(_templ);
}
replaced = ["$__buf__='';", replaced.join(''), ";echo($__buf__);"].join('');
return replaced;
}
function _proc(html, data) {
return html;
}
return {
parse: _parse,
proc: _proc
}
})();
reMarker.JavaScript = (function() {
var Ruler = {};
/**
* 匹配语法规则处理
* @type {{ruler: Function, rulerAssign: Function, rulerEndSwitch: Function, rulerCase: Function, rulerDefault: Function, rulerSwitch: Function, rulerElseIf: Function, rulerBreak: Function, rulerElse: Function, rulerEndIf: Function, rulerIf: Function, rulerEndList: Function, rulerList: Function}}
*/
Ruler.regRuler = {
ruler: function(str) {
var listArr = Ruler.util.removeEmpty(str.split(' '));
//import,include
var ruler = {
"list": this.rulerList,
"if": this.rulerIf,
"break": this.rulerBreak,
'/#list': this.rulerEndList,
'else': this.rulerElse,
"/#if": this.rulerEndIf,
'elseif': this.rulerElseIf,
'switch': this.rulerSwitch,
'case': this.rulerCase,
'default': this.rulerDefault,
'/#switch': this.rulerEndSwitch,
'assign': this.rulerAssign,
'return': this.rulerReturn
};
return (ruler[listArr[0]]).call(this, listArr);
},
rulerReturn: function() {
return 'return;';
},
/**
* 定义变量
* @param arr
* @returns {string}
*/
rulerAssign: function(arr) {
var result = [],
count;
var rt = findPairs(arr.slice(1));
count = rt.length;
for (j = 0; j < count; j += 2) {
var name = rt[j];
result.push('var ');
result.push(name + '=' + rt[j + 1] + ';');
}
return result.join('');
},
rulerEndSwitch: function(arr) {
return '}';
},
rulerCase: function(arr) {
return ('case ' + arr[1] + ':');
},
rulerDefault: function() {
return 'default:';
},
rulerSwitch: function(arr) {
return 'switch(' + arr.join('').replace('switch', '') + '){';
},
rulerElseIf: function(arr) {
if (arr.length < 2) {
return false;
}
return '}else if(' + Ruler.util.filter(arr.slice(1).join('')) + '){';
},
rulerBreak: function() {
return 'break;';
},
rulerElse: function(arr) {
return '}else{';
},
rulerEndIf: function(arr) {
return '}';
},
rulerIf: function(arr) {
if (arr.length < 2) {
return false;
}
return 'if(' + Ruler.util.filter(arr.slice(1).join('')) + '){';
},
rulerEndList: function(arr) {
return '}})();';
},
/**
* 循环列表方法
* @param arr
* @returns {string}
*/
rulerList: function(arr) {
var listName, loopName, loopIndexName, loopHasNextName, result = [];
if (arr.length != 4) {
return;
}
loopName = arr[3];
listName = arr[1];
loopIndexName = loopName + '_index';
loopHasNextName = loopName + '_has_next';
result.push('(function(){');
if (!/^\w+$/.test(listName)) {
result.push('var _list=' + listName + ';');
listName = '_list';
}
result.push([
'var _i=0',
'_count=' + listName + '.length',
loopName,
loopIndexName,
loopHasNextName + ';'
].join(','));
result.push('for(;_i<_count;_i++){');
result.push(loopName + '=' + listName + '[_i];');
result.push(loopIndexName + '=_i;');
result.push(loopHasNextName + '=_i!==_count-1;');
return result.join('');
}
};
/**
* 内嵌函数,待扩展
* @type {{trim: Function, lTrim: Function, rTrim: Function, removeEmpty: Function, filter: Function}}
*/
Ruler.util = {
trim: function(str) {
return str.replace(/(^\s*)|(\s*$)/g, "");
},
lTrim: function(str) {
return str.replace(/(^\s*)/g, "");
},
rTrim: function(str) {
return str.replace(/(\s*$)/g, "");
},
removeEmpty: function(arr) {
var splitStr = _separator(arr);
var REMOVE_REGEX = new RegExp(splitStr + splitStr);
var REMOVE_HEAD_REGEX = new RegExp('^' + splitStr);
return arr.join(splitStr).replace(REMOVE_REGEX, splitStr).replace(REMOVE_HEAD_REGEX, '').split(splitStr);
},
filter: function(str) {
return str.replace('<', '<').replace('>', '>');
}
};
/**
* 将模板语法解释为JS语法
* @param _templ 模板字符串
* @returns {String} 语法解析后的
* @private
*/
function _parse(_templ) {
var chunks = [],
replaced = [],
compiled;
var printPrefix = "__buf__.push(";
var lastIndex = 0;
var ss = /<#.+?>|\${.+?}|<\/#.+?>|<@.+?>/ig;
/**
* 将模块中的匹配替换为相应语言的语法
* @param {String} str 输入
* @param {Number} type 0普通字符 1变量 2表达式
* @return {Null}
*/
function _pushStr(str, type) {
str = str.replace(/'/g, "\\'");
if (str !== '') {
if (type == 1) {
replaced.push(printPrefix + str + ');')
} else if (type == 2) {
replaced.push(str)
} else {
replaced.push(printPrefix + '\'' + str + '\');')
}
}
}
//移除不安全代码
_templ = removeUnsafe(_templ);
_templ.replace(ss, function(match, index) {
//the last match index of all template
//上次匹配结束位置与当前匹配的位置之间可能会有一些字符,也要加进来
if (lastIndex != index) {
var _temp_ = _templ.substring(lastIndex, index);
if (Ruler.util.trim(_temp_) != '')
_pushStr(_templ.substring(lastIndex, index));
chunks.push(_temp_);
}
if (match[0] == '$') {
_pushStr(match.substring(2, match.length - 1), 1);
//replaced.push(printPrefix + match.substring(2, match.length - 1) + ');');
} else {
//是注释,暂时不处理
if (match[0] == '<' && match[1] == '#' && match[2] == '-') {
} else {
if (match[0] == '<' && match[1] == '#') {
_pushStr(Ruler.regRuler.ruler(match.substring(2, match.length - 1)), 2);
} else if (match[1] == '/' && match[2] == '#') {
_pushStr(Ruler.regRuler.ruler(match.substring(1, match.length - 1)), 2);
} else {}
chunks.push(match);
}
}
//set the last match index as current match index plus matched value length
lastIndex = index + match.length;
});
//add the end string for replaced string
if (lastIndex < _templ.length) {
_pushStr(_templ.substring(lastIndex));
}
//if no matched replace
if (!replaced.length) {
_pushStr(_templ);
}
replaced = ["var __buf__=[],$index=null;with($data){", replaced.join(''), "} return __buf__.join('');"].join('');
return replaced;
}
function _proc(html, data) {
var util = {};
if (Ruler.util) {
var _util = Ruler.util;
for (var key in _util) {
util[key] = _util[key];
}
}
if (Object.prototype.toString.call(data) !== '[object Object]') {
data = {};
}
var replaced = html;
try {
compiled = new Function("$data", "$util", replaced);
} catch (e) {
throw "template code error";
}
return compiled.call(window, data, util)
}
return {
parse: _parse,
proc: _proc
}
})();
/*
模板引擎,使用freemark语法,目前已知最快的
作者:陈鑫
*/
var nc = typeof exports !== 'undefined' ? exports : {};
nc.reMarker = {
/**
* 柯里化模板语法,二次传入
* @param templ
* @returns {Function}
*/
proc: reMarker,
parse:reMarker
};
});
//如果内嵌入web页面,则自动将模板导出为JS变量
! function(factory) {
if (typeof require === 'function' && typeof exports === 'object' && typeof module === 'object') {
var target = module['exports'] || exports;
factory(target);
} else if (typeof define === 'function' && define['amd']) {
define(['exports'], factory);
} else {
var scriptTags = document.getElementsByTagName('script'),
templates = [];
for (var i = 0; i < scriptTags.length; i++) {
if (scriptTags[i].getAttribute('type') == 'remark-template') {
templates.push(scriptTags[i]);
}
}
for (var t = 0; t < templates.length; t++) {
var _id = '__' + templates[t].id + '__';
window[_id] = window.NC.reMarker.proc(templates[t].innerHTML);
}
}
}(function(exports) {}); | simon4545/cff | Build/template-build.js | JavaScript | gpl-2.0 | 23,369 |
/**
* Route Mappings
* (sails.config.routes)
*
* Your routes map URLs to views and controllers.
*
* If Sails receives a URL that doesn't match any of the routes below,
* it will check for matching files (images, scripts, stylesheets, etc.)
* in your assets directory. e.g. `http://localhost:1337/images/foo.jpg`
* might match an image file: `/assets/images/foo.jpg`
*
* Finally, if those don't match either, the default 404 handler is triggered.
* See `api/responses/notFound.js` to adjust your app's 404 logic.
*
* Note: Sails doesn't ACTUALLY serve stuff from `assets`-- the default Gruntfile in Sails copies
* flat files from `assets` to `.tmp/public`. This allows you to do things like compile LESS or
* CoffeeScript for the front-end.
*
* For more information on configuring custom routes, check out:
* http://sailsjs.org/#/documentation/concepts/Routes/RouteTargetSyntax.html
*/
module.exports.routes = {
/***************************************************************************
* *
* Make the view located at `views/homepage.ejs` (or `views/homepage.jade`, *
* etc. depending on your default view engine) your home page. *
* *
* (Alternatively, remove this and add an `index.html` file in your *
* `assets` directory) *
* *
***************************************************************************/
'/': {
view: 'homepage',
locals: {
laytout: 'layout'
}
},
'/admin': {
view: 'admin',
locals: {
layout: 'cms'
}
},
'/admin/login': {
view: 'login',
locals: {
layout: 'layout'
}
},
'/admin/week': {
controller: 'week',
action: 'index',
locals: {
layout: 'cms'
}
},
'/admin/week/save': {
controller: 'week',
action: 'save',
locals: {
layout: 'cms'
}
},
'/admin/week/add': {
view: 'weeks-form',
locals: {
layout: 'cms'
}
},
/***************************************************************************
* *
* Custom routes here... *
* *
* If a request to a URL doesn't match any of the custom routes above, it *
* is matched against Sails route blueprints. See `config/blueprints.js` *
* for configuration options and examples. *
* *
***************************************************************************/
};
| hyphenated/reto40Semanas | config/routes.js | JavaScript | gpl-2.0 | 2,924 |
/**
* Textarea Element
*
* @copyright: Copyright (C) 2005-2013, fabrikar.com - All rights reserved.
* @license: GNU/GPL http://www.gnu.org/copyleft/gpl.html
*/
var FbTextarea = new Class({
Extends: FbElement,
initialize: function (element, options) {
this.plugin = 'fabriktextarea';
this.parent(element, options);
// $$$ rob need to slightly delay this as if lots of js loaded (eg maps)
// before the editor then the editor may not yet be loaded
this.periodFn = function () {
// Seems that tinyMCE isn't created if FbLike element published in form
this.getTextContainer();
if (typeof tinyMCE !== 'undefined') {
if (this.container !== false) {
clearInterval(p);
this.watchTextContainer();
}
} else {
clearInterval(p);
this.watchTextContainer();
}
};
var p = this.periodFn.periodical(200, this);
Fabrik.addEvent('fabrik.form.page.change.end', function (form) {
this.refreshEditor();
}.bind(this));
Fabrik.addEvent('fabrik.form.elements.added', function (form) {
if (form.isMultiPage()) {
this.refreshEditor();
}
}.bind(this));
},
unclonableProperties: function ()
{
var props = this.parent();
props.push('container');
return props;
},
/**
* Set names/ids/elements ect when the elements group is cloned
*
* @param int id element id
* @since 3.0.7
*/
cloneUpdateIds: function (id) {
this.element = document.id(id);
this.options.element = id;
this.options.htmlId = id;
},
watchTextContainer: function ()
{
if (typeOf(this.element) === 'null') {
this.element = document.id(this.options.element);
}
if (typeOf(this.element) === 'null') {
this.element = document.id(this.options.htmlId);
if (typeOf(this.element) === 'null') {
// Can occur when element is part of hidden first group
return;
}
}
if (this.options.editable === true) {
var c = this.getContainer();
if (c === false) {
fconsole('no fabrikElementContainer class found for textarea');
return;
}
var element = c.getElement('.fabrik_characters_left');
if (typeOf(element) !== 'null') {
this.warningFX = new Fx.Morph(element, {duration: 1000, transition: Fx.Transitions.Quart.easeOut});
this.origCol = element.getStyle('color');
if (this.options.wysiwyg && typeof(tinymce) !== 'undefined') {
// Joomla 3.2 + usess tinyMce 4
if (tinymce.majorVersion >= 4) {
tinyMCE.get(this.element.id).on('keyup', function (e) {
this.informKeyPress(e);
}.bind(this));
tinyMCE.get(this.element.id).on('focus', function (e) {
var c = this.element.getParent('.fabrikElementContainer');
c.getElement('span.badge').addClass('badge-info');
c.getElement('.fabrik_characters_left').removeClass('muted');
}.bind(this));
tinyMCE.get(this.element.id).on('blur', function (e) {
var c = this.element.getParent('.fabrikElementContainer');
c.getElement('span.badge').removeClass('badge-info');
c.getElement('.fabrik_characters_left').addClass('muted');
}.bind(this));
tinyMCE.get(this.element.id).on('blur', function (e) {
this.forwardEvent('blur');
}.bind(this));
} else {
tinymce.dom.Event.add(this.container, 'keyup', function (e) {
this.informKeyPress(e);
}.bind(this));
tinymce.dom.Event.add(this.container, 'blur', function (e) {
this.forwardEvent('blur');
}.bind(this));
}
} else {
if (typeOf(this.container) !== 'null') {
this.container.addEvent('keydown', function (e) {
this.informKeyPress(e);
}.bind(this));
this.container.addEvent('blur', function (e) {
this.blurCharsLeft(e);
}.bind(this));
this.container.addEvent('focus', function (e) {
this.focusCharsLeft(e);
}.bind(this));
}
}
}
}
},
/**
* Forward an event from tinyMce to the text editor - useful for triggering ajax validations
*
* @param string event Event name
*/
forwardEvent: function (event) {
var textarea = tinyMCE.activeEditor.getElement(),
c = this.getContent();
textarea.set('value', c);
textarea.fireEvent('blur', new Event.Mock(textarea, event));
},
focusCharsLeft: function () {
var c = this.element.getParent('.fabrikElementContainer');
c.getElement('span.badge').addClass('badge-info');
c.getElement('.fabrik_characters_left').removeClass('muted');
},
blurCharsLeft: function () {
var c = this.element.getParent('.fabrikElementContainer');
c.getElement('span.badge').removeClass('badge-info');
c.getElement('.fabrik_characters_left').addClass('muted');
},
/**
* Used to find element when form clones a group
* WYSIWYG text editor needs to return something specific as options.element has to use name
* and not id.
*/
getCloneName: function () {
var name = this.options.isGroupJoin ? this.options.htmlId : this.options.element;
return name;
},
/**
* Run when element cloned in repeating group
*
* @param int c repeat group counter
*/
cloned: function (c) {
if (this.options.wysiwyg) {
var p = this.element.getParent('.fabrikElement');
var txt = p.getElement('textarea').clone(true, true);
var charLeft = p.getElement('.fabrik_characters_left');
p.empty();
p.adopt(txt);
if (typeOf(charLeft) !== 'null') {
p.adopt(charLeft.clone());
}
txt.removeClass('mce_editable');
txt.setStyle('display', '');
this.element = txt;
var id = this.options.isGroupJoin ? this.options.htmlId : this.options.element;
tinyMCE.execCommand('mceAddControl', false, id);
}
this.getTextContainer();
this.watchTextContainer();
this.parent(c);
},
/**
* run when the element is decloled from the form as part of a deleted repeat group
*/
decloned: function (groupid) {
if (this.options.wysiwyg) {
var id = this.options.isGroupJoin ? this.options.htmlId : this.options.element;
tinyMCE.execCommand('mceFocus', false, id);
tinyMCE.execCommand('mceRemoveControl', false, id);
}
},
getTextContainer: function ()
{
if (this.options.wysiwyg && this.options.editable) {
var name = this.options.isGroupJoin ? this.options.htmlId : this.options.element;
document.id(name).addClass('fabrikinput');
var instance = typeof(tinyMCE) !== 'undefined' ? tinyMCE.get(name) : false;
if (instance) {
this.container = instance.getDoc();
} else {
this.contaner = false;
}
} else {
// Regrab the element for inline editing (otherwise 2nd col you edit doesnt pickup the textarea.
this.element = document.id(this.options.element);
this.container = this.element;
}
return this.container;
},
getContent: function ()
{
if (this.options.wysiwyg) {
return tinyMCE.activeEditor.getContent().replace(/<\/?[^>]+(>|$)/g, "");
} else {
return this.container.value;
}
},
/**
* On ajax loaded page need to re-load the editor
* For Chrome
*/
refreshEditor: function () {
if (this.options.wysiwyg) {
if (typeof WFEditor !== 'undefined') {
WFEditor.init(WFEditor.settings);
} else if (typeof tinymce !== 'undefined') {
tinyMCE.init(tinymce.settings);
}
// Need to re-observe the editor
this.watchTextContainer();
}
},
setContent: function (c)
{
if (this.options.wysiwyg) {
var r = tinyMCE.getInstanceById(this.element.id).setContent(c);
this.moveCursorToEnd();
return r;
} else {
this.getTextContainer();
if (typeOf(this.container) !== 'null') {
this.container.value = c;
}
}
return null;
},
/**
* For tinymce move the cursor to the end
*/
moveCursorToEnd: function () {
var inst = tinyMCE.getInstanceById(this.element.id);
inst.selection.select(inst.getBody(), true);
inst.selection.collapse(false);
},
informKeyPress: function ()
{
var charsleftEl = this.getContainer().getElement('.fabrik_characters_left');
var content = this.getContent();
charsLeft = this.itemsLeft();
if (this.limitReached()) {
this.limitContent();
this.warningFX.start({'opacity': 0, 'color': '#FF0000'}).chain(function () {
this.start({'opacity': 1, 'color': '#FF0000'}).chain(function () {
this.start({'opacity': 0, 'color': this.origCol}).chain(function () {
this.start({'opacity': 1});
});
});
});
} else {
charsleftEl.setStyle('color', this.origCol);
}
charsleftEl.getElement('span').set('html', charsLeft);
},
/**
* How many content items left (e.g 1 word, 100 characters)
*
* @return int
*/
itemsLeft: function () {
var i = 0,
content = this.getContent();
if (this.options.maxType === 'word') {
i = this.options.max - content.split(' ').length;
} else {
i = this.options.max - (content.length + 1);
}
if (i < 0) {
i = 0;
}
return i;
},
/**
* Limit the content based on maxType and max e.g. 100 words, 2000 characters
*/
limitContent: function () {
var c,
content = this.getContent();
if (this.options.maxType === 'word') {
c = content.split(' ').splice(0, this.options.max);
c = c.join(' ');
c += (this.options.wysiwyg) ? ' ' : ' ';
} else {
c = content.substring(0, this.options.max);
}
this.setContent(c);
},
/**
* Has the max content limit been reached?
*
* @return bool
*/
limitReached: function () {
var content = this.getContent();
if (this.options.maxType === 'word') {
var words = content.split(' ');
return words.length > this.options.max;
} else {
var charsLeft = this.options.max - (content.length + 1);
return charsLeft < 0 ? true : false;
}
},
reset: function ()
{
this.update(this.options.defaultVal);
},
update: function (val) {
this.getElement();
this.getTextContainer();
if (!this.options.editable) {
this.element.set('html', val);
return;
}
this.setContent(val);
}
}); | raimov/broneering | plugins/fabrik_element/textarea/textarea.js | JavaScript | gpl-2.0 | 9,888 |
Ext.define('Planche.lib.Query', {
constructor : function(query){
Ext.apply(this, query);
},
getPrevRecordSetSQL : function(){
this.start -= this.end;
if(this.start < 0) this.start = 0;
return this.getSQL();
},
getNextRecordSetSQL : function(){
this.start += this.end;
return this.getSQL();
},
getPrevRecordSQL : function(){
this.start--;
if(this.start < 0) this.start = 0;
return this.getSQL();
},
getNextRecordSQL : function(){
this.start++;
return this.getSQL();
},
getSQL : function(){
if(this.isSelectQuery == true){
return this.sql + ' LIMIT ' + this.start + ", " + this.end;
}
else {
return this.raw;
}
},
getRawSQL : function(){
return this.raw;
},
getTokens : function(){
return this.tokens;
},
isSelectQuery : function(){
return this.selectQuery;
},
isDelimiter : function(){
return this.delimiter;
},
hasNext : function(){
return this.raw.length > this.end ? true : false;
},
setRecords : function(records){
Ext.apply(this, {
records : records
});
},
isSelectedQuery : function(line, cursor){
var linecursor = parseFloat(line + "." + cursor);
if(this.sline <= linecursor && linecursor >= this.eline){
return true;
}
else {
return false;
}
}
}); | skyfly33/planche | lib/Query.js | JavaScript | gpl-2.0 | 1,386 |
;
;
;
;
;
| asheehan/VectorBase | sites/all/modules/custom/downloadable_file/include/sites/default/files/ftp/js/js_hGOh1qp3Vvjqy8AD12NYODQYydqXURqvXXSO1gvio1M.js | JavaScript | gpl-2.0 | 10 |
define('util', ['jquery'], function($){
$.extend({
restGet: function(url, data, callback){
$.get(url, data, function(data){
if(data.success){
callback(data);
} else {
if(data.redirect){
location.href = data.redirect;
}
else if(data.message){
$.showError('notify', data.message);
}
}
});
},
restPost: function(url, data, callback){
$.post(url, data, function(data){
if(data.success){
callback(data);
} else {
if(data.redirect){
location.href = data.redirect;
}
else if(data.message){
$.showError('notify', data.message);
}
}
});
},
showError: function(id, message){
$("#" + id).append('<div class="alert alert-error fade in"><a href="#" data-dismiss="alert" class="close">×</a><strong>错误:</strong><span></span></div>')
$("#" + id +" > div > span").text(message);
$("#" + id +" > .alert").alert();
setTimeout(function(){
$("#" + id +" > .alert").alert('close');
}, 3000);
},
showSuccess: function(id, message){
$("#" + id).append('<div class="alert alert-success fade in"><a href="#" data-dismiss="alert" class="close">×</a><span></span></div>')
$("#" + id +" > div > span").text(message);
$("#" + id +" > .alert").alert();
setTimeout(function(){
$("#" + id +" > .alert").alert('close');
}, 3000);
},
backdrop: function(state){
if(state == 'show'){
$("body").append("<div class='modal-backdrop fade in'></div>");
} else if(state == 'hide'){
$(".modal-backdrop").remove();
};
},
});
$.fn.extend({
edata: function(id){
return this.attr("data-" + id);
},
reset: function(){
var id = this.attr('id');
document.getElementById(id).reset();
},
is_disabled: function(){
return this.attr("disabled") == "disabled";
},
});
return $;
}); | Wangzr/rabbit-home | public/javascripts/jquery-extend.js | JavaScript | gpl-2.0 | 1,919 |
(function(){
if ( window.xataface == undefined ) window.xataface = {};
if ( window.xataface.modules == undefined ) window.xataface.modules = {};
if ( window.xataface.modules.htmlreports == undefined ) window.xataface.modules.htmlreports = {};
})(); | MfN-Berlin/AmphibiansTraits | modules/htmlreports/js/xataface/modules/htmlreports/__init__.js | JavaScript | gpl-2.0 | 253 |
(function($, Translator) {
Skin = function Skin(code, skinData) {
this.variableRegex = /\{#([\w \|]*)\#\}/;
this.translateRegex = /\{=([\w \|,]*)\=\}/;
this.code = code;
this.extractData(skinData);
}
Skin.prototype.scanChildren = function(code, skinData) {
if(skinData)
this.extractData(skinData);
var variables = this.data.variableBlocks;
var loops = this.data.loopBlocks;
code = this.checkCondition(code, variables);
code = this.checkLoop(code, loops, skinData);
return this.executeVariableBlocks(this.executeTranslateBlocks(code, variables), variables);
}
/*
* Gets code, parses with jQuery, checks and returns code
*/
Skin.prototype.checkCondition = function(code, variables) {
var checkCondition = $(code);
if(checkCondition.hasAttr('skif')) {
var skif = checkCondition.attr('skif');
if(variables[skif]) {
if($.toBoolean(variables[skif])) {
checkCondition.removeAttr('skif');
return checkCondition.outerHTML();
} else
return '';
} else
return '';
}
return code;
}
/*
* Gets code, parses with jQuery, checks and returns code
*/
Skin.prototype.checkLoop = function(code, loops, skinData) {
var checkLoop = $(code);
var newNodeHTML = '';
var children = checkLoop.contents();
var $this = this;
if(checkLoop.hasAttr('skloop')) {
var skloop = checkLoop.attr('skloop');
if(loops[skloop]) {
checkLoop.removeAttr('skloop');
for(var i = 0; i < loops[skloop].length; ++i) {
if(typeof(loops[skloop]) === 'array' || typeof(loops[skloop]) === 'object')
newNodeHTML += $this.scanChildren(checkLoop.outerHTML(), loops[skloop][i]);
}
} else
return '';
} else {
$.each(children, function(key, child) {
if(child.nodeType === 1)
newNodeHTML += $this.scanChildren($(child).outerHTML(), skinData);
else if(child.nodeType === 3)
newNodeHTML += child.textContent;
});
}
if(newNodeHTML !== '')
code = newNodeHTML;
checkLoop.html(code);
return checkLoop.outerHTML();
}
Skin.prototype.extractData = function(skinData) {
var $this = this;
this.data = {
'loopBlocks':{},
'variableBlocks':{}
};
$.each(skinData, function(key, value) {
switch (typeof(value)) {
case 'object':
case 'array':
$this.data.loopBlocks[key] = value;
break;
default:
$this.data.variableBlocks[key] = value;
break;
}
});
}
Skin.prototype.executeVariableBlocks = function(code, variableBlocks) {
if (variableBlocks) {
var matchVariable = code.matchAll(this.variableRegex);
if (matchVariable) {
for (var variables = 0; variables < matchVariable.length; ++variables) {
var explodeVar = matchVariable[variables][1].split('|');
var property = explodeVar[0].replace(' ', '');
if (variableBlocks[property]) {
if(explodeVar[1]) {
var explodeFunc = explodeVar[1].split(' ');
for(var i = 0; i < explodeFunc.length; ++i) {
var $func = this[explodeFunc[i]];
if(explodeFunc[i] && typeof $func === 'function')
variableBlocks[property] = $func(variableBlocks[property]);
}
}
return code.replace(matchVariable[variables][0], variableBlocks[property]);
} else
return code.replace(matchVariable[variables][0], '');
}
}
}
return code;
}
Skin.prototype.executeTranslateBlocks = function(code, variableBlocks) {
if(variableBlocks) {
var matchTranslate = code.matchAll(this.translateRegex);
if(matchTranslate) {
for(var translates = 0; translates < matchTranslate.length; ++translates) {
var explodeTranslate = matchTranslate[translates][1].replace(/ /g,'').split('|');
if(explodeTranslate[1]) {
var arguments = explodeTranslate[1].split(',');
var variables = [];
for(var i = 0; i < arguments.length; ++i)
variables[i] = variableBlocks[arguments[i]] ? variableBlocks[arguments[i]] : '"' + arguments[i] + '"';
return code.replace(matchTranslate[0][translates], Translator._(explodeTranslate[0], variables));
} else
return code.replace(matchTranslate[0][translates], Translator._(explodeTranslate[0]));
}
}
}
return code;
}
Skin.prototype.render = function() {
var domNode = $('<div id="skinTemporaryDiv">' + this.code + '</div>')
var children = domNode.contents();
var $this = this;
var outHTML = '';
$.each(children, function(key, child) {
outHTML += $this.scanChildren($(child).outerHTML());
});
return outHTML;
}
/*
* Skin functions & aliases
*/
Skin.prototype.e = Skin.prototype.escape = function(string) {
return string.htmlentities();
}
Skin.prototype.df = Skin.prototype.date = function(date) {
var date = new Date(date);
return date.format('dd/mm/yyyy')
}
Skin.prototype.l = Skin.prototype.link = function(string) {
}
return Skin;
}($, Translator)); | Laegel/Carpenter | Skin.js | JavaScript | gpl-2.0 | 6,085 |
/* Bootstrap v3.3.1 (http://getbootstrap.com)
* Copyright 2011-2014 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* Modifications from Andoni M. Garcia.
*/
if (typeof jQuery === 'undefined') {
throw new Error('Bootstrap\'s JavaScript requires jQuery')
}
+function ($) {
var version = $.fn.jquery.split(' ')[0].split('.')
if ((version[0] < 2 && version[1] < 9) || (version[0] == 1 && version[1] == 9 && version[2] < 1)) {
throw new Error('Bootstrap\'s JavaScript requires jQuery version 1.9.1 or higher')
}
}(jQuery);
/* ========================================================================
* Bootstrap: transition.js v3.3.1
* http://getbootstrap.com/javascript/#transitions
* ========================================================================
* Copyright 2011-2014 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// CSS TRANSITION SUPPORT (Shoutout: http://www.modernizr.com/)
// ============================================================
function transitionEnd() {
var el = document.createElement('bootstrap')
var transEndEventNames = {
WebkitTransition : 'webkitTransitionEnd',
MozTransition : 'transitionend',
OTransition : 'oTransitionEnd otransitionend',
transition : 'transitionend'
}
for (var name in transEndEventNames) {
if (el.style[name] !== undefined) {
return { end: transEndEventNames[name] }
}
}
return false // explicit for ie8 ( ._.)
}
// http://blog.alexmaccaw.com/css-transitions
$.fn.emulateTransitionEnd = function (duration) {
var called = false
var $el = this
$(this).one('bsTransitionEnd', function () { called = true })
var callback = function () { if (!called) $($el).trigger($.support.transition.end) }
setTimeout(callback, duration)
return this
}
$(function () {
$.support.transition = transitionEnd()
if (!$.support.transition) return
$.event.special.bsTransitionEnd = {
bindType: $.support.transition.end,
delegateType: $.support.transition.end,
handle: function (e) {
if ($(e.target).is(this)) return e.handleObj.handler.apply(this, arguments)
}
}
})
}(jQuery);
/* ========================================================================
* Bootstrap: collapse.js v3.3.1
* http://getbootstrap.com/javascript/#collapse
* ========================================================================
* Copyright 2011-2014 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// COLLAPSE PUBLIC CLASS DEFINITION
// ================================
var Collapse = function (element, options) {
this.$element = $(element)
this.options = $.extend({}, Collapse.DEFAULTS, options)
this.$trigger = $(this.options.trigger).filter('[href="#' + element.id + '"], [data-target="#' + element.id + '"]')
this.transitioning = null
if (this.options.parent) {
this.$parent = this.getParent()
} else {
this.addAriaAndCollapsedClass(this.$element, this.$trigger)
}
if (this.options.toggle) this.toggle()
}
Collapse.VERSION = '3.3.1'
Collapse.TRANSITION_DURATION = 350
Collapse.DEFAULTS = {
toggle: true,
trigger: '[data-toggle="collapse"]'
}
Collapse.prototype.dimension = function () {
var hasWidth = this.$element.hasClass('width')
return hasWidth ? 'width' : 'height'
}
Collapse.prototype.show = function () {
if (this.transitioning || this.$element.hasClass('in')) return
var activesData
var actives = this.$parent && this.$parent.find('> .panel').children('.in, .collapsing')
if (actives && actives.length) {
activesData = actives.data('bs.collapse')
if (activesData && activesData.transitioning) return
}
var startEvent = $.Event('show.bs.collapse')
this.$element.trigger(startEvent)
if (startEvent.isDefaultPrevented()) return
if (actives && actives.length) {
Plugin.call(actives, 'hide')
activesData || actives.data('bs.collapse', null)
}
var dimension = this.dimension()
this.$element
.removeClass('collapse')
.addClass('collapsing')[dimension](0)
.attr('aria-expanded', true)
this.$trigger
.removeClass('collapsed')
.attr('aria-expanded', true)
this.transitioning = 1
var complete = function () {
this.$element
.removeClass('collapsing')
.addClass('collapse in')[dimension]('')
this.transitioning = 0
this.$element
.trigger('shown.bs.collapse')
}
if (!$.support.transition) return complete.call(this)
var scrollSize = $.camelCase(['scroll', dimension].join('-'))
this.$element
.one('bsTransitionEnd', $.proxy(complete, this))
.emulateTransitionEnd(Collapse.TRANSITION_DURATION)[dimension](this.$element[0][scrollSize])
}
Collapse.prototype.hide = function () {
if (this.transitioning || !this.$element.hasClass('in')) return
var startEvent = $.Event('hide.bs.collapse')
this.$element.trigger(startEvent)
if (startEvent.isDefaultPrevented()) return
var dimension = this.dimension()
this.$element[dimension](this.$element[dimension]())[0].offsetHeight
this.$element
.addClass('collapsing')
.removeClass('collapse in')
.attr('aria-expanded', false)
this.$trigger
.addClass('collapsed')
.attr('aria-expanded', false)
this.transitioning = 1
var complete = function () {
this.transitioning = 0
this.$element
.removeClass('collapsing')
.addClass('collapse')
.trigger('hidden.bs.collapse')
}
if (!$.support.transition) return complete.call(this)
this.$element
[dimension](0)
.one('bsTransitionEnd', $.proxy(complete, this))
.emulateTransitionEnd(Collapse.TRANSITION_DURATION)
}
Collapse.prototype.toggle = function () {
this[this.$element.hasClass('in') ? 'hide' : 'show']()
}
Collapse.prototype.getParent = function () {
return $(this.options.parent)
.find('[data-toggle="collapse"][data-parent="' + this.options.parent + '"]')
.each($.proxy(function (i, element) {
var $element = $(element)
this.addAriaAndCollapsedClass(getTargetFromTrigger($element), $element)
}, this))
.end()
}
Collapse.prototype.addAriaAndCollapsedClass = function ($element, $trigger) {
var isOpen = $element.hasClass('in')
$element.attr('aria-expanded', isOpen)
$trigger
.toggleClass('collapsed', !isOpen)
.attr('aria-expanded', isOpen)
}
function getTargetFromTrigger($trigger) {
var href
var target = $trigger.attr('data-target')
|| (href = $trigger.attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '') // strip for ie7
return $(target)
}
// COLLAPSE PLUGIN DEFINITION
// ==========================
function Plugin(option) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.collapse')
var options = $.extend({}, Collapse.DEFAULTS, $this.data(), typeof option == 'object' && option)
if (!data && options.toggle && option == 'show') options.toggle = false
if (!data) $this.data('bs.collapse', (data = new Collapse(this, options)))
if (typeof option == 'string') data[option]()
})
}
var old = $.fn.collapse
$.fn.collapse = Plugin
$.fn.collapse.Constructor = Collapse
// COLLAPSE NO CONFLICT
// ====================
$.fn.collapse.noConflict = function () {
$.fn.collapse = old
return this
}
// COLLAPSE DATA-API
// =================
$(document).on('click.bs.collapse.data-api', '[data-toggle="collapse"]', function (e) {
var $this = $(this)
if (!$this.attr('data-target')) e.preventDefault()
var $target = getTargetFromTrigger($this)
var data = $target.data('bs.collapse')
var option = data ? 'toggle' : $.extend({}, $this.data(), { trigger: this })
Plugin.call($target, option)
})
}(jQuery);
/* ========================================================================
* Bootstrap: tab.js v3.3.1
* http://getbootstrap.com/javascript/#tabs
* ========================================================================
* Copyright 2011-2014 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// TAB CLASS DEFINITION
// ====================
var Tab = function (element) {
this.element = $(element)
}
Tab.VERSION = '3.3.1'
Tab.TRANSITION_DURATION = 150
Tab.prototype.show = function () {
var $this = this.element
var $ul = $this.closest('ul:not(.dropdown-menu)')
var selector = $this.data('target')
if (!selector) {
selector = $this.attr('href')
selector = selector && selector.replace(/.*(?=#[^\s]*$)/, '') // strip for ie7
}
if ($this.parent('li').hasClass('active')) return
var $previous = $ul.find('.active:last a')
var hideEvent = $.Event('hide.bs.tab', {
relatedTarget: $this[0]
})
var showEvent = $.Event('show.bs.tab', {
relatedTarget: $previous[0]
})
$previous.trigger(hideEvent)
$this.trigger(showEvent)
if (showEvent.isDefaultPrevented() || hideEvent.isDefaultPrevented()) return
var $target = $(selector)
this.activate($this.closest('li'), $ul)
this.activate($target, $target.parent(), function () {
$previous.trigger({
type: 'hidden.bs.tab',
relatedTarget: $this[0]
})
$this.trigger({
type: 'shown.bs.tab',
relatedTarget: $previous[0]
})
})
}
Tab.prototype.activate = function (element, container, callback) {
var $active = container.find('> .active')
var transition = callback
&& $.support.transition
&& (($active.length && $active.hasClass('fade')) || !!container.find('> .fade').length)
function next() {
$active
.removeClass('active')
.find('> .dropdown-menu > .active')
.removeClass('active')
.end()
.find('[data-toggle="tab"]')
.attr('aria-expanded', false)
element
.addClass('active')
.find('[data-toggle="tab"]')
.attr('aria-expanded', true)
if (transition) {
element[0].offsetWidth // reflow for transition
element.addClass('in')
} else {
element.removeClass('fade')
}
if (element.parent('.dropdown-menu')) {
element
.closest('li.dropdown')
.addClass('active')
.end()
.find('[data-toggle="tab"]')
.attr('aria-expanded', true)
}
callback && callback()
}
$active.length && transition ?
$active
.one('bsTransitionEnd', next)
.emulateTransitionEnd(Tab.TRANSITION_DURATION) :
next()
$active.removeClass('in')
}
// TAB PLUGIN DEFINITION
// =====================
function Plugin(option) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.tab')
if (!data) $this.data('bs.tab', (data = new Tab(this)))
if (typeof option == 'string') data[option]()
})
}
var old = $.fn.tab
$.fn.tab = Plugin
$.fn.tab.Constructor = Tab
// TAB NO CONFLICT
// ===============
$.fn.tab.noConflict = function () {
$.fn.tab = old
return this
}
// TAB DATA-API
// ============
var clickHandler = function (e) {
e.preventDefault()
Plugin.call($(this), 'show')
}
$(document)
.on('click.bs.tab.data-api', '[data-toggle="tab"]', clickHandler)
.on('click.bs.tab.data-api', '[data-toggle="pill"]', clickHandler)
}(jQuery); | andonigarcia/andonigarcia.github.io | js/bootstrap.js | JavaScript | gpl-2.0 | 12,178 |
// Generated by CoffeeScript 1.8.0
var db, monitor;
db = require('./db.js');
monitor = require('./monitor.js');
module.exports.launch = function() {
require('./argv_parser.js').parse(process.argv.slice(2), function() {
var m;
db.createClient();
db.clearQueue();
m = monitor.createMonitor().start();
});
};
| PaprikaZ/buyer-monitor | lib/launcher.js | JavaScript | gpl-2.0 | 329 |
self.addEventListener("message", nextEmpty);
function isAt(points, x, y) {
for (var i = 0, len = points.length; i < len; i += 2) {
if (points[i] == x && points[i + 1] == y)
return true;
}
return false;
}
function nextEmpty(event) {
var data = event.data;
var x = 0;
var y = 0;
while (true) {
x = parseInt(Math.random() * data.width);
y = parseInt(Math.random() * data.height);
if (!isAt(data.points, x, y))
break;
}
self.postMessage({x: x, y: y});
} | formigone/easylearntutorial | js/gamedev/app/snake/js/next-empty.worker.js | JavaScript | gpl-2.0 | 525 |
var Arduino = function(port) {
this.portName = port;
this.status = "CLOSED";
}
module.exports = Arduino; | Thom-x/arduino-serial-api | lib/class/arduino.js | JavaScript | gpl-2.0 | 109 |
'use strict';
var config = require('../config'),
gulp = require('gulp'),
size = require('gulp-size');
// output size in console
gulp.task('info', function() {
// You can pass as many relative urls as you want
return gulp.src(config.destPaths.root + '/*/**')
.pipe(size())
});
| kiriaze/new-sg | gulp/tasks/info.js | JavaScript | gpl-2.0 | 297 |
var _hc_windowTimeout;
var _hc_newDemographicHandler = function(args) {
clearTimeout(_hc_windowTimeout);
var window = jQuery("#_hc_window");
jQuery(window).find("#_hc_message, #_hc_read, #_hc_actions, #_hc_match, #_hc_noMatch, #_hc_matchSearch, #_hc_closeBtn").hide();
jQuery(window).find("._hc_mismatch").removeClass("_hc_mismatch");
jQuery(window).find("#_hc_errors").children().remove();
if (!(typeof args["error"] == "undefined")) {
jQuery(window).find("#_hc_closeBtn").hide();
jQuery(window).find("#_hc_status_text_success").hide();
jQuery(window).find("#_hc_status_text_error, #_hc_message_tryAgain, #_hc_message").show();
jQuery(window).find("#_hc_status_icon").attr("class", "_hc_inlineBlock _hc_status_error");
if (args["error"] == "INVALID") {
jQuery(window).find("#_hc_message_readError").css("display", "inline-block");
jQuery(window).find("#_hc_message_issuerError").css("display", "none");
} else if (args["error"] == "ISSUER") {
jQuery(window).find("#_hc_message_readError").css("display", "none");
jQuery(window).find("#_hc_message_issuerError").css("display", "inline-block");
} else {
jQuery(window).find("#_hc_message_readError").css("display", "none");
jQuery(window).find("#_hc_message_issuerError").css("display", "none");
}
_hc_windowTimeout = setTimeout(function() {
jQuery("#_hc_window").css("display", "none");
}, 3000);
} else {
jQuery(window).find("#_hc_status_text_success, #_hc_read, #_hc_layout").show();
jQuery(window).find("#_hc_message, #_hc_status_text_error").hide();
jQuery(window).find("#_hc_status_icon").attr("class", "_hc_inlineBlock _hc_status_success");
jQuery(window).find("#_hc_layout_name").text(args["lastName"] + ", " + args["firstName"]);
jQuery(window).find("#_hc_layout_hin_num").html(args["hin"].substring(0,4) + "• " + args["hin"].substring(4,7) + "• " + args["hin"].substring(7,10) + "•");
jQuery(window).find("#_hc_layout_hin_ver").text(args["hinVer"]);
jQuery(window).find("#_hc_layout_info_dob").text(args["dob"].substring(0,4) + "/" + args["dob"].substring(4,6) + "/" + args["dob"].substring(6,8));
jQuery(window).find("#_hc_layout_info_sex").text((args["sex"] == "1" ? "M" : (args["sex"] == "2" ? "F" : "")));
var issueDate = (args["issueDate"].substring(0,2) <= 30 ? "20" : "19") + args["issueDate"];
jQuery(window).find("#_hc_layout_valid_from").text(issueDate.substring(0,4) + "/" + issueDate.substring(4,6) + "/" + issueDate.substring(6,8));
var hinExp = (args["hinExp"].substring(0,2) <= 30 ? "20" : "19") + args["hinExp"];
jQuery(window).find("#_hc_layout_valid_to").text(hinExp.substring(0,4) + "/" + hinExp.substring(4,6));
if (hinExp != "0000") {
var hinExp = (args["hinExp"].substring(0,2) <= 30 ? "20" : "19") + args["hinExp"] + args["dob"].substring(6,8);
jQuery(window).find("#_hc_layout_valid_to").text(hinExp.substring(0,4) + "/" + hinExp.substring(4,6) + "/" + hinExp.substring(6,8));
var date = new Date();
var hinExpDate = new Date(hinExp.substring(0,4) + "/" + hinExp.substring(4,6) + "/" + hinExp.substring(6, 8));
if (hinExpDate <= new Date()) {
jQuery(window).find("#_hc_layout_valid_to").addClass("_hc_mismatch");
jQuery(window).find("#_hc_errors").append("<div class='_hc_error'>This health card has expired.</div>");
}
jQuery("input[name='end_date_year']").val(hinExp.substring(0,4));
jQuery("input[name='end_date_month']").val(hinExp.substring(4,6));
jQuery("input[name='end_date_date']").val(hinExp.substring(6,8));
} else {
jQuery(window).find("#_hc_layout_valid_to").text("No Expiry");
jQuery("input[name='end_date_year']").val("");
jQuery("input[name='end_date_month']").val("");
jQuery("input[name='end_date_date']").val("");
}
// Add all of these values to the correct fields on the page
jQuery("input[name='keyword']").val("");
jQuery("select[name='hc_type']").val("ON");
if (jQuery("select[name='hc_type']").val() != "ON"){
jQuery("input[name='hc_type']").css({'background-color' : 'yellow'});
jQuery("input[name='hc_type']").val("ON");
}
if (jQuery("input[name='last_name']").val() != args["lastName"]){
jQuery("input[name='last_name']").css({'background-color' : 'yellow'});
jQuery("input[name='last_name']").val(args["lastName"]);
}
if (jQuery("input[name='first_name']").val() != args["firstName"]){
jQuery("input[name='first_name']").css({'background-color' : 'yellow'});
jQuery("input[name='first_name']").val(args["firstName"]);
}
if (jQuery("input[name='hin']").val() != args["hin"]){
jQuery("input[name='hin']").css({'background-color' : 'yellow'});
jQuery("input[name='hin']").val(args["hin"]);
}
if (jQuery("input[name='year_of_birth']").val() != args["dob"].substring(0,4)){
jQuery("input[name='year_of_birth']").css({'background-color' : 'yellow'});
jQuery("input[name='year_of_birth']").val(args["dob"].substring(0,4));
}
if (jQuery("input[name='month_of_birth']").val() != args["dob"].substring(4,6)){
jQuery("input[name='month_of_birth']").css({'background-color' : 'yellow'});
jQuery("input[name='month_of_birth']").val(args["dob"].substring(4,6));
}
if (jQuery("input[name='date_of_birth']").val() != args["dob"].substring(6,8)){
jQuery("input[name='date_of_birth']").css({'background-color' : 'yellow'});
jQuery("input[name='date_of_birth']").val(args["dob"].substring(6,8));
}
if (jQuery("input[name='ver']").val() != args["hinVer"]){
jQuery("input[name='ver']").css({'background-color' : 'yellow'});
jQuery("input[name='ver']").val(args["hinVer"]);
}
if (jQuery("input[name='sex']").val() != (args["sex"] == "1" ? "M" : (args["sex"] == "2" ? "F" : ""))){
jQuery("input[name='sex']").css({'background-color' : 'yellow'});
jQuery("input[name='sex']").val((args["sex"] == "1" ? "M" : (args["sex"] == "2" ? "F" : "")));
}
if (jQuery("input[name='eff_date_year']").val() != issueDate.substring(0,4)){
jQuery("input[name='eff_date_year']").css({'background-color' : 'yellow'});
jQuery("input[name='eff_date_year']").val(issueDate.substring(0,4));
}
if (jQuery("input[name='eff_date_year']").val() != issueDate.substring(0,4)){
jQuery("input[name='eff_date_year']").css({'background-color' : 'yellow'});
jQuery("input[name='eff_date_year']").val(issueDate.substring(0,4));
}
if (jQuery("input[name='eff_date_year']").val() != issueDate.substring(0,4)){
jQuery("input[name='eff_date_year']").css({'background-color' : 'yellow'});
jQuery("input[name='eff_date_year']").val(issueDate.substring(0,4));
}
showEdit();
_hc_windowTimeout = setTimeout(function() {
jQuery("#_hc_window").css("display", "none");
}, 3000);
}
jQuery(window).css("display", "block");
}
jQuery(document).ready(function() {
jQuery("#_hc_window #_hc_matchSearch img").attr("src", window.pageContext + "/images/DMSLoader.gif");
jQuery("#_hc_window #_hc_closeBtn").click(function() {
jQuery("#_hc_window").hide();
});
new HealthCardHandler(_hc_newDemographicHandler);
});
| vvanherk/oscar_emr | src/main/webapp/hcHandler/hcHandlerUpdateDemographic.js | JavaScript | gpl-2.0 | 7,508 |
'use strict';
angular.module('wordclashApp').controller('LoginCtrl', ['$scope', '$location', 'authService', 'ngAuthSettings', function ($scope, $location, authService, ngAuthSettings) {
$scope.loginData = {
userName: "",
password: "",
useRefreshTokens: false
};
$scope.message = "";
$scope.clicked = false;
$scope.login = function () {
$scope.clicked = true;
authService.login($scope.loginData).then(function (response) {
$scope.clicked = false;
$location.path('/arena');
},
function (err) {
$scope.clicked = false;
$scope.message = err.error_description;
});
};
$scope.authExternalProvider = function (provider) {
var redirectUri = location.protocol + '//' + location.host + '/authcomplete.html';
var externalProviderUrl = ngAuthSettings.apiServiceBaseUri + "api/Account/ExternalLogin?provider=" + provider
+ "&response_type=token&client_id=" + ngAuthSettings.clientId
+ "&redirect_uri=" + redirectUri;
window.$windowScope = $scope;
var oauthWindow = window.open(externalProviderUrl, "Authenticate Account", "location=0,status=0,width=600,height=750");
};
$scope.authCompletedCB = function (fragment) {
$scope.$apply(function () {
if (fragment.haslocalaccount == 'False') {
authService.logOut();
authService.externalAuthData = {
provider: fragment.provider,
userName: fragment.external_user_name,
externalAccessToken: fragment.external_access_token
};
$location.path('/associate');
}
else {
//Obtain access token and redirect to orders
var externalData = { provider: fragment.provider, externalAccessToken: fragment.external_access_token };
authService.obtainAccessToken(externalData).then(function (response) {
$location.path('/arena');
},
function (err) {
$scope.message = err.error_description;
});
}
});
}
}]); | PascalS86/wordclash | wordclash/app/login/login.controller.js | JavaScript | gpl-2.0 | 2,373 |
import has from 'lodash/has';
import trim from 'lodash/trim';
import currencyFormatter from 'currency-formatter';
import { hasCurrencyCode } from '../utils/utils-settings';
import { maybeTrimHTML } from '../utils/utils-common';
import { getMoneyFormat, getShop } from '../ws/ws-shop';
import { showingLocalCurrency, getLocalCurrencyCodeCache, showingCurrencyCode } from './pricing-currency';
import { convertToLocalCurrency } from './pricing-conversion';
function priceSymbolMarkup(symbol) {
return '<span class="wps-product-price-currency" itemprop="priceCurrency">' + symbol + '</span>';
}
function priceAmountMarkup(amount) {
return '<span itemprop="price" class="wps-product-individual-price">' + amount + '</span>';
}
function priceMarkup(parts, amount) {
var priceMarkup = parts.map( ({type, value}) => {
switch (type) {
case 'currency': return priceSymbolMarkup(value) + priceAmountMarkup(amount);
default : return value;
}
});
return priceMarkup[0];
}
/*
locale currently not used
Config: {
locale: 'en-US',
countryCode: 'US',
amount: 123,
}
*/
function formatPrice(config) {
// Uses the browser locale by default
if ( !has(config, 'locale') ) {
config.locale = false;
}
var parts = new Intl.NumberFormat(config.locale, {
style: 'currency',
currency: config.countryCode,
currencyDisplay: config.currencyDisplay
}).formatToParts(config.amount);
return priceMarkup(parts, config.amount);
}
/*
"price" should always be preformatted
*/
function formatPriceToLocalCurrency(price) {
return formatPrice({
countryCode: getLocalCurrencyCodeCache(),
amount: price,
currencyDisplay: showingCurrencyCode() ? 'code' : 'symbol'
});
}
function formatPriceFromBase(price) {
return formatTotalAmount(price, maybeTrimHTML( getMoneyFormat( getShop() ) ) );
}
/*
Format product price into format from Shopify
*/
function maybeFormatPriceToLocalCurrency(price) {
if ( showingLocalCurrency() ) {
return formatPriceToLocalCurrency(price);
}
return formatPriceFromBase(price);
}
/*
Comes from Shopify
*/
function maybeAddCurrencyCodeToMoney(formatWithRealAmount) {
if ( hasCurrencyCode() ) {
return formatWithRealAmount + ' ' + getShop().currencyCode;
}
return formatWithRealAmount;
}
/*
Extract Money Format Type
*/
function extractMoneyFormatType(format) {
if (format) {
var newFormat = format;
newFormat = newFormat.split('{{').pop().split('}}').shift();
return newFormat.replace(/\s+/g, " ").trim();
} else {
return false;
}
}
/*
Formats the total amount
*/
function formatTotalAmount(amount, moneyFormat) {
var extractedMoneyFormat = extractMoneyFormatType(moneyFormat);
var formattedMoney = formatMoneyPerSetting(amount, extractedMoneyFormat, moneyFormat);
var formatWithRealAmount = replaceMoneyFormatWithRealAmount(formattedMoney, extractedMoneyFormat, moneyFormat);
formatWithRealAmount = formatWithRealAmount.replace(/ /g,'');
return maybeAddCurrencyCodeToMoney(formatWithRealAmount);
}
/*
Replace money format with real amount
*/
function replaceMoneyFormatWithRealAmount(formattedMoney, extractedMoneyFormat, moneyFormat = '') {
if (moneyFormat) {
var extractedMoneyFormat = new RegExp(extractedMoneyFormat, "g");
var finalPrice = trim(moneyFormat).replace(extractedMoneyFormat, formattedMoney);
finalPrice = finalPrice.replace(/{{/g, '');
finalPrice = finalPrice.replace(/}}/g, '');
return finalPrice;
}
}
/*
Format Money per settings
*/
function formatMoneyPerSetting(amount, format, origFormat) {
if (format === 'amount') {
var string = currencyFormatter.format(amount, {
symbol: '',
decimal: '.',
thousand: ',',
precision: 2,
format: '%v'
});
} else if (format === 'amount_no_decimals') {
amount = Number(amount);
amount = Math.round(amount);
var string = currencyFormatter.format(amount, {
symbol: '',
decimal: '.',
thousand: ',',
precision: 0,
format: '%v'
});
} else if (format === 'amount_with_comma_separator') {
var string = currencyFormatter.format(amount, {
symbol: '',
decimal: ',',
thousand: ',',
precision: 2,
format: '%v'
});
} else if (format === 'amount_no_decimals_with_comma_separator') {
amount = Number(amount);
amount = Math.round(amount);
var string = currencyFormatter.format(amount, {
symbol: '',
decimal: ',',
thousand: ',',
precision: 0,
format: '%v'
});
} else if (format === 'amount_with_space_separator') {
var string = currencyFormatter.format(amount, {
symbol: '',
decimal: ',',
thousand: ' ',
precision: 2,
format: '%v'
});
} else if (format === 'amount_no_decimals_with_space_separator') {
amount = Number(amount);
amount = Math.round(amount);
var string = currencyFormatter.format(amount, {
symbol: '',
decimal: ',',
thousand: ' ',
precision: 0,
format: '%v'
});
} else if (format === 'amount_with_apostrophe_separator') {
var string = currencyFormatter.format(amount, {
symbol: '',
decimal: '.',
thousand: '\'',
precision: 2,
format: '%v'
});
} else {
var string = currencyFormatter.format(amount, {
symbol: '',
decimal: '.',
thousand: ',',
precision: 2,
format: '%v'
});
}
return string;
}
export {
formatPrice,
maybeFormatPriceToLocalCurrency
}
| arobbins/wp-shopify | public/js/app/pricing/pricing-format.js | JavaScript | gpl-2.0 | 5,602 |
var AbstractExtendedActivityDataModifier = Fiber.extend(function(base) {
return {
content: '',
isAuthorOfViewedActivity: null,
dataViews: [],
summaryGrid: null,
init: function(analysisData, appResources, userSettings, athleteId, athleteIdAuthorOfActivity, basicInfos) {
this.analysisData_ = analysisData;
this.appResources_ = appResources;
this.userSettings_ = userSettings;
this.athleteId_ = athleteId;
this.athleteIdAuthorOfActivity_ = athleteIdAuthorOfActivity;
this.basicInfos = basicInfos;
this.isAuthorOfViewedActivity = (this.athleteIdAuthorOfActivity_ == this.athleteId_);
this.speedUnitsData = this.getSpeedUnitData();
this.setDataViewsNeeded();
},
modify: function() {
_.each(this.dataViews, function(view) {
// Append result of view.render() to this.content
view.render();
this.content += view.getContent();
}.bind(this));
},
placeSummaryPanel: function(panelAdded) {
this.makeSummaryGrid(2, 4);
this.insertContentSummaryGridContent();
$('.inline-stats.section').first().after(this.summaryGrid.html()).each(function() {
// Grid placed
if (panelAdded) panelAdded();
});
},
placeExtendedStatsButton: function(buttonAdded) {
var htmlButton = '<section>';
htmlButton += '<a class="button btn-block btn-primary" id="extendedStatsButton" href="#">';
htmlButton += 'Show extended statistics';
htmlButton += '</a>';
htmlButton += '</section>';
$('.inline-stats.section').first().after(htmlButton).each(function() {
$('#extendedStatsButton').click(function() {
$.fancybox({
'width': '100%',
'height': '100%',
'autoScale': true,
'transitionIn': 'fade',
'transitionOut': 'fade',
'type': 'iframe',
'content': '<div class="stravistiXExtendedData">' + this.content + '</div>'
});
// For each view start making the assossiated graphs
_.each(this.dataViews, function(view) {
view.displayGraph();
}.bind(this));
}.bind(this));
if (buttonAdded) buttonAdded();
}.bind(this));
},
makeSummaryGrid: function(columns, rows) {
var summaryGrid = '';
summaryGrid += '<div>';
summaryGrid += '<div class="summaryGrid">';
summaryGrid += '<table>';
for (var i = 0; i < rows; i++) {
summaryGrid += '<tr>';
for (var j = 0; j < columns; j++) {
summaryGrid += '<td data-column="' + j + '" data-row="' + i + '">';
summaryGrid += '</td>';
}
summaryGrid += '</tr>';
}
summaryGrid += '</table>';
summaryGrid += '</div>';
summaryGrid += '</div>';
this.summaryGrid = $(summaryGrid);
},
insertContentAtGridPosition: function(columnId, rowId, data, title, units, userSettingKey) {
var onClickHtmlBehaviour = "onclick='javascript:window.open(\"" + this.appResources_.settingsLink + "#/commonSettings?viewOptionHelperId=" + userSettingKey + "\",\"_blank\");'";
if (this.summaryGrid) {
var content = '<span class="summaryGridDataContainer" ' + onClickHtmlBehaviour + '>' + data + ' <span class="summaryGridUnits">' + units + '</span><br /><span class="summaryGridTitle">' + title + '</span></span>';
this.summaryGrid.find('[data-column=' + columnId + '][data-row=' + rowId + ']').html(content);
} else {
console.error('Grid is not initialized');
}
},
insertContentSummaryGridContent: function() {
// Insert summary data
var moveRatio = '-';
if (this.analysisData_.moveRatio && this.userSettings_.displayActivityRatio) {
moveRatio = this.analysisData_.moveRatio.toFixed(2);
}
this.insertContentAtGridPosition(0, 0, moveRatio, 'Move Ratio', '', 'displayActivityRatio');
// ...
var TRIMP = activityHeartRateReserve = '-';
var activityHeartRateReserveUnit = '%';
if (this.analysisData_.heartRateData && this.userSettings_.displayAdvancedHrData) {
TRIMP = this.analysisData_.heartRateData.TRIMP.toFixed(0) + ' <span class="summarySubGridTitle">(' + this.analysisData_.heartRateData.TRIMPPerHour.toFixed(0) + ' / hour)</span>';
activityHeartRateReserve = this.analysisData_.heartRateData.activityHeartRateReserve.toFixed(0);
activityHeartRateReserveUnit = '% <span class="summarySubGridTitle">(Max: ' + this.analysisData_.heartRateData.activityHeartRateReserveMax.toFixed(0) + '% @ ' + this.analysisData_.heartRateData.maxHeartRate + 'bpm)</span>';
}
this.insertContentAtGridPosition(0, 1, TRIMP, 'TRaining IMPulse', '', 'displayAdvancedHrData');
this.insertContentAtGridPosition(1, 1, activityHeartRateReserve, 'Heart Rate Reserve Avg', activityHeartRateReserveUnit, 'displayAdvancedHrData');
// ...
var climbTime = '-';
var climbTimeExtra = '';
if (this.analysisData_.gradeData && this.userSettings_.displayAdvancedGradeData) {
climbTime = Helper.secondsToHHMMSS(this.analysisData_.gradeData.upFlatDownInSeconds.up);
climbTimeExtra = '<span class="summarySubGridTitle">(' + (this.analysisData_.gradeData.upFlatDownInSeconds.up / this.analysisData_.gradeData.upFlatDownInSeconds.total * 100).toFixed(0) + '% of time)</span>';
}
this.insertContentAtGridPosition(0, 2, climbTime, 'Time climbing', climbTimeExtra, 'displayAdvancedGradeData');
},
/**
* Affect default view needed
*/
setDataViewsNeeded: function() {
// By default we have... If data exist of course...
// Featured view
if (this.analysisData_) {
var featuredDataView = new FeaturedDataView(this.analysisData_, this.userSettings_, this.basicInfos);
featuredDataView.setAppResources(this.appResources_);
featuredDataView.setIsAuthorOfViewedActivity(this.isAuthorOfViewedActivity);
this.dataViews.push(featuredDataView);
}
// Heart view
if (this.analysisData_.heartRateData && this.userSettings_.displayAdvancedHrData) {
var heartRateDataView = new HeartRateDataView(this.analysisData_.heartRateData, 'hrr', this.userSettings_);
heartRateDataView.setAppResources(this.appResources_);
heartRateDataView.setIsAuthorOfViewedActivity(this.isAuthorOfViewedActivity);
this.dataViews.push(heartRateDataView);
}
},
getSpeedUnitData: function() {
var measurementPreference = currentAthlete.get('measurement_preference');
var units = (measurementPreference == 'meters') ? 'km' : 'mi';
var speedUnitPerhour = (measurementPreference == 'meters') ? 'km/h' : 'mi/h';
var speedUnitFactor = (speedUnitPerhour == 'km/h') ? 1 : 0.62137;
return [speedUnitPerhour, speedUnitFactor, units];
},
}
});
| nishanttotla/stravistix | hook/extension/js/modifiers/extendedActivityData/AbstractExtendedActivityDataModifier.js | JavaScript | gpl-2.0 | 7,842 |
/**
* grunt/pipeline.js
*
* The order in which your css, javascript, and template files should be
* compiled and linked from your views and static HTML files.
*
* (Note that you can take advantage of Grunt-style wildcard/glob/splat expressions
* for matching multiple files, and the ! prefix for excluding files.)
*/
// Path to public folder
var tmpPath = '.tmp/public/';
// CSS files to inject in order
//
// (if you're using LESS with the built-in default config, you'll want
// to change `assets/styles/importer.less` instead.)
var cssFilesToInject = [
'styles/bootstrap.min.css',
'styles/bootstrap-theme.css'
];
// Client-side javascript files to inject in order
// (uses Grunt-style wildcard/glob/splat expressions)
var jsFilesToInject = [
// Load sails.io before everything else
'js/dependencies/sails.io.js',
'js/dependencies/angular.js',
'js/dependencies/angular-translate.min.js',
'js/dependencies/jquery.min.js',
'js/dependencies/bootstrap.min.js',
'js/dependencies/ui-bootstrap.min.js',
'js/dependencies/ui-bootstrap-tpls.min.js',
'js/dependencies/angular-translate.min.js',
'js/dependencies/smart-table.min.js',
'js/app.js'
// Dependencies like jQuery, or Angular are brought in here
// All of the rest of your client-side js files
// will be injected here in no particular order.
// Use the "exclude" operator to ignore files
// '!js/ignore/these/files/*.js'
];
// Client-side HTML templates are injected using the sources below
// The ordering of these templates shouldn't matter.
// (uses Grunt-style wildcard/glob/splat expressions)
//
// By default, Sails uses JST templates and precompiles them into
// functions for you. If you want to use jade, handlebars, dust, etc.,
// with the linker, no problem-- you'll just want to make sure the precompiled
// templates get spit out to the same file. Be sure and check out `tasks/README.md`
// for information on customizing and installing new tasks.
var templateFilesToInject = [
'templates/**/*.html'
];
// Prefix relative paths to source files so they point to the proper locations
// (i.e. where the other Grunt tasks spit them out, or in some cases, where
// they reside in the first place)
module.exports.cssFilesToInject = cssFilesToInject.map(transformPath);
module.exports.jsFilesToInject = jsFilesToInject.map(transformPath);
module.exports.templateFilesToInject = templateFilesToInject.map(transformPath);
// Transform paths relative to the "assets" folder to be relative to the public
// folder, preserving "exclude" operators.
function transformPath(path) {
return (path.substring(0,1) == '!') ? ('!' + tmpPath + path.substring(1)) : (tmpPath + path);
}
| libteiwm/FedShare | tasks/pipeline.js | JavaScript | gpl-2.0 | 2,692 |
angular.module('bhima.controllers')
.controller('ConfirmDonationController', ConfirmDonationController);
ConfirmDonationController.$inject = [
'$scope', '$q', '$http', 'validate', 'connect', '$location', 'uuid', 'SessionService'
];
function ConfirmDonationController($scope, $q, $http, validate, connect, $location, uuid, Session) {
var vm = this,
dependencies = {},
session = $scope.session = {};
dependencies.donations = {
query : {
identifier : 'uuid',
tables : {
donations : {columns : ['uuid', 'date', 'is_received', 'confirmed_by']},
donor : {columns : ['id', 'name']},
employee : {columns : ['prenom', 'name::nom_employee', 'postnom']}
},
join : ['donor.id=donations.donor_id', 'donations.employee_id=employee.id'],
where : ['donations.is_received=1', 'AND', 'donations.is_confirmed=0']
}
};
$scope.project = Session.project;
$scope.user = Session.user;
function initialise(model) {
angular.extend($scope, model);
}
function confirmDonation(donationId) {
session.selected = $scope.donations.get(donationId);
loadDetails(donationId);
}
function loadDetails(donationId) {
dependencies.donationDetails = {
query : {
identifier : 'inventory_uuid',
tables : {
donations : {columns : ['uuid', 'donor_id', 'employee_id', 'date', 'is_received']},
donation_item : {columns : ['uuid::donationItemUuid']},
stock : {columns : ['inventory_uuid', 'tracking_number', 'purchase_order_uuid', 'quantity::stockQuantity', 'lot_number', 'entry_date']},
purchase : {columns : ['uuid::purchaseUuid', 'cost', 'currency_id', 'note']},
purchase_item : {columns : ['uuid::purchaseItemUuid', 'unit_price', 'quantity']}
},
join : [
'donations.uuid=donation_item.donation_uuid',
'donation_item.tracking_number=stock.tracking_number',
'stock.purchase_order_uuid=purchase.uuid',
'stock.inventory_uuid=purchase_item.inventory_uuid',
'purchase.uuid=purchase_item.purchase_uuid',
],
where : ['donations.uuid=' + donationId]
}
};
validate.refresh(dependencies, ['donationDetails'])
.then(initialise);
}
function confirmReception() {
writeToJournal()
.then(updateDonation)
.then(generateDocument)
.then(resetSelected)
.catch(handleError);
}
function updatePurchase () {
var purchase = {
uuid : session.selected.uuid,
confirmed : 1,
confirmed_by : $scope.user.id,
paid : 1
};
return connect.put('purchase', [purchase], ['uuid']);
}
function updateDonation () {
var donation = {
uuid : session.selected.uuid,
is_confirmed : 1,
confirmed_by : $scope.user.id
};
return connect.put('donations', [donation], ['uuid']);
}
function writeToJournal() {
var document_id = uuid();
var synthese = [];
// Distinct inventory
var unique = {};
var distinctInventory = [];
$scope.donationDetails.data.forEach(function (x) {
if (!unique[x.inventory_uuid]) {
distinctInventory.push(x);
unique[x.inventory_uuid] = true;
}
});
// End Distinct inventory
// Grouping by lot
var inventoryByLot = [];
distinctInventory.forEach(function (x) {
var lot = [];
lot = $scope.donationDetails.data.filter(function (item) {
return item.inventory_uuid === x.inventory_uuid;
});
inventoryByLot.push({
inventory_uuid : x.inventory_uuid,
purchase_price : x.unit_price,
currency_id : x.currency_id,
quantity : x.quantity,
lots : lot
});
});
// End Grouping by lot
inventoryByLot.forEach(function (item) {
var donation = { uuid : item.lots[0].uuid },
inventory_lots = [];
item.lots.forEach(function (lot) {
inventory_lots.push(lot.tracking_number);
});
synthese.push({
movement : { document_id : document_id },
inventory_uuid : item.inventory_uuid,
donation : donation,
tracking_numbers : inventory_lots,
quantity : item.quantity,
purchase_price : item.purchase_price,
currency_id : item.currency_id,
project_id : $scope.project.id
});
});
return $q.all(synthese.map(function (postingEntry) {
// REM : Stock Account (3) in Debit and Donation Account (?) in credit
// OBJECTIF : Ecrire pour chaque inventory de la donation comme une transaction dans le journal
return $http.post('posting_donation/', postingEntry);
}));
}
function paymentSuccess(result) {
var purchase = {
uuid : session.selected.uuid,
paid : 1
};
return connect.put('purchase', [purchase], ['uuid']);
}
function generateDocument(res) {
$location.path('/invoice/confirm_donation/' + session.selected.uuid);
}
function handleError(error) {
console.log(error);
}
function resetSelected() {
session.selected = null;
validate.refresh(dependencies, ['donations'])
.then(initialise);
}
$scope.confirmDonation = confirmDonation;
$scope.confirmReception = confirmReception;
$scope.resetSelected = resetSelected;
// start the module up
validate.process(dependencies)
.then(initialise);
}
| IMA-WorldHealth/bhima-1.X | client/src/partials/stock/donation_management/confirm_donation.js | JavaScript | gpl-2.0 | 5,472 |
(function () {
'use strict';
var module = angular.module('memosWebApp', []);
}());
| tmorin/memos | app/scripts/modules/memosWebApp/module.js | JavaScript | gpl-2.0 | 95 |
// -*- mode: js; js-indent-level: 4; indent-tabs-mode: nil -*-
const Clutter = imports.gi.Clutter;
const Gio = imports.gi.Gio;
const GLib = imports.gi.GLib;
const GObject = imports.gi.GObject;
const Lang = imports.lang;
const Meta = imports.gi.Meta;
const Shell = imports.gi.Shell;
const Dialog = imports.ui.dialog;
const Main = imports.ui.main;
const Tweener = imports.ui.tweener;
var FROZEN_WINDOW_BRIGHTNESS = -0.3
var DIALOG_TRANSITION_TIME = 0.15
var ALIVE_TIMEOUT = 5000;
var CloseDialog = new Lang.Class({
Name: 'CloseDialog',
Extends: GObject.Object,
Implements: [ Meta.CloseDialog ],
Properties: {
'window': GObject.ParamSpec.override('window', Meta.CloseDialog)
},
_init(window) {
this.parent();
this._window = window;
this._dialog = null;
this._timeoutId = 0;
},
get window() {
return this._window;
},
set window(window) {
this._window = window;
},
_createDialogContent() {
let tracker = Shell.WindowTracker.get_default();
let windowApp = tracker.get_window_app(this._window);
/* Translators: %s is an application name */
let title = _("“%s” is not responding.").format(windowApp.get_name());
let subtitle = _("You may choose to wait a short while for it to " +
"continue or force the application to quit entirely.");
let icon = new Gio.ThemedIcon({ name: 'dialog-warning-symbolic' });
return new Dialog.MessageDialogContent({ icon, title, subtitle });
},
_initDialog() {
if (this._dialog)
return;
let windowActor = this._window.get_compositor_private();
this._dialog = new Dialog.Dialog(windowActor, 'close-dialog');
this._dialog.width = windowActor.width;
this._dialog.height = windowActor.height;
this._dialog.addContent(this._createDialogContent());
this._dialog.addButton({ label: _('Force Quit'),
action: this._onClose.bind(this),
default: true });
this._dialog.addButton({ label: _('Wait'),
action: this._onWait.bind(this),
key: Clutter.Escape });
global.focus_manager.add_group(this._dialog);
},
_addWindowEffect() {
// We set the effect on the surface actor, so the dialog itself
// (which is a child of the MetaWindowActor) does not get the
// effect applied itself.
let windowActor = this._window.get_compositor_private();
let surfaceActor = windowActor.get_first_child();
let effect = new Clutter.BrightnessContrastEffect();
effect.set_brightness(FROZEN_WINDOW_BRIGHTNESS);
surfaceActor.add_effect_with_name("gnome-shell-frozen-window", effect);
},
_removeWindowEffect() {
let windowActor = this._window.get_compositor_private();
let surfaceActor = windowActor.get_first_child();
surfaceActor.remove_effect_by_name("gnome-shell-frozen-window");
},
_onWait() {
this.response(Meta.CloseDialogResponse.WAIT);
},
_onClose() {
this.response(Meta.CloseDialogResponse.FORCE_CLOSE);
},
vfunc_show() {
if (this._dialog != null)
return;
Meta.disable_unredirect_for_display(global.display);
this._timeoutId = GLib.timeout_add(GLib.PRIORITY_DEFAULT, ALIVE_TIMEOUT,
() => {
this._window.check_alive(global.display.get_current_time_roundtrip());
return GLib.SOURCE_CONTINUE;
});
this._addWindowEffect();
this._initDialog();
this._dialog.scale_y = 0;
this._dialog.set_pivot_point(0.5, 0.5);
Tweener.addTween(this._dialog,
{ scale_y: 1,
transition: 'linear',
time: DIALOG_TRANSITION_TIME,
onComplete: () => {
Main.layoutManager.trackChrome(this._dialog, { affectsInputRegion: true });
}
});
},
vfunc_hide() {
if (this._dialog == null)
return;
Meta.enable_unredirect_for_display(global.display);
GLib.source_remove(this._timeoutId);
this._timeoutId = 0;
let dialog = this._dialog;
this._dialog = null;
this._removeWindowEffect();
Tweener.addTween(dialog,
{ scale_y: 0,
transition: 'linear',
time: DIALOG_TRANSITION_TIME,
onComplete: () => {
dialog.destroy();
}
});
},
vfunc_focus() {
if (this._dialog)
this._dialog.grab_key_focus();
}
});
| halfline/gnome-shell | js/ui/closeDialog.js | JavaScript | gpl-2.0 | 4,964 |
/* profiler-plugin.js is part of Aloha Editor project http://aloha-editor.org
*
* Aloha Editor is a WYSIWYG HTML5 inline editing library and editor.
* Copyright (c) 2010-2012 Gentics Software GmbH, Vienna, Austria.
* Contributors http://aloha-editor.org/contribution.php
*
* Aloha Editor 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 any later version.
*
* Aloha Editor is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
* As an additional permission to the GNU GPL version 2, you may distribute
* non-source (e.g., minimized or compacted) forms of the Aloha-Editor
* source code without the copy of the GNU GPL normally required,
* provided you include this license notice and a URL through which
* recipients can access the Corresponding Source.
*/
/* Aloha Profiler
* --------------
* Provides a useful interface to profile some of Aloha components and their
* methods.
*
* Potentially process intensive methods:
* Aloha.Profiler.profileAlohaComponent('Markup.preProcessKeyStrokes')
* Aloha.Profiler.profileAlohaComponent('Selection._updateSelection')
*/
window.define( [
'aloha/core',
'aloha/plugin',
'aloha/editable',
// 'aloha/sidebar',
'aloha/selection',
'aloha/markup',
'aloha/contenthandlermanager',
'aloha/floatingmenu',
'aloha/console',
'css!profiler/css/profiler'
], function( Aloha, Plugin, /* Sidebar */ Editable, Selection, Markup,
ContentHandlerManager, FloatingMenu, console ) {
// 'caller', 'callee', and 'arguments' properties may not be accessed on
// strict mode functions or the arguments objects for calls to them
//
var jQuery = Aloha.jQuery,
profiledFunctions = [],
// get the arguments string literal of this function, and split it into
// an array of names
argsStr = ( /function[^\(]*\(([^\)]+)/g ).exec( arguments.callee.toString() ),
argNames = argsStr ? argsStr[1].replace( /^\s+|\s+$/g, '' ).split( /\,\s*/ ) : [],
args = Array.prototype.slice.call( arguments );
/**
* @param {String} path dot seperated path to resolve inside a given object
* or browser window
* @param {?Object} object inwhich to resolve a path. If no object is
* passed, the browser window object will be used instead
* @return {?} Object
*/
function resolvePath(path, obj) {
if ( typeof path !== 'string' ) {
return path;
}
if ( !obj || typeof obj !== 'object' ) {
obj = window;
}
var parts = path.split( '.' ),
i = 0,
j = parts.length;
for ( ; i < j; ++i ) {
obj = obj[ parts[ i ] ];
if ( typeof obj === 'undefined' ) {
console.error(
'Aloha.Profiler',
'Property "' + parts[ i ] + '" does not exist' +
( i ? ' in object ' + parts.slice( 0, i ).join( '.' ) : '' )
);
return null;
}
}
return obj;
};
function parseObjectPath( path, obj ) {
if ( typeof path !== 'string' ) {
return null;
}
var parts = path.split( '.' ),
pathToProp = parts.slice( 0, Math.max( 1, parts.length - 1 ) ).join( '.' ),
prop;
obj = resolvePath( pathToProp, obj );
if ( !obj ) {
return null;
}
if ( parts.length > 1 ) {
var lastProp = parts[ parts.length - 1 ];
if ( typeof obj[ lastProp ] === 'undefined' ) {
console.error( 'Aloha.Profiler',
'Property "' + lastProp + '" does not exist in object ' +
pathToProp );
} else {
prop = lastProp;
}
}
return {
obj : obj[ prop ],
path : path,
parentObj : obj,
propName : prop
};
};
var panel;
function initSidebarPanel(sidebar) {
sidebar.addPanel( {
id : 'aloha-devtool-profiler-panel',
title : 'Aloha Profiler',
expanded : true,
activeOn : true,
content : '' +
'<div id="aloha-devtool-profiler-container">' +
'<input id="aloha-devtool-profiler-input" ' +
'value="Aloha.Profiler.profileAlohaComponent(\'Markup.preProcessKeyStrokes\')" />' +
'<ul id="aloha-devtool-profiler-console"></ul>' +
'</div>',
onInit : function() {
this.content.find( 'input#aloha-devtool-profiler-input' ).keydown( function( event ) {
// Handle ENTER
if ( event.keyCode === 13 ) {
var input = jQuery( this );
var value = input.val();
if ( value ) {
eval( value );
PanelConsole.log( value );
input.val( '' );
}
}
} );
}
} );
sidebar.show().open();
};
var PanelConsole = {
log: function() {
jQuery( '#aloha-devtool-profiler-console' )
.prepend( '<li>' +
Array.prototype.slice.call( arguments ).join( ' ' ) +
'</li>' );
}
}
Aloha.Profiler = Plugin.create( 'profiler', {
/**
* Explose all dependencies to allow easy access. eg:
* If the 5th dependency was Markup, then:
* Aloha.Profiler.profile(Aloha.Profiler.alohaObjects[4], 'preProcessKeyStrokes')
* would start profiling the Markup.preProcessKeyStrokes method.
*/
loadedDependencies: Array.prototype.slice.call( arguments ),
/**
* Provides a better interface to access various components of Aloha.
* eg: Aloha.Profiler.profile(Aloha.Profiler.alohaComponents[ 'Markup' ], 'preProcessKeyStrokes')
*/
alohaComponents: {},
panel: null,
/**
* Initializes Profiler plugin by populating alohaComponents with all
* arguments of our define function, mapping name, to object
*/
init: function() {
var j = argNames.length;
while ( --j >= 0 ) {
this.alohaComponents[ argNames[ j ] ] = args[ j ];
}
var that = this;
Aloha.ready( function() {
if ( Aloha.Sidebar && Aloha.Sidebar.right ) {
that.panel = initSidebarPanel( Aloha.Sidebar.right );
}
} );
},
log: function() {
PanelConsole.log.apply( PanelConsole, arguments );
},
/**
* Shortcut to profile one of the Aloha components that was required by
* Aloha Profiler.
*
* @param {String} path
* @param {String} fnName
*/
profileAlohaComponent: function( path, fnName ) {
var parts = parseObjectPath( path, this.alohaComponents );
return this.profile( parts.parentObj, fnName || parts.propName );
},
/**
* @param {(Object|String)} obj object or path to object that contains
* the function we want to profile. Or the path to the
* function itself
* @param {String} fnName name of function inside obj, which we want to
* profile
* @param {?Function(Function, Array):Boolean} intercept functiont to
* call each time this method is invoked
*/
profile: function( obj, fnName, intercept ) {
var path,
parts,
objIndex = -1,
i;
if ( typeof obj === 'string' ) {
parts = parseObjectPath( obj );
obj = parts.parentObj;
path = parts.path + ( fnName ? '.' + fnName : '' );
if ( parts.propName ) {
if ( typeof parts.obj === 'function' ) {
fnName = parts.propName;
} else if ( parts.obj === 'object' ) {
obj = parts.obj;
}
}
}
if ( !obj || !fnName || typeof obj[ fnName ] !== 'function' ) {
return;
}
for ( i = 0; i < profiledFunctions.length; ++i ) {
if ( profiledFunctions[ i ] === obj ) {
objIndex = i;
if ( profiledFunctions[ i ][ fnName ] ) {
return;
}
}
}
var fn = obj[ fnName ];
var that = this;
// In IE typeof window.console.log returns "object!!!"
if ( window.console && window.console.log ) {
if ( objIndex === -1 ) {
objIndex = profiledFunctions.push( obj ) - 1;
}
profiledFunctions[ objIndex ][ fnName ] = fn;
obj[ fnName ] = function() {
if ( typeof intercept === 'function' ) {
intercept( fn, arguments );
}
// window.console.time( fnName );
var start = +( new Date() );
var returnValue = fn.apply( obj, arguments );
// window.console.timeEnd( fnName );
that.log( ( path || fnName ) + ': ' +
( ( new Date() ) - start ) + 'ms' );
return returnValue;
};
}
},
/**
* @return {String} "Aloha.Profiler"
*/
toString: function() {
return 'Aloha.Profiler';
}
} );
return Aloha.Profiler;
} );
| bitcodes/pinecones | sites/all/libraries/aloha/aloha/plugins/extra/profiler/lib/profiler-plugin.js | JavaScript | gpl-2.0 | 8,987 |
jQuery.noConflict();
jQuery(document).ready(function(){
/**
* This will remove username/password text in the login form fields
**/
jQuery('.username, .password').focusout(function(){
if(jQuery(this).val() != '') {
jQuery(this).css({backgroundPosition: "0 -32px"});
} else {
jQuery(this).css({backgroundPosition: "0 0"});
}
});
jQuery('.username, .password').focusin(function(){
if(jQuery(this).val() == '') {
jQuery(this).css({backgroundPosition: "0 -32px"});
}
});
/**
* Message Notify Drop Down
**/
jQuery('.messagenotify .wrap, .alertnotify .wrap').click(function(){
var t = jQuery(this).parent();
var url = t.attr('href');
if(t.hasClass('showmsg')) {
t.removeClass('showmsg');
t.find('.thicon').removeClass('thiconhover');
t.parent().find('.dropbox').remove();
} else {
jQuery('.topheader li').each(function(){
jQuery(this).find('.showmsg').removeClass('showmsg');
jQuery(this).find('.thicon').removeClass('thiconhover');
jQuery(this).find('.dropbox').remove();
});
t.addClass('showmsg');
t.find('.thicon').addClass('thiconhover');
t.parent().append('<div class="dropbox"></div>');
jQuery.post(url,function(data){
jQuery('.dropbox').append(data);
});
}
return false;
});
jQuery(document).click(function(event) {
var msglist = jQuery('.dropbox');
if(!jQuery(event.target).is('.dropbox')) {
if(msglist.is(":visible")) {
msglist.prev().removeClass('showmsg');
msglist.prev().find('.thicon').removeClass('thiconhover');
msglist.remove();
}
}
});
/**
* Login form validation
**/
jQuery('#loginform').submit(function(){
var username = jQuery('.username').val();
var password = jQuery('.password').val();
if(username == '' && password == '') {
jQuery('.loginNotify').slideDown('fast');
return false;
} else {
return true;
}
});
/**
* Sidebar accordion
**/
jQuery('#accordion h3').click(function() {
if(jQuery(this).hasClass('open')) {
jQuery(this).removeClass('open');
jQuery(this).next().slideUp('fast');
} else {
jQuery(this).addClass('open');
jQuery(this).next().slideDown('fast');
} return false;
});
/**
* Widget Box Toggle
**/
jQuery('.widgetbox h3, .widgetbox2 h3').hover(function(){
jQuery(this).addClass('arrow');
return false;
},function(){
jQuery(this).removeClass('arrow');
return false;
});
jQuery('.widgetbox h3, .widgetbox2 h3').toggle(function(){
jQuery(this).next().slideUp('fast');
jQuery(this).css({MozBorderRadius: '3px',
WebkitBorderRadius: '3px',
borderRadius: '3px'});
return false;
},function(){
jQuery(this).next().slideDown('fast');
jQuery(this).css({MozBorderRadius: '3px 3px 0 0',
WebkitBorderRadius: '3px 3px 0 0',
borderRadius: '3px 3px 0 0'});
return false;
});
/**
* Notification
**/
jQuery('.notification .close').click(function(){
jQuery(this).parent().fadeOut();
});
/** Make footer always at the bottom**/
if(jQuery('body').height() > jQuery(window).height()) {
jQuery('.footer').removeClass('footer_float');
}
/**DROP DOWN MENU**/
jQuery(".subnav").css({display: "none"}); // Opera Fix
jQuery(".tabmenu li").hover(function(){
jQuery(this).find('ul:first').css({visibility: "visible",display: "none"}).show(400);
},function(){
jQuery(this).find('ul:first').css({visibility: "hidden"});
});
}); | berryjace/www | crm/assets/docs/theme/template/js/custom/general.js | JavaScript | gpl-2.0 | 3,455 |
/**
* Plugin to add header resizing functionality to a HeaderContainer.
* Always resizing header to the left of the splitter you are resizing.
*/
Ext.define('Ext.grid.plugin.HeaderResizer', {
extend: 'Ext.plugin.Abstract',
requires: [
'Ext.dd.DragTracker',
'Ext.util.Region'
],
alias: 'plugin.gridheaderresizer',
disabled: false,
config: {
/**
* @cfg {Boolean} dynamic
* True to resize on the fly rather than using a proxy marker.
* @accessor
*/
dynamic: false
},
colHeaderCls: Ext.baseCSSPrefix + 'column-header',
minColWidth: 40,
maxColWidth: 1000,
eResizeCursor: 'col-resize',
init: function(headerCt) {
var me = this;
me.headerCt = headerCt;
headerCt.on('render', me.afterHeaderRender, me, {single: me});
// Pull minColWidth from the minWidth in the Column prototype
if (!me.minColWidth) {
me.self.prototype.minColWidth = Ext.grid.column.Column.prototype.minWidth;
}
},
destroy: function() {
var tracker = this.tracker;
if (tracker) {
delete tracker.onBeforeStart;
delete tracker.onStart;
delete tracker.onDrag;
delete tracker.onEnd;
tracker.destroy();
this.tracker = null;
}
this.callParent();
},
afterHeaderRender: function() {
var me = this,
headerCt = me.headerCt,
el = headerCt.el;
headerCt.mon(el, 'mousemove', me.onHeaderCtMouseMove, me);
me.markerOwner = me.ownerGrid = me.headerCt.up('tablepanel');
if (me.markerOwner.ownerLockable) {
me.markerOwner = me.markerOwner.ownerLockable;
}
me.tracker = new Ext.dd.DragTracker({
disabled: me.disabled,
onBeforeStart: me.onBeforeStart.bind(me),
onStart: me.onStart.bind(me),
onDrag: me.onDrag.bind(me),
onEnd: me.onEnd.bind(me),
tolerance: 3,
autoStart: 300,
el: el
});
},
// As we mouse over individual headers, change the cursor to indicate
// that resizing is available, and cache the resize target header for use
// if/when they mousedown.
onHeaderCtMouseMove: function(e) {
var me = this;
if (me.headerCt.dragging || me.disabled) {
if (me.activeHd) {
me.activeHd.el.dom.style.cursor = '';
delete me.activeHd;
}
} else {
me.findActiveHeader(e);
}
},
findActiveHeader: function(e) {
var me = this,
headerEl = e.getTarget('.' + me.colHeaderCls, 3, true),
ownerGrid = me.ownerGrid,
ownerLockable = ownerGrid.ownerLockable,
overHeader, resizeHeader, headers, header;
if (headerEl) {
overHeader = Ext.getCmp(headerEl.id);
// If near the right edge, we're resizing the column we are over.
if (overHeader.isAtEndEdge(e)) {
// Cannot resize the only column in a forceFit grid.
if (me.headerCt.visibleColumnManager.getColumns().length === 1 && me.headerCt.forceFit) {
return;
}
resizeHeader = overHeader;
}
// Else... we might be near the right edge
else if (overHeader.isAtStartEdge(e)) {
// Extract previous visible leaf header
headers = me.headerCt.visibleColumnManager.getColumns();
header = overHeader.isGroupHeader ? overHeader.getGridColumns()[0] : overHeader;
resizeHeader = headers[Ext.Array.indexOf(headers, header) - 1];
// If there wasn't one, and we are the normal side of a lockable assembly then
// use the last visible leaf header of the locked side.
if (!resizeHeader && ownerLockable && !ownerGrid.isLocked) {
headers = ownerLockable.lockedGrid.headerCt.visibleColumnManager.getColumns();
resizeHeader = headers[headers.length - 1];
}
}
// We *are* resizing
if (resizeHeader) {
// If we're attempting to resize a group header, that cannot be resized,
// so find its last visible leaf header; Group headers are sized
// by the size of their child headers.
if (resizeHeader.isGroupHeader) {
headers = resizeHeader.getGridColumns();
resizeHeader = headers[headers.length - 1];
}
// Check if the header is resizable. Continue checking the old "fixed" property, bug also
// check whether the resizable property is set to false.
if (resizeHeader && !(resizeHeader.fixed || (resizeHeader.resizable === false))) {
me.activeHd = resizeHeader;
overHeader.el.dom.style.cursor = me.eResizeCursor;
if (overHeader.triggerEl) {
overHeader.triggerEl.dom.style.cursor = me.eResizeCursor;
}
}
// reset
} else {
overHeader.el.dom.style.cursor = '';
if (overHeader.triggerEl) {
overHeader.triggerEl.dom.style.cursor = '';
}
me.activeHd = null;
}
}
return me.activeHd;
},
// only start when there is an activeHd
onBeforeStart : function(e) {
var me = this;
// If on touch, we will have received no mouseover, so we have to
// decide whether the touch is in a resize zone, and if so, which header is to be sized.
// Cache any activeHd because it will be cleared on subsequent mousemoves outside the resize zone.
me.dragHd = Ext.supports.Touch ? me.findActiveHeader(e) : me.activeHd;
if (!!me.dragHd && !me.headerCt.dragging) {
// Calculate how far off the right marker line the mouse pointer is.
// This will be the xDelta during the following drag operation.
me.xDelta = me.dragHd.getX() + me.dragHd.getWidth() - me.tracker.getXY()[0];
me.tracker.constrainTo = me.getConstrainRegion();
return true;
} else {
me.headerCt.dragging = false;
return false;
}
},
// get the region to constrain to, takes into account max and min col widths
getConstrainRegion: function() {
var me = this,
dragHdEl = me.dragHd.el,
nextHd,
ownerGrid = me.ownerGrid,
widthModel = ownerGrid.getSizeModel().width,
maxColWidth = widthModel.shrinkWrap ? me.headerCt.getWidth() - me.headerCt.visibleColumnManager.getColumns().length * me.minColWidth : me.maxColWidth,
result;
// If forceFit, then right constraint is based upon not being able to force the next header
// beyond the minColWidth. If there is no next header, then the header may not be expanded.
if (me.headerCt.forceFit) {
nextHd = me.dragHd.nextNode('gridcolumn:not([hidden]):not([isGroupHeader])');
if (nextHd && me.headerInSameGrid(nextHd)) {
maxColWidth = dragHdEl.getWidth() + (nextHd.getWidth() - me.minColWidth);
}
}
// If resize header is in a locked grid, the maxWidth has to be 30px within the available locking grid's width
// But only if the locked grid shrinkwraps its columns
else if (ownerGrid.isLocked && widthModel.shrinkWrap) {
maxColWidth = me.dragHd.up('[scrollerOwner]').getTargetEl().getWidth(true) - ownerGrid.getWidth() - (ownerGrid.ownerLockable.normalGrid.visibleColumnManager.getColumns().length * me.minColWidth + Ext.getScrollbarSize().width);
}
result = me.adjustConstrainRegion(
dragHdEl.getRegion(),
0,
0,
0,
me.minColWidth
);
result.right = dragHdEl.getX() + maxColWidth;
return result;
},
// initialize the left and right hand side markers around
// the header that we are resizing
onStart: function(e) {
var me = this,
dragHd = me.dragHd,
width = dragHd.el.getWidth(),
headerCt = dragHd.getRootHeaderCt(),
x, y, markerOwner, lhsMarker, rhsMarker, markerHeight;
me.headerCt.dragging = true;
me.origWidth = width;
// setup marker proxies
if (!me.dynamic) {
markerOwner = me.markerOwner;
// https://sencha.jira.com/browse/EXTJSIV-11299
// In Neptune (and other themes with wide frame borders), resize handles are embedded in borders,
// *outside* of the outer element's content area, therefore the outer element is set to overflow:visible.
// During column resize, we should not see the resize markers outside the grid, so set to overflow:hidden.
if (markerOwner.frame && markerOwner.resizable) {
me.gridOverflowSetting = markerOwner.el.dom.style.overflow;
markerOwner.el.dom.style.overflow = 'hidden';
}
x = me.getLeftMarkerX(markerOwner);
lhsMarker = markerOwner.getLhsMarker();
rhsMarker = markerOwner.getRhsMarker();
markerHeight = me.ownerGrid.body.getHeight() + headerCt.getHeight();
y = headerCt.getOffsetsTo(markerOwner)[1] - markerOwner.el.getBorderWidth('t');
lhsMarker.setLocalY(y);
rhsMarker.setLocalY(y);
lhsMarker.setHeight(markerHeight);
rhsMarker.setHeight(markerHeight);
me.setMarkerX(lhsMarker, x);
me.setMarkerX(rhsMarker, x + width);
}
},
// synchronize the rhsMarker with the mouse movement
onDrag: function(e){
var me = this;
if (me.dynamic) {
me.doResize();
} else {
me.setMarkerX(me.getMovingMarker(me.markerOwner), me.calculateDragX(me.markerOwner));
}
},
getMovingMarker: function(markerOwner){
return markerOwner.getRhsMarker();
},
onEnd: function(e) {
var me = this,
markerOwner;
me.headerCt.dragging = false;
if (me.dragHd) {
if (!me.dynamic) {
markerOwner = me.headerCt.up('tablepanel');
// hide markers
if (markerOwner.ownerLockable) {
markerOwner = markerOwner.ownerLockable;
}
// If we had saved the gridOverflowSetting, restore it
if ('gridOverflowSetting' in me) {
markerOwner.el.dom.style.overflow = me.gridOverflowSetting;
}
me.setMarkerX(markerOwner.getLhsMarker(), -9999);
me.setMarkerX(markerOwner.getRhsMarker(), -9999);
}
me.doResize();
}
// If the mouse is still within the handleWidth, then we must be ready to drag again
me.onHeaderCtMouseMove(e);
},
doResize: function() {
var me = this,
dragHd = me.dragHd,
nextHd,
offset = me.tracker.getOffset('point');
// Only resize if we have dragged any distance in the X dimension...
if (dragHd && offset[0]) {
// resize the dragHd
if (dragHd.flex) {
delete dragHd.flex;
}
Ext.suspendLayouts();
// Set the new column width.
// Adjusted for the offset from the actual column border that the mousedownb too place at.
me.adjustColumnWidth(offset[0] - me.xDelta);
// In the case of forceFit, change the following Header width.
// Constraining so that neither neighbour can be sized to below minWidth is handled in getConstrainRegion
if (me.headerCt.forceFit) {
nextHd = dragHd.nextNode('gridcolumn:not([hidden]):not([isGroupHeader])');
if (nextHd && !me.headerInSameGrid(nextHd)) {
nextHd = null;
}
if (nextHd) {
delete nextHd.flex;
nextHd.setWidth(nextHd.getWidth() - offset[0]);
}
}
// Apply the two width changes by laying out the owning HeaderContainer
Ext.resumeLayouts(true);
}
},
// nextNode can traverse out of this grid, possibly to others on the page, so limit it here
headerInSameGrid: function(header) {
var grid = this.dragHd.up('tablepanel');
return !!header.up(grid);
},
disable: function() {
var tracker = this.tracker;
this.disabled = true;
if (tracker) {
tracker.disable();
}
},
enable: function() {
var tracker = this.tracker;
this.disabled = false;
if (tracker) {
tracker.enable();
}
},
calculateDragX: function(markerOwner) {
return this.tracker.getXY('point')[0] + this.xDelta - markerOwner.getX() - markerOwner.el.getBorderWidth('l');
},
getLeftMarkerX: function(markerOwner) {
return this.dragHd.getX() - markerOwner.getX() - markerOwner.el.getBorderWidth('l') - 1;
},
setMarkerX: function(marker, x) {
marker.setLocalX(x);
},
adjustConstrainRegion: function(region, t, r, b, l) {
return region.adjust(t, r, b, l);
},
adjustColumnWidth: function(offsetX) {
this.dragHd.setWidth(this.origWidth + offsetX);
}
});
| AlexeyPopovUA/Learning-ExtJS-6-Classes | ext/classic/classic/src/grid/plugin/HeaderResizer.js | JavaScript | gpl-2.0 | 13,965 |
(function ($) {
Drupal.behaviors.sbac_featured_content = {
attach: function (context, settings) {
// If JS is working, turn cursor into a pointer and redirect on click
$('.featured-content-inner').css( 'cursor', 'pointer' );
$('.featured-content-inner').click(function(){
window.location = '/' + $(this).attr('url');
});
}
};
})(jQuery); | SmarterApp/DigitalLibrary | docroot/sites/all/modules/custom/sbac_featured_content/js/sbac_featured_content.js | JavaScript | gpl-2.0 | 382 |
/* Publish module for wikiEditor */
( function ( $ ) {
$.wikiEditor.modules.publish = {
/**
* Compatability map
*/
browsers: {
// Left-to-right languages
ltr: {
msie: [['>=', 7]],
firefox: [['>=', 3]],
opera: [['>=', 9.6]],
safari: [['>=', 4]]
},
// Right-to-left languages
rtl: {
msie: [['>=', 8]],
firefox: [['>=', 3]],
opera: [['>=', 9.6]],
safari: [['>=', 4]]
}
},
/**
* Internally used functions
*/
fn: {
/**
* Creates a publish module within a wikiEditor
* @param context Context object of editor to create module in
* @param config Configuration object to create module from
*/
create: function ( context, config ) {
// Build the dialog behind the Publish button
var dialogID = 'wikiEditor-' + context.instance + '-dialog';
$.wikiEditor.modules.dialogs.fn.create(
context,
{
previewsave: {
id: dialogID,
titleMsg: 'wikieditor-publish-dialog-title',
html: '\
<div class="wikiEditor-publish-dialog-copywarn"></div>\
<div class="wikiEditor-publish-dialog-editoptions">\
<form id="wikieditor-' + context.instance + '-publish-dialog-form">\
<div class="wikiEditor-publish-dialog-summary">\
<label for="wikiEditor-' + context.instance + '-dialog-summary"\
rel="wikieditor-publish-dialog-summary"></label>\
<br />\
<input type="text" id="wikiEditor-' + context.instance + '-dialog-summary"\
style="width: 100%;" />\
</div>\
<div class="wikiEditor-publish-dialog-options">\
<input type="checkbox"\
id="wikiEditor-' + context.instance + '-dialog-minor" />\
<label for="wikiEditor-' + context.instance + '-dialog-minor"\
rel="wikieditor-publish-dialog-minor"></label>\
<input type="checkbox"\
id="wikiEditor-' + context.instance + '-dialog-watch" />\
<label for="wikiEditor-' + context.instance + '-dialog-watch"\
rel="wikieditor-publish-dialog-watch"></label>\
</div>\
</form>\
</div>',
init: function () {
var i;
$(this).find( '[rel]' ).each( function () {
$(this).text( mediaWiki.msg( $(this).attr( 'rel' ) ) );
});
/* REALLY DIRTY HACK! */
// Reformat the copyright warning stuff
var copyWarnHTML = $( '#editpage-copywarn p' ).html();
// TODO: internationalize by splitting on other characters that end statements
var copyWarnStatements = copyWarnHTML.split( '. ' );
var newCopyWarnHTML = '<ul>';
for ( i = 0; i < copyWarnStatements.length; i++ ) {
if ( copyWarnStatements[i] !== '' ) {
var copyWarnStatement = $.trim( copyWarnStatements[i] ).replace( /\.*$/, '' );
newCopyWarnHTML += '<li>' + copyWarnStatement + '.</li>';
}
}
newCopyWarnHTML += '</ul>';
// No list if there's only one element
$(this).find( '.wikiEditor-publish-dialog-copywarn' ).html(
copyWarnStatements.length > 1 ? newCopyWarnHTML : copyWarnHTML
);
/* END OF REALLY DIRTY HACK */
if ( $( '#wpMinoredit' ).length === 0 )
$( '#wikiEditor-' + context.instance + '-dialog-minor' ).hide();
else if ( $( '#wpMinoredit' ).is( ':checked' ) )
$( '#wikiEditor-' + context.instance + '-dialog-minor' )
.prop( 'checked', true );
if ( $( '#wpWatchthis' ).length === 0 )
$( '#wikiEditor-' + context.instance + '-dialog-watch' ).hide();
else if ( $( '#wpWatchthis' ).is( ':checked' ) )
$( '#wikiEditor-' + context.instance + '-dialog-watch' )
.prop( 'checked', true );
$(this).find( 'form' ).submit( function ( e ) {
$(this).closest( '.ui-dialog' ).find( 'button:first' ).click();
e.preventDefault();
});
},
dialog: {
buttons: {
'wikieditor-publish-dialog-publish': function () {
var minorChecked = $( '#wikiEditor-' + context.instance +
'-dialog-minor' ).is( ':checked' ) ?
'checked' : '';
var watchChecked = $( '#wikiEditor-' + context.instance +
'-dialog-watch' ).is( ':checked' ) ?
'checked' : '';
$( '#wpMinoredit' ).prop( 'checked', minorChecked );
$( '#wpWatchthis' ).prop( 'checked', watchChecked );
$( '#wpSummary' ).val( $( '#wikiEditor-' + context.instance +
'-dialog-summary' ).val() );
$( '#editform' ).submit();
},
'wikieditor-publish-dialog-goback': function () {
$(this).dialog( 'close' );
}
},
open: function () {
$( '#wikiEditor-' + context.instance + '-dialog-summary' ).focus();
},
width: 500
},
resizeme: false
}
}
);
context.fn.addButton( {
'captionMsg': 'wikieditor-publish-button-publish',
'action': function () {
$( '#' + dialogID ).dialog( 'open' );
return false;
}
} );
context.fn.addButton( {
'captionMsg': 'wikieditor-publish-button-cancel',
'action': function () { }
} );
}
}
};
}( jQuery ) );
| libis/schatkamer-mediawiki | extensions/WikiEditor/modules/jquery.wikiEditor.publish.js | JavaScript | gpl-2.0 | 5,169 |
/* global kirkiL10n */
var kirki = kirki || {};
kirki = jQuery.extend( kirki, {
/**
* An object containing definitions for input fields.
*
* @since 3.0.16
*/
input: {
/**
* Radio input fields.
*
* @since 3.0.17
*/
radio: {
/**
* Init the control.
*
* @since 3.0.17
* @param {Object} control - The control object.
* @param {Object} control.id - The setting.
* @returns {null}
*/
init: function( control ) {
var input = jQuery( 'input[data-id="' + control.id + '"]' );
// Save the value
input.on( 'change keyup paste click', function() {
kirki.setting.set( control.id, jQuery( this ).val() );
} );
}
},
/**
* Color input fields.
*
* @since 3.0.16
*/
color: {
/**
* Init the control.
*
* @since 3.0.16
* @param {Object} control - The control object.
* @param {Object} control.id - The setting.
* @param {Object} control.choices - Additional options for the colorpickers.
* @param {Object} control.params - Control parameters.
* @param {Object} control.params.choices - alias for control.choices.
* @returns {null}
*/
init: function( control ) {
var picker = jQuery( '.kirki-color-control[data-id="' + control.id + '"]' ),
clear;
control.choices = control.choices || {};
if ( _.isEmpty( control.choices ) && control.params.choices ) {
control.choices = control.params.choices;
}
// If we have defined any extra choices, make sure they are passed-on to Iris.
if ( ! _.isEmpty( control.choices ) ) {
picker.wpColorPicker( control.choices );
}
// Tweaks to make the "clear" buttons work.
setTimeout( function() {
clear = jQuery( '.kirki-input-container[data-id="' + control.id + '"] .wp-picker-clear' );
if ( clear.length ) {
clear.click( function() {
kirki.setting.set( control.id, '' );
} );
}
}, 200 );
// Saves our settings to the WP API
picker.wpColorPicker( {
change: function() {
// Small hack: the picker needs a small delay
setTimeout( function() {
kirki.setting.set( control.id, picker.val() );
}, 20 );
}
} );
}
},
/**
* Generic input fields.
*
* @since 3.0.17
*/
genericInput: {
/**
* Init the control.
*
* @since 3.0.17
* @param {Object} control - The control object.
* @param {Object} control.id - The setting.
* @returns {null}
*/
init: function( control ) {
var input = jQuery( 'input[data-id="' + control.id + '"]' );
// Save the value
input.on( 'change keyup paste click', function() {
kirki.setting.set( control.id, jQuery( this ).val() );
} );
}
},
/**
* Generic input fields.
*
* @since 3.0.17
*/
textarea: {
/**
* Init the control.
*
* @since 3.0.17
* @param {Object} control - The control object.
* @param {Object} control.id - The setting.
* @returns {null}
*/
init: function( control ) {
var textarea = jQuery( 'textarea[data-id="' + control.id + '"]' );
// Save the value
textarea.on( 'change keyup paste click', function() {
kirki.setting.set( control.id, jQuery( this ).val() );
} );
}
},
select: {
/**
* Init the control.
*
* @since 3.0.17
* @param {Object} control - The control object.
* @param {Object} control.id - The setting.
* @returns {null}
*/
init: function( control ) {
var element = jQuery( 'select[data-id="' + control.id + '"]' ),
multiple = parseInt( element.data( 'multiple' ), 10 ),
selectValue,
selectWooOptions = {
escapeMarkup: function( markup ) {
return markup;
}
};
if ( control.params.placeholder ) {
selectWooOptions.placeholder = control.params.placeholder;
selectWooOptions.allowClear = true;
}
if ( 1 < multiple ) {
selectWooOptions.maximumSelectionLength = multiple;
}
jQuery( element ).selectWoo( selectWooOptions ).on( 'change', function() {
selectValue = jQuery( this ).val();
selectValue = ( null === selectValue && 1 < multiple ) ? [] : selectValue;
kirki.setting.set( control.id, selectValue );
} );
}
},
/**
* Number fields.
*
* @since 3.0.26
*/
number: {
/**
* Init the control.
*
* @since 3.0.17
* @param {Object} control - The control object.
* @param {Object} control.id - The setting.
* @returns {null}
*/
init: function( control ) {
var element = jQuery( 'input[data-id="' + control.id + '"]' ),
value = control.setting._value,
up,
down;
// Make sure we use default values if none are define for some arguments.
control.params.choices = _.defaults( control.params.choices, {
min: 0,
max: 100,
step: 1
} );
// Make sure we have a valid value.
if ( isNaN( value ) || '' === value ) {
value = ( 0 > control.params.choices.min && 0 < control.params.choices.max ) ? 0 : control.params.choices.min;
}
value = parseFloat( value );
// If step is 'any', set to 0.001.
control.params.choices.step = ( 'any' === control.params.choices.step ) ? 0.001 : control.params.choices.step;
// Make sure choices are properly formtted as numbers.
control.params.choices.min = parseFloat( control.params.choices.min );
control.params.choices.max = parseFloat( control.params.choices.max );
control.params.choices.step = parseFloat( control.params.choices.step );
up = jQuery( '.kirki-input-container[data-id="' + control.id + '"] .plus' );
down = jQuery( '.kirki-input-container[data-id="' + control.id + '"] .minus' );
up.click( function() {
var oldVal = parseFloat( element.val() ),
newVal;
newVal = ( oldVal >= control.params.choices.max ) ? oldVal : oldVal + control.params.choices.step;
element.val( newVal );
element.trigger( 'change' );
} );
down.click( function() {
var oldVal = parseFloat( element.val() ),
newVal;
newVal = ( oldVal <= control.params.choices.min ) ? oldVal : oldVal - control.params.choices.step;
element.val( newVal );
element.trigger( 'change' );
} );
element.on( 'change keyup paste click', function() {
var val = jQuery( this ).val();
if ( isNaN( val ) ) {
val = parseFloat( val, 10 );
val = ( isNaN( val ) ) ? 0 : val;
jQuery( this ).attr( 'value', val );
}
kirki.setting.set( control.id, val );
} );
}
},
/**
* Image fields.
*
* @since 3.0.34
*/
image: {
/**
* Init the control.
*
* @since 3.0.34
* @param {Object} control - The control object.
* @returns {null}
*/
init: function( control ) {
var value = kirki.setting.get( control.id ),
saveAs = ( ! _.isUndefined( control.params.choices ) && ! _.isUndefined( control.params.choices.save_as ) ) ? control.params.choices.save_as : 'url',
preview = control.container.find( '.placeholder, .thumbnail' ),
previewImage = ( 'array' === saveAs ) ? value.url : value,
removeButton = control.container.find( '.image-upload-remove-button' ),
defaultButton = control.container.find( '.image-default-button' );
// Make sure value is properly formatted.
value = ( 'array' === saveAs && _.isString( value ) ) ? { url: value } : value;
// Tweaks for save_as = id.
if ( ( 'id' === saveAs || 'ID' === saveAs ) && '' !== value ) {
wp.media.attachment( value ).fetch().then( function() {
setTimeout( function() {
var url = wp.media.attachment( value ).get( 'url' );
preview.removeClass().addClass( 'thumbnail thumbnail-image' ).html( '<img src="' + url + '" alt="" />' );
}, 700 );
} );
}
// If value is not empty, hide the "default" button.
if ( ( 'url' === saveAs && '' !== value ) || ( 'array' === saveAs && ! _.isUndefined( value.url ) && '' !== value.url ) ) {
control.container.find( 'image-default-button' ).hide();
}
// If value is empty, hide the "remove" button.
if ( ( 'url' === saveAs && '' === value ) || ( 'array' === saveAs && ( _.isUndefined( value.url ) || '' === value.url ) ) ) {
removeButton.hide();
}
// If value is default, hide the default button.
if ( value === control.params.default ) {
control.container.find( 'image-default-button' ).hide();
}
if ( '' !== previewImage ) {
preview.removeClass().addClass( 'thumbnail thumbnail-image' ).html( '<img src="' + previewImage + '" alt="" />' );
}
control.container.on( 'click', '.image-upload-button', function( e ) {
var image = wp.media( { multiple: false } ).open().on( 'select', function() {
// This will return the selected image from the Media Uploader, the result is an object.
var uploadedImage = image.state().get( 'selection' ).first(),
jsonImg = uploadedImage.toJSON(),
previewImage = jsonImg.url;
if ( ! _.isUndefined( jsonImg.sizes ) ) {
previewImage = jsonImg.sizes.full.url;
if ( ! _.isUndefined( jsonImg.sizes.medium ) ) {
previewImage = jsonImg.sizes.medium.url;
} else if ( ! _.isUndefined( jsonImg.sizes.thumbnail ) ) {
previewImage = jsonImg.sizes.thumbnail.url;
}
}
if ( 'array' === saveAs ) {
kirki.setting.set( control.id, {
id: jsonImg.id,
url: jsonImg.sizes.full.url,
width: jsonImg.width,
height: jsonImg.height
} );
} else if ( 'id' === saveAs ) {
kirki.setting.set( control.id, jsonImg.id );
} else {
kirki.setting.set( control.id, ( ( ! _.isUndefined( jsonImg.sizes ) ) ? jsonImg.sizes.full.url : jsonImg.url ) );
}
if ( preview.length ) {
preview.removeClass().addClass( 'thumbnail thumbnail-image' ).html( '<img src="' + previewImage + '" alt="" />' );
}
if ( removeButton.length ) {
removeButton.show();
defaultButton.hide();
}
} );
e.preventDefault();
} );
control.container.on( 'click', '.image-upload-remove-button', function( e ) {
var preview,
removeButton,
defaultButton;
e.preventDefault();
kirki.setting.set( control.id, '' );
preview = control.container.find( '.placeholder, .thumbnail' );
removeButton = control.container.find( '.image-upload-remove-button' );
defaultButton = control.container.find( '.image-default-button' );
if ( preview.length ) {
preview.removeClass().addClass( 'placeholder' ).html( kirkiL10n.noFileSelected );
}
if ( removeButton.length ) {
removeButton.hide();
if ( jQuery( defaultButton ).hasClass( 'button' ) ) {
defaultButton.show();
}
}
} );
control.container.on( 'click', '.image-default-button', function( e ) {
var preview,
removeButton,
defaultButton;
e.preventDefault();
kirki.setting.set( control.id, control.params.default );
preview = control.container.find( '.placeholder, .thumbnail' );
removeButton = control.container.find( '.image-upload-remove-button' );
defaultButton = control.container.find( '.image-default-button' );
if ( preview.length ) {
preview.removeClass().addClass( 'thumbnail thumbnail-image' ).html( '<img src="' + control.params.default + '" alt="" />' );
}
if ( removeButton.length ) {
removeButton.show();
defaultButton.hide();
}
} );
}
}
}
} );
| reduxframework/kirki | controls/js/src/kirki.input.js | JavaScript | gpl-2.0 | 11,614 |
jQuery(document).ready(function ($) {
const $resourcesTable = $('#resources-table');
$resourcesTable.find('tbody tr:not(.sub-table-header)').hide();
$resourcesTable.find('.sub-table-header').click(function () {
$(this).nextUntil('tr.sub-table-header').toggle();
const visibleLength = $resourcesTable.find('tbody tr:has(:checkbox):visible').length,
allVisibleChecked = visibleLength > 0 && visibleLength === $resourcesTable.find('tbody tr.selected:visible').length;
$('#mark-all').prop('checked', allVisibleChecked);
});
});
| ACP3/module-permissions | Resources/Assets/js/admin/resources.index.js | JavaScript | gpl-2.0 | 579 |
/* $Id: jquery.pngFix.js,v 1.1.1.5 2009/02/04 19:23:30 gibbozer Exp $ */
/**
* --------------------------------------------------------------------
* jQuery-Plugin "pngFix"
* Version: 1.1, 11.09.2007
* by Andreas Eberhard, andreas.eberhard@gmail.com
* http://jquery.andreaseberhard.de/
*
* Copyright (c) 2007 Andreas Eberhard
* Licensed under GPL (http://www.opensource.org/licenses/gpl-license.php)
*
* Changelog:
* 11.09.2007 Version 1.1
* - removed noConflict
* - added png-support for input type=image
* - 01.08.2007 CSS background-image support extension added by Scott Jehl, scott@filamentgroup.com, http://www.filamentgroup.com
* 31.05.2007 initial Version 1.0
* --------------------------------------------------------------------
* @example $(function(){$(document).pngFix();});
* @desc Fixes all PNG's in the document on document.ready
*
* jQuery(function(){jQuery(document).pngFix();});
* @desc Fixes all PNG's in the document on document.ready when using noConflict
*
* @example $(function(){$('div.examples').pngFix();});
* @desc Fixes all PNG's within div with class examples
*
* @example $(function(){$('div.examples').pngFix( { blankgif:'ext.gif' } );});
* @desc Fixes all PNG's within div with class examples, provides blank gif for input with png
* --------------------------------------------------------------------
*/
(function($) {
jQuery.fn.pngFix = function(settings) {
// Settings
settings = jQuery.extend({
blankgif: 'blank.gif'
}, settings);
var ie55 = (navigator.appName == "Microsoft Internet Explorer" && parseInt(navigator.appVersion) == 4 && navigator.appVersion.indexOf("MSIE 5.5") != -1);
var ie6 = (navigator.appName == "Microsoft Internet Explorer" && parseInt(navigator.appVersion) == 4 && navigator.appVersion.indexOf("MSIE 6.0") != -1);
if (jQuery.browser.msie && (ie55 || ie6)) {
//fix images with png-source
jQuery(this).find("img[@src$=.png]").each(function() {
jQuery(this).attr('width',jQuery(this).width());
jQuery(this).attr('height',jQuery(this).height());
var prevStyle = '';
var strNewHTML = '';
var imgId = (jQuery(this).attr('id')) ? 'id="' + jQuery(this).attr('id') + '" ' : '';
var imgClass = (jQuery(this).attr('class')) ? 'class="' + jQuery(this).attr('class') + '" ' : '';
var imgTitle = (jQuery(this).attr('title')) ? 'title="' + jQuery(this).attr('title') + '" ' : '';
var imgAlt = (jQuery(this).attr('alt')) ? 'alt="' + jQuery(this).attr('alt') + '" ' : '';
var imgAlign = (jQuery(this).attr('align')) ? 'float:' + jQuery(this).attr('align') + ';' : '';
var imgHand = (jQuery(this).parent().attr('href')) ? 'cursor:hand;' : '';
if (this.style.border) {
prevStyle += 'border:'+this.style.border+';';
this.style.border = '';
}
if (this.style.padding) {
prevStyle += 'padding:'+this.style.padding+';';
this.style.padding = '';
}
if (this.style.margin) {
prevStyle += 'margin:'+this.style.margin+';';
this.style.margin = '';
}
var imgStyle = (this.style.cssText);
strNewHTML += '<span '+imgId+imgClass+imgTitle+imgAlt;
strNewHTML += 'style="position:relative;white-space:pre-line;display:inline-block;background:transparent;'+imgAlign+imgHand;
strNewHTML += 'width:' + jQuery(this).width() + 'px;' + 'height:' + jQuery(this).height() + 'px;';
strNewHTML += 'filter:progid:DXImageTransform.Microsoft.AlphaImageLoader' + '(src=\'' + jQuery(this).attr('src') + '\', sizingMethod=\'scale\');';
strNewHTML += imgStyle+'"></span>';
if (prevStyle != ''){
strNewHTML = '<span style="position:relative;display:inline-block;'+prevStyle+imgHand+'width:' + jQuery(this).width() + 'px;' + 'height:' + jQuery(this).height() + 'px;'+'">' + strNewHTML + '</span>';
}
jQuery(this).hide();
jQuery(this).after(strNewHTML);
});
// fix css background pngs
jQuery(this).find("*").each(function(){
var bgIMG = jQuery(this).css('background-image');
if(bgIMG.indexOf(".png")!=-1){
var iebg = bgIMG.split('url("')[1].split('")')[0];
jQuery(this).css('background-image', 'none');
jQuery(this).get(0).runtimeStyle.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + iebg + "',sizingMethod='scale')";
}
});
//fix input with png-source
jQuery(this).find("input[@src$=.png]").each(function() {
var bgIMG = jQuery(this).attr('src');
jQuery(this).get(0).runtimeStyle.filter = 'progid:DXImageTransform.Microsoft.AlphaImageLoader' + '(src=\'' + bgIMG + '\', sizingMethod=\'scale\');';
jQuery(this).attr('src', settings.blankgif)
});
}
return jQuery;
};
})(jQuery);
| rmontero/dla_ecommerce_site | sites/all/modules/contrib/colourise/js/jquery.pngFix.js | JavaScript | gpl-2.0 | 4,655 |
/*------------------------------------------------------------------------
# Full Name of JSN UniForm
# ------------------------------------------------------------------------
# author JoomlaShine.com Team
# copyright Copyright (C) 2012 JoomlaShine.com. All Rights Reserved.
# Websites: http://www.joomlashine.com
# Technical Support: Feedback - http://www.joomlashine.com/contact-us/get-support.html
# @license - GNU/GPL v2 or later http://www.gnu.org/licenses/gpl-2.0.html
# @version $Id: forms.js 19013 2012-11-28 04:48:47Z thailv $
-------------------------------------------------------------------------*/
define([
'jquery',
'uniform/help',
'uniform/dialogedition',
'jquery.ui'],
function($, JSNHelp, JSNUniformDialogEdition) {
function JSNUniformForms(params) {
this.params = params;
this.lang = params.language;
this.init();
}
JSNUniformForms.prototype = {
//Create modal box email list select
init: function() {
this.JSNHelp = new JSNHelp();
var self = this;
this.JSNUniformDialogEdition = new JSNUniformDialogEdition(this.params);
$(".jsn-popup-upgrade").click(function() {
JSNUniformDialogEdition.createDialogLimitation($(this), self.lang["JSN_UNIFORM_YOU_HAVE_REACHED_THE_LIMITATION_OF_3_FORM_IN_FREE_EDITION_0"]);
})
}
}
return JSNUniformForms;
}); | ducdongmg/joomla_tut25 | administrator/components/com_uniform/assets/js/forms.js | JavaScript | gpl-2.0 | 1,317 |
var InlineDonation = function(){
this.clientToken = document.getElementById('client_token').value;
this.setupEvents();
}
InlineDonation.prototype.setupEvents = function(){
jQuery(document.body).on('keyup', '#donation-form input', this.clearInvalidEntries);
this.setup();
}
InlineDonation.prototype.setup = function(){
braintree.setup(this.clientToken, 'dropin',{
container: 'dropin-container',
form: 'donation-form',
onReady: function(integration){
inlineDonation.integration = integration;
},
onPaymentMethodReceived: function(response){
inlineDonation.onPaymentMethodReceived(response);
}
})
}
InlineDonation.prototype.onPaymentMethodReceived = function(response){
inlineDonation.paymentMethodReceived = true;
var element = document.getElementById('payment_method_nonce');
if(element != null){
element.value = response.nonce;
}
else{
element = document.createElement('input');
element.type = 'hidden';
element.name = 'payment_method_nonce';
element.id = 'payment_method_nonce';
element.value = response.nonce;
jQuery('#donation-form').append(element);
}
inlineDonation.validateInputFields();
}
InlineDonation.prototype.validateInputFields = function(){
var hasFailures = false;
jQuery('#donation-form input').each(function(){
if(jQuery(this).val() === ""){
jQuery(this).parent().find('div.invalid-input-field').show().addClass('active');
hasFailures = true;
}
});
if(! hasFailures){
inlineDonation.submitPayment();
}
}
InlineDonation.prototype.submitPayment = function(){
var data = jQuery('#donation-form').serialize();
var url = jQuery('#ajax_url').val();
jQuery('.overlay-payment-processing').addClass('active');
jQuery.ajax({
type:'POST',
url: url,
dataType: 'json',
data: data
}).done(function(response){
jQuery('.overlay-payment-processing').removeClass('active');
if(response.result === 'success'){
inlineDonation.redirect(response.url);
}
else{
inlineDonation.showErrorMessage(response.message);
}
}).fail(function(response){
jQuery('.overlay-payment-processing').removeClass('active');
inlineDonation.showErrorMessage(response.message);
});
}
InlineDonation.prototype.redirect = function(url){
window.location.replace(url);
}
InlineDonation.prototype.showErrorMessage = function(message){
jQuery('#error_messages').html(message);
}
InlineDonation.prototype.clearInvalidEntries = function(){
jQuery(this).parent().find('div.invalid-input-field').hide().removeClass('active');
}
InlineDonation.prototype.clearErrorMessages = function(){
jQuery('#error_messages').empty();
}
InlineDonation.prototype.clearInvalidEntries = function(){
jQuery(this).parent().find('div.invalid-input-field').hide().removeClass('active');
}
InlineDonation.prototype.displayOverlay = function(callback){
jQuery('#donation_overlay').fadeIn(400, callback);
}
InlineDonation.prototype.hideOverlay = function(callback){
jQuery('#donation_overlay').fadeOut(400, callback);
}
var inlineDonation = new InlineDonation(); | namwoody/kart-zill.com | wp-content/plugins/woo-payment-gateway/assets/js/donations-inline.js | JavaScript | gpl-2.0 | 3,123 |
var Table = require ('../table.js');
var Command = require('../command.js');
require('../actions/report-action.js');
require('../actions/move-action.js');
require('../actions/right-action.js');
require('../actions/left-action.js');
require('../actions/place-action.js');
exports.Valid_PLACE = function(test){
var cmd = Command.GetCommand(['place', '1', '2', 'north']);
test.notEqual(cmd, null);
test.equal(cmd.data.x, 1);
test.equal(cmd.data.y, 2);
test.equal(cmd.data.f.getName(), 'NORTH');
test.done();
}
exports.Invalid_PLACE = function(test){
var cmd = Command.GetCommand(['place', '1', '2', 'northf']);
test.equal(cmd, null);
test.done();
}
exports.Valid_MOVE = function(test){
var cmd = Command.GetCommand(['MOVE']);
test.notEqual(cmd, null);
test.done();
}
exports.Valid_LEFT = function(test){
var cmd = Command.GetCommand(['left']);
test.notEqual(cmd, null);
test.done();
}
exports.Valid_RIGHT = function(test){
var cmd = Command.GetCommand(['Right']);
test.notEqual(cmd, null);
test.done();
}
exports.Invalid_Command = function(test){
var cmd = Command.GetCommand(['Oops']);
test.equal(cmd, null);
test.done();
}
exports.Valid_Execution = function(test){
// Create dummy Context
var ctx = {
table: new Table(5,5),
robot:null,
Feedback:{Show:function(msg){}},
Logger:{Log:function(msg){}}
}
Command.GetCommand(['place', '1', '1', 'east']).Execute(ctx);
Command.GetCommand(['move']).Execute(ctx);
Command.GetCommand(['left']).Execute(ctx);
Command.GetCommand(['move']).Execute(ctx);
Command.GetCommand(['move']).Execute(ctx);
test.equal(ctx.robot.x, 2);
test.equal(ctx.robot.y, 3);
test.equal(ctx.robot.f.getName(), 'NORTH');
test.done();
}
exports.Valid_IgnoreFallingMove = function(test){
// Create dummy Context
var ctx = {
table: new Table(5,5),
robot:null,
Feedback:{Show:function(msg){}},
Logger:{Log:function(msg){}}
}
Command.GetCommand(['place', '4', '1', 'east']).Execute(ctx);
Command.GetCommand(['move']).Execute(ctx);
test.equal(ctx.robot.x, 4);
test.equal(ctx.robot.y, 1);
test.equal(ctx.robot.f.getName(), 'EAST');
test.done();
} | PierreKel/ToyRobot | test/command-test.js | JavaScript | gpl-2.0 | 2,117 |
(function ($) {
Drupal.ychenikSearch = {};
/**
* jQuery plugin.
*/
$.fn.ychenikSearch = function (stars) {
stars = stars || 0;
this.each(function () {
$(this).addClass('ychenik-search').find('label').each(function () {
var context = this.form;
var $label = $(this);
if (!$label.attr('for')) {
return;
}
var $field = $('#' + $label.attr('for'), context);
if (!$field.length || !$field.is('input:text,input:password,textarea')) {
return;
}
// Store the initial field value, in case the browser is going to
// automatically fill it in upon focus.
var initial_value = $field.val();
if (initial_value != '') {
// Firefox doesn't like .hide() here for some reason.
$label.css('display', 'none');
}
$label.parent().addClass('ychenik-search-wrapper');
$label.addClass('ychenik-search-label');
$field.addClass('ychenik-search-field');
if (stars === 0) {
$label.find('.form-required').hide();
}
else if (stars === 2) {
$label.find('.form-required').insertAfter($field).prepend(' ');
}
$field.focus(function () {
// Some browsers (e.g., Firefox) are automatically inserting a stored
// username and password into login forms. In case the password field is
// manually emptied afterwards, and the user jumps back to the username
// field (without changing it), and forth to the password field, then
// the browser automatically re-inserts the password again. Therefore,
// we also need to test against the initial field value.
if ($field.val() === initial_value || $field.val() === '') {
$label.fadeOut('fast');
}
});
$field.blur(function () {
if ($field.val() === '') {
$label.fadeIn('slow');
}
});
// Chrome adds passwords after page load, so we need to track changes.
$field.change(function () {
if ($field.get(0) != document.activeElement) {
if ($field.val() === '') {
$label.fadeIn('fast');
}
else {
$label.css('display', 'none');
}
}
});
});
});
};
/**
* Attach compact forms behavior to all enabled forms upon page load.
*/
Drupal.behaviors.ychenikSearch = {
attach: function (context, settings) {
if (!settings || !settings.ychenikSearch) {
return;
}
$('#' + settings.ychenikSearch.forms.join(',#'), context).ychenikSearch(settings.ychenikSearch.stars);
// Safari adds passwords without triggering any event after page load.
// We therefore need to wait a bit and then check for field values.
if ($.browser.safari) {
setTimeout(Drupal.ychenikSearch.fixSafari, 200);
}
}
};
/**
* Checks for field values and hides the corresponding label if non-empty.
*
* @todo Convert $.fn.compactForm to always use a function like this.
*/
Drupal.ychenikSearch.fixSafari = function () {
$('label.ychenik-search-label').each(function () {
var $label = $(this);
var context = this.form;
if ($('#' + $label.attr('for'), context).val() != '') {
$label.css('display', 'none');
}
});
}
})(jQuery);
| borisay/ychenik | sites/all/modules/custom/ychenik_search/ychenik_search.js | JavaScript | gpl-2.0 | 3,267 |
angular.module('SpamExpertsApp')
.run(['$rootScope', '$state', 'uiService', 'AuthService', 'API_EVENTS',
function ($rootScope, $state, uiService, AuthService, API_EVENTS) {
$rootScope.$on('$stateChangeStart', function (event, next) {
if (next.name !== 'login') {
$rootScope.username = AuthService.getUsername();
$rootScope.role = AuthService.getRole();
if (!AuthService.isAuthenticated()) {
event.preventDefault();
$state.go('login');
} else if ('data' in next && 'authorizedRoles' in next.data) {
var authorizedRoles = next.data.authorizedRoles;
if (!AuthService.isAuthorized(authorizedRoles)) {
event.preventDefault();
$state.go($state.current, {}, {reload: true});
$rootScope.$broadcast(API_EVENTS.notAuthorized);
}
}
} else {
if (AuthService.isAuthenticated()) {
event.preventDefault();
$state.go('main.dash');
}
}
});
$rootScope.$on('$logout', function () {
uiService.confirm({
title: 'Confirm logout',
template: 'Are you sure you want to log out?'
}, function() {
AuthService.logout();
$state.go('login');
});
});
$rootScope.$on(API_EVENTS.notAuthorized, function() {
uiService.alert({
title: 'Unauthorized!',
template: 'You are not allowed to access this resource.'
});
});
$rootScope.$on(API_EVENTS.userNotAllowed, function() {
uiService.alert({
title: 'Error logging in!',
template: 'Sorry, admin users are not able to use this app yet. Please log in as a domain or email user.'
});
});
$rootScope.$on(API_EVENTS.notAuthenticated, function() {
AuthService.logout();
AuthService.clearPassword();
$state.go('login');
uiService.alert({
title: 'Authentication expired',
template: 'Sorry, you have to login again.'
});
});
}
]); | SpamExperts/mobile-app | src/js/auth/init.js | JavaScript | gpl-2.0 | 2,639 |
module.exports = function (grunt) {
"use strict";
grunt.initConfig({
dirs: {
css: 'app/css',
js: 'app/js',
sass: 'app/sass',
},
compass: {
dist: {
options: {
config: 'config.rb',
}
}
},
concat: {
options: {
seperator: ';',
},
dist: {
src: ['<%= dirs.js %>/modules/*.js', '<%= dirs.js %>/src/*.js'],
dest: '<%= dirs.js %>/app.js'
}
},
uglify: {
options: {
// mangle: false,
debug: true,
},
target: {
files: {
'<%= dirs.js %>/app.min.js': ['<%= dirs.js %>/app.js']
}
}
},
watch: {
css: {
files: [
'<%= dirs.sass %>/*.scss',
'<%= dirs.sass %>/modules/*.scss',
'<%= dirs.sass %>/partials/*.scss'
],
tasks: ['css'],
options: {
spawn: false,
}
},
js: {
files: [
'<%= dirs.js %>/modules/*.js',
'<%= dirs.js %>/src/*.js'
],
tasks: ['js'],
options: {
spawn: false,
}
}
}
});
grunt.loadNpmTasks('grunt-contrib-compass');
grunt.loadNpmTasks('grunt-contrib-concat');
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.registerTask('default', ['css', 'js']);
grunt.registerTask('css', ['compass']);
grunt.registerTask('js', ['concat', 'uglify']);
};
| SeerUK/WoWPR | Gruntfile.js | JavaScript | gpl-2.0 | 1,487 |
Ext.define('TrackApp.view.main.Main', {
extend: 'Ext.panel.Panel',
requires: [
'Ext.resizer.Splitter'
],
xtype: 'app-main',
controller: 'main',
viewModel: {
type: 'main'
},
title: 'Oslo-Bergen til fots',
header: {
titlePosition: 0,
defaults: {
xtype: 'button',
toggleGroup: 'menu'
},
items: [{
text: 'Bilder',
id: 'instagram'
},{
text: 'Høydeprofil',
id: 'profile'
},{
text: 'Posisjon',
id: 'positions'
},{
text: 'Facebook',
id: 'facebookUrl',
reference: 'facebookBtn'
},{
text: 'Instagram',
id: 'instagramUrl',
reference: 'instagramBtn'
}]
},
layout: {
type: 'vbox',
pack: 'start',
align: 'stretch'
},
items: [{
reference: 'map',
xtype: 'map',
flex: 3
}, {
reference: 'bottom',
xtype: 'panel',
flex: 2,
//split: true,
hidden: true,
layout: {
type: 'fit'
},
defaults: {
hidden: true
},
items: [{
reference: 'profile',
xtype: 'profile'
},{
reference: 'positions',
xtype: 'positions'
}]
}]
}); | turban/oslobergen | app/view/main/Main.js | JavaScript | gpl-2.0 | 1,049 |
"use strict"
var util = require('util')
var MessageEvent = require('./messageevent')
var Config = require('./config')
/**
* Coordinate the connection of a new chat client to the server.
* Different chat clients send the information differently, so far this chat server supports: TinTin++, mudjs, MudMaster, MudMaster 2k6, ZChat
*/
class Handshake {
/**
* Handshake constructor
* Constructs a new handshake object to process new connections to the chatserver
* @param {Socket} socket nodejs net socket object
* @param {Function} callback the callback that will be processed once the handshake has completed
* @todo Get the chatserver's name from some sort of preferences file
* @todo Get the chatserver's version from some sort of preferences file
*/
constructor(socket, callback) {
this.socket = socket
this.cb = callback
socket.on('data', data => {
var str = data.toString()
var nameAndIp = []
// check if our handshake data contains the expected :
if (str.indexOf(':') > -1) {
// set the connection's protocol information
this.setProtocol(str)
// send the chat name of the server to the client
this.setName('chatserver')
// send the version of the chatserver to the client
this.setVersion(`chatserver v${Config.version}`)
// setup the version response listener to get the client's version
this.socket.on('data', data => this.getVersion(data))
}
})
}
/**
* Set the protocol of the handshake
* @param {String} protocolStr colon and new line delimitered string of the handshake data
*/
setProtocol(protocolStr) {
// split the protocol string by the :
var result = protocolStr.split(':', 2)
// check the first part of the result to get the protocol
if (result[0] == 'CHAT') {
// MudMaster protocol
this.protocol = 'mudmaster'
} else if (result[0] == 'ZCHAT') {
// ZChat protocol
this.protocol = 'zchat'
} else {
// Unknown protocol
this.protocol = 'unknown'
}
// get the name and ip from the second part of the result
this.name = result[1].split('\n')[0]
this.ip = this.socket.remoteAddress
this.port = this.socket.remotePort
}
/**
* Send the chat servers name to the client
* @param {String} name the name of the chat server
*/
setName(name) {
this.socket.write(util.format('YES:%s\n', name))
}
/**
* Send the chat servers version to the client
* @param {String} version the version of the chatserver
*/
setVersion(version) {
// create the version as hex
var hexVersion = ""
for (var i = 0; i < version.length; i++) {
hexVersion += ''+version.charCodeAt(i).toString(16)
}
// send the version
MessageEvent.version(version).toSocket(this.socket).send()
}
/**
* Get the chat client's version
* @param {String} data the data received over the socket
*/
getVersion(data) {
if (data[0].toString(16) == MessageEvent.Type.VERSION) {
this.version = data.toString().substring(1, data.length - 2)
}
// remove all the listeners for 'data' on the socket as we don't want getVersion called over and over
this.socket.removeAllListeners('data')
// callback with self
this.cb(this)
}
}
module.exports = Handshake
| logikaljay/mudchat | core/handshake.js | JavaScript | gpl-2.0 | 3,704 |
'use strict';
import React from 'react';
import ReactDOM from 'react-dom';
import UIDropdownComponent from './component';
let uiDropdown = function (element) {
ReactDOM.render(
React.createElement(
UIDropdownComponent,
{'message': element.getAttribute('data-message')}
),
element
);
};
export default uiDropdown; | roman901/Overheard | frontend/js/ui/dropdown/index.js | JavaScript | gpl-2.0 | 371 |
/*
* \brief localization strings for fr_FR
*
* \file loc_fr_FR.js
*
* Copyright (C) 2006-2009 Jedox AG
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License (Version 2) as published
* by the Free Software Foundation at http://www.gnu.org/copyleft/gpl.html.
*
* 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 General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place, Suite 330, Boston, MA 02111-1307 USA
*
* You may obtain a copy of the License at
*
* <a href="http://www.jedox.com/license_palo_bi_suite.txt">
* http://www.jedox.com/license_palo_bi_suite.txt
* </a>
*
* If you are developing and distributing open source applications under the
* GPL License, then you are free to use Palo under the GPL License. For OEMs,
* ISVs, and VARs who distribute Palo with their products, and do not license
* and distribute their source code under the GPL, Jedox provides a flexible
* OEM Commercial License.
*
* \author
* Drazen Kljajic <drazen.kljajic@develabs.com>
* Mladen Todorovic <mladen.todorovic@develabs.com>
* Srdjan Vukadinovic <srdjan.vukadinovic@develabs.com>
* Andrej Vrhovac <andrej.vrhovac@develabs.com>
* Predrag Malicevic <predrag.malicevic@develabs.com>
*
* \version
* SVN: $Id: loc_fr_FR.js 4895 2011-04-27 09:35:11Z l10n-tool $
*
*/
Jedox.wss.i18n.L10n = 'fr_FR';
Jedox.wss.i18n.separators = [ ',', '.', ';' ];
Jedox.wss.i18n.bool = { 'true': 'VRAI', 'false': 'FAUX' };
Jedox.wss.i18n.strings = {
// Menubar
"Import": "Import",
"Save as": "Enregistrer sous",
"Save Workspace": "Volet enregistrer",
"File Search": "Recherche de fichiers",
"Permission": "Autorisation",
"Print Area": "Zone d'impression",
"Print Preview": "Aperçu avant impression",
"Print": "Imprimer",
"Send to": "Envoyer vers",
"Form Elements": "Éléments de formulaire",
"ComboBox": "Liste déroulante",
"Can\'t Repeat": "Répétition impossible",
"Quick Publish": "Publication rapide",
"Can\'t Undo": "Impossible d'annuler",
"Can\'t Redo": "Impossible de rétablir",
"WSS Clipboard": "Presse-papiers",
"Paste as Hyperlink": "Coller comme lien hypertexte",
"Clear": "Effacer",
"Delete Rows": "Supprimer les lignes",
"Delete Columns": "Supprimer les colonnes",
"Move or Shopy Sheet": "Déplacer ou copier la feuille",
"Replace": "Remplacer",
"Go To": "Atteindre",
"Object": "Objet",
"Normal": "Normal ",
"Page Break Preview": "Aperçu des sauts de page",
"Task Pane": "Panneau des tâches",
"Header and Footer": "En-tête et pied de page",
"Comments": "Commentaires",
"Custom View": "Affichage personnalisé",
"Full Screen": "Plein écran",
"Zoom": "Zoom ",
"Entire row": "Insertion de lignes",
"Entire column": "Insertion de colonnes",
"Worksheet": "Feuille",
"Symbol": "Caractères spéciaux",
"Page Break": "Saut de page",
"Diagram": "Diagramme",
"Edit Hyperlink": "Editer le lien hypertexte",
"Row": "Ligne",
"Row Height": "Hauteur de ligne",
"Autofit Row Height": "Ajustement automatique des lignes",
"Autofit Column Width": "Ajustement automatique des colonnes",
"Sheet": "Feuille",
"AutoFormat": "Mise en forme automatique",
"Conditional Formatting": "Mise en forme conditionnelle",
"Style": "Style ",
"Tools": "Outils",
"Spelling": "Orthographe",
"Research": "Recherche",
"Error Checking": "Vérification des erreurs",
"Shared Workspace": "Espace de travail partagé",
"Share Workbook": "Partager le classeur",
"Track Changes": "Suivi des modifications",
"Compare and Merge Workbooks": "Comparaison et fusion de classeurs",
"Online Collaboration": "Collaboration en ligne",
"Goal Seek": "Valeur cible",
"Scenarios": "Scénarios",
"Formula Auditing": "Audit de formules",
"Macros": "Macros",
"Add-Ins": "Macros complémentaires",
"AutoCorrect Options": "Options de correction automatique",
"Customize": "Personnaliser",
"Options": "Options ",
"Palo": "Palo ",
"Paste View": "Créer une vue",
"Paste SubSet": "Coller le sous-ensemble",
"Paste Data Function": "Fonction d\'accès aux données",
"Data Import": "Import de données",
"Palo Wizard": "Assistant Palo",
"WikiPalo": "WikiPalo",
"About": "A propos de",
"Data": "Données",
"Filter": "Filtre",
"Form": "Formulaire",
"Subtotals": "Sous-totaux",
"Validation": "Validation ",
"Table": "Table ",
"Text to Columns": "Convertir",
"Group and Outline": "Groupe et contours",
"Import External Data": "Données externes",
"XML": "XML ",
"Refresh Data": "Actualisation des données",
"Auto-Refresh Data": "Actualisation automatique des données",
"Auto-Calculate Data":"Calculation automatique des données",
"New Window": "Nouvelle fenêtre",
"Arrange": "Réorganiser",
"Compare Side by Side with": "Comparer côte à côte avec",
"Split": "Fractionner",
"Freeze Panes": "Figer les volets",
"Worksheet-Server Help": "Aide sur Worksheet-Server",
"Jedox Online": "Jedox_Online",
"Contact us": "Contactez-nous",
"Check for Updates": "Rechercher les mises à jour",
"Customer Feedback Options": "Options pour les commentaires utilisateurs",
"About Worksheet-Server": "A propos de Worksheet-Server",
"About Palo Suite":"A propos de Palo Suite",
// Formatbar
"Center text": "Au centre",
"Align Text Right": "Aligné à droite",
"Show/Hide Grid": "Afficher/masquer quadrillage",
"Item Lock/Unlock": "Verrouiller les cellules",
"Insert Chart": "Insérer un graphique",
"Back": "Retour",
"Back To": "Retour à",
"Refresh / Recalculate": "Actualiser / Recalculer",
"Print To PDF": "Imprimer en PDF",
"Download": "Télécharger",
"Download Workbook": "Télécharger le classeur",
// Sheet Selector
"First Sheet": "La première feuille",
"Previous Sheet": "La feuille précédente",
"Next Sheet": "La feuille suivante",
"Last Sheet": "La dernière feuille",
"Delete Worksheet": "Supprimer la feuille",
"delLastWorksheet": "Un classeur doit contenir au moins une feuille.<br>Pour supprimer les feuilles sélectionnées, vous devez insérer d'abord une nouvelle feuille.",
"Move Worksheet": "Déplacer la feuille",
"moveLastWorksheet": "Un classeur doit contenir au moins une feuille.<br>Pour déplacer les feuilles sélectionnées, vous devez insérer d'abord une nouvelle feuille.",
// Workbook
"saveFileErr": "Votre fichier n'a pas pu être enregistré !",
"errWBSave_nameExists": "{Name} existe déjà.<br>Souhaitez-vous remplacer le fichier ?",
"errWBSave_noParent": "Nom du classeur \"{Name}\" est trop court.<br>Il doit contenir au moins 2 caractères.",
"errWBSave_noParentAccess": "Nom du classeur \"{Name}\" est trop long.<br>Il ne doit pas contenir plus de 64 caractères.",
"errWBSave_noAccess": "Vous ne pouvez pas enregistrer ce classeur car <br>un autre classeur \"(nom) \" est toujours ouvert.<br><br>Sélectionnez un autre nom ou fermez le même classeur.",
// Import Dialog
"impDlg_fieldLbl": "Fichier à importer (seulement les fichiers xlsx sont permis)",
"impDlg_msgWrongType": "Dans ce champ, vous devez entrer la totalité du chemin d'accès au fichier xlsx !",
"Upload": "Importer",
"Import Error": "Erreur d'importation",
"imp_err_msg": "Il n'est pas possible d'importer le fichier \"{Name}\" ",
// Insert Function Dialog
"Select a category": "Sélectionnez une catégorie",
"Select a function": "Sélectionnez une fonction",
"Functions": "Fonctions",
"Insert Function": "Insérer une fonction",
// Save As Dialog
"newWBName": "Entrez le nouveau nom de fichier",
// Errors
"srvNotRespond": "Erreur fatale : le serveur ne répond pas ! \N Le client a été arrêté.",
"Invalid input!": "Entrée non valide !",
"Override me!": "Ignorez l'erreur !",
"Error Data": "Erreur de données",
"General Error": "Erreur générale",
"Application Backend Error": "Backend application erreur",
"Server Error": "Erreur du serveur",
"This is a fatal error, re-login will be required!": "Il s'agit d'une erreur fatale. Cela nécessite un nouvel login!",
// Insert/Edit Chart
"End Select Range": "Fin de la plage sélectionnée",
"Select Data Source": "Sélectionnez la source de données",
"Input Error": "Erreur de saisie",
"Unsupported Element": "Elément non supporté",
"Operation Error": "Erreur d'opération",
"Data Source": "Source de données",
"Chart data range": "Plage de données du graphique",
"Group data by": "Série en",
"Use series labels": "Utiliser les noms des séries",
"Label location": "Position de l'étiquette",
"Use category labels": "Utiliser les noms de catégories",
"Select Range": "Sélectionner une plage",
"Labels": "Étiquettes",
"Chart title": "Titre du graphique",
"Edit Chart": "Editer le graphique",
"Cols": "Cimes",
"Delete Chart": "Supprimer le graphique",
"chartDlg_invalidChartType": "Le type du graphique n\'est pas valide.",
"chartDlg_rangeEmpty": "La plage de cellules est vide. Veuillez entrer des données ou choisir une source de données valide.",
"chartDlg_deleteError": "Le graphique sélectionné ne peut pas être supprimé!",
"chartDlg_EditError": "Les propriétés actuelles du graphique ne peuvent pas être récupérées",
"chartDlg_unsupportedChartType": "Le type de graphique sélectionné sera bientôt disponible !",
"chartDlg_genError": "La création du graphique n\'est pas possible. Veuillez vérifier les propriétés du graphique sélectionné.",
"Incorect Chart Size": "La taille du graphique est incorrect",
"infoChart_wrongSize": "La nouvelle taille du graphique n\'est pas bonne, il est automatiquement ajusté à la taille appropriée.",
"infoChart_wrongSize2": "Certains graphiques n'ont pas la taille appropriée. Leur taille sera automatiquement ajustée.",
"Change Chart Type": "Changer le type du graphique",
"Format Chart Properties": "Formater le graphique",
"Scales": "Echelles",
"Zones": "Gammes",
"Scale": "Echelle",
"Zones options": "Options des gammes",
"Points": "Aiguilles",
"Points options": "Options des aiguilles",
"Categories": "Catégories",
"Type": "Objet",
"Sort Ascending": "Tri croissant",
"Sort Descending": "Tri descendant",
"Group by": "Groupe par",
//editChart
"Column": "Histogramme",
"Area": "Aires",
"X Y (Scatter)": "Nuages de points",
"Stock": "Bousier",
"Radar": "Radar",
"Meter": "Tachymètre",
"Clustered Column": "Histogramme groupé",
"Stacked Column": "Histogramme empilé",
"100% Stacked Column": "Histogramme empilé 100%",
"3-D Clustered Column": "Histogramme groupé avec effet 3D",
"Stacked Column in 3-D": "Histogramme empilé avec effet 3D",
"100% Stacked Column in 3-D": "Histogramme empilé 100% avec effet 3D",
"Clustered Cylinder": "Histogramme groupé à formes cylindriques",
"Stacked Cylinder": "Histogramme empilé à formes cylindriques",
"100% Stacked Cylinder": "Histogramme empilé 100% à formes cylindriques",
"Stacked Line": "Courbes empilées",
"100% Stacked Line": "Courbes empilées 100%",
"Rotated Line": "Courbes pivotées",
"Line with Markers": "Courbes avec marques de données affichées à chaque point",
"Stacked Line with Markers": "Courbes empilées avec marques de données affichées à chaque point",
"100% Stacked Line with Markers": "Courbes empilées 100% avec marques de données affichées à chaque point",
"Rotated Line with Markers": "Courbes pivotées avec marques de données affichées à chaque point",
"3-D Line": "Courbes avec effet 3D",
"Pie in 3-D": "Secteurs avec effet 3D",
"Exploded Pie": "Secteurs éclatés",
"Exploded Pie in 3-D": "Secteurs éclatés avec effet 3D",
"Clustered Bar": "Barres groupées",
"Stacked Bar": "Barres empilées",
"100% Stacked Bar": "Barres empilées 100%",
"Clustered Bar in 3-D": "Barres groupées avec effet 3D",
"Stacked Bar in 3-D": "Barres empilées avec effet 3D",
"100% Stacked Bar in 3-D": "Barres empilées 100% avec effet 3D",
"Clustered Horizontal Cylinder": "Barres groupées de formes cylindriques",
"Stacked Horizontal Cylinder": "Barres empilées de formes cylindriques",
"100% Stacked Horizontal Cylinder": "Barres empilées 100% de formes cylindriques",
"Stacked Area": "Aires empilées",
"100% Stacked Area": "Aires empilées 100%",
"3-D Area": "Aires avec effet 3D",
"Stacked Area in 3-D": "Aires empilées avec effet 3D",
"100% Stacked Area in 3-D": "Aires empilées 100% avec effet 3D",
"Scatter with only Markers": "Nuage de points avec marques des données",
"Scatter with Smooth Lines and Markers": "Nuage de points reliés par une courbe lissée",
"Scatter with Smooth Lines": "Nuage de points avec lissage sans marquage des données",
"Scatter with Straight Lines and Markers": "Nuage de points reliés par une courbe",
"Scatter with Straight Lines": "Nuage de points reliés par une courbe sans marquage des données",
"High-Low-Close": "Haut-bas-fermé",
"Open-High-Low-Close": "Ouvert-haut-bas-fermé",
"Doughnut": "Anneau",
"Exploded Doughnut": "Anneau éclaté",
"Bubble": "Bulles",
"Bubble with a 3-D Effect": "Bulle avec effet 3D",
"Radar with Markers": "Radar avec marquage des données",
"Filled Radar": "Radar plein",
"Odometer Full": "Cercle-Tachymètre",
"Odometer Full Percentage": "Cercle-Tachymètre avec %",
"Odometer Half": "Demi-Cercle-Tachymètre",
"Odometer Half Percentage": "Demi-Cercle-Tachymètre avec %",
"Wide Angular Meter": "Grand-Angle-Tachymètre",
"Horizontal Line Meter": "Tachymètre horizontal",
"Vertical Line Meter": "Tachymètre vertical",
"Fill": "Remplir",
"Border Color": "Couleur de la bordure",
"No fill": "Ne pas remplir",
"Solid fill": "Remplissage plein",
"Automatic": "Automatique",
"No line": "Pas de ligne",
"Solid line": "Ligne solide",
"Source Data Options": "Options de la source de données",
"Chart Data Range": "Plage de données du graphique",
"Group Data By": "Série en",
"Columns": "Colonnes",
"Rows": "Lignes",
"Yes": "Oui",
"No": "Non",
"Font Options": "Options de police",
"Title Options": "Options du titre",
"Legend Options": "Options de la légende",
"Horizontal Axis": "Axe des abscisses",
"Horizontal axis": "Axe des abscisses",
"Vertical Axis": "Axe des ordonnées",
"Vertical axis": "Axe des ordonnées",
"Auto": "Auto ",
"Fixed": "Fixé",
"Major Unit": "Grand unité",
"Minor Unit": "Petit unité",
"Chart Type": "Type du graphique",
"Chart Area": "Zone du graphique",
"Plot Area": "Zone de la figure",
"Source Data": "Source de données",
"Title": "Titre",
"Legend": "Légende",
"Axes": "Axes",
"Format Chart": "Format du graphique",
"Series Options":"Options des séries",
"Series":"Séries",
"Office":"Bureau",
"Apex":"Apex",
"Aspect":"Aspect",
"Name":"Nom",
"General":"Général",
"No border":"Aucun bordure",
"Select Source Data":"Source de données",
//Cell Comments
"Comment": "Commentaire",
"Edit Comment": "Editer le commentaire",
"Delete Comment": "Supprimer le commentaire",
"Hide Comment": "Masquer le commentaire",
"Show/Hide Comment": "Afficher/masquer le commentaire",
"Insert Comment": "Insérer un commentaire",
// PALO Paste View
"Choose Cube": "Sélectionner le cube",
"Wrap Labels": "Réaligner",
"Fixed width": "Largeur fixe",
"Show element selector on doubleclick": "Montrer le sélecteur en double-cliquant",
"Paste at selected cell": "Coller dans la cellule sélectionnée",
"Page selector": "Selecteur de page",
"Column titles": "Titres en en-tête de colonne",
"Row titles": "Titres de ligne",
"Select Elements": "Choisir un élément",
"Please wait": "Veuillez patienter",
"Obtaining data!": "Transmission des données!",
// Select Elements
"B": " B ",
"Select Branch": "Choisir une branche",
"Invert Selec": "Inverser la sélection",
"Paste Vertically": "Coller verticalement",
"Ascending": "Ordre croissant",
"Descending": "Ordre décroissant",
"Clear list": "Vider la liste",
"Pick list": "Liste de choix",
"_msg: se_Tip": "Astuce",
"Show all selection tools": "Afficher tous les outils de sélection",
"insert database elements": "Insérer des éléments de la base de données ",
"insert server/database (connection)": "Insérer Serveur/base de données (connexion)",
"insert cube name": "Insérer le nom du cube",
"insert dimension names": "Insérer les noms des dimensions",
"Invert Select": "Inverser la sélection",
"Paste horizontaly": "Coller horizontalement",
// Paste Data Functions
"Paste Data Functions": "Fonction d\'accès aux données",
"Attribute Cubes": "Cube d'attributs",
"Guess Arguments": "Choix automatique des paramètres",
// Format Cells Dialog
"Format Cells": "Format des cellules",
"Number": "Nombre",
"Currency": "Monétaire",
"Accounting": "Comptabilité",
"Date": "Date",
"Time": "Heure",
"Percentage": "Pourcentage",
"Fraction": "Fraction",
"Scientific": "Scientifique",
"Special": "Spécial",
"Custom": "Personnalisé",
"$ US Dollar": "Dollar $ US",
"€ Euro": "Euro €",
"£ GB Pound": "Anglais £",
"CHF Swiss Francs": "Francs Suisse CHF",
"¥ Japanese Yen": "Yen japonais ¥",
"YTL Turkey Liras": "Lires turques YTL",
"Zł Poland Zlotych": "Zloty polonais Zł",
"₪ Israel, New Shekels": "Nouveaux Shekels israéliens ₪",
"HKD Hong Kong Dollar": "Hong Kong Dollar HKD",
"KC Czech Koruny": "Couronnes tchèques KC",
"CNY China Yuan": "Yen chinois CNY",
"P Russian Rubles": "Roubles russes P",
"_catDescr: general": "Les cellules avec un format Standard n\'ont pas de format de nombre spécifique.",
"_catDescr: number": "Le format Nombre est utilisé pour l\'affichage général des nombres. Les catégories Monétaire et Comptabilité offrent des formats spéciaux pour les valeurs monétaires.",
"_catDescr: currency": "Les formats Monétaire sont utilisés pour des valeurs monétaires générales. Utilisez les formats Comptabilité pour aligner les décimaux dans une colonne.",
"_catDescr: accounting": "Les formats Comptabilité alignent les symboles monétaires et les décimaux dans une colonne.",
"_catDescr: date": "Les formats Date affichent les numéros de date et d\'heure comme valeurs de date. À l\'exception des éléments précédés d\'un astérisque(*), l\'ordre des parties de la date ne change pas en fonction du système d\'exploitation.",
"_catDescr: time": "Les formats Heures affichent les numéros de date et heure comme valeurs d\'heure. À l\'exception des éléments précédés d\'un astérisque(*), l\'ordre des parties de la date ou de l\'heure ne change pas en fonction du système d\'exploitation.",
"_catDescr: percentage": "Les formats Pourcentage multiplient la valeur de la cellule par 100 et affichent le résultat avec le symbole pourcentage.",
"_catDescr: special": "Les formats Spécial sont utilisés pour contrôler des valeurs de liste et de base de données.",
"_catDescr: text": "Les cellules de format Texte sont traitées comme du texte même si c\'est un nombre qui se trouve dans la cellule. La cellule est affichée exactement comme elle a été entrée.",
"_catDescr: custom": "Entrez le code du format de nombre, en utilisant un des codes existants comme point de départ.",
"Sample": "Exemple",
"Locale (location)": "Paramètres régionaux (emplacement)",
"Category": "Catégorie",
"Up to one digit(1/4)": "D'un chiffre(1/4)",
"Up to two digits(21/35)": "De deux chiffres(21/35)",
"Up to three digits(312/943)": "De trois chiffres(312/943)",
"Up to halves(1/2)": "Demis(1/2)",
"Up to quarters(2/4)": "Quarts(2/4)",
"Up to eights(4/8)": "Huitièmes(4/8)",
"Up to sixteenths(8/16)": "Seizièmes(8/16)",
"Up to tenths(3/10)": "Dixièmes(3/10)",
"Up to hundredths(30/100)": "Centièmes(30/100)",
"Context": "Contexte",
"Left-to-Right": "De gauche à droite",
"Right-to-Left": "De droite à gauche",
"Top": "Haut",
"Justify": "Justifié",
"Distributed": "Distribué",
"Distributed (Indent)": "Distribué (Retrait)",
"Center across section": "Centré sur plusieurs colonnes",
"Left (Indent)": "Gauche (Retrait)",
"Decimal places": "Décimales",
"Negative numbers": "Nombres négatifs",
"Use 1000 Separator (.)": "Utiliser le séparateur de milliers(.)",
"Wrap Text": "Renvoyer à la ligne automatiquement",
"Text alignment": "Alignement du texte",
"Vertical": "Verticale",
"Horizontal": "Horizontal",
"Text control": "Contrôle du texte",
"Merge cells": "Fusionner les cellules",
"Text direction": "Orientation du texte",
"Line": "Courbes",
"Color": "Couleur",
"Presets": "Présélections",
"Border": "Bordure",
"The selected border style can be applied by clicking the presets, preview diagram or the buttons above.": "Le style de bordure sélectionné peut être appliqué en cliquant sur l\'une des présélections ou les autres boutons ci-dessus.",
"No Color": "Pas de couleur",
"More Colors": "Plus de couleurs",
"Background color": "Couleur de fond",
"Pattern style": "Motifs",
"Locked": "Verrouillée",
"Hidden": "Masquée",
"Normal font": "Police normale",
"Strikethrough": "Barré",
"Overline": "Souligné",
"Effects": "Effets",
"Font style": "Style ",
"This is a TrueType font. The same font will be used on both your printer and your screen.": "Police TrueType, identique à l'écran et à l'impression.",
"-1234,10": "-1234,10 ",
"1234,10": "1234,10 ",
"Protection": "Protection",
"Font": "Police ",
"Locking cells or hiding formulas has no effect until you protect the worksheet.": "Verrouillé ou Masqué a seulement des effets après la protection de la feuille.",
"Merge": "Fusionner",
"Wrap text": "Renvoyer à la ligne automatiquement",
"General format cells have no formatting.": "Les cellules de format Standard n\'ont pas de format de nombre spécifique.",
// Main Context Menu
"Edit Micro Chart": "Editer le micrographique",
// DynaRanges
"Local List": "Liste locale",
"Vertical Hyperblock": "DynaRange vertical",
"Horizontal Hyperblock": "DynaRange horizontal",
"Switch Direction": "Changer la direction",
"Edit List": "Editer la liste",
// hb Dialog
"_tit: hb Properties": "Propriétés du DynaRange",
"Standard": "Standard",
"Text Format of the List": "Format texte de la liste",
"List Selector": "Sélecteur de la liste",
"Drill down, begin at level": "Drill down, commencer au niveau",
"Indent Text": "Indenter le texte",
"Fixed column width": "Largeur fixé",
"Display": "Affichage",
"Filling": "Remplissage",
"Pattern": "Motifs",
"_name: UnnamedHb": "DynaRange",
"Solid": "Solide",
"Dotted": "Pointillé",
"Dashed": "En trait",
"Direction": "Orientation",
"Width": "Largeur",
"auto": "auto ",
"fixed": "fixé",
"Set column width": "Définir la largeur des colonnes",
// Unhide Windows
"Unhide workbook": "Afficher le classeur",
// MicroChart Dialog
"Bar": "Barres",
"Dots": "Points",
"Doted Line": "Ligne point.",
"Whisker": "Ligne mince",
"Pie": "Secteurs",
"0..max": "0...max",
"min..max": "min..max",
"user defined": "Personnalisé",
"Select Cell": "Choix de cellule",
"Scaling": "Échelle",
"Source": "Source",
"Target": "Affichage dans",
"Min": "Min",
"Max": "Max",
"pos. values": "Valeurs positives",
"neg. values": "Valeurs négatives",
"win": "Profit",
"tie": "Equivalent",
"lose": "Perte",
"first": "Première",
"last": "Dernière",
"min": "min",
"max": "max",
// Arrange Windows Dialog
"Arrange Windows": "Réorganiser",
"Tiled": "Mosaïque",
"Cascade": "Cascade",
//Open Dialog
"Look in": "Rechercher dans",
"My Recent Documents": "Documents récents",
"My Workbook Documents": "Mes documents",
"Go Up one level": "Dossier parent",
"Adds New folder to the list": "Ajouter un nouveau dossier à la liste",
"File name": "Nom de fichier",
"Files of type": "Type de fichiers",
"Work Sheet Files": "Feuilles de calcul",
"All Files": "Tous les fichiers",
"Save as type": "Type de fichiers",
"Work Sheet Files (*.wss)": "Feuilles de calcul (*.wss)",
"save_as_err_msg": "Le nom du fichier <b>\"{fileName}\"</b> n\'est pas valide. Veuillez entrer un nom valide.",
"Database read error":"Erreur de lecture de base de données",
"read_data_err":"Impossible de lire la base de données. Veuillez actualiser le groupe de dossiers.",
"Database write error":" Erreur d'écriture dans la base de données",
"write_data_err":"Impossible d'écrire dans la base. Veuillez actualiser le groupe de dossiers.",
// Format Col/Row dialog
"Row height": "Hauteur de ligne",
"Column width": "Largeur de colonne",
// Conditional Formatting dialog + Manage Conditional FMT
"Format all cells based on their values": "Mettre en forme toutes les cellules d'après leur valeur",
"Format only cells that contain": "Appliquer une mise en forme uniquement aux cellules avec contenu déterminé",
"Format only top or bottom ranked values": "Appliquer une mise en forme uniquement aux valeurs classées parmi les premières ou les dernières valeurs",
"Format only values that are above or below average": "Appliquer une mise en forme uniquement aux valeurs au-dessus ou en-dessous de la moyenne",
"Format only unique or duplicate values": "Appliquer une mise en forme uniquement aux valeurs uniques ou aux doublons",
"Use a formula to determine which cells to format": "Utiliser une formule pour déterminer pour quelles cellules le format sera appliqué",
"Current Selection": "Sélection actuelle",
"This Worksheet": "Cette feuille de calcul",
"Edit Rule": "Modifier la règle",
"Delete Rule": "Effacer la règle",
"Conditional Formatting Rules Manager": "Gestionnaire des règles de mise en forme conditionnelle",
"Show formatting rules for": "Affiche les règles de mise en page pour",
"Rule (applied in order shown)": "Règle (appliqué de haut en bas)",
"Edit Formatting Rule": "Modifier règle de mise en forme",
"Applies to": "Appliqué à",
"2-Color Scale": "Échelle à deux couleurs",
"3-Color Scale": "Échelle à trois couleurs",
"Lowest value": "Valeur inférieure",
"Percent": "Pourcentage",
"Formula": "Formule",
"Percentile": "Centile",
"Highest value": "Valeur supérieure",
"above": "au-dessus",
"below": "en-dessous",
"equal or above": "égales ou au-dessus",
"equal or below": "égales ou en-dessous",
"1 std dev above": "1 écart-type au-dessus",
"2 std dev above": "2 écarts-type au-dessus",
"3 std dev above": "3 écarts-type au-dessus",
"1 std dev below": "1 écart-type en-dessous",
"2 std dev below": "2 écarts-type en-dessous",
"3 std dev below": "3 écarts-type en-dessous",
"duplicate": "en double",
"unique": "unique",
"Cell Value": "Valeur de la cellule",
"Specific Text": "Texte spécifique",
"Dates Occurring": "Dates se produisant",
"Blanks": "Cellules vides",
"No Blanks": "Aucune cellule vide",
"Errors": "Erreurs",
"No errors": "Aucune erreur",
"between": "Comprise entre",
"not between": "non comprise entre",
"equal to": "égale à",
"not equal to": "différente de",
"greater than": "supérieure à",
"less than": "inférieure à",
"greater than or equal to": "supérieure ou égale à",
"less than or equal to": "inférieure ou égale à",
"containing": "contenant",
"not containing": "ne contenant pas",
"beginning with": "commençant par",
"ending with": "se terminant par",
"Yesterday": "Hier",
"Today": "Aujourd'hui",
"Tomorrow": "Demain",
"In the last 7 days": "Dans les sept derniers jours",
"Last week": "Semaine dernière",
"This week": "Cette semaine",
"Next week": "Semaine prochaine",
"Last month": "Le mois dernier",
"This month": "Ce mois",
"Next month": "Mois prochain",
"Midpoint": "Point central",
"New Formatting Rule": "Nouvelle règle de mise en forme",
"Select a Rule Type": "Sélectionnez un type de règles",
"Edit the Rule Description": "Instructions de règle",
"Stop If True": "Arrêter si vrai",
"Average Value": "Valeur moyenne",
"grater than": "supérieure à",
"Minimum": "Minimum",
"Maximum": "Maximum",
"and": "et",
"Format only cells with": "Appliquer une mise en forme uniquement aux cellules contenant",
"% of the selected range": "% de la plage sélectionnée",
"Format values that rank in the": "Appliquer une mise en forme aux valeurs figurant dans les",
"the average for the selected range": "la moyenne de la plage sélectionnée",
"Format values that are": "Appliquer une mise en forme aux valeurs qui",
"values in the selected range": "Valeurs dans la plage sélectionnée",
"Format all": "Appliquer une mise en forme à toutes",
"Format values where this formula is true": "Appliquer une mise en forme aux valeurs pour lesquelles cette formule est vraie",
// Insert Hyperlink dialog
"Text to display": "Nom du lien",
"E-mail address": "Adresse de messagerie",
"Subject": "Objet",
"Edit the new document later": "Modifier le nouveau document ultérieurement",
"Edit the new document now": "Modifier le nouveau document maintenant",
"Cell Reference": "Référence de cellule",
"Text": "Texte",
"Web Address": "Adresse Web",
"Type the cell reference": "Tapez la référence de la cellule",
"_cell_sheet_reference": "Cible (cellule ou feuille)",
"_error: empty hl name": "Le nom de lien hypertexte (texte à afficher) est vide. Veuillez ajouter un nom.",
"This field is required": "Ce champ est obligatoire",
"Select a place in this document": "Veuillez sélectionnez un emplacement dans le document",
"Name of new document": "Nom du nouveau document",
"When to edit": "Quand modifier",
"Link to": "Lien vers",
"Address": "Adresse",
"Existing File": "Fichier existant",
"Place in This Document": "Emplacement dans ce document",
"Create New Document": "Créer un document",
"Web page": "Page Web",
"E-mail Address": "Adresse de messagerie",
"No images to display": "Pas d'image à afficher",
"Screen tip": "Info bulle",
"Insert Hyperlink": "Insérer un lien hypertexte",
"Selection": "Sélection",
"Named Rang": "Plage nommée",
"Variable": "Variable",
"Constant Value": "Valeur constante",
"Constant List": "Liste constante",
"Variable list": "Liste variable",
"From Cell": "De la cellule",
"Hyperlink Error": "Erreur de lien hypertexte",
"_hl_missing_target_node": "Le document lié n\'existe pas. Il a peut être été déplacé ou supprimé. Veuillez en choisir un autre.",
"_hl_missing_target_sheet_nr":"La feuille liée ou la plage nommée n\'existe pas. Elle a peut être été renommée ou supprimée. Veuillez en choisir une autre.",
"_hl_no_selected_file": "Vous n'avez sélectionné aucun fichier. <br> Veuillez sélectionner un fichier et essayer à nouveau.",
"Transfer": "Transfert",
"Transfer to": "Transfert à",
"Transfer To (Key)": "Transfert à",
"Transfer From (Key)": "Transfert de",
"Transfer From": "Transfert de",
"Named Range": "Plage nommée",
"Update": "Actualiser",
"Picture Hyperlink": "Lien hypertexte d\'une image",
//Insert Picture Dialog
"Select a picture": "Sélectionner une image",
"Photo": "Photo",
"File Name": "Nom du fichier",
"Enter the File name": "Indiquer le nom du fichier.",
"Enter the File description": "Indiquer la description du fichier",
"_lbl: picToImport": "Fichier image pour l'import (uniquement .gif, .jpg, .jpeg et .png possible)",
"Edit Picture": "Modifier l'image",
"Delete Picture": "Supprimer l'image",
"impImg_msgWrongType": "Format d'image non supporté !",
"imgDlg_genError": "L\'import de l\'image n\'est pas possible.",
"imgDlg_deleteError": "Il n'est pas possible de supprimer l'image sélectionnée !",
"Unable to import picture": "L\'import de l\'image n\'est pas possible.",
"imgFile_toBig": "L\'image est trop grande. La taille maximale de l\'image est 2MB.",
"imgFile_unsupportedType": "Format d'image non supporté !",
"imgFile_undefError": "Une erreur inconnue est survenue.",
"Reset": "Annuler",
//Sheet Move OR Copy dialog
"(new book)": "(nouvelle feuille de calcul)",
"(move to end)": "(mettre à la fin)",
"To Book": "Dans la feuille de calcul",
"Before sheet": "Coller avant",
"Move or Copy": "Déplacer/Copier",
"Create a copy": "Créer une copie",
//Rename Sheet Dialog
"New Name": "Nouveau nom",
"informationMsg": "Le nom existe déjà",
"adviceMsg": "Indiquer un nouveau nom",
// Status Bar Localization
"Designer": "Designer",
"User": "Utilisateur",
"QuickView": "Aperçu rapide",
"Ready": "Prêt",
"Mode": "Mode",
//Paste Special Dialog
"All using Source theme": "Tout ce qu'utilise la plage source",
"All except borders": "Tout sauf bordure",
"Column widths": "Largeurs des colonnes",
"Formulas and number": "Formules et nombre",
"Values and number formats": "Valeurs et format de nombres",
"Substract": "Soustraire",
"Multiply": "Multiplier",
"Divide": "Diviser",
"Skip blanks": "Sauter les blancs",
"Transpose": "Transposer",
"Paste Link": "Insérer lien",
"Formulas and number formats": "Formules et formats de nombres",
"Myltiply": "Multiplier",
"Transponse": "Transposer",
"All": "Tous",
"Content Types": "Types de contenu",
"Values": "Valeurs",
"Styles": "Styles",
"Formats": "Formats",
"Conditional Formats": "Format conditionnel",
"Cell Metadata": "Métadonnée de cellule",
"Cancel": "Annuler",
"OK": "OK ",
//Name Manager Dialog
"Value": "Valeur",
"Refers To": "Fait référence à",
"Scope": "Portée",
"Name Manager": "Gérer les noms",
"Edit Name": "Modifier le nom",
"Save Range": "Enregistrer la plage",
"Names Scoped to Worksheet": "Noms limités à cette feuille",
"Names Scoped to Workbook": "Noms limités à ce classeur",
"Names With Errors": "Noms avec erreurs",
"Names Without Errors": "Noms sans erreur",
"Named formula couldn't be created": "La formule nommée n\'a pas pu être créée",
// Hyperlink
"follHLInvalidRef": "Référence non valide",
"follHLTmpDisabledRef": "Référence temporairement désactivée",
"follHLInvalidRng": "Il n'est pas possible d'accéder à l'adresse du lien hypertexte.",
"follHLInvalidSheet": "La feuille de calcul n\'existe pas.",
"follHLNamedRngUnsupport": "Le lien hypertexte contient un lien vers une plage de cellules avec noms - actuellement non supporté.",
"follHLInvalidFormat": "Le format du lien hypertexte est invalide.",
"follHLInvalidWB": "Il n'est pas possible de trouver et d'ouvrir le classeur indiqué par le lien hypertexte.",
"follHLInvalidDoc": "Il n'est pas possible de trouver et d'ouvrir le document indiqué par le lien hypertexte.",
"follHLInvalidURL": "L\'URL du lien hypertexte est invalide.",
"follHLTmpDisabledWB": "Les liens vers d\'autres classeurs ne fonctionnent pas dans ce mode d\'application.",
"follHLTmpDisabledWS": "Les liens vers d\'autres feuilles ne fonctionnent pas dans ce mode d\'application.",
"follHLInvTrgNRange": "Le plage cible nommé n\'existe pas.",
"follHLNotSuppInStandalone": "La cible du lien hypertexte n\'est pas supporté en mode standalone. Il ne peut être utilisés que dans Palo Studio.",
"HLCntxNewWin": "Ouvrir le lien dans une nouvelle fenêtre.",
"HLCntxNewTab": "Ouvrir le lien dans un nouvel onglet.",
"HLCntxRemove": "Supprimer le lien hypertexte",
"HLInvalidRefNotice": "Veuillez modifier pour le faire fonctionner correctement.",
//New Name Dialog
"Workbook": "Classeur",
"newNameDlg_WarningMsg": "Vous n'avez pas correctement indiqué les paramètres. <br>Veuillez corriger les paramètres et essayer à nouveau.",
"newNameDlg_NameWarningMsg": "Le nom indiqué n\'est pas valide.<br><br>La raison peut être :<br> - Le nom commence par une lettre ou un souligné<br> - Le nom contient un espace ou un autre signe non valide<br> - Le nom est en conflit avec le nom d\'un élément de la solution ou avec un autre nom d\'objet dans le classeur",
//Page Setup Dialog
"Header": "En-tête",
"Footer": "Pied de p.",
"Horizontally": "Horizontalement",
"Vertically": "Verticalement",
"Orientation": "Centrer sur la page",
"Custom Header": "En-tête personnalisé",
"Custom Footer": "Pied de page personnalisé",
"Print area": "Zone d'impression",
"Gridlines": "Quadrillage",
"Cell Errors As": "Cellules avec erreurs",
"Down, then over": "Première vers le bas",
"Over, then down": "Première à droite",
"Page order": "Ordre des pages",
"Adjust to": "Taille ",
"Fit to": "Ajuster",
"Page": "Page",
"Margins": "Marges",
"Header/Footer": "En-tête/Pied de page",
"(none)": "(Aucun)",
"Book": "Classeur",
"of": "de",
"Format text": "Format texte",
"Portrait": "Portrait",
"Landscape": "Paysage",
"Paper size": "Format du papier",
"Letter": "Format lettre",
"Print quality": "Qualité d'impression",
"First page": "Commencer la numérotation à",
//Custom Header Footer
"customHFLbl": "Pour formater le texte, sélectionnez le texte et cliquez ensuite sur le bouton Formet texte. <br>"+
"Pour insérer des numéros de page, la date, l'heure, des noms de fichier, des noms de feuille de calcul ou un chemin d'accès, positionnez le curseur dans la barre de traitement et cliquez sur le bouton souhaité.<br>"+
"Pour insérer une image, cliquez sur le bouton Insérer une image. <br><br>",
"Insert Page Number": "Insérer le numéro de page",
"Insert Number of Pages": "Insérer le nombre de pages",
"Insert Date": "Insérer la date",
"Insert Time": "Insérer l'heure",
"Insert File Name": "Insérer le nom du fichier",
"Insert Sheet Name": "Insérer le nom de la feuille de calcul",
"Insert Picture": "Insérer une image",
"Left section": "Section à gauche",
"Center section": "Section au milieu",
"Right section": "Section à droite",
// Suspend Mode
"suspModeMsg": "Le mode de designer est bloqué parce que le mode d\'utilisateur est ouvert dans une fenêtre.<br><br>Pour continuer, veuillez fermez cette fenêtre.",
"Suspend Mode": "Mode en pause",
// Form ComboBox Dialog
"Format ComboBox": "Formater la ComboBox",
"List Type": "Type de liste",
"Palo Subset": "Sous-ensemble Palo",
"Cell": "Cellule",
"Select Wizard type": "Choisissez le type d'assistant",
"WSS_FormComboBox_empty_source": "La source n\'est pas indiquée.",
"WSS_FormComboBox_empty_target": "La destination n\'est pas indiquée.",
"formel_inv_add": "Il n'est pas possible d'insérer l'élement formulaire.",
"formel_exists": "L\'élément \"{nom}\" existe déjà.",
"formel_nrange_exists": "Le nom de la plage cible \"{Nom}\" existe déjà.",
"formel_no_nrange": "Le nom de la plage cible \"{Name}\" n\'existe pas.",
"formel_inv_target": "La cellule cible ou la plage cible non valide.",
"formel_inv_target_sheet": "La feuille cible \"{name}\" n\'existe pas.",
"formel_add_wsel_err": "L\'insertion de l\'élément formulaire à la mémoire WSEl a échoué",
"formel_proc_err": "Erreur de l'élément formulaire",
"formel_edit": "Modifier {type}",
"formel_delete": "Supprimer {type}",
"formel_assign_macro_err": "Impossible d'assigner une macro.",
"formel_no_el": "L\'élément cible n\'a pas été trouvé.",
"ComboBox Name": "Nom de la ComboBox",
"Subset": "Sous-ensemble",
"checkbox_inv_state": "La Check Box a un statut invalide.",
"CheckBox Name": "Nom de la Check Box",
"Unchecked": "Non coché",
"Checked": "Coché",
"Mixed": "Mélangé",
"Format Control": "Contrôle format",
"Checkbox Label": "Libellé de la Check Box",
"Button Label": "Libellé du bouton",
"Button Name": "Nom du bouton",
"Assign Macro": "Assigner une macro",
"Application Error": "Erreur d'application",
"noWBtoSwitch": "Il n'est pas possible de basculer vers la feuille sélectionnée.",
"noWBtoClose": "Il n'est pas possible de de fermer le classeur sélectionné.",
// Load Workbook messages
"errLoadWB_intro": "Il n'est pas possible d'ouvrir le classeur.",
"errLoadWB_noNode": "La connexion n\'a pas été trouvée.",
"errLoadWB_noFile": "Le fichier n\'existe pas.",
"errLoadWB_selErr": "Il n'est pas possible de sélectionner un classeur déjà ouvert.",
"errLoadWB_coreErr": "Le système ne peut pas ouvrir le classeur sélectionné",
"errLoadWB_noRights": "Droits d'accès insuffisants.",
"errLoadWB_cyclicDep": "Cyclic dépendance existe entre le classeur sélectionné et ses ressources.",
// PALO Import Wizard
"PALO Import Wizard": "Assistant d'import Palo",
"impPalo_msgWrongType": "Le chemin d\'accès complet vers le fichier TXT ou CSV doit être présent dans ce champ !",
"impPalo_msgFieldBlank": "Veuillez choisir un fichier !",
"Next": "Suivant",
"Decimalpoint": "Point décimal",
"_msg: Palo Import 1": "Cet assistant va vous permettre de parcourir les enregistrements dans la première ligne de la feuille active.",
"_msg: Palo Import 21": "A cette étape, vous allez indiquer le fichier texte à importer.",
"_msg: Palo Import 3": "Cliquez sur suivant pour voir l'enregistrement suivant ou terminer pour parcourir tous les enregistrements.",
"Select the sourcefile (*.txt, *.csv)": "Choisissez le fichier source (*.txt, *.csv).",
"Flat Textfile (*.txt, *.csv)": "Fichier texte (*.txt, *.csv)",
"ODBC Query": "Requête ODBC",
"Internal Loop (increse A1 until error in B1)": "Boucle interne (augmente A1 jusqu'à provoquer une erreur en B1)",
"Tab": "Tabulation",
"Comma": "Virgule",
"Semicolon": "Point virgule",
"Blank": "Blanc",
"User-defined": "Défini par l'utilisateur",
"Header exists": "En-têtes existants",
"Step by Step": "Pas à pas",
"_msg: PaloImport Wait": "Veuillez patienter, les données sont importées dans la feuille !",
"Importing": "L\'import est en cours",
"Finish": "Terminé",
"_msg: PaloImport Upload": "Les données PALO ont été importées",
"Uploading": "Chargement",
// Function arguments dialog: funcArgs.js
"_error: fnc_desc": "Erreur lors du chargement de la description de la fonction",
"fnc_no_params": "La fonction n\'a pas de paramètres",
"Function Arguments": "Arguments de la fonction",
//Edit Macro
"New Module": "Nouveau module",
"Add New Module": "Ajouter un nouveau module",
"Find": "Rechercher",
"Modules Repository": "Référentiel de Modules",
"Error Renaming Module": "Erreur en renommant le module",
"rename_module_error_msg": "Erreur_renommant_le_module",
"Macro Editor": "Editeur de Macro",
"Rename Module": "Renommer le module",
"Delete Module": "Supprimer le module",
"Module": "Module",
"edit_macro_no_module_selected_err": "edition_macro_erreur_aucun_module_sélectionné",
"Error": "Erreur",
//autoRefresh.js
"Refresh every": "Actualiser toutes les",
"seconds": "secondes",
"Auto Refresh": "Actualisation automatique",
// Autosave
"File not saved": "Le fichier n\'est pas été enregistré",
"autosave_msg": "Voulez-vous enregistrer vos modifications?",
"Open and Repair": "Ouvrir et réparer",
"Size": "Taille ",
"date_format": "d/m/Y H:i:s",
"astype_orig": "Ouvrir le fichier original (Date: {date} / Taille: {size})",
"astype_recov": "Ouvrir le fichier de récupération de la liste:",
"as_msg": "Le classeur n\'a pas été fermé correctement. Comment voulez-vous procéder?",
// Quick Publish
"_QP_unsaved_warning": "Le document non enregistré ne peut pas être publié. Souhaitez-vous enregistrer le document maintenant?",
"_QP_error": "La publication n\'a pas fonctionné. Veuillez essayer de nouveau",
"Report name": "Nom du rapport",
"_QP_double_warning": "Un rapport nommé <b>{rName}</b> existe déjà dans le dossier sélectionné. Veuillez le renommer ou utiliser le nom suggéré.",
"_QP_noSelection": "Veuillez sélectionnez le dossier où le classeur devrait être publié.",
"Group": "Groupe",
"Hierarchy": "Hiérarchie",
"Publish": "Publication",
"_QP_directions": "Choisissez le dossier où vous souhaitez publier le classeur.",
"_QP_success": "Le classeur a été publié avec succès!",
"Report must have name": "Le rapport doit porter un nom",
//ribbon.js
"Home":"Accueil",
"View": "Affichage",
"New<br>document":"Nouveau<br>document",
"Create new document":"Créer un nouveau document",
"Open":"Ouvrir",
"Recent":"Dernières",
"Open document":"Ouvrir un document",
"Save":"Enregistrer",
"Save document":"Enregistrer le document",
"Export":"Export ",
"XLSX":"XLSX ",
"PDF":"PDF ",
"HTML":"HTML ",
"Save As":"Enregistrer sous",
"Save As document":"Enregistrer comme un document",
"Close":"Fermer",
"Operation":"Opération",
"Undo":"Annuler",
"Redo":"Rétablir",
"Clipboard":"Presse-papiers",
"Paste":"Coller",
"Paste Special":"Collage spécial",
"Cut":"Couper",
"Copy":"Copier",
"Format Painter":"Reproduire la mise en forme",
"Bold":"Gras",
"Italic":"Italique",
"Bottom Border":"Bordure inférieure",
"Top Border": "Bordure supérieure",
"Left Border": "Bordure gauche",
"Right Border": "Bordure droite",
"All Borders": "Toutes les bordures",
"Outside Borders": "Bordures extérieures",
"Thick Outside Border": "Bordure extérieure épaisse",
"No Border": "Aucune bordure",
"Top and Bottom Border": "Bordure en haut et en bas",
"Thick Bottom Border": "Bordure épaisse en bas",
"Top and Thick Bottom Border": "Bordure simple en haut et épaisse en bas",
"More Borders": "Plus de bordure",
"Fill Color": "Couleur de remplissage",
"Font Color":"Couleur de police",
"Alignment":"Alignement",
"Left":"À gauche",
"Align Text Left":"Aligner le texte à gauche",
"Center":"Au centre",
"Align Text Center":"Aligner le texte au centre",
"Right":"À droite",
"Merge Cells":"Fusionner les cellules",
"Unmerge Cells":"Annuler la fusion des cellules",
"Cells":"Cellules",
"Insert Rows":"Insérer des lignes",
"Insert Columns":"Insérer des colonnes",
"Insert Sheet":"Insérer une feuille",
"Delete":"Supprimer",
"Delete Sheet":"Supprimer la feuille",
"Format":"Format ",
"AutoFit Row Height":"Ajustement automatique des lignes",
"Column Width":"Largeur de colonne",
"AutoFit Column Width":"Ajustement automatique des colonnes",
"Rename Sheet":"Renommer la feuille",
"Move or Copy Sheet":"Déplacer où copier la feuille",
"Lock<br>Unlock":"Verouillée<br>déverrouillée",
"Conditional<br>Formating":"Mise en forme<br>conditionnelle",
"New Rule":"Nouvelle règle",
"Clear Rules":"Supprimer des règles",
"Clear Rules from Selected Cells":"Supprimer les règles des cellules sélectionnées",
"Clear Rules from Entire Sheet":"Supprimer les règles de la feuille entière",
"Manage Rules":"Gérer les règles",
"Editing":"Modifier",
"Clear All":"Effacer tout",
"Clear Formats":"Effacer le format",
"Clear Contents":"Effacer le contenu",
"Quick View":"Aperçu rapide",
"Designer Preview": "Aperçu Designer",
"User Mode":"Mode d\'utilisateur",
"Open User Mode":"Ouvrir le mode d'utilisateur",
"Insert":"Insertion",
"Ilustrations":"Illustrations",
"Picture":"Image",
"Links":"Liens",
"Hyperlink":"Hyperlien",
"Charts":"Graphiques",
"Chart":"Graphique",
"Micro Chart":"Micrographique",
"Page Layout":"Mise en page",
"Themes":"Thèmes",
"Theme":"Thème",
"Blue (default)":"Bleu (défaut)",
"Gray":"Gris",
"Dark":"Sombre",
"Page Setup":"Mise en page",
"Print<br>Preview":"Aperçu<br>avant impression",
"Formulas":"Formules",
"Function":"Fonction",
"Insert<br>Funciton":"Insérer<br>fonction",
"Defined Names":"Noms définis",
"Name<br> Manager":"Gestion<br>des noms",
"Define Name":"Définir un nom",
"Calculation":"Calcul",
"Refresh<br>Data":"Actualiser les données",
"Auto - Refresh Data":"Actualiser les données automatiquement",
"Show/Hide":"Afficher/Masquer",
"Toolbars":"Barres d'outils",
"Formula Bar":"Barre de formule",
"Status Bar":"Barre d'état",
"Window":"Fenêtre",
"Arrange <br>All":"Réorganiser<br>tous",
"Hide":"Masquer",
"Unhide":"Démasquer",
"Developer":"Développeurs",
"Controls":"Contrôles",
"Macro <br>Editor":"Editeur <br>Macro",
"Combo Box":"Liste Déroulante",
"Check Box":"Case à cocher",
"Button":"Bouton",
"Dyna Ranges":"Dyna_Ranges",
"Horizontal <br> Dyna Range":"Dyna Range <br> Horizontal",
"Vertical <br> Dyna Range":"Dyna Range <br> Vertical",
"Create or Modify Reports":"Créer ou modifier les rapports",
"Paste <br>View":"Créer<br>une vue",
"Paste Elements":"Coller des éléments",
"Paste Subset":"Coller un sous-ensemble",
"Paste Function":"Fonction d'accès aux données",
"Control and Modify Palo":"Contrôler et modifier Palo",
"Modeller":"Outil de modélisation",
"Import Data":"Import de données",
"Save as Snapshot":"Sauvegarder comme instantané",
"Info":"Info",
"Wiki Palo":"Wiki Palo",
"About Palo":"À propos de Palo",
"Open documents": "Ouvrir des documents",
"Help": "Aide",
"_bold": "_gras",
"_italic": "_italique",
"Data labels orientation": "Orientation des étiquettes de données",
"Rotate all text 90": "Rotation 90 du texte",
"Rotate all text 270": "Rotation 270 du texte",
"Custom angle": "Angle spécifique",
"Palo_get_paste_view_init": "La vue collée n\'a pas été correctement stockée. Essayez de la recréer.",
"Vertical Dynarange": "Vertical_DynaRange",
"Horizontal Dynarange": "Horizontal_DynaRange",
"CheckBox": "Case à cocher",
"Variables": "Variables",
"Private": "Privé",
"Current Value": "Valeur Courante",
"Used Variables": "Variables utilisées",
"invalidContext": "L\'application a essayé d\'utiliser un contexte inexistant.",
"Bring Forward": "Déplacer d\'un niveau vers l\'avant",
"Bring to Front": "Déplacer vers l\'avant",
"Please select rule to edit": "Veuillez sélectionner la règle à modifier.",
"Send Backward": "Déplacer d\'un niveau vers l\'arrière",
"Send to Back": "Déplacer vers l\'arrière",
"save_as_override_msg": "Le fichier <b>{fileName}</b> existe déjà. Voulez-vous remplacer le fichier existant?",
"execHLInvRange": "La cellule ou la plage du lien hypertexte n\'est pas valide.",
"#N/A": "#N/A",
"Bold Italic": "Gras Italique",
"Cell/Range": "Cellule//Gamme",
"Control": "Contrôle",
"First": "Première",
"Inside": "A l'intérieur",
"Last": "Dernier",
"Lose": "Perte",
"Micro Chart Type": "Type",
"Neg. Values": "Valeurs nég",
"None": "Aucun",
"Open Recent": "Classeurs dernières",
"Outline": "A l'extérieur",
"Pos. Values": "Valeurs pos.",
"Reference": "Référence",
"Regular": "Régulier",
"Tie": "Équilibre",
"Win": "Profit",
"blank": "Laisser vide",
"displayed": "Imprimer",
"normal size": "de la taille normale",
"page(s) wide by": "page(s) en largeur sur",
"tall": "en hauteur",
"wsel_inv_target": "La cellule cible ou la plage cible n\'est pas valide.",
"wsel_inv_target_sheet": "La feuille cible \"{name}\" n\'existe pas.",
"wsel_nrange_exists": "Le zone cible indiquée \"{name}\" existe déjà.",
"Widgets": "Widgets",
"Custom Widget": "Widget personnalisé",
"widget_exists": "Widget \"{name}\" existe déjà.",
"widget_add_wsel_err": "Adjonction de Widget au stockage WSEl était echoué.",
"widget_edit": "Éditer Widget",
"widget_delete": "Supprimer Widget",
"WSS_Forms_empty_name": "Le nom n\'est pas précisé",
"WSS_Widget_empty_content": "Le contenu des Widgets n\'est pas spécifié. S\'il vous plaît entrez le code HTML ou l\'URL.",
"New name": "Nouveau nom",
"inset_name_err_msg": "La formule nommée n'a pas pu être créé.",
"currCoord_validate_err_msg": "Vous devez entrer une référence valide où vous voulez aller, ou tapez un nom valide pour la sélection.",
"Show borders in User mode": "Afficher les bordures en mode utilisateur.",
"new_folder_name_warrning": "Le nom de dossier <b> {new_name} </b> existe déjà. Type un autre nom pour le dossier.",
"imp_success_msg": "Le fichier a été importé avec succès.",
"Import log": "Journal d\'importation",
"floatingElement_wrongSizePos": "La taille ou la position de l\'élément n\'est pas valide. Veuillez vérifier les valeurs de la taille et de la position dans le cadre.",
"invalid_chart_sizepos": "La taille ou la position du graphique n\'est pas valide. Veuillez entrer des valeurs valides.",
"invalid_picture_size": "La taille ou la position de l\'image n\'est pas valide. Veuillez entrer des valeurs valides.",
"fopperLic": "Le licence pour imprimer PDF.",
"License could not be checked": "La licence n\'a pas pu être vérifiée.",
"License could not be found.": "La licence n\'a pas pu être trouvée.",
"License could not be read.": "La licence n\'a pas pu être lu.",
"License is not valid.": "La licence n\'est pas valide.",
"no_perm_err_msg": "Vous n\'avez pas la permission pour cette opération.",
"Zero suppression": "Omission du zéro",
"Lock": "Verouiller",
"Unlock": "Déverrouiller",
"Vertical DynaRange": "Vertical DynaRange",
"Horizontal DynaRange": "Horizontal DynaRange",
"_error: empty targ name": "La cible du lien hypertexte est vide. Veuillez sélectionner ou entrer cible valide.",
"Select target or <br />input frame name": "Options des trames",
"Format Widget": "Format Widget",
"Widget Name": "Nom de Widget",
"macro_preselection_err_msg": "La macro affectée n\'est pas trouvé.<br>La macro affectée est renommé ou supprimé.<br>Veuillez réaffecter la macro à nouveau!",
"Content": "Contenu",
"errLoadFS_intro": "Impossible de charger le frameset.",
"errLoadFS_noNode": "Impossible de trouver le frameset.",
"Format painter": "Reproduire la mise en forme",
"no_uxpc_err_msg": "Impossible d\'obtenir le privilège du système local.",
"no_file_err_msg": "Impossible d\'accéder à le fichier local.",
"Size & Position": "Taille et position",
"Height": "Hauteur",
"errFrameSave_noAccess": "Impossible d\'enregistrer le classeur \"{name}\" dans le frame \"{frame}\" en raison de\ndroits d\'accès insuffisants.",
"macro_selection_wrg_msg": "Impossible d\'attribuer macro. Votre sélection est vide.<br>Veuillez sélectionner un macro dans la liste, et essayez à nouveau.",
"Show legend": "Afficher la légende",
"Bottom": "Dessous",
"Top Right": "En haut à droite",
"Show the legend without overlapping the chart": "Afficher la légende sans chevauchement du graphique",
"Minimum value is 10": "La valeur minimale est 10",
"Not correct format": "Le format n\'est pas correct",
"min 10": "min 10",
"Target_formElems": "Cible",
"Convert": "Convertir",
"Show log": "Afficher le journal.",
"All Workbook Files": "Tous les classeur.",
"fnArg_multiple": "multiples",
"fnArg_number": "nombre",
"fnArg_sequence": "séquence",
"fnArg_any": "tout",
"fnArg_logical": "logique",
"fnArg_reference": "référence",
"fnArg_text": "texte"
};
| fschaper/netcell | ui/docroot/ui/wss/base/i18n/loc_fr_FR.js | JavaScript | gpl-2.0 | 53,246 |
/*
* @brief ajax
*
* @file Group.js
*
* Copyright (C) 2006-2009 Jedox AG
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License (Version 2) as published
* by the Free Software Foundation at http://www.gnu.org/copyleft/gpl.html.
*
* 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 General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place, Suite 330, Boston, MA 02111-1307 USA
*
* You may obtain a copy of the License at
*
* <a href="http://www.jedox.com/license_palo_bi_suite.txt">
* http://www.jedox.com/license_palo_bi_suite.txt
* </a>
*
* If you are developing and distributing open source applications under the
* GPL License, then you are free to use Palo under the GPL License. For OEMs,
* ISVs, and VARs who distribute Palo with their products, and do not license
* and distribute their source code under the GPL, Jedox provides a flexible
* OEM Commercial License.
*
* \author
* Drazen Kljajic <drazen.kljajic@develabs.com>
*
* \version
* SVN: $Id: CopyRange.js 4776 2011-03-28 14:25:45Z predragm $
*
*/
Jedox.wss.grid.CopyRange = (function ()
{
// private static fields
// private static methods
// class constructor
return function (selection, startPoint, endPoint)
{
Jedox.wss.grid.CopyRange.parent.constructor.call(this, selection, startPoint, endPoint);
// private fields
// private methods
// public fields
// privileged methods
// constructor code
var that = this,
panesLen = this._panes.length,
htmlEl, htmlElCp;
// Init presentation.
// Add html elements for each line in an range:
for(var clsName = 'formularRangeBorder', i = 3; i >= 0; --i) {
htmlEl = document.createElement('div');
htmlEl.className = clsName;
for (var j = panesLen - 1; j >= 0; j--) {
htmlElCp = j > 0 ? htmlEl.cloneNode(true) : htmlEl;
this._edgeElems[j][i] = htmlElCp;
this._containers[j].appendChild(htmlElCp);
}
}
}
}
)();
// CopyRange extends Range
Jedox.util.extend(Jedox.wss.grid.CopyRange, Jedox.wss.grid.Range);
// public static methods
// public methods
clsRef = Jedox.wss.grid.CopyRange;
clsRef = null; | fschaper/netcell | ui/docroot/ui/wss/base/grid/CopyRange.js | JavaScript | gpl-2.0 | 2,491 |
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
/* @api */
define([
'underscore',
'Magento_Checkout/js/view/payment/default',
'Magento_Payment/js/model/credit-card-validation/credit-card-data',
'Magento_Payment/js/model/credit-card-validation/credit-card-number-validator',
'mage/translate'
], function (_, Component, creditCardData, cardNumberValidator, $t) {
'use strict';
return Component.extend({
defaults: {
creditCardType: '',
creditCardExpYear: '',
creditCardExpMonth: '',
creditCardNumber: '',
creditCardSsStartMonth: '',
creditCardSsStartYear: '',
creditCardSsIssue: '',
creditCardVerificationNumber: '',
selectedCardType: null
},
/** @inheritdoc */
initObservable: function () {
this._super()
.observe([
'creditCardType',
'creditCardExpYear',
'creditCardExpMonth',
'creditCardNumber',
'creditCardVerificationNumber',
'creditCardSsStartMonth',
'creditCardSsStartYear',
'creditCardSsIssue',
'selectedCardType'
]);
return this;
},
/**
* Init component
*/
initialize: function () {
var self = this;
this._super();
//Set credit card number to credit card data object
this.creditCardNumber.subscribe(function (value) {
var result;
self.selectedCardType(null);
if (value === '' || value === null) {
return false;
}
result = cardNumberValidator(value);
if (!result.isPotentiallyValid && !result.isValid) {
return false;
}
if (result.card !== null) {
self.selectedCardType(result.card.type);
creditCardData.creditCard = result.card;
}
if (result.isValid) {
creditCardData.creditCardNumber = value;
self.creditCardType(result.card.type);
}
});
//Set expiration year to credit card data object
this.creditCardExpYear.subscribe(function (value) {
creditCardData.expirationYear = value;
});
//Set expiration month to credit card data object
this.creditCardExpMonth.subscribe(function (value) {
creditCardData.expirationMonth = value;
});
//Set cvv code to credit card data object
this.creditCardVerificationNumber.subscribe(function (value) {
creditCardData.cvvCode = value;
});
},
/**
* Get code
* @returns {String}
*/
getCode: function () {
return 'cc';
},
/**
* Get data
* @returns {Object}
*/
getData: function () {
return {
'method': this.item.method,
'additional_data': {
'cc_cid': this.creditCardVerificationNumber(),
'cc_ss_start_month': this.creditCardSsStartMonth(),
'cc_ss_start_year': this.creditCardSsStartYear(),
'cc_ss_issue': this.creditCardSsIssue(),
'cc_type': this.creditCardType(),
'cc_exp_year': this.creditCardExpYear(),
'cc_exp_month': this.creditCardExpMonth(),
'cc_number': this.creditCardNumber()
}
};
},
/**
* Get list of available credit card types
* @returns {Object}
*/
getCcAvailableTypes: function () {
return window.checkoutConfig.payment.ccform.availableTypes[this.getCode()];
},
/**
* Get payment icons
* @param {String} type
* @returns {Boolean}
*/
getIcons: function (type) {
return window.checkoutConfig.payment.ccform.icons.hasOwnProperty(type) ?
window.checkoutConfig.payment.ccform.icons[type]
: false;
},
/**
* Get list of months
* @returns {Object}
*/
getCcMonths: function () {
return window.checkoutConfig.payment.ccform.months[this.getCode()];
},
/**
* Get list of years
* @returns {Object}
*/
getCcYears: function () {
return window.checkoutConfig.payment.ccform.years[this.getCode()];
},
/**
* Check if current payment has verification
* @returns {Boolean}
*/
hasVerification: function () {
return window.checkoutConfig.payment.ccform.hasVerification[this.getCode()];
},
/**
* @deprecated
* @returns {Boolean}
*/
hasSsCardType: function () {
return window.checkoutConfig.payment.ccform.hasSsCardType[this.getCode()];
},
/**
* Get image url for CVV
* @returns {String}
*/
getCvvImageUrl: function () {
return window.checkoutConfig.payment.ccform.cvvImageUrl[this.getCode()];
},
/**
* Get image for CVV
* @returns {String}
*/
getCvvImageHtml: function () {
return '<img src="' + this.getCvvImageUrl() +
'" alt="' + $t('Card Verification Number Visual Reference') +
'" title="' + $t('Card Verification Number Visual Reference') +
'" />';
},
/**
* @deprecated
* @returns {Object}
*/
getSsStartYears: function () {
return window.checkoutConfig.payment.ccform.ssStartYears[this.getCode()];
},
/**
* Get list of available credit card types values
* @returns {Object}
*/
getCcAvailableTypesValues: function () {
return _.map(this.getCcAvailableTypes(), function (value, key) {
return {
'value': key,
'type': value
};
});
},
/**
* Get list of available month values
* @returns {Object}
*/
getCcMonthsValues: function () {
return _.map(this.getCcMonths(), function (value, key) {
return {
'value': key,
'month': value
};
});
},
/**
* Get list of available year values
* @returns {Object}
*/
getCcYearsValues: function () {
return _.map(this.getCcYears(), function (value, key) {
return {
'value': key,
'year': value
};
});
},
/**
* @deprecated
* @returns {Object}
*/
getSsStartYearsValues: function () {
return _.map(this.getSsStartYears(), function (value, key) {
return {
'value': key,
'year': value
};
});
},
/**
* Is legend available to display
* @returns {Boolean}
*/
isShowLegend: function () {
return false;
},
/**
* Get available credit card type by code
* @param {String} code
* @returns {String}
*/
getCcTypeTitleByCode: function (code) {
var title = '',
keyValue = 'value',
keyType = 'type';
_.each(this.getCcAvailableTypesValues(), function (value) {
if (value[keyValue] === code) {
title = value[keyType];
}
});
return title;
},
/**
* Prepare credit card number to output
* @param {String} number
* @returns {String}
*/
formatDisplayCcNumber: function (number) {
return 'xxxx-' + number.substr(-4);
},
/**
* Get credit card details
* @returns {Array}
*/
getInfo: function () {
return [
{
'name': 'Credit Card Type', value: this.getCcTypeTitleByCode(this.creditCardType())
},
{
'name': 'Credit Card Number', value: this.formatDisplayCcNumber(this.creditCardNumber())
}
];
}
});
});
| kunj1988/Magento2 | app/code/Magento/Payment/view/frontend/web/js/view/payment/cc-form.js | JavaScript | gpl-2.0 | 8,982 |
'use strict';
var angular = require('angular');
var angularMessages = require('angular-messages');
var satellizer = require('satellizer');
var material = require('angular-material');
angular.module('sheltrApp', [
require('angular-ui-router'),
require('./controllers'),
require('./services'),
'ngMaterial',
'ngMessages',
'satellizer',
])
.run([
'$animate',
'$rootScope',
'$state',
'$stateParams',
'$auth',
function($animate, $rootScope, $state, $stateParams, $auth) {
$animate.enabled(true);
$rootScope.$state = $state;
$rootScope.$stateParams = $stateParams;
$rootScope.isAuthenticated = function() {
return $auth.isAuthenticated();
};
},
])
.config([
'$stateProvider',
'$authProvider',
'$urlRouterProvider',
function(
$stateProvider,
$authProvider,
$urlRouterProvider) {
$urlRouterProvider.otherwise('/login');
$authProvider.tokenPrefix = 'sheltr';
$authProvider.loginUrl = '/api/authenticate';
function skipIfLoggedIn($q, $auth) {
var deferred = $q.defer();
if ($auth.isAuthenticated()) {
deferred.reject();
} else {
deferred.resolve();
}
return deferred.promise;
}
function loginRequired($q, $location, $auth) {
var deferred = $q.defer();
if ($auth.isAuthenticated()) {
deferred.resolve();
} else {
$location.path('/login');
}
return deferred.promise;
}
function isAuthorized(permission) {
return function($q, $location, $auth) {
var deferred = $q.defer();
var payload = $auth.getPayload();
if (payload[permission]) {
deferred.resolve();
} else {
$location.path('/');
}
return deferred.promise;
};
}
$stateProvider
.state('login', {
url: '/login',
templateUrl: 'views/login.form.html',
controller: 'LoginController',
resolve: {
skipIfLoggedIn: skipIfLoggedIn,
},
})
.state('logout', {
url: '/logout',
template: null,
controller: 'LogoutController',
resolve: {
loginRequired: loginRequired,
},
})
.state('signup', {
url: '/applicants/new',
templateUrl: 'views/applicant.view.html',
controller: 'SignupController',
resolve: {
loginRequired: loginRequired,
},
})
.state('home', {
url: '/',
templateUrl: 'views/home.html',
controller: 'HomeController',
resolve: {
loginRequired: loginRequired,
},
})
.state('applicant', {
url: '/applicants/:id',
templateUrl: 'views/applicant.view.html',
controller: 'ApplicantController',
resolve: {
loginRequired: loginRequired,
},
})
.state('organization', {
url: '/organization',
templateUrl: 'views/org.view.html',
controller: 'OrgController',
resolve: {
adminRequired: isAuthorized('admin'),
},
});
},
]);
| ChrisMcKenzie/sheltr | public/scripts/app.js | JavaScript | gpl-2.0 | 3,328 |
var searchData=
[
['y',['y',['../group___accelerometer_service.html#a58008ae111afcb60b47419541c48aa91',1,'AccelData::y()'],['../group___graphics_types.html#a94afc39fa39df567b9e78702d1f07b3e',1,'GPoint::y()']]],
['year_5funit',['YEAR_UNIT',['../group___wall_time.html#gga0423d00e0eb199de523a92031b5a1107a652f00ea2c629930a32a684f9d8c876d',1,'pebble.h']]]
];
| sdeyerle/pebble_fun | PebbleSDK-2.0-BETA7/Documentation/pebble-api-reference/search/all_79.js | JavaScript | gpl-2.0 | 360 |
/**
* Created by reuben on 10/11/14.
*/
"use strict";
angular.module('crookedFireApp.filters', []).filter('tabsFilter', function () {
return function (tabs, roles) {
var arr = [];
//load public tabs
for (var i = 0; i < tabs.length; i++) {
for (var j = 0; j < tabs[i].roles.length; j++) {
if (tabs[i].roles[j] === '') {
arr.push(tabs[i]);
j = tabs[i].roles.length;
}
if (roles && roles[tabs[i].roles[j]]) {
arr.push(tabs[i]);
j = tabs[i].roles.length;
}
}
}
return arr;
};
});
| Gaurav2Github/MyCrookedFireBase | app/scripts/filters/navigation.fltr.js | JavaScript | gpl-2.0 | 698 |
/**
* Attr: cmTooltip and cmTooltipContent
*/
myApp.directive('cmTooltip', function() {
return function (scope, iElement, iAttrs) {
console.log("appling cm tooltip");
var currentValue = "";
iAttrs.$observe('cmTooltipContent', function(value) {
if(value != currentValue && value != "") {
iElement.tooltip({
"animation": true,
"placement": "top",
"title": value
});
currentValue = value;
}
});
}
}); | Bio-LarK/skeletome-knowledge | sites/all/modules/custom/skeletome_angular/js/directives/cm_tooltip.js | JavaScript | gpl-2.0 | 573 |
$(window).load(function(){FusionCharts.ready(function () {
var cnstrctnPlan = new FusionCharts({
type: 'gantt',
renderAt: 'chart-container',
width: '750',
height: '500',
dataFormat: 'json',
dataSource: {
"chart": {
"caption": "Construction management of a new store in Denver",
"subcaption": "Planned vs Actual",
"dateformat": "dd/mm/yyyy",
"outputdateformat": "ddds mns yy",
"ganttwidthpercent": "60",
"ganttPaneDuration": "40",
"ganttPaneDurationUnit": "d",
"plottooltext": "$processName{br} $label starting date $start{br}$label ending date $end",
"legendBorderAlpha": "0",
"legendShadow": "0",
"usePlotGradientColor": "0",
"showCanvasBorder": "0",
"flatScrollBars": "1",
"gridbordercolor": "#333333",
"gridborderalpha": "20",
"slackFillColor": "#e44a00",
"taskBarFillMix": "light+0"
},
"categories": [
{
"bgcolor": "#999999",
"category": [
{
"start": "1/4/2014",
"end": "30/6/2014",
"label": "Months",
"align": "middle",
"fontcolor": "#ffffff",
"fontsize": "12"
}
]
},
{
"bgcolor": "#999999",
"align": "middle",
"fontcolor": "#ffffff",
"fontsize": "12",
"category": [
{
"start": "1/4/2014",
"end": "30/4/2014",
"label": "April"
},
{
"start": "1/5/2014",
"end": "31/5/2014",
"label": "May"
},
{
"start": "1/6/2014",
"end": "30/6/2014",
"label": "June"
}
]
},
{
"bgcolor": "#ffffff",
"fontcolor": "#333333",
"fontsize": "11",
"align": "center",
"category": [
{
"start": "1/4/2014",
"end": "5/4/2014",
"label": "Week 1"
},
{
"start": "6/4/2014",
"end": "12/4/2014",
"label": "Week 2"
},
{
"start": "13/4/2014",
"end": "19/4/2014",
"label": "Week 3"
},
{
"start": "20/4/2014",
"end": "26/4/2014",
"label": "Week 4"
},
{
"start": "27/4/2014",
"end": "3/5/2014",
"label": "Week 5"
},
{
"start": "4/5/2014",
"end": "10/5/2014",
"label": "Week 6"
},
{
"start": "11/5/2014",
"end": "17/5/2014",
"label": "Week 7"
},
{
"start": "18/5/2014",
"end": "24/5/2014",
"label": "Week 8"
},
{
"start": "25/5/2014",
"end": "31/5/2014",
"label": "Week 9"
},
{
"start": "1/6/2014",
"end": "7/6/2014",
"label": "Week 10"
},
{
"start": "8/6/2014",
"end": "14/6/2014",
"label": "Week 11"
},
{
"start": "15/6/2014",
"end": "21/6/2014",
"label": "Week 12"
},
{
"start": "22/6/2014",
"end": "28/6/2014",
"label": "Week 13"
}
]
}
],
"processes": {
"headertext": "Task",
"fontcolor": "#000000",
"fontsize": "11",
"isanimated": "1",
"bgcolor": "#6baa01",
"headervalign": "bottom",
"headeralign": "left",
"headerbgcolor": "#999999",
"headerfontcolor": "#ffffff",
"headerfontsize": "12",
"align": "left",
"isbold": "1",
"bgalpha": "25",
"process": [
{
"label": "Clear site",
"id": "1"
},
{
"label": "Excavate Foundation",
"id": "2",
"hoverBandColor": "#e44a00",
"hoverBandAlpha": "40"
},
{
"label": "Concrete Foundation",
"id": "3",
"hoverBandColor": "#e44a00",
"hoverBandAlpha": "40"
},
{
"label": "Footing to DPC",
"id": "4",
"hoverBandColor": "#e44a00",
"hoverBandAlpha": "40"
},
{
"label": "Drainage Services",
"id": "5",
"hoverBandColor": "#e44a00",
"hoverBandAlpha": "40"
},
{
"label": "Backfill",
"id": "6",
"hoverBandColor": "#e44a00",
"hoverBandAlpha": "40"
},
{
"label": "Ground Floor",
"id": "7"
},
{
"label": "Walls on First Floor",
"id": "8"
},
{
"label": "First Floor Carcass",
"id": "9",
"hoverBandColor": "#e44a00",
"hoverBandAlpha": "40"
},
{
"label": "First Floor Deck",
"id": "10",
"hoverBandColor": "#e44a00",
"hoverBandAlpha": "40"
},
{
"label": "Roof Structure",
"id": "11"
},
{
"label": "Roof Covering",
"id": "12"
},
{
"label": "Rainwater Gear",
"id": "13"
},
{
"label": "Windows",
"id": "14"
},
{
"label": "External Doors",
"id": "15"
},
{
"label": "Connect Electricity",
"id": "16"
},
{
"label": "Connect Water Supply",
"id": "17",
"hoverBandColor": "#e44a00",
"hoverBandAlpha": "40"
},
{
"label": "Install Air Conditioning",
"id": "18",
"hoverBandColor": "#e44a00",
"hoverBandAlpha": "40"
},
{
"label": "Interior Decoration",
"id": "19",
"hoverBandColor": "#e44a00",
"hoverBandAlpha": "40"
},
{
"label": "Fencing And signs",
"id": "20"
},
{
"label": "Exterior Decoration",
"id": "21",
"hoverBandColor": "#e44a00",
"hoverBandAlpha": "40"
},
{
"label": "Setup racks",
"id": "22"
}
]
},
"datatable": {
"showprocessname": "1",
"namealign": "left",
"fontcolor": "#000000",
"fontsize": "10",
"valign": "right",
"align": "center",
"headervalign": "bottom",
"headeralign": "center",
"headerbgcolor": "#999999",
"headerfontcolor": "#ffffff",
"headerfontsize": "12",
"datacolumn": [
{
"bgcolor": "#eeeeee",
"headertext": "Actual{br}Start{br}Date",
"text": [
{
"label": "9/4/2014"
},
{
"label": "13/4/2014"
},
{
"label": "26/4/2014",
"bgcolor": "#e44a00",
"bgAlpha": "40",
},
{
"label": "4/5/2014",
"bgcolor": "#e44a00",
"bgAlpha": "40"
},
{
"label": "6/5/2014"
},
{
"label": "5/5/2014",
"bgcolor": "#e44a00",
"bgAlpha": "40"
},
{
"label": "11/5/2014"
},
{
"label": "16/5/2014"
},
{
"label": "16/5/2014"
},
{
"label": "21/5/2014",
"bgcolor": "#e44a00",
"bgAlpha": "40"
},
{
"label": "25/5/2014"
},
{
"label": "28/5/2014"
},
{
"label": "4/6/2014"
},
{
"label": "4/6/2014"
},
{
"label": "4/6/2014"
},
{
"label": "2/6/2014"
},
{
"label": "5/6/2014"
},
{
"label": "18/6/2014",
"bgcolor": "#e44a00",
"bgAlpha": "40"
},
{
"label": "16/6/2014",
"bgcolor": "#e44a00",
"bgAlpha": "40"
},
{
"label": "23/6/2014"
},
{
"label": "18/6/2014"
},
{
"label": "25/6/2014"
}
]
},
{
"bgcolor": "#eeeeee",
"headertext": "Actual{br}End{br}Date",
"text": [
{
"label": "12/4/2014"
},
{
"label": "25/4/2014",
"bgcolor": "#e44a00",
"bgAlpha": "40"
},
{
"label": "4/5/2014",
"bgcolor": "#e44a00",
"bgAlpha": "40"
},
{
"label": "10/5/2014"
},
{
"label": "10/5/2014"
},
{
"label": "11/5/2014",
"bgcolor": "#e44a00",
"bgAlpha": "40"
},
{
"label": "14/5/2014"
},
{
"label": "19/5/2014"
},
{
"label": "21/5/2014",
"bgcolor": "#e44a00",
"bgAlpha": "40"
},
{
"label": "24/5/2014",
"bgcolor": "#e44a00",
"bgAlpha": "40"
},
{
"label": "27/5/2014"
},
{
"label": "1/6/2014"
},
{
"label": "6/6/2014"
},
{
"label": "4/6/2014"
},
{
"label": "4/6/2014"
},
{
"label": "7/6/2014"
},
{
"label": "17/6/2014",
"bgcolor": "#e44a00",
"bgAlpha": "40"
},
{
"label": "20/6/2014",
"bgcolor": "#e44a00",
"bgAlpha": "40"
},
{
"label": "23/6/2014"
},
{
"label": "23/6/2014"
},
{
"label": "23/6/2014",
"bgcolor": "#e44a00",
"bgAlpha": "40"
},
{
"label": "28/6/2014"
}
]
}
]
},
"tasks": {
"task": [
{
"label": "Planned",
"processid": "1",
"start": "9/4/2014",
"end": "12/4/2014",
"id": "1-1",
"color": "#008ee4",
"height": "32%",
"toppadding": "12%"
},
{
"label": "Actual",
"processid": "1",
"start": "9/4/2014",
"end": "12/4/2014",
"id": "1",
"color": "#6baa01",
"toppadding": "56%",
"height": "32%"
},
{
"label": "Planned",
"processid": "2",
"start": "13/4/2014",
"end": "23/4/2014",
"id": "2-1",
"color": "#008ee4",
"height": "32%",
"toppadding": "12%"
},
{
"label": "Actual",
"processid": "2",
"start": "13/4/2014",
"end": "25/4/2014",
"id": "2",
"color": "#6baa01",
"toppadding": "56%",
"height": "32%"
},
{
"label": "Delay",
"processid": "2",
"start": "23/4/2014",
"end": "25/4/2014",
"id": "2-2",
"color": "#e44a00",
"toppadding": "56%",
"height": "32%",
"tooltext": "Delayed by 2 days."
},
{
"label": "Planned",
"processid": "3",
"start": "23/4/2014",
"end": "30/4/2014",
"id": "3-1",
"color": "#008ee4",
"height": "32%",
"toppadding": "12%"
},
{
"label": "Actual",
"processid": "3",
"start": "26/4/2014",
"end": "4/5/2014",
"id": "3",
"color": "#6baa01",
"toppadding": "56%",
"height": "32%"
},
{
"label": "Delay",
"processid": "3",
"start": "3/5/2014",
"end": "4/5/2014",
"id": "3-2",
"color": "#e44a00",
"toppadding": "56%",
"height": "32%",
"tooltext": "Delayed by 1 days."
},
{
"label": "Planned",
"processid": "4",
"start": "3/5/2014",
"end": "10/5/2014",
"id": "4-1",
"color": "#008ee4",
"height": "32%",
"toppadding": "12%"
},
{
"label": "Actual",
"processid": "4",
"start": "4/5/2014",
"end": "10/5/2014",
"id": "4",
"color": "#6baa01",
"toppadding": "56%",
"height": "32%"
},
{
"label": "Planned",
"processid": "5",
"start": "6/5/2014",
"end": "11/5/2014",
"id": "5-1",
"color": "#008ee4",
"height": "32%",
"toppadding": "12%"
},
{
"label": "Actual",
"processid": "5",
"start": "6/5/2014",
"end": "10/5/2014",
"id": "5",
"color": "#6baa01",
"toppadding": "56%",
"height": "32%"
},
{
"label": "Planned",
"processid": "6",
"start": "4/5/2014",
"end": "7/5/2014",
"id": "6-1",
"color": "#008ee4",
"height": "32%",
"toppadding": "12%"
},
{
"label": "Actual",
"processid": "6",
"start": "5/5/2014",
"end": "11/5/2014",
"id": "6",
"color": "#6baa01",
"toppadding": "56%",
"height": "32%"
},
{
"label": "Delay",
"processid": "6",
"start": "7/5/2014",
"end": "11/5/2014",
"id": "6-2",
"color": "#e44a00",
"toppadding": "56%",
"height": "32%",
"tooltext": "Delayed by 4 days."
},
{
"label": "Planned",
"processid": "7",
"start": "11/5/2014",
"end": "14/5/2014",
"id": "7-1",
"color": "#008ee4",
"height": "32%",
"toppadding": "12%"
},
{
"label": "Actual",
"processid": "7",
"start": "11/5/2014",
"end": "14/5/2014",
"id": "7",
"color": "#6baa01",
"toppadding": "56%",
"height": "32%"
},
{
"label": "Planned",
"processid": "8",
"start": "16/5/2014",
"end": "19/5/2014",
"id": "8-1",
"color": "#008ee4",
"height": "32%",
"toppadding": "12%"
},
{
"label": "Actual",
"processid": "8",
"start": "16/5/2014",
"end": "19/5/2014",
"id": "8",
"color": "#6baa01",
"toppadding": "56%",
"height": "32%"
},
{
"label": "Planned",
"processid": "9",
"start": "16/5/2014",
"end": "18/5/2014",
"id": "9-1",
"color": "#008ee4",
"height": "32%",
"toppadding": "12%"
},
{
"label": "Actual",
"processid": "9",
"start": "16/5/2014",
"end": "21/5/2014",
"id": "9",
"color": "#6baa01",
"toppadding": "56%",
"height": "32%"
},
{
"label": "Delay",
"processid": "9",
"start": "18/5/2014",
"end": "21/5/2014",
"id": "9-2",
"color": "#e44a00",
"toppadding": "56%",
"height": "32%",
"tooltext": "Delayed by 3 days."
},
{
"label": "Planned",
"processid": "10",
"start": "20/5/2014",
"end": "23/5/2014",
"id": "10-1",
"color": "#008ee4",
"height": "32%",
"toppadding": "12%"
},
{
"label": "Actual",
"processid": "10",
"start": "21/5/2014",
"end": "24/5/2014",
"id": "10",
"color": "#6baa01",
"toppadding": "56%",
"height": "32%"
},
{
"label": "Delay",
"processid": "10",
"start": "23/5/2014",
"end": "24/5/2014",
"id": "10-2",
"color": "#e44a00",
"toppadding": "56%",
"height": "32%",
"tooltext": "Delayed by 1 days."
},
{
"label": "Planned",
"processid": "11",
"start": "25/5/2014",
"end": "27/5/2014",
"id": "11-1",
"color": "#008ee4",
"height": "32%",
"toppadding": "12%"
},
{
"label": "Actual",
"processid": "11",
"start": "25/5/2014",
"end": "27/5/2014",
"id": "11",
"color": "#6baa01",
"toppadding": "56%",
"height": "32%"
},
{
"label": "Planned",
"processid": "12",
"start": "28/5/2014",
"end": "1/6/2014",
"id": "12-1",
"color": "#008ee4",
"height": "32%",
"toppadding": "12%"
},
{
"label": "Actual",
"processid": "12",
"start": "28/5/2014",
"end": "1/6/2014",
"id": "12",
"color": "#6baa01",
"toppadding": "56%",
"height": "32%"
},
{
"label": "Planned",
"processid": "13",
"start": "4/6/2014",
"end": "6/6/2014",
"id": "13-1",
"color": "#008ee4",
"height": "32%",
"toppadding": "12%"
},
{
"label": "Actual",
"processid": "13",
"start": "4/6/2014",
"end": "6/6/2014",
"id": "13",
"color": "#6baa01",
"toppadding": "56%",
"height": "32%"
},
{
"label": "Planned",
"processid": "14",
"start": "4/6/2014",
"end": "4/6/2014",
"id": "14-1",
"color": "#008ee4",
"height": "32%",
"toppadding": "12%"
},
{
"label": "Actual",
"processid": "14",
"start": "4/6/2014",
"end": "4/6/2014",
"id": "14",
"color": "#6baa01",
"toppadding": "56%",
"height": "32%"
},
{
"label": "Planned",
"processid": "15",
"start": "4/6/2014",
"end": "4/6/2014",
"id": "15-1",
"color": "#008ee4",
"height": "32%",
"toppadding": "12%"
},
{
"label": "Actual",
"processid": "15",
"start": "4/6/2014",
"end": "4/6/2014",
"id": "15",
"color": "#6baa01",
"toppadding": "56%",
"height": "32%"
},
{
"label": "Planned",
"processid": "16",
"start": "2/6/2014",
"end": "7/6/2014",
"id": "16-1",
"color": "#008ee4",
"height": "32%",
"toppadding": "12%"
},
{
"label": "Actual",
"processid": "16",
"start": "2/6/2014",
"end": "7/6/2014",
"id": "16",
"color": "#6baa01",
"toppadding": "56%",
"height": "32%"
},
{
"label": "Planned",
"processid": "17",
"start": "5/6/2014",
"end": "10/6/2014",
"id": "17-1",
"color": "#008ee4",
"height": "32%",
"toppadding": "12%"
},
{
"label": "Actual",
"processid": "17",
"start": "5/6/2014",
"end": "17/6/2014",
"id": "17",
"color": "#6baa01",
"toppadding": "56%",
"height": "32%"
},
{
"label": "Delay",
"processid": "17",
"start": "10/6/2014",
"end": "17/6/2014",
"id": "17-2",
"color": "#e44a00",
"toppadding": "56%",
"height": "32%",
"tooltext": "Delayed by 7 days."
},
{
"label": "Planned",
"processid": "18",
"start": "10/6/2014",
"end": "12/6/2014",
"id": "18-1",
"color": "#008ee4",
"height": "32%",
"toppadding": "12%"
},
{
"label": "Delay",
"processid": "18",
"start": "18/6/2014",
"end": "20/6/2014",
"id": "18",
"color": "#e44a00",
"toppadding": "56%",
"height": "32%",
"tooltext": "Delayed by 8 days."
},
{
"label": "Planned",
"processid": "19",
"start": "15/6/2014",
"end": "23/6/2014",
"id": "19-1",
"color": "#008ee4",
"height": "32%",
"toppadding": "12%"
},
{
"label": "Actual",
"processid": "19",
"start": "16/6/2014",
"end": "23/6/2014",
"id": "19",
"color": "#6baa01",
"toppadding": "56%",
"height": "32%"
},
{
"label": "Planned",
"processid": "20",
"start": "23/6/2014",
"end": "23/6/2014",
"id": "20-1",
"color": "#008ee4",
"height": "32%",
"toppadding": "12%"
},
{
"label": "Actual",
"processid": "20",
"start": "23/6/2014",
"end": "23/6/2014",
"id": "20",
"color": "#6baa01",
"toppadding": "56%",
"height": "32%"
},
{
"label": "Planned",
"processid": "21",
"start": "18/6/2014",
"end": "21/6/2014",
"id": "21-1",
"color": "#008ee4",
"height": "32%",
"toppadding": "12%"
},
{
"label": "Actual",
"processid": "21",
"start": "18/6/2014",
"end": "23/6/2014",
"id": "21",
"color": "#6baa01",
"toppadding": "56%",
"height": "32%"
},
{
"label": "Delay",
"processid": "21",
"start": "21/6/2014",
"end": "23/6/2014",
"id": "21-2",
"color": "#e44a00",
"toppadding": "56%",
"height": "32%",
"tooltext": "Delayed by 2 days."
},
{
"label": "Planned",
"processid": "22",
"start": "24/6/2014",
"end": "28/6/2014",
"id": "22-1",
"color": "#008ee4",
"height": "32%",
"toppadding": "12%"
},
{
"label": "Actual",
"processid": "22",
"start": "25/6/2014",
"end": "28/6/2014",
"id": "22",
"color": "#6baa01",
"toppadding": "56%",
"height": "32%"
}
]
},
"connectors": [
{
"connector": [
{
"fromtaskid": "1",
"totaskid": "2",
"color": "#008ee4",
"thickness": "2",
"fromtaskconnectstart_": "1"
},
{
"fromtaskid": "2-2",
"totaskid": "3",
"color": "#008ee4",
"thickness": "2"
},
{
"fromtaskid": "3-2",
"totaskid": "4",
"color": "#008ee4",
"thickness": "2"
},
{
"fromtaskid": "3-2",
"totaskid": "6",
"color": "#008ee4",
"thickness": "2"
},
{
"fromtaskid": "7",
"totaskid": "8",
"color": "#008ee4",
"thickness": "2"
},
{
"fromtaskid": "7",
"totaskid": "9",
"color": "#008ee4",
"thickness": "2"
},
{
"fromtaskid": "12",
"totaskid": "16",
"color": "#008ee4",
"thickness": "2"
},
{
"fromtaskid": "12",
"totaskid": "17",
"color": "#008ee4",
"thickness": "2"
},
{
"fromtaskid": "17-2",
"totaskid": "18",
"color": "#008ee4",
"thickness": "2"
},
{
"fromtaskid": "19",
"totaskid": "22",
"color": "#008ee4",
"thickness": "2"
}
]
}
],
"milestones": {
"milestone": [
{
"date": "2/6/2014",
"taskid": "12",
"color": "#f8bd19",
"shape": "star",
"tooltext": "Completion of Phase 1"
}
/*{
"date": "21/8/2008",
"taskid": "10",
"color": "#f8bd19",
"shape": "star",
"tooltext": "New estimated moving date"
}*/
]
},
"legend": {
"item": [
{
"label": "Planned",
"color": "#008ee4"
},
{
"label": "Actual",
"color": "#6baa01"
},
{
"label": "Slack (Delay)",
"color": "#e44a00"
}
]
}
}
})
.render();
});}); | sguha-work/fiddletest | fiddles/Chart/Gantt-Chart/A-sample-Gantt-chart-_45/demo.js | JavaScript | gpl-2.0 | 42,182 |
// requestAnim shim layer by Paul Irish
window.requestAnimFrame = (function(){
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function(/* function */ callback, /* DOMElement */ element){
window.setTimeout(callback, 1000 / 60);
};
})();
// example code from mr doob : http://mrdoob.com/lab/javascript/requestanimationframe/
//var canvas = document.getElementById("myCanvas");
//var context = canvas.getContext("2d");
var canvas, context, toggle;
var y= 220;
var x= 284;
var y2=-10;
var x2= 10;
var y3=-10;
var x3= 400;
var mid = 128;
var dirX = 1;
var dirY = 1;
var destX ;
var destY ;
var i;
var state ;
var inbounds='true';
var status = -1; // -1: stopped , 0 In play
var imageObj = new Image();
var imageObj2 = new Image();
var imageObj3 = new Image();
var background_obj= new Image();
background_obj.src = "deep-space.jpg";
imageObj.src = "spshipsprite.png";
imageObj2.src = "spacestation.png";
imageObj3.src = "blueship4.png";
var jump = 'rest';
var backg_x = 0;
var backg_y = 0;
var floating =false;
var degrees = 0;
var str;
var name;
//init();
var dir = 1;
var monster = {};
var origin = {};
// Bullet image
var bulletReady = false;
var bulletImage = new Image();
bulletImage.onload = function () {
//bulletReady = true;
};
bulletImage.src = "images/bullet.png";
var bullet = {
speed: 256 // movement in pixels per second
};
//function init() {
canvas = document.createElement( 'canvas' );
canvas.width = 568;
canvas.height = 400;
context = canvas.getContext( '2d' );
//context.font = "40pt Calibri";
//context.fillStyle = "white";
// align text horizontally center
context.textAlign = "center";
// align text vertically center
context.textBaseline = "middle";
//context.font = "12pt Calibri";
//canvas.width = 8248;
context.drawImage(background_obj, backg_x, backg_y);
//imageData = context.getImageData(0,0,8248,400); //fnord
//var x = document;
// canvas.width = 568;
$( "#container" ).append( canvas );
//}
animate();
// shoot addition
var shoot = function(modifier){
if (dir==1){
bullet.y -= bullet.speed * modifier * 4;
}
if (dir==2){
bullet.y += bullet.speed * modifier * 4;
}
if (dir==3){
bullet.x -= bullet.speed * modifier * 4;
}
if (dir==4){
bullet.x += bullet.speed * modifier * 4;
}
// Are they touching2?
if (
bullet.x <= (monster.x + 32)
&& monster.x <= (bullet.x + 32)
&& hero.y <= (bullet.y + 32)
&& monster.y <= (bullet.y + 32)
) {
++monstersShot;
reset();
}
//distance = square root sqrt of ( (x2-x1)^2 + (y2-y1)^2)
var distance = Math.sqrt( Math.pow(bullet.x-origin.x, 2) + Math.pow(bullet.y - origin.y,2) );
if (distance > 200)
{
bulletReady = false;
first = true
}
}
if (bulletReady) {
context.drawImage(bulletImage, bullet.x, bullet.y);
}
// shoot addition
function shoot()
{
if (dir==1){
bullet.y -= bullet.speed * 4;
}
if (dir==2){
bullet.y += bullet.speed * 4;
}
if (dir==3){
bullet.x -= bullet.speed * 4;
}
if (dir==4){
bullet.x += bullet.speed * 4;
}
//distance = square root sqrt of ( (x2-x1)^2 + (y2-y1)^2)
var distance = Math.sqrt( Math.pow(bullet.x - x, 2) + Math.pow(bullet.y - y,2) );
if (distance > 200)
{
bulletReady = false;
first = true
}
}
function animate() {
update();
requestAnimFrame( animate );
shoot();
draw();
}
function update() {
y2++;
x2++;
y3++;
x3--;
if (y2==400)
{
y2=0;
}
if (x2==598)
{
x2=0;
}
if (y3==400)
{
y3=0;
}
if (x3==0)
{
x3=598;
}
}
function draw() {
context.fillText( state + ":" , canvas.width / 2 , canvas.height / 2 );
$(document).keyup(function(e)
{
if (e.keyCode == 37)
{
state= "stop";
dirX=1;
dir=3;
}
if (e.keyCode == 39)
{
state= "stop";
dirX=1;
dir=4;
}
if (e.keyCode == 38)
{
jump = 'descend';
}
});
$(document).keydown(function(e) {
//alert (e.keyCode);
//if space start/stop gameloop
//var time = new Date().getTime() * 0.002;
if(e.keyCode == 32)
{
status = 0 - status;
bulletReady = true;
bullet.x = x;
bullet.y = y;
}
// if (jump != 'descend')
// {
if (e.keyCode == 38 )
{
jump = 'ascend';
}
// }
if (e.keyCode == 40){
// down
}
if (e.keyCode == 37){
state = 'left';
}
if (e.keyCode == 39){
state = 'right';
}
});
///////////////////////////////////////////////////////////////////////////////
if (state == 'left')
{
//x = x-(1 * dirX);
// backg_x = backg_x + 1 ;
degrees = degrees - 1;
// context.setTransform(1,0.5,-0.5,10,10);
}
if (state == 'right')
{
//x = x + (1 * dirX);
// backg_x = backg_x - 1 ;
degrees = degrees +1 ;
// context.setTransform(1,0.5,-0.5,1,10,10);
}
if (jump == 'ascend')
{
}
if (jump == 'descend')
{
y = y - 1;
if (y == 0)
{
jump = 'rest';
}
}
if (jump == 'rest')
{
y = 0;
dirY = -1;
}
if (inbounds=='true')
{
// destX = (canvas.width / 2 ) + x;
// destY = canvas.height - 30 - y ;// 60 pixels offset from centre
}//end if inbounds
if (destX > canvas.width || destX < 0)
{
// dirX =-dirX;
}
if (destY > canvas.width || destY < 0)
{
// dirY =-dirY;
}
//canvas.width = 8248;
context.clearRect(0,0 , canvas.width, canvas.height);
context.drawImage(background_obj, backg_x, backg_y);
context.save();
context.beginPath();
context.translate( 290,210 );
// rotate the rect
context.rotate(degrees*Math.PI/180);
context.drawImage(imageObj, -37, -50);
context.restore();
context.drawImage(imageObj2, x2, y2);
context.drawImage(imageObj3, x3, y3);
str = "width=" + imageData.width + " height=" + imageData.height
+ " red :" + red + " green :" + green + " blue :" + blue
+ " destX :" + parseInt(0-backg_x) + " destY :" +destY
+ " inbounds:" + inbounds
+ " float: " + floating + " jump : " + jump;
context.fillText(str, 20, 14);
str2 = "x: " + x + "y :" + y;
context.fillText(str2, 20, 34);
context.fillStyle = 'white';
}
| Techbot/Techbot.github.io | template013/script.js | JavaScript | gpl-2.0 | 6,656 |
/* ************************************************************************
qooxdoo - the new era of web development
http://qooxdoo.org
Copyright:
2004-2008 1&1 Internet AG, Germany, http://www.1und1.de
License:
LGPL: http://www.gnu.org/licenses/lgpl.html
EPL: http://www.eclipse.org/org/documents/epl-v10.php
See the LICENSE file in the project's top-level directory for details.
Authors:
* Sebastian Werner (wpbasti)
* Andreas Ecker (ecker)
************************************************************************ */
/**
* @appearance toolbar-button
*/
qx.Class.define("qx.legacy.ui.toolbar.Button",
{
extend : qx.legacy.ui.form.Button,
/*
*****************************************************************************
PROPERTIES
*****************************************************************************
*/
properties :
{
// Omit focus
tabIndex :
{
refine : true,
init : -1
},
appearance :
{
refine : true,
init : "toolbar-button"
},
show :
{
refine : true,
init : "inherit"
},
height :
{
refine : true,
init : null
},
allowStretchY :
{
refine : true,
init : true
}
},
/*
*****************************************************************************
MEMBERS
*****************************************************************************
*/
members :
{
/*
---------------------------------------------------------------------------
EVENT HANDLER
---------------------------------------------------------------------------
*/
/**
* @signature function()
*/
_onkeydown : qx.lang.Function.returnTrue,
/**
* @signature function()
*/
_onkeyup : qx.lang.Function.returnTrue
}
});
| omid/webian | usr/qx/sdk/framework/source/class/qx/legacy/ui/toolbar/Button.js | JavaScript | gpl-2.0 | 1,870 |
var Traverse = require('.');
var assert = require('assert');
exports['negative update test'] = function () {
var obj = [ 5, 6, -3, [ 7, 8, -2, 1 ], { f : 10, g : -13 } ];
var fixed = Traverse.map(obj, function (x) {
if (x < 0) this.update(x + 128);
});
assert.deepEqual(fixed,
[ 5, 6, 125, [ 7, 8, 126, 1 ], { f: 10, g: 115 } ],
'Negative values += 128'
);
assert.deepEqual(obj,
[ 5, 6, -3, [ 7, 8, -2, 1 ], { f: 10, g: -13 } ],
'Original references not modified'
);
}
| daslicht/TimberExperiments | mat/timber-starter-theme_/node_modules/grunt-contrib-nodeunit/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/node_modules/traverse/test/negative.js | JavaScript | gpl-2.0 | 549 |
/**
* @package JCE
* @copyright Copyright (c) 2009-2015 Ryan Demmer. All rights reserved.
* @license GNU/GPL 2 or later - http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
* JCE is free software. This version may have been modified pursuant
* to the GNU General Public License, and as distributed it includes or
* is derivative of works licensed under the GNU General Public License or
* other free or open source software licenses.
*/
(function(){
tinymce.create('tinymce.plugins.Browser', {
init: function(ed, url){
this.ed = ed;
},
browse: function(name, url, type, win){
var ed = this.ed;
ed.windowManager.open({
file: ed.getParam('site_url') + 'index.php?option=com_jce&view=editor&layout=plugin&plugin=browser&type=' + type,
width : 780 + ed.getLang('browser.delta_width', 0),
height : 480 + ed.getLang('browser.delta_height', 0),
resizable: "yes",
inline: "yes",
close_previous: "no",
popup_css : false
}, {
window: win,
input: name,
url: url,
type: type
});
return false;
},
getInfo: function(){
return {
longname: 'Browser',
author: 'Ryan Demmer',
authorurl: 'http://www.joomlacontenteditor.net',
infourl: 'http://www.joomlacontenteditor.net/index.php?option=com_content&view=article&task=findkey&tmpl=component&lang=en&keyref=browser.about',
version: '@@version@@'
};
}
});
// Register plugin
tinymce.PluginManager.add('browser', tinymce.plugins.Browser);
})(); | widgetfactory/jce-editor | editor/tiny_mce/plugins/browser/editor_plugin.js | JavaScript | gpl-2.0 | 1,889 |
var FileChooser = function(config)
{
// Setup a variable for the current directory
this.current_directory;
/* ---- Begin side_navbar tree --- */
this.tree = new Ext.tree.TreePanel(
{
region: 'west',
width: 150,
minSize: 150,
maxSize: 250,
animate: true,
loader: new Ext.tree.TreeLoader({dataUrl: 'tree_data.json.php' }),
enableDD: true,
containerScroll: true,
rootVisible:true,
root: new Ext.tree.AsyncTreeNode(
{
text: 'Files',
draggable: false,
id: 'source',
expanded: true
}),
listeners:
{
scope: this,
'click': function(node, e)
{
current_directory = node.attributes.url;
this.ds.load({ params: {directory: node.attributes.url}});
}
}
});
// Add a tree sorter in folder mode
new Ext.tree.TreeSorter(this.tree, {folderSort: true});
/* ---- End side_navbar tree --- */
/* ---- Begin grid --- */
this.ds = new Ext.data.GroupingStore(
{
url: 'js/grid_data.json.php',
method: 'POST',
autoLoad: true,
sortInfo: {field: 'name', direction: 'ASC'},
reader: new Ext.data.JsonReader(
{
root: 'data',
totalProperty: 'count'
},
[
{name: 'name'},
{name: 'size', type: 'float'},
{name: 'type'},
{name: 'relative_path'},
{name: 'full_path'},
{name: 'web_path'}
])
});
this.cm = new Ext.grid.ColumnModel(
[
{header: 'Name', dataIndex: 'name', sortable: true},
{header: 'Size', dataIndex: 'size', sortable: true, renderer: Ext.util.Format.fileSize},
{header: 'Type', dataIndex: 'type', sortable: true},
{header: 'Relative Path', dataIndex: 'relative_path', sortable: true, hidden: true},
{header: 'Full Path', dataIndex: 'full_path', sortable: true, hidden: true},
{header: 'Web Path', dataIndex: 'web_path', sortable: true, hidden: true}
]);
this.grid = new Ext.grid.GridPanel(
{
region: 'center',
border: false,
view: new Ext.grid.GroupingView(
{
emptyText: 'This folder contains no files.',
forceFit: true,
showGroupName: false,
enableNoGroups: true
}),
ds: this.ds,
cm: this.cm,
listeners:
{
scope: this,
'rowdblclick': this.doCallback
}
});
/* ---- End grid --- */
/* ---- Begin window --- */
this.popup = new Ext.Window(
{
id: 'FileChooser',
title: 'Choose A File',
width: config.width,
height: config.height,
minWidth: config.width,
minHeight: config.height,
layout: 'border',
items: [ this.tree, this.grid ],
buttons: [
{
text: 'Ok',
scope: this,
handler: this.doCallback
},
{
text: 'Cancel',
scope: this,
handler: function()
{
this.popup.hide();
}
}]
});
/* ---- End window --- */
};
FileChooser.prototype =
{
show : function(el, callback)
{
if (Ext.type(el) == 'object')
this.showEl = el.getEl();
else
this.showEl = el;
this.el = el;
this.popup.show(this.showEl);
this.callback = callback;
},
doCallback : function()
{
var row = this.grid.getSelectionModel().getSelected();
var callback = this.callback;
var el = this.el;
this.popup.close();
if (row && callback)
{
var data = row.data.web_path;
callback(el, data);
}
}
};
function FileBrowser(fieldName, url, win)
{
var chooser = new FileChooser({width: 500, height:400});
chooser.show(fieldName, function(el, data)
{
win.document.getElementById(el).value = data;
});
} | vyos/vyatta-webgui | src/client/Vyatta/utils/vyatta-filechooser.js | JavaScript | gpl-2.0 | 4,309 |
;(function ($, window) {
var intervals = {};
var removeListener = function(selector) {
if (intervals[selector]) {
window.clearInterval(intervals[selector]);
intervals[selector] = null;
}
};
var found = 'waitUntilExists.found';
/**
* @function
* @property {object} jQuery plugin which runs handler function once specified
* element is inserted into the DOM
* @param {function|string} handler
* A function to execute at the time when the element is inserted or
* string "remove" to remove the listener from the given selector
* @param {bool} shouldRunHandlerOnce
* Optional: if true, handler is unbound after its first invocation
* @example jQuery(selector).waitUntilExists(function);
*/
$.fn.waitUntilExists = function(handler, shouldRunHandlerOnce, isChild) {
var selector = this.selector;
var $this = $(selector);
var $elements = $this.not(function() { return $(this).data(found); });
if (handler === 'remove') {
// Hijack and remove interval immediately if the code requests
removeListener(selector);
}
else {
// Run the handler on all found elements and mark as found
$elements.each(handler).data(found, true);
if (shouldRunHandlerOnce && $this.length) {
// Element was found, implying the handler already ran for all
// matched elements
removeListener(selector);
}
else if (!isChild) {
// If this is a recurring search or if the target has not yet been
// found, create an interval to continue searching for the target
intervals[selector] = window.setInterval(function () {
$this.waitUntilExists(handler, shouldRunHandlerOnce, true);
}, 500);
}
}
return $this;
};
}(jQuery, window)); | chikato/TND | wp-content/plugins/smart-social-media-widget/js/jquery.waituntilexists.js | JavaScript | gpl-2.0 | 1,735 |
/*! lightgallery - v1.2.15 - 2016-03-10
* http://sachinchoolur.github.io/lightGallery/
* Copyright (c) 2016 Sachin N; Licensed Apache 2.0 */
(function($, window, document, undefined) {
'use strict';
var defaults = {
thumbnail: true,
animateThumb: true,
currentPagerPosition: 'middle',
thumbWidth: 100,
thumbContHeight: 100,
thumbMargin: 5,
exThumbImage: false,
showThumbByDefault: true,
toogleThumb: true,
pullCaptionUp: true,
enableThumbDrag: true,
enableThumbSwipe: true,
swipeThreshold: 50,
loadYoutubeThumbnail: true,
youtubeThumbSize: 1,
loadVimeoThumbnail: true,
vimeoThumbSize: 'thumbnail_small',
loadDailymotionThumbnail: true
};
var Thumbnail = function(element) {
// get lightGallery core plugin data
this.core = $(element).data('lightGallery');
// extend module default settings with lightGallery core settings
this.core.s = $.extend({}, defaults, this.core.s);
this.$el = $(element);
this.$thumbOuter = null;
this.thumbOuterWidth = 0;
this.thumbTotalWidth = (this.core.$items.length * (this.core.s.thumbWidth + this.core.s.thumbMargin));
this.thumbIndex = this.core.index;
// Thumbnail animation value
this.left = 0;
this.init();
return this;
};
Thumbnail.prototype.init = function() {
var _this = this;
if (this.core.s.thumbnail && this.core.$items.length > 1) {
if (this.core.s.showThumbByDefault) {
setTimeout(function(){
_this.core.$outer.addClass('lg-thumb-open');
}, 700);
}
if (this.core.s.pullCaptionUp) {
this.core.$outer.addClass('lg-pull-caption-up');
}
this.build();
if (this.core.s.animateThumb) {
if (this.core.s.enableThumbDrag && !this.core.isTouch && this.core.doCss()) {
this.enableThumbDrag();
}
if (this.core.s.enableThumbSwipe && this.core.isTouch && this.core.doCss()) {
this.enableThumbSwipe();
}
this.thumbClickable = false;
} else {
this.thumbClickable = true;
}
this.toogle();
this.thumbkeyPress();
}
};
Thumbnail.prototype.build = function() {
var _this = this;
var thumbList = '';
var vimeoErrorThumbSize = '';
var $thumb;
var html = '<div class="lg-thumb-outer">' +
'<div class="lg-thumb group">' +
'</div>' +
'</div>';
switch (this.core.s.vimeoThumbSize) {
case 'thumbnail_large':
vimeoErrorThumbSize = '640';
break;
case 'thumbnail_medium':
vimeoErrorThumbSize = '200x150';
break;
case 'thumbnail_small':
vimeoErrorThumbSize = '100x75';
}
_this.core.$outer.addClass('lg-has-thumb');
_this.core.$outer.find('.lg').append(html);
_this.$thumbOuter = _this.core.$outer.find('.lg-thumb-outer');
_this.thumbOuterWidth = _this.$thumbOuter.width();
if (_this.core.s.animateThumb) {
_this.core.$outer.find('.lg-thumb').css({
width: _this.thumbTotalWidth + 'px',
position: 'relative'
});
}
if (this.core.s.animateThumb) {
_this.$thumbOuter.css('height', _this.core.s.thumbContHeight + 'px');
}
function getThumb(src, thumb, index) {
var isVideo = _this.core.isVideo(src, index) || {};
var thumbImg;
var vimeoId = '';
if (isVideo.youtube || isVideo.vimeo || isVideo.dailymotion) {
if (isVideo.youtube) {
if (_this.core.s.loadYoutubeThumbnail) {
thumbImg = '//img.youtube.com/vi/' + isVideo.youtube[1] + '/' + _this.core.s.youtubeThumbSize + '.jpg';
} else {
thumbImg = thumb;
}
} else if (isVideo.vimeo) {
if (_this.core.s.loadVimeoThumbnail) {
thumbImg = '//i.vimeocdn.com/video/error_' + vimeoErrorThumbSize + '.jpg';
vimeoId = isVideo.vimeo[1];
} else {
thumbImg = thumb;
}
} else if (isVideo.dailymotion) {
if (_this.core.s.loadDailymotionThumbnail) {
thumbImg = '//www.dailymotion.com/thumbnail/video/' + isVideo.dailymotion[1];
} else {
thumbImg = thumb;
}
}
} else {
thumbImg = thumb;
}
thumbList += '<div data-vimeo-id="' + vimeoId + '" class="lg-thumb-item" style="width:' + _this.core.s.thumbWidth + 'px; margin-right: ' + _this.core.s.thumbMargin + 'px"><img src="' + thumbImg + '" /></div>';
vimeoId = '';
}
if (_this.core.s.dynamic) {
for (var i = 0; i < _this.core.s.dynamicEl.length; i++) {
getThumb(_this.core.s.dynamicEl[i].src, _this.core.s.dynamicEl[i].thumb, i);
}
} else {
_this.core.$items.each(function(i) {
if (!_this.core.s.exThumbImage) {
getThumb($(this).attr('href') || $(this).attr('data-src'), $(this).find('img').attr('src'), i);
} else {
getThumb($(this).attr('href') || $(this).attr('data-src'), $(this).attr(_this.core.s.exThumbImage), i);
}
});
}
_this.core.$outer.find('.lg-thumb').html(thumbList);
$thumb = _this.core.$outer.find('.lg-thumb-item');
// Load vimeo thumbnails
$thumb.each(function() {
var $this = $(this);
var vimeoVideoId = $this.attr('data-vimeo-id');
if (vimeoVideoId) {
$.getJSON('//www.vimeo.com/api/v2/video/' + vimeoVideoId + '.json?callback=?', {
format: 'json'
}, function(data) {
$this.find('img').attr('src', data[0][_this.core.s.vimeoThumbSize]);
});
}
});
// manage active class for thumbnail
$thumb.eq(_this.core.index).addClass('active');
_this.core.$el.on('onBeforeSlide.lg.tm', function() {
$thumb.removeClass('active');
$thumb.eq(_this.core.index).addClass('active');
});
$thumb.on('click.lg touchend.lg', function() {
var _$this = $(this);
setTimeout(function() {
// In IE9 and bellow touch does not support
// Go to slide if browser does not support css transitions
if ((_this.thumbClickable && !_this.core.lgBusy) || !_this.core.doCss()) {
_this.core.index = _$this.index();
_this.core.slide(_this.core.index, false, true);
}
}, 50);
});
_this.core.$el.on('onBeforeSlide.lg.tm', function() {
_this.animateThumb(_this.core.index);
});
$(window).on('resize.lg.thumb orientationchange.lg.thumb', function() {
setTimeout(function() {
_this.animateThumb(_this.core.index);
_this.thumbOuterWidth = _this.$thumbOuter.width();
}, 200);
});
};
Thumbnail.prototype.setTranslate = function(value) {
// jQuery supports Automatic CSS prefixing since jQuery 1.8.0
this.core.$outer.find('.lg-thumb').css({
transform: 'translate3d(-' + (value) + 'px, 0px, 0px)'
});
};
Thumbnail.prototype.animateThumb = function(index) {
var $thumb = this.core.$outer.find('.lg-thumb');
if (this.core.s.animateThumb) {
var position;
switch (this.core.s.currentPagerPosition) {
case 'left':
position = 0;
break;
case 'middle':
position = (this.thumbOuterWidth / 2) - (this.core.s.thumbWidth / 2);
break;
case 'right':
position = this.thumbOuterWidth - this.core.s.thumbWidth;
}
this.left = ((this.core.s.thumbWidth + this.core.s.thumbMargin) * index - 1) - position;
if (this.left > (this.thumbTotalWidth - this.thumbOuterWidth)) {
this.left = this.thumbTotalWidth - this.thumbOuterWidth;
}
if (this.left < 0) {
this.left = 0;
}
if (this.core.lGalleryOn) {
if (!$thumb.hasClass('on')) {
this.core.$outer.find('.lg-thumb').css('transition-duration', this.core.s.speed + 'ms');
}
if (!this.core.doCss()) {
$thumb.animate({
left: -this.left + 'px'
}, this.core.s.speed);
}
} else {
if (!this.core.doCss()) {
$thumb.css('left', -this.left + 'px');
}
}
this.setTranslate(this.left);
}
};
// Enable thumbnail dragging and swiping
Thumbnail.prototype.enableThumbDrag = function() {
var _this = this;
var startCoords = 0;
var endCoords = 0;
var isDraging = false;
var isMoved = false;
var tempLeft = 0;
_this.$thumbOuter.addClass('lg-grab');
_this.core.$outer.find('.lg-thumb').on('mousedown.lg.thumb', function(e) {
if (_this.thumbTotalWidth > _this.thumbOuterWidth) {
// execute only on .lg-object
e.preventDefault();
startCoords = e.pageX;
isDraging = true;
// ** Fix for webkit cursor issue https://code.google.com/p/chromium/issues/detail?id=26723
_this.core.$outer.scrollLeft += 1;
_this.core.$outer.scrollLeft -= 1;
// *
_this.thumbClickable = false;
_this.$thumbOuter.removeClass('lg-grab').addClass('lg-grabbing');
}
});
$(window).on('mousemove.lg.thumb', function(e) {
if (isDraging) {
tempLeft = _this.left;
isMoved = true;
endCoords = e.pageX;
_this.$thumbOuter.addClass('lg-dragging');
tempLeft = tempLeft - (endCoords - startCoords);
if (tempLeft > (_this.thumbTotalWidth - _this.thumbOuterWidth)) {
tempLeft = _this.thumbTotalWidth - _this.thumbOuterWidth;
}
if (tempLeft < 0) {
tempLeft = 0;
}
// move current slide
_this.setTranslate(tempLeft);
}
});
$(window).on('mouseup.lg.thumb', function() {
if (isMoved) {
isMoved = false;
_this.$thumbOuter.removeClass('lg-dragging');
_this.left = tempLeft;
if (Math.abs(endCoords - startCoords) < _this.core.s.swipeThreshold) {
_this.thumbClickable = true;
}
} else {
_this.thumbClickable = true;
}
if (isDraging) {
isDraging = false;
_this.$thumbOuter.removeClass('lg-grabbing').addClass('lg-grab');
}
});
};
Thumbnail.prototype.enableThumbSwipe = function() {
var _this = this;
var startCoords = 0;
var endCoords = 0;
var isMoved = false;
var tempLeft = 0;
_this.core.$outer.find('.lg-thumb').on('touchstart.lg', function(e) {
if (_this.thumbTotalWidth > _this.thumbOuterWidth) {
e.preventDefault();
startCoords = e.originalEvent.targetTouches[0].pageX;
_this.thumbClickable = false;
}
});
_this.core.$outer.find('.lg-thumb').on('touchmove.lg', function(e) {
if (_this.thumbTotalWidth > _this.thumbOuterWidth) {
e.preventDefault();
endCoords = e.originalEvent.targetTouches[0].pageX;
isMoved = true;
_this.$thumbOuter.addClass('lg-dragging');
tempLeft = _this.left;
tempLeft = tempLeft - (endCoords - startCoords);
if (tempLeft > (_this.thumbTotalWidth - _this.thumbOuterWidth)) {
tempLeft = _this.thumbTotalWidth - _this.thumbOuterWidth;
}
if (tempLeft < 0) {
tempLeft = 0;
}
// move current slide
_this.setTranslate(tempLeft);
}
});
_this.core.$outer.find('.lg-thumb').on('touchend.lg', function() {
if (_this.thumbTotalWidth > _this.thumbOuterWidth) {
if (isMoved) {
isMoved = false;
_this.$thumbOuter.removeClass('lg-dragging');
if (Math.abs(endCoords - startCoords) < _this.core.s.swipeThreshold) {
_this.thumbClickable = true;
}
_this.left = tempLeft;
} else {
_this.thumbClickable = true;
}
} else {
_this.thumbClickable = true;
}
});
};
Thumbnail.prototype.toogle = function() {
var _this = this;
if (_this.core.s.toogleThumb) {
_this.core.$outer.addClass('lg-can-toggle');
_this.$thumbOuter.append('<span class="lg-toogle-thumb lg-icon"></span>');
_this.core.$outer.find('.lg-toogle-thumb').on('click.lg', function() {
_this.core.$outer.toggleClass('lg-thumb-open');
});
}
};
Thumbnail.prototype.thumbkeyPress = function() {
var _this = this;
$(window).on('keydown.lg.thumb', function(e) {
if (e.keyCode === 38) {
e.preventDefault();
_this.core.$outer.addClass('lg-thumb-open');
} else if (e.keyCode === 40) {
e.preventDefault();
_this.core.$outer.removeClass('lg-thumb-open');
}
});
};
Thumbnail.prototype.destroy = function() {
if (this.core.s.thumbnail && this.core.$items.length > 1) {
$(window).off('resize.lg.thumb orientationchange.lg.thumb keydown.lg.thumb');
this.$thumbOuter.remove();
this.core.$outer.removeClass('lg-has-thumb');
}
};
$.fn.lightGallery.modules.Thumbnail = Thumbnail;
})(jQuery, window, document);
| reed23/cinemafilms | node_modules/lightgallery/dist/js/lg-thumbnail.js | JavaScript | gpl-2.0 | 15,685 |
/**
Represents an asynchronous operation. Provides a
standard API for subscribing to the moment that the operation completes either
successfully (`fulfill()`) or unsuccessfully (`reject()`).
@class Promise.Resolver
@constructor
@param {Promise} promise The promise instance this resolver will be handling
**/
function Resolver(promise) {
/**
List of success callbacks
@property _callbacks
@type Array
@private
**/
this._callbacks = [];
/**
List of failure callbacks
@property _errbacks
@type Array
@private
**/
this._errbacks = [];
/**
The promise for this Resolver.
@property promise
@type Promise
**/
this.promise = promise;
/**
The status of the operation. This property may take only one of the following
values: 'pending', 'fulfilled' or 'rejected'.
@property _status
@type String
@default 'pending'
@private
**/
this._status = 'pending';
}
Y.mix(Resolver.prototype, {
/**
Resolves the promise, signaling successful completion of the
represented operation. All "onFulfilled" subscriptions are executed and passed
the value provided to this method. After calling `fulfill()`, `reject()` and
`notify()` are disabled.
@method fulfill
@param {Any} value Value to pass along to the "onFulfilled" subscribers
**/
fulfill: function (value) {
if (this._status === 'pending') {
this._result = value;
}
if (this._status !== 'rejected') {
this._notify(this._callbacks, this._result);
// Reset the callback list so that future calls to fulfill()
// won't call the same callbacks again. Promises keep a list
// of callbacks, they're not the same as events. In practice,
// calls to fulfill() after the first one should not be made by
// the user but by then()
this._callbacks = [];
// Once a promise gets fulfilled it can't be rejected, so
// there is no point in keeping the list. Remove it to help
// garbage collection
this._errbacks = null;
this._status = 'fulfilled';
}
},
/**
Resolves the promise, signaling *un*successful completion of the
represented operation. All "onRejected" subscriptions are executed with
the value provided to this method. After calling `reject()`, `resolve()`
and `notify()` are disabled.
@method reject
@param {Any} value Value to pass along to the "reject" subscribers
**/
reject: function (reason) {
if (this._status === 'pending') {
this._result = reason;
}
if (this._status !== 'fulfilled') {
this._notify(this._errbacks, this._result);
// See fulfill()
this._callbacks = null;
this._errbacks = [];
this._status = 'rejected';
}
},
/**
Schedule execution of a callback to either or both of "resolve" and
"reject" resolutions for the Resolver. The callbacks
are wrapped in a new Resolver and that Resolver's corresponding promise
is returned. This allows operation chaining ala
`functionA().then(functionB).then(functionC)` where `functionA` returns
a promise, and `functionB` and `functionC` _may_ return promises.
@method then
@param {Function} [callback] function to execute if the Resolver
resolves successfully
@param {Function} [errback] function to execute if the Resolver
resolves unsuccessfully
@return {Promise} The promise of a new Resolver wrapping the resolution
of either "resolve" or "reject" callback
**/
then: function (callback, errback) {
// When the current promise is fulfilled or rejected, either the
// callback or errback will be executed via the function pushed onto
// this._callbacks or this._errbacks. However, to allow then()
// chaining, the execution of either function needs to be represented
// by a Resolver (the same Resolver can represent both flow paths), and
// its promise returned.
var promise = this.promise,
thenFulfill, thenReject,
// using promise constructor allows for customized promises to be
// returned instead of plain ones
then = new promise.constructor(function (fulfill, reject) {
thenFulfill = fulfill;
thenReject = reject;
}),
callbackList = this._callbacks || [],
errbackList = this._errbacks || [];
// Because the callback and errback are represented by a Resolver, it
// must be fulfilled or rejected to propagate through the then() chain.
// The same logic applies to resolve() and reject() for fulfillment.
callbackList.push(typeof callback === 'function' ?
this._wrap(thenFulfill, thenReject, callback) : thenFulfill);
errbackList.push(typeof errback === 'function' ?
this._wrap(thenFulfill, thenReject, errback) : thenReject);
// If a promise is already fulfilled or rejected, notify the newly added
// callbacks by calling fulfill() or reject()
if (this._status === 'fulfilled') {
this.fulfill(this._result);
} else if (this._status === 'rejected') {
this.reject(this._result);
}
return then;
},
/**
Wraps the callback in Y.soon to guarantee its asynchronous execution. It
also catches exceptions to turn them into rejections and links promises
returned from the `then` callback.
@method _wrap
@param {Function} thenFulfill Fulfillment function of the resolver that
handles this promise
@param {Function} thenReject Rejection function of the resolver that
handles this promise
@param {Function} fn Callback to wrap
@return {Function}
@private
**/
_wrap: function (thenFulfill, thenReject, fn) {
// callbacks and errbacks only get one argument
return function (valueOrReason) {
var result;
// Promises model exception handling through callbacks
// making both synchronous and asynchronous errors behave
// the same way
try {
// Use the argument coming in to the callback/errback from the
// resolution of the parent promise.
// The function must be called as a normal function, with no
// special value for |this|, as per Promises A+
result = fn(valueOrReason);
} catch (e) {
// calling return only to stop here
return thenReject(e);
}
if (Promise.isPromise(result)) {
// Returning a promise from a callback makes the current
// promise sync up with the returned promise
result.then(thenFulfill, thenReject);
} else {
// Non-promise return values always trigger resolve()
// because callback is affirmative, and errback is
// recovery. To continue on the rejection path, errbacks
// must return rejected promises or throw.
thenFulfill(result);
}
};
},
/**
Returns the current status of the Resolver as a string "pending",
"fulfilled", or "rejected".
@method getStatus
@return {String}
**/
getStatus: function () {
return this._status;
},
/**
Executes an array of callbacks from a specified context, passing a set of
arguments.
@method _notify
@param {Function[]} subs The array of subscriber callbacks
@param {Any} result Value to pass the callbacks
@protected
**/
_notify: function (subs, result) {
// Since callback lists are reset synchronously, the subs list never
// changes after _notify() receives it. Avoid calling Y.soon() for
// an empty list
if (subs.length) {
// Calling all callbacks after Y.soon to guarantee
// asynchronicity. Because setTimeout can cause unnecessary
// delays that *can* become noticeable in some situations
// (especially in Node.js)
Y.soon(function () {
var i, len;
for (i = 0, len = subs.length; i < len; ++i) {
subs[i](result);
}
});
}
}
}, true);
Y.Promise.Resolver = Resolver;
| schancel/gameserver | public/js/yui3-3.12.0/src/promise/js/resolver.js | JavaScript | gpl-2.0 | 8,693 |
/**
* Copyright (c) 2008- Samuli Jrvel
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html. If redistributing this code,
* this entire header must remain intact.
*/
mollify.registerPlugin(new ArchiverPlugin());
function ArchiverPlugin() {
var that = this;
this.getPluginInfo = function() { return { id: "plugin_archiver" }; }
this.initialize = function(env) {
that.env = env;
that.env.addItemContextProvider(that.getItemContext);
$.getScript(that.env.pluginUrl("Archiver") + "client/texts_" + that.env.texts().locale + ".js");
}
this.getItemContext = function(item, details) {
if (!details["plugin_archiver"] || !details["plugin_archiver"]["action_extract"]) return null;
var extractServiceUrl = details["plugin_archiver"]["action_extract"];
return {
actions : {
secondary: [
{ title: "-" },
{
title: that.env.texts().get("plugin_archiver_extractAction"),
callback: function(item) { that.onExtract(extractServiceUrl, false); }
}
]
}
}
}
this.onExtract = function(url, allowOverwrite) {
var wd = that.env.dialog().showWait(that.env.texts().get("pleaseWait"));
var params = { overwrite: allowOverwrite };
that.env.service().post(url, params,
function(result) {
wd.close();
that.env.fileview().refresh();
},
function(code, error) {
wd.close();
if (code == 205) {
that.env.dialog().showConfirmation({
title: that.env.texts().get("plugin_archiver_extractFolderAlreadyExistsTitle"),
message: that.env.texts().get("plugin_archiver_extractFolderAlreadyExistsMessage"),
on_confirm: function() { that.onExtract(url, true); }
});
return;
}
alert("Extract error: "+code+"/"+error);
}
);
}
} | janosgyerik/TheToolbox | mollify/backend/plugin/Archiver/client/plugin.js | JavaScript | gpl-2.0 | 1,939 |
/**
* cordova Web Intent plugin
* Copyright (c) Boris Smus 2010
*
*/
var WebIntent = function() {
};
WebIntent.prototype.ACTION_SEND = "android.intent.action.SEND";
WebIntent.prototype.ACTION_VIEW= "android.intent.action.VIEW";
WebIntent.prototype.EXTRA_TEXT = "android.intent.extra.TEXT";
WebIntent.prototype.EXTRA_SUBJECT = "android.intent.extra.SUBJECT";
WebIntent.prototype.EXTRA_STREAM = "android.intent.extra.STREAM";
WebIntent.prototype.EXTRA_EMAIL = "android.intent.extra.EMAIL";
WebIntent.prototype.startActivity = function(params, success, fail) {
return cordova.exec(function(args) {
success(args);
}, function(args) {
fail(args);
}, 'WebIntent', 'startActivity', [params]);
};
WebIntent.prototype.hasExtra = function(params, success, fail) {
return cordova.exec(function(args) {
success(args);
}, function(args) {
fail(args);
}, 'WebIntent', 'hasExtra', [params]);
};
WebIntent.prototype.saveImage = function(b64String, params, win, fail) {
return cordova.exec(win, fail, "WebIntent", "saveImage", [b64String, params]);
};
WebIntent.prototype.createAccount = function(params, win, fail) {
return cordova.exec(win, fail, "WebIntent", "createAccount", [params]);
};
WebIntent.prototype.getUri = function(success, fail) {
return cordova.exec(function(args) {
success(args);
}, function(args) {
fail(args);
}, 'WebIntent', 'getUri', []);
};
WebIntent.prototype.getExtra = function(params, success, fail) {
return cordova.exec(function(args) {
success(args);
}, function(args) {
fail(args);
}, 'WebIntent', 'getExtra', [params]);
};
WebIntent.prototype.getAccounts = function(params, success, fail) {
return cordova.exec(function(args) {
success(args);
}, function(args) {
fail(args);
}, 'WebIntent', 'getAccounts', [params]);
};
WebIntent.prototype.clearCookies = function(params, success, fail) {
return cordova.exec(function(args) {
success(args);
}, function(args) {
fail(args);
}, 'WebIntent', 'clearCookies', [params]);
};
WebIntent.prototype.onNewIntent = function(callback) {
return cordova.exec(function(args) {
callback(args);
}, function(args) {
}, 'WebIntent', 'onNewIntent', []);
};
WebIntent.prototype.sendBroadcast = function(params, success, fail) {
return cordova.exec(function(args) {
success(args);
}, function(args) {
fail(args);
}, 'WebIntent', 'sendBroadcast', [params]);
};
cordova.addConstructor(function() {
window.webintent = new WebIntent();
// backwards compatibility
window.plugins = window.plugins || {};
window.plugins.webintent = window.webintent;
});
| ComunidadeExpresso/expressomobile-www | js/libs/cordova/webintent.js | JavaScript | gpl-2.0 | 3,059 |
/*
Copyright (c) 2004-2006, The Dojo Foundation
All Rights Reserved.
Licensed under the Academic Free License version 2.1 or above OR the
modified BSD license. For more information on Dojo licensing, see:
http://dojotoolkit.org/community/licensing.shtml
*/
dojo.provide("dojo.data.old.Item");
dojo.require("dojo.data.old.Observable");
dojo.require("dojo.data.old.Value");
dojo.require("dojo.lang.common");
dojo.require("dojo.lang.assert");
dojo.data.old.Item = function (dataProvider) {
dojo.lang.assertType(dataProvider, dojo.data.old.provider.Base, {optional:true});
dojo.data.old.Observable.call(this);
this._dataProvider = dataProvider;
this._dictionaryOfAttributeValues = {};
};
dojo.inherits(dojo.data.old.Item, dojo.data.old.Observable);
dojo.data.old.Item.compare = function (itemOne, itemTwo) {
dojo.lang.assertType(itemOne, dojo.data.old.Item);
if (!dojo.lang.isOfType(itemTwo, dojo.data.old.Item)) {
return -1;
}
var nameOne = itemOne.getName();
var nameTwo = itemTwo.getName();
if (nameOne == nameTwo) {
var attributeArrayOne = itemOne.getAttributes();
var attributeArrayTwo = itemTwo.getAttributes();
if (attributeArrayOne.length != attributeArrayTwo.length) {
if (attributeArrayOne.length > attributeArrayTwo.length) {
return 1;
} else {
return -1;
}
}
for (var i in attributeArrayOne) {
var attribute = attributeArrayOne[i];
var arrayOfValuesOne = itemOne.getValues(attribute);
var arrayOfValuesTwo = itemTwo.getValues(attribute);
dojo.lang.assert(arrayOfValuesOne && (arrayOfValuesOne.length > 0));
if (!arrayOfValuesTwo) {
return 1;
}
if (arrayOfValuesOne.length != arrayOfValuesTwo.length) {
if (arrayOfValuesOne.length > arrayOfValuesTwo.length) {
return 1;
} else {
return -1;
}
}
for (var j in arrayOfValuesOne) {
var value = arrayOfValuesOne[j];
if (!itemTwo.hasAttributeValue(value)) {
return 1;
}
}
return 0;
}
} else {
if (nameOne > nameTwo) {
return 1;
} else {
return -1;
}
}
};
dojo.data.old.Item.prototype.toString = function () {
var arrayOfStrings = [];
var attributes = this.getAttributes();
for (var i in attributes) {
var attribute = attributes[i];
var arrayOfValues = this.getValues(attribute);
var valueString;
if (arrayOfValues.length == 1) {
valueString = arrayOfValues[0];
} else {
valueString = "[";
valueString += arrayOfValues.join(", ");
valueString += "]";
}
arrayOfStrings.push(" " + attribute + ": " + valueString);
}
var returnString = "{ ";
returnString += arrayOfStrings.join(",\n");
returnString += " }";
return returnString;
};
dojo.data.old.Item.prototype.compare = function (otherItem) {
return dojo.data.old.Item.compare(this, otherItem);
};
dojo.data.old.Item.prototype.isEqual = function (otherItem) {
return (this.compare(otherItem) == 0);
};
dojo.data.old.Item.prototype.getName = function () {
return this.get("name");
};
dojo.data.old.Item.prototype.get = function (attributeId) {
var literalOrValueOrArray = this._dictionaryOfAttributeValues[attributeId];
if (dojo.lang.isUndefined(literalOrValueOrArray)) {
return null;
}
if (literalOrValueOrArray instanceof dojo.data.old.Value) {
return literalOrValueOrArray.getValue();
}
if (dojo.lang.isArray(literalOrValueOrArray)) {
var dojoDataValue = literalOrValueOrArray[0];
return dojoDataValue.getValue();
}
return literalOrValueOrArray;
};
dojo.data.old.Item.prototype.getValue = function (attributeId) {
var literalOrValueOrArray = this._dictionaryOfAttributeValues[attributeId];
if (dojo.lang.isUndefined(literalOrValueOrArray)) {
return null;
}
if (literalOrValueOrArray instanceof dojo.data.old.Value) {
return literalOrValueOrArray;
}
if (dojo.lang.isArray(literalOrValueOrArray)) {
var dojoDataValue = literalOrValueOrArray[0];
return dojoDataValue;
}
var literal = literalOrValueOrArray;
dojoDataValue = new dojo.data.old.Value(literal);
this._dictionaryOfAttributeValues[attributeId] = dojoDataValue;
return dojoDataValue;
};
dojo.data.old.Item.prototype.getValues = function (attributeId) {
var literalOrValueOrArray = this._dictionaryOfAttributeValues[attributeId];
if (dojo.lang.isUndefined(literalOrValueOrArray)) {
return null;
}
if (literalOrValueOrArray instanceof dojo.data.old.Value) {
var array = [literalOrValueOrArray];
this._dictionaryOfAttributeValues[attributeId] = array;
return array;
}
if (dojo.lang.isArray(literalOrValueOrArray)) {
return literalOrValueOrArray;
}
var literal = literalOrValueOrArray;
var dojoDataValue = new dojo.data.old.Value(literal);
array = [dojoDataValue];
this._dictionaryOfAttributeValues[attributeId] = array;
return array;
};
dojo.data.old.Item.prototype.load = function (attributeId, value) {
this._dataProvider.registerAttribute(attributeId);
var literalOrValueOrArray = this._dictionaryOfAttributeValues[attributeId];
if (dojo.lang.isUndefined(literalOrValueOrArray)) {
this._dictionaryOfAttributeValues[attributeId] = value;
return;
}
if (!(value instanceof dojo.data.old.Value)) {
value = new dojo.data.old.Value(value);
}
if (literalOrValueOrArray instanceof dojo.data.old.Value) {
var array = [literalOrValueOrArray, value];
this._dictionaryOfAttributeValues[attributeId] = array;
return;
}
if (dojo.lang.isArray(literalOrValueOrArray)) {
literalOrValueOrArray.push(value);
return;
}
var literal = literalOrValueOrArray;
var dojoDataValue = new dojo.data.old.Value(literal);
array = [dojoDataValue, value];
this._dictionaryOfAttributeValues[attributeId] = array;
};
dojo.data.old.Item.prototype.set = function (attributeId, value) {
this._dataProvider.registerAttribute(attributeId);
this._dictionaryOfAttributeValues[attributeId] = value;
this._dataProvider.noteChange(this, attributeId, value);
};
dojo.data.old.Item.prototype.setValue = function (attributeId, value) {
this.set(attributeId, value);
};
dojo.data.old.Item.prototype.addValue = function (attributeId, value) {
this.load(attributeId, value);
this._dataProvider.noteChange(this, attributeId, value);
};
dojo.data.old.Item.prototype.setValues = function (attributeId, arrayOfValues) {
dojo.lang.assertType(arrayOfValues, Array);
this._dataProvider.registerAttribute(attributeId);
var finalArray = [];
this._dictionaryOfAttributeValues[attributeId] = finalArray;
for (var i in arrayOfValues) {
var value = arrayOfValues[i];
if (!(value instanceof dojo.data.old.Value)) {
value = new dojo.data.old.Value(value);
}
finalArray.push(value);
this._dataProvider.noteChange(this, attributeId, value);
}
};
dojo.data.old.Item.prototype.getAttributes = function () {
var arrayOfAttributes = [];
for (var key in this._dictionaryOfAttributeValues) {
arrayOfAttributes.push(this._dataProvider.getAttribute(key));
}
return arrayOfAttributes;
};
dojo.data.old.Item.prototype.hasAttribute = function (attributeId) {
return (attributeId in this._dictionaryOfAttributeValues);
};
dojo.data.old.Item.prototype.hasAttributeValue = function (attributeId, value) {
var arrayOfValues = this.getValues(attributeId);
for (var i in arrayOfValues) {
var candidateValue = arrayOfValues[i];
if (candidateValue.isEqual(value)) {
return true;
}
}
return false;
};
| freemed/freemed | ui/dojo/htdocs/dojo/src/data/old/Item.js | JavaScript | gpl-2.0 | 7,279 |
import config from '@automattic/calypso-config';
import debugFactory from 'debug';
// Enable/disable ad-tracking
// These should not be put in the json config as they must not differ across environments
export const isGoogleAnalyticsEnabled = true;
export const isGoogleAnalyticsEnhancedEcommerceEnabled = true;
export const isFloodlightEnabled = true;
export const isFacebookEnabled = true;
export const isBingEnabled = true;
export const isGeminiEnabled = false;
export const isWpcomGoogleAdsGtagEnabled = true;
export const isJetpackGoogleAdsGtagEnabled = true;
export const isQuantcastEnabled = false;
export const isExperianEnabled = true;
export const isOutbrainEnabled = true;
export const isPinterestEnabled = true;
export const isIconMediaEnabled = false;
export const isTwitterEnabled = true;
export const isLinkedinEnabled = false;
export const isCriteoEnabled = false;
export const isPandoraEnabled = false;
export const isQuoraEnabled = false;
export const isAdRollEnabled = false;
/**
* Module variables
*/
export const debug = debugFactory( 'calypso:analytics:ad-tracking' );
export const FACEBOOK_TRACKING_SCRIPT_URL = 'https://connect.facebook.net/en_US/fbevents.js';
export const GOOGLE_GTAG_SCRIPT_URL = 'https://www.googletagmanager.com/gtag/js?id=';
export const BING_TRACKING_SCRIPT_URL = 'https://bat.bing.com/bat.js';
export const CRITEO_TRACKING_SCRIPT_URL = 'https://static.criteo.net/js/ld/ld.js';
export const YAHOO_GEMINI_CONVERSION_PIXEL_URL =
'https://sp.analytics.yahoo.com/spp.pl?a=10000&.yp=10014088&ec=wordpresspurchase';
export const YAHOO_GEMINI_AUDIENCE_BUILDING_PIXEL_URL =
'https://sp.analytics.yahoo.com/spp.pl?a=10000&.yp=10014088';
export const PANDORA_CONVERSION_PIXEL_URL =
'https://data.adxcel-ec2.com/pixel/?ad_log=referer&action=purchase&pixid=7efc5994-458b-494f-94b3-31862eee9e26';
export const EXPERIAN_CONVERSION_PIXEL_URL =
'https://d.turn.com/r/dd/id/L21rdC84MTYvY2lkLzE3NDc0MzIzNDgvdC8yL2NhdC8zMjE4NzUwOQ';
export const ICON_MEDIA_RETARGETING_PIXEL_URL =
'https://tags.w55c.net/rs?id=cab35a3a79dc4173b8ce2c47adad2cea&t=marketing';
export const ICON_MEDIA_SIGNUP_PIXEL_URL =
'https://tags.w55c.net/rs?id=d239e9cb6d164f7299d2dbf7298f930a&t=marketing';
export const ICON_MEDIA_ORDER_PIXEL_URL =
'https://tags.w55c.net/rs?id=d299eef42f2d4135a96d0d40ace66f3a&t=checkout';
export const ADROLL_PAGEVIEW_PIXEL_URL_1 =
'https://d.adroll.com/ipixel/PEJHFPIHPJC2PD3IMTCWTT/WV6A5O5PBJBIBDYGZHVBM5?name=ded132f8';
export const ADROLL_PAGEVIEW_PIXEL_URL_2 =
'https://d.adroll.com/fb/ipixel/PEJHFPIHPJC2PD3IMTCWTT/WV6A5O5PBJBIBDYGZHVBM5?name=ded132f8';
export const ADROLL_PURCHASE_PIXEL_URL_1 =
'https://d.adroll.com/ipixel/PEJHFPIHPJC2PD3IMTCWTT/WV6A5O5PBJBIBDYGZHVBM5?name=8eb337b5';
export const ADROLL_PURCHASE_PIXEL_URL_2 =
'https://d.adroll.com/fb/ipixel/PEJHFPIHPJC2PD3IMTCWTT/WV6A5O5PBJBIBDYGZHVBM5?name=8eb337b5';
export const TWITTER_TRACKING_SCRIPT_URL = 'https://static.ads-twitter.com/uwt.js';
export const LINKED_IN_SCRIPT_URL = 'https://snap.licdn.com/li.lms-analytics/insight.min.js';
export const QUORA_SCRIPT_URL = 'https://a.quora.com/qevents.js';
export const OUTBRAIN_SCRIPT_URL = 'https://amplify.outbrain.com/cp/obtp.js';
export const PINTEREST_SCRIPT_URL = 'https://s.pinimg.com/ct/core.js';
export const TRACKING_IDS = {
bingInit: '4074038',
criteo: '31321',
dcmFloodlightAdvertiserId: '6355556',
facebookInit: '823166884443641',
facebookJetpackInit: '919484458159593',
fullStory: '120RG4',
fullStoryJetpack: '181XXV',
linkedInPartnerId: '195308',
outbrainAdvId: '00f0f5287433c2851cc0cb917c7ff0465e',
pinterestInit: '2613194105266',
quantcast: 'p-3Ma3jHaQMB_bS',
quoraPixelId: '420845cb70e444938cf0728887a74ca1',
twitterPixelId: 'nvzbs',
wpcomGoogleAnalyticsGtag: config( 'google_analytics_key' ),
wpcomFloodlightGtag: 'DC-6355556',
wpcomGoogleAdsGtag: 'AW-946162814',
wpcomGoogleAdsGtagSignupStart: 'AW-946162814/baDICKzQiq4BEP6YlcMD', // "WordPress.com Signup Start"
wpcomGoogleAdsGtagRegistration: 'AW-946162814/_6cKCK6miZYBEP6YlcMD', // "WordPress.com Registration"
wpcomGoogleAdsGtagSignup: 'AW-946162814/5-NnCKy3xZQBEP6YlcMD', // "All Calypso Signups (WordPress.com)"
wpcomGoogleAdsGtagAddToCart: 'AW-946162814/MF4yCNi_kZYBEP6YlcMD', // "WordPress.com AddToCart"
wpcomGoogleAdsGtagPurchase: 'AW-946162814/taG8CPW8spQBEP6YlcMD', // "WordPress.com Purchase Gtag"
jetpackGoogleAnalyticsGtag: 'UA-52447-43', // Jetpack Gtag (Analytics) for use in Jetpack x WordPress.com Flows
jetpackGoogleAdsGtagPurchase: 'AW-946162814/kIF1CL3ApfsBEP6YlcMD',
};
// This name is something we created to store a session id for DCM Floodlight session tracking
export const DCM_FLOODLIGHT_SESSION_COOKIE_NAME = 'dcmsid';
export const DCM_FLOODLIGHT_SESSION_LENGTH_IN_SECONDS = 1800;
export const GA_PRODUCT_BRAND_WPCOM = 'WordPress.com';
export const GA_PRODUCT_BRAND_JETPACK = 'Jetpack';
| Automattic/wp-calypso | client/lib/analytics/ad-tracking/constants.js | JavaScript | gpl-2.0 | 4,877 |
$(document).ready(function(){
createCaroussel($('div[data-caroussel=caroussel]'));
setVisibleInCaroussel($('div[data-caroussel=caroussel]'), 0);
setAutoChange($('div[data-caroussel=caroussel]'));
});
function createCaroussel(carousselElement){
carousselElement.append('<div class="caroussel"></div>');
carousselElement.append('<div class="caroussel-pin-wrapper"></div>');
var pins = carousselElement.find('.caroussel-pin-wrapper');
var data = carousselElement.find('[data-caroussel=data]');
data.hide();
// ADD EACH IMAGE FROM DATA
data.children('span[data-url]').each(function(){
$(this).closest('div[data-caroussel=caroussel]').find('.caroussel').append('<div class="caroussel-img-wrapper"><img src="'+$(this).attr('data-url')+'"/></div>');
if ($(this).parent().attr('data-caroussel-pin') != 'false')
$(this).closest('div[data-caroussel=caroussel]').find('.caroussel-pin-wrapper').append('<div class="caroussel-pin"></div>');
});
// COUNT THE NUMBER OF IMAGES AND MEMORIZE DELAY AND COUNT
carousselElement.each(function(){
$(this).attr('data-nbr-images', $(this).find('.caroussel-img-wrapper').length);
var delay = parseInt($(this).find('[data-caroussel=data]').attr('data-caroussel-delay'));
if (delay){
$(this).attr('data-delay', delay);
// ADD A PROGRESS INDICATOR ON THE IMAGE
if ($(this).find('[data-caroussel=data]').attr('data-caroussel-progress-bar') == 'true')
$(this).find('.caroussel').append('<div class="caroussel-progress-bar"></div>');
$(window).resize(function(e){
adjustProgressBar($('div[data-caroussel=caroussel]'));
});
}
});
// ADD EVENT HANDLER ON PINS
pins.find('.caroussel-pin').click(function(e){
setVisibleInCaroussel($(this).closest('div[data-caroussel=caroussel]'), $(this).index());
setAutoChange($(this).closest('div[data-caroussel=caroussel]'));
});
// ADD CLICK EVENT ON PHOTOS
carousselElement.find('.caroussel-img-wrapper img').click(function(e){
// click on right of the photo
if (e.pageX < ($(this).offset().left + ($(this).width() / 4))){
var caroussel = $(this).closest('div[data-caroussel=caroussel]');
decreaseVisibleInCaroussel(caroussel);
setAutoChange(caroussel);
}
else if (e.pageX > ($(this).offset().left + (3 * ($(this).width() / 4)))){
var caroussel = $(this).closest('div[data-caroussel=caroussel]');
increaseVisibleInCaroussel(caroussel);
setAutoChange(caroussel);
}
});
}
function setAutoChange(carousselElement){
// SET AUTOMATIC FUNCTION
carousselElement.each(function(){
var caroussel = $(this);
if (parseInt(caroussel.attr('data-delay'))){
// IF A LOOP FUNCTION IS ALREADY ATTACHED, WE CLOSE IT
if (parseInt(caroussel.attr('data-interval-function'))) clearInterval(parseInt(caroussel.attr('data-interval-function')));
if (parseInt(caroussel.attr('data-interval-function-progress-bar'))) clearInterval(parseInt(caroussel.attr('data-interval-function-progress-bar')));
// WE LAUNCH A LOOP FUNCTION TO CHANGE THE IMAGE
caroussel.attr('data-interval-function', setInterval(function(){
increaseVisibleInCaroussel(caroussel);
}, parseInt(caroussel.attr('data-delay'))));
// WE LAUNCH A LOOP FUNCTION TO CHANGE THE PROGRESS BAR
if (caroussel.find('[data-caroussel=data]').attr('data-caroussel-progress-bar') == 'true'){
var nbrOfRefreshRequired = parseInt(caroussel.attr('data-delay')) / 40;
caroussel.attr('data-interval-function-progress-bar', setInterval(function(){
var progressBar = caroussel.find('.caroussel-progress-bar');
progressBar.css('width', Math.min(progressBar.width() + parseInt(progressBar.attr('data-width'))/nbrOfRefreshRequired, parseInt(progressBar.attr('data-width'))));
}, 39));
}
}
});
}
function increaseVisibleInCaroussel(carousselElement){
setVisibleInCaroussel(carousselElement, (parseInt(carousselElement.attr('data-current-index'))+1) % carousselElement.attr('data-nbr-images'));
}
function decreaseVisibleInCaroussel(carousselElement){
var index = parseInt(carousselElement.attr('data-current-index')) - 1;
if (index < 0) index = parseInt(carousselElement.attr('data-nbr-images')) + index;
setVisibleInCaroussel(carousselElement, index);
}
function setVisibleInCaroussel(carousselElement, index){
// MEMORIZE THE INDEX
carousselElement.attr('data-current-index', index);
// SHOW THE IMAGE
carousselElement.find('.caroussel').find('.caroussel-img-wrapper').hide();
carousselElement.find('.caroussel').find('.caroussel-img-wrapper:eq('+index+')').show();
// ACTIVE THE PIN
carousselElement.find('.caroussel-pin-wrapper').find('.caroussel-pin').removeClass('active');
carousselElement.find('.caroussel-pin-wrapper').find('.caroussel-pin:eq('+index+')').addClass('active');
// INITIALIZE THE PROGRESS BAR
if (carousselElement.find('[data-caroussel=data]').attr('data-caroussel-progress-bar') == 'true'){
adjustProgressBar(carousselElement);
carousselElement.find('.caroussel').each(function(){
$(this).find('.caroussel-progress-bar').css('width', 0);
});
}
}
function adjustProgressBar(carousselElement){
carousselElement.find('.caroussel').each(function(){
var progressBar = $(this).find('.caroussel-progress-bar');
var visibleImgWrapper = $(this).find('.caroussel-img-wrapper:visible');
progressBar.css('top', visibleImgWrapper.offset().top + (visibleImgWrapper.height()*(9/10)));
progressBar.css('left', visibleImgWrapper.offset().left);
progressBar.css('height', visibleImgWrapper.height()/10);
progressBar.attr('data-width', visibleImgWrapper.width());
});
} | Remi-Laot-CreiZyz/caroussel-jquery | caroussel.js | JavaScript | gpl-2.0 | 5,546 |
/*
* This file is part of the TYPO3 CMS project.
*
* It is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License, either version 2
* of the License, or any later version.
*
* For the full copyright and license information, please read the
* LICENSE.txt file that was distributed with this source code.
*
* The TYPO3 project - inspiring people to share!
*/
/**
* Adds a public API for the browsers' localStorage called
* TYPO3.Storage.Client and the Backend Users "uc",
* available via TYPO3.Storage.Persistent
*/
define('TYPO3/CMS/Backend/Storage', ['jquery'], function ($) {
var Storage = {
Client: {},
Persistent: {
_data: false
}
};
/**
* simple localStorage wrapper, common functions get/set/clear
*/
Storage.Client.get = function(key) {
return localStorage.getItem('t3-' + key);
};
Storage.Client.set = function(key, value) {
return localStorage.setItem('t3-' + key, value);
};
Storage.Client.clear = function() {
localStorage.clear();
};
/**
* checks if a key was set before, useful to not do all the undefined checks all the time
*/
Storage.Client.isset = function(key) {
var value = this.get(key);
return (typeof value !== 'undefined' && typeof value !== 'null' && value != 'undefined');
};
/**
* persistent storage, stores everything on the server
* via AJAX, does a greedy load on read
* common functions get/set/clear
*/
Storage.Persistent.get = function(key) {
if (this._data === false) {
var value;
this._loadFromServer().done(function() {
value = Storage.Persistent._getRecursiveDataByDeepKey(Storage.Persistent._data, key.split('.'));
});
return value;
} else {
return this._getRecursiveDataByDeepKey(this._data, key.split('.'));
}
};
Storage.Persistent.set = function(key, value) {
if (this._data !== false) {
this._data = this._setRecursiveDataByDeepKey(this._data, key.split('.'), value);
}
return this._storeOnServer(key, value);
};
Storage.Persistent.addToList = function(key, value) {
return $.ajax(TYPO3.settings.ajaxUrls['usersettings_process'], {data: {'action': 'addToList', key: key, value: value}}).done(function(data) {
Storage.Persistent._data = data;
});
};
Storage.Persistent.removeFromList = function(key, value) {
return $.ajax(TYPO3.settings.ajaxUrls['usersettings_process'], {data: {'action': 'removeFromList', key: key, value: value}}).done(function(data) {
Storage.Persistent._data = data;
});
};
Storage.Persistent.unset = function(key) {
return $.ajax(TYPO3.settings.ajaxUrls['usersettings_process'], {data: {'action': 'unset', key: key}}).done(function(data) {
Storage.Persistent._data = data;
});
};
Storage.Persistent.clear = function() {
$.ajax(TYPO3.settings.ajaxUrls['usersettings_process'], {data: {'action': 'clear'}});
this._data = false;
};
/**
* checks if a key was set before, useful to not do all the undefined checks all the time
*/
Storage.Persistent.isset = function(key) {
var value = this.get(key);
return (typeof value !== 'undefined' && typeof value !== 'null' && value != 'undefined');
};
/**
* loads the data from outside, only used for the initial call from BackendController
* @param data
*/
Storage.Persistent.load = function(data) {
this._data = data;
};
/**
* loads all data from the server
* @returns jQuery Deferred
* @private
*/
Storage.Persistent._loadFromServer = function() {
return $.ajax(TYPO3.settings.ajaxUrls['usersettings_process'], {data: {'action': 'getAll'}, async: false}).done(function(data) {
Storage.Persistent._data = data;
});
};
/**
* stores data on the server, and gets the updated data on return
* to always be up-to-date inside the browser
* @returns jQuery Deferred
* @private
*/
Storage.Persistent._storeOnServer = function(key, value) {
return $.ajax(TYPO3.settings.ajaxUrls['usersettings_process'], {data: {'action': 'set', key: key, value: value}}).done(function(data) {
Storage.Persistent._data = data;
});
};
/**
* helper function used to set a value which could have been a flat object key data["my.foo.bar"] to
* data[my][foo][bar]
* is called recursively by itself
*
* @param data the data to be uased as base
* @param keyParts the keyParts for the subtree
* @param value the value to be set
* @returns the data object
* @private
*/
Storage.Persistent._setRecursiveDataByDeepKey = function(data, keyParts, value) {
if (keyParts.length === 1) {
data = data || {};
data[keyParts[0]] = value;
} else {
var firstKey = keyParts.shift();
data[firstKey] = this._setRecursiveDataByDeepKey(data[firstKey] || {}, keyParts, value);
}
return data;
};
/**
* helper function used to set a value which could have been a flat object key data["my.foo.bar"] to
* data[my][foo][bar]
* is called recursively by itself
*
* @param data the data to be uased as base
* @param keyParts the keyParts for the subtree
* @returns {*}
* @private
*/
Storage.Persistent._getRecursiveDataByDeepKey = function(data, keyParts) {
if (keyParts.length === 1) {
return (data || {})[keyParts[0]];
} else {
var firstKey = keyParts.shift();
return this._getRecursiveDataByDeepKey(data[firstKey] || {}, keyParts);
}
};
/**
* return the Storage object, and attach it to the global TYPO3 object on the global frame
*/
return function() {
top.TYPO3.Storage = Storage;
return Storage;
}();
});
| dalder/TYPO3.CMS | typo3/sysext/backend/Resources/Public/JavaScript/Storage.js | JavaScript | gpl-2.0 | 5,501 |
/* Shape Settings Tab */
TP.shapesStore = Ext.create('Ext.data.Store', {
fields: ['name', 'data'],
proxy: {
type: 'ajax',
url: 'panorama.cgi?task=userdata_shapes',
reader: {
type: 'json',
root: 'data'
}
},
data : thruk_shape_data
});
TP.iconsetsStore = Ext.create('Ext.data.Store', {
fields: ['name', 'sample', 'value', 'fileset'],
proxy: {
type: 'ajax',
url: 'panorama.cgi?task=userdata_iconsets&withempty=1',
reader: {
type: 'json',
root: 'data'
}
},
autoLoad: true,
data : thruk_iconset_data
});
TP.iconTypesStore = Ext.create('Ext.data.Store', {
fields: ['name', 'value', 'icon'],
autoLoad: false,
data : [{value:'TP.HostStatusIcon', name:'Host', icon:url_prefix+'plugins/panorama/images/server.png'},
{value:'TP.HostgroupStatusIcon', name:'Hostgroup', icon:url_prefix+'plugins/panorama/images/server_link.png'},
{value:'TP.ServiceStatusIcon', name:'Service', icon:url_prefix+'plugins/panorama/images/computer.png'},
{value:'TP.ServicegroupStatusIcon', name:'Service Group', icon:url_prefix+'plugins/panorama/images/computer_link.png'},
{value:'TP.FilterStatusIcon', name:'Custom Filter', icon:url_prefix+'plugins/panorama/images/page_find.png'}
]
});
TP.iconSettingsWindow = undefined;
TP.iconShowEditDialog = function(panel) {
panel.stateful = false;
var tab = Ext.getCmp(panel.panel_id);
var lastType = panel.xdata.appearance.type;
// make sure only one window is open at a time
if(TP.iconSettingsWindow != undefined) {
TP.iconSettingsWindow.destroy();
}
tab.disableMapControlsTemp();
TP.resetMoveIcons();
TP.skipRender = false;
var defaultSpeedoSource = 'problems';
var perfDataUpdate = function() {
// ensure fresh and correct performance data
window.perfdata = {};
panel.setIconLabel(undefined, true);
// update speedo
var data = [['number of problems', 'problems'],
['number of problems (incl. warnings)', 'problems_warn']];
for(var key in perfdata) {
if(defaultSpeedoSource == 'problems') { defaultSpeedoSource = 'perfdata:'+key; }
var r = TP.getPerfDataMinMax(perfdata[key], '?');
var options = r.min+" - "+r.max;
data.push(['Perf. Data: '+key+' ('+options+')', 'perfdata:'+key]);
}
/* use availability data as source */
var xdata = TP.get_icon_form_xdata(settingsWindow);
if(xdata.label && xdata.label.labeltext && TP.availabilities && TP.availabilities[panel.id]) {
var avail = TP.availabilities[panel.id];
for(var key in avail) {
var d = avail[key];
var last = d.last != undefined ? d.last : '...';
if(last == -1) { last = '...'; }
var options = d.opts['d'];
if(d.opts['tm']) {
options += '/'+d.opts['tm'];
}
data.push(['Availability: '+last+'% ('+options+')', 'avail:'+key]);
}
}
var cbo = Ext.getCmp('speedosourceStore');
TP.updateArrayStoreKV(cbo.store, data);
// update shape
var data = [['fixed', 'fixed']];
for(var key in perfdata) {
var r = TP.getPerfDataMinMax(perfdata[key], 100);
var options = r.min+" - "+r.max;
data.push(['Perf. Data: '+key+' ('+options+')', 'perfdata:'+key]);
}
var cbo = Ext.getCmp('shapesourceStore');
TP.updateArrayStoreKV(cbo.store, data);
var cbo = Ext.getCmp('connectorsourceStore');
TP.updateArrayStoreKV(cbo.store, data);
}
/* General Settings Tab */
var stateUpdate = function() {
var xdata = TP.get_icon_form_xdata(settingsWindow);
TP.updateAllIcons(Ext.getCmp(panel.panel_id), panel.id, xdata);
labelUpdate();
// update performance data stores
perfDataUpdate();
}
var generalItems = panel.getGeneralItems();
if(generalItems != undefined && panel.xdata.cls != 'TP.StaticIcon') {
generalItems.unshift({
xtype: 'combobox',
name: 'newcls',
fieldLabel: 'Filter Type',
displayField: 'name',
valueField: 'value',
store: TP.iconTypesStore,
editable: false,
listConfig : {
getInnerTpl: function(displayField) {
return '<div class="x-combo-list-item"><img src="{icon}" height=16 width=16 style="vertical-align:top; margin-right: 3px;">{name}<\/div>';
}
},
value: panel.xdata.cls,
listeners: {
change: function(This, newValue, oldValue, eOpts) {
if(TP.iconSettingsWindow == undefined) { return; }
TP.iconSettingsWindow.mask('changing...');
var key = panel.id;
var xdata = TP.get_icon_form_xdata(settingsWindow);
var conf = {xdata: xdata};
conf.xdata.cls = newValue;
panel.redrawOnly = true;
panel.destroy();
TP.timeouts['timeout_' + key + '_show_settings'] = window.setTimeout(function() {
TP.iconSettingsWindow.skipRestore = true;
/* does not exist when changing a newly placed icon */
if(TP.cp.state[key]) {
TP.cp.state[key].xdata.cls = newValue;
}
panel = TP.add_panlet({id:key, skip_state:true, tb:tab, autoshow:true, state:conf, type:newValue}, false);
panel.xdata = conf.xdata;
panel.classChanged = newValue;
TP.iconShowEditDialog(panel);
TP.cp.state[key].xdata.cls = oldValue;
}, 50);
}
}
});
}
var generalTab = {
title : 'General',
type : 'panel',
hidden: generalItems != undefined ? false : true,
items: [{
xtype : 'panel',
layout: 'fit',
border: 0,
items: [{
xtype: 'form',
id: 'generalForm',
bodyPadding: 2,
border: 0,
bodyStyle: 'overflow-y: auto;',
submitEmptyText: false,
defaults: { anchor: '-12', labelWidth: panel.generalLabelWidth || 132, listeners: { change: function(This, newValue, oldValue, eOpts) { if(newValue != "") { stateUpdate() } } } },
items: generalItems
}]
}]
};
var updateDisabledFields = function(xdata) {
var originalRenderUpdate = renderUpdate;
renderUpdate = Ext.emptyFn;
Ext.getCmp('shapeheightfield').setDisabled(xdata.appearance.shapelocked);
Ext.getCmp('shapetogglelocked').toggle(xdata.appearance.shapelocked);
Ext.getCmp('pieheightfield').setDisabled(xdata.appearance.pielocked);
Ext.getCmp('pietogglelocked').toggle(xdata.appearance.pielocked);
if(xdata.appearance.type == "connector" || xdata.appearance.type == "none") {
Ext.getCmp('rotationfield').setVisible(false);
} else {
Ext.getCmp('rotationfield').setVisible(true);
}
renderUpdate = originalRenderUpdate;
};
/* Layout Settings Tab */
var layoutTab = {
title: 'Layout',
type: 'panel',
items: [{
xtype : 'panel',
layout: 'fit',
border: 0,
items: [{
xtype: 'form',
id: 'layoutForm',
bodyPadding: 2,
border: 0,
bodyStyle: 'overflow-y: auto;',
submitEmptyText: false,
defaults: { anchor: '-12', labelWidth: 80 },
items: [{
fieldLabel: 'Position',
xtype: 'fieldcontainer',
layout: 'table',
items: [{ xtype: 'label', text: 'x:', style: 'margin-left: 0; margin-right: 2px;' },
{ xtype: 'numberfield', name: 'x', width: 55, value: panel.xdata.layout.x, listeners: {
change: function(This, newValue, oldValue, eOpts) {
if(!panel.noMoreMoves) {
panel.noMoreMoves = true;
var y = Number(This.up('panel').getValues().y);
panel.setPosition(newValue, y);
panel.noMoreMoves = false;
}
}
}},
{ xtype: 'label', text: 'y:', style: 'margin-left: 10px; margin-right: 2px;' },
{ xtype: 'numberfield', name: 'y', width: 55, value: panel.xdata.layout.y, listeners: {
change: function(This, newValue, oldValue, eOpts) {
if(!panel.noMoreMoves) {
panel.noMoreMoves = true;
var x = Number(This.up('panel').getValues().x);
panel.setPosition(x, newValue);
panel.noMoreMoves = false;
}
}
}},
{ xtype: 'label', text: '(use cursor keys)', style: 'margin-left: 10px;', cls: 'form-hint' }
]
}, {
fieldLabel: 'Rotation',
xtype: 'numberunit',
allowDecimals: false,
name: 'rotation',
id: 'rotationfield',
unit: '°',
minValue: -360,
maxValue: 360,
step: 15,
value: panel.xdata.layout.rotation != undefined ? panel.xdata.layout.rotation : 0,
listeners: { change: function(This) { var xdata = TP.get_icon_form_xdata(settingsWindow); panel.applyRotation(This.value, xdata); } }
}, {
fieldLabel: 'Z-Index',
xtype: 'numberfield',
allowDecimals: false,
name: 'zindex',
minValue: -10,
maxValue: 100,
step: 1,
value: panel.xdata.layout.zindex != undefined ? panel.xdata.layout.zindex : 0,
listeners: { change: function(This) { var xdata = TP.get_icon_form_xdata(settingsWindow); panel.applyZindex(This.value, xdata); } }
}, {
fieldLabel: 'Scale',
id: 'layoutscale',
xtype: 'numberunit',
unit: '%',
allowDecimals: true,
name: 'scale',
minValue: 0,
maxValue: 10000,
step: 1,
value: panel.xdata.layout.scale != undefined ? panel.xdata.layout.scale : 100,
listeners: { change: function(This) { var xdata = TP.get_icon_form_xdata(settingsWindow); panel.applyScale(This.value, xdata); } },
disabled: (panel.hasScale || panel.xdata.appearance.type == 'icon') ? false : true,
hidden: panel.iconType == 'text' ? true : false
}]
}]
}]
};
TP.shapesStore.load();
var renderUpdate = Ext.emptyFn;
var renderUpdateDo = function(forceColor, forceRenderItem) {
if(TP.skipRender) { return; }
var xdata = TP.get_icon_form_xdata(settingsWindow);
if(panel.iconType == 'image') { panel.setRenderItem(xdata); }
if(xdata.appearance == undefined) { return; }
if(xdata.appearance.type == undefined) { return; }
if(xdata.appearance.type == 'shape') { forceRenderItem = true; }
if(xdata.appearance.type != lastType || forceRenderItem) {
if(panel.setRenderItem) { panel.setRenderItem(xdata, forceRenderItem); }
}
lastType = xdata.appearance.type;
if(xdata.appearance.type == 'shape') {
panel.shapeRender(xdata, forceColor);
}
if(xdata.appearance.type == 'pie') {
panel.pieRender(xdata, forceColor);
}
if(xdata.appearance.type == 'speedometer') {
panel.speedoRender(xdata, forceColor);
}
if(xdata.appearance.type == 'connector') {
panel.connectorRender(xdata, forceColor);
}
labelUpdate();
updateDisabledFields(xdata);
}
var appearanceTab = {
title: 'Appearance',
type: 'panel',
hidden: panel.hideAppearanceTab,
listeners: { show: perfDataUpdate },
items: [{
xtype : 'panel',
layout: 'fit',
border: 0,
items: [{
xtype: 'form',
id: 'appearanceForm',
bodyPadding: 2,
border: 0,
bodyStyle: 'overflow-y: auto;',
submitEmptyText: false,
defaults: { anchor: '-12', labelWidth: 60, listeners: { change: function() { renderUpdate(); } } },
items: [{
/* appearance type */
xtype: 'combobox',
fieldLabel: 'Type',
name: 'type',
store: [['none','Label Only'], ['icon','Icon'], ['connector', 'Line / Arrow / Watermark'], ['pie', 'Pie Chart'], ['speedometer', 'Speedometer'], ['shape', 'Shape']],
id: 'appearance_types',
editable: false,
listeners: {
change: function(This, newValue, oldValue, eOpts) {
Ext.getCmp('appearanceForm').items.each(function(f, i) {
if(f.cls != undefined) {
if(f.cls.match(newValue)) {
f.show();
} else {
f.hide();
}
}
});
if(newValue == 'icon' || panel.hasScale) {
Ext.getCmp('layoutscale').setDisabled(false);
} else {
Ext.getCmp('layoutscale').setDisabled(true);
}
if(newValue == 'shape') {
// fill in defaults
var values = Ext.getCmp('appearanceForm').getForm().getValues();
if(!values['shapename']) {
values['shapename'] = 'arrow';
values['shapelocked'] = true;
values['shapewidth'] = 50;
values['shapeheight'] = 50;
values['shapecolor_ok'] = '#199C0F';
values['shapecolor_warning'] = '#CDCD0A';
values['shapecolor_critical'] = '#CA1414';
values['shapecolor_unknown'] = '#CC740F';
values['shapegradient'] = 0;
values['shapesource'] = 'fixed';
}
var originalRenderUpdate = renderUpdate;
renderUpdate = Ext.emptyFn;
Ext.getCmp('appearanceForm').getForm().setValues(values);
renderUpdate = originalRenderUpdate;
}
if(newValue == 'pie') {
// fill in defaults
var values = Ext.getCmp('appearanceForm').getForm().getValues();
if(!values['piewidth']) {
values['piewidth'] = 50;
values['pieheight'] = 50;
values['pielocked'] = true;
values['pieshadow'] = false;
values['piedonut'] = 0;
values['pielabel'] = false;
values['piegradient'] = 0;
values['piecolor_ok'] = '#199C0F';
values['piecolor_warning'] = '#CDCD0A';
values['piecolor_critical'] = '#CA1414';
values['piecolor_unknown'] = '#CC740F';
values['piecolor_up'] = '#199C0F';
values['piecolor_down'] = '#CA1414';
values['piecolor_unreachable'] = '#CA1414';
}
Ext.getCmp('appearanceForm').getForm().setValues(values);
}
if(newValue == 'speedometer') {
// fill in defaults
var values = Ext.getCmp('appearanceForm').getForm().getValues();
if(!values['speedowidth']) {
values['speedowidth'] = 180;
values['speedoshadow'] = false;
values['speedoneedle'] = false;
values['speedodonut'] = 0;
values['speedogradient'] = 0;
values['speedosource'] = defaultSpeedoSource;
values['speedomargin'] = 5;
values['speedosteps'] = 10;
values['speedocolor_ok'] = '#199C0F';
values['speedocolor_warning'] = '#CDCD0A';
values['speedocolor_critical'] = '#CA1414';
values['speedocolor_unknown'] = '#CC740F';
values['speedocolor_bg'] = '#DDDDDD';
}
Ext.getCmp('appearanceForm').getForm().setValues(values);
}
if(newValue == 'connector') {
// fill in defaults
var values = Ext.getCmp('appearanceForm').getForm().getValues();
if(!values['connectorwidth']) {
var pos = panel.getPosition();
values['connectorfromx'] = pos[0]-100;
values['connectorfromy'] = pos[1];
values['connectortox'] = pos[0]+100;
values['connectortoy'] = pos[1];
values['connectorwidth'] = 3;
values['connectorarrowtype'] = 'both';
values['connectorarrowwidth'] = 10;
values['connectorarrowlength'] = 20;
values['connectorarrowinset'] = 2;
values['connectorcolor_ok'] = '#199C0F';
values['connectorcolor_warning'] = '#CDCD0A';
values['connectorcolor_critical'] = '#CA1414';
values['connectorcolor_unknown'] = '#CC740F';
values['connectorgradient'] = 0;
values['connectorsource'] = 'fixed';
}
var originalRenderUpdate = renderUpdate;
renderUpdate = Ext.emptyFn;
Ext.getCmp('appearanceForm').getForm().setValues(values);
renderUpdate = originalRenderUpdate;
}
renderUpdate();
}
}
},
/* Icons */
{
fieldLabel: 'Icon Set',
id: 'iconset_field',
xtype: 'combobox',
name: 'iconset',
cls: 'icon',
store: TP.iconsetsStore,
value: '',
emptyText: 'use dashboards default icon set',
displayField: 'name',
valueField: 'value',
listConfig : {
getInnerTpl: function(displayField) {
return '<div class="x-combo-list-item"><img src="{sample}" height=16 width=16 style="vertical-align:top; margin-right: 3px;">{name}<\/div>';
}
},
listeners: {
change: function(This) { renderUpdate(undefined, true); }
}
}, {
xtype: 'panel',
cls: 'icon',
html: 'Place image sets in: '+usercontent_folder+'/images/status/',
style: 'text-align: center;',
bodyCls: 'form-hint',
padding: '10 0 0 0',
border: 0
},
/* Shapes */
{
fieldLabel: 'Shape',
xtype: 'combobox',
name: 'shapename',
cls: 'shape',
store: TP.shapesStore,
displayField: 'name',
valueField: 'name',
listConfig : {
getInnerTpl: function(displayField) {
TP.tmpid = 0;
return '<div class="x-combo-list-item"><span name="{name}" height=16 width=16 style="vertical-align:top; margin-right: 3px;"><\/span>{name}<\/div>';
}
},
listeners: {
afterrender: function(This) {
var me = This;
me.shapes = [];
This.getPicker().addListener('show', function(This) {
Ext.Array.each(This.el.dom.getElementsByTagName('SPAN'), function(item, idx) {
TP.show_shape_preview(item, panel, me.shapes);
});
});
This.getPicker().addListener('refresh', function(This) {
Ext.Array.each(This.el.dom.getElementsByTagName('SPAN'), function(item, idx) {
TP.show_shape_preview(item, panel, me.shapes);
});
});
},
destroy: function(This) {
// clean up
Ext.Array.each(This.shapes, function(item, idx) { item.destroy() });
},
change: function(This) { renderUpdate(); }
}
}, {
fieldLabel: 'Size',
xtype: 'fieldcontainer',
name: 'shapesize',
cls: 'shape',
layout: 'table',
defaults: { listeners: { change: function() { renderUpdate() } } },
items: [{ xtype: 'label', text: 'Width:', style: 'margin-left: 0; margin-right: 2px;' },
{ xtype: 'numberunit', name: 'shapewidth', unit: 'px', width: 65, value: panel.xdata.appearance.shapewidth },
{ xtype: 'label', text: 'Height:', style: 'margin-left: 10px; margin-right: 2px;' },
{ xtype: 'numberunit', name: 'shapeheight', unit: 'px', width: 65, value: panel.xdata.appearance.shapeheight, id: 'shapeheightfield' },
{ xtype: 'button', width: 22, icon: url_prefix+'plugins/panorama/images/link.png', enableToggle: true, style: 'margin-left: 2px; margin-top: -6px;', id: 'shapetogglelocked',
toggleHandler: function(btn, state) { this.up('form').getForm().setValues({shapelocked: state ? '1' : '' }); renderUpdate(); }
},
{ xtype: 'hidden', name: 'shapelocked' }
]
}, {
fieldLabel: 'Colors',
cls: 'shape',
xtype: 'fieldcontainer',
layout: { type: 'table', columns: 4, tableAttrs: { style: { width: '100%' } } },
defaults: {
listeners: { change: function() { renderUpdateDo() } },
mouseover: function(color) { renderUpdateDo(color); },
mouseout: function(color) { renderUpdateDo(); }
},
items: [
{ xtype: 'label', text: panel.iconType == 'host' ? 'Up: ' : 'Ok: ' },
{
xtype: 'colorcbo',
name: 'shapecolor_ok',
value: panel.xdata.appearance.shapecolor_ok,
width: 80,
tdAttrs: { style: 'padding-right: 10px;'},
colorGradient: { start: '#D3D3AE', stop: '#00FF00' }
},
{ xtype: 'label', text: panel.iconType == 'host' ? 'Unreachable: ' : 'Warning: ' },
{
xtype: 'colorcbo',
name: 'shapecolor_warning',
value: panel.xdata.appearance.shapecolor_warning,
width: 80,
colorGradient: { start: '#E1E174', stop: '#FFFF00' }
},
{ xtype: 'label', text: panel.iconType == 'host' ? 'Down: ' : 'Critical: ' },
{
xtype: 'colorcbo',
name: 'shapecolor_critical',
value: panel.xdata.appearance.shapecolor_critical,
width: 80,
colorGradient: { start: '#D3AEAE', stop: '#FF0000' }
},
{ xtype: 'label', text: 'Unknown: ', hidden: panel.iconType == 'host' ? true : false },
{
xtype: 'colorcbo',
name: 'shapecolor_unknown',
value: panel.xdata.appearance.shapecolor_unknown,
width: 80,
colorGradient: { start: '#DAB891', stop: '#FF8900' },
hidden: panel.iconType == 'host' ? true : false
}]
}, {
fieldLabel: 'Gradient',
cls: 'shape',
xtype: 'fieldcontainer',
layout: { type: 'hbox', align: 'stretch' },
items: [{
xtype: 'numberfield',
allowDecimals: true,
name: 'shapegradient',
maxValue: 1,
minValue: -1,
step: 0.05,
value: panel.xdata.appearance.shapegradient,
width: 55,
listeners: { change: function() { renderUpdate(); } }
},
{ xtype: 'label', text: 'Source:', margins: {top: 2, right: 2, bottom: 0, left: 10} },
{
name: 'shapesource',
xtype: 'combobox',
id: 'shapesourceStore',
displayField: 'name',
valueField: 'value',
queryMode: 'local',
store: { fields: ['name', 'value'], data: [] },
editable: false,
value: panel.xdata.appearance.shapesource,
listeners: { focus: perfDataUpdate, change: function() { renderUpdate(); } },
flex: 1
}]
}, {
xtype: 'panel',
cls: 'shape',
html: 'Place shapes in: '+usercontent_folder+'/shapes/',
style: 'text-align: center;',
bodyCls: 'form-hint',
padding: '10 0 0 0',
border: 0
},
/* Connector */
{
fieldLabel: 'From',
xtype: 'fieldcontainer',
name: 'connectorfrom',
cls: 'connector',
layout: { type: 'hbox', align: 'stretch' },
defaults: { listeners: { change: function() { renderUpdate(); } } },
items: [{
xtype: 'label',
text: 'x',
margins: {top: 3, right: 2, bottom: 0, left: 7}
}, {
xtype: 'numberunit',
allowDecimals: false,
name: 'connectorfromx',
width: 70,
unit: 'px',
value: panel.xdata.appearance.connectorfromx
}, {
xtype: 'label',
text: 'y',
margins: {top: 3, right: 2, bottom: 0, left: 7}
}, {
xtype: 'numberunit',
allowDecimals: false,
name: 'connectorfromy',
width: 70,
unit: 'px',
value: panel.xdata.appearance.connectorfromy
},{
xtype: 'label',
text: 'Endpoints',
margins: {top: 3, right: 2, bottom: 0, left: 7}
}, {
xtype: 'combobox',
name: 'connectorarrowtype',
width: 70,
matchFieldWidth: false,
value: panel.xdata.appearance.connectorarrowtype,
store: ['both', 'left', 'right', 'none'],
listConfig : {
getInnerTpl: function(displayField) {
return '<div class="x-combo-list-item"><img src="'+url_prefix+'plugins/panorama/images/connector_type_{field1}.png" height=16 width=77 style="vertical-align:top; margin-right: 3px;"> {field1}<\/div>';
}
}
}]
},
{
fieldLabel: 'To',
xtype: 'fieldcontainer',
name: 'connectorto',
cls: 'connector',
layout: { type: 'hbox', align: 'stretch' },
defaults: { listeners: { change: function() { renderUpdate(); } } },
items: [{
xtype: 'label',
text: 'x',
margins: {top: 3, right: 2, bottom: 0, left: 7}
}, {
xtype: 'numberunit',
allowDecimals: false,
name: 'connectortox',
width: 70,
unit: 'px',
value: panel.xdata.appearance.connectortox
}, {
xtype: 'label',
text: 'y',
margins: {top: 3, right: 2, bottom: 0, left: 7}
}, {
xtype: 'numberunit',
allowDecimals: false,
name: 'connectortoy',
width: 70,
unit: 'px',
value: panel.xdata.appearance.connectortoy
}]
},
{
fieldLabel: 'Size',
xtype: 'fieldcontainer',
name: 'connectorsize',
cls: 'connector',
layout: { type: 'hbox', align: 'stretch' },
defaults: { listeners: { change: function() { renderUpdate(); } } },
items: [{
xtype: 'label',
text: 'Width',
margins: {top: 3, right: 2, bottom: 0, left: 7}
}, {
xtype: 'numberunit',
allowDecimals: false,
name: 'connectorwidth',
width: 60,
unit: 'px',
value: panel.xdata.appearance.connectorwidth
}, {
xtype: 'label',
text: 'Variable Width',
margins: {top: 3, right: 2, bottom: 0, left: 7}
}, {
xtype: 'checkbox',
name: 'connectorvariable'
}]
},
{
fieldLabel: 'Endpoints',
xtype: 'fieldcontainer',
name: 'connectorarrow',
cls: 'connector',
layout: { type: 'hbox', align: 'stretch' },
defaults: { listeners: { change: function() { renderUpdate(); } } },
items: [{
xtype: 'label',
text: 'Width',
margins: {top: 3, right: 2, bottom: 0, left: 7}
}, {
xtype: 'numberunit',
allowDecimals: false,
name: 'connectorarrowwidth',
width: 60,
unit: 'px',
minValue: 0,
value: panel.xdata.appearance.connectorarrowwidth
}, {
xtype: 'label',
text: 'Length',
margins: {top: 3, right: 2, bottom: 0, left: 7}
}, {
xtype: 'numberunit',
allowDecimals: false,
name: 'connectorarrowlength',
width: 60,
minValue: 0,
unit: 'px',
value: panel.xdata.appearance.connectorarrowlength
}, {
xtype: 'label',
text: 'Inset',
margins: {top: 3, right: 2, bottom: 0, left: 7}
}, {
xtype: 'numberunit',
allowDecimals: false,
name: 'connectorarrowinset',
width: 60,
unit: 'px',
value: panel.xdata.appearance.connectorarrowinset
}]
}, {
fieldLabel: 'Colors',
cls: 'connector',
xtype: 'fieldcontainer',
layout: { type: 'table', columns: 4, tableAttrs: { style: { width: '100%' } } },
defaults: {
listeners: { change: function() { renderUpdateDo() } },
mouseover: function(color) { renderUpdateDo(color); },
mouseout: function(color) { renderUpdateDo(); }
},
items: [
{ xtype: 'label', text: panel.iconType == 'host' ? 'Up ' : 'Ok ' },
{
xtype: 'colorcbo',
name: 'connectorcolor_ok',
value: panel.xdata.appearance.connectorcolor_ok,
width: 80,
tdAttrs: { style: 'padding-right: 10px;'},
colorGradient: { start: '#D3D3AE', stop: '#00FF00' }
},
{ xtype: 'label', text: panel.iconType == 'host' ? 'Unreachable ' : 'Warning ' },
{
xtype: 'colorcbo',
name: 'connectorcolor_warning',
value: panel.xdata.appearance.connectorcolor_warning,
width: 80,
colorGradient: { start: '#E1E174', stop: '#FFFF00' }
},
{ xtype: 'label', text: panel.iconType == 'host' ? 'Down ' : 'Critical ' },
{
xtype: 'colorcbo',
name: 'connectorcolor_critical',
value: panel.xdata.appearance.connectorcolor_critical,
width: 80,
colorGradient: { start: '#D3AEAE', stop: '#FF0000' }
},
{ xtype: 'label', text: 'Unknown ', hidden: panel.iconType == 'host' ? true : false },
{
xtype: 'colorcbo',
name: 'connectorcolor_unknown',
value: panel.xdata.appearance.connectorcolor_unknown,
width: 80,
colorGradient: { start: '#DAB891', stop: '#FF8900' },
hidden: panel.iconType == 'host' ? true : false
}]
}, {
fieldLabel: 'Gradient',
cls: 'connector',
xtype: 'fieldcontainer',
layout: { type: 'hbox', align: 'stretch' },
items: [{
xtype: 'numberfield',
allowDecimals: true,
name: 'connectorgradient',
maxValue: 1,
minValue: -1,
step: 0.05,
value: panel.xdata.appearance.connectorgradient,
width: 55,
listeners: { change: function() { renderUpdate(); } }
},
{ xtype: 'label', text: 'Source', margins: {top: 2, right: 2, bottom: 0, left: 10} },
{
name: 'connectorsource',
xtype: 'combobox',
id: 'connectorsourceStore',
displayField: 'name',
valueField: 'value',
queryMode: 'local',
store: { fields: ['name', 'value'], data: [] },
editable: false,
value: panel.xdata.appearance.connectorsource,
listeners: { focus: perfDataUpdate, change: function() { renderUpdate(); } },
flex: 1
}]
}, {
fieldLabel: 'Options',
xtype: 'fieldcontainer',
cls: 'connector',
layout: 'table',
defaults: { listeners: { change: function() { renderUpdate(undefined, true) } } },
items: [
{ xtype: 'label', text: 'Cust. Perf. Data Min', style: 'margin-left: 0px; margin-right: 2px;' },
{ xtype: 'numberfield', allowDecimals: true, width: 70, name: 'connectormin', step: 100 },
{ xtype: 'label', text: 'Max', style: 'margin-left: 8px; margin-right: 2px;' },
{ xtype: 'numberfield', allowDecimals: true, width: 70, name: 'connectormax', step: 100 }
]
},
/* Pie Chart */
{
fieldLabel: 'Size',
xtype: 'fieldcontainer',
cls: 'pie',
layout: 'table',
defaults: { listeners: { change: function() { renderUpdate() } } },
items: [{ xtype: 'label', text: 'Width:', style: 'margin-left: 0; margin-right: 2px;' },
{ xtype: 'numberunit', name: 'piewidth', unit: 'px', width: 65, value: panel.xdata.appearance.piewidth },
{ xtype: 'label', text: 'Height:', style: 'margin-left: 10px; margin-right: 2px;' },
{ xtype: 'numberunit', name: 'pieheight', unit: 'px', width: 65, value: panel.xdata.appearance.pieheight, id: 'pieheightfield' },
{ xtype: 'button', width: 22, icon: url_prefix+'plugins/panorama/images/link.png', enableToggle: true, style: 'margin-left: 2px; margin-top: -6px;', id: 'pietogglelocked',
toggleHandler: function(btn, state) { this.up('form').getForm().setValues({pielocked: state ? '1' : '' }); renderUpdate(); }
},
{ xtype: 'hidden', name: 'pielocked' }
]
}, {
fieldLabel: 'Options',
xtype: 'fieldcontainer',
cls: 'pie',
layout: 'table',
defaults: { listeners: { change: function() { renderUpdate(undefined, true) } } },
items: [
{ xtype: 'label', text: 'Shadow:', style: 'margin-left: 0px; margin-right: 2px;', hidden: true },
{
xtype: 'checkbox',
name: 'pieshadow',
hidden: true
},
{ xtype: 'label', text: 'Label Name:', style: 'margin-left: 8px; margin-right: 2px;' },
{
xtype: 'checkbox',
name: 'pielabel'
},
{ xtype: 'label', text: 'Label Value:', style: 'margin-left: 8px; margin-right: 2px;' },
{
xtype: 'checkbox',
name: 'pielabelval'
},
{ xtype: 'label', text: 'Donut:', style: 'margin-left: 8px; margin-right: 2px;' },
{
xtype: 'numberunit',
allowDecimals: false,
width: 60,
name: 'piedonut',
unit: 'px'
}]
}, {
fieldLabel: 'Colors',
cls: 'pie',
xtype: 'fieldcontainer',
layout: { type: 'table', columns: 4, tableAttrs: { style: { width: '100%' } } },
defaults: {
listeners: { change: function() { renderUpdateDo() } },
mouseover: function(color) { renderUpdateDo(color); },
mouseout: function(color) { renderUpdateDo(); }
},
items: [
{ xtype: 'label', text: 'Ok:' },
{
xtype: 'colorcbo',
name: 'piecolor_ok',
value: panel.xdata.appearance.piecolor_ok,
width: 80,
tdAttrs: { style: 'padding-right: 10px;'},
colorGradient: { start: '#D3D3AE', stop: '#00FF00' }
},
{ xtype: 'label', text: 'Warning:' },
{
xtype: 'colorcbo',
name: 'piecolor_warning',
value: panel.xdata.appearance.piecolor_warning,
width: 80,
colorGradient: { start: '#E1E174', stop: '#FFFF00' }
},
{ xtype: 'label', text: 'Critical:' },
{
xtype: 'colorcbo',
name: 'piecolor_critical',
value: panel.xdata.appearance.piecolor_critical,
width: 80,
colorGradient: { start: '#D3AEAE', stop: '#FF0000' }
},
{ xtype: 'label', text: 'Unknown:' },
{
xtype: 'colorcbo',
name: 'piecolor_unknown',
value: panel.xdata.appearance.piecolor_unknown,
width: 80,
colorGradient: { start: '#DAB891', stop: '#FF8900' }
},
{ xtype: 'label', text: 'Up:' },
{
xtype: 'colorcbo',
name: 'piecolor_up',
value: panel.xdata.appearance.piecolor_up,
width: 80,
colorGradient: { start: '#D3D3AE', stop: '#00FF00' }
},
{ xtype: 'label', text: 'Down:' },
{
xtype: 'colorcbo',
name: 'piecolor_down',
value: panel.xdata.appearance.piecolor_down,
width: 80,
colorGradient: { start: '#D3AEAE', stop: '#FF0000' }
},
{ xtype: 'label', text: 'Unreachable:' },
{
xtype: 'colorcbo',
name: 'piecolor_unreachable',
value: panel.xdata.appearance.piecolor_unreachable,
width: 80,
colorGradient: { start: '#D3AEAE', stop: '#FF0000' }
},
{ xtype: 'label', text: 'Gradient:' },
{
xtype: 'numberfield',
allowDecimals: true,
width: 80,
name: 'piegradient',
maxValue: 1,
minValue: -1,
step: 0.05,
value: panel.xdata.appearance.piegradient
}
]
},
/* Speedometer Chart */
{
fieldLabel: 'Size',
xtype: 'fieldcontainer',
cls: 'speedometer',
layout: 'table',
defaults: { listeners: { change: function() { renderUpdate(undefined, true) } } },
items: [{ xtype: 'label', text: 'Width:', style: 'margin-left: 0; margin-right: 2px;' },
{ xtype: 'numberunit', name: 'speedowidth', unit: 'px', width: 65, value: panel.xdata.appearance.speedowidth },
{ xtype: 'label', text: 'Shadow:', style: 'margin-left: 0px; margin-right: 2px;', hidden: true },
{ xtype: 'checkbox', name: 'speedoshadow', hidden: true },
{ xtype: 'label', text: 'Needle:', style: 'margin-left: 8px; margin-right: 2px;' },
{ xtype: 'checkbox', name: 'speedoneedle' },
{ xtype: 'label', text: 'Donut:', style: 'margin-left: 8px; margin-right: 2px;' },
{ xtype: 'numberunit', allowDecimals: false, width: 60, name: 'speedodonut', unit: 'px' }
]
}, {
fieldLabel: 'Axis',
xtype: 'fieldcontainer',
cls: 'speedometer',
layout: 'table',
defaults: { listeners: { change: function() { renderUpdate(undefined, true) } } },
items: [
{ xtype: 'label', text: 'Steps:', style: 'margin-left: 0px; margin-right: 2px;' },
{
xtype: 'numberfield',
allowDecimals: false,
width: 60,
name: 'speedosteps',
step: 1,
minValue: 0,
maxValue: 1000
},
{ xtype: 'label', text: 'Margin:', style: 'margin-left: 8px; margin-right: 2px;' },
{
xtype: 'numberunit',
allowDecimals: false,
width: 60,
name: 'speedomargin',
unit: 'px'
}]
}, {
fieldLabel: 'Colors',
cls: 'speedometer',
xtype: 'fieldcontainer',
layout: { type: 'table', columns: 4, tableAttrs: { style: { width: '100%' } } },
defaults: {
listeners: { change: function() { renderUpdateDo() } },
mouseover: function(color) { renderUpdateDo(color); },
mouseout: function(color) { renderUpdateDo(); }
},
items: [
{ xtype: 'label', text: panel.iconType == 'host' ? 'Up: ' : 'Ok: ' },
{
xtype: 'colorcbo',
name: 'speedocolor_ok',
value: panel.xdata.appearance.speedocolor_ok,
width: 80,
tdAttrs: { style: 'padding-right: 10px;'},
colorGradient: { start: '#D3D3AE', stop: '#00FF00' }
},
{ xtype: 'label', text: panel.iconType == 'host' ? 'Unreachable: ' : 'Warning: ' },
{
xtype: 'colorcbo',
name: 'speedocolor_warning',
value: panel.xdata.appearance.speedocolor_warning,
width: 80,
colorGradient: { start: '#E1E174', stop: '#FFFF00' }
},
{ xtype: 'label', text: panel.iconType == 'host' ? 'Down: ' : 'Critical: ' },
{
xtype: 'colorcbo',
name: 'speedocolor_critical',
value: panel.xdata.appearance.speedocolor_critical,
width: 80,
colorGradient: { start: '#D3AEAE', stop: '#FF0000' }
},
{ xtype: 'label', text: 'Unknown:' },
{
xtype: 'colorcbo',
name: 'speedocolor_unknown',
value: panel.xdata.appearance.speedocolor_unknown,
width: 80,
colorGradient: { start: '#DAB891', stop: '#FF8900' }
},
{ xtype: 'label', text: 'Background:' },
{
xtype: 'colorcbo',
name: 'speedocolor_bg',
value: panel.xdata.appearance.speedocolor_bg,
width: 80
},
{ xtype: 'label', text: 'Gradient:' },
{
xtype: 'numberfield',
allowDecimals: true,
width: 80,
name: 'speedogradient',
maxValue: 1,
minValue: -1,
step: 0.05,
value: panel.xdata.appearance.speedogradient
}
]
}, {
fieldLabel: 'Source',
name: 'speedosource',
xtype: 'combobox',
cls: 'speedometer',
id: 'speedosourceStore',
displayField: 'name',
valueField: 'value',
queryMode: 'local',
store: { fields: ['name', 'value'], data: [] },
editable: false,
listeners: { focus: perfDataUpdate,
change: function() { renderUpdate(undefined, true) }
}
}, {
fieldLabel: 'Options',
xtype: 'fieldcontainer',
cls: 'speedometer',
layout: 'table',
defaults: { listeners: { change: function() { renderUpdate(undefined, true) } } },
items: [{ xtype: 'label', text: 'Invert:', style: 'margin-left: 0; margin-right: 2px;' },
{ xtype: 'checkbox', name: 'speedoinvert' },
{ xtype: 'label', text: 'Min:', style: 'margin-left: 8px; margin-right: 2px;' },
{ xtype: 'numberfield', allowDecimals: true, width: 70, name: 'speedomin', step: 100 },
{ xtype: 'label', text: 'Max:', style: 'margin-left: 8px; margin-right: 2px;' },
{ xtype: 'numberfield', allowDecimals: true, width: 70, name: 'speedomax', step: 100 }
]
}]
}]
}]
};
/* Link Settings Tab */
var server_actions_menu = [];
Ext.Array.each(action_menu_actions, function(name, i) {
server_actions_menu.push({
text: name,
icon: url_prefix+'plugins/panorama/images/cog.png',
handler: function(This, eOpts) { This.up('form').getForm().setValues({link: 'server://'+name+'/'}) }
});
});
var action_menus_menu = [];
Ext.Array.each(action_menu_items, function(val, i) {
var name = val[0];
action_menus_menu.push({
text: name,
icon: url_prefix+'plugins/panorama/images/cog.png',
handler: function(This, eOpts) { This.up('form').getForm().setValues({link: 'menu://'+name+'/'}) }
});
});
var linkTab = {
title: 'Link',
type: 'panel',
items: [{
xtype : 'panel',
layout: 'fit',
border: 0,
items: [{
xtype: 'form',
id: 'linkForm',
bodyPadding: 2,
border: 0,
bodyStyle: 'overflow-y: auto;',
submitEmptyText: false,
defaults: { anchor: '-12', labelWidth: 132 },
items: [{
fieldLabel: 'Hyperlink',
xtype: 'textfield',
name: 'link',
emptyText: 'http://... or predefined from below'
}, {
fieldLabel: 'Predefined Links',
xtype: 'fieldcontainer',
items: [{
xtype: 'button',
text: 'Choose',
icon: url_prefix+'plugins/panorama/images/world.png',
menu: {
items: [{
text: 'My Dashboards',
icon: url_prefix+'plugins/panorama/images/user_suit.png',
menu: [{
text: 'Loading...',
icon: url_prefix+'plugins/panorama/images/loading-icon.gif',
disabled: true
}]
}, {
text: 'Public Dashboards',
icon: url_prefix+'plugins/panorama/images/world.png',
menu: [{
text: 'Loading...',
icon: url_prefix+'plugins/panorama/images/loading-icon.gif',
disabled: true
}]
}, {
text: 'Show Details',
icon: url_prefix+'plugins/panorama/images/application_view_columns.png',
handler: function(This, eOpts) { This.up('form').getForm().setValues({link: 'dashboard://show_details'}) }
}, {
text: 'Refresh',
icon: url_prefix+'plugins/panorama/images/arrow_refresh.png',
handler: function(This, eOpts) { This.up('form').getForm().setValues({link: 'dashboard://refresh'}) }
}, {
text: 'Server Actions',
icon: url_prefix+'plugins/panorama/images/lightning_go.png',
menu: server_actions_menu,
disabled: server_actions_menu.length > 0 ? false : true
}, {
text: 'Action Menus',
icon: url_prefix+'plugins/panorama/images/lightning_go.png',
menu: action_menus_menu,
disabled: action_menus_menu.length > 0 ? false : true
}],
listeners: {
afterrender: function(This, eOpts) {
TP.load_dashboard_menu_items(This.items.get(0).menu, 'panorama.cgi?task=dashboard_list&list=my', function(val) { This.up('form').getForm().setValues({link: 'dashboard://'+val.replace(/^tabpan-tab_/,'')})}, true);
TP.load_dashboard_menu_items(This.items.get(1).menu, 'panorama.cgi?task=dashboard_list&list=public', function(val) { This.up('form').getForm().setValues({link: 'dashboard://'+val.replace(/^tabpan-tab_/,'')})}, true);
}
}
}
}]
}, {
fieldLabel: 'New Tab',
xtype: 'checkbox',
name: 'newtab',
boxLabel: '(opens links in new tab or window)'
}]
}]
}]
};
/* Label Settings Tab */
var labelUpdate = function() { var xdata = TP.get_icon_form_xdata(settingsWindow); panel.setIconLabel(xdata.label || {}, true); };
var labelTab = {
title: 'Label',
type: 'panel',
items: [{
xtype : 'panel',
layout: 'fit',
border: 0,
items: [{
xtype: 'form',
id: 'labelForm',
bodyPadding: 2,
border: 0,
bodyStyle: 'overflow-y: auto;',
submitEmptyText: false,
defaults: { anchor: '-12', labelWidth: 80, listeners: { change: labelUpdate } },
items: [{
fieldLabel: 'Labeltext',
xtype: 'fieldcontainer',
layout: { type: 'hbox', align: 'stretch' },
items: [{
xtype: 'textfield',
name: 'labeltext',
flex: 1,
id: 'label_textfield',
listeners: { change: labelUpdate }
}, {
xtype: 'button',
icon: url_prefix+'plugins/panorama/images/lightning_go.png',
margins: {top: 0, right: 0, bottom: 0, left: 3},
tooltip: 'open label editor wizard',
handler: function(btn) {
TP.openLabelEditorWindow(panel);
}
}]
}, {
fieldLabel: 'Color',
xtype: 'colorcbo',
name: 'fontcolor',
value: '#000000',
mouseover: function(color) { var oldValue=this.getValue(); this.setValue(color); labelUpdate(); this.setRawValue(oldValue); },
mouseout: function(color) { labelUpdate(); }
}, {
xtype: 'fieldcontainer',
fieldLabel: 'Font',
layout: { type: 'hbox', align: 'stretch' },
defaults: { listeners: { change: labelUpdate } },
items: [{
name: 'fontfamily',
xtype: 'fontcbo',
value: '',
flex: 1,
editable: false
}, {
xtype: 'numberunit',
allowDecimals: false,
name: 'fontsize',
width: 60,
unit: 'px',
margins: {top: 0, right: 0, bottom: 0, left: 3},
value: panel.xdata.label.fontsize != undefined ? panel.xdata.label.fontsize : 14
}, {
xtype: 'hiddenfield',
name: 'fontitalic',
value: panel.xdata.label.fontitalic
}, {
xtype: 'button',
enableToggle: true,
name: 'fontitalic',
icon: url_prefix+'plugins/panorama/images/text_italic.png',
margins: {top: 0, right: 0, bottom: 0, left: 3},
toggleHandler: function(btn, state) { this.up('form').getForm().setValues({fontitalic: state ? '1' : '' }); },
listeners: {
afterrender: function() { if(panel.xdata.label.fontitalic) { this.toggle(); } }
}
}, {
xtype: 'hiddenfield',
name: 'fontbold',
value: panel.xdata.label.fontbold
}, {
xtype: 'button',
enableToggle: true,
name: 'fontbold',
icon: url_prefix+'plugins/panorama/images/text_bold.png',
margins: {top: 0, right: 0, bottom: 0, left: 3},
toggleHandler: function(btn, state) { this.up('form').getForm().setValues({fontbold: state ? '1' : ''}); },
listeners: {
afterrender: function() { if(panel.xdata.label.fontbold) { this.toggle(); } }
}
}]
}, {
xtype: 'fieldcontainer',
fieldLabel: 'Position',
layout: { type: 'hbox', align: 'stretch' },
defaults: { listeners: { change: labelUpdate } },
items: [{
name: 'position',
xtype: 'combobox',
store: ['below', 'above', 'left', 'right', 'center', 'top-left'],
value: 'below',
flex: 1,
editable: false
}, {
xtype: 'label',
text: 'Offset: x',
margins: {top: 3, right: 2, bottom: 0, left: 7}
}, {
xtype: 'numberunit',
allowDecimals: false,
name: 'offsetx',
width: 60,
unit: 'px'
}, {
xtype: 'label',
text: 'y',
margins: {top: 3, right: 2, bottom: 0, left: 7}
}, {
xtype: 'numberunit',
allowDecimals: false,
name: 'offsety',
width: 60,
unit: 'px'
}]
}, {
fieldLabel: 'Orientation',
name: 'orientation',
xtype: 'combobox',
store: ['horizontal', 'vertical'],
value: 'horizontal',
editable: false
}, {
fieldLabel: 'Background',
xtype: 'colorcbo',
name: 'bgcolor',
value: '',
mouseover: function(color) { var oldValue=this.getValue(); this.setValue(color); labelUpdate(); this.setRawValue(oldValue); },
mouseout: function(color) { labelUpdate(); }
}, {
xtype: 'fieldcontainer',
fieldLabel: 'Border',
layout: { type: 'hbox', align: 'stretch' },
defaults: { listeners: { change: labelUpdate } },
items: [{
xtype: 'colorcbo',
name: 'bordercolor',
value: '',
mouseover: function(color) { var oldValue=this.getValue(); this.setValue(color); labelUpdate(); this.setRawValue(oldValue); },
mouseout: function(color) { labelUpdate(); },
flex: 1,
margins: {top: 0, right: 3, bottom: 0, left: 0}
}, {
xtype: 'numberunit',
allowDecimals: false,
name: 'bordersize',
width: 60,
unit: 'px'
}]
}, {
fieldLabel: 'Backgr. Size',
xtype: 'fieldcontainer',
layout: 'table',
items: [{ xtype: 'label', text: 'width:', style: 'margin-left: 0; margin-right: 2px;' },
{ xtype: 'numberfield', name: 'width', width: 55, value: panel.xdata.label.width, listeners: {
change: function(This, newValue, oldValue, eOpts) {
labelUpdate();
}
}},
{ xtype: 'label', text: 'height:', style: 'margin-left: 10px; margin-right: 2px;' },
{ xtype: 'numberfield', name: 'height', width: 55, value: panel.xdata.label.height, listeners: {
change: function(This, newValue, oldValue, eOpts) {
labelUpdate();
}
}}
]
}
]
}]
}]
};
/* Source Tab */
var sourceTab = {
title: 'Source',
type: 'panel',
listeners: {
activate: function(This) {
var xdata = TP.get_icon_form_xdata(settingsWindow);
var j = Ext.JSON.encode(xdata);
try {
j = JSON.stringify(xdata, null, 2);
} catch(err) {
TP.logError(panel.id, "jsonStringifyException", err);
}
this.down('form').getForm().setValues({source: j, sourceError: ''});
}
},
items: [{
xtype : 'panel',
layout: 'fit',
border: 0,
items: [{
xtype: 'form',
id: 'sourceForm',
bodyPadding: 2,
border: 0,
bodyStyle: 'overflow-y: auto;',
submitEmptyText: false,
defaults: { anchor: '-12', labelWidth: 50 },
items: [{
fieldLabel: 'Source',
xtype: 'textarea',
name: 'source',
height: 190
}, {
fieldLabel: ' ',
labelSeparator: '',
xtype: 'fieldcontainer',
items: [{
xtype: 'button',
name: 'sourceapply',
text: 'Apply',
width: 100,
handler: function(btn) {
var values = Ext.getCmp('sourceForm').getForm().getValues();
try {
var xdata = Ext.JSON.decode(values.source);
TP.setIconSettingsValues(xdata);
} catch(err) {
TP.logError(panel.id, "jsonDecodeException", err);
Ext.getCmp('sourceForm').getForm().setValues({sourceError: err});
}
}
}]
}, {
fieldLabel: ' ',
labelSeparator: '',
xtype: 'displayfield',
name: 'sourceError',
value: ''
}]
}]
}]
};
var tabPanel = new Ext.TabPanel({
activeTab : panel.initialSettingsTab ? panel.initialSettingsTab : 0,
enableTabScroll : true,
items : [
generalTab,
layoutTab,
appearanceTab,
linkTab,
labelTab,
sourceTab
]
});
/* add current available backends */
var backendItem = TP.getFormField(Ext.getCmp("generalForm"), 'backends');
if(backendItem) {
TP.updateArrayStoreKV(backendItem.store, TP.getAvailableBackendsTab(tab));
if(backendItem.store.count() <= 1) { backendItem.hide(); }
}
var settingsWindow = new Ext.Window({
height: 350,
width: 400,
layout: 'fit',
items: tabPanel,
panel: panel,
title: 'Icon Settings',
buttonAlign: 'center',
fbar: [/* panlet setting cancel button */
{ xtype: 'button',
text: 'cancel',
handler: function(This) {
settingsWindow.destroy();
}
},
/* panlet setting save button */
{ xtype: 'button',
text: 'save',
handler: function() {
settingsWindow.skipRestore = true;
panel.stateful = true;
delete panel.xdata.label;
delete panel.xdata.link;
var xdata = TP.get_icon_form_xdata(settingsWindow);
TP.log('['+this.id+'] icon config updated: '+Ext.JSON.encode(xdata));
for(var key in xdata) { panel.xdata[key] = xdata[key]; }
panel.applyState({xdata: panel.xdata});
if(panel.classChanged) {
panel.xdata.cls = panel.classChanged;
}
panel.forceSaveState();
delete TP.iconSettingsWindow;
settingsWindow.destroy();
panel.firstRun = false;
panel.applyXdata();
var tab = Ext.getCmp(panel.panel_id);
TP.updateAllIcons(tab, panel.id);
TP.updateAllLabelAvailability(tab, panel.id);
}
}
],
listeners: {
afterRender: function (This) {
var form = This.items.getAt(0).items.getAt(1).down('form').getForm();
this.nav = Ext.create('Ext.util.KeyNav', this.el, {
'left': function(evt){ form.setValues({x: Number(form.getValues().x)-1}); },
'right': function(evt){ form.setValues({x: Number(form.getValues().x)+1}); },
'up': function(evt){ form.setValues({y: Number(form.getValues().y)-1}); },
'down': function(evt){ form.setValues({y: Number(form.getValues().y)+1}); },
ignoreInputFields: true,
scope: panel
});
},
destroy: function() {
delete TP.iconSettingsWindow;
panel.stateful = true;
if(!settingsWindow.skipRestore) {
// if we cancel directly after adding a new icon, destroy it
tab.enableMapControlsTemp();
if(panel.firstRun) {
panel.destroy();
} else {
if(panel.classChanged) {
var key = panel.id;
panel.redrawOnly = true;
panel.destroy();
TP.timeouts['timeout_' + key + '_show_settings'] = window.setTimeout(function() {
panel = TP.add_panlet({id:key, skip_state:true, tb:tab, autoshow:true}, false);
TP.updateAllIcons(Ext.getCmp(panel.panel_id), panel.id);
}, 50);
return;
} else {
// restore position and layout
if(panel.setRenderItem) { panel.setRenderItem(undefined, true); }
if(TP.cp.state[panel.id]) { panel.applyXdata(TP.cp.state[panel.id].xdata); }
}
}
}
if(panel.el) {
panel.el.dom.style.outline = "";
panel.setIconLabel();
}
if(panel.dragEl1 && panel.dragEl1.el) { panel.dragEl1.el.dom.style.outline = ""; }
if(panel.dragEl2 && panel.dragEl2.el) { panel.dragEl2.el.dom.style.outline = ""; }
if(panel.labelEl && panel.labelEl.el) { panel.labelEl.el.dom.style.outline = ""; }
TP.updateAllIcons(Ext.getCmp(panel.panel_id)); // workaround to put labels in front
}
}
}).show();
tab.body.unmask();
TP.setIconSettingsValues(panel.xdata);
TP.iconSettingsWindow = settingsWindow;
// new mouseover tips while settings are open
TP.iconTip.hide();
// move settings window next to panel itself
var showAtPos = TP.getNextToPanelPos(panel, settingsWindow.width, settingsWindow.height);
panel.setIconLabel(undefined, true);
settingsWindow.showAt(showAtPos);
TP.iconSettingsWindow.panel = panel;
settingsWindow.renderUpdateDo = renderUpdateDo;
renderUpdate = function(forceColor, forceRenderItem) {
if(TP.skipRender) { return; }
TP.reduceDelayEvents(TP.iconSettingsWindow, function() {
if(TP.skipRender) { return; }
if(!TP.iconSettingsWindow) { return; }
TP.iconSettingsWindow.renderUpdateDo(forceColor, forceRenderItem);
}, 100, 'timeout_settings_render_update');
};
settingsWindow.renderUpdate = renderUpdate;
renderUpdate();
/* highlight current icon */
if(panel.xdata.appearance.type == "connector") {
panel.dragEl1.el.dom.style.outline = "2px dotted orange";
panel.dragEl2.el.dom.style.outline = "2px dotted orange";
} else if (panel.iconType == "text") {
panel.labelEl.el.dom.style.outline = "2px dotted orange";
} else {
panel.el.dom.style.outline = "2px dotted orange";
}
window.setTimeout(function() {
TP.iconSettingsWindow.toFront();
}, 100);
TP.modalWindows.push(settingsWindow);
};
TP.get_icon_form_xdata = function(settingsWindow) {
var xdata = {
general: Ext.getCmp('generalForm').getForm().getValues(),
layout: Ext.getCmp('layoutForm').getForm().getValues(),
appearance: Ext.getCmp('appearanceForm').getForm().getValues(),
link: Ext.getCmp('linkForm').getForm().getValues(),
label: Ext.getCmp('labelForm').getForm().getValues()
}
// clean up
if(xdata.label.labeltext == '') { delete xdata.label; }
if(xdata.link.link == '') { delete xdata.link; }
if(xdata.layout.rotation == 0) { delete xdata.layout.rotation; }
Ext.getCmp('appearance_types').store.each(function(data, i) {
var t = data.raw[0];
for(var key in xdata.appearance) {
var t2 = t;
if(t == 'speedometer') { t2 = 'speedo'; }
var p = new RegExp('^'+t2, 'g');
if(key.match(p) && t != xdata.appearance.type) {
delete xdata.appearance[key];
}
}
});
if(settingsWindow.panel.hideAppearanceTab) { delete xdata.appearance; }
if(settingsWindow.panel.iconType == 'text') { delete xdata.general; }
if(xdata.appearance) {
delete xdata.appearance.speedoshadow;
delete xdata.appearance.pieshadow;
}
if(xdata.general) {
delete xdata.general.newcls;
}
return(xdata);
}
TP.openLabelEditorWindow = function(panel) {
var oldValue = Ext.getCmp('label_textfield').getValue();
var perf_data = '';
window.perfdata = {};
// ensure fresh and correct performance data
panel.setIconLabel(undefined, true);
for(var key in perfdata) {
delete perfdata[key].perf;
delete perfdata[key].key;
for(var key2 in perfdata[key]) {
var keyname = '.'+key;
if(key.match(/[^a-zA-Z]/)) { keyname = '[\''+key+'\']'; }
perf_data += '<tr><td><\/td><td><i>perfdata'+keyname+'.'+key2+'<\/i><\/td><td>'+perfdata[key][key2]+'<\/td><\/tr>'
}
}
var labelEditorWindow = new Ext.Window({
height: 500,
width: 650,
layout: 'fit',
title: 'Label Editor',
modal: true,
buttonAlign: 'center',
fbar: [/* panlet setting cancel button */
{ xtype: 'button',
text: 'cancel',
handler: function(This) {
var labelEditorWindow = This.up('window');
Ext.getCmp('label_textfield').setValue(oldValue);
labelEditorWindow.destroy();
}
},
/* panlet setting save button */
{ xtype: 'button',
text: 'save',
handler: function(This) {
var labelEditorWindow = This.up('window');
Ext.getCmp('label_textfield').setValue(labelEditorWindow.down('textarea').getValue())
labelEditorWindow.destroy();
}
}
],
items: [{
xtype: 'form',
bodyPadding: 2,
border: 0,
bodyStyle: 'overflow-y: auto;',
submitEmptyText: false,
layout: 'anchor',
defaults: { width: '99%', labelWidth: 40 },
items: [{
xtype: 'textarea',
fieldLabel: 'Label',
value: Ext.getCmp('label_textfield').getValue().replace(/<br>/g,"<br>\n"),
id: 'label_textfield_edit',
height: 90,
listeners: {
change: function(This) {
Ext.getCmp('label_textfield').setValue(This.getValue())
}
}
}, {
fieldLabel: 'Help',
xtype: 'fieldcontainer',
items: [{
xtype: 'label',
cls: 'labelhelp',
html: '<p>Use HTML to format your label<br>'
+'Ex.: <i>Host <b>{{name}}</b><\/i>, Newlines: <i><br><\/i><\/p>'
+'<p>It is possible to create dynamic labels with {{placeholders}}.<br>'
+'Ex.: <i>Host {{name}}: {{plugin_output}}<\/i><\/p>'
+'<p>You may also do calculations inside placeholders like this:<br>'
+'Ex.: <i>Group XY {{totals.ok}}/{{totals.ok + totals.critical + totals.warning + totals.unknown}}<\/i><\/p>'
+'<p>use sprintf to format numbers:<br>'
+'Ex.: <i>{{sprintf("%.2f %s",perfdata.rta.val, perfdata.rta.unit)}}<\/i><\/p>'
+'<p>use strftime to format timestamps:<br>'
+'Ex.: <i>{{strftime("%Y-%m-%d",last_check)}}<\/i><\/p>'
+'<p>conditionals are possible:<br>'
+'Ex.: <i>{{ if(acknowledged) {...} else {...} }}<\/i><\/p>'
+'<p>There are different variables available depending on the type of icon/widget:<br>'
+'<table><tr><th>Groups/Filters:<\/th><td><i>totals.services.ok<\/i><\/td><td>totals number of ok services<\/td><\/tr>'
+'<tr><td><\/td><td><i>totals.services.warning<\/i><\/td><td>totals number of warning services<\/td><\/tr>'
+'<tr><td><\/td><td><i>totals.services.critical<\/i><\/td><td>totals number of critical services<\/td><\/tr>'
+'<tr><td><\/td><td><i>totals.services.unknown<\/i><\/td><td>totals number of unknown services<\/td><\/tr>'
+'<tr><td><\/td><td><i>totals.hosts.up<\/i><\/td><td>totals number of up hosts<\/td><\/tr>'
+'<tr><td><\/td><td><i>totals.hosts.down<\/i><\/td><td>totals number of down hosts<\/td><\/tr>'
+'<tr><td><\/td><td><i>totals.hosts.unreachable<\/i><\/td><td>totals number of unreachable hosts<\/td><\/tr>'
+'<tr><th>Hosts:<\/th><td><i>name<\/i><\/td><td>Hostname<\/td><\/tr>'
+'<tr><td><\/td><td><i>state<\/i><\/td><td>State: 0 - Ok, 1 - Warning, 2 - Critical,...<\/td><\/tr>'
+'<tr><td><\/td><td><i>performance_data<\/i><\/td><td>Performance data. Use list below to access specific values<\/td><\/tr>'
+'<tr><td><\/td><td><i>has_been_checked<\/i><\/td><td>Has this host been checked: 0 - No, 1 - Yes<\/td><\/tr>'
+'<tr><td><\/td><td><i>scheduled_downtime_depth<\/i><\/td><td>Downtime: 0 - No, >l;=1 - Yes<\/td><\/tr>'
+'<tr><td><\/td><td><i>acknowledged<\/i><\/td><td>Has this host been acknowledged: 0 - No, 1 - Yes<\/td><\/tr>'
+'<tr><td><\/td><td><i>last_check<\/i><\/td><td>Timestamp of last check<\/td><\/tr>'
+'<tr><td><\/td><td><i>last_state_change<\/i><\/td><td>Timestamp of last state change<\/td><\/tr>'
+'<tr><td><\/td><td><i>last_notification<\/i><\/td><td>Timestamp of last notification<\/td><\/tr>'
+'<tr><td><\/td><td><i>plugin_output<\/i><\/td><td>Plugin Output<\/td><\/tr>'
+'<tr><th>Services:<\/th><td><i>host_name<\/i><\/td><td>Hostname<\/td><\/tr>'
+'<tr><td><\/td><td><i>description<\/i><\/td><td>Servicename<\/td><\/tr>'
+'<tr><td><\/td><td colspan=2>(other attributes are identical to hosts)<\/td><\/tr>'
+'<tr><th>Performance Data:<\/th><td colspan=2>(available performance data with their current values)<\/td><\/tr>'
+perf_data
+'<tr><th>Availability Data:<\/th><td colspan=2><\/td><\/tr>'
+'<tr><td><\/td><td><i>{{ sprintf("%.2f", availability({d: "60m"})) }}%<\/i><\/td><td>availability for the last 60 minutes<\/td><\/tr>'
+'<tr><td><\/td><td><i>{{ sprintf("%.2f", availability({d: "24h"})) }}%<\/i><\/td><td>availability for the last 24 hours<\/td><\/tr>'
+'<tr><td><\/td><td><i>{{ sprintf("%.2f", availability({d: "7d"})) }}%<\/i><\/td><td>availability for the last 7 days<\/td><\/tr>'
+'<tr><td><\/td><td><i>{{ sprintf("%.2f", availability({d: "31d"})) }}%<\/i><\/td><td>availability for the last 31 days<\/td><\/tr>'
+'<tr><td><\/td><td colspan=2><i>{{ sprintf("%.2f", availability({d: "24h", tm: "5x8"})) }}%<\/i><\/td><\/tr>'
+'<tr><td><\/td><td><\/td><td>availability for the last 24 hours within given timeperiod<\/td><\/tr>'
+'<\/table>',
listeners: {
afterrender: function(This) {
var examples = This.el.dom.getElementsByTagName('i');
Ext.Array.each(examples, function(el, i) {
el.className = "clickable";
el.onclick = function(i) {
var cur = Ext.getCmp('label_textfield_edit').getValue();
var val = Ext.htmlDecode(el.innerHTML);
if(!val.match(/\{\{.*?\}\}/) && (val.match(/^perfdata\./) || val.match(/^perfdata\[/) || val.match(/^totals\./) || val.match(/^avail\./) || val.match(/^[a-z_]+$/))) { val = '{{'+val+'}}'; }
if(val.match(/<br>/)) { val += "\n"; }
Ext.getCmp('label_textfield_edit').setValue(cur+val);
Ext.getCmp('label_textfield_edit').up('form').body.dom.scrollTop=0;
Ext.getCmp('label_textfield_edit').focus();
}
});
}
}
}]
}]
}]
}).show();
Ext.getCmp('label_textfield').setValue(" ");
Ext.getCmp('label_textfield').setValue(Ext.getCmp('label_textfield_edit').getValue());
TP.modalWindows.push(labelEditorWindow);
labelEditorWindow.toFront();
}
TP.setIconSettingsValues = function(xdata) {
xdata = TP.clone(xdata);
// set some defaults
if(!xdata.label) { xdata.label = { labeltext: '' }; }
if(!xdata.label.fontsize) { xdata.label.fontsize = 14; }
if(!xdata.label.bordersize) { xdata.label.bordersize = 1; }
Ext.getCmp('generalForm').getForm().setValues(xdata.general);
Ext.getCmp('layoutForm').getForm().setValues(xdata.layout);
Ext.getCmp('appearanceForm').getForm().setValues(xdata.appearance);
Ext.getCmp('linkForm').getForm().setValues(xdata.link);
Ext.getCmp('labelForm').getForm().setValues(xdata.label);
}
TP.getNextToPanelPos = function(panel, width, height) {
if(!panel || !panel.el) { return([0,0]); }
var sizes = [];
sizes.push(panel.getSize().width);
if(panel.labelEl) {
sizes.push(panel.labelEl.getSize().width);
}
sizes.push(180); // max size of new speedos
var offsetLeft = 30;
var offsetRight = Ext.Array.max(sizes) + 10;
var offsetY = 40;
var panelPos = panel.getPosition();
var viewPortSize = TP.viewport.getSize();
if(viewPortSize.width > panelPos[0] + width+offsetRight) {
panelPos[0] = panelPos[0] + offsetRight;
} else {
panelPos[0] = panelPos[0] - width - offsetLeft;
}
if(panelPos[1] - 50 < 0) {
panelPos[1] = offsetY;
}
else if(viewPortSize.height > panelPos[1] + height - offsetY) {
panelPos[1] = panelPos[1] - offsetY;
} else {
panelPos[1] = viewPortSize.height - height - offsetY;
}
// make sure its on the screen
if(panelPos[0] < 0) { panelPos[0] = 0; }
if(panelPos[1] < 20) { panelPos[1] = 20; }
return(panelPos);
}
| awiddersheim/Thruk | plugins/plugins-available/panorama/root/js/panorama_js_panlet_icon_widgets_settings.js | JavaScript | gpl-2.0 | 94,388 |
(function() {
angular.module('hb5').controller('HbFontaineListController', ['$attrs', '$scope', 'GeoxmlService', '$routeParams', '$log', '$filter', '$timeout', 'hbAlertMessages', 'hbUtil', function($attrs, $scope, GeoxmlService, $routeParams, $log, $filter, $timeout, hbAlertMessages, hbUtil) {
$log.debug(" >>>> HbFontaineListController called...");
// FONTAINE default order is by "Address" stored in NOM field
$scope.predicate = 'IDENTIFIANT.NOM';
$scope.reverse = false;
// Object holding user entered search (filter) criteria
$scope.search = {
"objectif" : "",
"nom" : "",
"alias" : "",
"remark" : "",
"text" : ""
};
// Initialise general search text with search request parameter if defined.
// This is only expected from Dashboard calls.
if ($routeParams.search) {
$scope.search.text = $routeParams.search;
}
/**
* Apply fontaine specific filters and sorting.
*/
var filterSortElfins = function(elfins_p, search_p, predicate_p, reverse_p) {
// Apply prestationListFilter
var filteredSortedElfins = $filter('fontaineListFilter')(elfins_p, search_p);
filteredSortedElfins = $filter('fontaineListAnyFilter')(filteredSortedElfins, search_p.text);
// Apply predicate, reverse sorting
filteredSortedElfins = $filter('orderBy')(filteredSortedElfins, predicate_p, reverse_p);
return filteredSortedElfins;
};
/**
* Update filtered collection when search or sorting criteria are modified.
*/
$scope.$watch('[search,predicate,reverse]', function(newSearch, oldSearch) {
//$log.debug(">>>>> HbFontaineListController search, predicate or reverse UPDATED <<<<< \n" + angular.toJson(newSearch) );
if ($scope.elfins!=null) {
$scope.filteredElfins = filterSortElfins($scope.elfins, $scope.search, $scope.predicate, $scope.reverse);
}
}, true);
/**
* elfins can result from queries taking possibly seconds to tens of seconds to complete.
* This requires watching for elfins result availability before computing filteredElfins.length.
*/
$scope.$watch('elfins', function() {
if ($scope.elfins!=null) {
$scope.filteredElfins = filterSortElfins($scope.elfins, $scope.search, $scope.predicate, $scope.reverse);
} else {
//$log.debug(">>>>> HbFontaineListController elfins NOT YET LOADED <<<<<");
}
});
/**
* Set focus on the list global search field
*/
var focusOnSearchField = function() {
$('#globalSearchField').focus();
};
$timeout(focusOnSearchField, 250, false);
}]);
})();
| bsisa/hb-ui | main/src/fontaine/hbFontaineListController.js | JavaScript | gpl-2.0 | 2,720 |
import styles from './index.css'
import React from 'react'
export default React.createClass({
propTypes: {
isLoading: React.PropTypes.bool.isRequired
},
render() {
return (
<div className={
this.props.isLoading === true ? styles.show : styles.hide
}></div>
)
}
})
| ndxm/nd-react-scaffold | src/components/common/loading/index.js | JavaScript | gpl-2.0 | 306 |
$.ajax({
async: false,
url: "http://api.visalus.com/ITReporting/SalesAnalytics/GetDataBySP/?SPName=usp_PROMO_ViCrunch3FF_JSON&?",
type: 'GET',
dataType: 'jsonp',
success: function (data) {
var result = JSON.stringify(data);
//alert(result);
var obj = jQuery.parseJSON(result);
var output="<table class='standings-table' width='100%'><tr class='head'><td align='center'>Rank</td><td>Name</td><td>Location</td><td align='center'>VIP Tier</td></tr>";
for (var i in obj) {
output+="<tr><td align='center'>" + obj[i].Rank + "</td><td>" + obj[i].Name + "</td><td>" + obj[i].Location + "</td><td align='center'>" + obj[i].VIPtier + "</td></tr>";
}
output+="</table>";
document.getElementById("crunchtime").innerHTML = output;
},
error: function (e) {
alert('fail');
}
});
| tsmulugeta/vi.com | js/crunchtime.js | JavaScript | gpl-2.0 | 1,074 |
/*
* collection
* A collection of posts
*
* If fetch items are specified, then only gets those posts.
* Otherwise, gets the posts specified from a configuration endpoint.
*/
define([
"lodash",
"backbone",
"helpers/urls",
"helpers/types",
"helpers/params",
"components/content/entities/parser",
"module"
], function(_, Backbone, urls, types, params, parser, module) {
// Definition of a post collection
var PostCollection = Backbone.Collection.extend({
urlRoot: module.config().urlRoot,
initialize: function(models, options) {
options = options || {};
// preserve any options specified to constructor
this.options = _.extend(this.options || {}, options);
},
// remove fetch items as they become models
_maintainItems: function(model) {
this.options.items = _.reject(this.options.items, function(item) {
return item.object_id == model[types.objectIdType(item.object_id)];
});
if (this.options.items.length === 0) {
this.off("add", this.maintainItems, this);
}
},
// merge in additional fetch items after initialize
mergeItems: function(items) {
// remove any new fetch items that are already fetched
items = _.reject(items, function(item) {
return this.get(item.object_id);
}, this);
// create a union of previous fetch items and the new fetch items
this.options.items = _.union(this.options.items, items);
},
url: function() {
var fetchItems = this.options.items;
// if fetch items are specified, get the specific items
// object_ids all have to be homogenous (same types)
if (fetchItems && fetchItems.length > 0) {
var method = types.objectIdType(fetchItems[0].object_id);
var posts = params.collection[method](_.pluck(fetchItems, "object_id"));
// maintain the fetchItems as they are added
this.on("add", this._maintainItems, this);
return urls.normalizeUrlRoot(this.urlRoot) +
"?post_type=any" +
"&"+posts +
"&"+params.meta.custom_fields;
} else {
return module.config().endpoint;
}
},
parse: function(data) {
return parser(data);
}
});
return PostCollection;
}); | localnerve/wpspa | app/components/content/entities/collection.js | JavaScript | gpl-2.0 | 2,289 |
/**
* IRCAnywhere server/channels.js
*
* @title ChannelManager
* @copyright (c) 2013-2014 http://ircanywhere.com
* @license GPL v2
* @author Ricki Hastings
*/
var _ = require('lodash'),
hooks = require('hooks');
/**
* This object is responsible for managing everything related to channel records, such as
* the handling of joins/parts/mode changes/topic changes and such.
* As always these functions are extendable and can be prevented or extended by using hooks.
*
* @class ChannelManager
* @method ChannelManager
* @return void
*/
function ChannelManager() {
this.channel = {
network: '',
channel: '',
topic: {},
modes: ''
};
// a default channel object
}
/**
* Gets a tab record from the parameters passed in, strictly speaking this doesn't have to
* be a channel, a normal query window will also be returned. However this class doesn't
* need to work with anything other than channels.
*
* A new object is created but not inserted into the database if the channel doesn't exist.
*
* @method getChannel
* @param {String} network A network string such as 'freenode'
* @param {String} channel The name of a channel **with** the hash key '#ircanywhere'
* @return {Object} A channel object straight out of the database.
*/
ChannelManager.prototype.getChannel = function(network, channel) {
var chan = application.Tabs.sync.findOne({network: network, target: channel});
if (!chan) {
var chan = _.clone(this.channel);
chan.network = network;
chan.channel = channel;
}
return chan;
}
/**
* Inserts a user or an array of users into a channel record matching the network key
* network name and channel name, with the option to force an overwrite
*
* @method insertUsers
* @param {ObjectID} key A valid Mongo ObjectID for the networks collection
* @param {String} network The network name, such as 'freenode'
* @param {String} channel The channel name '#ircanywhere'
* @param {Array[Object]} users An array of valid user objects usually from a who/join output
* @param {Boolean} [force] Optional boolean whether to overwrite the contents of the channelUsers
* @return {Array} The final array of the users inserted
*/
ChannelManager.prototype.insertUsers = function(key, network, channel, users, force) {
var force = force || false,
channel = channel.toLowerCase(),
burst = (users.length > 1) ? true : false,
find = [],
chan = this.getChannel(key, channel),
finalArray = [];
for (var uid in users) {
var u = users[uid];
u.network = network;
u.channel = channel;
u._burst = burst;
find.push(u.nickname);
if (u.nickname == Clients[key].nick) {
application.Networks.sync.update({_id: key}, {$set: {hostname: u.hostname}});
}
// update hostname
}
// turn this into an array of nicknames
if (force) {
application.ChannelUsers.sync.remove({network: network, channel: channel});
} else {
application.ChannelUsers.sync.remove({network: network, channel: channel, nickname: {$in: find}});
}
// ok so here we've gotta remove any users in the channel already
// and all of them if we're being told to force the update
for (var uid in users) {
var u = users[uid],
prefix = eventManager.getPrefix(Clients[key], u);
u.sort = prefix.sort;
u.prefix = prefix.prefix;
finalArray.push(u);
}
// send the update out
if (finalArray.length > 0) {
return application.ChannelUsers.sync.insert(finalArray);
} else {
return [];
}
}
/**
* Removes a specific user from a channel, if users is omitted, channel should be equal to a nickname
* and that nickname will be removed from all channels records on that network.
*
* @method removeUsers
* @param {String} network A valid network name
* @param {String} [channel] A valid channel name
* @param {Array} users An array of users to remove from the network `or` channel
* @return void
*/
ChannelManager.prototype.removeUsers = function(network, channel, users) {
var channel = (_.isArray(channel)) ? channel : channel.toLowerCase(),
users = (_.isArray(channel)) ? channel : users;
// basically we check if channel is an array, if it is we're being told to
// just remove the user from the entire network (on quits etc)
if (users.length === 0) {
return false;
}
if (_.isArray(channel)) {
application.ChannelUsers.remove({network: network, nickname: {$in: users}}, {safe: false});
} else {
application.ChannelUsers.remove({network: network, channel: channel, nickname: {$in: users}}, {safe: false});
}
// send the update out
}
/**
* Updates a user or an array of users from the specific channel with the values passed in.
*
* @method updateUsers
* @param {ObjectID} key A valid Mongo ObjectID for the networks collection
* @param {String} network The name of the network
* @param {Array} users A valid users array
* @param {Object} values A hash of keys and values to be replaced in the users array
* @return void
*/
ChannelManager.prototype.updateUsers = function(key, network, users, values) {
var update = {};
for (var uid in users) {
var u = users[uid],
s = {network: network, nickname: u},
records = application.ChannelUsers.sync.find(s).sync.toArray();
for (var rid in records) {
var user = records[rid];
var updated = _.extend(user, values);
updated.sort = eventManager.getPrefix(Clients[key], updated).sort;
application.ChannelUsers.sync.update(s, _.omit(updated, '_id'));
// update the record
}
}
// this is hacky as hell I feel but it's getting done this way to
// comply with all the other functions in this class
}
/**
* Takes a mode string, parses it and handles any updates to any records relating to
* the specific channel. This handles user updates and such, it shouldn't really be called
* externally, however can be pre and post hooked like all other functions in this object.
*
* @method updateModes
* @param {ObjectID} key A valid Mongo ObjectID for the networks collection
* @param {Object} capab A valid capabilities object from the 'registered' event
* @param {String} network Network name
* @param {String} channel Channel name
* @param {String} mode Mode string
* @return void
*/
ChannelManager.prototype.updateModes = function(key, capab, network, channel, mode) {
var channel = channel.toLowerCase(),
chan = this.getChannel(key, channel),
us = {};
var users = application.ChannelUsers.sync.find({network: network, channel: channel}).sync.toArray(),
parsedModes = modeParser.sortModes(capab, mode);
// we're not arsed about the channel or network here
var modes = modeParser.changeModes(capab, chan.modes, parsedModes);
// we need to attempt to update the record now with the new info
application.Tabs.update({network: key, target: channel}, {$set: {modes: modes}}, {safe: false});
// update the record
users.forEach(function(u) {
delete u._id;
us[u.nickname] = u;
});
modeParser.handleParams(capab, us, parsedModes).forEach(function(u) {
var prefix = eventManager.getPrefix(Clients[key], u);
u.sort = prefix.sort;
u.prefix = prefix.prefix;
application.ChannelUsers.update({network: network, channel: channel, nickname: u.nickname}, u, {safe: false});
});
// update users now
}
/**
* Updates the specific channel's topic and setby in the internal records.
*
* @method updateTopic
* @param {ObjectID} key A valid Mongo ObjectID for the networks collection
* @param {String} channel A valid channel name
* @param {String} topic The new topic
* @param {String} setby A setter string, usually in the format of 'nickname!username@hostname'
* @return void
*/
ChannelManager.prototype.updateTopic = function(key, channel, topic, setby) {
var channel = channel.toLowerCase(),
chan = this.getChannel(key, channel);
var topic = {
topic: topic,
setter: setby || ''
};
// updat the topic record
application.Tabs.update({network: key, target: channel}, {$set: {topic: topic}}, {safe: false});
// update the record
}
exports.ChannelManager = _.extend(ChannelManager, hooks); | KenanSulayman/ircanywhere | server/channels.js | JavaScript | gpl-2.0 | 8,230 |
showWord(["v. ","korije, redrese."
]) | georgejhunt/HaitiDictionary.activity | data/words/rektifye.js | JavaScript | gpl-2.0 | 37 |
showWord(["n. "," aktivite pou al chase bèt sovaj pou vyann nan osnon pou po. Mwen pa janm al lachas, paske mwen pa gen kè pou mwen touye okenn bèt."
]) | georgejhunt/HaitiDictionary.activity | data/words/lachas.js | JavaScript | gpl-2.0 | 155 |
/*
* Copyright 2013 IMOS
*
* The AODN/IMOS Portal is distributed under the terms of the GNU General Public License
*
*/
describe('Portal.data.GeoNetworkRecord', function() {
var record;
beforeEach(function() {
record = new Portal.data.GeoNetworkRecord({
abstract: 'the abstract',
links: [
{
href: 'http://geoserver.imos.org.au/geoserver/wms',
name: 'imos:radar_stations',
protocol: 'OGC:WMS-1.1.1-http-get-map',
title: 'ACORN Radar Stations',
type: 'application/vnd.ogc.wms_xml'
},
{
href: 'http://geonetwork.imos.org.au/1234',
name: 'imos:radar_stations',
protocol: 'WWW:LINK-1.0-http--metadata-URL',
title: 'ACORN Radar Stations',
type: 'text/html'
}
],
title: 'the layer title',
wmsLayer: {
server: {
uri: "server_url"
},
params: {
LAYERS: 'layer name',
CQL_FILTER: 'cql_filter'
},
someUnusedField: 'la la la'
}
});
});
describe('wms link', function() {
it('has wms link', function() {
record.get('links')[0].protocol = 'OGC:WMS-1.1.1-http-get-map';
expect(record.hasWmsLink()).toBeTruthy();
});
it('does not have wms link', function() {
record.get('links')[0].protocol = 'some protocol';
expect(record.hasWmsLink()).toBeFalsy();
});
it('does not have any links', function() {
record.set('links', undefined);
expect(record.hasWmsLink()).toBeFalsy();
});
it('get first wms link', function() {
record.get('links')[0].protocol = 'OGC:WMS-1.1.1-http-get-map';
var link = record.getFirstWmsLink();
expect(link.server.uri).toBe('http://geoserver.imos.org.au/geoserver/wms');
expect(link.protocol).toBe('OGC:WMS-1.1.1-http-get-map');
});
});
});
| IMASau/aodn-portal | src/test/javascript/portal/data/GeoNetworkRecordSpec.js | JavaScript | gpl-3.0 | 2,250 |
/**
Template Controllers
@module Templates
*/
/**
The dashboard template
@class [template] views_dashboard
@constructor
*/
Template['views_dashboard'].helpers({
/**
Get all current wallets
@method (wallets)
*/
'wallets': function(disabled){
var wallets = Wallets.find({disabled: disabled}, {sort: {creationBlock: 1}}).fetch();
// sort wallets by balance
wallets.sort(Helpers.sortByBalance);
return wallets;
},
/**
Get all current accounts
@method (accounts)
*/
'accounts': function(){
// balance need to be present, to show only full inserted accounts (not ones added by mist.requestAccount)
var accounts = EthAccounts.find({name: {$exists: true}}, {sort: {name: 1}}).fetch();
accounts.sort(Helpers.sortByBalance);
return accounts;
},
/**
Are there any accounts?
@method (hasAccounts)
*/
'hasAccounts' : function() {
return (EthAccounts.find().count() > 0);
},
/**
Are there any accounts?
@method (hasAccounts)
*/
'hasMinimumBalance' : function() {
var enoughBalance = false;
_.each(_.pluck(EthAccounts.find({}).fetch(), 'balance'), function(bal){
if(new BigNumber(bal, '10').gt(1000000000000000000)) enoughBalance = true;
});
return enoughBalance;
},
/**
Get all transactions
@method (allTransactions)
*/
'allTransactions': function(){
return Transactions.find({}, {sort: {timestamp: -1}}).count();
},
/**
Returns an array of pending confirmations, from all accounts
@method (pendingConfirmations)
@return {Array}
*/
'pendingConfirmations': function(){
return _.pluck(PendingConfirmations.find({operation: {$exists: true}, confirmedOwners: {$ne: []}}).fetch(), '_id');
}
});
Template['views_dashboard'].events({
/**
Request to create an account in mist
@event click .create.account
*/
'click .create.account': function(e){
e.preventDefault();
mist.requestAccount(function(e, account) {
if(!e) {
account = account.toLowerCase();
EthAccounts.upsert({address: account}, {$set: {
address: account,
new: true
}});
}
});
}
}); | EarthDollar/ed-meteor-dapp-wallet | app/client/templates/views/dashboard.js | JavaScript | gpl-3.0 | 2,400 |
'use strict';
angular.module("ngLocale", [], ["$provide", function($provide) {
var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"};
function getDecimals(n) {
n = n + '';
var i = n.indexOf('.');
return (i == -1) ? 0 : n.length - i - 1;
}
function getVF(n, opt_precision) {
var v = opt_precision;
if (undefined === v) {
v = Math.min(getDecimals(n), 3);
}
var base = Math.pow(10, v);
var f = ((n * base) | 0) % base;
return {v: v, f: f};
}
$provide.value("$locale", {
"DATETIME_FORMATS": {
"AMPMS": [
"vorm.",
"nachm."
],
"DAY": [
"Sonntag",
"Montag",
"Dienstag",
"Mittwoch",
"Donnerstag",
"Freitag",
"Samstag"
],
"ERANAMES": [
"v. Chr.",
"n. Chr."
],
"ERAS": [
"v. Chr.",
"n. Chr."
],
"FIRSTDAYOFWEEK": 0,
"MONTH": [
"Januar",
"Februar",
"M\u00e4rz",
"April",
"Mai",
"Juni",
"Juli",
"August",
"September",
"Oktober",
"November",
"Dezember"
],
"SHORTDAY": [
"So.",
"Mo.",
"Di.",
"Mi.",
"Do.",
"Fr.",
"Sa."
],
"SHORTMONTH": [
"Jan.",
"Feb.",
"M\u00e4rz",
"Apr.",
"Mai",
"Juni",
"Juli",
"Aug.",
"Sep.",
"Okt.",
"Nov.",
"Dez."
],
"STANDALONEMONTH": [
"Januar",
"Februar",
"M\u00e4rz",
"April",
"Mai",
"Juni",
"Juli",
"August",
"September",
"Oktober",
"November",
"Dezember"
],
"WEEKENDRANGE": [
5,
6
],
"fullDate": "EEEE, d. MMMM y",
"longDate": "d. MMMM y",
"medium": "dd.MM.y HH:mm:ss",
"mediumDate": "dd.MM.y",
"mediumTime": "HH:mm:ss",
"short": "dd.MM.yy HH:mm",
"shortDate": "dd.MM.yy",
"shortTime": "HH:mm"
},
"NUMBER_FORMATS": {
"CURRENCY_SYM": "CHF",
"DECIMAL_SEP": ".",
"GROUP_SEP": "'",
"PATTERNS": [
{
"gSize": 3,
"lgSize": 3,
"maxFrac": 3,
"minFrac": 0,
"minInt": 1,
"negPre": "-",
"negSuf": "",
"posPre": "",
"posSuf": ""
},
{
"gSize": 3,
"lgSize": 3,
"maxFrac": 2,
"minFrac": 2,
"minInt": 1,
"negPre": "\u00a4-",
"negSuf": "",
"posPre": "\u00a4\u00a0",
"posSuf": ""
}
]
},
"id": "de-ch",
"localeID": "de_CH",
"pluralCat": function(n, opt_precision) { var i = n | 0; var vf = getVF(n, opt_precision); if (i == 1 && vf.v == 0) { return PLURAL_CATEGORY.ONE; } return PLURAL_CATEGORY.OTHER;}
});
}]);
| espringtran/travis-web-fonts | test/vendors/angular-1.5.5/i18n/angular-locale_de-ch.js | JavaScript | gpl-3.0 | 2,891 |
/************************************************************************
* This file is part of EspoCRM.
*
* EspoCRM - Open Source CRM application.
* Copyright (C) 2014-2021 Yurii Kuznietsov, Taras Machyshyn, Oleksii Avramenko
* Website: https://www.espocrm.com
*
* EspoCRM 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 3 of the License, or
* (at your option) any later version.
*
* EspoCRM 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 EspoCRM. If not, see http://www.gnu.org/licenses/.
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU General Public License version 3.
*
* In accordance with Section 7(b) of the GNU General Public License version 3,
* these Appropriate Legal Notices must retain the display of the "EspoCRM" word.
************************************************************************/
Espo.define('views/record/detail-small', 'views/record/detail', function (Dep) {
return Dep.extend({
bottomView: null
});
});
| ayman-alkom/espocrm | client/src/views/record/detail-small.js | JavaScript | gpl-3.0 | 1,503 |
Simpla CMS 2.3.8 = 1040075c69dc0e56580b73f479381087
| gohdan/DFC | known_files/hashes/simpla/design/js/codemirror/mode/octave/octave.js | JavaScript | gpl-3.0 | 52 |
reportico_jquery = jQuery.noConflict();
var reportico_ajax_script = "index.php";
/*
** Reportico Javascript functions
*/
function setupDynamicGrids()
{
if (typeof reportico_dynamic_grids === 'undefined') {
return;
}
if ( reportico_jquery.type(reportico_dynamic_grids) != 'undefined' )
if ( reportico_dynamic_grids )
{
reportico_jquery(".swRepPage").each(function(){
reportico_jquery(this).dataTable(
{
"retrieve" : true,
"searching" : reportico_dynamic_grids_searchable,
"ordering" : reportico_dynamic_grids_sortable,
"paging" : reportico_dynamic_grids_paging,
"iDisplayLength": reportico_dynamic_grids_page_size
}
);
});
}
}
function setupDatePickers()
{
reportico_jquery(".swDateField").each(function(){
reportico_jquery(this).datepicker({dateFormat: reportico_datepicker_language});
});
}
function setupModals()
{
var options = {
}
reportico_jquery('#reporticoModal').modal(options);
}
function setupDropMenu()
{
if ( reportico_jquery('ul.jd_menu').length != 0 )
{
reportico_jquery('ul.jd_menu').jdMenu();
//reportico_jquery(document).bind('click', function() {
//reportico_jquery('ul.jd_menu ul:visible').jdMenuHide();
//});
}
}
/*
* Where multiple data tables exist due to graphs
* resize the columns of all tables to match the first
*/
function resizeHeaders()
{
// Size page header blocks to fit page headers
reportico_jquery(".swPageHeaderBlock").each(function() {
var maxheight = 0;
reportico_jquery(this).find(".swPageHeader").each(function() {
var headerheight = reportico_jquery(this).height();
if ( headerheight > maxheight )
maxheight = headerheight;
});
reportico_jquery(this).css("height", maxheight + "px");
});
//reportico_jquery(".swRepForm").columnize();
}
/*
* Where multiple data tables exist due to graphs
* resize the columns of all tables to match the first
*/
function resizeTables()
{
var tableArr = reportico_jquery('.swRepPage');
var tableDataRow = reportico_jquery('.swRepResultLine:first');
var cellWidths = new Array();
reportico_jquery(tableDataRow).each(function() {
for(j = 0; j < reportico_jquery(this)[0].cells.length; j++){
var cell = reportico_jquery(this)[0].cells[j];
if(!cellWidths[j] || cellWidths[j] < cell.clientWidth) cellWidths[j] = cell.clientWidth;
}
});
var tablect = 0;
reportico_jquery(tableArr).each(function() {
tablect++;
if ( tablect == 1 )
return;
reportico_jquery(this).find(".swRepResultLine:first").each(function() {
for(j = 0; j < reportico_jquery(this)[0].cells.length; j++){
reportico_jquery(this)[0].cells[j].style.width = cellWidths[j]+'px';
}
});
});
}
//reportico_jquery(document).on('click', 'ul.dropdown-menu li a, ul.dropdown-menu li ul li a, ul.jd_menu li a, ul.jd_menu li ul li a', function(event)
//{
//event.preventDefault();
//return false;
//});
reportico_jquery(document).on('click', 'a.reportico-dropdown-item, ul li.r1eportico-dropdown a, ul li ul.reportico-dropdown li a, ul.jd_menu li a, ul.jd_menu li ul li a', function(event)
{
if ( reportico_jquery.type(reportico_ajax_mode) === 'undefined' || !reportico_ajax_mode)
{
return true;
}
var url = reportico_jquery(this).prop('href');
runreport(url, this);
event.preventDefault();
return false;
});
/* Load Date Pickers */
reportico_jquery(document).ready(function()
{
setupDatePickers();
setupDropMenu();
resizeHeaders();
resizeTables();
setupDynamicGrids();
});
reportico_jquery(document).on('click', '.reportico-bootstrap-modal-close', function(event)
{
reportico_jquery("#swMiniMaintain").html("");
reportico_jquery('#reporticoModal').modal('hide');
});
reportico_jquery(document).on('click', '.reportico-modal-close', function(event)
{
reportico_jquery("#swMiniMaintain").html("");
reportico_jquery('#reporticoModal').hide();
});
reportico_jquery(document).on('click', '.swMiniMaintainSubmit', function(event)
{
if ( reportico_bootstrap_modal )
var loadpanel = reportico_jquery("#reporticoModal .modal-dialog .modal-content .modal-header");
else
var loadpanel = reportico_jquery("#reporticoModal .reportico-modal-dialog .reportico-modal-content .reportico-modal-header");
var expandpanel = reportico_jquery('#swPrpExpandCell');
reportico_jquery(loadpanel).addClass("modal-loading");
forms = reportico_jquery(this).closest('#reportico_container').find(".swPrpForm");
if ( reportico_jquery.type(reportico_ajax_script) === 'undefined' )
{
var ajaxaction = reportico_jquery(forms).prop("action");
}
else
{
ajaxaction = reportico_ajax_script;
}
params = forms.serialize();
params += "&" + reportico_jquery(this).prop("name") + "=1";
params += "&reportico_ajax_called=1";
params += "&execute_mode=PREPARE";
var cont = this;
reportico_jquery.ajax({
type: 'POST',
url: ajaxaction,
data: params,
dataType: 'html',
success: function(data, status)
{
reportico_jquery(loadpanel).removeClass("modal-loading");
if ( reportico_bootstrap_modal )
{
reportico_jquery('#reporticoModal').modal('hide');
reportico_jquery('.modal-backdrop').remove();
reportico_jquery('#reportico_container').closest('body').removeClass('modal-open');
}
else
reportico_jquery('#reporticoModal').hide();
reportico_jquery("#swMiniMaintain").html("");
//reportico_jquery(reportico_container).removeClass("loading");
fillDialog(data, cont);
},
error: function(xhr, desc, err) {
reportico_jquery("#swMiniMaintain").html("");
reportico_jquery('#reporticoModal').modal('hide');
reportico_jquery('.modal-backdrop').remove();
reportico_jquery(loadpanel).removeClass("modal-loading");
reportico_jquery(loadpanel).prop('innerHTML',"Ajax Error: " + xhr + "\nTextStatus: " + desc + "\nErrorThrown: " + err);
}
});
return false;
});
/*
** Trigger AJAX request for reportico button/link press if running in AJAX mode
** AJAX mode is in place when reportico session ("reportico_ajax_script") is set
** will generate full reportico output to replace the reportico_container tag
*/
reportico_jquery(document).on('click', '.swMiniMaintain', function(event)
{
var expandpanel = reportico_jquery(this).closest('#criteriaform').find('#swPrpExpandCell');
var reportico_container = reportico_jquery(this).closest("#reportico_container");
reportico_jquery(expandpanel).addClass("loading");
forms = reportico_jquery(this).closest('.swMntForm,.swPrpForm,form');
if ( reportico_jquery.type(reportico_ajax_script) === 'undefined' )
{
var ajaxaction = reportico_jquery(forms).prop("action");
}
else
{
ajaxaction = reportico_ajax_script;
}
maintainButton = reportico_jquery(this).prop("name");
reportico_jquery(".reportico-modal-title").html(reportico_jquery(this).prop("title"));
bits = maintainButton.split("_");
params = forms.serialize();
params += "&execute_mode=MAINTAIN&partialMaintain=" + maintainButton + "&partial_template=mini&submit_" + bits[0] + "_SHOW=1";
params += "&reportico_ajax_called=1";
reportico_jquery.ajax({
type: 'POST',
url: ajaxaction,
data: params,
dataType: 'html',
success: function(data, status)
{
reportico_jquery(expandpanel).removeClass("loading");
reportico_jquery(reportico_container).removeClass("loading");
if ( reportico_bootstrap_modal )
setupModals();
else
reportico_jquery("#reporticoModal").show();
reportico_jquery("#swMiniMaintain").html(data);
x = reportico_jquery(".swMntButton").prop("name");
reportico_jquery(".swMiniMaintainSubmit").prop("id", x);
},
error: function(xhr, desc, err) {
reportico_jquery(expandpanel).removeClass("loading");
reportico_jquery(reportico_container).removeClass("loading");
reportico_jquery(expandpanel).prop('innerHTML',"Ajax Error: " + xhr + "\nTextStatus: " + desc + "\nErrorThrown: " + err);
}
});
return false;
})
/*
** Trigger AJAX request for reportico button/link press if running in AJAX mode
** AJAX mode is in place when reportico session ("reportico_ajax_script") is set
** will generate full reportico output to replace the reportico_container tag
*/
reportico_jquery(document).on('click', '.swAdminButton, .swAdminButton2, .swMenuItemLink, .swPrpSubmit, .swLinkMenu, .swLinkMenu2, .reporticoSubmit', function(event)
{
if ( reportico_jquery(this).hasClass("swNoSubmit" ) )
{
return false;
}
if ( reportico_jquery(this).parents("#swMiniMaintain").length == 1 )
{
var expandpanel = reportico_jquery(this).closest('#criteriaform').find('#swPrpExpandCell');
if ( reportico_bootstrap_modal )
var loadpanel = reportico_jquery("#reporticoModal .modal-dialog .modal-content .modal-header");
else
var loadpanel = reportico_jquery("#reporticoModal .reportico-modal-dialog .reportico-modal-content .reportico-modal-header");
var reportico_container = reportico_jquery(this).closest("#reportico_container");
reportico_jquery(loadpanel).addClass("modal-loading");
forms = reportico_jquery(this).closest('.swMiniMntForm');
if ( reportico_jquery.type(reportico_ajax_script) === 'undefined' )
{
var ajaxaction = reportico_jquery(forms).prop("action");
}
else
{
ajaxaction = reportico_ajax_script;
}
params = forms.serialize();
maintainButton = reportico_jquery(this).prop("name");
params += "&execute_mode=MAINTAIN&partial_template=mini";
params += "&" + reportico_jquery(this).prop("name") + "=1";
params += "&reportico_ajax_called=1";
reportico_jquery.ajax({
type: 'POST',
url: ajaxaction,
data: params,
dataType: 'html',
success: function(data, status)
{
reportico_jquery(loadpanel).removeClass("modal-loading");
if ( reportico_bootstrap_modal )
setupModals();
reportico_jquery("#swMiniMaintain").html(data);
x = reportico_jquery(".swMntButton").prop("name");
reportico_jquery(".swMiniMaintainSubmit").prop("id", x);
},
error: function(xhr, desc, err) {
reportico_jquery(loadpanel).removeClass("modal-loading");
reportico_jquery(expandpanel).prop('innerHTML',"Ajax Error: " + xhr + "\nTextStatus: " + desc + "\nErrorThrown: " + err);
}
});
return false;
}
if ( reportico_jquery(this).parent().hasClass("swRepPrintBox" ) )
{
//var data = reportico_jquery(this).closest("#reportico_container").html();
//html_print(data);
window.print();
return false;
}
if ( reportico_jquery.type(reportico_ajax_mode) === 'undefined' || !reportico_ajax_mode)
{
return true;
}
var expandpanel = reportico_jquery(this).closest('#criteriaform').find('#swPrpExpandCell');
var reportico_container = reportico_jquery(this).closest("#reportico_container");
if ( !reportico_jquery(this).prop("href") )
{
reportico_jquery(expandpanel).addClass("loading");
reportico_jquery(reportico_container).addClass("loading");
forms = reportico_jquery(this).closest('.swMntForm,.swPrpForm,form');
if ( reportico_jquery.type(reportico_ajax_script) === 'undefined' )
{
var ajaxaction = reportico_jquery(forms).prop("action");
}
else
{
ajaxaction = reportico_ajax_script;
}
params = forms.serialize();
params += "&" + reportico_jquery(this).prop("name") + "=1";
params += "&reportico_ajax_called=1";
csvpdfoutput = false;
if ( reportico_jquery(this).prop("name") != "submit_design_mode" )
reportico_jquery(reportico_container).find("input:radio").each(function() {
d = 0;
nm = reportico_jquery(this).prop("value");
chk = reportico_jquery(this).prop("checked");
if ( chk && ( nm == "PDF" || nm == "CSV" ) )
csvpdfoutput = true;
});
if ( csvpdfoutput )
{
var windowSizeArray = [ "width=200,height=200",
"width=300,height=400,scrollbars=yes" ];
var url = ajaxaction +"?" + params;
var windowName = "popUp";//reportico_jquery(this).prop("name");
var windowSize = windowSizeArray[reportico_jquery(this).prop("rel")];
window.open(url, windowName, "width=200,height=200");
reportico_jquery(expandpanel).removeClass("loading");
reportico_jquery(reportico_container).removeClass("loading");
return false;
}
var cont = this;
reportico_jquery.ajax({
type: 'POST',
url: ajaxaction,
data: params,
dataType: 'html',
success: function(data, status)
{
reportico_jquery(expandpanel).removeClass("loading");
reportico_jquery(reportico_container).removeClass("loading");
fillDialog(data, cont);
},
error: function(xhr, desc, err) {
reportico_jquery(expandpanel).removeClass("loading");
reportico_jquery(reportico_container).removeClass("loading");
reportico_jquery(expandpanel).prop('innerHTML',"Ajax Error: " + xhr + "\nTextStatus: " + desc + "\nErrorThrown: " + err);
}
});
return false;
}
else
{
url = reportico_jquery(this).prop("href");
params = false;
runreport(url, this);
}
return false;
})
/*
** Called when used presses ok in expand mode to
** refresh middle prepare mode section with non expand mode
** text
*/
reportico_jquery(document).on('click', '#returnFromExpand', function() {
var critform = reportico_jquery(this).closest('#criteriaform');
var expandpanel = reportico_jquery(this).closest('#criteriaform').find('#swPrpExpandCell');
reportico_jquery(expandpanel).addClass("loading");
var params = reportico_jquery(critform).serialize();
params += "&execute_mode=PREPARE";
params += "&partial_template=critbody";
params += "&" + reportico_jquery(this).prop("name") + "=1";
forms = reportico_jquery(this).closest('.swMntForm,.swPrpForm,form');
ajaxaction = reportico_ajax_script;
fillPoint = reportico_jquery(this).closest('#criteriaform').find('#criteriabody');
reportico_jquery.ajax({
type: 'POST',
url: ajaxaction,
data: params,
dataType: 'html',
success: function(data, status) {
reportico_jquery(expandpanel).removeClass("loading");
reportico_jquery(fillPoint).html(data);
setupDatePickers();
setupDropMenu();
},
error: function(xhr, desc, err) {
reportico_jquery(expandpanel).removeClass("loading");
reportico_jquery(fillPoint).prop('innerHTML',"Ajax Error: " + xhr + "\nTextStatus: " + desc + "\nErrorThrown: " + err);
}
});
return false;
});
reportico_jquery(document).on('click', '#reporticoPerformExpand', function() {
forms = reportico_jquery(this).closest('.swMntForm,.swPrpForm,form');
var ajaxaction = reportico_jquery(forms).prop("action");
var critform = reportico_jquery(this).closest('#criteriaform');
ajaxaction = reportico_ajax_script;
var params = reportico_jquery(critform).serialize();
params += "&execute_mode=PREPARE";
params += "&partial_template=expand";
params += "&" + reportico_jquery(this).prop("name") + "=1";
var fillPoint = reportico_jquery(this).closest('#criteriaform').find('#swPrpExpandCell');
reportico_jquery(fillPoint).addClass("loading");
reportico_jquery.ajax({
type: 'POST',
url: ajaxaction,
data: params,
dataType: 'html',
success: function(data, status) {
reportico_jquery(fillPoint).removeClass("loading");
reportico_jquery(fillPoint).html(data);
},
error: function(xhr, desc, err) {
reportico_jquery(fillPoint).removeClass("loading");
reportico_jquery(fillPoint).prop('innerHTML',"Ajax Error: " + xhr + "\nTextStatus: " + desc + "\nErrorThrown: " + err);
}
});
return false;
});
/*
** AJAX call to run a report
** In pdf/csv mode this needs to trigger opening of a new browser window
** with output in rather that directing to screen
*/
reportico_jquery(document).on('click', '.swPrintBox,.prepareAjaxExecute,#prepareAjaxExecute', function() {
var reportico_container = reportico_jquery(this).closest("#reportico_container");
reportico_jquery(reportico_container).find("#rpt_format_pdf").prop("checked", false );
reportico_jquery(reportico_container).find("#rpt_format_csv").prop("checked", false );
reportico_jquery(reportico_container).find("#rpt_format_html").prop("checked", false );
reportico_jquery(reportico_container).find("#rpt_format_json").prop("checked", false );
reportico_jquery(reportico_container).find("#rpt_format_xml").prop("checked", false );
if ( reportico_jquery(this).hasClass("swPDFBox") )
reportico_jquery(reportico_container).find("#rpt_format_pdf").prop("checked", "checked");
if ( reportico_jquery(this).hasClass("swCSVBox") )
reportico_jquery(reportico_container).find("#rpt_format_csv").prop("checked", "checked");
if ( reportico_jquery(this).hasClass("swHTMLBox") )
reportico_jquery(reportico_container).find("#rpt_format_html").prop("checked", "checked");
if ( reportico_jquery(this).hasClass("swHTMLGoBox") )
reportico_jquery(reportico_container).find("#rpt_format_html").prop("checked", "checked");
if ( reportico_jquery(this).hasClass("swXMLBox") )
reportico_jquery(reportico_container).find("#rpt_format_xml").prop("checked", "checked");
if ( reportico_jquery(this).hasClass("swJSONBox") )
reportico_jquery(reportico_container).find("#rpt_format_json").prop("checked", "checked");
if ( reportico_jquery(this).hasClass("swPrintBox") )
reportico_jquery(reportico_container).find("#rpt_format_html").prop("checked", "checked");
if ( !reportico_jquery(this).hasClass("swPrintBox") )
if ( reportico_jquery.type(reportico_ajax_mode) === 'undefined' || !reportico_ajax_mode)
{
return true;
}
var expandpanel = reportico_jquery(this).closest('#criteriaform').find('#swPrpExpandCell');
var critform = reportico_jquery(this).closest('#criteriaform');
reportico_jquery(expandpanel).addClass("loading");
params = reportico_jquery(critform).serialize();
params += "&execute_mode=EXECUTE";
params += "&" + reportico_jquery(this).prop("name") + "=1";
forms = reportico_jquery(this).closest('.swMntForm,.swPrpForm,form');
if ( jQuery.type(reportico_ajax_script) === 'undefined' || !reportico_ajax_script )
{
var ajaxaction = reportico_jquery(forms).prop("action");
}
else
{
ajaxaction = reportico_ajax_script;
}
var csvpdfoutput = false;
var htmloutput = false;
reportico_report_title = reportico_jquery(this).closest('#reportico_container').find('.swTitle').html();
if ( !reportico_jquery(this).hasClass("swPrintBox") )
{
reportico_jquery(reportico_container).find("input:radio").each(function() {
d = 0;
nm = reportico_jquery(this).prop("value");
chk = reportico_jquery(this).prop("checked");
if ( chk && ( nm == "PDF" || nm == "CSV" ) )
csvpdfoutput = true;
//if ( chk && ( nm == "HTML" ) )
//htmloutput = true;
});
}
if ( csvpdfoutput )
{
var windowSizeArray = [ "width=200,height=200",
"width=300,height=400,scrollbars=yes" ];
var url = ajaxaction +"?" + params;
var windowName = "popUp";//reportico_jquery(this).prop("name");
var windowSize = windowSizeArray[reportico_jquery(this).prop("rel")];
window.open(url, windowName, "width=200,height=200");
reportico_jquery(expandpanel).removeClass("loading");
return false;
}
if ( reportico_jquery(this).hasClass("swPrintBox") )
{
htmloutput = true;
}
if ( !htmloutput )
params += "&reportico_ajax_called=1";
if ( reportico_jquery(this).hasClass("swPrintBox") )
params += "&printable_html=1&new_reportico_window=1";
var cont = this;
reportico_jquery.ajax({
type: 'POST',
url: ajaxaction,
data: params,
dataType: 'html',
success: function(data, status) {
reportico_jquery(expandpanel).removeClass("loading");
if ( htmloutput )
{
html_print(reportico_report_title, data);
}
else
fillDialog(data, cont);
},
error: function(xhr, desc, err) {
reportico_jquery(expandpanel).removeClass("loading");
try {
// a try/catch is recommended as the error handler
// could occur in many events and there might not be
// a JSON response from the server
var errstatus = reportico_jquery.parseJSON(xhr.responseText);
var msg = errstatus.errmsg;
//reportico_jquery(expandpanel).prop('innerHTML', msg);
alert(msg);
} catch(e) {
reportico_jquery(expandpanel).prop('innerHTML',"Error occurred in data request. Error " + xhr.status + ": " + xhr.statusText);
}
}
});
return false;
});
/*
** Runs an AJAX reportico request from a link
*/
function runreport(url, container)
{
url += "&reportico_template=";
url += "&reportico_ajax_called=1";
reportico_jquery(container).closest("#reportico_container").addClass("loading");
reportico_jquery.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: url,
dataType: "html",
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert ("Ajax Error: " + XMLHttpRequest.responseText + "\nTextStatus: " + textStatus + "\nErrorThrown: " + errorThrown);
},
success: function(data, status) {
reportico_jquery(container).closest("#reportico_container").removeClass("loading");
fillDialog(data,container);
}
});
}
function fillDialog(results, cont) {
x = reportico_jquery(cont).closest("#reportico_container");
reportico_jquery(cont).closest("#reportico_container").replaceWith(results);
setupDatePickers();
setupDropMenu();
setupDynamicGrids();
resizeHeaders();
resizeTables();
}
var ie7 = (document.all && !window.opera && window.XMLHttpRequest) ? true : false;
/*
** Shows and hides a block of design items fields
*/
function toggleLine(id) {
var a = this;
var nm = a.id;
var togbut = document.getElementById(id);
var ele = document.getElementById("toggleText");
var elems = document.getElementsByTagName('*'),i;
for (i in elems)
{
if ( ie7 )
{
if((" "+elems[i].className+" ").indexOf(" "+id+" ") > -1)
{
if(elems[i].style.display == "inline") {
elems[i].style.display = "none";
togbut.innerHTML = "+";
}
else {
togbut.innerHTML = "-";
elems[i].style.display = "";
elems[i].style.display = "inline";
}
}
}
else
{
if((" "+elems[i].className+" ").indexOf(" "+id+" ") > -1)
{
if(elems[i].style.display == "table-row") {
elems[i].style.display = "none";
togbut.innerHTML = "+";
}
else {
togbut.innerHTML = "-";
elems[i].style.display = "";
elems[i].style.display = "table-row";
}
}
}
}
}
reporticohtmlwindow = null;
function html_div_print(data)
{
var reporticohtmlwindow = window.open('oooo', reportico_report_title, 'height=600,width=800');
reporticohtmlwindow.document.write('<html><head><title>' + reportico_report_title + '</title>');
reporticohtmlwindow.document.write('<link rel="stylesheet" href="' + reportico_css_path + '" type="text/css" />');
reporticohtmlwindow.document.write('</head><body >');
reporticohtmlwindow.document.write(data);
reporticohtmlwindow.document.write('</body></html>');
reporticohtmlwindow.print();
reporticohtmlwindow.close();
return true;
}
function html_print(title, data)
{
if (navigator.userAgent.indexOf('Chrome/') > 0) {
if (reporticohtmlwindow) {
reporticohtmlwindow.close();
reporticohtmlwindow = null;
}
}
reporticohtmlwindow = window.open('', "reportico_print", 'location=no,scrollbars=yes,status=no,height=600,width=800');
d = reporticohtmlwindow.document.open("text/html","replace");
reporticohtmlwindow.document.write(data);
reporticohtmlwindow.document.close();
setTimeout(html_print_fix,200);
reporticohtmlwindow.focus();
return true;
}
function html_print_fix()
{
if(!reporticohtmlwindow.resizeOutputTables)
{
setTimeout(html_print_fix,1000);
}
else
{
reporticohtmlwindow.resizeOutputTables(reporticohtmlwindow);
}
}
| grupo-glud/EcoHack | plugin/reportico/script/reportico/js/reportico.js | JavaScript | gpl-3.0 | 27,172 |
/*
* Copyright (C) 2005-2010 Erik Nilsson, software on versionstudio point com
*
* This program 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 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
Ext.namespace("vibe.plugin.playlists");
vibe.plugin.playlists.PlaylistsDialog = Ext.extend(Ext.Window,
{
/**
* @cfg {Mixed} data
* The data records for the combo box simple store.
*/
data: [],
/**
* @cfg {String} emptyText
* The text to display if the combo box is empty.
*/
emptyText : "",
/**
* @cfg {String} requireSelection
* Require a selection in the list.
*/
requireSelection : false,
// private
closeButton : null,
// private
comboBox : null,
// private
okButton : null,
/**
* @override
*/
initComponent: function()
{
this.addEvents(
/**
* @event submit
* Fired when the dialog is successfully submitted through
* a click on the OK button.
* @param {String} name the name of the playlist
* @param {Number} playlistId the database id of the playlist or null if
* playlist does not exists in the database.
*/
"submit"
);
var store = new Ext.data.SimpleStore({
autoLoad: false,
data: this.data,
fields: ["name","playlistId"]
});
this.comboBox = new Ext.form.ComboBox({
displayField: "name",
emptyText: this.emptyText,
enableKeyEvents: true,
forceSelection: false,
mode: "local",
selectOnFocus: true,
store: store,
triggerAction: "all",
typeAhead: this.requireSelection
});
this.okButton = new Ext.Button({
disabled: true,
minWidth: 75,
scope: this,
text: vibe.Language.app.OK
});
this.closeButton = new Ext.Button({
minWidth: 75,
scope: this,
text: vibe.Language.app.CLOSE
});
Ext.apply(this,
{
bodyStyle: "padding: 10px 10px 10px 10px",
buttonAlign: "center",
buttons: [this.okButton,
this.closeButton],
height: 110,
items: [this.comboBox],
modal: true,
layout: "fit",
resizable: false,
shadowOffset: 6,
width: 300
});
vibe.plugin.playlists.PlaylistsDialog.superclass.initComponent.call(this);
this.closeButton.on("click",this.onCloseButtonClick,this);
this.comboBox.on("keyup",this.onComboBoxKeyUp,this);
this.comboBox.on("select",this.onComboBoxSelect,this);
this.okButton.on("click",this.onOkButtonClick,this);
},
// private
onComboBoxKeyUp : function(comboBox,e)
{
if ( this.comboBox.getValue().length==0 ) {
this.okButton.disable();
return;
}
if ( this.requireSelection && this.getSelectedRecord()==null ) {
this.okButton.disable();
}
else {
this.okButton.enable();
}
},
// private
onComboBoxSelect : function(comboBox,record,index)
{
this.okButton.enable();
},
// private
onCloseButtonClick : function()
{
this.close();
},
// private
onOkButtonClick : function()
{
var name = null;
var playlistId = null;
var record = this.getSelectedRecord();
if ( record!=null ) {
name = record.get("name");
playlistId = record.get("playlistId");
}
else {
name = this.comboBox.getValue();
}
this.fireEvent("submit",name,playlistId);
this.close();
},
// private
getSelectedRecord : function()
{
var selectedRecord = null;
var index = this.comboBox.selectedIndex;
if ( index!=-1 )
{
// make sure selected record matches exactly
// the combo box value
var record = this.comboBox.store.getAt(index);
if ( record.get("name")==this.comboBox.getValue() ) {
selectedRecord = record;
}
}
return selectedRecord;
}
}); | versionstudio/vibestreamer | client/vibe-ext/plugins/playlists/src/PlaylistsDialog.js | JavaScript | gpl-3.0 | 4,457 |
var _ = require('underscore'),
Backbone = require('backbone'),
DAL = require('../DAL');
var Message = Backbone.Model.extend(
/** @lends Message.prototype */
{
defaults: {
userId: null,
waveId: null,
parentId: null,
message: '',
unread: true,
created_at: null
},
idAttribute: '_id',
/** @constructs */
initialize: function () {
if (this.isNew()) {
this.set('created_at', Date.now());
}
},
save: function () {
return DAL.saveMessage(this);
},
validate: function (attrs) {
if (0 === attrs.message.trim().length) {
return 'Empty message';
}
}
}
);
/** @class */
var MessageCollection = Backbone.Collection.extend(
/** @lends MessageCollection.prototype */
{
model: Message
}
);
module.exports = { Model: Message, Collection: MessageCollection }; | tofuseng/SURF | code/model/Message.js | JavaScript | gpl-3.0 | 1,029 |
function parse(req) {
var arreglo_parametros = [], parametros = {};
if (req.url.indexOf("?") > 0 ){
var url_data = req.url.split("?");
var arreglo_parametros = url_data[1].split("&");
}
for (var i = arreglo_parametros.length - 1; i >= 0; i--) {
var parametro = arreglo_parametros[i]
var param_data = parametro.split("=");
parametros[param_data[0]] = [param_data[1]];
}
return parametros;
}
module.exports.parse = parse; | fcojulio/Test-NodeJS | params_parser.js | JavaScript | gpl-3.0 | 445 |
let html_audio = document.getElementById("audio-source");
let html_open_button = document.getElementById("open-button");
//Setup the audio graph and context
let audioContext = new window.AudioContext();
let audioSource = audioContext.createMediaElementSource($("#audio-source")[0]);
let audioAnalyser = audioContext.createAnalyser();
audioAnalyser.fftSize = 2048;
let audioVolume = audioContext.createGain();
audioVolume.gain.value = 1;
audioSource.connect(audioAnalyser);
audioSource.connect(audioVolume);
audioVolume.connect(audioContext.destination);
//File input
html_open_button.addEventListener("click", () => {
remote.dialog.showOpenDialog({filters: [{name: "Music files" ,extensions: ["mp3"]}], properties: ['openFile']}, (file) => {
if(file) {
readMusicFile(file);
}
});
});
function readMusicFile(file) {
html_audio.pause();
html_audio.src = file[0];
html_audio.load();
MusicMetadata.parseFile(file[0], {duration: true})
.then((metadata) => {
if(metadata.common.artist) {
document.getElementById("audio-artist").innerHTML = metadata.common.artist;
}
else {
document.getElementById("audio-artist").innerHTML = null;
}
if(metadata.common.title) {
document.getElementById("audio-title").innerHTML = metadata.common.title;
}
else {
document.getElementById("audio-title").innerHTML = file[0].slice(file[0].lastIndexOf("\\")+1, file[0].lastIndexOf("."));
}
readNewDirectory(file[0]);
if(metadata.common.picture !== null && typeof metadata.common.picture == "object") {
document.getElementById("album-image").width = 125;
document.getElementById("album-image").height = 125;
let pictureData = new Uint8Array(metadata.common.picture[0].data);
let len = metadata.common.picture[0].data.byteLength;
let pictureDataString = "";
for (let i = 0; i < len; i++) {
pictureDataString += String.fromCharCode(pictureData[i]);
}
let base64String = btoa(pictureDataString);
document.getElementById("album-image").src = "data:image/jpg;base64,"+base64String;
document.getElementById("audio-title").style.marginLeft = "20px";
}
else {
document.getElementById("album-image").width = 0;
document.getElementById("album-image").height = 0;
document.getElementById("album-image").src = "";
document.getElementById("audio-title").style.marginLeft = "0px";
}
document.getElementById("slider").max = Math.floor(metadata.format.duration);
let minutes = Math.floor(metadata.format.duration / 60).toString();
if(minutes < 10) {
minutes = "0" + minutes;
}
let seconds = Math.round(metadata.format.duration % 60).toString();
if(seconds < 10) {
seconds = "0" + seconds;
}
document.getElementById("total-time").innerHTML = minutes + ":" + seconds;
})
.catch((err) => console.log(err));
startSliderPositionUpdate();
html_audio.play();
document.getElementById("play-button").innerHTML = "❘❘";
};
//Slider and timestamp
let sliderPositionInterval = 0;
let mousedown = false;
let startSliderPositionUpdate = function() {
sliderPositionInterval = setInterval(() => {
if(!mousedown) {
let minutes = Math.floor(html_audio.currentTime / 60);
if(minutes < 10) {
minutes = "0" + minutes.toString();
}
let seconds = Math.round(html_audio.currentTime % 60);
if(seconds < 10) {
seconds = "0" + seconds.toString();
}
document.getElementById("current-time").innerHTML = minutes + ":" + seconds;
document.getElementById("slider").value = html_audio.currentTime;
}
}, 500);
};
document.getElementById("slider").addEventListener("mousedown", () => {
mousedown = true;
clearInterval(sliderPositionInterval);
sliderPositionInterval = 0;
});
document.getElementById("slider").addEventListener("mouseup", () => {
mousedown = false;
html_audio.currentTime = $("#slider").val();
startSliderPositionUpdate();
});
//Play-pause button
document.getElementById("play-button").addEventListener("click", () => {
if(html_audio.paused) {
html_audio.play();
document.getElementById("play-button").innerHTML = "❘❘";
}
else {
html_audio.pause();
document.getElementById("play-button").innerHTML = "▷";
}
});
//Next song button
document.getElementById("next-song-button").addEventListener("click", () => {
if(currentSong == songsList.length - 1) {
currentSong = 0;
readMusicFile(new Array(currentDir + "\\" + songsList[currentSong]));
}
else {
currentSong += 1;
readMusicFile(new Array(currentDir + "\\" + songsList[currentSong]));
}
});
//Previous song button
document.getElementById("previous-song-button").addEventListener("click", () => {
if(html_audio.currentTime >= 15) {
readMusicFile(new Array(currentDir + "\\" + songsList[currentSong]));
}
else if(currentSong == 0) {
currentSong = songsList.length - 1;
readMusicFile(new Array(currentDir + "\\" + songsList[currentSong]));
}
else {
currentSong -= 1;
readMusicFile(new Array(currentDir + "\\" + songsList[currentSong]));
}
});
//Automatically load next song
document.getElementById("audio-source").addEventListener("ended", () => {
if(currentSong == songsList.length - 1) {
currentSong = 0;
readMusicFile(new Array(currentDir + "\\" + songsList[currentSong]));
}
else {
currentSong += 1;
readMusicFile(new Array(currentDir + "\\" + songsList[currentSong]));
}
});
//Mouse hover delay in player info
let playerInfoHoverTimer = 0;
$("#audio-info").hover(() => {
if(playerInfoHoverTimer == 0) {
$("#audio-info").css("opacity", 1.0);
$("#audio-info").css("top", "30px");
}
else {
clearTimeout(playerInfoHoverTimer);
}
},
() => {
playerInfoHoverTimer = setTimeout(() => {
$("#audio-info").css("opacity", 0.0);
$("#audio-info").css("top", "0px");
playerInfoHoverTimer = 0;
}, 2500);
});
| Yordrar/pulse | mainWin/js/player.js | JavaScript | gpl-3.0 | 6,544 |
/*
Copyright 2010-2012 Infracom & Eurotechnia (support@webcampak.com)
This file is part of the Webcampak project.
Webcampak 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 3 of the License,
or (at your option) any later version.
Webcampak is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
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 Webcampak.
If not, see http://www.gnu.org/licenses/.
*/
console.log('Log: Load: Webcampak.view.permissions.PermissionsWindow');
Ext.define('Webcampak.view.permissions.PermissionsWindow' ,{
extend: 'Ext.window.Window',
alias: 'widget.permissionswindow',
requires: [
'Webcampak.view.permissions.GroupsWindow',
'Webcampak.view.permissions.SourcesWindow',
'Webcampak.view.permissions.UsersWindow'
],
iconCls: 'icon-user',
title: i18n.gettext('Manage Permissions & interface settings'),
layout: 'fit',
width: 900,
//height: 400,
scroll: true,
autoScroll: true,
maximizable: true,
minimizable: true,
closeAction : 'hide',
items: [{
xtype: 'tabpanel',
items: [{
title: i18n.gettext('Users'),
itemID: 'users',
xtype: 'userswindow',
border: 0
}, {
title: i18n.gettext('Groups'),
itemID: 'openGroupsTab',
layout: 'fit',
items: [{
xtype: 'groupwindow'
}]
}, {
title: i18n.gettext('Companies'),
itemID: 'companies',
xtype: 'companylist',
border: 0
}, {
title: i18n.gettext('Sources'),
itemID: 'sources',
layout: 'fit',
items: [{
xtype: 'sourcewindow'
}]
}]
}]
});
| Webcampak/v2.0 | src/www/interface/dev/app/view/permissions/PermissionsWindow.js | JavaScript | gpl-3.0 | 1,869 |