<commit_before>var guard = require('../utils/guard')
  , context = require('../context')
  , semver = require('semver')
  , path = require('path')
  , Package = {}

module.exports = Package

Package.getVersionMeta = get_version_meta
Package.removeVersion = remove_version
Package.getVersions = get_versions
Package.publish = publish
Package.remove = remove

var methods = [
    'getMeta'
  , 'setMeta'
  , 'removeMeta'
  , 'getTarball'
  , 'setTarball'
  , 'removeTarball'
]

var meta_keys = [
    'author'
  , 'bugs'
  , 'description'
  , 'homepage'
  , 'keywords'
  , 'license'
  , 'maintainers'
  , 'readme'
  , 'readmeFilename'
  , 'repository'
]

methods.forEach(function(key) {
  Package[key] = function() {
    var backend = context().backend

    return backend[key].apply(backend, [].slice.call(arguments))
  }
})

function set_meta(name, meta, done) {
  meta._rev = ~~meta._rev + 1
  Package.setMeta(name, meta, done)
}

function remove(name, done) {
  Package.getVersions(name, function(err, versions) {
    if(err || !versions.length) {
      return done(err)
    }

    var remaining = versions.length
      , returned

    versions.forEach(function(version) {
      Package.removeTarball(name, version, removed)
    })

    function removed(err) {
      if(returned) {
        return
      }

      if(err) {
        returned = true

        return done(err)
      }

      if(!--remaining) {
        returned = true
        Package.removeMeta(name, done)
      }
    }
  })
}

function remove_version(name, version, done) {
  Package.getMeta(name, function(err, meta) {
    if(err) {
      return done(err)
    }

    version = version_from_meta(meta, version)

    var version_meta = meta.versions[version]

    if(!version || !version_meta) {
      return done()
    }

    delete meta.versions[version]

    meta['dist-tags'].latest = Object.keys(meta.versions).sort(semver.lt)[0]

    if(Object.keys(meta.versions).length) {
      set_meta(name, meta, remove_tarball)
    } else {
      Package.removeMeta(name, meta, remove_tarball)
    }
  })

  function remove_tarball(err, data) {
    if(err) {
      return done(err)
    }

    Package.removeTarball(name, version, function(err) {
      done(err, data)
    })
  }
}

function get_versions(name, done) {
  Package.getMeta(name, guard(function(meta) {
    if(!meta) {
      return done()
    }

    done(null, Object.keys(meta.versions))
  }, done))
}

function version_from_meta(meta, version) {
  return meta['dist-tags'][version || 'latest'] || semver.maxSatisfying(
      Object.keys(meta.versions)
    , version || '*'
  )
}

function get_version_meta(name, version, done) {
  Package.getMeta(name, guard(function(meta) {
    if(!meta) {
      return done()
    }

    version = version_from_meta(meta, version)

    if(!version) {
      done()
    }

    done(null, meta.versions[version])
  }, done))
}

function publish(meta, done) {
  var tags = meta['dist-tags']
    , version = tags.latest
    , name = meta.name
    , filename
    , stream

  filename = name + '-' + version + '.tgz'

  try {
    stream = Package.setTarball(name, version)
    stream.write(new Buffer(meta._attachments[filename].data, 'base64'))
    stream.end()
  } catch(err) {
    done(err)
  }

  delete meta._attachments
  save_meta(name, version, tags, meta.versions[version], done)
}

function save_meta(name, version, tags, meta, done) {
  Package.getMeta(name, function(err, module_meta) {
    module_meta = module_meta || {'dist-tags': {}, versions: {}, name: name}

    var versions = Object.keys(module_meta.versions)

    module_meta.versions[version] = meta
    versions.push(version)

    versions.sort(semver.lt)
    module_meta['dist-tags'].latest = versions[0]

    Object.keys(tags).forEach(function(tag) {
      if(!module_meta['dist-tags'][tag]) {
        module_meta['dist-tags'][tag] = tags[tag]
      }
    })

    if(versions[0] === version) {
      for(var i = 0, l = meta_keys.length; i < l; ++i) {
        module_meta[meta_keys[i]] = meta[meta_keys[i]]
      }
    }

    delete meta.readme

    set_meta(name, module_meta, function(err) {
      done(err, err ? null : module_meta)
    })
  })
}
<commit_msg>fb does weird<commit_after>var guard = require('../utils/guard')
  , context = require('../context')
  , semver = require('semver')
  , path = require('path')
  , Package = {}

module.exports = Package

Package.getVersionMeta = get_version_meta
Package.removeVersion = remove_version
Package.getVersions = get_versions
Package.publish = publish
Package.remove = remove

var methods = [
    'getMeta'
  , 'setMeta'
  , 'removeMeta'
  , 'getTarball'
  , 'setTarball'
  , 'removeTarball'
]

var meta_keys = [
    'author'
  , 'bugs'
  , 'description'
  , 'homepage'
  , 'keywords'
  , 'license'
  , 'maintainers'
  , 'readme'
  , 'readmeFilename'
  , 'repository'
]

methods.forEach(function(key) {
  Package[key] = function() {
    var backend = context().backend

    return backend[key].apply(backend, [].slice.call(arguments))
  }
})

function set_meta(name, meta, done) {
  meta._rev = ~~meta._rev + 1
  Package.setMeta(name, meta, done)
}

function remove(name, done) {
  Package.getVersions(name, function(err, versions) {
    if(err || !versions.length) {
      return done(err)
    }

    var remaining = versions.length
      , returned

    versions.forEach(function(version) {
      Package.removeTarball(name, version, removed)
    })

    function removed(err) {
      if(returned) {
        return
      }

      if(err) {
        returned = true

        return done(err)
      }

      if(!--remaining) {
        returned = true
        Package.removeMeta(name, done)
      }
    }
  })
}

function remove_version(name, version, done) {
  Package.getMeta(name, function(err, meta) {
    if(err) {
      return done(err)
    }

    version = version_from_meta(meta, version)

    var version_meta = meta.versions[version]

    if(!version || !version_meta) {
      return done()
    }

    delete meta.versions[version]

    meta['dist-tags'].latest = Object.keys(meta.versions).sort(semver.lt)[0]

    if(Object.keys(meta.versions).length) {
      set_meta(name, meta, remove_tarball)
    } else {
      Package.removeMeta(name, meta, remove_tarball)
    }
  })

  function remove_tarball(err, data) {
    if(err) {
      return done(err)
    }

    Package.removeTarball(name, version, function(err) {
      done(err, data)
    })
  }
}

function get_versions(name, done) {
  Package.getMeta(name, guard(function(meta) {
    if(!meta) {
      return done()
    }

    done(null, Object.keys(meta.versions))
  }, done))
}

function version_from_meta(meta, version) {
  return meta['dist-tags'][version || 'latest'] || semver.maxSatisfying(
      Object.keys(meta.versions)
    , version || '*'
  )
}

function get_version_meta(name, version, done) {
  Package.getMeta(name, guard(function(meta) {
    if(!meta) {
      return done()
    }

    version = version_from_meta(meta, version)

    if(!version) {
      done()
    }

    done(null, meta.versions[version])
  }, done))
}

function publish(meta, done) {
  var tags = meta['dist-tags']
    , version = tags.latest
    , name = meta.name
    , filename
    , stream

  filename = name + '-' + version + '.tgz'

  var fixed_version = version.replace(
      /^[\d\.]*/
    , version.match(/^[\d\.]*/)[0].split('.').map(function(val) {
        return +val
      }).join('.')
  )

  try {
    stream = Package.setTarball(name, fixed_version)
    stream.write(new Buffer(meta._attachments[filename].data, 'base64'))
    stream.end()
  } catch(err) {
    done(err)
  }

  delete meta._attachments
  save_meta(name, fixed_version, tags, meta.versions[version], done)
}

function save_meta(name, version, tags, meta, done) {
  Package.getMeta(name, function(err, module_meta) {
    module_meta = module_meta || {'dist-tags': {}, versions: {}, name: name}

    var versions = Object.keys(module_meta.versions)

    module_meta.versions[version] = meta
    versions.push(version)

    versions.sort(semver.lt)
    module_meta['dist-tags'].latest = versions[0]

    Object.keys(tags).forEach(function(tag) {
      if(!module_meta['dist-tags'][tag]) {
        module_meta['dist-tags'][tag] = tags[tag]
      }
    })

    if(versions[0] === version) {
      for(var i = 0, l = meta_keys.length; i < l; ++i) {
        module_meta[meta_keys[i]] = meta[meta_keys[i]]
      }
    }

    delete meta.readme

    set_meta(name, module_meta, function(err) {
      done(err, err ? null : module_meta)
    })
  })
}
<|endoftext|>


<commit_before>/*
Name:           geoip2ws
Description:    Maxmind GeoIP2 Web Services for Node.js
Source & docs:  https://github.com/fvdm/nodejs-geoip2ws
Feedback:       https://github.com/fvdm/nodejs-geoip2ws/issues
License:        Public Domain / Unlicense

This product includes GeoLite2 data created by MaxMind, available from
<http://www.maxmind.com>.
*/

var https = require('https')

// setup
var app = {
	userId: null,
	licenseKey: null,
	service: 'city_isp_org',
	requestTimeout: 5000
}

module.exports = function( userId, licenseKey, service, requestTimeout ) {
	if( userId === undefined || licenseKey === undefined ) {
		return new Error('no userId or licenseKey')
	}

	app.userId = userId
	app.licenseKey = licenseKey

	if( typeof service === 'number' ) {
		var requestTimeout = service
	}

	app.service = service || app.service
	app.requestTimeout = requestTimeout || app.requestTimeout

	return function( service, ip, callback ) {

		// service is optional
		if( arguments.length === 2 ) {
			var callback = ip
			var ip = service
			var service = app.service
		}

		// prevent multiple callbacks
		var complete = false
		function doCallback( err, res ) {
			if( ! complete ) {
				complete = true
				callback( err, res )
			}
		}

		// build request
		var options = {
			hostname: 'geoip.maxmind.com',
			path: '/geoip/v2.0/'+ service +'/'+ ip,
			agent: false,
			headers: {
				'Accept': 'application/json',
				'User-Agent': 'https://github.com/fvdm/nodejs-geoip2ws'
			},
			auth: app.userId +':'+ app.licenseKey
		}

		var request = https.request( options )

		// request response
		request.on( 'response', function( response ) {
			var data = []
			var size = 0
			var err = null

			// collect data
			response.on( 'data', function( chunk ) {
				data.push( chunk )
				size += chunk.length
			})

			// process data
			response.on( 'end', function() {
				if( data.length >= 1 ) {
					var buf = new Buffer( size )
					var pos = 0

					for( var d in data ) {
						data[d].copy( buf, pos )
						pos += data[d].length
					}

					data = data.toString('utf8').trim()

					try {
						data = JSON.parse( data )

						if( data.error !== undefined ) {
							err = new Error('API error')
							err.code = data.code
							err.error = data.error
						}
					} catch(e) {
						err = new Error('not json')
					}
				} else {
					err = new Error('no data')
				}

				doCallback( err, data )
			})

			// connection dropped
			response.on( 'close', function() {
				doCallback( new Error('request dropped') )
			})
		})

		request.on( 'socket', function( socket ) {
			if( app.requestTimeout !== undefined ) {
				socket.setTimeout( app.requestTimeout )
				socket.on( 'timeout', function() {
					request.abort()
					doCallback( new Error('request timeout') )
				})
			}
		})

		// request error
		request.on( 'error', function( error ) {
			var err = new Error('request failed')
			err.error = error
			doCallback( err )
		})

		// request finished
		request.end()

	}
}
<commit_msg>Properly fixed optional settings (#1)<commit_after>/*
Name:           geoip2ws
Description:    Maxmind GeoIP2 Web Services for Node.js
Source & docs:  https://github.com/fvdm/nodejs-geoip2ws
Feedback:       https://github.com/fvdm/nodejs-geoip2ws/issues
License:        Public Domain / Unlicense

This product includes GeoLite2 data created by MaxMind, available from
<http://www.maxmind.com>.
*/

var https = require('https')

// setup
var app = {
	userId: null,
	licenseKey: null,
	service: 'city_isp_org',
	requestTimeout: 5000
}

module.exports = function( userId, licenseKey, service, requestTimeout ) {
	if( userId === undefined || licenseKey === undefined ) {
		return new Error('no userId or licenseKey')
	}

	app.userId = userId
	app.licenseKey = licenseKey

	if( typeof service === 'number' ) {
		app.requestTimeout = service
	} else {
		app.service = service || app.service
		app.requestTimeout = requestTimeout || app.requestTimeout
	}

	return function( service, ip, callback ) {

		// service is optional
		if( arguments.length === 2 ) {
			var callback = ip
			var ip = service
			var service = app.service
		}

		// prevent multiple callbacks
		var complete = false
		function doCallback( err, res ) {
			if( ! complete ) {
				complete = true
				callback( err, res )
			}
		}

		// build request
		var options = {
			hostname: 'geoip.maxmind.com',
			path: '/geoip/v2.0/'+ service +'/'+ ip,
			agent: false,
			headers: {
				'Accept': 'application/json',
				'User-Agent': 'https://github.com/fvdm/nodejs-geoip2ws'
			},
			auth: app.userId +':'+ app.licenseKey
		}

		var request = https.request( options )

		// request response
		request.on( 'response', function( response ) {
			var data = []
			var size = 0
			var err = null

			// collect data
			response.on( 'data', function( chunk ) {
				data.push( chunk )
				size += chunk.length
			})

			// process data
			response.on( 'end', function() {
				if( data.length >= 1 ) {
					var buf = new Buffer( size )
					var pos = 0

					for( var d in data ) {
						data[d].copy( buf, pos )
						pos += data[d].length
					}

					data = data.toString('utf8').trim()

					try {
						data = JSON.parse( data )

						if( data.error !== undefined ) {
							err = new Error('API error')
							err.code = data.code
							err.error = data.error
						}
					} catch(e) {
						err = new Error('not json')
					}
				} else {
					err = new Error('no data')
				}

				doCallback( err, data )
			})

			// connection dropped
			response.on( 'close', function() {
				doCallback( new Error('request dropped') )
			})
		})

		request.on( 'socket', function( socket ) {
			if( app.requestTimeout !== undefined ) {
				socket.setTimeout( app.requestTimeout )
				socket.on( 'timeout', function() {
					request.abort()
					doCallback( new Error('request timeout') )
				})
			}
		})

		// request error
		request.on( 'error', function( error ) {
			var err = new Error('request failed')
			err.error = error
			doCallback( err )
		})

		// request finished
		request.end()

	}
}
<|endoftext|>


<commit_before>/**
 * BPM for Discord
 * (c) 2015-2016 ByzantineFailure
 *
 * Updates panel handlers.  Version number inserted
 * during the build process (see Makefile).  Also creates
 * updates notification span and checker
 **/

var BPM_updatesSubpanel = {
    init: null,
    teardown: null
};
(function() {
var UPDATE_INTERVAL_HOURS = 3;
var codeVersion = /* REPLACE-WITH-DC-VERSION */;
function BPM_checkForUpdates(createAlert) {
    var xhr = new XMLHttpRequest();
    xhr.open('GET', 'https://api.github.com/repos/ByzantineFailure/bpm/releases');
    xhr.onreadystatechange = function() {
        if(xhr.readyState != 4) return;
        if(xhr.status !== 200 && xhr.status !== 304) {
           alert('Error checking for updates, HTTP status: ' + xhr.status + '.  Is Github down?');
           return;
        }
        var response = JSON.parse(xhr.responseText);
        //TODO:  Will fail if there's no non-prereleases ready.
        //Not a problem, though, fairly isolated, doesn't break anything
        //Still should fix.
        var release = response
            .filter(function(release) {
                return !release.prerelease;
            })
            .sort(function(a, b) {
                var aDate = new Date(a.created_at);
                var bDate = new Date(b.created_at);
                if(aDate > bDate) {
                    return -1;
                } else if (bDate > aDate) {
                    return 1;
                } else {
                    return 0;
                }
            })
            [0];

        if(release.tag_name !== codeVersion) {
            if(createAlert) {
                alert('Current BPM for Discord version is ' + codeVersion + ', found version ' + release.tag_name + '\n' +
                        'Link to updates can be found in the Updates panel of BPM settings.');
            }
            addUpdatesNotifier(release.html_url);
        } else if(createAlert) {
            alert('BPM up to date!');
        }
    }
    xhr.send(null);
}

function addUpdatesNotifier(url) {
    var preexisting = document.getElementById('bpm-update-link');
    if(preexisting) {
        if(preexisting.href != url) {
            preexisting.href = url;
        }
        return;
    }

    var li = document.createElement('li');

    var ginner = document.createElement('div');
    li.appendChild(ginner);
    ginner.className = 'guild-inner';
    ginner.id = 'bpm-new-version-button';

    var link = document.createElement('a');
    ginner.appendChild(link);
    link.id = 'bpm-update-link';
    link.href = url;
    link.target = '_blank';
    link.appendChild(document.createTextNode('Update'));

    var container = document.querySelector('ul.guilds');
    container.insertBefore(li, container.firstChild);
}

function initUpdates(subpanel) {
    var updateButton = document.getElementById('bpm-check-for-updates-button');
    updateButton.addEventListener('click', function(e) {
        e.preventDefault();
        BPM_checkForUpdates(true);
    });
}

function teardownUpdates(subpanel) {
    var updateButton = document.getElementById('bpm-check-for-updates-button');
    updateButton.removeEventListener('click');
}

function backgroundUpdateCheck() {
    BPM_checkForUpdates(false);
    window.setTimeout(backgroundUpdateCheck, 1000 * 60 * 60 * UPDATE_INTERVAL_HOURS);
}

BPM_updatesSubpanel.init = initUpdates;
BPM_updatesSubpanel.teardown = teardownUpdates;
backgroundUpdateCheck();
})();

<commit_msg>Update check failure should no longer bother the user unless they manually initiated the check<commit_after>/**
 * BPM for Discord
 * (c) 2015-2016 ByzantineFailure
 *
 * Updates panel handlers.  Version number inserted
 * during the build process (see Makefile).  Also creates
 * updates notification span and checker
 **/

var BPM_updatesSubpanel = {
    init: null,
    teardown: null
};
(function() {
var UPDATE_INTERVAL_HOURS = 3;
var codeVersion = /* REPLACE-WITH-DC-VERSION */;
function BPM_checkForUpdates(createAlert) {
    var xhr = new XMLHttpRequest();
    xhr.open('GET', 'https://api.github.com/repos/ByzantineFailure/bpm/releases');
    xhr.onreadystatechange = function() {
        if(xhr.readyState != 4) return;
        if(xhr.status !== 200 && xhr.status !== 304) {
            if(createAlert) {
                alert('Error checking for updates, HTTP status: ' + xhr.status + '.  Is Github down?');
            }
            return;
        }
        var response = JSON.parse(xhr.responseText);
        //TODO:  Will fail if there's no non-prereleases ready.
        //Not a problem, though, fairly isolated, doesn't break anything
        //Still should fix.
        var release = response
            .filter(function(release) {
                return !release.prerelease;
            })
            .sort(function(a, b) {
                var aDate = new Date(a.created_at);
                var bDate = new Date(b.created_at);
                if(aDate > bDate) {
                    return -1;
                } else if (bDate > aDate) {
                    return 1;
                } else {
                    return 0;
                }
            })
            [0];

        if(release.tag_name !== codeVersion) {
            if(createAlert) {
                alert('Current BPM for Discord version is ' + codeVersion + ', found version ' + release.tag_name + '\n' +
                        'Link to updates can be found in the Updates panel of BPM settings.');
            }
            addUpdatesNotifier(release.html_url);
        } else if(createAlert) {
            alert('BPM up to date!');
        }
    }
    xhr.send(null);
}

function addUpdatesNotifier(url) {
    var preexisting = document.getElementById('bpm-update-link');
    if(preexisting) {
        if(preexisting.href != url) {
            preexisting.href = url;
        }
        return;
    }

    var li = document.createElement('li');

    var ginner = document.createElement('div');
    li.appendChild(ginner);
    ginner.className = 'guild-inner';
    ginner.id = 'bpm-new-version-button';

    var link = document.createElement('a');
    ginner.appendChild(link);
    link.id = 'bpm-update-link';
    link.href = url;
    link.target = '_blank';
    link.appendChild(document.createTextNode('Update'));

    var container = document.querySelector('ul.guilds');
    container.insertBefore(li, container.firstChild);
}

function initUpdates(subpanel) {
    var updateButton = document.getElementById('bpm-check-for-updates-button');
    updateButton.addEventListener('click', function(e) {
        e.preventDefault();
        BPM_checkForUpdates(true);
    });
}

function teardownUpdates(subpanel) {
    var updateButton = document.getElementById('bpm-check-for-updates-button');
    updateButton.removeEventListener('click');
}

function backgroundUpdateCheck() {
    BPM_checkForUpdates(false);
    window.setTimeout(backgroundUpdateCheck, 1000 * 60 * 60 * UPDATE_INTERVAL_HOURS);
}

BPM_updatesSubpanel.init = initUpdates;
BPM_updatesSubpanel.teardown = teardownUpdates;
backgroundUpdateCheck();
})();

<|endoftext|>


<commit_before>(function() {
    var m = angular.module('parkandride.users', [
        'ui.router',
        'parkandride.auth',
        'parkandride.operators',
        'parkandride.UserResource',
        'parkandride.layout',
        'showErrors'
    ]);

    m.config(function($stateProvider) {
        $stateProvider.state('user-list', {
            parent: 'userstab',
            url: '/users',
            views: {
                "main": {
                    controller: 'UserListCtrl as ctrl',
                    templateUrl: 'users/userList.tpl.html'
                }
            },
            data: { pageTitle: 'Users' },
            resolve: {
                users: function(UserResource) {
                    return UserResource.listUsers();
                },
                operatorsById: function(OperatorResource) {
                    return OperatorResource.listOperators().then(function(operators) {
                        return _.indexBy(operators.results, "id");
                    });
                }
            }
        });
    });
    m.controller('UserListCtrl', function($state, users, operatorsById, userModal) {
        var vm = this;
        vm.users = users.results;
        vm.openModal = openModal;

        initialize();

        function initialize() {
            _.forEach(vm.users, function(user) {
                var operator = operatorsById[user.operatorId];
                user.operatorNameFi = operator ? operator.name.fi : "";
            });
        }

        function openModal(user) {
            userModal.open(user).result.then(function() { $state.reload(); });
        }
    });

    m.directive('userListNavi', function() {
        return {
            restrict: 'E',
            templateUrl: 'users/userListNavi.tpl.html'
        };
    });

    m.factory('userModal', function($modal, OperatorResource) {
        return {
            open: function(user) {
                return $modal.open({
                    templateUrl: 'users/userModal.tpl.html',
                    controller: 'UserModalCtrl as ctrl',
                    resolve: {
                        user: function () {
                            return _.cloneDeep(user);
                        },
                        operators: function() {
                            return OperatorResource.listOperators();
                        }
                    },
                    backdrop: 'static'
                });
            }
        };
    });
    m.controller('UserModalCtrl', function($scope, $modalInstance, $translate, schema, user, EVENTS, UserResource, operators, Session) {
        var vm = this;
        vm.titleKey = 'users.action.' + (user ? 'edit' : 'new');
        vm.user = user || {};
        vm.save = save;
        vm.cancel = cancel;
        vm.roles = translatedEnumValues("roles", schema.roles);
        vm.operators = operators.results;
        vm.onOperatorSelect = onOperatorSelect;
        vm.onRoleSelect = onRoleSelect;
        vm.isOperatorCreator = false;

        initialize();

        function initialize() {
            var login = Session.get();
            if (login && login.operatorId) {
                vm.operators = _.filter(vm.operators, function(o) { return o.id === login.operatorId; });
                vm.user.operatorId = login.operatorId;
                vm.isOperatorCreator = true;
            }
        }

        function onOperatorSelect(item, model) {
            if (vm.user.role === 'ADMIN') {
                vm.user.role = undefined;
            }
        }

        function onRoleSelect(item, model) {
            if (model === 'ADMIN') {
                vm.user.operatorId = undefined;
            }
        }

        function save(form) {
            validateAndSubmit(form, function() {
                UserResource.save(vm.user).then(handleSubmitSuccess, handleSubmitReject);
            });
        }

        function cancel() {
            $modalInstance.dismiss();
        }

        function translatedEnumValues(prefix, values) {
            return _.map(values, function(v) {
                return {
                    id: v,
                    label: $translate.instant(prefix + "." + v + ".label")
                };
            });
        }

        function handleSubmitSuccess(success) {
            $modalInstance.close(success);
        }

        function handleSubmitReject(rejection) {
            if (rejection.status == 400 && rejection.data.violations) {
                $scope.violations = rejection.data.violations;
            }
        }

        function validateAndSubmit(form, saveFn) {
            $scope.$broadcast(EVENTS.showErrorsCheckValidity);
            if (form.$valid) {
                saveFn();
            } else {
                $scope.violations = [{
                    path: "",
                    type: "BasicRequirements"
                }];
            }
        }
    });

})();
<commit_msg>feat(users): filter out admin role if creator is operator<commit_after>(function() {
    var m = angular.module('parkandride.users', [
        'ui.router',
        'parkandride.auth',
        'parkandride.operators',
        'parkandride.UserResource',
        'parkandride.layout',
        'showErrors'
    ]);

    m.config(function($stateProvider) {
        $stateProvider.state('user-list', {
            parent: 'userstab',
            url: '/users',
            views: {
                "main": {
                    controller: 'UserListCtrl as ctrl',
                    templateUrl: 'users/userList.tpl.html'
                }
            },
            data: { pageTitle: 'Users' },
            resolve: {
                users: function(UserResource) {
                    return UserResource.listUsers();
                },
                operatorsById: function(OperatorResource) {
                    return OperatorResource.listOperators().then(function(operators) {
                        return _.indexBy(operators.results, "id");
                    });
                }
            }
        });
    });
    m.controller('UserListCtrl', function($state, users, operatorsById, userModal) {
        var vm = this;
        vm.users = users.results;
        vm.openModal = openModal;

        initialize();

        function initialize() {
            _.forEach(vm.users, function(user) {
                var operator = operatorsById[user.operatorId];
                user.operatorNameFi = operator ? operator.name.fi : "";
            });
        }

        function openModal(user) {
            userModal.open(user).result.then(function() { $state.reload(); });
        }
    });

    m.directive('userListNavi', function() {
        return {
            restrict: 'E',
            templateUrl: 'users/userListNavi.tpl.html'
        };
    });

    m.factory('userModal', function($modal, OperatorResource) {
        return {
            open: function(user) {
                return $modal.open({
                    templateUrl: 'users/userModal.tpl.html',
                    controller: 'UserModalCtrl as ctrl',
                    resolve: {
                        user: function () {
                            return _.cloneDeep(user);
                        },
                        operators: function() {
                            return OperatorResource.listOperators();
                        }
                    },
                    backdrop: 'static'
                });
            }
        };
    });
    m.controller('UserModalCtrl', function($scope, $modalInstance, $translate, schema, user, EVENTS, UserResource, operators, Session) {
        var vm = this;
        vm.titleKey = 'users.action.' + (user ? 'edit' : 'new');
        vm.user = user || {};
        vm.save = save;
        vm.cancel = cancel;
        vm.roles = translatedEnumValues("roles", schema.roles);
        vm.operators = operators.results;
        vm.onOperatorSelect = onOperatorSelect;
        vm.onRoleSelect = onRoleSelect;
        vm.isOperatorCreator = false;

        initialize();

        function initialize() {
            var login = Session.get();
            if (login && login.operatorId) {
                vm.isOperatorCreator = true;

                vm.operators = _.filter(vm.operators, function(o) { return o.id === login.operatorId; });
                vm.user.operatorId = login.operatorId;

                vm.roles = _.filter(vm.roles, function(r) { return r.id !== 'ADMIN'; });
            }
        }

        function onOperatorSelect(item, model) {
            if (vm.user.role === 'ADMIN') {
                vm.user.role = undefined;
            }
        }

        function onRoleSelect(item, model) {
            if (model === 'ADMIN') {
                vm.user.operatorId = undefined;
            }
        }

        function save(form) {
            validateAndSubmit(form, function() {
                UserResource.save(vm.user).then(handleSubmitSuccess, handleSubmitReject);
            });
        }

        function cancel() {
            $modalInstance.dismiss();
        }

        function translatedEnumValues(prefix, values) {
            return _.map(values, function(v) {
                return {
                    id: v,
                    label: $translate.instant(prefix + "." + v + ".label")
                };
            });
        }

        function handleSubmitSuccess(success) {
            $modalInstance.close(success);
        }

        function handleSubmitReject(rejection) {
            if (rejection.status == 400 && rejection.data.violations) {
                $scope.violations = rejection.data.violations;
            }
        }

        function validateAndSubmit(form, saveFn) {
            $scope.$broadcast(EVENTS.showErrorsCheckValidity);
            if (form.$valid) {
                saveFn();
            } else {
                $scope.violations = [{
                    path: "",
                    type: "BasicRequirements"
                }];
            }
        }
    });

})();
<|endoftext|>


<commit_before>var jsface                  = require('jsface'),
	_und                    = require('underscore'),
	vm                      = require('vm'),
	ErrorHandler            = require('../utilities/ErrorHandler'),
	AbstractResponseHandler = require('./AbstractResponseHandler'),
	window                  = require("jsdom-nogyp").jsdom().parentWindow,
	_jq                     = require("jquery")(window),
	_lod                    = require("lodash"),
	Helpers                 = require('../utilities/Helpers'),
	log                     = require('../utilities/Logger'),
	Backbone                = require("backbone"),
	xmlToJson               = require("xml2js"),
	Globals                 = require("../utilities/Globals"),
	tv4                     = require("tv4");
require('sugar');
/**
 * @class TestResponseHandler
 * @classdesc
 */
var TestResponseHandler = jsface.Class(AbstractResponseHandler, {
	$singleton: true,

	// function called when the event "requestExecuted" is fired. Takes 4 self-explanatory parameters
	_onRequestExecuted: function(error, response, body, request) {
		var results = this._runTestCases(error, response, body, request);
		AbstractResponseHandler._onRequestExecuted.call(this, error, response, body, request, results);
		this._logTestResults(results);
	},

	_runTestCases: function(error, response, body, request) {
		if (this._hasTestCases(request)) {
			var tests = this._getValidTestCases(request.tests);
			var sandbox = this._createSandboxedEnvironment(error, response, body, request);
			return this._runAndGenerateTestResults(tests, sandbox);
		}
		return {};
	},

	_hasTestCases: function(request) {
		return !!request.tests;
	},

	// returns an array of test cases ( as strings )
	_getValidTestCases: function(tests) {
		return _und.reduce(tests.split(';'), function(listOfTests, testCase) {
			var t = testCase.trim();
			if (t.length > 0) {
				listOfTests.push(t);
			}
			return listOfTests;
		}, []);
	},

	// run and generate test results. Also exit if any of the tests has failed
	// given the users passes the flag
	_runAndGenerateTestResults: function(testCases, sandbox) {
		var testResults = this._evaluateInSandboxedEnvironment(testCases, sandbox);
		if (Globals.stopOnError) {
			_und.each(_und.keys(testResults), function(key){
				if (!testResults[key]) {
					ErrorHandler.terminateWithError("Test case failed: " + key);
				}
			});
		}
		return testResults;
	},

	// evaluates a list of testcases in a sandbox generated by _createSandboxedEnvironment
	// catches exceptions and throws a custom error message
	_evaluateInSandboxedEnvironment: function(testCases, sandbox) {
		var sweet= "for(p in sugar.object) Object.prototype[p]  = sugar.object[p];";
		sweet += "for(p in sugar.array)  Array.prototype[p]   = sugar.array[p];";
		sweet += "for(p in sugar.string) String.prototype[p]  = sugar.string[p];";
		sweet += "for(p in sugar.date)   Date.prototype[p]    = sugar.date[p];";
		sweet += "for(p in sugar.funcs)  Function.prototype[p]= sugar.funcs[p];";
		testCases = sweet + 'String.prototype.has = function(value){ return this.indexOf(value) > -1};' + testCases.join(";");
		try {
			vm.runInNewContext(testCases, sandbox);
		} catch (err) {
			ErrorHandler.exceptionError(err);
		}
		return sandbox.tests;
	},

    _getTransformedRequestData: function(request) {
        var transformedData;

        if (request.transformed.data === "") {
            return {};
        }
        if (request.dataMode === "raw") {
            transformedData = request.transformed.data;
        } else {
            transformedData = Helpers.transformFromKeyValue(request.transformed.data);
        }
        return transformedData;
    },

	// sets the env vars json as a key value pair
	_setEnvironmentContext: function() {
		return Helpers.transformFromKeyValue(Globals.envJson.values);
	},

	_createSandboxedEnvironment: function(error, response, body, request) {
		var sugar = { array:{}, object:{}, string:{}, funcs:{}, date:{} };
		Object.getOwnPropertyNames(Array.prototype).each(function(p) { sugar.array[p] = Array.prototype[p];});
		Object.getOwnPropertyNames(Object.prototype).each(function(p) { sugar.object[p] = Object.prototype[p];});
		Object.getOwnPropertyNames(String.prototype).each(function(p) { sugar.string[p] = String.prototype[p];});
		Object.getOwnPropertyNames(Date.prototype).each(function(p) { sugar.date[p] = Date.prototype[p]};);
		Object.getOwnPropertyNames(Function.prototype).each(function(p) { sugar.funcs[p] = Function.prototype[p]};);
		return {
			sugar: sugar,
			tests: {},
			responseHeaders: response.headers,
			responseBody: body,
			responseTime: response.stats.timeTaken,
			request: {
				url: request.transformed.url,
				method: request.method,
				headers: Helpers.generateHeaderObj(request.transformed.headers),
				data: this._getTransformedRequestData(request),
				dataMode: request.dataMode
			},
			responseCode: {
				code: response.statusCode,
				name: request.name,
				detail: request.description
			},
			data: {},
			iteration: Globals.iterationNumber,
			environment: this._setEnvironmentContext(),
			globals: {},
			$: _jq,
			_: _lod,
			Backbone: Backbone,
			xmlToJson: function(string) {
				var JSON = {};
				xmlToJson.parseString(string, {explicitArray: false,async: false}, function (err, result) {
					JSON = result;
				});
				return JSON;
			},
			tv4: tv4,
			console: {log: function(){}},
			postman: {
				setEnvironmentVariable: function(key, value) {
					var envVar = _und.find(Globals.envJson.values, function(envObject){
						return envObject["key"] === key;
					});

					if (envVar) { // if the envVariable exists replace it
						envVar["value"] = value;
					} else { // else add a new envVariable
						Globals.envJson.values.push({
							key: key,
							value: value,
							type: "text",
							name: key
						});
					}
				},
				setGlobalVariable: function(key, value) {
					// Set this guy up when we setup globals.
				}
			}
		};
	},

	// logger for test case results
	_logTestResults: function(results) {
		_und.each(_und.keys(results), function(key) {
			if (results[key]) {
				log.testCaseSuccess(key);
			} else {
				ErrorHandler.testCaseError(key);
			}
		});
	}
});

module.exports = TestResponseHandler;
<commit_msg>Update TestResponseHandler.js<commit_after>var jsface                  = require('jsface'),
	_und                    = require('underscore'),
	vm                      = require('vm'),
	ErrorHandler            = require('../utilities/ErrorHandler'),
	AbstractResponseHandler = require('./AbstractResponseHandler'),
	window                  = require("jsdom-nogyp").jsdom().parentWindow,
	_jq                     = require("jquery")(window),
	_lod                    = require("lodash"),
	Helpers                 = require('../utilities/Helpers'),
	log                     = require('../utilities/Logger'),
	Backbone                = require("backbone"),
	xmlToJson               = require("xml2js"),
	Globals                 = require("../utilities/Globals"),
	tv4                     = require("tv4");
require('sugar');
/**
 * @class TestResponseHandler
 * @classdesc
 */
var TestResponseHandler = jsface.Class(AbstractResponseHandler, {
	$singleton: true,

	// function called when the event "requestExecuted" is fired. Takes 4 self-explanatory parameters
	_onRequestExecuted: function(error, response, body, request) {
		var results = this._runTestCases(error, response, body, request);
		AbstractResponseHandler._onRequestExecuted.call(this, error, response, body, request, results);
		this._logTestResults(results);
	},

	_runTestCases: function(error, response, body, request) {
		if (this._hasTestCases(request)) {
			var tests = this._getValidTestCases(request.tests);
			var sandbox = this._createSandboxedEnvironment(error, response, body, request);
			return this._runAndGenerateTestResults(tests, sandbox);
		}
		return {};
	},

	_hasTestCases: function(request) {
		return !!request.tests;
	},

	// returns an array of test cases ( as strings )
	_getValidTestCases: function(tests) {
		return _und.reduce(tests.split(';'), function(listOfTests, testCase) {
			var t = testCase.trim();
			if (t.length > 0) {
				listOfTests.push(t);
			}
			return listOfTests;
		}, []);
	},

	// run and generate test results. Also exit if any of the tests has failed
	// given the users passes the flag
	_runAndGenerateTestResults: function(testCases, sandbox) {
		var testResults = this._evaluateInSandboxedEnvironment(testCases, sandbox);
		if (Globals.stopOnError) {
			_und.each(_und.keys(testResults), function(key){
				if (!testResults[key]) {
					ErrorHandler.terminateWithError("Test case failed: " + key);
				}
			});
		}
		return testResults;
	},

	// evaluates a list of testcases in a sandbox generated by _createSandboxedEnvironment
	// catches exceptions and throws a custom error message
	_evaluateInSandboxedEnvironment: function(testCases, sandbox) {
		var sweet= "for(p in sugar.object) Object.prototype[p]  = sugar.object[p];";
		sweet += "for(p in sugar.array)  Array.prototype[p]   = sugar.array[p];";
		sweet += "for(p in sugar.string) String.prototype[p]  = sugar.string[p];";
		sweet += "for(p in sugar.date)   Date.prototype[p]    = sugar.date[p];";
		sweet += "for(p in sugar.funcs)  Function.prototype[p]= sugar.funcs[p];";
		testCases = sweet + 'String.prototype.has = function(value){ return this.indexOf(value) > -1};' + testCases.join(";");
		try {
			vm.runInNewContext(testCases, sandbox);
		} catch (err) {
			ErrorHandler.exceptionError(err);
		}
		return sandbox.tests;
	},

    _getTransformedRequestData: function(request) {
        var transformedData;

        if (request.transformed.data === "") {
            return {};
        }
        if (request.dataMode === "raw") {
            transformedData = request.transformed.data;
        } else {
            transformedData = Helpers.transformFromKeyValue(request.transformed.data);
        }
        return transformedData;
    },

	// sets the env vars json as a key value pair
	_setEnvironmentContext: function() {
		return Helpers.transformFromKeyValue(Globals.envJson.values);
	},

	_createSandboxedEnvironment: function(error, response, body, request) {
		var sugar = { array:{}, object:{}, string:{}, funcs:{}, date:{} };
		Object.getOwnPropertyNames(Array.prototype).each(function(p) { sugar.array[p] = Array.prototype[p];});
		Object.getOwnPropertyNames(Object.prototype).each(function(p) { sugar.object[p] = Object.prototype[p];});
		Object.getOwnPropertyNames(String.prototype).each(function(p) { sugar.string[p] = String.prototype[p];});
		Object.getOwnPropertyNames(Date.prototype).each(function(p) { sugar.date[p] = Date.prototype[p];});
		Object.getOwnPropertyNames(Function.prototype).each(function(p) { sugar.funcs[p] = Function.prototype[p];});
		return {
			sugar: sugar,
			tests: {},
			responseHeaders: response.headers,
			responseBody: body,
			responseTime: response.stats.timeTaken,
			request: {
				url: request.transformed.url,
				method: request.method,
				headers: Helpers.generateHeaderObj(request.transformed.headers),
				data: this._getTransformedRequestData(request),
				dataMode: request.dataMode
			},
			responseCode: {
				code: response.statusCode,
				name: request.name,
				detail: request.description
			},
			data: {},
			iteration: Globals.iterationNumber,
			environment: this._setEnvironmentContext(),
			globals: {},
			$: _jq,
			_: _lod,
			Backbone: Backbone,
			xmlToJson: function(string) {
				var JSON = {};
				xmlToJson.parseString(string, {explicitArray: false,async: false}, function (err, result) {
					JSON = result;
				});
				return JSON;
			},
			tv4: tv4,
			console: {log: function(){}},
			postman: {
				setEnvironmentVariable: function(key, value) {
					var envVar = _und.find(Globals.envJson.values, function(envObject){
						return envObject["key"] === key;
					});

					if (envVar) { // if the envVariable exists replace it
						envVar["value"] = value;
					} else { // else add a new envVariable
						Globals.envJson.values.push({
							key: key,
							value: value,
							type: "text",
							name: key
						});
					}
				},
				setGlobalVariable: function(key, value) {
					// Set this guy up when we setup globals.
				}
			}
		};
	},

	// logger for test case results
	_logTestResults: function(results) {
		_und.each(_und.keys(results), function(key) {
			if (results[key]) {
				log.testCaseSuccess(key);
			} else {
				ErrorHandler.testCaseError(key);
			}
		});
	}
});

module.exports = TestResponseHandler;
<|endoftext|>


<commit_before>#!/user/bin/env nodejs
'use strict';

const fs = require('fs');

try {
  fs.unlinkSync('dist/umd/PNotifyBrightTheme.js');
  fs.unlinkSync('dist/umd/PNotifyMaterial.js');
} catch (e) {}
<commit_msg>Update cleanup script.<commit_after>#!/user/bin/env nodejs
'use strict';

const fs = require('fs');

try {
  fs.unlinkSync('dist/PNotifyBrightTheme.js');
  fs.unlinkSync('dist/PNotifyMaterial.js');
} catch (e) {}
<|endoftext|>


<commit_before>/* -*- Mode: js; js-indent-level: 2; indent-tabs-mode: nil; tab-width: 2 -*- */
/* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */
/*
 * Copyright 2013 Mozilla Foundation
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/*global TelemetryService, VIDEO_FEATURE */

var VideoDefinition = (function () {
  var def = {
    initialize: function initialize() {
      TelemetryService.reportTelemetry({topic: 'feature', feature: VIDEO_FEATURE});
    },
    attachNetStream: function (netStream) {
      this._netStream = netStream;
      netStream._videoReady.then(function (element) {
        this._element = element;
        netStream._videoMetadataReady.then(function (url) {
          this._element.width = this._videoWidth = this._element.videoWidth;
          this._element.height = this._videoHeight = this._element.videoHeight;
          if (this.stage) {
            this.stage._invalid = true;
          }
        }.bind(this));
      }.bind(this));
    },
    ctor: function(width, height) {
      if (!width || width < 0) width = 320;
      if (!height || height < 0) height = 240;

      this._bbox = {xMin: 0, yMin: 0, xMax: width * 20, yMax: height * 20};

      this._initialWidth = this._videoWidth = width;
      this._initialHeight = this._videoHeight = height;

      this._element = null;
      this._added = false;
    },
    draw: function (ctx) {
      if (!this._element) {
        return;
      }
      if (!this._added) {
        ctx.canvas.parentNode.appendChild(this._element);
        this._added = true;
      }

      var width = this._initialWidth;
      var height = this._initialHeight;

      if (width > 0 && height > 0) {
        ctx.save();
        ctx.beginPath();
        ctx.rect(0, 0, width, height);
        ctx.clip();
        ctx.clearRect(0, 0, width, height);
        ctx.restore();
      }

      var matrix = ctx.currentTransform;
      var sx = width / this._videoWidth;
      var sy = height / this._videoHeight;

      var scaleFactor = (this.stage && this.stage._contentsScaleFactor) || 1;
      var a = sx * matrix.a / scaleFactor;
      var b = sx * matrix.b / scaleFactor;
      var c = sy * matrix.c / scaleFactor;
      var d = sy * matrix.d / scaleFactor;
      var e = matrix.e / scaleFactor;
      var f = matrix.f / scaleFactor;

      var cssTransform = "transform: matrix(" + a + "," + b + "," + c + "," +
         d + "," + e + "," + f + ");";

      if (this._currentCssTransform !== cssTransform) {
        this._currentCssTransform = cssTransform;
        this._element.setAttribute("style", "position: absolute; top:0; left:0; z-index: -100;" +
                                   "transform-origin: 0px 0px 0;" + cssTransform +
                                   "-webkit-transform-origin: 0px 0px 0; -webkit-" + cssTransform);
      }
    }
  };

  def.__glue__ = {
    native: {
      instance: {
        attachNetStream: def.attachNetStream,
        ctor: def.ctor,
        smoothing: {
          get: function smoothing() { // (void) -> Boolean
            return this._smoothing;
          },
          set: function smoothing(value) { // (value:Boolean) -> void
            somewhatImplemented("Video.smoothing");
            this._smoothing = value;
          }
        },
        videoHeight: {
          get: function videoHeight() { // (void) -> int
            return this._videoHeight;
          }
        },
        videoWidth: {
          get: function videoWidth() { // (void) -> int
            return this._videoWidth;
          }
        },
      }
    }
  };

  return def;
}).call(this);
<commit_msg>Fixes video player location<commit_after>/* -*- Mode: js; js-indent-level: 2; indent-tabs-mode: nil; tab-width: 2 -*- */
/* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */
/*
 * Copyright 2013 Mozilla Foundation
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/*global TelemetryService, VIDEO_FEATURE */

var VideoDefinition = (function () {
  var def = {
    initialize: function initialize() {
      TelemetryService.reportTelemetry({topic: 'feature', feature: VIDEO_FEATURE});
    },
    attachNetStream: function (netStream) {
      this._netStream = netStream;
      netStream._videoReady.then(function (element) {
        this._element = element;
        netStream._videoMetadataReady.then(function (url) {
          this._element.width = this._videoWidth = this._element.videoWidth;
          this._element.height = this._videoHeight = this._element.videoHeight;
          if (this.stage) {
            this.stage._invalid = true;
          }
        }.bind(this));
      }.bind(this));
    },
    ctor: function(width, height) {
      if (!width || width < 0) width = 320;
      if (!height || height < 0) height = 240;

      this._bbox = {xMin: 0, yMin: 0, xMax: width * 20, yMax: height * 20};

      this._initialWidth = this._videoWidth = width;
      this._initialHeight = this._videoHeight = height;

      this._element = null;
      this._added = false;
    },
    draw: function (ctx) {
      if (!this._element) {
        return;
      }
      if (!this._added) {
        ctx.canvas.parentNode.appendChild(this._element);
        this._added = true;
      }

      var width = this._initialWidth;
      var height = this._initialHeight;

      if (width > 0 && height > 0) {
        ctx.save();
        ctx.beginPath();
        ctx.rect(0, 0, width, height);
        ctx.clip();
        ctx.clearRect(0, 0, width, height);
        ctx.restore();
      }

      var matrix = this._getConcatenatedTransform(true);
      var sx = width / this._videoWidth;
      var sy = height / this._videoHeight;

      var scaleFactor = (this.stage && this.stage._contentsScaleFactor) || 1;
      var a = sx * matrix.a / scaleFactor;
      var b = sx * matrix.b / scaleFactor;
      var c = sy * matrix.c / scaleFactor;
      var d = sy * matrix.d / scaleFactor;
      var e = matrix.tx / 20 / scaleFactor;
      var f = matrix.ty / 20 / scaleFactor;

      var cssTransform = "transform: matrix(" + a + "," + b + "," + c + "," +
         d + "," + e + "," + f + ");";

      if (this._currentCssTransform !== cssTransform) {
        this._currentCssTransform = cssTransform;
        this._element.setAttribute("style", "position: absolute; top:0; left:0; z-index: -100;" +
                                   "transform-origin: 0px 0px 0;" + cssTransform +
                                   "-webkit-transform-origin: 0px 0px 0; -webkit-" + cssTransform);
      }
    }
  };

  def.__glue__ = {
    native: {
      instance: {
        attachNetStream: def.attachNetStream,
        ctor: def.ctor,
        smoothing: {
          get: function smoothing() { // (void) -> Boolean
            return this._smoothing;
          },
          set: function smoothing(value) { // (value:Boolean) -> void
            somewhatImplemented("Video.smoothing");
            this._smoothing = value;
          }
        },
        videoHeight: {
          get: function videoHeight() { // (void) -> int
            return this._videoHeight;
          }
        },
        videoWidth: {
          get: function videoWidth() { // (void) -> int
            return this._videoWidth;
          }
        },
      }
    }
  };

  return def;
}).call(this);
<|endoftext|>


<commit_before>var mongoose = require('mongoose');
var async = require('async');
var _ = require('lodash');

var dgv = require('../dgv');
var geogw = require('../geogw');
var map = require('../mapping').map;

var Schema = mongoose.Schema;
var ObjectId = Schema.Types.ObjectId;

var DatasetSchema = new Schema({
    _id: { type: String },
    hashedId: String, // TEMP

    // Last known title
    title: { type: String }, // May be overriden by alternative revision

    // Last known producers
    producers: { type: [String] }, // May be overriden by alternative revision

    // Attributes related to the publication on the udata platform
    publication: {
        // Unique ID on the udata platform
        _id: { type: String, unique: true, sparse: true },

        // Publication status: can be private or public
        status: { type: String, enum: ['private', 'public'] },

        // Organization on the udata platform which hold the dataset
        organization: { type: ObjectId, ref: 'Organization' },

        // Source catalog on the geogw platform from which the dataset is synced
        sourceCatalog: { type: ObjectId },

        // Published dataset revision
        revision: { type: Date }
    },

    // List of organizations for which the dataset is matching criteria
    matchingFor: [{ type: ObjectId, ref: 'Organization' }]

});

DatasetSchema.methods = {

    fetchAndConvert: function (done) {
        var datasetRef = this;

        geogw.getRecordFromCatalog(datasetRef._id, datasetRef.publication.organization, function (err, sourceDataset) {
            if (err) return done(err);
            var uDataset;

            datasetRef
                .set('title', sourceDataset.metadata.title)
                .set('producers', sourceDataset.organizations);

            try {
                uDataset = map(sourceDataset);
                uDataset.organization = datasetRef.publication.organization;
                uDataset.private = datasetRef.publication.status !== 'public';
            } catch (e) {
                return done(e);
            }

            done(null, uDataset);
        });
    },

    fetchWorkingAccessToken: function (done) {
        var Organization = mongoose.model('Organization');
        var organization = new Organization({ _id: this.publication.organization });
        organization.fetchWorkingAccessToken(done);
    },

    processSynchronization: function (type, done) {
        var datasetRef = this;

        async.parallel({
            uDataset: _.bind(datasetRef.fetchAndConvert, datasetRef),
            accessToken: _.bind(datasetRef.fetchWorkingAccessToken, datasetRef)
        }, function (err, context) {
            if (err) return done(err);
            if (!context.accessToken) return done(new Error('No working accessToken found'));

            function requestSyncCallback(err, publishedDataset) {
                if (err) return done(err);

                // var now = new Date();

                if (type === 'create') {
                    datasetRef
                        // .set('_created', now)
                        .set('publication._id', publishedDataset.id);
                }

                datasetRef
                    // .set('_updated', now)
                    .save(done);
            }

            if (type === 'create') {
                dgv.createDataset(context.uDataset, context.accessToken, requestSyncCallback);
            } else if (type === 'update') {
                dgv.updateDataset(datasetRef.publication._id, context.uDataset, context.accessToken, requestSyncCallback);
            } else {
                throw new Error('Unknown type for processSynchronization');
            }
        });
    },

    synchronize: function (done) {
        this.processSynchronization('update', done);
    },

    publish: function (done) {
        this.processSynchronization('create', done);
    },

    unpublish: function (done) {
        var datasetRef = this;

        datasetRef.fetchWorkingAccessToken(function (err, accessToken) {
            if (err) return done(err);
            if (!accessToken) return done(new Error('No working accessToken found'));

            dgv.deleteDataset(datasetRef.publication._id, accessToken, function (err) {
                if (err) return done(err);
                datasetRef.set('publication', undefined).save(done);
            });
        });
    }

};

mongoose.model('Dataset', DatasetSchema);
<commit_msg>Fix geogw API<commit_after>var mongoose = require('mongoose');
var async = require('async');
var _ = require('lodash');

var dgv = require('../dgv');
var geogw = require('../geogw');
var map = require('../mapping').map;

var Schema = mongoose.Schema;
var ObjectId = Schema.Types.ObjectId;

var DatasetSchema = new Schema({
    _id: { type: String },
    hashedId: String, // TEMP

    // Last known title
    title: { type: String }, // May be overriden by alternative revision

    // Last known producers
    producers: { type: [String] }, // May be overriden by alternative revision

    // Attributes related to the publication on the udata platform
    publication: {
        // Unique ID on the udata platform
        _id: { type: String, unique: true, sparse: true },

        // Publication status: can be private or public
        status: { type: String, enum: ['private', 'public'] },

        // Organization on the udata platform which hold the dataset
        organization: { type: ObjectId, ref: 'Organization' },

        // Source catalog on the geogw platform from which the dataset is synced
        sourceCatalog: { type: ObjectId },

        // Published dataset revision
        revision: { type: Date }
    },

    // List of organizations for which the dataset is matching criteria
    matchingFor: [{ type: ObjectId, ref: 'Organization' }]

});

DatasetSchema.methods = {

    fetchAndConvert: function (done) {
        var datasetRef = this;

        geogw.getRecordFromCatalog(datasetRef._id, datasetRef.publication.sourceCatalog, function (err, sourceDataset) {
            if (err) return done(err);
            var uDataset;

            datasetRef
                .set('title', sourceDataset.metadata.title)
                .set('producers', sourceDataset.organizations);

            try {
                uDataset = map(sourceDataset);
                uDataset.organization = datasetRef.publication.organization;
                uDataset.private = datasetRef.publication.status !== 'public';
            } catch (e) {
                return done(e);
            }

            done(null, uDataset);
        });
    },

    fetchWorkingAccessToken: function (done) {
        var Organization = mongoose.model('Organization');
        var organization = new Organization({ _id: this.publication.organization });
        organization.fetchWorkingAccessToken(done);
    },

    processSynchronization: function (type, done) {
        var datasetRef = this;

        async.parallel({
            uDataset: _.bind(datasetRef.fetchAndConvert, datasetRef),
            accessToken: _.bind(datasetRef.fetchWorkingAccessToken, datasetRef)
        }, function (err, context) {
            if (err) return done(err);
            if (!context.accessToken) return done(new Error('No working accessToken found'));

            function requestSyncCallback(err, publishedDataset) {
                if (err) return done(err);

                // var now = new Date();

                if (type === 'create') {
                    datasetRef
                        // .set('_created', now)
                        .set('publication._id', publishedDataset.id);
                }

                datasetRef
                    // .set('_updated', now)
                    .save(done);
            }

            if (type === 'create') {
                dgv.createDataset(context.uDataset, context.accessToken, requestSyncCallback);
            } else if (type === 'update') {
                dgv.updateDataset(datasetRef.publication._id, context.uDataset, context.accessToken, requestSyncCallback);
            } else {
                throw new Error('Unknown type for processSynchronization');
            }
        });
    },

    synchronize: function (done) {
        this.processSynchronization('update', done);
    },

    publish: function (done) {
        this.processSynchronization('create', done);
    },

    unpublish: function (done) {
        var datasetRef = this;

        datasetRef.fetchWorkingAccessToken(function (err, accessToken) {
            if (err) return done(err);
            if (!accessToken) return done(new Error('No working accessToken found'));

            dgv.deleteDataset(datasetRef.publication._id, accessToken, function (err) {
                if (err) return done(err);
                datasetRef.set('publication', undefined).save(done);
            });
        });
    }

};

mongoose.model('Dataset', DatasetSchema);
<|endoftext|>


<commit_before>/*!
 * ${copyright}
 */
/**
 * Defines support rules of the Avatar control of sap.f library.
 */
sap.ui.define(["sap/ui/support/library", "../library"],
	function(SupportLib,library) {
		"use strict";

		var Categories = SupportLib.Categories, // Accessibility, Performance, Memory, ...
			Severity = SupportLib.Severity, // Hint, Warning, Error
			Audiences = SupportLib.Audiences; // Control, Internal, Application

		var oAvatarWithCustomDisplaySize = {
			id : "avatarWithCustomDisplaySize",
			title: "Avatar with customDisplaySize property",
			minversion: "1.46",
			audiences: [Audiences.Application],
			categories: [Categories.Usage],
			description: "Avatar customDisplaySize property takes affect, only when displaySize property is set to Custom.",
			resolution: "Set displaySize property to Custom",
			check: function (oIssueManager, oCoreFacade, oScope) {
				oScope.getElementsByClassName("sap.f.Avatar")
					.forEach(function(oElement) {

					var sElementId = oElement.getId(),
					sElementName = oElement.getMetadata().getElementName();

					if (oElement.getCustomDisplaySize() && oElement.getDisplaySize() !== library.AvatarSize.Custom) {
						oIssueManager.addIssue({
							severity: Severity.Medium,
							details: "Avatar '" + sElementName + "' (" + sElementId + ") has customDisplaySize property, without setting displaySize to Custom",
							context: {
								id: sElementId
							}
						});
					}
				});
			}
		};

		return [oAvatarWithCustomDisplaySize];

	}, true);
<commit_msg>[INTERNAL] Avatar: Added support rule for customFontSize<commit_after>/*!
 * ${copyright}
 */
/**
 * Defines support rules of the Avatar control of sap.f library.
 */
sap.ui.define(["sap/ui/support/library", "../library"],
	function(SupportLib,library) {
		"use strict";

		var Categories = SupportLib.Categories, // Accessibility, Performance, Memory, ...
			Severity = SupportLib.Severity, // Hint, Warning, Error
			Audiences = SupportLib.Audiences; // Control, Internal, Application

		var oAvatarWithCustomDisplaySize = {
			id : "avatarWithCustomDisplaySize",
			title: "Avatar with customDisplaySize property",
			minversion: "1.46",
			audiences: [Audiences.Application],
			categories: [Categories.Usage],
			description: "Avatar customDisplaySize property takes affect, only when displaySize property is set to Custom.",
			resolution: "Set displaySize property to Custom",
			check: function (oIssueManager, oCoreFacade, oScope) {
				oScope.getElementsByClassName("sap.f.Avatar")
					.forEach(function(oElement) {

					var sElementId = oElement.getId(),
					sElementName = oElement.getMetadata().getElementName();

					if (oElement.getCustomDisplaySize() && oElement.getDisplaySize() !== library.AvatarSize.Custom) {
						oIssueManager.addIssue({
							severity: Severity.Medium,
							details: "Avatar '" + sElementName + "' (" + sElementId + ") has customDisplaySize property, without setting displaySize to Custom",
							context: {
								id: sElementId
							}
						});
					}
				});
			}
		};

		var oAvatarWithCustomFontSize = {
			id : "avatarWithCustomFontSize",
			title: "Avatar: Invalid combination of customFontSize and displaySize properties",
			minversion: "1.46",
			audiences: [Audiences.Application],
			categories: [Categories.Usage],
			description: "Avatar customFontSize property takes affect, only when displaySize property is set to Custom.",
			resolution: "Set displaySize property to Custom",
			check: function (oIssueManager, oCoreFacade, oScope) {
				oScope.getElementsByClassName("sap.f.Avatar")
					.forEach(function(oElement) {

					var sElementId = oElement.getId(),
					sElementName = oElement.getMetadata().getElementName(),
					bIsDefaultCustomFontSize = oElement.getCustomFontSize() === oElement.getMetadata().getProperty("customFontSize").getDefaultValue();

					if (!bIsDefaultCustomFontSize && oElement.getDisplaySize() !== library.AvatarSize.Custom) {
						oIssueManager.addIssue({
							severity: Severity.Medium,
							details: "Avatar '" + sElementName + "' (" + sElementId + ") has customFontSize property, without setting displaySize to Custom",
							context: {
								id: sElementId
							}
						});
					}
				});
			}
		};

		return [oAvatarWithCustomDisplaySize, oAvatarWithCustomFontSize];

	}, true);<|endoftext|>


<commit_before>
var cmd = require('./process');

//caches a list of installed haxelibs for the remaining execution,
var libs = {};

    exports.path = function(flow, name) {

        console.log('flow / haxelib get path for ' + name);

        if(libs[name]) {
            return libs[name].path;
        }

        var path = cmd.execsync('haxelib path ' + name);

        if(path.code != 0) {
            return '';
        } else {
            path = path.output.trim();
        }

            //for each line we need to find the one without - in front
        var lines = path.split('\n');
        for(index in lines) {
            var line = lines[index];
            if(line.charAt(0) != '-') {
                path = line;
                break;
            }
        }

        libs[name] = {
            name : name,
            path : path
        };

        return path;

    } //path

    exports.get = function(flow, name) {

        if(!libs[name]) {
            libs[name] = {
                name : name,
                path : exports.path(flow, name)
            };
        }

        return libs[name];

    } //get<commit_msg>more execsync tweaks for windows<commit_after>
var   cmd = require('./process')
    , path = require('path')

//caches a list of installed haxelibs for the remaining execution,
var libs = {};

    exports.path = function(flow, name) {

        console.log('flow / haxelib get path for ' + name);

        if(libs[name]) {
            return libs[name].path;
        }

        var result = cmd.execsync('haxelib path ' + name);

        if(result.code != 0) {
            return '';
        } else {
            result = result.output.trim();
        }

            //for each line we need to find the one without - in front
        var lines = result.split('\n');
        for(index in lines) {
            var line = lines[index].trim();
            if(line.charAt(0) != '-') {
                result = path.normalize(line);
                break;
            }
        }

        if(libs[name]) {
            libs[name].path = result;
        } else {
            libs[name] = {
                name : name,
                path : result
            };
        }

        return result;

    } //path

    exports.get = function(flow, name) {

        if(!libs[name]) {
            libs[name] = {
                name : name,
                path : exports.path(flow, name)
            };
        }

        return libs[name];

    } //get<|endoftext|>


<commit_before>/*!
 * ${copyright}
 */
sap.ui.define(['jquery.sap.global', './FlexBoxCssPropertyMap'],
	function(jQuery, FlexBoxCssPropertyMap) {
	"use strict";

	/**
	 * FlexBox styling helper
	 * @namespace
	 */
	var FlexBoxStylingHelper = {};

	/**
	 * Goes through applicable item styles and sets them on the given control.
	 *
	 * @param {sap.ui.core.RenderManager} oRm the RenderManager that can be used for writing to the render output buffer
	 * @param {sap.m.FlexItemData} oLayoutData an object representation of the layout data
	 */
	FlexBoxStylingHelper.setFlexItemStyles = function(oRm, oLayoutData) {
		oRm = oRm || null;

		var iOrder = oLayoutData.getOrder(),
			iGrowFactor = oLayoutData.getGrowFactor(),
			iShrinkFactor = oLayoutData.getShrinkFactor(),
			sBaseSize = oLayoutData.getBaseSize().toLowerCase(),
			sMinHeight = oLayoutData.getMinHeight(),
			sMaxHeight = oLayoutData.getMaxHeight(),
			sMinWidth = oLayoutData.getMinWidth(),
			sMaxWidth = oLayoutData.getMaxWidth();

		// Set values if different from default
		if (iOrder) {
			FlexBoxStylingHelper.setStyle(oRm, oLayoutData, "order", iOrder);
		}

		if (iGrowFactor != undefined) {
			FlexBoxStylingHelper.setStyle(oRm, oLayoutData, "flex-grow", iGrowFactor);
		}

		if (jQuery.support.newFlexBoxLayout || jQuery.support.ie10FlexBoxLayout) {
			if (iShrinkFactor !== 1) {
				FlexBoxStylingHelper.setStyle(oRm, oLayoutData, "flex-shrink", iShrinkFactor);
			}

			if (sBaseSize != undefined) {
				FlexBoxStylingHelper.setStyle(oRm, oLayoutData, "flex-basis", sBaseSize);
			}
		}

		if (sMinHeight != undefined) {
			FlexBoxStylingHelper.setStyle(oRm, oLayoutData, "min-height", sMinHeight);
		}
		if (sMaxHeight != undefined) {
			FlexBoxStylingHelper.setStyle(oRm, oLayoutData, "max-height", sMaxHeight);
		}
		if (sMinWidth != undefined) {
			FlexBoxStylingHelper.setStyle(oRm, oLayoutData, "min-width", sMinWidth);
		}
		if (sMaxWidth != undefined) {
			FlexBoxStylingHelper.setStyle(oRm, oLayoutData, "max-width", sMaxWidth);
		}
	};

	/**
	 * Sets style (including fall-back styles) to the given control, using the provided {@link sap.ui.core.RenderManager}.
	 *
	 * @param {sap.ui.core.RenderManager} oRm the RenderManager that can be used for writing to the render output buffer
	 * @param {sap.m.FlexItemData} oLayoutData an object representation of the layout data
	 * @param sProperty name of the property
	 * @param sValue value of the property
	 */
	FlexBoxStylingHelper.setStyle = function(oRm, oLayoutData, sProperty, sValue) {
		if (typeof (sValue) === "string") {
			// Convert camel-case to lower-case and dashes
			sValue = sValue.replace(/([a-z])([A-Z])/g, "$1-$2").toLowerCase();
		}

		if (jQuery.support.flexBoxPrefixed) {
			if (sap.ui.Device.browser.webkit) {
				this.sVendorPrefix = "-webkit-";
			} else if (sap.ui.Device.browser.mozilla) {
				this.sVendorPrefix = "-moz-";
			} else if (sap.ui.Device.browser.internet_explorer) {
				this.sVendorPrefix = "-ms-";
			}
		} else {
			this.sVendorPrefix = "";
		}

		// Choose flex box styling method
		if (jQuery.support.newFlexBoxLayout || ["min-height", "max-height", "min-width", "max-width"].indexOf(sProperty) !== -1) {
			// New spec
			FlexBoxStylingHelper.writeStyle(oRm, oLayoutData, sProperty, sValue);
		} else if (jQuery.support.flexBoxLayout || jQuery.support.ie10FlexBoxLayout) {
			// Old spec
			FlexBoxStylingHelper.setOldSpecStyle(oRm, oLayoutData, sProperty, sValue);
		}
	};

	/**
	 * Sets style for the OLD or the IE10 flex box spec to the given control, using the provided {@link sap.ui.core.RenderManager}.
	 *
	 * @param {sap.ui.core.RenderManager} oRm the RenderManager that can be used for writing to the render output buffer
	 * @param {sap.m.FlexItemData} oLayoutData an object representation of the layout data
	 * @param sProperty name of the property
	 * @param sValue value of the property
	 */
	FlexBoxStylingHelper.setOldSpecStyle = function(oRm, oLayoutData, sProperty, sValue) {
		// Choose specification
		var sSpec = "";
		if (this.sVendorPrefix == "-ms-") {
			sSpec = "specie10"; // IE10 specification
		} else {
			sSpec = "spec0907";	// old specification
		}

		// Nothing to do if final standard is supported or property doesn't exist in this spec or is the same as standard
		// Else map to old property
		if (FlexBoxCssPropertyMap[sSpec][sProperty] !== null && FlexBoxCssPropertyMap[sSpec][sProperty] !== "<idem>") {
			// Prepare mapped properties and values
			var mLegacyMap = null;
			if (typeof (FlexBoxCssPropertyMap[sSpec][sProperty]) === "object") {
				if (FlexBoxCssPropertyMap[sSpec][sProperty]["<number>"]) {
					mLegacyMap = {};
					for (var key in FlexBoxCssPropertyMap[sSpec][sProperty]["<number>"]) {
						// Check if the target is also a number, otherwise assume it's a literal
						if (FlexBoxCssPropertyMap[sSpec][sProperty]["<number>"][key] === "<number>") {
							mLegacyMap[key] = sValue;
						} else {
							mLegacyMap[key] = FlexBoxCssPropertyMap[sSpec][sProperty]["<number>"][key];
						}
					}
				} else {
					mLegacyMap = FlexBoxCssPropertyMap[sSpec][sProperty][sValue];
				}
			} else {
				mLegacyMap = FlexBoxCssPropertyMap[sSpec][sProperty][sValue];
			}

			// Nothing to do if value doesn't exist or is the same as standard
			if (mLegacyMap !== null && mLegacyMap !== "<idem>") {
				if (typeof (mLegacyMap) === "object") {
					for (var sLegacyProperty in mLegacyMap) {
						// Write property/value to control
						FlexBoxStylingHelper.writeStyle(oRm, oLayoutData, sLegacyProperty, mLegacyMap[sLegacyProperty]);
					}
				}
			}
		}
	};

	/**
	 * Writes the style to the given control, using the provided {@link sap.ui.core.RenderManager} or jQuery.
	 *
	 * @param {sap.ui.core.RenderManager} oRm the RenderManager that can be used for writing to the render output buffer
	 * @param {sap.m.FlexItemData} oLayoutData an object representation of the layout data
	 * @param sProperty name of the property
	 * @param sValue value of the property
	 */
	FlexBoxStylingHelper.writeStyle = function(oRm, oLayoutData, sProperty, sValue) {
		var sPropertyPrefix = "";
		var sValuePrefix = "";

		// Set prefix to value for 'display' property
		// As 'display' is a long-standing standard property, the value is vendor-prefixed instead of the property name
		if (sProperty !== "display") {
			sPropertyPrefix = this.sVendorPrefix;
		} else {
			sValuePrefix = this.sVendorPrefix;
		}

		// IE 10-11 miscalculate the width of the flex items when box-sizing: border-box
		// Instead of using flex-basis, we use an explicit width/height
		// @see https://github.com/philipwalton/flexbugs#7-flex-basis-doesnt-account-for-box-sizingborder-box
		if (sap.ui.Device.browser.internet_explorer && (sProperty === "flex-basis" || sProperty === "flex-preferred-size")) {
			sPropertyPrefix = "";
			if (oLayoutData.getParent().getParent().getDirection().indexOf("Row") > -1) {
				sProperty = "width";
			} else {
				sProperty = "height";
			}
		}

		// Finally, write property value to control using either the renderer or element directly
		if (oRm) {
			oRm.addStyle(sPropertyPrefix + sProperty, sValuePrefix + sValue);
		} else {
			oLayoutData.$().css(sPropertyPrefix + sProperty, sValuePrefix + sValue);
		}
	};

	return FlexBoxStylingHelper;

}, /* bExport= */ true);
<commit_msg>[INTERNAL][FIX] sap.m.FlexBoxItem: correct exception on creation in IE<commit_after>/*!
 * ${copyright}
 */
sap.ui.define(['jquery.sap.global', './FlexBoxCssPropertyMap'],
	function(jQuery, FlexBoxCssPropertyMap) {
	"use strict";

	/**
	 * FlexBox styling helper
	 * @namespace
	 */
	var FlexBoxStylingHelper = {};

	/**
	 * Goes through applicable item styles and sets them on the given control.
	 *
	 * @param {sap.ui.core.RenderManager} oRm the RenderManager that can be used for writing to the render output buffer
	 * @param {sap.m.FlexItemData} oLayoutData an object representation of the layout data
	 */
	FlexBoxStylingHelper.setFlexItemStyles = function(oRm, oLayoutData) {
		oRm = oRm || null;

		var iOrder = oLayoutData.getOrder(),
			iGrowFactor = oLayoutData.getGrowFactor(),
			iShrinkFactor = oLayoutData.getShrinkFactor(),
			sBaseSize = oLayoutData.getBaseSize().toLowerCase(),
			sMinHeight = oLayoutData.getMinHeight(),
			sMaxHeight = oLayoutData.getMaxHeight(),
			sMinWidth = oLayoutData.getMinWidth(),
			sMaxWidth = oLayoutData.getMaxWidth();

		// Set values if different from default
		if (iOrder) {
			FlexBoxStylingHelper.setStyle(oRm, oLayoutData, "order", iOrder);
		}

		if (iGrowFactor != undefined) {
			FlexBoxStylingHelper.setStyle(oRm, oLayoutData, "flex-grow", iGrowFactor);
		}

		if (jQuery.support.newFlexBoxLayout || jQuery.support.ie10FlexBoxLayout) {
			if (iShrinkFactor !== 1) {
				FlexBoxStylingHelper.setStyle(oRm, oLayoutData, "flex-shrink", iShrinkFactor);
			}

			if (sBaseSize != undefined) {
				FlexBoxStylingHelper.setStyle(oRm, oLayoutData, "flex-basis", sBaseSize);
			}
		}

		if (sMinHeight != undefined) {
			FlexBoxStylingHelper.setStyle(oRm, oLayoutData, "min-height", sMinHeight);
		}
		if (sMaxHeight != undefined) {
			FlexBoxStylingHelper.setStyle(oRm, oLayoutData, "max-height", sMaxHeight);
		}
		if (sMinWidth != undefined) {
			FlexBoxStylingHelper.setStyle(oRm, oLayoutData, "min-width", sMinWidth);
		}
		if (sMaxWidth != undefined) {
			FlexBoxStylingHelper.setStyle(oRm, oLayoutData, "max-width", sMaxWidth);
		}
	};

	/**
	 * Sets style (including fall-back styles) to the given control, using the provided {@link sap.ui.core.RenderManager}.
	 *
	 * @param {sap.ui.core.RenderManager} oRm the RenderManager that can be used for writing to the render output buffer
	 * @param {sap.m.FlexItemData} oLayoutData an object representation of the layout data
	 * @param sProperty name of the property
	 * @param sValue value of the property
	 */
	FlexBoxStylingHelper.setStyle = function(oRm, oLayoutData, sProperty, sValue) {
		if (typeof (sValue) === "string") {
			// Convert camel-case to lower-case and dashes
			sValue = sValue.replace(/([a-z])([A-Z])/g, "$1-$2").toLowerCase();
		}

		if (jQuery.support.flexBoxPrefixed) {
			if (sap.ui.Device.browser.webkit) {
				this.sVendorPrefix = "-webkit-";
			} else if (sap.ui.Device.browser.mozilla) {
				this.sVendorPrefix = "-moz-";
			} else if (sap.ui.Device.browser.internet_explorer) {
				this.sVendorPrefix = "-ms-";
			}
		} else {
			this.sVendorPrefix = "";
		}

		// Choose flex box styling method
		if (jQuery.support.newFlexBoxLayout || ["min-height", "max-height", "min-width", "max-width"].indexOf(sProperty) !== -1) {
			// New spec
			FlexBoxStylingHelper.writeStyle(oRm, oLayoutData, sProperty, sValue);
		} else if (jQuery.support.flexBoxLayout || jQuery.support.ie10FlexBoxLayout) {
			// Old spec
			FlexBoxStylingHelper.setOldSpecStyle(oRm, oLayoutData, sProperty, sValue);
		}
	};

	/**
	 * Sets style for the OLD or the IE10 flex box spec to the given control, using the provided {@link sap.ui.core.RenderManager}.
	 *
	 * @param {sap.ui.core.RenderManager} oRm the RenderManager that can be used for writing to the render output buffer
	 * @param {sap.m.FlexItemData} oLayoutData an object representation of the layout data
	 * @param sProperty name of the property
	 * @param sValue value of the property
	 */
	FlexBoxStylingHelper.setOldSpecStyle = function(oRm, oLayoutData, sProperty, sValue) {
		// Choose specification
		var sSpec = "";
		if (this.sVendorPrefix == "-ms-") {
			sSpec = "specie10"; // IE10 specification
		} else {
			sSpec = "spec0907";	// old specification
		}

		// Nothing to do if final standard is supported or property doesn't exist in this spec or is the same as standard
		// Else map to old property
		if (FlexBoxCssPropertyMap[sSpec][sProperty] !== null && FlexBoxCssPropertyMap[sSpec][sProperty] !== "<idem>") {
			// Prepare mapped properties and values
			var mLegacyMap = null;
			if (typeof (FlexBoxCssPropertyMap[sSpec][sProperty]) === "object") {
				if (FlexBoxCssPropertyMap[sSpec][sProperty]["<number>"]) {
					mLegacyMap = {};
					for (var key in FlexBoxCssPropertyMap[sSpec][sProperty]["<number>"]) {
						// Check if the target is also a number, otherwise assume it's a literal
						if (FlexBoxCssPropertyMap[sSpec][sProperty]["<number>"][key] === "<number>") {
							mLegacyMap[key] = sValue;
						} else {
							mLegacyMap[key] = FlexBoxCssPropertyMap[sSpec][sProperty]["<number>"][key];
						}
					}
				} else {
					mLegacyMap = FlexBoxCssPropertyMap[sSpec][sProperty][sValue];
				}
			} else {
				mLegacyMap = FlexBoxCssPropertyMap[sSpec][sProperty][sValue];
			}

			// Nothing to do if value doesn't exist or is the same as standard
			if (mLegacyMap !== null && mLegacyMap !== "<idem>") {
				if (typeof (mLegacyMap) === "object") {
					for (var sLegacyProperty in mLegacyMap) {
						// Write property/value to control
						FlexBoxStylingHelper.writeStyle(oRm, oLayoutData, sLegacyProperty, mLegacyMap[sLegacyProperty]);
					}
				}
			}
		}
	};

	/**
	 * Writes the style to the given control, using the provided {@link sap.ui.core.RenderManager} or jQuery.
	 *
	 * @param {sap.ui.core.RenderManager} oRm the RenderManager that can be used for writing to the render output buffer
	 * @param {sap.m.FlexItemData} oLayoutData an object representation of the layout data
	 * @param sProperty name of the property
	 * @param sValue value of the property
	 */
	FlexBoxStylingHelper.writeStyle = function(oRm, oLayoutData, sProperty, sValue) {
		var sPropertyPrefix = "";
		var sValuePrefix = "";

		// Set prefix to value for 'display' property
		// As 'display' is a long-standing standard property, the value is vendor-prefixed instead of the property name
		if (sProperty !== "display") {
			sPropertyPrefix = this.sVendorPrefix;
		} else {
			sValuePrefix = this.sVendorPrefix;
		}

		// IE 10-11 miscalculate the width of the flex items when box-sizing: border-box
		// Instead of using flex-basis, we use an explicit width/height
		// @see https://github.com/philipwalton/flexbugs#7-flex-basis-doesnt-account-for-box-sizingborder-box
		if (sap.ui.Device.browser.internet_explorer && (sProperty === "flex-basis" || sProperty === "flex-preferred-size")) {
			sPropertyPrefix = "";
			if (oLayoutData.getParent()) {
				if (oLayoutData.getParent().getParent().getDirection().indexOf("Row") > -1) {
					sProperty = "width";
				} else {
					sProperty = "height";
				}
			}
		}

		// Finally, write property value to control using either the renderer or element directly
		if (oRm) {
			oRm.addStyle(sPropertyPrefix + sProperty, sValuePrefix + sValue);
		} else {
			oLayoutData.$().css(sPropertyPrefix + sProperty, sValuePrefix + sValue);
		}
	};

	return FlexBoxStylingHelper;

}, /* bExport= */ true);
<|endoftext|>