code stringlengths 3 1.05M | repo_name stringlengths 4 116 | path stringlengths 4 991 | language stringclasses 9
values | license stringclasses 15
values | size int32 3 1.05M |
|---|---|---|---|---|---|
!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.Bam=e()}}(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
},{}],2:[function(require,module,exports){
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
'use strict';
// If obj.hasOwnProperty has been overridden, then calling
// obj.hasOwnProperty(prop) will break.
// See: https://github.com/joyent/node/issues/1707
function hasOwnProperty(obj, prop) {
return Object.prototype.hasOwnProperty.call(obj, prop);
}
module.exports = function(qs, sep, eq, options) {
sep = sep || '&';
eq = eq || '=';
var obj = {};
if (typeof qs !== 'string' || qs.length === 0) {
return obj;
}
var regexp = /\+/g;
qs = qs.split(sep);
var maxKeys = 1000;
if (options && typeof options.maxKeys === 'number') {
maxKeys = options.maxKeys;
}
var len = qs.length;
// maxKeys <= 0 means that we should not limit keys count
if (maxKeys > 0 && len > maxKeys) {
len = maxKeys;
}
for (var i = 0; i < len; ++i) {
var x = qs[i].replace(regexp, '%20'),
idx = x.indexOf(eq),
kstr, vstr, k, v;
if (idx >= 0) {
kstr = x.substr(0, idx);
vstr = x.substr(idx + 1);
} else {
kstr = x;
vstr = '';
}
k = decodeURIComponent(kstr);
v = decodeURIComponent(vstr);
if (!hasOwnProperty(obj, k)) {
obj[k] = v;
} else if (isArray(obj[k])) {
obj[k].push(v);
} else {
obj[k] = [obj[k], v];
}
}
return obj;
};
var isArray = Array.isArray || function (xs) {
return Object.prototype.toString.call(xs) === '[object Array]';
};
},{}],3:[function(require,module,exports){
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
'use strict';
var stringifyPrimitive = function(v) {
switch (typeof v) {
case 'string':
return v;
case 'boolean':
return v ? 'true' : 'false';
case 'number':
return isFinite(v) ? v : '';
default:
return '';
}
};
module.exports = function(obj, sep, eq, name) {
sep = sep || '&';
eq = eq || '=';
if (obj === null) {
obj = undefined;
}
if (typeof obj === 'object') {
return map(objectKeys(obj), function(k) {
var ks = encodeURIComponent(stringifyPrimitive(k)) + eq;
if (isArray(obj[k])) {
return map(obj[k], function(v) {
return ks + encodeURIComponent(stringifyPrimitive(v));
}).join(sep);
} else {
return ks + encodeURIComponent(stringifyPrimitive(obj[k]));
}
}).join(sep);
}
if (!name) return '';
return encodeURIComponent(stringifyPrimitive(name)) + eq +
encodeURIComponent(stringifyPrimitive(obj));
};
var isArray = Array.isArray || function (xs) {
return Object.prototype.toString.call(xs) === '[object Array]';
};
function map (xs, f) {
if (xs.map) return xs.map(f);
var res = [];
for (var i = 0; i < xs.length; i++) {
res.push(f(xs[i], i));
}
return res;
}
var objectKeys = Object.keys || function (obj) {
var res = [];
for (var key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) res.push(key);
}
return res;
};
},{}],4:[function(require,module,exports){
'use strict';
exports.decode = exports.parse = require('./decode');
exports.encode = exports.stringify = require('./encode');
},{"./decode":2,"./encode":3}],5:[function(require,module,exports){
module.exports = require('backbone');
},{"backbone":1}],6:[function(require,module,exports){
var Backbone, Collection,
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
Backbone = require('backbone');
Collection = (function(_super) {
__extends(Collection, _super);
function Collection() {
return Collection.__super__.constructor.apply(this, arguments);
}
/*
Returns the model at the index immediately before the passed in model
instance. If the model instance is the first model in the collection, or
the model instance does not exist in the collection, this will return
null.
*/
Collection.prototype.before = function(model) {
var index;
index = this.indexOf(model);
if (index === -1 || index === 0) {
return null;
}
return this.at(index - 1);
};
/*
Returns the model at the index immediately after the passed in model
instance. If the model instance is the last model in the collection, or
the model instance does not exist in the collection, this will return
null.
*/
Collection.prototype.after = function(model) {
var index;
index = this.indexOf(model);
if (index === -1 || index === this.length - 1) {
return null;
}
return this.at(index + 1);
};
/*
Convenience function for getting an array of all the models in a
collection
*/
Collection.prototype.all = function() {
return this.models.slice();
};
return Collection;
})(Backbone.Collection);
module.exports = Collection;
},{"backbone":1}],7:[function(require,module,exports){
var Bam;
module.exports = Bam = {
Backbone: require('./backbone'),
Router: require('./router'),
View: require('./view'),
Model: require('./model'),
Collection: require('./collection')
};
},{"./backbone":5,"./collection":6,"./model":8,"./router":9,"./view":10}],8:[function(require,module,exports){
var Backbone, DEFAULT_CASTS, Model, any, map, _ref,
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
Backbone = require('backbone');
_ref = require('underscore'), map = _ref.map, any = _ref.any;
DEFAULT_CASTS = {
string: function(v) {
return v + '';
},
int: function(v) {
return Math.floor(+v);
},
number: function(v) {
return +v;
},
date: function(v) {
return new Date(v);
},
boolean: function(v) {
return !!v;
}
};
Model = (function(_super) {
__extends(Model, _super);
function Model() {
return Model.__super__.constructor.apply(this, arguments);
}
/*
Allows derived get values. The format is:
derived:
foo:
deps: ['bar', 'baz']
value: (bar, baz) -> bar + ' ' + baz
Your deps define which properties will be passed to the value function and
in what order. They're also used to trigger change events for derived values
i.e., if a dep changes the derived value will trigger a change too.
*/
Model.prototype.derived = {};
/*
Allows casting specific keys. The format is:
cast:
timestamp: (v) -> moment(v)
bar: 'string'
baz: 'int'
You can either provide your own function or use a provided basic cast. These
include:
* `'string'`: `(v) -> v + ''`
* `'int'`: `(v) -> Math.floor(+v)`
* `'number'`: `(v) -> +v`
* `'date'`: `(v) -> new Date(v)`
* `'boolean'`: (v) -> !!v
Doesn't cast derived or null values.
*/
Model.prototype.cast = {};
/*
Returns the model after this model in its collection. If it's not in a
collection this will return null.
*/
Model.prototype.next = function() {
var _ref1;
return (_ref1 = this.collection) != null ? _ref1.after(this) : void 0;
};
/*
Returns the model before this model in its collection. If it's not in a
collection this will return null.
*/
Model.prototype.prev = function() {
var _ref1;
return (_ref1 = this.collection) != null ? _ref1.before(this) : void 0;
};
/*
Returns a clone of the attributes object.
*/
Model.prototype.getAttributes = function() {
return Backbone.$.extend(true, {}, this.attributes);
};
/*
Override get to allow default value and derived values.
*/
Model.prototype.get = function(key, defaultValue) {
var ret;
if (this.derived[key]) {
ret = this._derive(derived[key]);
} else {
ret = Model.__super__.get.call(this, key);
}
if (ret === void 0) {
return defaultValue;
} else {
return ret;
}
};
/*
Derive a value from a definition
*/
Model.prototype._derive = function(definition) {
var args;
args = map(definition.deps, (function(_this) {
return function(key) {
return _this.get('key');
};
})(this));
return definition.value.apply(definition, args);
};
/*
Override the set method to allow for casting as data comes in.
*/
Model.prototype.set = function(key, val, options) {
var attrs, changed, definition, derived, ret, _ref1;
if (typeof key === 'object') {
attrs = key;
options = val;
} else {
attrs = {};
attrs[key] = val;
}
for (key in attrs) {
val = attrs[key];
if (val === null) {
continue;
}
if (this.cast[key]) {
attrs[key] = this._cast(val, this.cast[key]);
}
}
ret = Model.__super__.set.call(this, attrs, options);
_ref1 = this.derived;
for (derived in _ref1) {
definition = _ref1[derived];
changed = map(definition.deps, function(key) {
return attrs.hasOwnProperty(key);
});
if (any(changed)) {
this.trigger("change:" + derived, this._derive(definition));
}
}
return ret;
};
/*
Take a value, and a casting definition and perform the cast
*/
Model.prototype._cast = function(value, cast) {
var error;
try {
return value = this._getCastFunc(cast)(value);
} catch (_error) {
error = _error;
return value = null;
} finally {
return value;
}
};
/*
Given a casting definition, return a function that should perform the cast
*/
Model.prototype._getCastFunc = function(cast) {
var _ref1;
if (typeof cast === 'function') {
return cast;
}
return (_ref1 = DEFAULT_CASTS[cast]) != null ? _ref1 : function(v) {
return v;
};
};
return Model;
})(Backbone.Model);
module.exports = Model;
},{"backbone":1,"underscore":1}],9:[function(require,module,exports){
var Backbone, Router, difference, extend, getIndexes, getNames, isFunction, isRegExp, keys, map, object, pluck, process, querystring, sortBy, splice, zip, _,
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
__slice = [].slice;
Backbone = require('backbone');
querystring = require('querystring');
_ = require('underscore');
extend = _.extend, object = _.object, isRegExp = _.isRegExp, isFunction = _.isFunction, zip = _.zip, pluck = _.pluck, sortBy = _.sortBy, keys = _.keys;
difference = _.difference, map = _.map;
getNames = function(string) {
var ret;
ret = [];
ret.push.apply(ret, process(string, /(\(\?)?:\w+/g));
ret.push.apply(ret, process(string, /\*\w+/g));
return ret;
};
process = function(string, regex) {
var indexes, matches, _ref;
matches = (_ref = string.match(regex)) != null ? _ref : [];
indexes = getIndexes(string, regex);
return zip(matches, indexes);
};
getIndexes = function(string, regex) {
var ret;
ret = [];
while (regex.test(string)) {
ret.push(regex.lastIndex);
}
return ret;
};
splice = function(source, from, to, replacement) {
if (replacement == null) {
replacement = '';
}
return source.slice(0, from) + replacement + source.slice(to);
};
Router = (function(_super) {
__extends(Router, _super);
/*
Override so our _routes object is unique to each router. I hate this side of
js.
*/
function Router() {
var args;
args = 1 <= arguments.length ? __slice.call(arguments, 0) : [];
this._routes = {};
Router.__super__.constructor.apply(this, args);
}
/*
Override route to perform some subtle tweaks! Namely, storing raw string
routes for reverse routing and passing the name to the buildRequest function
*/
Router.prototype.route = function(route, name, callback) {
if (!isRegExp(route)) {
this._routes[name] = route;
route = this._routeToRegExp(route);
}
if (isFunction(name)) {
callback = name;
name = '';
}
if (!callback) {
callback = this[name];
}
return Backbone.history.route(route, (function(_this) {
return function(fragment) {
var req;
req = _this._buildRequest(route, fragment, name);
_this.execute(callback, req);
_this.trigger.apply(_this, ['route:' + name, req]);
_this.trigger('route', name, req);
return Backbone.history.trigger('route', _this, name, req);
};
})(this));
};
/*
Store names of parameters in a propery of route
*/
Router.prototype._routeToRegExp = function(route) {
var names, ret;
ret = Router.__super__._routeToRegExp.call(this, route);
names = getNames(route);
ret.names = map(pluck(sortBy(names, '1'), '0'), function(s) {
return s.slice(1);
});
return ret;
};
/*
Create a request object. It should have the route name, named params as
keys with their values and a query object which is the query params, an
empty object if no query params available.
*/
Router.prototype._buildRequest = function(route, fragment, name) {
var names, query, req, values, _ref, _ref1;
values = this._extractParameters(route, fragment);
query = fragment.split('?').slice(1).join('?');
if (values[values.length - 1] === query) {
values = values.slice(0, -1);
}
names = (_ref = route.names) != null ? _ref : map(values, function(v, i) {
return i;
});
req = {
route: (_ref1 = this._routes[name]) != null ? _ref1 : route,
fragment: fragment,
name: name,
values: values,
params: object(names, values),
query: querystring.parse(query)
};
return req;
};
/*
No-op to stop the routes propery being used
*/
Router.prototype._bindRoutes = function() {};
/*
Rather than the default backbone behaviour of applying the args to the
callback, call the callback with the request object.
*/
Router.prototype.execute = function(callback, req) {
if (callback) {
return callback.call(this, req);
}
};
/*
Reverse a named route with a barebones request object.
*/
Router.prototype.reverse = function(name, req) {
var diff, lastIndex, nameds, names, optional, optionals, params, query, ret, route, segment, value, _i, _j, _len, _len1, _ref, _ref1, _ref2, _ref3, _ref4;
route = this._routes[name];
if (!route) {
return null;
}
ret = route;
params = (_ref = req.params) != null ? _ref : {};
query = (_ref1 = req.query) != null ? _ref1 : {};
names = keys(params);
optionals = process(route, /\((.*?)\)/g).reverse();
for (_i = 0, _len = optionals.length; _i < _len; _i++) {
_ref2 = optionals[_i], optional = _ref2[0], lastIndex = _ref2[1];
nameds = map(pluck(getNames(optional), '0'), function(s) {
return s.slice(1);
});
diff = difference(nameds, names).length;
if (nameds.length === 0 || diff !== 0) {
route = splice(route, lastIndex - optional.length, lastIndex);
} else {
route = splice(route, lastIndex - optional.length, lastIndex, optional.slice(1, -1));
}
}
nameds = getNames(route).reverse();
for (_j = 0, _len1 = nameds.length; _j < _len1; _j++) {
_ref3 = nameds[_j], segment = _ref3[0], lastIndex = _ref3[1];
value = (_ref4 = params[segment.slice(1)]) != null ? _ref4 : null;
if (value !== null) {
route = splice(route, lastIndex - segment.length, lastIndex, params[segment.slice(1)]);
}
}
query = querystring.stringify(query);
if (query) {
route += '?' + query;
}
return route;
};
return Router;
})(Backbone.Router);
module.exports = Router;
},{"backbone":1,"querystring":4,"underscore":1}],10:[function(require,module,exports){
var Backbone, View, difference, without, _ref,
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
__indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; },
__slice = [].slice;
Backbone = require('backbone');
_ref = require('underscore'), without = _ref.without, difference = _ref.difference;
View = (function(_super) {
__extends(View, _super);
View.prototype.parent = null;
View.prototype.children = null;
View.prototype.namespace = '';
/*
Ensure the classname is applied, then set the parent and children if any
are passed in. Does the normal backbone constructor and then does the
first state change.
*/
function View(options) {
var _ref1;
this.children = [];
if (options.className) {
this.className = options.className;
}
if (options.namespace) {
this.namespace = options.namespace;
}
if (options.el) {
this._ensureClass(options.el);
}
if (options.parent) {
this.setParent(options.parent);
}
if ((_ref1 = options.children) != null ? _ref1.length : void 0) {
this.addChildren(options.children);
}
View.__super__.constructor.call(this, options);
}
/*
Used to ensure that the className property of the view is applied to an
el passed in as an option.
*/
View.prototype._ensureClass = function(el, className) {
if (className == null) {
className = this.className;
}
return Backbone.$(el).addClass(className);
};
/*
Adds a list of views as children of this view.
*/
View.prototype.addChildren = function(views) {
var view, _i, _len, _results;
_results = [];
for (_i = 0, _len = views.length; _i < _len; _i++) {
view = views[_i];
_results.push(this.addChild(view));
}
return _results;
};
/*
Adds a view as a child of this view.
*/
View.prototype.addChild = function(view) {
if (view.parent) {
view.unsetParent();
}
this.children.push(view);
return view.parent = this;
};
/*
Sets the parent view.
*/
View.prototype.setParent = function(parent) {
if (this.parent) {
this.unsetParent();
}
this.parent = parent;
return this.parent.children.push(this);
};
/*
Unsets the parent view.
*/
View.prototype.unsetParent = function() {
if (!this.parent) {
return;
}
return this.parent.removeChild(this);
};
/*
Parent and Child accessors.
*/
View.prototype.hasParent = function() {
return !!this.parent;
};
View.prototype.getParent = function() {
return this.parent;
};
View.prototype.hasChildren = function() {
return this.children.length;
};
View.prototype.getChildren = function() {
return this.children;
};
View.prototype.hasChild = function(view) {
return __indexOf.call(this.children, view) >= 0;
};
View.prototype.hasDescendant = function(view) {
var child, _i, _len, _ref1;
if (__indexOf.call(this.children, view) >= 0) {
return true;
}
_ref1 = this.children;
for (_i = 0, _len = _ref1.length; _i < _len; _i++) {
child = _ref1[_i];
if (child.hasDescendant(view)) {
return true;
}
}
return false;
};
View.prototype.removeChild = function(child) {
this.children = without(this.children, child);
return child.parent = null;
};
View.prototype.removeChildren = function(children) {
var child, _i, _len, _ref1, _results;
_ref1 = this.children;
_results = [];
for (_i = 0, _len = _ref1.length; _i < _len; _i++) {
child = _ref1[_i];
_results.push(this.removeChild(child));
}
return _results;
};
/*
Gets the root view for a particular view. Can be itself.
*/
View.prototype.root = function() {
var root;
root = this;
while (root.hasParent()) {
root = root.getParent();
}
return root;
};
/*
Calls remove on all child views before removing itself
*/
View.prototype.remove = function() {
this.children.forEach(function(child) {
return child.remove();
});
this.children = [];
this.parent = null;
this.off();
this.undelegateEvents();
return View.__super__.remove.call(this);
};
/*
Calls trigger on the root() object with the namespace added, and also on
itself without the namespace.
*/
View.prototype.trigger = function() {
var args;
args = 1 <= arguments.length ? __slice.call(arguments, 0) : [];
Backbone.View.prototype.trigger.apply(this, args);
if (this.namespace) {
args[0] = this.namespace + '.' + args[0];
}
if (this.parent) {
return this.parent.trigger.apply(this.parent, args);
}
};
return View;
})(Backbone.View);
module.exports = View;
},{"backbone":1,"underscore":1}]},{},[7])(7)
}); | Bockit/bam | dist/bam.js | JavaScript | bsd-3-clause | 24,391 |
<?php
namespace Application\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity
* @ORM\Table(name="video")
**/
class Video
{
/**
* @ORM\Column(name="video_id", type="integer", nullable=false)
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $videoId;
/**
* @ORM\Column(name="video_title", type="string", nullable=false)
**/
private $videoTitle;
/**
* @ORM\Column(name="video_url", type="string", nullable=false)
**/
private $videoUrl;
/**
* @ORM\Column(name="video_toggle", type="boolean", nullable=false, options={"default"=1})
**/
private $videoToggle;
//--------------------------------------------------------------------------------//
public function getVideoId(){
return $this->videoId;
}
public function setVideoId($videoId){
$this->videoId = $videoId;
}
public function getVideoTitle(){
return $this->videoTitle;
}
public function setVideoTitle($videoTitle){
$this->videoTitle = $videoTitle;
}
public function getVideoUrl(){
return $this->videoUrl;
}
public function setVideoUrl($videoUrl){
$this->videoUrl = $videoUrl;
}
public function getVideoToggle(){
return $this->videoToggle;
}
public function setVideoToggle($videoToggle){
$this->videoToggle = $videoToggle;
}
} | felsf/consultoria | module/Application/src/Application/Entity/Video.php | PHP | bsd-3-clause | 1,276 |
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "net/tools/quic/quic_packet_reader.h"
#include <errno.h>
#ifndef __APPLE__
// This is a GNU header that is not present in /usr/include on MacOS
#include <features.h>
#endif
#include <string.h>
#include <sys/epoll.h>
#include "base/logging.h"
#include "net/base/ip_endpoint.h"
#include "net/quic/quic_flags.h"
#include "net/tools/quic/quic_dispatcher.h"
#include "net/tools/quic/quic_socket_utils.h"
#define MMSG_MORE 0
#ifndef SO_RXQ_OVFL
#define SO_RXQ_OVFL 40
#endif
namespace net {
namespace tools {
QuicPacketReader::QuicPacketReader() {
Initialize();
}
void QuicPacketReader::Initialize() {
// Zero initialize uninitialized memory.
memset(cbuf_, 0, arraysize(cbuf_));
memset(buf_, 0, arraysize(buf_));
memset(raw_address_, 0, sizeof(raw_address_));
memset(mmsg_hdr_, 0, sizeof(mmsg_hdr_));
for (int i = 0; i < kNumPacketsPerReadMmsgCall; ++i) {
iov_[i].iov_base = buf_ + (2 * kMaxPacketSize * i);
iov_[i].iov_len = 2 * kMaxPacketSize;
msghdr* hdr = &mmsg_hdr_[i].msg_hdr;
hdr->msg_name = &raw_address_[i];
hdr->msg_namelen = sizeof(sockaddr_storage);
hdr->msg_iov = &iov_[i];
hdr->msg_iovlen = 1;
hdr->msg_control = cbuf_ + kSpaceForOverflowAndIp * i;
hdr->msg_controllen = kSpaceForOverflowAndIp;
}
}
QuicPacketReader::~QuicPacketReader() {
}
bool QuicPacketReader::ReadAndDispatchPackets(
int fd,
int port,
ProcessPacketInterface* processor,
QuicPacketCount* packets_dropped) {
#if MMSG_MORE
// Re-set the length fields in case recvmmsg has changed them.
for (int i = 0; i < kNumPacketsPerReadMmsgCall; ++i) {
iov_[i].iov_len = 2 * kMaxPacketSize;
mmsg_hdr_[i].msg_len = 0;
msghdr* hdr = &mmsg_hdr_[i].msg_hdr;
hdr->msg_namelen = sizeof(sockaddr_storage);
hdr->msg_iovlen = 1;
hdr->msg_controllen = kSpaceForOverflowAndIp;
}
int packets_read =
recvmmsg(fd, mmsg_hdr_, kNumPacketsPerReadMmsgCall, 0, nullptr);
if (packets_read <= 0) {
return false; // recvmmsg failed.
}
for (int i = 0; i < packets_read; ++i) {
if (mmsg_hdr_[i].msg_len == 0) {
continue;
}
IPEndPoint client_address = IPEndPoint(raw_address_[i]);
IPAddressNumber server_ip =
QuicSocketUtils::GetAddressFromMsghdr(&mmsg_hdr_[i].msg_hdr);
if (!IsInitializedAddress(server_ip)) {
LOG(DFATAL) << "Unable to get server address.";
continue;
}
QuicEncryptedPacket packet(reinterpret_cast<char*>(iov_[i].iov_base),
mmsg_hdr_[i].msg_len, false);
IPEndPoint server_address(server_ip, port);
processor->ProcessPacket(server_address, client_address, packet);
}
if (packets_dropped != nullptr) {
QuicSocketUtils::GetOverflowFromMsghdr(&mmsg_hdr_[0].msg_hdr,
packets_dropped);
}
if (FLAGS_quic_read_packets_full_recvmmsg) {
// We may not have read all of the packets available on the socket.
return packets_read == kNumPacketsPerReadMmsgCall;
} else {
return true;
}
#else
LOG(FATAL) << "Unsupported";
return false;
#endif
}
/* static */
bool QuicPacketReader::ReadAndDispatchSinglePacket(
int fd,
int port,
ProcessPacketInterface* processor,
QuicPacketCount* packets_dropped) {
// Allocate some extra space so we can send an error if the packet is larger
// than kMaxPacketSize.
char buf[2 * kMaxPacketSize];
IPEndPoint client_address;
IPAddressNumber server_ip;
int bytes_read = QuicSocketUtils::ReadPacket(
fd, buf, arraysize(buf), packets_dropped, &server_ip, &client_address);
if (bytes_read < 0) {
return false; // ReadPacket failed.
}
QuicEncryptedPacket packet(buf, bytes_read, false);
IPEndPoint server_address(server_ip, port);
processor->ProcessPacket(server_address, client_address, packet);
// The socket read was successful, so return true even if packet dispatch
// failed.
return true;
}
} // namespace tools
} // namespace net
| Bysmyyr/chromium-crosswalk | net/tools/quic/quic_packet_reader.cc | C++ | bsd-3-clause | 4,147 |
/*
* Copyright (c) 2009 tarchan. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY TARCHAN ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
* EVENT SHALL TARCHAN OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* The views and conclusions contained in the software and documentation are
* those of the authors and should not be interpreted as representing official
* policies, either expressed or implied, of tarchan.
*/
package com.mac.tarchan.nanika.shell;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JPanel;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* NanikaScope
*
* @author tarchan
*/
public class NanikaCanvas extends JPanel
{
/** シリアルバージョンID */
private static final long serialVersionUID = -8122309255321836447L;
/** ログ */
private static final Log log = LogFactory.getLog(NanikaCanvas.class);
/** シェル */
protected NanikaShell shell;
/** サーフェス */
protected NanikaSurface surface;
/**
* シェルを設定します。
*
* @param shell シェル
*/
public void setShell(NanikaShell shell)
{
this.shell = shell;
}
/**
* 指定された ID のサーフェスに切り替えます。
*
* @param id サーフェス ID
*/
public void setSurface(String id)
{
log.debug("id=" + id);
surface = shell.getSurface(id);
if (surface != null)
{
setSize(surface.getSize());
// if (surface.isAnimations())
// for (SerikoAnimation animation : surface.getAnimations())
// {
//// new SerikoTimer(90, new ActionListener()
// new SerikoTimer(animation, new ActionListener()
// {
// @Override
// public void actionPerformed(ActionEvent e)
// {
// if (log.isTraceEnabled()) log.debug("repaint=" + surface.getID());
// repaint();
// }
// }).start();
// }
}
}
/**
* @see javax.swing.JComponent#getPreferredSize()
*/
@Override
public Dimension getPreferredSize()
{
return surface != null ? surface.getSize() : null;
}
/**
* @see javax.swing.JComponent#getMaximumSize()
*/
@Override
public Dimension getMaximumSize()
{
return getPreferredSize();
}
/**
* @see javax.swing.JComponent#getMinimumSize()
*/
@Override
public Dimension getMinimumSize()
{
return getPreferredSize();
}
/**
* @see javax.swing.JComponent#paintComponent(java.awt.Graphics)
*/
@Override
protected void paintComponent(Graphics g)
// public void paint(Graphics g)
{
if (surface == null) return;
// g.clearRect(0, 0, getWidth(), getHeight());
if (surface != null) surface.draw((Graphics2D)g);
// new Thread(new Runnable()
// {
// @Override
// public void run()
// {
// try
// {
// if (log.isTraceEnabled()) log.debug("sleep");
// Thread.sleep(90);
// if (log.isTraceEnabled()) log.debug("wakeup");
//// repaint(90);
//// invalidate();
//// validate();
// repaint();
// }
// catch (InterruptedException x)
// {
// // 何もしない
// }
// }
// }).start();
}
/** {@inheritDoc} */
@Override
public String toString()
{
StringBuilder buf = new StringBuilder(super.toString());
buf.append("[");
buf.append("surface=");
buf.append(surface);
buf.append("]");
return buf.toString();
}
}
| tarchan/NanikaKit | src/com/mac/tarchan/nanika/shell/NanikaCanvas.java | Java | bsd-3-clause | 4,436 |
<?php
namespace User\Forms;
use Zend\Form\Form;
use User\Filter\UserFilter;
class UserForm extends Form
{
protected $_userId;
protected $_prioArray;
protected $_statausArray;
/*
* getter and setter
*/
public function __construct($name = null)
{
parent::__construct('add');
$inputFilter = new UserFilter();
$this->setInputFilter($inputFilter);
$this->setAttribute('method', 'post');
$this->add(array(
'name' => 'firstname',
'attributes' => array(
'type' => 'text',
),
'options' => array(
'label' => 'Name',
),
));
$this->add(array(
'name' => 'lastname',
'attributes' => array(
'type' => 'text',
),
'options' => array(
'label' => 'Nachname',
),
));
$this->add(array(
'name' => 'email',
'attributes' => array(
'type' => 'text',
),
'options' => array(
'label' => 'Email',
),
));
$this->add(array(
'name' => 'password',
'attributes' => array(
'type' => 'password',
),
'options' => array(
'label' => 'Passwort',
),
));
$this->add(array(
'name' => 'submit',
'attributes' => array(
'type' => 'submit',
'value' => 'login',
'id' => 'submitbutton'
),
));
}
}
| roxmox/pmts | module/User/src/User/Forms/UserForm.php | PHP | bsd-3-clause | 1,766 |
// Package customsearch provides access to the CustomSearch API.
//
// See https://developers.google.com/custom-search/v1/using_rest
//
// Usage example:
//
// import "google.golang.org/api/customsearch/v1"
// ...
// customsearchService, err := customsearch.New(oauthHttpClient)
package customsearch // import "google.golang.org/api/customsearch/v1"
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"golang.org/x/net/context"
"golang.org/x/net/context/ctxhttp"
"google.golang.org/api/googleapi"
"google.golang.org/api/internal"
"io"
"net/http"
"net/url"
"strconv"
"strings"
)
// Always reference these packages, just in case the auto-generated code
// below doesn't.
var _ = bytes.NewBuffer
var _ = strconv.Itoa
var _ = fmt.Sprintf
var _ = json.NewDecoder
var _ = io.Copy
var _ = url.Parse
var _ = googleapi.Version
var _ = errors.New
var _ = strings.Replace
var _ = internal.MarshalJSON
const apiId = "customsearch:v1"
const apiName = "customsearch"
const apiVersion = "v1"
const basePath = "https://www.googleapis.com/customsearch/"
func New(client *http.Client) (*Service, error) {
if client == nil {
return nil, errors.New("client is nil")
}
s := &Service{client: client, BasePath: basePath}
s.Cse = NewCseService(s)
return s, nil
}
type Service struct {
client *http.Client
BasePath string // API endpoint base URL
UserAgent string // optional additional User-Agent fragment
Cse *CseService
}
func (s *Service) userAgent() string {
if s.UserAgent == "" {
return googleapi.UserAgent
}
return googleapi.UserAgent + " " + s.UserAgent
}
func NewCseService(s *Service) *CseService {
rs := &CseService{s: s}
return rs
}
type CseService struct {
s *Service
}
type Context struct {
Facets [][]*ContextFacetsItem `json:"facets,omitempty"`
Title string `json:"title,omitempty"`
// ForceSendFields is a list of field names (e.g. "Facets") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
}
func (s *Context) MarshalJSON() ([]byte, error) {
type noMethod Context
raw := noMethod(*s)
return internal.MarshalJSON(raw, s.ForceSendFields)
}
type ContextFacetsItem struct {
Anchor string `json:"anchor,omitempty"`
Label string `json:"label,omitempty"`
LabelWithOp string `json:"label_with_op,omitempty"`
// ForceSendFields is a list of field names (e.g. "Anchor") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
}
func (s *ContextFacetsItem) MarshalJSON() ([]byte, error) {
type noMethod ContextFacetsItem
raw := noMethod(*s)
return internal.MarshalJSON(raw, s.ForceSendFields)
}
type Promotion struct {
BodyLines []*PromotionBodyLines `json:"bodyLines,omitempty"`
DisplayLink string `json:"displayLink,omitempty"`
HtmlTitle string `json:"htmlTitle,omitempty"`
Image *PromotionImage `json:"image,omitempty"`
Link string `json:"link,omitempty"`
Title string `json:"title,omitempty"`
// ForceSendFields is a list of field names (e.g. "BodyLines") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
}
func (s *Promotion) MarshalJSON() ([]byte, error) {
type noMethod Promotion
raw := noMethod(*s)
return internal.MarshalJSON(raw, s.ForceSendFields)
}
type PromotionBodyLines struct {
HtmlTitle string `json:"htmlTitle,omitempty"`
Link string `json:"link,omitempty"`
Title string `json:"title,omitempty"`
Url string `json:"url,omitempty"`
// ForceSendFields is a list of field names (e.g. "HtmlTitle") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
}
func (s *PromotionBodyLines) MarshalJSON() ([]byte, error) {
type noMethod PromotionBodyLines
raw := noMethod(*s)
return internal.MarshalJSON(raw, s.ForceSendFields)
}
type PromotionImage struct {
Height int64 `json:"height,omitempty"`
Source string `json:"source,omitempty"`
Width int64 `json:"width,omitempty"`
// ForceSendFields is a list of field names (e.g. "Height") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
}
func (s *PromotionImage) MarshalJSON() ([]byte, error) {
type noMethod PromotionImage
raw := noMethod(*s)
return internal.MarshalJSON(raw, s.ForceSendFields)
}
type Query struct {
Count int64 `json:"count,omitempty"`
Cr string `json:"cr,omitempty"`
Cref string `json:"cref,omitempty"`
Cx string `json:"cx,omitempty"`
DateRestrict string `json:"dateRestrict,omitempty"`
DisableCnTwTranslation string `json:"disableCnTwTranslation,omitempty"`
ExactTerms string `json:"exactTerms,omitempty"`
ExcludeTerms string `json:"excludeTerms,omitempty"`
FileType string `json:"fileType,omitempty"`
Filter string `json:"filter,omitempty"`
Gl string `json:"gl,omitempty"`
GoogleHost string `json:"googleHost,omitempty"`
HighRange string `json:"highRange,omitempty"`
Hl string `json:"hl,omitempty"`
Hq string `json:"hq,omitempty"`
ImgColorType string `json:"imgColorType,omitempty"`
ImgDominantColor string `json:"imgDominantColor,omitempty"`
ImgSize string `json:"imgSize,omitempty"`
ImgType string `json:"imgType,omitempty"`
InputEncoding string `json:"inputEncoding,omitempty"`
Language string `json:"language,omitempty"`
LinkSite string `json:"linkSite,omitempty"`
LowRange string `json:"lowRange,omitempty"`
OrTerms string `json:"orTerms,omitempty"`
OutputEncoding string `json:"outputEncoding,omitempty"`
RelatedSite string `json:"relatedSite,omitempty"`
Rights string `json:"rights,omitempty"`
Safe string `json:"safe,omitempty"`
SearchTerms string `json:"searchTerms,omitempty"`
SearchType string `json:"searchType,omitempty"`
SiteSearch string `json:"siteSearch,omitempty"`
SiteSearchFilter string `json:"siteSearchFilter,omitempty"`
Sort string `json:"sort,omitempty"`
StartIndex int64 `json:"startIndex,omitempty"`
StartPage int64 `json:"startPage,omitempty"`
Title string `json:"title,omitempty"`
TotalResults int64 `json:"totalResults,omitempty,string"`
// ForceSendFields is a list of field names (e.g. "Count") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
}
func (s *Query) MarshalJSON() ([]byte, error) {
type noMethod Query
raw := noMethod(*s)
return internal.MarshalJSON(raw, s.ForceSendFields)
}
type Result struct {
CacheId string `json:"cacheId,omitempty"`
DisplayLink string `json:"displayLink,omitempty"`
FileFormat string `json:"fileFormat,omitempty"`
FormattedUrl string `json:"formattedUrl,omitempty"`
HtmlFormattedUrl string `json:"htmlFormattedUrl,omitempty"`
HtmlSnippet string `json:"htmlSnippet,omitempty"`
HtmlTitle string `json:"htmlTitle,omitempty"`
Image *ResultImage `json:"image,omitempty"`
Kind string `json:"kind,omitempty"`
Labels []*ResultLabels `json:"labels,omitempty"`
Link string `json:"link,omitempty"`
Mime string `json:"mime,omitempty"`
Pagemap *ResultPagemap `json:"pagemap,omitempty"`
Snippet string `json:"snippet,omitempty"`
Title string `json:"title,omitempty"`
// ForceSendFields is a list of field names (e.g. "CacheId") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
}
func (s *Result) MarshalJSON() ([]byte, error) {
type noMethod Result
raw := noMethod(*s)
return internal.MarshalJSON(raw, s.ForceSendFields)
}
type ResultImage struct {
ByteSize int64 `json:"byteSize,omitempty"`
ContextLink string `json:"contextLink,omitempty"`
Height int64 `json:"height,omitempty"`
ThumbnailHeight int64 `json:"thumbnailHeight,omitempty"`
ThumbnailLink string `json:"thumbnailLink,omitempty"`
ThumbnailWidth int64 `json:"thumbnailWidth,omitempty"`
Width int64 `json:"width,omitempty"`
// ForceSendFields is a list of field names (e.g. "ByteSize") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
}
func (s *ResultImage) MarshalJSON() ([]byte, error) {
type noMethod ResultImage
raw := noMethod(*s)
return internal.MarshalJSON(raw, s.ForceSendFields)
}
type ResultLabels struct {
DisplayName string `json:"displayName,omitempty"`
LabelWithOp string `json:"label_with_op,omitempty"`
Name string `json:"name,omitempty"`
// ForceSendFields is a list of field names (e.g. "DisplayName") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
}
func (s *ResultLabels) MarshalJSON() ([]byte, error) {
type noMethod ResultLabels
raw := noMethod(*s)
return internal.MarshalJSON(raw, s.ForceSendFields)
}
type ResultPagemap struct {
}
type Search struct {
Context *Context `json:"context,omitempty"`
Items []*Result `json:"items,omitempty"`
Kind string `json:"kind,omitempty"`
Promotions []*Promotion `json:"promotions,omitempty"`
Queries map[string][]Query `json:"queries,omitempty"`
SearchInformation *SearchSearchInformation `json:"searchInformation,omitempty"`
Spelling *SearchSpelling `json:"spelling,omitempty"`
Url *SearchUrl `json:"url,omitempty"`
// ServerResponse contains the HTTP response code and headers from the
// server.
googleapi.ServerResponse `json:"-"`
// ForceSendFields is a list of field names (e.g. "Context") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
}
func (s *Search) MarshalJSON() ([]byte, error) {
type noMethod Search
raw := noMethod(*s)
return internal.MarshalJSON(raw, s.ForceSendFields)
}
type SearchSearchInformation struct {
FormattedSearchTime string `json:"formattedSearchTime,omitempty"`
FormattedTotalResults string `json:"formattedTotalResults,omitempty"`
SearchTime float64 `json:"searchTime,omitempty"`
TotalResults int64 `json:"totalResults,omitempty,string"`
// ForceSendFields is a list of field names (e.g. "FormattedSearchTime")
// to unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
}
func (s *SearchSearchInformation) MarshalJSON() ([]byte, error) {
type noMethod SearchSearchInformation
raw := noMethod(*s)
return internal.MarshalJSON(raw, s.ForceSendFields)
}
type SearchSpelling struct {
CorrectedQuery string `json:"correctedQuery,omitempty"`
HtmlCorrectedQuery string `json:"htmlCorrectedQuery,omitempty"`
// ForceSendFields is a list of field names (e.g. "CorrectedQuery") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
}
func (s *SearchSpelling) MarshalJSON() ([]byte, error) {
type noMethod SearchSpelling
raw := noMethod(*s)
return internal.MarshalJSON(raw, s.ForceSendFields)
}
type SearchUrl struct {
Template string `json:"template,omitempty"`
Type string `json:"type,omitempty"`
// ForceSendFields is a list of field names (e.g. "Template") to
// unconditionally include in API requests. By default, fields with
// empty values are omitted from API requests. However, any non-pointer,
// non-interface field appearing in ForceSendFields will be sent to the
// server regardless of whether the field is empty or not. This may be
// used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
}
func (s *SearchUrl) MarshalJSON() ([]byte, error) {
type noMethod SearchUrl
raw := noMethod(*s)
return internal.MarshalJSON(raw, s.ForceSendFields)
}
// method id "search.cse.list":
type CseListCall struct {
s *Service
q string
opt_ map[string]interface{}
ctx_ context.Context
}
// List: Returns metadata about the search performed, metadata about the
// custom search engine used for the search, and the search results.
func (r *CseService) List(q string) *CseListCall {
c := &CseListCall{s: r.s, opt_: make(map[string]interface{})}
c.q = q
return c
}
// C2coff sets the optional parameter "c2coff": Turns off the
// translation between zh-CN and zh-TW.
func (c *CseListCall) C2coff(c2coff string) *CseListCall {
c.opt_["c2coff"] = c2coff
return c
}
// Cr sets the optional parameter "cr": Country restrict(s).
func (c *CseListCall) Cr(cr string) *CseListCall {
c.opt_["cr"] = cr
return c
}
// Cref sets the optional parameter "cref": The URL of a linked custom
// search engine
func (c *CseListCall) Cref(cref string) *CseListCall {
c.opt_["cref"] = cref
return c
}
// Cx sets the optional parameter "cx": The custom search engine ID to
// scope this search query
func (c *CseListCall) Cx(cx string) *CseListCall {
c.opt_["cx"] = cx
return c
}
// DateRestrict sets the optional parameter "dateRestrict": Specifies
// all search results are from a time period
func (c *CseListCall) DateRestrict(dateRestrict string) *CseListCall {
c.opt_["dateRestrict"] = dateRestrict
return c
}
// ExactTerms sets the optional parameter "exactTerms": Identifies a
// phrase that all documents in the search results must contain
func (c *CseListCall) ExactTerms(exactTerms string) *CseListCall {
c.opt_["exactTerms"] = exactTerms
return c
}
// ExcludeTerms sets the optional parameter "excludeTerms": Identifies a
// word or phrase that should not appear in any documents in the search
// results
func (c *CseListCall) ExcludeTerms(excludeTerms string) *CseListCall {
c.opt_["excludeTerms"] = excludeTerms
return c
}
// FileType sets the optional parameter "fileType": Returns images of a
// specified type. Some of the allowed values are: bmp, gif, png, jpg,
// svg, pdf, ...
func (c *CseListCall) FileType(fileType string) *CseListCall {
c.opt_["fileType"] = fileType
return c
}
// Filter sets the optional parameter "filter": Controls turning on or
// off the duplicate content filter.
//
// Possible values:
// "0" - Turns off duplicate content filter.
// "1" - Turns on duplicate content filter.
func (c *CseListCall) Filter(filter string) *CseListCall {
c.opt_["filter"] = filter
return c
}
// Gl sets the optional parameter "gl": Geolocation of end user.
func (c *CseListCall) Gl(gl string) *CseListCall {
c.opt_["gl"] = gl
return c
}
// Googlehost sets the optional parameter "googlehost": The local Google
// domain to use to perform the search.
func (c *CseListCall) Googlehost(googlehost string) *CseListCall {
c.opt_["googlehost"] = googlehost
return c
}
// HighRange sets the optional parameter "highRange": Creates a range in
// form as_nlo value..as_nhi value and attempts to append it to query
func (c *CseListCall) HighRange(highRange string) *CseListCall {
c.opt_["highRange"] = highRange
return c
}
// Hl sets the optional parameter "hl": Sets the user interface
// language.
func (c *CseListCall) Hl(hl string) *CseListCall {
c.opt_["hl"] = hl
return c
}
// Hq sets the optional parameter "hq": Appends the extra query terms to
// the query.
func (c *CseListCall) Hq(hq string) *CseListCall {
c.opt_["hq"] = hq
return c
}
// ImgColorType sets the optional parameter "imgColorType": Returns
// black and white, grayscale, or color images: mono, gray, and color.
//
// Possible values:
// "color" - color
// "gray" - gray
// "mono" - mono
func (c *CseListCall) ImgColorType(imgColorType string) *CseListCall {
c.opt_["imgColorType"] = imgColorType
return c
}
// ImgDominantColor sets the optional parameter "imgDominantColor":
// Returns images of a specific dominant color: yellow, green, teal,
// blue, purple, pink, white, gray, black and brown.
//
// Possible values:
// "black" - black
// "blue" - blue
// "brown" - brown
// "gray" - gray
// "green" - green
// "pink" - pink
// "purple" - purple
// "teal" - teal
// "white" - white
// "yellow" - yellow
func (c *CseListCall) ImgDominantColor(imgDominantColor string) *CseListCall {
c.opt_["imgDominantColor"] = imgDominantColor
return c
}
// ImgSize sets the optional parameter "imgSize": Returns images of a
// specified size, where size can be one of: icon, small, medium, large,
// xlarge, xxlarge, and huge.
//
// Possible values:
// "huge" - huge
// "icon" - icon
// "large" - large
// "medium" - medium
// "small" - small
// "xlarge" - xlarge
// "xxlarge" - xxlarge
func (c *CseListCall) ImgSize(imgSize string) *CseListCall {
c.opt_["imgSize"] = imgSize
return c
}
// ImgType sets the optional parameter "imgType": Returns images of a
// type, which can be one of: clipart, face, lineart, news, and photo.
//
// Possible values:
// "clipart" - clipart
// "face" - face
// "lineart" - lineart
// "news" - news
// "photo" - photo
func (c *CseListCall) ImgType(imgType string) *CseListCall {
c.opt_["imgType"] = imgType
return c
}
// LinkSite sets the optional parameter "linkSite": Specifies that all
// search results should contain a link to a particular URL
func (c *CseListCall) LinkSite(linkSite string) *CseListCall {
c.opt_["linkSite"] = linkSite
return c
}
// LowRange sets the optional parameter "lowRange": Creates a range in
// form as_nlo value..as_nhi value and attempts to append it to query
func (c *CseListCall) LowRange(lowRange string) *CseListCall {
c.opt_["lowRange"] = lowRange
return c
}
// Lr sets the optional parameter "lr": The language restriction for the
// search results
//
// Possible values:
// "lang_ar" - Arabic
// "lang_bg" - Bulgarian
// "lang_ca" - Catalan
// "lang_cs" - Czech
// "lang_da" - Danish
// "lang_de" - German
// "lang_el" - Greek
// "lang_en" - English
// "lang_es" - Spanish
// "lang_et" - Estonian
// "lang_fi" - Finnish
// "lang_fr" - French
// "lang_hr" - Croatian
// "lang_hu" - Hungarian
// "lang_id" - Indonesian
// "lang_is" - Icelandic
// "lang_it" - Italian
// "lang_iw" - Hebrew
// "lang_ja" - Japanese
// "lang_ko" - Korean
// "lang_lt" - Lithuanian
// "lang_lv" - Latvian
// "lang_nl" - Dutch
// "lang_no" - Norwegian
// "lang_pl" - Polish
// "lang_pt" - Portuguese
// "lang_ro" - Romanian
// "lang_ru" - Russian
// "lang_sk" - Slovak
// "lang_sl" - Slovenian
// "lang_sr" - Serbian
// "lang_sv" - Swedish
// "lang_tr" - Turkish
// "lang_zh-CN" - Chinese (Simplified)
// "lang_zh-TW" - Chinese (Traditional)
func (c *CseListCall) Lr(lr string) *CseListCall {
c.opt_["lr"] = lr
return c
}
// Num sets the optional parameter "num": Number of search results to
// return
func (c *CseListCall) Num(num int64) *CseListCall {
c.opt_["num"] = num
return c
}
// OrTerms sets the optional parameter "orTerms": Provides additional
// search terms to check for in a document, where each document in the
// search results must contain at least one of the additional search
// terms
func (c *CseListCall) OrTerms(orTerms string) *CseListCall {
c.opt_["orTerms"] = orTerms
return c
}
// RelatedSite sets the optional parameter "relatedSite": Specifies that
// all search results should be pages that are related to the specified
// URL
func (c *CseListCall) RelatedSite(relatedSite string) *CseListCall {
c.opt_["relatedSite"] = relatedSite
return c
}
// Rights sets the optional parameter "rights": Filters based on
// licensing. Supported values include: cc_publicdomain, cc_attribute,
// cc_sharealike, cc_noncommercial, cc_nonderived and combinations of
// these.
func (c *CseListCall) Rights(rights string) *CseListCall {
c.opt_["rights"] = rights
return c
}
// Safe sets the optional parameter "safe": Search safety level
//
// Possible values:
// "high" - Enables highest level of safe search filtering.
// "medium" - Enables moderate safe search filtering.
// "off" (default) - Disables safe search filtering.
func (c *CseListCall) Safe(safe string) *CseListCall {
c.opt_["safe"] = safe
return c
}
// SearchType sets the optional parameter "searchType": Specifies the
// search type: image.
//
// Possible values:
// "image" - custom image search
func (c *CseListCall) SearchType(searchType string) *CseListCall {
c.opt_["searchType"] = searchType
return c
}
// SiteSearch sets the optional parameter "siteSearch": Specifies all
// search results should be pages from a given site
func (c *CseListCall) SiteSearch(siteSearch string) *CseListCall {
c.opt_["siteSearch"] = siteSearch
return c
}
// SiteSearchFilter sets the optional parameter "siteSearchFilter":
// Controls whether to include or exclude results from the site named in
// the as_sitesearch parameter
//
// Possible values:
// "e" - exclude
// "i" - include
func (c *CseListCall) SiteSearchFilter(siteSearchFilter string) *CseListCall {
c.opt_["siteSearchFilter"] = siteSearchFilter
return c
}
// Sort sets the optional parameter "sort": The sort expression to apply
// to the results
func (c *CseListCall) Sort(sort string) *CseListCall {
c.opt_["sort"] = sort
return c
}
// Start sets the optional parameter "start": The index of the first
// result to return
func (c *CseListCall) Start(start int64) *CseListCall {
c.opt_["start"] = start
return c
}
// Fields allows partial responses to be retrieved.
// See https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *CseListCall) Fields(s ...googleapi.Field) *CseListCall {
c.opt_["fields"] = googleapi.CombineFields(s)
return c
}
// IfNoneMatch sets the optional parameter which makes the operation
// fail if the object's ETag matches the given value. This is useful for
// getting updates only after the object has changed since the last
// request. Use googleapi.IsNotModified to check whether the response
// error from Do is the result of In-None-Match.
func (c *CseListCall) IfNoneMatch(entityTag string) *CseListCall {
c.opt_["ifNoneMatch"] = entityTag
return c
}
// Context sets the context to be used in this call's Do method.
// Any pending HTTP request will be aborted if the provided context
// is canceled.
func (c *CseListCall) Context(ctx context.Context) *CseListCall {
c.ctx_ = ctx
return c
}
func (c *CseListCall) doRequest(alt string) (*http.Response, error) {
var body io.Reader = nil
params := make(url.Values)
params.Set("alt", alt)
params.Set("q", fmt.Sprintf("%v", c.q))
if v, ok := c.opt_["c2coff"]; ok {
params.Set("c2coff", fmt.Sprintf("%v", v))
}
if v, ok := c.opt_["cr"]; ok {
params.Set("cr", fmt.Sprintf("%v", v))
}
if v, ok := c.opt_["cref"]; ok {
params.Set("cref", fmt.Sprintf("%v", v))
}
if v, ok := c.opt_["cx"]; ok {
params.Set("cx", fmt.Sprintf("%v", v))
}
if v, ok := c.opt_["dateRestrict"]; ok {
params.Set("dateRestrict", fmt.Sprintf("%v", v))
}
if v, ok := c.opt_["exactTerms"]; ok {
params.Set("exactTerms", fmt.Sprintf("%v", v))
}
if v, ok := c.opt_["excludeTerms"]; ok {
params.Set("excludeTerms", fmt.Sprintf("%v", v))
}
if v, ok := c.opt_["fileType"]; ok {
params.Set("fileType", fmt.Sprintf("%v", v))
}
if v, ok := c.opt_["filter"]; ok {
params.Set("filter", fmt.Sprintf("%v", v))
}
if v, ok := c.opt_["gl"]; ok {
params.Set("gl", fmt.Sprintf("%v", v))
}
if v, ok := c.opt_["googlehost"]; ok {
params.Set("googlehost", fmt.Sprintf("%v", v))
}
if v, ok := c.opt_["highRange"]; ok {
params.Set("highRange", fmt.Sprintf("%v", v))
}
if v, ok := c.opt_["hl"]; ok {
params.Set("hl", fmt.Sprintf("%v", v))
}
if v, ok := c.opt_["hq"]; ok {
params.Set("hq", fmt.Sprintf("%v", v))
}
if v, ok := c.opt_["imgColorType"]; ok {
params.Set("imgColorType", fmt.Sprintf("%v", v))
}
if v, ok := c.opt_["imgDominantColor"]; ok {
params.Set("imgDominantColor", fmt.Sprintf("%v", v))
}
if v, ok := c.opt_["imgSize"]; ok {
params.Set("imgSize", fmt.Sprintf("%v", v))
}
if v, ok := c.opt_["imgType"]; ok {
params.Set("imgType", fmt.Sprintf("%v", v))
}
if v, ok := c.opt_["linkSite"]; ok {
params.Set("linkSite", fmt.Sprintf("%v", v))
}
if v, ok := c.opt_["lowRange"]; ok {
params.Set("lowRange", fmt.Sprintf("%v", v))
}
if v, ok := c.opt_["lr"]; ok {
params.Set("lr", fmt.Sprintf("%v", v))
}
if v, ok := c.opt_["num"]; ok {
params.Set("num", fmt.Sprintf("%v", v))
}
if v, ok := c.opt_["orTerms"]; ok {
params.Set("orTerms", fmt.Sprintf("%v", v))
}
if v, ok := c.opt_["relatedSite"]; ok {
params.Set("relatedSite", fmt.Sprintf("%v", v))
}
if v, ok := c.opt_["rights"]; ok {
params.Set("rights", fmt.Sprintf("%v", v))
}
if v, ok := c.opt_["safe"]; ok {
params.Set("safe", fmt.Sprintf("%v", v))
}
if v, ok := c.opt_["searchType"]; ok {
params.Set("searchType", fmt.Sprintf("%v", v))
}
if v, ok := c.opt_["siteSearch"]; ok {
params.Set("siteSearch", fmt.Sprintf("%v", v))
}
if v, ok := c.opt_["siteSearchFilter"]; ok {
params.Set("siteSearchFilter", fmt.Sprintf("%v", v))
}
if v, ok := c.opt_["sort"]; ok {
params.Set("sort", fmt.Sprintf("%v", v))
}
if v, ok := c.opt_["start"]; ok {
params.Set("start", fmt.Sprintf("%v", v))
}
if v, ok := c.opt_["fields"]; ok {
params.Set("fields", fmt.Sprintf("%v", v))
}
urls := googleapi.ResolveRelative(c.s.BasePath, "v1")
urls += "?" + params.Encode()
req, _ := http.NewRequest("GET", urls, body)
googleapi.SetOpaque(req.URL)
req.Header.Set("User-Agent", c.s.userAgent())
if v, ok := c.opt_["ifNoneMatch"]; ok {
req.Header.Set("If-None-Match", fmt.Sprintf("%v", v))
}
if c.ctx_ != nil {
return ctxhttp.Do(c.ctx_, c.s.client, req)
}
return c.s.client.Do(req)
}
// Do executes the "search.cse.list" call.
// Exactly one of *Search or error will be non-nil. Any non-2xx status
// code is an error. Response headers are in either
// *Search.ServerResponse.Header or (if a response was returned at all)
// in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to
// check whether the returned error was because http.StatusNotModified
// was returned.
func (c *CseListCall) Do() (*Search, error) {
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &Search{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
if err := json.NewDecoder(res.Body).Decode(&ret); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Returns metadata about the search performed, metadata about the custom search engine used for the search, and the search results.",
// "httpMethod": "GET",
// "id": "search.cse.list",
// "parameterOrder": [
// "q"
// ],
// "parameters": {
// "c2coff": {
// "description": "Turns off the translation between zh-CN and zh-TW.",
// "location": "query",
// "type": "string"
// },
// "cr": {
// "description": "Country restrict(s).",
// "location": "query",
// "type": "string"
// },
// "cref": {
// "description": "The URL of a linked custom search engine",
// "location": "query",
// "type": "string"
// },
// "cx": {
// "description": "The custom search engine ID to scope this search query",
// "location": "query",
// "type": "string"
// },
// "dateRestrict": {
// "description": "Specifies all search results are from a time period",
// "location": "query",
// "type": "string"
// },
// "exactTerms": {
// "description": "Identifies a phrase that all documents in the search results must contain",
// "location": "query",
// "type": "string"
// },
// "excludeTerms": {
// "description": "Identifies a word or phrase that should not appear in any documents in the search results",
// "location": "query",
// "type": "string"
// },
// "fileType": {
// "description": "Returns images of a specified type. Some of the allowed values are: bmp, gif, png, jpg, svg, pdf, ...",
// "location": "query",
// "type": "string"
// },
// "filter": {
// "description": "Controls turning on or off the duplicate content filter.",
// "enum": [
// "0",
// "1"
// ],
// "enumDescriptions": [
// "Turns off duplicate content filter.",
// "Turns on duplicate content filter."
// ],
// "location": "query",
// "type": "string"
// },
// "gl": {
// "description": "Geolocation of end user.",
// "location": "query",
// "type": "string"
// },
// "googlehost": {
// "description": "The local Google domain to use to perform the search.",
// "location": "query",
// "type": "string"
// },
// "highRange": {
// "description": "Creates a range in form as_nlo value..as_nhi value and attempts to append it to query",
// "location": "query",
// "type": "string"
// },
// "hl": {
// "description": "Sets the user interface language.",
// "location": "query",
// "type": "string"
// },
// "hq": {
// "description": "Appends the extra query terms to the query.",
// "location": "query",
// "type": "string"
// },
// "imgColorType": {
// "description": "Returns black and white, grayscale, or color images: mono, gray, and color.",
// "enum": [
// "color",
// "gray",
// "mono"
// ],
// "enumDescriptions": [
// "color",
// "gray",
// "mono"
// ],
// "location": "query",
// "type": "string"
// },
// "imgDominantColor": {
// "description": "Returns images of a specific dominant color: yellow, green, teal, blue, purple, pink, white, gray, black and brown.",
// "enum": [
// "black",
// "blue",
// "brown",
// "gray",
// "green",
// "pink",
// "purple",
// "teal",
// "white",
// "yellow"
// ],
// "enumDescriptions": [
// "black",
// "blue",
// "brown",
// "gray",
// "green",
// "pink",
// "purple",
// "teal",
// "white",
// "yellow"
// ],
// "location": "query",
// "type": "string"
// },
// "imgSize": {
// "description": "Returns images of a specified size, where size can be one of: icon, small, medium, large, xlarge, xxlarge, and huge.",
// "enum": [
// "huge",
// "icon",
// "large",
// "medium",
// "small",
// "xlarge",
// "xxlarge"
// ],
// "enumDescriptions": [
// "huge",
// "icon",
// "large",
// "medium",
// "small",
// "xlarge",
// "xxlarge"
// ],
// "location": "query",
// "type": "string"
// },
// "imgType": {
// "description": "Returns images of a type, which can be one of: clipart, face, lineart, news, and photo.",
// "enum": [
// "clipart",
// "face",
// "lineart",
// "news",
// "photo"
// ],
// "enumDescriptions": [
// "clipart",
// "face",
// "lineart",
// "news",
// "photo"
// ],
// "location": "query",
// "type": "string"
// },
// "linkSite": {
// "description": "Specifies that all search results should contain a link to a particular URL",
// "location": "query",
// "type": "string"
// },
// "lowRange": {
// "description": "Creates a range in form as_nlo value..as_nhi value and attempts to append it to query",
// "location": "query",
// "type": "string"
// },
// "lr": {
// "description": "The language restriction for the search results",
// "enum": [
// "lang_ar",
// "lang_bg",
// "lang_ca",
// "lang_cs",
// "lang_da",
// "lang_de",
// "lang_el",
// "lang_en",
// "lang_es",
// "lang_et",
// "lang_fi",
// "lang_fr",
// "lang_hr",
// "lang_hu",
// "lang_id",
// "lang_is",
// "lang_it",
// "lang_iw",
// "lang_ja",
// "lang_ko",
// "lang_lt",
// "lang_lv",
// "lang_nl",
// "lang_no",
// "lang_pl",
// "lang_pt",
// "lang_ro",
// "lang_ru",
// "lang_sk",
// "lang_sl",
// "lang_sr",
// "lang_sv",
// "lang_tr",
// "lang_zh-CN",
// "lang_zh-TW"
// ],
// "enumDescriptions": [
// "Arabic",
// "Bulgarian",
// "Catalan",
// "Czech",
// "Danish",
// "German",
// "Greek",
// "English",
// "Spanish",
// "Estonian",
// "Finnish",
// "French",
// "Croatian",
// "Hungarian",
// "Indonesian",
// "Icelandic",
// "Italian",
// "Hebrew",
// "Japanese",
// "Korean",
// "Lithuanian",
// "Latvian",
// "Dutch",
// "Norwegian",
// "Polish",
// "Portuguese",
// "Romanian",
// "Russian",
// "Slovak",
// "Slovenian",
// "Serbian",
// "Swedish",
// "Turkish",
// "Chinese (Simplified)",
// "Chinese (Traditional)"
// ],
// "location": "query",
// "type": "string"
// },
// "num": {
// "default": "10",
// "description": "Number of search results to return",
// "format": "uint32",
// "location": "query",
// "type": "integer"
// },
// "orTerms": {
// "description": "Provides additional search terms to check for in a document, where each document in the search results must contain at least one of the additional search terms",
// "location": "query",
// "type": "string"
// },
// "q": {
// "description": "Query",
// "location": "query",
// "required": true,
// "type": "string"
// },
// "relatedSite": {
// "description": "Specifies that all search results should be pages that are related to the specified URL",
// "location": "query",
// "type": "string"
// },
// "rights": {
// "description": "Filters based on licensing. Supported values include: cc_publicdomain, cc_attribute, cc_sharealike, cc_noncommercial, cc_nonderived and combinations of these.",
// "location": "query",
// "type": "string"
// },
// "safe": {
// "default": "off",
// "description": "Search safety level",
// "enum": [
// "high",
// "medium",
// "off"
// ],
// "enumDescriptions": [
// "Enables highest level of safe search filtering.",
// "Enables moderate safe search filtering.",
// "Disables safe search filtering."
// ],
// "location": "query",
// "type": "string"
// },
// "searchType": {
// "description": "Specifies the search type: image.",
// "enum": [
// "image"
// ],
// "enumDescriptions": [
// "custom image search"
// ],
// "location": "query",
// "type": "string"
// },
// "siteSearch": {
// "description": "Specifies all search results should be pages from a given site",
// "location": "query",
// "type": "string"
// },
// "siteSearchFilter": {
// "description": "Controls whether to include or exclude results from the site named in the as_sitesearch parameter",
// "enum": [
// "e",
// "i"
// ],
// "enumDescriptions": [
// "exclude",
// "include"
// ],
// "location": "query",
// "type": "string"
// },
// "sort": {
// "description": "The sort expression to apply to the results",
// "location": "query",
// "type": "string"
// },
// "start": {
// "description": "The index of the first result to return",
// "format": "uint32",
// "location": "query",
// "type": "integer"
// }
// },
// "path": "v1",
// "response": {
// "$ref": "Search"
// }
// }
}
| upworthy/oauth2-proxy-buildpack | vendor/src/google.golang.org/api/customsearch/v1/customsearch-gen.go | GO | bsd-3-clause | 39,845 |
# -*- coding: utf-8 -*-
"""
jinja2.filters
~~~~~~~~~~~~~~
Bundled jinja filters.
:copyright: (c) 2010 by the Jinja Team.
:license: BSD, see LICENSE for more details.
"""
import re
import math
from random import choice
from operator import itemgetter
from itertools import groupby
from jinja2.utils import Markup, escape, pformat, urlize, soft_unicode, \
unicode_urlencode
from jinja2.runtime import Undefined
from jinja2.exceptions import FilterArgumentError
from jinja2._compat import imap, string_types, text_type, iteritems
_word_re = re.compile(r'\w+(?u)')
def contextfilter(f):
"""Decorator for marking context dependent filters. The current
:class:`Context` will be passed as first argument.
"""
f.contextfilter = True
return f
def evalcontextfilter(f):
"""Decorator for marking eval-context dependent filters. An eval
context object is passed as first argument. For more information
about the eval context, see :ref:`eval-context`.
.. versionadded:: 2.4
"""
f.evalcontextfilter = True
return f
def environmentfilter(f):
"""Decorator for marking evironment dependent filters. The current
:class:`Environment` is passed to the filter as first argument.
"""
f.environmentfilter = True
return f
def make_attrgetter(environment, attribute):
"""Returns a callable that looks up the given attribute from a
passed object with the rules of the environment. Dots are allowed
to access attributes of attributes. Integer parts in paths are
looked up as integers.
"""
if not isinstance(attribute, string_types) \
or ('.' not in attribute and not attribute.isdigit()):
return lambda x: environment.getitem(x, attribute)
attribute = attribute.split('.')
def attrgetter(item):
for part in attribute:
if part.isdigit():
part = int(part)
item = environment.getitem(item, part)
return item
return attrgetter
def do_forceescape(value):
"""Enforce HTML escaping. This will probably double escape variables."""
if hasattr(value, '__html__'):
value = value.__html__()
return escape(text_type(value))
def do_urlencode(value):
"""Escape strings for use in URLs (uses UTF-8 encoding). It accepts both
dictionaries and regular strings as well as pairwise iterables.
.. versionadded:: 2.7
"""
itemiter = None
if isinstance(value, dict):
itemiter = iteritems(value)
elif not isinstance(value, string_types):
try:
itemiter = iter(value)
except TypeError:
pass
if itemiter is None:
return unicode_urlencode(value)
return u'&'.join(unicode_urlencode(k) + '=' +
unicode_urlencode(v) for k, v in itemiter)
@evalcontextfilter
def do_replace(eval_ctx, s, old, new, count=None):
"""Return a copy of the value with all occurrences of a substring
replaced with a new one. The first argument is the substring
that should be replaced, the second is the replacement string.
If the optional third argument ``count`` is given, only the first
``count`` occurrences are replaced:
.. sourcecode:: jinja
{{ "Hello World"|replace("Hello", "Goodbye") }}
-> Goodbye World
{{ "aaaaargh"|replace("a", "d'oh, ", 2) }}
-> d'oh, d'oh, aaargh
"""
if count is None:
count = -1
if not eval_ctx.autoescape:
return text_type(s).replace(text_type(old), text_type(new), count)
if hasattr(old, '__html__') or hasattr(new, '__html__') and \
not hasattr(s, '__html__'):
s = escape(s)
else:
s = soft_unicode(s)
return s.replace(soft_unicode(old), soft_unicode(new), count)
def do_upper(s):
"""Convert a value to uppercase."""
return soft_unicode(s).upper()
def do_lower(s):
"""Convert a value to lowercase."""
return soft_unicode(s).lower()
@evalcontextfilter
def do_xmlattr(_eval_ctx, d, autospace=True):
"""Create an SGML/XML attribute string based on the items in a dict.
All values that are neither `none` nor `undefined` are automatically
escaped:
.. sourcecode:: html+jinja
<ul{{ {'class': 'my_list', 'missing': none,
'id': 'list-%d'|format(variable)}|xmlattr }}>
...
</ul>
Results in something like this:
.. sourcecode:: html
<ul class="my_list" id="list-42">
...
</ul>
As you can see it automatically prepends a space in front of the item
if the filter returned something unless the second parameter is false.
"""
rv = u' '.join(
u'%s="%s"' % (escape(key), escape(value))
for key, value in iteritems(d)
if value is not None and not isinstance(value, Undefined)
)
if autospace and rv:
rv = u' ' + rv
if _eval_ctx.autoescape:
rv = Markup(rv)
return rv
def do_capitalize(s):
"""Capitalize a value. The first character will be uppercase, all others
lowercase.
"""
return soft_unicode(s).capitalize()
def do_title(s):
"""Return a titlecased version of the value. I.e. words will start with
uppercase letters, all remaining characters are lowercase.
"""
rv = []
for item in re.compile(r'([-\s]+)(?u)').split(soft_unicode(s)):
if not item:
continue
rv.append(item[0].upper() + item[1:].lower())
return ''.join(rv)
def do_dictsort(value, case_sensitive=False, by='key'):
"""Sort a dict and yield (key, value) pairs. Because python dicts are
unsorted you may want to use this function to order them by either
key or value:
.. sourcecode:: jinja
{% for item in mydict|dictsort %}
sort the dict by key, case insensitive
{% for item in mydict|dictsort(true) %}
sort the dict by key, case sensitive
{% for item in mydict|dictsort(false, 'value') %}
sort the dict by value, case insensitive
"""
if by == 'key':
pos = 0
elif by == 'value':
pos = 1
else:
raise FilterArgumentError('You can only sort by either '
'"key" or "value"')
def sort_func(item):
value = item[pos]
if isinstance(value, string_types) and not case_sensitive:
value = value.lower()
return value
return sorted(value.items(), key=sort_func)
@environmentfilter
def do_sort(environment, value, reverse=False, case_sensitive=False,
attribute=None):
"""Sort an iterable. Per default it sorts ascending, if you pass it
true as first argument it will reverse the sorting.
If the iterable is made of strings the third parameter can be used to
control the case sensitiveness of the comparison which is disabled by
default.
.. sourcecode:: jinja
{% for item in iterable|sort %}
...
{% endfor %}
It is also possible to sort by an attribute (for example to sort
by the date of an object) by specifying the `attribute` parameter:
.. sourcecode:: jinja
{% for item in iterable|sort(attribute='date') %}
...
{% endfor %}
.. versionchanged:: 2.6
The `attribute` parameter was added.
"""
if not case_sensitive:
def sort_func(item):
if isinstance(item, string_types):
item = item.lower()
return item
else:
sort_func = None
if attribute is not None:
getter = make_attrgetter(environment, attribute)
def sort_func(item, processor=sort_func or (lambda x: x)):
return processor(getter(item))
return sorted(value, key=sort_func, reverse=reverse)
def do_default(value, default_value=u'', boolean=False):
"""If the value is undefined it will return the passed default value,
otherwise the value of the variable:
.. sourcecode:: jinja
{{ my_variable|default('my_variable is not defined') }}
This will output the value of ``my_variable`` if the variable was
defined, otherwise ``'my_variable is not defined'``. If you want
to use default with variables that evaluate to false you have to
set the second parameter to `true`:
.. sourcecode:: jinja
{{ ''|default('the string was empty', true) }}
"""
if isinstance(value, Undefined) or (boolean and not value):
return default_value
return value
@evalcontextfilter
def do_join(eval_ctx, value, d=u'', attribute=None):
"""Return a string which is the concatenation of the strings in the
sequence. The separator between elements is an empty string per
default, you can define it with the optional parameter:
.. sourcecode:: jinja
{{ [1, 2, 3]|join('|') }}
-> 1|2|3
{{ [1, 2, 3]|join }}
-> 123
It is also possible to join certain attributes of an object:
.. sourcecode:: jinja
{{ users|join(', ', attribute='username') }}
.. versionadded:: 2.6
The `attribute` parameter was added.
"""
if attribute is not None:
value = imap(make_attrgetter(eval_ctx.environment, attribute), value)
# no automatic escaping? joining is a lot eaiser then
if not eval_ctx.autoescape:
return text_type(d).join(imap(text_type, value))
# if the delimiter doesn't have an html representation we check
# if any of the items has. If yes we do a coercion to Markup
if not hasattr(d, '__html__'):
value = list(value)
do_escape = False
for idx, item in enumerate(value):
if hasattr(item, '__html__'):
do_escape = True
else:
value[idx] = text_type(item)
if do_escape:
d = escape(d)
else:
d = text_type(d)
return d.join(value)
# no html involved, to normal joining
return soft_unicode(d).join(imap(soft_unicode, value))
def do_center(value, width=80):
"""Centers the value in a field of a given width."""
return text_type(value).center(width)
@environmentfilter
def do_first(environment, seq):
"""Return the first item of a sequence."""
try:
return next(iter(seq))
except StopIteration:
return environment.undefined('No first item, sequence was empty.')
@environmentfilter
def do_last(environment, seq):
"""Return the last item of a sequence."""
try:
return next(iter(reversed(seq)))
except StopIteration:
return environment.undefined('No last item, sequence was empty.')
@environmentfilter
def do_random(environment, seq):
"""Return a random item from the sequence."""
try:
return choice(seq)
except IndexError:
return environment.undefined('No random item, sequence was empty.')
def do_filesizeformat(value, binary=False):
"""Format the value like a 'human-readable' file size (i.e. 13 kB,
4.1 MB, 102 Bytes, etc). Per default decimal prefixes are used (Mega,
Giga, etc.), if the second parameter is set to `True` the binary
prefixes are used (Mebi, Gibi).
"""
bytes = float(value)
base = binary and 1024 or 1000
prefixes = [
(binary and 'KiB' or 'kB'),
(binary and 'MiB' or 'MB'),
(binary and 'GiB' or 'GB'),
(binary and 'TiB' or 'TB'),
(binary and 'PiB' or 'PB'),
(binary and 'EiB' or 'EB'),
(binary and 'ZiB' or 'ZB'),
(binary and 'YiB' or 'YB')
]
if bytes == 1:
return '1 Byte'
elif bytes < base:
return '%d Bytes' % bytes
else:
for i, prefix in enumerate(prefixes):
unit = base ** (i + 2)
if bytes < unit:
return '%.1f %s' % ((base * bytes / unit), prefix)
return '%.1f %s' % ((base * bytes / unit), prefix)
def do_pprint(value, verbose=False):
"""Pretty print a variable. Useful for debugging.
With Jinja 1.2 onwards you can pass it a parameter. If this parameter
is truthy the output will be more verbose (this requires `pretty`)
"""
return pformat(value, verbose=verbose)
@evalcontextfilter
def do_urlize(eval_ctx, value, trim_url_limit=None, nofollow=False,
target=None):
"""Converts URLs in plain text into clickable links.
If you pass the filter an additional integer it will shorten the urls
to that number. Also a third argument exists that makes the urls
"nofollow":
.. sourcecode:: jinja
{{ mytext|urlize(40, true) }}
links are shortened to 40 chars and defined with rel="nofollow"
If *target* is specified, the ``target`` attribute will be added to the
``<a>`` tag:
.. sourcecode:: jinja
{{ mytext|urlize(40, target='_blank') }}
.. versionchanged:: 2.8+
The *target* parameter was added.
"""
rv = urlize(value, trim_url_limit, nofollow, target)
if eval_ctx.autoescape:
rv = Markup(rv)
return rv
def do_indent(s, width=4, indentfirst=False):
"""Return a copy of the passed string, each line indented by
4 spaces. The first line is not indented. If you want to
change the number of spaces or indent the first line too
you can pass additional parameters to the filter:
.. sourcecode:: jinja
{{ mytext|indent(2, true) }}
indent by two spaces and indent the first line too.
"""
indention = u' ' * width
rv = (u'\n' + indention).join(s.splitlines())
if indentfirst:
rv = indention + rv
return rv
def do_truncate(s, length=255, killwords=False, end='...'):
"""Return a truncated copy of the string. The length is specified
with the first parameter which defaults to ``255``. If the second
parameter is ``true`` the filter will cut the text at length. Otherwise
it will discard the last word. If the text was in fact
truncated it will append an ellipsis sign (``"..."``). If you want a
different ellipsis sign than ``"..."`` you can specify it using the
third parameter.
.. sourcecode:: jinja
{{ "foo bar baz"|truncate(9) }}
-> "foo ..."
{{ "foo bar baz"|truncate(9, True) }}
-> "foo ba..."
"""
if len(s) <= length:
return s
elif killwords:
return s[:length - len(end)] + end
result = s[:length - len(end)].rsplit(' ', 1)[0]
if len(result) < length:
result += ' '
return result + end
@environmentfilter
def do_wordwrap(environment, s, width=79, break_long_words=True,
wrapstring=None):
"""
Return a copy of the string passed to the filter wrapped after
``79`` characters. You can override this default using the first
parameter. If you set the second parameter to `false` Jinja will not
split words apart if they are longer than `width`. By default, the newlines
will be the default newlines for the environment, but this can be changed
using the wrapstring keyword argument.
.. versionadded:: 2.7
Added support for the `wrapstring` parameter.
"""
if not wrapstring:
wrapstring = environment.newline_sequence
import textwrap
return wrapstring.join(textwrap.wrap(s, width=width, expand_tabs=False,
replace_whitespace=False,
break_long_words=break_long_words))
def do_wordcount(s):
"""Count the words in that string."""
return len(_word_re.findall(s))
def do_int(value, default=0):
"""Convert the value into an integer. If the
conversion doesn't work it will return ``0``. You can
override this default using the first parameter.
"""
try:
return int(value)
except (TypeError, ValueError):
# this quirk is necessary so that "42.23"|int gives 42.
try:
return int(float(value))
except (TypeError, ValueError):
return default
def do_float(value, default=0.0):
"""Convert the value into a floating point number. If the
conversion doesn't work it will return ``0.0``. You can
override this default using the first parameter.
"""
try:
return float(value)
except (TypeError, ValueError):
return default
def do_format(value, *args, **kwargs):
"""
Apply python string formatting on an object:
.. sourcecode:: jinja
{{ "%s - %s"|format("Hello?", "Foo!") }}
-> Hello? - Foo!
"""
if args and kwargs:
raise FilterArgumentError('can\'t handle positional and keyword '
'arguments at the same time')
return soft_unicode(value) % (kwargs or args)
def do_trim(value):
"""Strip leading and trailing whitespace."""
return soft_unicode(value).strip()
def do_striptags(value):
"""Strip SGML/XML tags and replace adjacent whitespace by one space.
"""
if hasattr(value, '__html__'):
value = value.__html__()
return Markup(text_type(value)).striptags()
def do_slice(value, slices, fill_with=None):
"""Slice an iterator and return a list of lists containing
those items. Useful if you want to create a div containing
three ul tags that represent columns:
.. sourcecode:: html+jinja
<div class="columwrapper">
{%- for column in items|slice(3) %}
<ul class="column-{{ loop.index }}">
{%- for item in column %}
<li>{{ item }}</li>
{%- endfor %}
</ul>
{%- endfor %}
</div>
If you pass it a second argument it's used to fill missing
values on the last iteration.
"""
seq = list(value)
length = len(seq)
items_per_slice = length // slices
slices_with_extra = length % slices
offset = 0
for slice_number in range(slices):
start = offset + slice_number * items_per_slice
if slice_number < slices_with_extra:
offset += 1
end = offset + (slice_number + 1) * items_per_slice
tmp = seq[start:end]
if fill_with is not None and slice_number >= slices_with_extra:
tmp.append(fill_with)
yield tmp
def do_batch(value, linecount, fill_with=None):
"""
A filter that batches items. It works pretty much like `slice`
just the other way round. It returns a list of lists with the
given number of items. If you provide a second parameter this
is used to fill up missing items. See this example:
.. sourcecode:: html+jinja
<table>
{%- for row in items|batch(3, ' ') %}
<tr>
{%- for column in row %}
<td>{{ column }}</td>
{%- endfor %}
</tr>
{%- endfor %}
</table>
"""
tmp = []
for item in value:
if len(tmp) == linecount:
yield tmp
tmp = []
tmp.append(item)
if tmp:
if fill_with is not None and len(tmp) < linecount:
tmp += [fill_with] * (linecount - len(tmp))
yield tmp
def do_round(value, precision=0, method='common'):
"""Round the number to a given precision. The first
parameter specifies the precision (default is ``0``), the
second the rounding method:
- ``'common'`` rounds either up or down
- ``'ceil'`` always rounds up
- ``'floor'`` always rounds down
If you don't specify a method ``'common'`` is used.
.. sourcecode:: jinja
{{ 42.55|round }}
-> 43.0
{{ 42.55|round(1, 'floor') }}
-> 42.5
Note that even if rounded to 0 precision, a float is returned. If
you need a real integer, pipe it through `int`:
.. sourcecode:: jinja
{{ 42.55|round|int }}
-> 43
"""
if not method in ('common', 'ceil', 'floor'):
raise FilterArgumentError('method must be common, ceil or floor')
if method == 'common':
return round(value, precision)
func = getattr(math, method)
return func(value * (10 ** precision)) / (10 ** precision)
@environmentfilter
def do_groupby(environment, value, attribute):
"""Group a sequence of objects by a common attribute.
If you for example have a list of dicts or objects that represent persons
with `gender`, `first_name` and `last_name` attributes and you want to
group all users by genders you can do something like the following
snippet:
.. sourcecode:: html+jinja
<ul>
{% for group in persons|groupby('gender') %}
<li>{{ group.grouper }}<ul>
{% for person in group.list %}
<li>{{ person.first_name }} {{ person.last_name }}</li>
{% endfor %}</ul></li>
{% endfor %}
</ul>
Additionally it's possible to use tuple unpacking for the grouper and
list:
.. sourcecode:: html+jinja
<ul>
{% for grouper, list in persons|groupby('gender') %}
...
{% endfor %}
</ul>
As you can see the item we're grouping by is stored in the `grouper`
attribute and the `list` contains all the objects that have this grouper
in common.
.. versionchanged:: 2.6
It's now possible to use dotted notation to group by the child
attribute of another attribute.
"""
expr = make_attrgetter(environment, attribute)
return sorted(map(_GroupTuple, groupby(sorted(value, key=expr), expr)))
class _GroupTuple(tuple):
__slots__ = ()
grouper = property(itemgetter(0))
list = property(itemgetter(1))
def __new__(cls, xxx_todo_changeme):
(key, value) = xxx_todo_changeme
return tuple.__new__(cls, (key, list(value)))
@environmentfilter
def do_sum(environment, iterable, attribute=None, start=0):
"""Returns the sum of a sequence of numbers plus the value of parameter
'start' (which defaults to 0). When the sequence is empty it returns
start.
It is also possible to sum up only certain attributes:
.. sourcecode:: jinja
Total: {{ items|sum(attribute='price') }}
.. versionchanged:: 2.6
The `attribute` parameter was added to allow suming up over
attributes. Also the `start` parameter was moved on to the right.
"""
if attribute is not None:
iterable = imap(make_attrgetter(environment, attribute), iterable)
return sum(iterable, start)
def do_list(value):
"""Convert the value into a list. If it was a string the returned list
will be a list of characters.
"""
return list(value)
def do_mark_safe(value):
"""Mark the value as safe which means that in an environment with automatic
escaping enabled this variable will not be escaped.
"""
return Markup(value)
def do_mark_unsafe(value):
"""Mark a value as unsafe. This is the reverse operation for :func:`safe`."""
return text_type(value)
def do_reverse(value):
"""Reverse the object or return an iterator the iterates over it the other
way round.
"""
if isinstance(value, string_types):
return value[::-1]
try:
return reversed(value)
except TypeError:
try:
rv = list(value)
rv.reverse()
return rv
except TypeError:
raise FilterArgumentError('argument must be iterable')
@environmentfilter
def do_attr(environment, obj, name):
"""Get an attribute of an object. ``foo|attr("bar")`` works like
``foo.bar`` just that always an attribute is returned and items are not
looked up.
See :ref:`Notes on subscriptions <notes-on-subscriptions>` for more details.
"""
try:
name = str(name)
except UnicodeError:
pass
else:
try:
value = getattr(obj, name)
except AttributeError:
pass
else:
if environment.sandboxed and not \
environment.is_safe_attribute(obj, name, value):
return environment.unsafe_undefined(obj, name)
return value
return environment.undefined(obj=obj, name=name)
@contextfilter
def do_map(*args, **kwargs):
"""Applies a filter on a sequence of objects or looks up an attribute.
This is useful when dealing with lists of objects but you are really
only interested in a certain value of it.
The basic usage is mapping on an attribute. Imagine you have a list
of users but you are only interested in a list of usernames:
.. sourcecode:: jinja
Users on this page: {{ users|map(attribute='username')|join(', ') }}
Alternatively you can let it invoke a filter by passing the name of the
filter and the arguments afterwards. A good example would be applying a
text conversion filter on a sequence:
.. sourcecode:: jinja
Users on this page: {{ titles|map('lower')|join(', ') }}
.. versionadded:: 2.7
"""
context = args[0]
seq = args[1]
if len(args) == 2 and 'attribute' in kwargs:
attribute = kwargs.pop('attribute')
if kwargs:
raise FilterArgumentError('Unexpected keyword argument %r' %
next(iter(kwargs)))
func = make_attrgetter(context.environment, attribute)
else:
try:
name = args[2]
args = args[3:]
except LookupError:
raise FilterArgumentError('map requires a filter argument')
func = lambda item: context.environment.call_filter(
name, item, args, kwargs, context=context)
if seq:
for item in seq:
yield func(item)
@contextfilter
def do_select(*args, **kwargs):
"""Filters a sequence of objects by applying a test to the object and only
selecting the ones with the test succeeding.
Example usage:
.. sourcecode:: jinja
{{ numbers|select("odd") }}
{{ numbers|select("odd") }}
.. versionadded:: 2.7
"""
return _select_or_reject(args, kwargs, lambda x: x, False)
@contextfilter
def do_reject(*args, **kwargs):
"""Filters a sequence of objects by applying a test to the object and
rejecting the ones with the test succeeding.
Example usage:
.. sourcecode:: jinja
{{ numbers|reject("odd") }}
.. versionadded:: 2.7
"""
return _select_or_reject(args, kwargs, lambda x: not x, False)
@contextfilter
def do_selectattr(*args, **kwargs):
"""Filters a sequence of objects by applying a test to an attribute of an
object and only selecting the ones with the test succeeding.
Example usage:
.. sourcecode:: jinja
{{ users|selectattr("is_active") }}
{{ users|selectattr("email", "none") }}
.. versionadded:: 2.7
"""
return _select_or_reject(args, kwargs, lambda x: x, True)
@contextfilter
def do_rejectattr(*args, **kwargs):
"""Filters a sequence of objects by applying a test to an attribute of an
object or the attribute and rejecting the ones with the test succeeding.
.. sourcecode:: jinja
{{ users|rejectattr("is_active") }}
{{ users|rejectattr("email", "none") }}
.. versionadded:: 2.7
"""
return _select_or_reject(args, kwargs, lambda x: not x, True)
def _select_or_reject(args, kwargs, modfunc, lookup_attr):
context = args[0]
seq = args[1]
if lookup_attr:
try:
attr = args[2]
except LookupError:
raise FilterArgumentError('Missing parameter for attribute name')
transfunc = make_attrgetter(context.environment, attr)
off = 1
else:
off = 0
transfunc = lambda x: x
try:
name = args[2 + off]
args = args[3 + off:]
func = lambda item: context.environment.call_test(
name, item, args, kwargs)
except LookupError:
func = bool
if seq:
for item in seq:
if modfunc(func(transfunc(item))):
yield item
FILTERS = {
'attr': do_attr,
'replace': do_replace,
'upper': do_upper,
'lower': do_lower,
'escape': escape,
'e': escape,
'forceescape': do_forceescape,
'capitalize': do_capitalize,
'title': do_title,
'default': do_default,
'd': do_default,
'join': do_join,
'count': len,
'dictsort': do_dictsort,
'sort': do_sort,
'length': len,
'reverse': do_reverse,
'center': do_center,
'indent': do_indent,
'title': do_title,
'capitalize': do_capitalize,
'first': do_first,
'last': do_last,
'map': do_map,
'random': do_random,
'reject': do_reject,
'rejectattr': do_rejectattr,
'filesizeformat': do_filesizeformat,
'pprint': do_pprint,
'truncate': do_truncate,
'wordwrap': do_wordwrap,
'wordcount': do_wordcount,
'int': do_int,
'float': do_float,
'string': soft_unicode,
'list': do_list,
'urlize': do_urlize,
'format': do_format,
'trim': do_trim,
'striptags': do_striptags,
'select': do_select,
'selectattr': do_selectattr,
'slice': do_slice,
'batch': do_batch,
'sum': do_sum,
'abs': abs,
'round': do_round,
'groupby': do_groupby,
'safe': do_mark_safe,
'xmlattr': do_xmlattr,
'urlencode': do_urlencode
}
| dstufft/jinja2 | jinja2/filters.py | Python | bsd-3-clause | 29,972 |
<?php
/**
* Global Configuration Override
*
* You can use this file for overriding configuration values from modules, etc.
* You would place values in here that are agnostic to the environment and not
* sensitive to security.
*
* @NOTE: In practice, this file will typically be INCLUDED in your source
* control, so do not include passwords or other sensitive information in this
* file.
*/
return array(
'db'=>array(
'driver' =>'pdo',
'dsn' =>'mysql:dbname=hwims;host=localhost',
'driver_options' => array(
PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES \'UTF8\''
),
'username' =>'root',
'password' =>'',
),
'service_manager' =>array(
'factories' =>array(
'Zend\Db\Adapter\Adapter' => 'Zend\Db\Adapter\AdapterServiceFactory',
),
),
);
| pdhwi/hwizfms | config/autoload/global.php | PHP | bsd-3-clause | 864 |
<?php
namespace frontend\modules\patient\controllers;
use common\components\AppController;
use common\components\MyHelper;
/**
* Description of PrintController
*
* @author utehn
*/
class PrintController extends AppController {
public function beforeAction($action) {
if ($action->id == 'index') {
$this->enableCsrfValidation = false;
}
return parent::beforeAction($action);
}
public function actionIndex($pid){
$this->layout = 'main';
$this->permitRole([1,2]);
return $this->render('index',[
'pid'=>$pid
]);
}
}
| sirensoft/smartcare | frontend/modules/patient/controllers/PrintController.php | PHP | bsd-3-clause | 678 |
<?php
/* @var $this TblSoldHogsController */
/* @var $model TblSoldHogs */
/* @var $form CActiveForm */
$farmHerd = Yii::app()->request->cookies['farm_herd'];
$farmHerdName = Yii::app()->request->cookies['farm_herd_name'];
$herdmark = Yii::app()->request->cookies['breeder_herd_mark'];
$hogtag = Yii::app()->request->cookies['hog_tag'];
if($herdmark != "")
$herdmark = $herdmark." ";
$activitydate = isset(Yii::app()->request->cookies['date'])?Yii::app()->request->cookies['date']:date("m/d/Y");
?>
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'tbl-sold-hogs-form',
'enableAjaxValidation'=>false,
)); ?>
<div class="form">
<div class="row buttons">
<?php echo CHtml::Button('List Sold Hogs',array('onClick'=>'window.location="index.php?r=tblSoldHogs/admin"')); ?>
<?php echo CHtml::submitButton($model->isNewRecord ? 'Save' : 'Save', array('onClick'=>'return validateForm();')); ?>
<?php echo CHtml::submitButton($model->isNewRecord ? 'Save & New' : 'Save & New', array('onClick'=>'return validateForm();','name'=>'savenew')); ?>
<?php echo CHtml::Button('Cancel',array('onClick'=>'cancelsoldhogs()')); ?>
</div>
<?php echo $form->errorSummary($model); ?>
<div class="row">
<?php echo $form->labelEx($model,'hog_ear_notch'); ?>
<?php
if($model->isNewRecord)
echo $form->textField($model,'hog_ear_notch',array('size'=>20,'maxlength'=>20,'onBlur'=>'checkData(this,1)','value'=>$farmHerd." ".$herdmark,'id'=>'earnotch','onkeyup'=>'dottodash(this);'));
else
echo $form->textField($model,'hog_ear_notch',array('size'=>20,'maxlength'=>20,'onBlur'=>'checkData(this,2)','id'=>'earnotch','onkeyup'=>'dottodash(this);'));
?>
<?php echo $form->error($model,'hog_ear_notch'); ?>
<?php echo $form->hiddenField($model, 'ear_notch_id',array('id'=>'ear_notch_id')); ?>
<?php if($hogtag == 'T') {?>
<label>Hog Ear Tag </label>
<input type="text" name="hog_ear_tag" id="hog_ear_tag" onChange="getEarnotch(this,'earnotch','TblSoldHogs_customer_name');" onBlur="$('#TblSoldHogs_customer_name').focus();" value="<?php echo $model->hog_ear_tag; ?>">
<?php } ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'customer_name'); ?>
<?php echo $form->textField($model,'customer_name',array('size'=>50,'maxlength'=>50)); ?>
<?php echo $form->hiddenField($model, 'cust_id',array('id'=>'cust_id')); ?>
<?php echo $form->error($model,'customer_name'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'date_sold'); ?>
<?php //echo $form->textField($model,'date_sold',array('size'=>20,'maxlength'=>20));
$this->widget('zii.widgets.jui.CJuiDatePicker', array(
'model' => $model,
'attribute' => 'date_sold',
'options' =>array(
//'dateFormat'=>'mm-dd-yy',
'constrainInput'=>false,
'showOn'=>'button',
'defaultDate'=>''.$activitydate.'',
'buttonImage'=>'img/calendar.gif',
),
'htmlOptions' => array(
'id'=>'date_sold',
'size' => '20', // textField size
'maxlength' => '20', // textField maxlength
'onBlur'=>'validateDatePicker("date_sold")',
),
));
?>
<?php echo $form->error($model,'date_sold'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'sold_price'); ?>
<?php echo $form->textField($model,'sold_price', array('onkeypress'=>'return isInteger(event);')); ?>
<?php echo $form->error($model,'sold_price'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'sale_type'); ?>
<?php echo $form->textField($model,'sale_type',array('size'=>1,'maxlength'=>1)); ?>
<?php echo $form->error($model,'sale_type'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'invoice_number'); ?>
<?php echo $form->textField($model,'invoice_number',array('onkeypress'=>'return isInteger(event);')); ?>
<?php echo $form->error($model,'invoice_number'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'app_xfer'); ?>
<?php
//echo $form->textField($model,'app_xfer',array('size'=>1,'maxlength'=>1));
echo $form->dropDownList($model,'app_xfer',array('Y'=>'Y','N'=>'N'),
array('size'=>0,'tabindex'=>23,'maxlength'=>0));
?>
<?php echo $form->error($model,'app_xfer'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'comments'); ?>
<?php echo $form->textArea($model,'comments',array('rows'=>3, 'cols'=>50)); ?>
<?php echo $form->error($model,'comments'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'reason_sold',array('id'=>'label_reason_sold')); ?>
<?php echo $form->textArea($model,'reason_sold',array('rows'=>3, 'cols'=>50, 'id'=>'reason_sold')); ?>
<?php echo $form->error($model,'reason_sold'); ?>
</div>
<div> </div>
<div class="row buttons">
<?php echo CHtml::Button('List Sold Hogs',array('onClick'=>'window.location="index.php?r=tblSoldHogs/admin"')); ?>
<?php echo CHtml::submitButton($model->isNewRecord ? 'Save' : 'Save', array('onClick'=>'return validateForm();')); ?>
<?php echo CHtml::submitButton($model->isNewRecord ? 'Save & New' : 'Save & New', array('onClick'=>'return validateForm();','name'=>'savenew')); ?>
<?php echo CHtml::Button('Cancel',array('onClick'=>'cancelsoldhogs()')); ?>
</div>
<?php $this->endWidget(); ?>
</div><!-- form -->
<p class="note">Fields with <span class="required">*</span> are required.</p> | jntd11/yiitest | testdrive/protected/views/tblSoldHogs/_form.php | PHP | bsd-3-clause | 5,383 |
(function ()
{
"use strict";
angular.module('BuDirectives', []).
directive('bindHtmlWithJs', ['$sce', '$parse', function ($sce, $parse)
{
/**
* It removes script tags from html and inserts it into DOM.
*
* Testing:
* html += '<script>alert(1234)</script><script type="text/javascript">alert(12345)</script><script type="asdf">alert(1234)</script><script src="/js/alert.js">alert(1234)</script><span style="color: red;">1234</span>';
* or
* html += '<script src="/js/alert.js"></script><script type="text/javascript">console.log(window.qwerqwerqewr1234)</script><span style="color: red;">1234</span>';
*
* @param html {String}
* @returns {String}
*/
function handleScripts(html)
{
// html must start with tag - it's angularjs' jqLite bug/feature
html = '<i></i>' + html;
var originElements = angular.element(html),
elements = angular.element('<div></div>');
if (originElements.length)
{
// start from 1 for removing first tag we just added
for (var i = 1, l = originElements.length; i < l; i ++)
{
var $el = originElements.eq(i),
el = $el[0];
if (el.nodeName == 'SCRIPT' && ((! el.type) || el.type == 'text/javascript')) {
evalScript($el[0]);
}
else {
elements.append($el);
}
}
}
// elements = elements.contents();
html = elements.html();
return html;
}
/**
* It's taken from AngularJS' jsonpReq function.
* It's not ie < 9 compatible.
* @param {DOMElement} element
*/
function evalScript(element)
{
var script = document.createElement('script'),
body = document.body,
doneWrapper = function() {
script.onload = script.onerror = null;
body.removeChild(script);
};
script.type = 'text/javascript';
if (element.src)
{
script.src = element.src;
script.async = element.async;
script.onload = script.onerror = function () {
doneWrapper();
};
}
else
{
// doesn't work on ie...
try {
script.appendChild(document.createTextNode(element.innerText));
}
// IE has funky script nodes
catch (e) {
script.text = element.innerText;
}
setTimeout(function () {doneWrapper()}, 10);
}
body.appendChild(script);
}
return function ($scope, element, attr)
{
element.addClass('ng-binding').data('$binding', attr.bindHtmlWithJs);
var parsed = $parse(attr.bindHtmlWithJs);
function getStringValue()
{
return (parsed($scope) || '').toString();
}
$scope.$watch(getStringValue, function bindHtmlWithJsWatchAction(value)
{
var html = value ? $sce.getTrustedHtml(parsed($scope)) : '';
if (html) {
html = handleScripts(html);
}
element.html(html || '');
});
};
}]).
/* This filter is for demo only */
filter('trustAsHtml', ['$sce', function ($sce) {
return function trustAsHtml(value) {
return $sce.trustAsHtml(value);
}
}]);
}()); | makc45/blog | web/js/directive_bind_html_with_js.js | JavaScript | bsd-3-clause | 3,009 |
// *****************************************************************************
/*!
\file src/NoWarning/tut_runner.hpp
\copyright 2012-2015 J. Bakosi,
2016-2018 Los Alamos National Security, LLC.,
2019-2020 Triad National Security, LLC.
All rights reserved. See the LICENSE file for details.
\brief Include tut/tut_runner.hpp with turning off specific compiler
warnings
*/
// *****************************************************************************
#ifndef nowarning_tut_runner_h
#define nowarning_tut_runner_h
#include "Macro.hpp"
#if defined(__clang__)
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated"
#pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant"
#elif defined(STRICT_GNUC)
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wshadow"
#elif defined(__INTEL_COMPILER)
#pragma warning( push )
#pragma warning( disable: 1720 )
#endif
#include <map>
#include <tut/tut_runner.hpp>
#if defined(__clang__)
#pragma clang diagnostic pop
#elif defined(STRICT_GNUC)
#pragma GCC diagnostic pop
#elif defined(__INTEL_COMPILER)
#pragma warning( pop )
#endif
#endif // nowarning_tut_runner_h
| jbakosi/quinoa | src/NoWarning/tut_runner.hpp | C++ | bsd-3-clause | 1,238 |
/******************************************************************************
* ____ _ _____ *
* / ___| / \ | ___| C++ *
* | | / _ \ | |_ Actor *
* | |___ / ___ \| _| Framework *
* \____/_/ \_|_| *
* *
* Copyright (C) 2011 - 2016 *
* Dominik Charousset <dominik.charousset (at) haw-hamburg.de> *
* *
* Distributed under the terms and conditions of the BSD 3-Clause License or *
* (at your option) under the terms and conditions of the Boost Software *
* License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. *
* *
* If you did not receive a copy of the license files, see *
* http://opensource.org/licenses/BSD-3-Clause and *
* http://www.boost.org/LICENSE_1_0.txt. *
******************************************************************************/
#ifndef CAF_DETAIL_SYNC_REQUEST_BOUNCER_HPP
#define CAF_DETAIL_SYNC_REQUEST_BOUNCER_HPP
#include <cstdint>
#include "caf/fwd.hpp"
#include "caf/exit_reason.hpp"
namespace caf {
class actor_addr;
class message_id;
class local_actor;
class mailbox_element;
} // namespace caf
namespace caf {
namespace detail {
struct sync_request_bouncer {
error rsn;
explicit sync_request_bouncer(error r);
void operator()(const strong_actor_ptr& sender, const message_id& mid) const;
void operator()(const mailbox_element& e) const;
};
} // namespace detail
} // namespace caf
#endif // CAF_DETAIL_SYNC_REQUEST_BOUNCER_HPP
| nq-ebaratte/actor-framework | libcaf_core/caf/detail/sync_request_bouncer.hpp | C++ | bsd-3-clause | 2,066 |
// This file was generated using Parlex's cpp_generator
#include "FUNCTION_MODIFIER_MODEL.hpp"
#include "plange_grammar.hpp"
#include "parlex/detail/document.hpp"
#include "FUNCTION_MODIFIER_CALLING_CONVENTION.hpp"
#include "ICR.hpp"
plc::FUNCTION_MODIFIER_MODEL::field_1_t_1_t plc::FUNCTION_MODIFIER_MODEL::field_1_t_1_t::build(parlex::detail::node const * b, parlex::detail::document::walk & w) {
auto const & children = b->children;
auto v0 = parlex::detail::document::element<erased<ICR>>::build(&*children[0], w);
auto v1 = parlex::detail::document::element<erased<FUNCTION_MODIFIER_CALLING_CONVENTION>>::build(&*children[1], w);
return field_1_t_1_t(std::move(v0), std::move(v1));
}
plc::FUNCTION_MODIFIER_MODEL plc::FUNCTION_MODIFIER_MODEL::build(parlex::detail::ast_node const & n) {
static auto const * b = state_machine().behavior;
parlex::detail::document::walk w{ n.children.cbegin(), n.children.cend() };
auto const & children = b->children;
auto v0 = parlex::detail::document::element<std::variant<
parlex::detail::document::text<literal_pure_t>,
parlex::detail::document::text<literal_imperative_t>,
parlex::detail::document::text<literal_opaque_t>
>>::build(&*children[0], w);
auto v1 = parlex::detail::document::element<std::optional<field_1_t_1_t>>::build(&*children[1], w);
return FUNCTION_MODIFIER_MODEL(std::move(v0), std::move(v1));
}
parlex::detail::state_machine const & plc::FUNCTION_MODIFIER_MODEL::state_machine() {
static auto const & result = *static_cast<parlex::detail::state_machine const *>(&plange_grammar::get().get_recognizer(plange_grammar::get().FUNCTION_MODIFIER_MODEL));
return result;
}
| dlin172/Plange | source/plc/src/document/FUNCTION_MODIFIER_MODEL.cpp | C++ | bsd-3-clause | 1,657 |
<?php
/**
* Phergie (http://phergie.org)
*
* @link http://github.com/phergie/phergie-irc-generator for the canonical source repository
* @copyright Copyright (c) 2008-2014 Phergie Development Team (http://phergie.org)
* @license http://phergie.org/license Simplified BSD License
* @package Phergie\Irc
*/
namespace Phergie\Irc;
/**
* Canonical implementation of GeneratorInterface.
*
* @category Phergie
* @package Phergie\Irc
*/
class Generator implements GeneratorInterface
{
/**
* Message prefix
*
* @var string
*/
protected $prefix = null;
/**
* Implements GeneratorInterface::setPrefix().
*
* @param string $prefix
*/
public function setPrefix($prefix)
{
$this->prefix = $prefix;
}
/**
* Returns a formatted IRC message.
*
* @param string $type Command or response code
* @param array $params Optional message parameters
* @return string
*/
protected function getIrcMessage($type, array $params = array())
{
$message = '';
if ($this->prefix) {
$message .= ':' . $this->prefix . ' ';
}
$message .= $type;
$params = array_filter($params, function($param) {
return $param !== null;
});
if ($params) {
$last = end($params);
$params[key($params)] = ':' . $last;
$message .= ' ' . implode(' ', $params);
}
$message .= "\r\n";
return $message;
}
/**
* Returns a PASS message.
*
* @param string $password
* @return string
*/
public function ircPass($password)
{
return $this->getIrcMessage('PASS', array($password));
}
/**
* Returns a NICK message.
*
* @param string $nickname
* @param int $hopcount
* @return string
*/
public function ircNick($nickname, $hopcount = null)
{
return $this->getIrcMessage('NICK', array($nickname, $hopcount));
}
/**
* Returns a USER message.
*
* @param string $username
* @param string $hostname
* @param string $servername
* @param string $realname
* @return string
*/
public function ircUser($username, $hostname, $servername, $realname)
{
return $this->getIrcMessage('USER', array($username, $hostname, $servername, $realname));
}
/**
* Returns a SERVER message.
*
* @param string $servername
* @param int $hopcount
* @param string $info
* @return string
*/
public function ircServer($servername, $hopcount, $info)
{
return $this->getIrcMessage('SERVER', array($servername, $hopcount, $info));
}
/**
* Returns an OPER message.
*
* @param string $user
* @param string $password
* @return string
*/
public function ircOper($user, $password)
{
return $this->getIrcMessage('OPER', array($user, $password));
}
/**
* Returns a QUIT message.
*
* @param string $message
* @return string
*/
public function ircQuit($message = null)
{
return $this->getIrcMessage('QUIT', array($message));
}
/**
* Returns an SQUIT message.
*
* @param string $server
* @param string $comment
* @return string
*/
public function ircSquit($server, $comment)
{
return $this->getIrcMessage('SQUIT', array($server, $comment));
}
/**
* Returns a JOIN message.
*
* @param string $channels
* @param string $keys
* @return string
*/
public function ircJoin($channels, $keys = null)
{
return $this->getIrcMessage('JOIN', array($channels, $keys));
}
/**
* Returns a PART message.
*
* @param string $channels
* @param string $message
* @return string
*/
public function ircPart($channels, $message = null)
{
return $this->getIrcMessage('PART', array($channels, $message));
}
/**
* Returns a MODE message.
*
* @param string $target
* @param string|null $mode
* @param string|null $param
* @return string
*/
public function ircMode($target, $mode = null, $param = null)
{
return $this->getIrcMessage('MODE', array($target, $mode, $param));
}
/**
* Returns a TOPIC message.
*
* @param string $channel
* @param string $topic
* @return string
*/
public function ircTopic($channel, $topic = null)
{
return $this->getIrcMessage('TOPIC', array($channel, $topic));
}
/**
* Returns a NAMES message.
*
* @param string $channels
* @return string
*/
public function ircNames($channels)
{
return $this->getIrcMessage('NAMES', array($channels));
}
/**
* Returns a LIST message.
*
* @param string $channels
* @param string $server
* @return string
*/
public function ircList($channels = null, $server = null)
{
return $this->getIrcMessage('LIST', array($channels, $server));
}
/**
* Returns an INVITE message.
*
* @param string $nickname
* @param string $channel
* @return string
*/
public function ircInvite($nickname, $channel)
{
return $this->getIrcMessage('INVITE', array($nickname, $channel));
}
/**
* Returns a KICK message.
*
* @param string $channel
* @param string $user
* @param string $comment
* @return string
*/
public function ircKick($channel, $user, $comment = null)
{
return $this->getIrcMessage('KICK', array($channel, $user, $comment));
}
/**
* Returns a VERSION message.
*
* @param string $server
* @return string
*/
public function ircVersion($server = null)
{
return $this->getIrcMessage('VERSION', array($server));
}
/**
* Returns a STATS message.
*
* @param string $query
* @param string $server
* @return string
*/
public function ircStats($query, $server = null)
{
return $this->getIrcMessage('STATS', array($query, $server));
}
/**
* Returns a LINKS message.
*
* Note that the parameter order of this method is reversed with respect to
* the corresponding IRC message to alleviate the need to explicitly specify
* a null value for $remoteserver when it is not used.
*
* @param string $servermask
* @param string $remoteserver
* @return string
*/
public function ircLinks($servermask = null, $remoteserver = null)
{
return $this->getIrcMessage('LINKS', array($remoteserver, $servermask));
}
/**
* Returns a TIME message.
*
* @param string $server
* @return string
*/
public function ircTime($server = null)
{
return $this->getIrcMessage('TIME', array($server));
}
/**
* Returns a CONNECT message.
*
* @param string $targetserver
* @param int $port
* @param string $remoteserver
* @return string
*/
public function ircConnect($targetserver, $port = null, $remoteserver = null)
{
return $this->getIrcMessage('CONNECT', array($targetserver, $port, $remoteserver));
}
/**
* Returns a TRACE message.
*
* @param string $server
* @return string
*/
public function ircTrace($server = null)
{
return $this->getIrcMessage('TRACE', array($server));
}
/**
* Returns an ADMIN message.
*
* @param string $server
* @return string
*/
public function ircAdmin($server = null)
{
return $this->getIrcMessage('ADMIN', array($server));
}
/**
* Returns an INFO message.
*
* @param string $server
* @return string
*/
public function ircInfo($server = null)
{
return $this->getIrcMessage('INFO', array($server));
}
/**
* Returns a PRIVMSG message.
*
* @param string $receivers
* @param string $text
* @return string
*/
public function ircPrivmsg($receivers, $text)
{
return $this->getIrcMessage('PRIVMSG', array($receivers, $text));
}
/**
* Returns a NOTICE message.
*
* @param string $nickname
* @param string $text
* @return string
*/
public function ircNotice($nickname, $text)
{
return $this->getIrcMessage('NOTICE', array($nickname, $text));
}
/**
* Returns a WHO message.
*
* @param string $name
* @param string $o
* @return string
*/
public function ircWho($name, $o = null)
{
return $this->getIrcMessage('WHO', array($name, $o));
}
/**
* Returns a WHOIS message.
*
* @param string $nickmasks
* @param string $server
* @return string
*/
public function ircWhois($nickmasks, $server = null)
{
return $this->getIrcMessage('WHOIS', array($server, $nickmasks));
}
/**
* Returns a WHOWAS message.
*
* @param string $nickname
* @param int $count
* @param string $server
* @return string
*/
public function ircWhowas($nickname, $count = null, $server = null)
{
return $this->getIrcMessage('WHOWAS', array($nickname, $count, $server));
}
/**
* Returns a KILL message.
*
* @param string $nickname
* @param string $comment
* @return string
*/
public function ircKill($nickname, $comment)
{
return $this->getIrcMessage('KILL', array($nickname, $comment));
}
/**
* Returns a PING message.
*
* @param string $server1
* @param string $server2
* @return string
*/
public function ircPing($server1, $server2 = null)
{
return $this->getIrcMessage('PING', array($server1, $server2));
}
/**
* Returns a PONG message.
*
* @param string $daemon
* @param string $daemon2
* @return string
*/
public function ircPong($daemon, $daemon2 = null)
{
return $this->getIrcMessage('PONG', array($daemon, $daemon2));
}
/**
* Returns an ERROR message.
*
* @param string $message
* @return string
*/
public function ircError($message)
{
return $this->getIrcMessage('ERROR', array($message));
}
/**
* Returns an AWAY message.
*
* @param string $message
* @return string
*/
public function ircAway($message = null)
{
return $this->getIrcMessage('AWAY', array($message));
}
/**
* Returns a REHASH message.
*
* @return string
*/
public function ircRehash()
{
return $this->getIrcMessage('REHASH');
}
/**
* Returns a RESTART message.
*
* @return string
*/
public function ircRestart()
{
return $this->getIrcMessage('RESTART');
}
/**
* Returns a SUMMON message.
*
* @param string $user
* @param string $server
* @return string
*/
public function ircSummon($user, $server = null)
{
return $this->getIrcMessage('SUMMON', array($user, $server));
}
/**
* Returns a USERS message.
*
* @param string $server
* @return string
*/
public function ircUsers($server = null)
{
return $this->getIrcMessage('USERS', array($server));
}
/**
* Returns a WALLOPS message.
*
* @param string $text
* @return string
*/
public function ircWallops($text)
{
return $this->getIrcMessage('WALLOPS', array($text));
}
/**
* Returns a USERHOST message.
*
* @param string $nickname1
* @param string $nickname2
* @param string $nickname3
* @param string $nickname4
* @param string $nickname5
* @return string
*/
public function ircUserhost($nickname1, $nickname2 = null, $nickname3 = null, $nickname4 = null, $nickname5 = null)
{
return $this->getIrcMessage('USERHOST', array($nickname1, $nickname2, $nickname3, $nickname4, $nickname5));
}
/**
* Returns an ISON message.
*
* @param string $nicknames
* @return string
*/
public function ircIson($nicknames)
{
return $this->getIrcMessage('ISON', array($nicknames));
}
/**
* Returns a PROTOCTL message.
*
* @param string $proto
* @return string
*/
public function ircProtoctl($proto)
{
return $this->getIrcMessage('PROTOCTL', array($proto));
}
/**
* Returns a CTCP request.
*
* @param string $receivers
* @param string $message
* @return string
*/
protected function getCtcpRequest($receivers, $message)
{
return $this->ircPrivmsg($receivers, "\001" . $message . "\001");
}
/**
* Returns a CTCP response.
*
* @param string $receivers
* @param string $message
* @return string
*/
protected function getCtcpResponse($receivers, $message)
{
return $this->ircNotice($receivers, "\001" . $message . "\001");
}
/**
* Returns a CTCP FINGER message.
*
* @param string $receivers
* @return string
*/
public function ctcpFinger($receivers)
{
return $this->getCtcpRequest($receivers, 'FINGER');
}
/**
* Returns a CTCP FINGER reply message.
*
* @param string $nickname
* @param string $text
* @return string
*/
public function ctcpFingerResponse($nickname, $text)
{
return $this->getCtcpResponse($nickname, 'FINGER ' . $text);
}
/**
* Returns a CTCP VERSION message.
*
* @param string $receivers
* @return string
*/
public function ctcpVersion($receivers)
{
return $this->getCtcpRequest($receivers, 'VERSION');
}
/**
* Returns a CTCP VERSION reply message.
*
* @param string $nickname
* @param string $name
* @param string $version
* @param string $environment
* @return string
*/
public function ctcpVersionResponse($nickname, $name, $version, $environment)
{
return $this->getCtcpResponse($nickname, 'VERSION ' . $name . ':' . $version . ':' . $environment);
}
/**
* Returns a CTCP SOURCE message.
*
* @param string $receivers
* @return string
*/
public function ctcpSource($receivers)
{
return $this->getCtcpRequest($receivers, 'SOURCE');
}
/**
* Returns a CTCP SOURCE reply message.
*
* @param string $nickname
* @param string $host
* @param string $directories
* @param string $files
* @return string
*/
public function ctcpSourceResponse($nickname, $host, $directories, $files)
{
return $this->getCtcpResponse($nickname, 'SOURCE ' . $host . ':' . $directories . ':' . $files);
}
/**
* Returns a CTCP USERINFO message.
*
* @param string $receivers
* @return string
*/
public function ctcpUserinfo($receivers)
{
return $this->getCtcpRequest($receivers, 'USERINFO');
}
/**
* Returns a CTCP USERINFO reply message.
*
* @param string $nickname
* @param string $text
* @return string
*/
public function ctcpUserinfoResponse($nickname, $text)
{
return $this->getCtcpResponse($nickname, 'USERINFO ' . $text);
}
/**
* Returns a CTCP CLIENTINFO message.
*
* @param string $receivers
* @return string
*/
public function ctcpClientinfo($receivers)
{
return $this->getCtcpRequest($receivers, 'CLIENTINFO');
}
/**
* Returns a CTCP CLIENTINFO reply message.
*
* @param string $nickname
* @param string $client
* @return string
*/
public function ctcpClientinfoResponse($nickname, $client)
{
return $this->getCtcpResponse($nickname, 'CLIENTINFO ' . $client);
}
/**
* Returns a CTCP ERRMSG message.
*
* @param string $receivers
* @param string $query
* @return string
*/
public function ctcpErrmsg($receivers, $query)
{
return $this->getCtcpRequest($receivers, 'ERRMSG ' . $query);
}
/**
* Returns a CTCP ERRMSG reply message.
*
* @param string $nickname
* @param string $query
* @param string $message
* @return string
*/
public function ctcpErrmsgResponse($nickname, $query, $message)
{
return $this->getCtcpResponse($nickname, 'ERRMSG ' . $query . ' :' . $message);
}
/**
* Returns a CTCP PING message.
*
* @param string $receivers
* @param int $timestamp
* @return string
*/
public function ctcpPing($receivers, $timestamp)
{
return $this->getCtcpRequest($receivers, 'PING ' . $timestamp);
}
/**
* Returns a CTCP PING reply message.
*
* @param string $nickname
* @param int $timestamp
* @return string
*/
public function ctcpPingResponse($nickname, $timestamp)
{
return $this->getCtcpResponse($nickname, 'PING ' . $timestamp);
}
/**
* Returns a CTCP TIME message.
*
* @param string $receivers
* @return string
*/
public function ctcpTime($receivers)
{
return $this->getCtcpRequest($receivers, 'TIME');
}
/**
* Returns a CTCP TIME reply message.
*
* @param string $nickname
* @param string $time
* @return string
*/
public function ctcpTimeResponse($nickname, $time)
{
return $this->getCtcpResponse($nickname, 'TIME ' . $time);
}
/**
* Returns a CTCP ACTION message.
*
* @param string $receivers
* @param string $action
* @return string
*/
public function ctcpAction($receivers, $action)
{
return $this->getCtcpRequest($receivers, 'ACTION ' . $action);
}
/**
* Returns a CTCP ACTION reply message.
*
* @param string $nickname
* @param string $action
* @return string
*/
public function ctcpActionResponse($nickname, $action)
{
return $this->getCtcpResponse($nickname, 'ACTION ' . $action);
}
}
| phergie/phergie-irc-generator | src/Generator.php | PHP | bsd-3-clause | 18,448 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('formbuilder', '0005_auto_20150826_1600'),
]
operations = [
migrations.RemoveField(
model_name='choiceanswer',
name='option',
),
migrations.AddField(
model_name='choiceanswer',
name='choices',
field=models.ManyToManyField(related_name='answers', to='formbuilder.Option'),
),
migrations.AddField(
model_name='choiceanswer',
name='other',
field=models.TextField(blank=True),
),
migrations.AddField(
model_name='choiceanswer',
name='question',
field=models.ForeignKey(related_name='answers', to='formbuilder.Choice', null=True),
),
]
| Kvoti/ditto | ditto/formbuilder/migrations/0006_auto_20150827_1019.py | Python | bsd-3-clause | 918 |
<?php
namespace Becklyn\SearchBundle\Search\Result;
class SearchResult implements \IteratorAggregate, \Countable
{
/**
* @var EntitySearchHits[]
*/
private $resultLists = [];
/**
* @var int
*/
private $totalCount = 0;
/**
* @var float
*/
private $maxScore = 0;
/**
* @param EntitySearchHits[] $resultLists
*/
public function __construct (array $resultLists)
{
foreach ($resultLists as $resultList)
{
$this->resultLists[$resultList->getEntityClass()] = $resultList;
$this->totalCount += count($resultList);
$this->maxScore = max($this->maxScore, $resultList->getMaxScore());
}
}
/**
* Returns a list of all entity search hits lists
*
* @return EntitySearchHits[]
*/
public function getEntityResultLists () : array
{
return $this->resultLists;
}
/**
* @param string $fqcn
*
* @return EntitySearchHits|null
*/
public function getResults (string $fqcn)
{
return $this->resultLists[$fqcn] ?? null;
}
/**
* @return int
*/
public function getTotalCount () : int
{
return $this->totalCount;
}
/**
* @return float
*/
public function getMaxScore () : float
{
return $this->maxScore;
}
/**
* @inheritdoc
*/
public function count ()
{
return count($this->resultLists);
}
/**
* @inheritdoc
*/
public function getIterator ()
{
return new \ArrayIterator($this->resultLists);
}
}
| Becklyn/SearchBundle | Search/Result/SearchResult.php | PHP | bsd-3-clause | 1,655 |
import React from 'react';
import SvgIcon from './svgIcon';
type Props = React.ComponentProps<typeof SvgIcon>;
const IconSentry = React.forwardRef(function IconSentry(
props: Props,
ref: React.Ref<SVGSVGElement>
) {
return (
<SvgIcon {...props} ref={ref}>
<path d="M15.8,14.57a1.53,1.53,0,0,0,0-1.52L9.28,1.43a1.46,1.46,0,0,0-2.56,0L4.61,5.18l.54.32A10.43,10.43,0,0,1,8.92,9.39a10.84,10.84,0,0,1,1.37,4.67H8.81a9.29,9.29,0,0,0-1.16-3.91A9,9,0,0,0,4.41,6.81L3.88,6.5,1.91,10l.53.32a5.12,5.12,0,0,1,2.42,3.73H1.48a.25.25,0,0,1-.21-.12.24.24,0,0,1,0-.25L2.21,12a3.32,3.32,0,0,0-1.07-.63L.2,13.05a1.53,1.53,0,0,0,0,1.52,1.46,1.46,0,0,0,1.28.76H6.13V14.7a6.55,6.55,0,0,0-.82-3.16,6.31,6.31,0,0,0-1.73-2l.74-1.32a7.85,7.85,0,0,1,2.26,2.53,8,8,0,0,1,1,3.92v.63h3.94V14.7A12.14,12.14,0,0,0,10,8.75a11.8,11.8,0,0,0-3.7-4l1.5-2.67a.24.24,0,0,1,.42,0l6.52,11.63a.24.24,0,0,1,0,.25.24.24,0,0,1-.21.12H13c0,.43,0,.85,0,1.27h1.53a1.46,1.46,0,0,0,1.28-.76" />
</SvgIcon>
);
});
IconSentry.displayName = 'IconSentry';
export {IconSentry};
| beeftornado/sentry | src/sentry/static/sentry/app/icons/iconSentry.tsx | TypeScript | bsd-3-clause | 1,050 |
/**
* Logback: the reliable, generic, fast and flexible logging framework.
* Copyright (C) 2006-2011, QOS.ch. All rights reserved.
*
* This program and the accompanying materials are dual-licensed under
* either the terms of the Eclipse Public License v1.0 as published by
* the Eclipse Foundation
*
* or (per the licensee's choosing)
*
* under the terms of the GNU Lesser General Public License version 2.1
* as published by the Free Software Foundation.
*/
package ch.qos.logback.audit.client.joran.action;
import org.xml.sax.Attributes;
import ch.qos.logback.core.joran.action.Action;
import ch.qos.logback.core.joran.spi.ActionException;
import ch.qos.logback.core.joran.spi.InterpretationContext;
import ch.qos.logback.core.util.StatusPrinter;
public class AuditorAction extends Action {
static final String INTERNAL_DEBUG_ATTR = "debug";
boolean debugMode = false;
public void begin(InterpretationContext ec, String name, Attributes attributes) throws ActionException {
String debugAttrib = attributes.getValue(INTERNAL_DEBUG_ATTR);
if ((debugAttrib == null) || debugAttrib.equals("")
|| debugAttrib.equals("false") || debugAttrib.equals("null")) {
addInfo("Ignoring " + INTERNAL_DEBUG_ATTR + " attribute.");
} else {
debugMode = true;
}
// if ((nameAttrib == null) || nameAttrib.equals("")) {
// String errMsg = "Empty " + NAME_ATTRIBUTE + " attribute.";
// addError(errMsg);
// throw new ActionException(ActionException.SKIP_CHILDREN);
// }
// the context is appender attachable, so it is pushed on top of the stack
ec.pushObject(getContext());
}
public void end(InterpretationContext ec, String name) {
if (debugMode) {
addInfo("End of configuration.");
StatusPrinter.print(context);
}
ec.popObject();
}
}
| OBHITA/Consent2Share | ThirdParty/logback-audit/audit-client/src/main/java/ch/qos/logback/audit/client/joran/action/AuditorAction.java | Java | bsd-3-clause | 1,850 |
"""
Django settings for example_site project.
Generated by 'django-admin startproject' using Django 1.8.dev20150302062936.
For more information on this file, see
https://docs.djangoproject.com/en/dev/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/dev/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
import environ
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
env = environ.Env()
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/dev/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = "fbaa1unu0e8z5@9mm%k#+*d@iny*=-)ma2b#ymq)o9z^3%ijh)"
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
TEMPLATE_DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = (
"address",
"person",
"django.contrib.admin",
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sessions",
"django.contrib.messages",
"django.contrib.staticfiles",
)
MIDDLEWARE = (
"django.middleware.security.SecurityMiddleware",
"django.contrib.sessions.middleware.SessionMiddleware",
"django.middleware.common.CommonMiddleware",
"django.middleware.csrf.CsrfViewMiddleware",
"django.contrib.auth.middleware.AuthenticationMiddleware",
"django.contrib.messages.middleware.MessageMiddleware",
"django.middleware.clickjacking.XFrameOptionsMiddleware",
)
ROOT_URLCONF = "example_site.urls"
TEMPLATES = [
{
"BACKEND": "django.template.backends.django.DjangoTemplates",
"DIRS": [],
"APP_DIRS": True,
"OPTIONS": {
"context_processors": [
"django.template.context_processors.debug",
"django.template.context_processors.request",
"django.contrib.auth.context_processors.auth",
"django.contrib.messages.context_processors.messages",
],
},
},
]
WSGI_APPLICATION = "example_site.wsgi.application"
# Specify your Google API key as environment variable GOOGLE_API_KEY
# You may also specify it here, though be sure not to commit it to a repository
GOOGLE_API_KEY = "" # Specify your Google API key here
GOOGLE_API_KEY = os.environ.get("GOOGLE_API_KEY", GOOGLE_API_KEY)
# Database
# https://docs.djangoproject.com/en/dev/ref/settings/#databases
DATABASES = {
"default": env.db(),
}
# Password validation
# https://docs.djangoproject.com/en/2.0/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
"NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator",
},
{
"NAME": "django.contrib.auth.password_validation.MinimumLengthValidator",
},
{
"NAME": "django.contrib.auth.password_validation.CommonPasswordValidator",
},
{
"NAME": "django.contrib.auth.password_validation.NumericPasswordValidator",
},
]
# Internationalization
# https://docs.djangoproject.com/en/dev/topics/i18n/
LANGUAGE_CODE = "en-us"
TIME_ZONE = "UTC"
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/dev/howto/static-files/
STATIC_URL = "/static/"
DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField"
| furious-luke/django-address | example_site/example_site/settings.py | Python | bsd-3-clause | 3,436 |
/*
* PROJECT: Aura Operating System Development
* CONTENT: DNS Client
* PROGRAMMERS: Valentin Charbonnier <valentinbreiz@gmail.com>
*/
using Cosmos.System.Network.Config;
using Cosmos.HAL;
using System;
using System.Collections.Generic;
using System.Text;
namespace Cosmos.System.Network.IPv4.UDP.DNS
{
/// <summary>
/// DnsClient class. Used to manage the DNS connection to a server.
/// </summary>
public class DnsClient : UdpClient
{
/// <summary>
/// Domain Name query string
/// </summary>
private string queryurl;
/// <summary>
/// Create new instance of the <see cref="DnsClient"/> class.
/// </summary>
/// <exception cref="ArgumentOutOfRangeException">Thrown on fatal error (contact support).</exception>
/// <exception cref="ArgumentException">Thrown if UdpClient with localPort 53 exists.</exception>
public DnsClient() : base(53)
{
}
/// <summary>
/// Connect to client.
/// </summary>
/// <param name="dest">Destination address.</param>
public void Connect(Address address)
{
Connect(address, 53);
}
/// <summary>
/// Send DNS Ask for Domain Name string
/// </summary>
/// <param name="url">Domain Name string.</param>
public void SendAsk(string url)
{
Address source = IPConfig.FindNetwork(destination);
queryurl = url;
var askpacket = new DNSPacketAsk(source, destination, url);
OutgoingBuffer.AddPacket(askpacket);
NetworkStack.Update();
}
/// <summary>
/// Receive data
/// </summary>
/// <param name="timeout">timeout value, default 5000ms</param>
/// <returns>Address from Domain Name</returns>
/// <exception cref="InvalidOperationException">Thrown on fatal error (contact support).</exception>
public Address Receive(int timeout = 5000)
{
int second = 0;
int _deltaT = 0;
while (rxBuffer.Count < 1)
{
if (second > (timeout / 1000))
{
return null;
}
if (_deltaT != RTC.Second)
{
second++;
_deltaT = RTC.Second;
}
}
var packet = new DNSPacketAnswer(rxBuffer.Dequeue().RawData);
if ((ushort)(packet.DNSFlags & 0x0F) == (ushort)ReplyCode.OK)
{
if (packet.Queries.Count > 0 && packet.Queries[0].Name == queryurl)
{
if (packet.Answers.Count > 0 && packet.Answers[0].Address.Length == 4)
{
return new Address(packet.Answers[0].Address, 0);
}
}
}
return null;
}
}
}
| CosmosOS/Cosmos | source/Cosmos.System2/Network/IPv4/UDP/DNS/DNSClient.cs | C# | bsd-3-clause | 3,003 |
/*
* Software License Agreement (BSD License)
*
* Point Cloud Library (PCL) - www.pointclouds.org
* Copyright (c) 2009, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
#ifndef PCL_SEGMENTATION_IMPL_CONDITIONAL_EUCLIDEAN_CLUSTERING_HPP_
#define PCL_SEGMENTATION_IMPL_CONDITIONAL_EUCLIDEAN_CLUSTERING_HPP_
#include <pcl/segmentation/conditional_euclidean_clustering.h>
template<typename PointT> void
pcl::ConditionalEuclideanClustering<PointT>::segment (pcl::IndicesClusters &clusters)
{
// Prepare output (going to use push_back)
clusters.clear ();
if (extract_removed_clusters_)
{
small_clusters_->clear ();
large_clusters_->clear ();
}
// Validity checks
if (!initCompute () || input_->points.empty () || indices_->empty () || !condition_function_)
return;
// Initialize the search class
if (!searcher_)
{
if (input_->isOrganized ())
searcher_.reset (new pcl::search::OrganizedNeighbor<PointT> ());
else
searcher_.reset (new pcl::search::KdTree<PointT> ());
}
searcher_->setInputCloud (input_, indices_);
// Temp variables used by search class
std::vector<int> nn_indices;
std::vector<float> nn_distances;
// Create a bool vector of processed point indices, and initialize it to false
// Need to have it contain all possible points because radius search can not return indices into indices
std::vector<bool> processed (input_->points.size (), false);
// Process all points indexed by indices_
for (int iii = 0; iii < static_cast<int> (indices_->size ()); ++iii) // iii = input indices iterator
{
// Has this point been processed before?
if ((*indices_)[iii] == -1 || processed[(*indices_)[iii]])
continue;
// Set up a new growing cluster
std::vector<int> current_cluster;
int cii = 0; // cii = cluster indices iterator
// Add the point to the cluster
current_cluster.push_back ((*indices_)[iii]);
processed[(*indices_)[iii]] = true;
// Process the current cluster (it can be growing in size as it is being processed)
while (cii < static_cast<int> (current_cluster.size ()))
{
// Search for neighbors around the current seed point of the current cluster
if (searcher_->radiusSearch (input_->points[current_cluster[cii]], cluster_tolerance_, nn_indices, nn_distances) < 1)
{
cii++;
continue;
}
// Process the neighbors
for (int nii = 1; nii < static_cast<int> (nn_indices.size ()); ++nii) // nii = neighbor indices iterator
{
// Has this point been processed before?
if (nn_indices[nii] == -1 || processed[nn_indices[nii]])
continue;
// Validate if condition holds
if (condition_function_ (input_->points[current_cluster[cii]], input_->points[nn_indices[nii]], nn_distances[nii]))
{
// Add the point to the cluster
current_cluster.push_back (nn_indices[nii]);
processed[nn_indices[nii]] = true;
}
}
cii++;
}
// If extracting removed clusters, all clusters need to be saved, otherwise only the ones within the given cluster size range
if (extract_removed_clusters_ || (current_cluster.size () >= min_cluster_size_ && current_cluster.size () <= max_cluster_size_))
{
pcl::PointIndices pi;
pi.header = input_->header;
pi.indices.resize (current_cluster.size ());
for (int ii = 0; ii < static_cast<int> (current_cluster.size ()); ++ii) // ii = indices iterator
pi.indices[ii] = current_cluster[ii];
if (extract_removed_clusters_ && current_cluster.size () < min_cluster_size_)
small_clusters_->push_back (pi);
else if (extract_removed_clusters_ && current_cluster.size () > max_cluster_size_)
large_clusters_->push_back (pi);
else
clusters.push_back (pi);
}
}
deinitCompute ();
}
#define PCL_INSTANTIATE_ConditionalEuclideanClustering(T) template class PCL_EXPORTS pcl::ConditionalEuclideanClustering<T>;
#endif // PCL_SEGMENTATION_IMPL_CONDITIONAL_EUCLIDEAN_CLUSTERING_HPP_
| kalectro/pcl_groovy | segmentation/include/pcl/segmentation/impl/conditional_euclidean_clustering.hpp | C++ | bsd-3-clause | 5,629 |
<?php
/**
* EvaCrawler
*
* @link https://github.com/AlloVince/EvaCrawler
* @copyright Copyright (c) 2012-2013 AlloVince (http://avnpc.com/)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @author AlloVince
*/
namespace EvaCrawler\Exception;
class InvalidArgumentException extends \InvalidArgumentException implements
ExceptionInterface
{}
| iuyes/EvaCrawler | src/EvaCrawler/Exception/InvalidArgumentException.php | PHP | bsd-3-clause | 385 |
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
/* @var $this yii\web\View */
/* @var $model backend\models\VendorProductsSearch */
/* @var $form yii\widgets\ActiveForm */
?>
<div class="vendor-products-search">
<?php $form = ActiveForm::begin([
'action' => ['index'],
'method' => 'get',
]); ?>
<?= $form->field($model, 'vpid') ?>
<?= $form->field($model, 'vid') ?>
<?= $form->field($model, 'prid') ?>
<?= $form->field($model, 'unit') ?>
<?= $form->field($model, 'price') ?>
<?php // echo $form->field($model, 'crtdt') ?>
<?php // echo $form->field($model, 'crtby') ?>
<?php // echo $form->field($model, 'upddt') ?>
<?php // echo $form->field($model, 'updby') ?>
<div class="form-group">
<?= Html::submitButton(Yii::t('app', 'Search'), ['class' => 'btn btn-primary']) ?>
<?= Html::resetButton(Yii::t('app', 'Reset'), ['class' => 'btn btn-default']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
| diginmanager/digin | backend/views/vendor-products/_search.php | PHP | bsd-3-clause | 1,006 |
<?php
/**
* This file is part of PHP Mess Detector.
*
* Copyright (c) Manuel Pichler <mapi@phpmd.org>.
* All rights reserved.
*
* Licensed under BSD License
* For full copyright and license information, please see the LICENSE file.
* Redistributions of files must retain the above copyright notice.
*
* @author Manuel Pichler <mapi@phpmd.org>
* @copyright Manuel Pichler. All rights reserved.
* @license https://opensource.org/licenses/bsd-license.php BSD License
* @link http://phpmd.org/
*/
namespace PHPMD;
/**
* Test case for the parser factory class.
*
* @covers \PHPMD\ParserFactory
*/
class ParserFactoryTest extends AbstractTest
{
/**
* testFactoryConfiguresInputDirectory
*
* @return void
*/
public function testFactoryConfiguresInputDirectory()
{
$factory = new ParserFactory();
$uri = $this->createFileUri('ParserFactory/Directory');
$phpmd = $this->getMockBuilder('PHPMD\\PHPMD')->setMethods(array('getInput'))->getMock();
$phpmd->expects($this->once())
->method('getInput')
->will($this->returnValue($uri));
$ruleSet = $this->getRuleSetMock('PHPMD\\Node\\ClassNode');
$parser = $factory->create($phpmd);
$parser->addRuleSet($ruleSet);
$parser->parse($this->getReportMock(0));
}
/**
* testFactoryConfiguresInputFile
*
* @return void
*/
public function testFactoryConfiguresInputFile()
{
$factory = new ParserFactory();
$uri = $this->createFileUri('ParserFactory/File/Test.php');
$phpmd = $this->getMockBuilder('PHPMD\\PHPMD')->setMethods(array('getInput'))->getMock();
$phpmd->expects($this->once())
->method('getInput')
->will($this->returnValue($uri));
$ruleSet = $this->getRuleSetMock('PHPMD\\Node\\ClassNode');
$parser = $factory->create($phpmd);
$parser->addRuleSet($ruleSet);
$parser->parse($this->getReportMock(0));
}
/**
* testFactoryConfiguresMultipleInputDirectories
*
* @return void
*/
public function testFactoryConfiguresMultipleInputDirectories()
{
$factory = new ParserFactory();
$uri1 = $this->createFileUri('ParserFactory/File');
$uri2 = $this->createFileUri('ParserFactory/Directory');
$phpmd = $this->getMockBuilder('PHPMD\\PHPMD')->setMethods(array('getInput'))->getMock();
$phpmd->expects($this->once())
->method('getInput')
->will($this->returnValue($uri1 . ',' . $uri2));
$ruleSet = $this->getRuleSetMock('PHPMD\\Node\\ClassNode', 2);
$parser = $factory->create($phpmd);
$parser->addRuleSet($ruleSet);
$parser->parse($this->getReportMock(0));
}
/**
* testFactoryConfiguresMultipleInputFilesAndDirectories
*
* @return void
*/
public function testFactoryConfiguresMultipleInputFilesAndDirectories()
{
$factory = new ParserFactory();
$uri1 = $this->createFileUri('ParserFactory/File/Test.php');
$uri2 = $this->createFileUri('ParserFactory/Directory');
$phpmd = $this->getMockBuilder('PHPMD\\PHPMD')->setMethods(array('getInput'))->getMock();
$phpmd->expects($this->once())
->method('getInput')
->will($this->returnValue($uri1 . ',' . $uri2));
$ruleSet = $this->getRuleSetMock('PHPMD\\Node\\ClassNode', 2);
$parser = $factory->create($phpmd);
$parser->addRuleSet($ruleSet);
$parser->parse($this->getReportMock(0));
}
/**
* testFactoryConfiguresIgnorePattern
*
* @return void
*/
public function testFactoryConfiguresIgnorePattern()
{
$factory = new ParserFactory();
$uri = $this->createFileUri('ParserFactory/File/Test.php');
$phpmd = $this->getMockBuilder('PHPMD\\PHPMD')->setMethods(array('getIgnorePattern', 'getInput'))->getMock();
$phpmd->expects($this->exactly(2))
->method('getIgnorePattern')
->will($this->returnValue(array('Test')));
$phpmd->expects($this->once())
->method('getInput')
->will($this->returnValue($uri));
$factory->create($phpmd);
}
/**
* testFactoryConfiguresFileExtensions
*
* @return void
*/
public function testFactoryConfiguresFileExtensions()
{
$factory = new ParserFactory();
$uri = $this->createFileUri('ParserFactory/File/Test.php');
$phpmd = $this->getMockBuilder('PHPMD\\PHPMD')->setMethods(array('getFileExtensions', 'getInput'))->getMock();
$phpmd->expects($this->exactly(2))
->method('getFileExtensions')
->will($this->returnValue(array('.php')));
$phpmd->expects($this->once())
->method('getInput')
->will($this->returnValue($uri));
$factory->create($phpmd);
}
}
| ravage84/phpmd | src/test/php/PHPMD/ParserFactoryTest.php | PHP | bsd-3-clause | 4,955 |
require 'helper'
describe SBA do
describe ".data_city_county" do
before do
stub_request(:get, 'http://api.sba.gov/geodata/city_county_data_for_state_of/ca.json').
with().
to_return(:body => fixture('data_city_county.json'),
:headers => {'Content-Type' => 'application/json'})
end
it "should request the correct resource" do
SBA.data_city_county('ca')
a_request(:get, 'http://api.sba.gov/geodata/city_county_data_for_state_of/ca.json').
with().
should have_been_made
end
it "should return the correct results" do
test = SBA.data_city_county('ca')
test.should be_an Array
test[0]["url"].should == "http://www.ci.adelanto.ca.us/"
test[1]["url"].should == "http://ci.agoura-hills.ca.us/"
end
end
describe ".data_city" do
before do
stub_request(:get, 'http://api.sba.gov/geodata/city_data_for_state_of/ca.json').
with().
to_return(:body => fixture('data_city.json'),
:headers => {'Content-Type' => 'application/json'})
end
it "should request the correct resource" do
SBA.data_city('ca')
a_request(:get, 'http://api.sba.gov/geodata/city_data_for_state_of/ca.json').
with().
should have_been_made
end
it "should return the correct results" do
test = SBA.data_city('ca')
test.should be_an Array
test[0]["url"].should == "http://www.ci.adelanto.ca.us/"
test[1]["url"].should == "http://ci.agoura-hills.ca.us/"
end
end
describe ".data_county" do
before do
stub_request(:get, 'http://api.sba.gov/geodata/county_data_for_state_of/ca.json').
with().
to_return(:body => fixture('data_county.json'),
:headers => {'Content-Type' => 'application/json'})
end
it "should request the correct resource" do
SBA.data_county('ca')
a_request(:get, 'http://api.sba.gov/geodata/county_data_for_state_of/ca.json').
with().
should have_been_made
end
it "should return the correct results" do
test = SBA.data_county('ca')
test.should be_an Array
test[0]["url"].should == "http://www.acgov.org/"
test[1]["url"].should == "http://www.alpinecountyca.gov/"
end
end
describe ".data_specific_city" do
before do
stub_request(:get, 'http://api.sba.gov/geodata/all_data_for_city_of/seattle/wa.json').
with().
to_return(:body => fixture('data_specific_city.json'),
:headers => {'Content-Type' => 'application/json'})
end
it "should request the correct resource" do
SBA.data_specific_city('seattle', 'wa')
a_request(:get, 'http://api.sba.gov/geodata/all_data_for_city_of/seattle/wa.json').
with().
should have_been_made
end
it "should return the correct results" do
test = SBA.data_specific_city('seattle', 'wa')
test.should be_an Array
test[0]["url"].should == "http://seattle.gov/"
end
end
describe ".data_specific_county" do
before do
stub_request(:get, 'http://api.sba.gov/geodata/all_data_for_county_of/frederick%20county/md.json').
with().
to_return(:body => fixture('data_specific_county.json'),
:headers => {'Content-Type' => 'application/json'})
end
it "should request the correct resource" do
SBA.data_specific_county('frederick county', 'md')
a_request(:get, 'http://api.sba.gov/geodata/all_data_for_county_of/frederick%20county/md.json').
with().
should have_been_made
end
it "should return the correct results" do
test = SBA.data_specific_county('frederick county', 'md')
test.should be_an Array
test[0]["url"].should == "http://www.brunswickmd.gov/"
test[2]["url"].should == "http://www.emmitsburg.net/towngov/"
end
end
end
| codeforamerica/sba_ruby | spec/data_spec.rb | Ruby | bsd-3-clause | 3,892 |
var NAVTREEINDEX1 =
{
"classcrossbow_1_1basic__string.html#acd8734bee97210a1c2600ce3c56cef95":[2,0,0,5,98],
"classcrossbow_1_1basic__string.html#acdd883ec84ff972ef30486f4af448ce0":[2,0,0,5,54],
"classcrossbow_1_1basic__string.html#ace46e4e9d1a632317c6584597deaa789":[2,0,0,5,29],
"classcrossbow_1_1basic__string.html#ad16e6f0b50261ed8600afccff12e4366":[2,0,0,5,57],
"classcrossbow_1_1basic__string.html#ad63a3db7d68d6d0847bc1a99c87cfdef":[2,0,0,5,99],
"classcrossbow_1_1basic__string.html#ad6ac2ee49ffc8b09b90e723fb5a6d9d2":[2,0,0,5,55],
"classcrossbow_1_1basic__string.html#ad77aaf4d117f8a658601368d8cf68b52":[2,0,0,5,20],
"classcrossbow_1_1basic__string.html#ad87813baffb616dff0b5bd1bbc1e9f8b":[2,0,0,5,126],
"classcrossbow_1_1basic__string.html#adc313b8b1c14d50984e2361a608b8ed1":[2,0,0,5,140],
"classcrossbow_1_1basic__string.html#ade6af6157c96db8dc9a7e24f00b92fb7":[2,0,0,5,9],
"classcrossbow_1_1basic__string.html#ae7891280b4bc5aaab7fe72e846ff61f7":[2,0,0,5,4],
"classcrossbow_1_1basic__string.html#aea2798fbf5f4e47601ac0d2b02a32e4a":[2,0,0,5,15],
"classcrossbow_1_1basic__string.html#aeb9d2e3eba8c78a72bfc75ef852fbd49":[2,0,0,5,70],
"classcrossbow_1_1basic__string.html#aece4af5e1bc5fe0e4c15c37649430606":[2,0,0,5,48],
"classcrossbow_1_1basic__string.html#aef65d6573a85fe38d15b01ebda098525":[2,0,0,5,90],
"classcrossbow_1_1basic__string.html#af0c5f471f6a4b461696823cdd75ddbcf":[2,0,0,5,27],
"classcrossbow_1_1basic__string.html#af245a40b570e609be525cc8891f26012":[2,0,0,5,64],
"classcrossbow_1_1basic__string.html#af67ef102a9740f67b91259397a4449a8":[2,0,0,5,142],
"classcrossbow_1_1basic__string.html#af758b8cb6b0125ff811cfad5298c9fa1":[2,0,0,5,74],
"classcrossbow_1_1basic__string.html#af78b0cf30301287e8b08d826891e65ec":[2,0,0,5,47],
"classcrossbow_1_1basic__string.html#afcfa6dd1d2a775a87a2e5728e49fe164":[2,0,0,5,49],
"classcrossbow_1_1buffer__reader.html":[2,0,0,6],
"classcrossbow_1_1buffer__reader.html#a0311322092badb5755f40e09c076a4f5":[2,0,0,6,2],
"classcrossbow_1_1buffer__reader.html#a0e6cb5b3f061dbc638ca33bac5c5858d":[2,0,0,6,4],
"classcrossbow_1_1buffer__reader.html#a29166d11e9f6db6aa91728e9207dfe4d":[2,0,0,6,0],
"classcrossbow_1_1buffer__reader.html#a467ff4627e2ee5b109a59fd0754ad8e6":[2,0,0,6,9],
"classcrossbow_1_1buffer__reader.html#a8107671442f3ec061ada4180fc359b1d":[2,0,0,6,3],
"classcrossbow_1_1buffer__reader.html#a85b1f5f4a32d11a9aab8f895ed6acced":[2,0,0,6,1],
"classcrossbow_1_1buffer__reader.html#a90d5cf56c68db2749a0b92db0687cb69":[2,0,0,6,5],
"classcrossbow_1_1buffer__reader.html#aadb8f5bca74761999be6904e5901e729":[2,0,0,6,8],
"classcrossbow_1_1buffer__reader.html#ab5f54f33e99fb4cc4068bf00af1ee6a4":[2,0,0,6,6],
"classcrossbow_1_1buffer__reader.html#ad19a702b6c522fbf8a0f0e1757e76f88":[2,0,0,6,7],
"classcrossbow_1_1buffer__writer.html":[2,0,0,7],
"classcrossbow_1_1buffer__writer.html#a02fee8fbba1780aeae8a89ef5f550712":[2,0,0,7,11],
"classcrossbow_1_1buffer__writer.html#a327571c57616830b085e11d6201df43d":[2,0,0,7,2],
"classcrossbow_1_1buffer__writer.html#a44f69080102aabfcecd43577bd11fe33":[2,0,0,7,5],
"classcrossbow_1_1buffer__writer.html#a644569934c908f46ba1419f6626d9137":[2,0,0,7,6],
"classcrossbow_1_1buffer__writer.html#a75d4edc470cac391e78966d79ba11a7a":[2,0,0,7,3],
"classcrossbow_1_1buffer__writer.html#a85982e17059614d924a7963f74e78144":[2,0,0,7,7],
"classcrossbow_1_1buffer__writer.html#a98db3b5c32874c80ee0b9b050da9dabd":[2,0,0,7,10],
"classcrossbow_1_1buffer__writer.html#a9917655354d206ab34ea957374f31603":[2,0,0,7,8],
"classcrossbow_1_1buffer__writer.html#ac409737cb105a801bf11e6d65c192afb":[2,0,0,7,1],
"classcrossbow_1_1buffer__writer.html#ad50ec2a8bd9da6008005961bd6543171":[2,0,0,7,0],
"classcrossbow_1_1buffer__writer.html#ad9d132389923980304a4a59f42c0a16b":[2,0,0,7,9],
"classcrossbow_1_1buffer__writer.html#afeed84606701f16f110a722e0234418f":[2,0,0,7,4],
"classcrossbow_1_1concurrent__map.html":[2,0,0,11],
"classcrossbow_1_1concurrent__map.html#a16b39293ce701d458bf2871ea4b4f01c":[2,0,0,11,22],
"classcrossbow_1_1concurrent__map.html#a1d63dc57f6f83fb804dc75986a22a344":[2,0,0,11,25],
"classcrossbow_1_1concurrent__map.html#a22b21ad0bcdbf839ead27b330d595d3d":[2,0,0,11,3],
"classcrossbow_1_1concurrent__map.html#a2970ad2f0b05d52f8eeee3ddee09babf":[2,0,0,11,20],
"classcrossbow_1_1concurrent__map.html#a29f81acb26bf290f3d4ffc85c02e7d59":[2,0,0,11,5],
"classcrossbow_1_1concurrent__map.html#a2e42a2a7fc760109cfa183a0caa84267":[2,0,0,11,8],
"classcrossbow_1_1concurrent__map.html#a4aff5cb5afde326b2e7c0b6d96b5fe8b":[2,0,0,11,1],
"classcrossbow_1_1concurrent__map.html#a6778df3936e33f2037349057f0608157":[2,0,0,11,6],
"classcrossbow_1_1concurrent__map.html#a7108c78b48e525ba42aef103c4142c05":[2,0,0,11,24],
"classcrossbow_1_1concurrent__map.html#a762722da9390d9b385ee0d848c5309c6":[2,0,0,11,18],
"classcrossbow_1_1concurrent__map.html#a7f43b025b95e94a8ca3023ca79a150ae":[2,0,0,11,12],
"classcrossbow_1_1concurrent__map.html#a8036290fd74f104e9fff96e47b779315":[2,0,0,11,21],
"classcrossbow_1_1concurrent__map.html#a8c2d2b360f588fcd0aa78a550ad5c4ec":[2,0,0,11,13],
"classcrossbow_1_1concurrent__map.html#a9242d6f7770aac702b24f31726e6ddcf":[2,0,0,11,2],
"classcrossbow_1_1concurrent__map.html#a955faffc552dcb84f624446228afd94b":[2,0,0,11,14],
"classcrossbow_1_1concurrent__map.html#ab30f8ac027dea27ad7b9e5c3137094d3":[2,0,0,11,7],
"classcrossbow_1_1concurrent__map.html#abd36c628e35fc20ce4a918126654a213":[2,0,0,11,17],
"classcrossbow_1_1concurrent__map.html#ac6c87af8eeb7626a14a2b64e7026a083":[2,0,0,11,10],
"classcrossbow_1_1concurrent__map.html#acefeeb56129aaa7ee2ea004843e4aabf":[2,0,0,11,19],
"classcrossbow_1_1concurrent__map.html#ad8b4538fe8cda1ef35ad562f511e9efa":[2,0,0,11,9],
"classcrossbow_1_1concurrent__map.html#ae6eb1248c28d1c9336b5738a4fe72aa9":[2,0,0,11,11],
"classcrossbow_1_1concurrent__map.html#ae812f9cf3397e663625ec0fad7c8c86f":[2,0,0,11,16],
"classcrossbow_1_1concurrent__map.html#af1ab12ec31ecb0a68256d679a47cb4eb":[2,0,0,11,4],
"classcrossbow_1_1concurrent__map.html#af6ae89314c3222400eea9eb4cdee069b":[2,0,0,11,15],
"classcrossbow_1_1concurrent__map.html#af7628f2f6957354e4972be60d0d5b332":[2,0,0,11,23],
"classcrossbow_1_1fixed__size__stack.html":[2,0,0,32],
"classcrossbow_1_1fixed__size__stack.html#a14d9917f053bcebda504255f176b8a06":[2,0,0,32,3],
"classcrossbow_1_1fixed__size__stack.html#a3ddaa1c4ea4e8f28a4679678d971a71e":[2,0,0,32,4],
"classcrossbow_1_1fixed__size__stack.html#a40eb1163de07825bd86ad486a9722fd9":[2,0,0,32,0],
"classcrossbow_1_1fixed__size__stack.html#a5bc4f1e3568ce5104b3eb039dfbefc7c":[2,0,0,32,2],
"classcrossbow_1_1fixed__size__stack.html#aabf178e9876c6860b4aecc7649f4b60d":[2,0,0,32,1],
"classcrossbow_1_1has__visit__helper_1_1_helper.html":[2,0,0,34,2],
"classcrossbow_1_1has__visit__helper_1_1no.html":[2,0,0,34,3],
"classcrossbow_1_1has__visit__helper_1_1yes.html":[2,0,0,34,4],
"classcrossbow_1_1infinio_1_1_allocated_memory_region.html":[2,0,0,1,1],
"classcrossbow_1_1infinio_1_1_allocated_memory_region.html#a2d425bffb81219cc4c11aa2f9758e810":[2,0,0,1,1,2],
"classcrossbow_1_1infinio_1_1_allocated_memory_region.html#a417929fbf0872434a01b777f97103f6a":[2,0,0,1,1,3],
"classcrossbow_1_1infinio_1_1_allocated_memory_region.html#a6c77463fbabc4eb9c4e5262289b8eac6":[2,0,0,1,1,5],
"classcrossbow_1_1infinio_1_1_allocated_memory_region.html#a8b42ee82862ebc88432e43428516da87":[2,0,0,1,1,9],
"classcrossbow_1_1infinio_1_1_allocated_memory_region.html#aa0bfe3a7b4a5ab6ae6533ecfc9445f31":[2,0,0,1,1,8],
"classcrossbow_1_1infinio_1_1_allocated_memory_region.html#aa1043cd6d2c263260b675063046db35b":[2,0,0,1,1,11],
"classcrossbow_1_1infinio_1_1_allocated_memory_region.html#aa98096c46c7836e83caab551defc94a0":[2,0,0,1,1,1],
"classcrossbow_1_1infinio_1_1_allocated_memory_region.html#ab0e1fc475690b1a166d579e266e99da5":[2,0,0,1,1,0],
"classcrossbow_1_1infinio_1_1_allocated_memory_region.html#ab60ac89e77b318de3842165cc64b092f":[2,0,0,1,1,7],
"classcrossbow_1_1infinio_1_1_allocated_memory_region.html#ad1c6c25da2916be0fc06a06b3852c8d8":[2,0,0,1,1,6],
"classcrossbow_1_1infinio_1_1_allocated_memory_region.html#aef6d4c2dc97d3d8d027350e2ce746540":[2,0,0,1,1,4],
"classcrossbow_1_1infinio_1_1_allocated_memory_region.html#afc7709ffd84a4a8abb76ad6554d20aee":[2,0,0,1,1,10],
"classcrossbow_1_1infinio_1_1_batching_message_socket.html":[2,0,0,1,2],
"classcrossbow_1_1infinio_1_1_batching_message_socket.html#a2336a845d9a48a6d6fc6919f308dcb9c":[2,0,0,1,2,9],
"classcrossbow_1_1infinio_1_1_batching_message_socket.html#a285f9e59c4591d23b0451b4817454d30":[2,0,0,1,2,1],
"classcrossbow_1_1infinio_1_1_batching_message_socket.html#a4aa0f87f34b11f6d8b28ca5933b24976":[2,0,0,1,2,7],
"classcrossbow_1_1infinio_1_1_batching_message_socket.html#a5e62cd53bf6e5d460d69d6ce61b3a01a":[2,0,0,1,2,4],
"classcrossbow_1_1infinio_1_1_batching_message_socket.html#a6bfd7b2d9d5871cad379425d8050ac93":[2,0,0,1,2,6],
"classcrossbow_1_1infinio_1_1_batching_message_socket.html#a6e7575aa9d9f21ac5dd147a235d05c46":[2,0,0,1,2,5],
"classcrossbow_1_1infinio_1_1_batching_message_socket.html#a961d1ae24f991b02566079d51872b3ab":[2,0,0,1,2,2],
"classcrossbow_1_1infinio_1_1_batching_message_socket.html#a9c8b1fbab0e49c3dedff2d707a3f92d2":[2,0,0,1,2,3],
"classcrossbow_1_1infinio_1_1_batching_message_socket.html#abd82278f6622efb0f0f4d7a71e2d94a3":[2,0,0,1,2,0],
"classcrossbow_1_1infinio_1_1_batching_message_socket.html#abd82278f6622efb0f0f4d7a71e2d94a3a99c8ce56e7ab246445d3b134724428f3":[2,0,0,1,2,0,0],
"classcrossbow_1_1infinio_1_1_batching_message_socket.html#abd82278f6622efb0f0f4d7a71e2d94a3a9a14f95e151eec641316e7c784ce832d":[2,0,0,1,2,0,2],
"classcrossbow_1_1infinio_1_1_batching_message_socket.html#abd82278f6622efb0f0f4d7a71e2d94a3aa5afd6edd5336d91316964e493936858":[2,0,0,1,2,0,3],
"classcrossbow_1_1infinio_1_1_batching_message_socket.html#abd82278f6622efb0f0f4d7a71e2d94a3ab9984206799a7f9fe4bd1b6c18db8112":[2,0,0,1,2,0,1],
"classcrossbow_1_1infinio_1_1_batching_message_socket.html#adb2b4ebd181dad63d354bda030f51d01":[2,0,0,1,2,10],
"classcrossbow_1_1infinio_1_1_batching_message_socket.html#af435d48bba4c96fae56b165c830e6c01":[2,0,0,1,2,8],
"classcrossbow_1_1infinio_1_1_condition_variable.html":[2,0,0,1,3],
"classcrossbow_1_1infinio_1_1_condition_variable.html#a0466a9ace7b5dc9689bb88a2ff6162f9":[2,0,0,1,3,0],
"classcrossbow_1_1infinio_1_1_condition_variable.html#a2ccd1a70e6e62e881e26afa522371cf8":[2,0,0,1,3,4],
"classcrossbow_1_1infinio_1_1_condition_variable.html#a5a888f752f40f96491544a1dd3682297":[2,0,0,1,3,2],
"classcrossbow_1_1infinio_1_1_condition_variable.html#aa888738b4853109df6d6b4afb068c5b6":[2,0,0,1,3,3],
"classcrossbow_1_1infinio_1_1_condition_variable.html#af11132fff713b18625a039798d8fea08":[2,0,0,1,3,1],
"classcrossbow_1_1infinio_1_1_endpoint.html":[2,0,0,1,4],
"classcrossbow_1_1infinio_1_1_endpoint.html#a08809a6515f8adf722007a348b9909ec":[2,0,0,1,4,4],
"classcrossbow_1_1infinio_1_1_endpoint.html#a43b1831cfe5abf5038b7a14c3af5efac":[2,0,0,1,4,6],
"classcrossbow_1_1infinio_1_1_endpoint.html#a5017f6423ec7837eb8aa5f2479c6eadc":[2,0,0,1,4,2],
"classcrossbow_1_1infinio_1_1_endpoint.html#a69614f5d8b5c2ee91f0065bcb9ae6695":[2,0,0,1,4,3],
"classcrossbow_1_1infinio_1_1_endpoint.html#a7ae5515ae3f217c6ee84a243b332ffc1":[2,0,0,1,4,8],
"classcrossbow_1_1infinio_1_1_endpoint.html#aaafa8e6ad5325313d254f34c60a9622a":[2,0,0,1,4,0],
"classcrossbow_1_1infinio_1_1_endpoint.html#ab6a88eda3cd520fb70bdb6bf56b46fa4":[2,0,0,1,4,5],
"classcrossbow_1_1infinio_1_1_endpoint.html#ac2dbe6b6c6cfd68d070a0e9771656e2c":[2,0,0,1,4,1],
"classcrossbow_1_1infinio_1_1_endpoint.html#afb9122923a2423a95cf611901446cd89":[2,0,0,1,4,7],
"classcrossbow_1_1infinio_1_1_event_poll.html":[2,0,0,1,5],
"classcrossbow_1_1infinio_1_1_event_poll.html#a1680db113341250c64f51b3af14ca578":[2,0,0,1,5,1],
"classcrossbow_1_1infinio_1_1_event_poll.html#a5531fb00028eb79adba7b678bab7e3d6":[2,0,0,1,5,0],
"classcrossbow_1_1infinio_1_1_event_poll.html#ae4ce2ed048bafc1578df635c38c63259":[2,0,0,1,5,2],
"classcrossbow_1_1infinio_1_1_event_processor.html":[2,0,0,1,6],
"classcrossbow_1_1infinio_1_1_event_processor.html#a286824679461f308c2e7bafdc194b145":[2,0,0,1,6,2],
"classcrossbow_1_1infinio_1_1_event_processor.html#a5f61a3d62361a5647a4b5155ccdbaf85":[2,0,0,1,6,4],
"classcrossbow_1_1infinio_1_1_event_processor.html#a6e784628d548f72f5874570bfc42839c":[2,0,0,1,6,1],
"classcrossbow_1_1infinio_1_1_event_processor.html#a8d948b3d64f0ce7c73d973631e54bc71":[2,0,0,1,6,5],
"classcrossbow_1_1infinio_1_1_event_processor.html#ac62240d70c4fe864e1f32fa4eefa73b6":[2,0,0,1,6,0],
"classcrossbow_1_1infinio_1_1_event_processor.html#aeda672519fde10112294b27d8ea357f2":[2,0,0,1,6,3],
"classcrossbow_1_1infinio_1_1_fiber.html":[2,0,0,1,7],
"classcrossbow_1_1infinio_1_1_fiber.html#a0de20c21c002560b0ff83362b9f451de":[2,0,0,1,7,2],
"classcrossbow_1_1infinio_1_1_fiber.html#a506496c44cb8cdd9608ded88485f7fbc":[2,0,0,1,7,0],
"classcrossbow_1_1infinio_1_1_fiber.html#a6bd47edaa664588f959b279f988e96ca":[2,0,0,1,7,3],
"classcrossbow_1_1infinio_1_1_fiber.html#a94c9b20085e6a1d1df99835efef4578a":[2,0,0,1,7,6],
"classcrossbow_1_1infinio_1_1_fiber.html#ac0edcfc882617fb8851e0c4a7d44f125":[2,0,0,1,7,4],
"classcrossbow_1_1infinio_1_1_fiber.html#ac17b789298aa9f48f7b4fffd928c1886":[2,0,0,1,7,7],
"classcrossbow_1_1infinio_1_1_fiber.html#aca60a5d8c78524d5d6e65150a2656861":[2,0,0,1,7,8],
"classcrossbow_1_1infinio_1_1_fiber.html#ad209b959b4cd1598bd87b34f032852e7":[2,0,0,1,7,1],
"classcrossbow_1_1infinio_1_1_fiber.html#af11c411aaf847d0a34ad4d2df03d9072":[2,0,0,1,7,9],
"classcrossbow_1_1infinio_1_1_fiber.html#af5f8dd8683fb107f28a0929c11127c24":[2,0,0,1,7,5],
"classcrossbow_1_1infinio_1_1_infiniband_acceptor_handler.html":[2,0,0,1,8],
"classcrossbow_1_1infinio_1_1_infiniband_acceptor_handler.html#a1e48121bbb7ae989e3287191ca6fd45e":[2,0,0,1,8,0],
"classcrossbow_1_1infinio_1_1_infiniband_acceptor_handler.html#a6e237853121016b1558a33ef41f755b4":[2,0,0,1,8,1],
"classcrossbow_1_1infinio_1_1_infiniband_acceptor_impl.html":[2,0,0,1,9],
"classcrossbow_1_1infinio_1_1_infiniband_acceptor_impl.html#a65448cadeea713a7bcfea68f74f9752c":[2,0,0,1,9,0],
"classcrossbow_1_1infinio_1_1_infiniband_acceptor_impl.html#a88c9db079e85cae51ffc369aa9bbf922":[2,0,0,1,9,2],
"classcrossbow_1_1infinio_1_1_infiniband_acceptor_impl.html#a993b817f0ced3175af08449a64ee38b0":[2,0,0,1,9,1],
"classcrossbow_1_1infinio_1_1_infiniband_base_socket.html":[2,0,0,1,10],
"classcrossbow_1_1infinio_1_1_infiniband_base_socket.html#a05430bdd275d20fe59c3d02297051cb0":[2,0,0,1,10,1],
"classcrossbow_1_1infinio_1_1_infiniband_base_socket.html#a3022a638aaccff4755b7980e5e81541e":[2,0,0,1,10,8],
"classcrossbow_1_1infinio_1_1_infiniband_base_socket.html#a40b227137fc8cb90a1c321968a84067f":[2,0,0,1,10,2],
"classcrossbow_1_1infinio_1_1_infiniband_base_socket.html#a6f63321b9c926de4e2c0ebc2088ea4cb":[2,0,0,1,10,3],
"classcrossbow_1_1infinio_1_1_infiniband_base_socket.html#a9ac6132248f29fc85a73726578826d28":[2,0,0,1,10,5],
"classcrossbow_1_1infinio_1_1_infiniband_base_socket.html#a9e010b08158bf6083104f18ef0a3071b":[2,0,0,1,10,7],
"classcrossbow_1_1infinio_1_1_infiniband_base_socket.html#ac0bb5aa878e19ce99036ea08ca1e42e8":[2,0,0,1,10,9],
"classcrossbow_1_1infinio_1_1_infiniband_base_socket.html#acf360f73d57a8f560f536e721aad9e1a":[2,0,0,1,10,0],
"classcrossbow_1_1infinio_1_1_infiniband_base_socket.html#aedb40bfa0059fd3d18829563e4a8447d":[2,0,0,1,10,4],
"classcrossbow_1_1infinio_1_1_infiniband_base_socket.html#afd7818f5d086bead86cf28343e9ec1b5":[2,0,0,1,10,6],
"classcrossbow_1_1infinio_1_1_infiniband_buffer.html":[2,0,0,1,11],
"classcrossbow_1_1infinio_1_1_infiniband_buffer.html#a2c8a3464fa011e6cf01f4647a22a57fa":[2,0,0,1,11,6],
"classcrossbow_1_1infinio_1_1_infiniband_buffer.html#a4c57e479471d68da75dc9b2284d8ad0c":[2,0,0,1,11,7],
"classcrossbow_1_1infinio_1_1_infiniband_buffer.html#a5a313da18f35c38898f6bbfb3058fa2d":[2,0,0,1,11,3],
"classcrossbow_1_1infinio_1_1_infiniband_buffer.html#a77813f81944e046fb53d6bbd5c0d3d8a":[2,0,0,1,11,5],
"classcrossbow_1_1infinio_1_1_infiniband_buffer.html#a9203219408532042c44d3d9cc6681aad":[2,0,0,1,11,2],
"classcrossbow_1_1infinio_1_1_infiniband_buffer.html#aa92974e2bc7cb90c13fba8f27096836f":[2,0,0,1,11,1],
"classcrossbow_1_1infinio_1_1_infiniband_buffer.html#aa93a1d14bc0cebf266b1fc1a939c55fc":[2,0,0,1,11,4],
"classcrossbow_1_1infinio_1_1_infiniband_buffer.html#ac64e00a7100dd224dbac6f04493ed4d1":[2,0,0,1,11,0],
"classcrossbow_1_1infinio_1_1_infiniband_buffer.html#acfa900a1ac4d204c43044595c75ee90c":[2,0,0,1,11,8],
"classcrossbow_1_1infinio_1_1_infiniband_buffer.html#aea5dd4c74a61cf36b4526ba02f4510d1":[2,0,0,1,11,9],
"classcrossbow_1_1infinio_1_1_infiniband_processor.html":[2,0,0,1,13],
"classcrossbow_1_1infinio_1_1_infiniband_processor.html#a0def6dc4dcfd56dfae12e0b6898a4e45":[2,0,0,1,13,5],
"classcrossbow_1_1infinio_1_1_infiniband_processor.html#a511ed6fa9672d47cff3d22a922663db7":[2,0,0,1,13,1],
"classcrossbow_1_1infinio_1_1_infiniband_processor.html#a67973d0611959bb0eaa76e2fdf40b759":[2,0,0,1,13,0],
"classcrossbow_1_1infinio_1_1_infiniband_processor.html#a67dd6490bc36ae8e38d7b6dfcd43c44b":[2,0,0,1,13,7],
"classcrossbow_1_1infinio_1_1_infiniband_processor.html#a72b56531535b0b55acd59f47da8e26c9":[2,0,0,1,13,4],
"classcrossbow_1_1infinio_1_1_infiniband_processor.html#a87a616a1350a043ee7172754e2521db8":[2,0,0,1,13,8],
"classcrossbow_1_1infinio_1_1_infiniband_processor.html#a9f3e7af6e4891856c7b52486ccba0f14":[2,0,0,1,13,2],
"classcrossbow_1_1infinio_1_1_infiniband_processor.html#aa2f199cc2d367a8ce968d554edbe42ab":[2,0,0,1,13,3],
"classcrossbow_1_1infinio_1_1_infiniband_processor.html#abfafb2e53a7d67a761cd7b12d3964888":[2,0,0,1,13,6],
"classcrossbow_1_1infinio_1_1_infiniband_service.html":[2,0,0,1,14],
"classcrossbow_1_1infinio_1_1_infiniband_service.html#a0f2fa6b12384e868943b980886159ea4":[2,0,0,1,14,6],
"classcrossbow_1_1infinio_1_1_infiniband_service.html#a379140a90244c1a1dcbedbbb2640b821":[2,0,0,1,14,10],
"classcrossbow_1_1infinio_1_1_infiniband_service.html#a3eddc3966b19f7a81218542791918c85":[2,0,0,1,14,0],
"classcrossbow_1_1infinio_1_1_infiniband_service.html#a45d1653b33fe2a9f17183086a503013e":[2,0,0,1,14,11],
"classcrossbow_1_1infinio_1_1_infiniband_service.html#a58deaaba80dc7aab9bfb01da12b7422d":[2,0,0,1,14,1],
"classcrossbow_1_1infinio_1_1_infiniband_service.html#a5a095f0a03ac2371ca54df7d10905392":[2,0,0,1,14,9],
"classcrossbow_1_1infinio_1_1_infiniband_service.html#a6f08328cd35740fc0be8d38c38abe04b":[2,0,0,1,14,5],
"classcrossbow_1_1infinio_1_1_infiniband_service.html#a6f113932afef04bb0df87be7506d2696":[2,0,0,1,14,4],
"classcrossbow_1_1infinio_1_1_infiniband_service.html#a71337e376f02c064736007944599794a":[2,0,0,1,14,8],
"classcrossbow_1_1infinio_1_1_infiniband_service.html#a8235e94e97c111ac19dafd746a550b0c":[2,0,0,1,14,3],
"classcrossbow_1_1infinio_1_1_infiniband_service.html#a8448f4aeb3302513a7e5a8e64cf3810a":[2,0,0,1,14,2],
"classcrossbow_1_1infinio_1_1_infiniband_service.html#ae0df2e571f013aa6812df30a95efe065":[2,0,0,1,14,7],
"classcrossbow_1_1infinio_1_1_infiniband_socket_handler.html":[2,0,0,1,15],
"classcrossbow_1_1infinio_1_1_infiniband_socket_handler.html#a16b55c9228eef44981a9b8547ffcc365":[2,0,0,1,15,1],
"classcrossbow_1_1infinio_1_1_infiniband_socket_handler.html#a47d531238f54e126f32c05f0a82a6917":[2,0,0,1,15,8],
"classcrossbow_1_1infinio_1_1_infiniband_socket_handler.html#a4b01b6f118f4b9552d1d79bdfd6c5c0a":[2,0,0,1,15,6],
"classcrossbow_1_1infinio_1_1_infiniband_socket_handler.html#a589d1aac79f52e033cac8376f5b1e735":[2,0,0,1,15,2],
"classcrossbow_1_1infinio_1_1_infiniband_socket_handler.html#a6d2cf3e35f6678fc1f0460975f8efba9":[2,0,0,1,15,0],
"classcrossbow_1_1infinio_1_1_infiniband_socket_handler.html#a7b5407f0a1d56c56fb58167bad6a37fd":[2,0,0,1,15,3],
"classcrossbow_1_1infinio_1_1_infiniband_socket_handler.html#a8039776c809c6a35556227e89b4cb6fa":[2,0,0,1,15,5],
"classcrossbow_1_1infinio_1_1_infiniband_socket_handler.html#aa65c1a89a1b864bde1f28f03b90309c9":[2,0,0,1,15,7],
"classcrossbow_1_1infinio_1_1_infiniband_socket_handler.html#ac666313a5638dcf55887f9fbc55cb0e9":[2,0,0,1,15,4],
"classcrossbow_1_1infinio_1_1_infiniband_socket_impl.html":[2,0,0,1,16],
"classcrossbow_1_1infinio_1_1_infiniband_socket_impl.html#a043e82e717264e649e16e2c1f5ace5eb":[2,0,0,1,16,8],
"classcrossbow_1_1infinio_1_1_infiniband_socket_impl.html#a07d9f91ef930b1ee24a372d5a8791dc3":[2,0,0,1,16,9],
"classcrossbow_1_1infinio_1_1_infiniband_socket_impl.html#a0c71b98a6e691a1d8107d90df5ebf5ac":[2,0,0,1,16,3],
"classcrossbow_1_1infinio_1_1_infiniband_socket_impl.html#a29cc9f8efc14f7bd870300222879e461":[2,0,0,1,16,0],
"classcrossbow_1_1infinio_1_1_infiniband_socket_impl.html#a30a1a54c4425a5e61aa4259e4bf9e3f6":[2,0,0,1,16,15],
"classcrossbow_1_1infinio_1_1_infiniband_socket_impl.html#a4656209e36dfb474720c767aa568dd1a":[2,0,0,1,16,16],
"classcrossbow_1_1infinio_1_1_infiniband_socket_impl.html#a496845299b933d3f855f59ad16ad6fda":[2,0,0,1,16,4],
"classcrossbow_1_1infinio_1_1_infiniband_socket_impl.html#a49c52b28f29bf89bc704e8ac4f18e204":[2,0,0,1,16,19],
"classcrossbow_1_1infinio_1_1_infiniband_socket_impl.html#a49e07459471d21456e5f254501697282":[2,0,0,1,16,17],
"classcrossbow_1_1infinio_1_1_infiniband_socket_impl.html#a5293f9d12add24d69720ea791ef5326b":[2,0,0,1,16,13],
"classcrossbow_1_1infinio_1_1_infiniband_socket_impl.html#a567d5f1ac03388b208029b1f7d642cde":[2,0,0,1,16,14],
"classcrossbow_1_1infinio_1_1_infiniband_socket_impl.html#a5a1c5b02aa5835fee381c0ec356f64c9":[2,0,0,1,16,5],
"classcrossbow_1_1infinio_1_1_infiniband_socket_impl.html#a68b152d53045d60de2b13434c45988ec":[2,0,0,1,16,12],
"classcrossbow_1_1infinio_1_1_infiniband_socket_impl.html#a70c3d47e83e2524f6006672583303521":[2,0,0,1,16,6],
"classcrossbow_1_1infinio_1_1_infiniband_socket_impl.html#a7efedc602e7cd90f6c0cc95f4fdc2930":[2,0,0,1,16,24],
"classcrossbow_1_1infinio_1_1_infiniband_socket_impl.html#a7f9ffd8a77abdaecc9674134f38235ba":[2,0,0,1,16,21],
"classcrossbow_1_1infinio_1_1_infiniband_socket_impl.html#a808abdff97bf8cb7b8d0b490bc230d55":[2,0,0,1,16,7],
"classcrossbow_1_1infinio_1_1_infiniband_socket_impl.html#a88c9db079e85cae51ffc369aa9bbf922":[2,0,0,1,16,27],
"classcrossbow_1_1infinio_1_1_infiniband_socket_impl.html#a8bb0a02cdff8ebf0bf3d99c73059586c":[2,0,0,1,16,26],
"classcrossbow_1_1infinio_1_1_infiniband_socket_impl.html#a96d1d2d25f040f5941eb9fac6d125912":[2,0,0,1,16,10],
"classcrossbow_1_1infinio_1_1_infiniband_socket_impl.html#a98922de863d46b1e583705c58e1b06f8":[2,0,0,1,16,1],
"classcrossbow_1_1infinio_1_1_infiniband_socket_impl.html#a9a5f8586f4f12eeb7cecb57ec2e2876f":[2,0,0,1,16,2],
"classcrossbow_1_1infinio_1_1_infiniband_socket_impl.html#aaada3cfae17909d95bb02542ad79070f":[2,0,0,1,16,11],
"classcrossbow_1_1infinio_1_1_infiniband_socket_impl.html#ae025a52c29dd5b612c584b12624f1b1e":[2,0,0,1,16,18],
"classcrossbow_1_1infinio_1_1_infiniband_socket_impl.html#ae05b8b5ec59d64c42a12a4f78ef025d2":[2,0,0,1,16,23],
"classcrossbow_1_1infinio_1_1_infiniband_socket_impl.html#ae733bbdbcf7fee16b0ecf22be2522dfe":[2,0,0,1,16,20],
"classcrossbow_1_1infinio_1_1_infiniband_socket_impl.html#aea695116fe44c5265d139beb3bc9e7b8":[2,0,0,1,16,25],
"classcrossbow_1_1infinio_1_1_infiniband_socket_impl.html#aedc62fc168abbb4cd3b8a63f59527726":[2,0,0,1,16,22],
"classcrossbow_1_1infinio_1_1_local_memory_region.html":[2,0,0,1,17],
"classcrossbow_1_1infinio_1_1_local_memory_region.html#a0593e2c7ea6de96b5d8ae94e1b7b66e0":[2,0,0,1,17,3],
"classcrossbow_1_1infinio_1_1_local_memory_region.html#a124c03ac42f2c1e82a9d54d0c6f647b3":[2,0,0,1,17,5],
"classcrossbow_1_1infinio_1_1_local_memory_region.html#a41fc8d4df7494ac55c11be96fff4d019":[2,0,0,1,17,8],
"classcrossbow_1_1infinio_1_1_local_memory_region.html#a4534a746809145b19e5519d90ffc8dd8":[2,0,0,1,17,6],
"classcrossbow_1_1infinio_1_1_local_memory_region.html#a4b285b29b94633ea0b975998f6f80f42":[2,0,0,1,17,7],
"classcrossbow_1_1infinio_1_1_local_memory_region.html#a541d7af8c9dd46e6f7c38216cc89896d":[2,0,0,1,17,0],
"classcrossbow_1_1infinio_1_1_local_memory_region.html#a8f555b1680fd818d972ff2ed406f8c56":[2,0,0,1,17,9],
"classcrossbow_1_1infinio_1_1_local_memory_region.html#a95b049f4f20954a1bca106719bd145e2":[2,0,0,1,17,4],
"classcrossbow_1_1infinio_1_1_local_memory_region.html#a96dbe592a5daef58e233066be2d0436c":[2,0,0,1,17,2],
"classcrossbow_1_1infinio_1_1_local_memory_region.html#abcf24e06d1c8c090b148daf7a766827e":[2,0,0,1,17,11],
"classcrossbow_1_1infinio_1_1_local_memory_region.html#aca3c2f33d23d158b65131fe5dd23f6ec":[2,0,0,1,17,10]
};
| tellproject/homepage-generator | api/navtreeindex1.js | JavaScript | bsd-3-clause | 24,314 |
var Backbone = require('backbone'),
$ = require('jquery'),
lang = require('../lang'),
template = require('../templates/nav.hbs')
module.exports = Backbone.View.extend({
events: {
'click .js-nav': 'navigate'
},
initialize: function (options) {
this.$el.html(template({
name: window.app.name,
lang: lang
}))
this.$navLis = this.$('.js-li')
this.setActivePage()
this.listenTo(options.router, 'route', this.setActivePage)
return this
},
setActivePage: function () {
var pathname = window.location.pathname
this.$navLis.removeClass('active')
this.$('.js-nav').each(function (index, value) {
var $this = $(this)
var href = $this.attr('href')
if(href === '/') {
if(pathname === '/')
$this.parent().addClass('active')
}
else {
if(href && pathname.match(new RegExp('^' + href.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&')))) {
$this.parent().addClass('active')
}
}
})
},
navigate: function (e) {
e.preventDefault()
this.$('.navbar-collapse').removeClass('in')
Backbone.history.navigate($(e.target).attr('href'), {
trigger: true,
replace: false
})
}
})
| akileh/fermpi | front/views/nav.js | JavaScript | bsd-3-clause | 1,413 |
using System.Threading.Tasks;
using OrchardCore.Deployment;
using OrchardCore.DisplayManagement.Handlers;
using OrchardCore.DisplayManagement.ModelBinding;
using OrchardCore.DisplayManagement.Views;
using OrchardCore.Templates.ViewModels;
namespace OrchardCore.Templates.Deployment
{
public class AllAdminTemplatesDeploymentStepDriver : DisplayDriver<DeploymentStep, AllAdminTemplatesDeploymentStep>
{
public override IDisplayResult Display(AllAdminTemplatesDeploymentStep step)
{
return
Combine(
View("AllAdminTemplatesDeploymentStep_Summary", step).Location("Summary", "Content"),
View("AllAdminTemplatesDeploymentStep_Thumbnail", step).Location("Thumbnail", "Content")
);
}
public override IDisplayResult Edit(AllAdminTemplatesDeploymentStep step)
{
return Initialize<AllAdminTemplatesDeploymentStepViewModel>("AllAdminTemplatesDeploymentStep_Fields_Edit", model => model.ExportAsFiles = step.ExportAsFiles).Location("Content");
}
public override async Task<IDisplayResult> UpdateAsync(AllAdminTemplatesDeploymentStep step, IUpdateModel updater)
{
await updater.TryUpdateModelAsync(step, Prefix, x => x.ExportAsFiles);
return Edit(step);
}
}
}
| xkproject/Orchard2 | src/OrchardCore.Modules/OrchardCore.Templates/Deployment/AllAdminTemplatesDeploymentStepDriver.cs | C# | bsd-3-clause | 1,354 |
<?php
namespace common\models\db;
use Yii;
use yii\base\NotSupportedException;
use yii\db\ActiveRecord;
use yii\web\IdentityInterface;
/**
* This is the model class for table "users".
*
* @property integer $id
* @property string $email
* @property string $password
* @property string $name
* @property integer $user_type
* @property integer $created_at
* @property integer $updated_at
* @property string $activate_key
* @property integer $status
* @property string $auth_key
* @property Services[] $services
*/
class User extends ActiveRecord implements IdentityInterface
{
const STATUS_DELETED = 0;
const STATUS_ACTIVE = 10;
/**
* @inheritdoc
*/
public static function tableName()
{
return '{{%user}}';
}
/**
* @inheritdoc
*/
public function rules()
{
return [
[['email', 'password', 'name'], 'required'],
[['email'], 'string', 'max' => 80],
[['password'], 'string', 'max' => 128],
[['name'], 'string', 'max' => 40],
[['user_type'], 'safe']
];
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'id' => 'ID',
'email' => 'Email',
'password' => 'Пароль',
'name' => 'Имя',
'user_type' => 'User Type',
];
}
/**
* @return \yii\db\ActiveQuery
*/
public function getServices()
{
return $this->hasMany(Services::className(), ['user_id' => 'id']);
}
public function generatePassword($password){
$this->password = md5($password);
}
public function generateAdditionalInfo(){
$this->created_at = time();
$this->updated_at = time();
$this->activate_key = md5(time());
$this->user_type = 0;
$this->status = 0;
}
public static function findByEmail($email){
return static::findOne(['email'=>$email]);
}
/**
* Validates password
*
* @param string $password password to validate
* @return boolean if password provided is valid for current user
*/
public function validatePassword($password){
$currentPassword = md5($password);
if ($currentPassword == $this->password)
return true;
return false;
}
/**
* @inheritdoc
*/
public static function findIdentity($id)
{
return static::findOne(['id' => $id]);
}
/**
* @inheritdoc
*/
public static function findIdentityByAccessToken($token, $type = null)
{
throw new NotSupportedException('"findIdentityByAccessToken" is not implemented.');
}
/**
* Finds user by username
*
* @param string $username
* @return static|null
*/
public static function findByUsername($username)
{
return static::findOne(['name' => $username, 'status' => self::STATUS_ACTIVE]);
}
/**
* @inheritdoc
*/
public function getId()
{
return $this->getPrimaryKey();
}
/**
* Returns a key that can be used to check the validity of a given identity ID.
*
* The key should be unique for each individual user, and should be persistent
* so that it can be used to check the validity of the user identity.
*
* The space of such keys should be big enough to defeat potential identity attacks.
*
* This is required if [[User::enableAutoLogin]] is enabled.
* @return string a key that is used to check the validity of a given identity ID.
* @see validateAuthKey()
*/
public function getAuthKey()
{
$this->auth_key = md5(time());
}
/**
* Validates the given auth key.
*
* This is required if [[User::enableAutoLogin]] is enabled.
* @param string $authKey the given auth key
* @return boolean whether the given auth key is valid.
* @see getAuthKey()
*/
public function validateAuthKey($authKey)
{
if ($authKey == $this->auth_key) {
return true;
} else {
return false;
}
}
}
| morozovigor/AutoService | common/models/db/User.php | PHP | bsd-3-clause | 4,178 |
# Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
Implements rotations, including spherical rotations as defined in WCS Paper II
[1]_
`RotateNative2Celestial` and `RotateCelestial2Native` follow the convention in
WCS Paper II to rotate to/from a native sphere and the celestial sphere.
The implementation uses `EulerAngleRotation`. The model parameters are
three angles: the longitude (``lon``) and latitude (``lat``) of the fiducial point
in the celestial system (``CRVAL`` keywords in FITS), and the longitude of the celestial
pole in the native system (``lon_pole``). The Euler angles are ``lon+90``, ``90-lat``
and ``-(lon_pole-90)``.
References
----------
.. [1] Calabretta, M.R., Greisen, E.W., 2002, A&A, 395, 1077 (Paper II)
"""
import math
import numpy as np
from .core import Model
from .parameters import Parameter
from astropy.coordinates.matrix_utilities import rotation_matrix, matrix_product
from astropy import units as u
from .utils import _to_radian, _to_orig_unit
__all__ = ['RotateCelestial2Native', 'RotateNative2Celestial', 'Rotation2D',
'EulerAngleRotation', 'RotationSequence3D', 'SphericalRotationSequence']
def _create_matrix(angles, axes_order):
matrices = []
for angle, axis in zip(angles, axes_order):
if isinstance(angle, u.Quantity):
angle = angle.value
angle = angle.item()
matrices.append(rotation_matrix(angle, axis, unit=u.rad))
result = matrix_product(*matrices[::-1])
return result
def spherical2cartesian(alpha, delta):
alpha = np.deg2rad(alpha)
delta = np.deg2rad(delta)
x = np.cos(alpha) * np.cos(delta)
y = np.cos(delta) * np.sin(alpha)
z = np.sin(delta)
return np.array([x, y, z])
def cartesian2spherical(x, y, z):
h = np.hypot(x, y)
alpha = np.rad2deg(np.arctan2(y, x))
delta = np.rad2deg(np.arctan2(z, h))
return alpha, delta
class RotationSequence3D(Model):
"""
Perform a series of rotations about different axis in 3D space.
Positive angles represent a counter-clockwise rotation.
Parameters
----------
angles : array-like
Angles of rotation in deg in the order of axes_order.
axes_order : str
A sequence of 'x', 'y', 'z' corresponding to axis of rotation.
Examples
--------
>>> model = RotationSequence3D([1.1, 2.1, 3.1, 4.1], axes_order='xyzx')
"""
standard_broadcasting = False
_separable = False
n_inputs = 3
n_outputs = 3
angles = Parameter(default=[], getter=_to_orig_unit, setter=_to_radian)
def __init__(self, angles, axes_order, name=None):
self.axes = ['x', 'y', 'z']
unrecognized = set(axes_order).difference(self.axes)
if unrecognized:
raise ValueError("Unrecognized axis label {0}; "
"should be one of {1} ".format(unrecognized,
self.axes))
self.axes_order = axes_order
if len(angles) != len(axes_order):
raise ValueError("The number of angles {0} should match the number \
of axes {1}.".format(len(angles),
len(axes_order)))
super().__init__(angles, name=name)
self._inputs = ('x', 'y', 'z')
self._outputs = ('x', 'y', 'z')
@property
def inverse(self):
"""Inverse rotation."""
angles = self.angles.value[::-1] * -1
return self.__class__(angles, axes_order=self.axes_order[::-1])
def evaluate(self, x, y, z, angles):
"""
Apply the rotation to a set of 3D Cartesian coordinates.
"""
if x.shape != y.shape != z.shape:
raise ValueError("Expected input arrays to have the same shape")
# Note: If the original shape was () (an array scalar) convert to a
# 1-element 1-D array on output for consistency with most other models
orig_shape = x.shape or (1,)
inarr = np.array([x.flatten(), y.flatten(), z.flatten()])
result = np.dot(_create_matrix(angles[0], self.axes_order), inarr)
x, y, z = result[0], result[1], result[2]
x.shape = y.shape = z.shape = orig_shape
return x, y, z
class SphericalRotationSequence(RotationSequence3D):
"""
Perform a sequence of rotations about arbitrary number of axes
in spherical coordinates.
Parameters
----------
angles : list
A sequence of angles (in deg).
axes_order : str
A sequence of characters ('x', 'y', or 'z') corresponding to the
axis of rotation and matching the order in ``angles``.
"""
def __init__(self, angles, axes_order, name=None, **kwargs):
self._n_inputs = 2
self._n_outputs = 2
super().__init__(angles, axes_order=axes_order, name=name, **kwargs)
self._inputs = ("lon", "lat")
self._outputs = ("lon", "lat")
@property
def n_inputs(self):
return self._n_inputs
@property
def n_outputs(self):
return self._n_outputs
def evaluate(self, lon, lat, angles):
x, y, z = spherical2cartesian(lon, lat)
x1, y1, z1 = super().evaluate(x, y, z, angles)
lon, lat = cartesian2spherical(x1, y1, z1)
return lon, lat
class _EulerRotation:
"""
Base class which does the actual computation.
"""
_separable = False
def evaluate(self, alpha, delta, phi, theta, psi, axes_order):
shape = None
if isinstance(alpha, np.ndarray) and alpha.ndim == 2:
alpha = alpha.flatten()
delta = delta.flatten()
shape = alpha.shape
inp = spherical2cartesian(alpha, delta)
matrix = _create_matrix([phi, theta, psi], axes_order)
result = np.dot(matrix, inp)
a, b = cartesian2spherical(*result)
if shape is not None:
a.shape = shape
b.shape = shape
return a, b
_input_units_strict = True
_input_units_allow_dimensionless = True
@property
def input_units(self):
""" Input units. """
return {'alpha': u.deg, 'delta': u.deg}
@property
def return_units(self):
""" Output units. """
return {'alpha': u.deg, 'delta': u.deg}
class EulerAngleRotation(_EulerRotation, Model):
"""
Implements Euler angle intrinsic rotations.
Rotates one coordinate system into another (fixed) coordinate system.
All coordinate systems are right-handed. The sign of the angles is
determined by the right-hand rule..
Parameters
----------
phi, theta, psi : float or `~astropy.units.Quantity`
"proper" Euler angles in deg.
If floats, they should be in deg.
axes_order : str
A 3 character string, a combination of 'x', 'y' and 'z',
where each character denotes an axis in 3D space.
"""
n_inputs = 2
n_outputs = 2
phi = Parameter(default=0, getter=_to_orig_unit, setter=_to_radian)
theta = Parameter(default=0, getter=_to_orig_unit, setter=_to_radian)
psi = Parameter(default=0, getter=_to_orig_unit, setter=_to_radian)
def __init__(self, phi, theta, psi, axes_order, **kwargs):
self.axes = ['x', 'y', 'z']
if len(axes_order) != 3:
raise TypeError(
"Expected axes_order to be a character sequence of length 3,"
"got {}".format(axes_order))
unrecognized = set(axes_order).difference(self.axes)
if unrecognized:
raise ValueError("Unrecognized axis label {}; "
"should be one of {} ".format(unrecognized, self.axes))
self.axes_order = axes_order
qs = [isinstance(par, u.Quantity) for par in [phi, theta, psi]]
if any(qs) and not all(qs):
raise TypeError("All parameters should be of the same type - float or Quantity.")
super().__init__(phi=phi, theta=theta, psi=psi, **kwargs)
self._inputs = ('alpha', 'delta')
self._outputs = ('alpha', 'delta')
def inverse(self):
return self.__class__(phi=-self.psi,
theta=-self.theta,
psi=-self.phi,
axes_order=self.axes_order[::-1])
def evaluate(self, alpha, delta, phi, theta, psi):
a, b = super().evaluate(alpha, delta, phi, theta, psi, self.axes_order)
return a, b
class _SkyRotation(_EulerRotation, Model):
"""
Base class for RotateNative2Celestial and RotateCelestial2Native.
"""
lon = Parameter(default=0, getter=_to_orig_unit, setter=_to_radian)
lat = Parameter(default=0, getter=_to_orig_unit, setter=_to_radian)
lon_pole = Parameter(default=0, getter=_to_orig_unit, setter=_to_radian)
def __init__(self, lon, lat, lon_pole, **kwargs):
qs = [isinstance(par, u.Quantity) for par in [lon, lat, lon_pole]]
if any(qs) and not all(qs):
raise TypeError("All parameters should be of the same type - float or Quantity.")
super().__init__(lon, lat, lon_pole, **kwargs)
self.axes_order = 'zxz'
def _evaluate(self, phi, theta, lon, lat, lon_pole):
alpha, delta = super().evaluate(phi, theta, lon, lat, lon_pole,
self.axes_order)
mask = alpha < 0
if isinstance(mask, np.ndarray):
alpha[mask] += 360
else:
alpha += 360
return alpha, delta
class RotateNative2Celestial(_SkyRotation):
"""
Transform from Native to Celestial Spherical Coordinates.
Parameters
----------
lon : float or or `~astropy.units.Quantity`
Celestial longitude of the fiducial point.
lat : float or or `~astropy.units.Quantity`
Celestial latitude of the fiducial point.
lon_pole : float or or `~astropy.units.Quantity`
Longitude of the celestial pole in the native system.
Notes
-----
If ``lon``, ``lat`` and ``lon_pole`` are numerical values they
should be in units of deg. Inputs are angles on the native sphere.
Outputs are angles on the celestial sphere.
"""
n_inputs = 2
n_outputs = 2
@property
def input_units(self):
""" Input units. """
return {'phi_N': u.deg, 'theta_N': u.deg}
@property
def return_units(self):
""" Output units. """
return {'alpha_C': u.deg, 'delta_C': u.deg}
def __init__(self, lon, lat, lon_pole, **kwargs):
super().__init__(lon, lat, lon_pole, **kwargs)
self.inputs = ('phi_N', 'theta_N')
self.outputs = ('alpha_C', 'delta_C')
def evaluate(self, phi_N, theta_N, lon, lat, lon_pole):
"""
Parameters
----------
phi_N, theta_N : float (deg) or `~astropy.units.Quantity`
Angles in the Native coordinate system.
lon, lat, lon_pole : float (in deg) or `~astropy.units.Quantity`
Parameter values when the model was initialized.
Returns
-------
alpha_C, delta_C : float (deg) or `~astropy.units.Quantity`
Angles on the Celestial sphere.
"""
# The values are in radians since they have already been through the setter.
if isinstance(lon, u.Quantity):
lon = lon.value
lat = lat.value
lon_pole = lon_pole.value
# Convert to Euler angles
phi = lon_pole - np.pi / 2
theta = - (np.pi / 2 - lat)
psi = -(np.pi / 2 + lon)
alpha_C, delta_C = super()._evaluate(phi_N, theta_N, phi, theta, psi)
return alpha_C, delta_C
@property
def inverse(self):
# convert to angles on the celestial sphere
return RotateCelestial2Native(self.lon, self.lat, self.lon_pole)
class RotateCelestial2Native(_SkyRotation):
"""
Transform from Celestial to Native Spherical Coordinates.
Parameters
----------
lon : float or or `~astropy.units.Quantity`
Celestial longitude of the fiducial point.
lat : float or or `~astropy.units.Quantity`
Celestial latitude of the fiducial point.
lon_pole : float or or `~astropy.units.Quantity`
Longitude of the celestial pole in the native system.
Notes
-----
If ``lon``, ``lat`` and ``lon_pole`` are numerical values they should be
in units of deg. Inputs are angles on the celestial sphere.
Outputs are angles on the native sphere.
"""
n_inputs = 2
n_outputs = 2
@property
def input_units(self):
""" Input units. """
return {'alpha_C': u.deg, 'delta_C': u.deg}
@property
def return_units(self):
""" Output units. """
return {'phi_N': u.deg, 'theta_N': u.deg}
def __init__(self, lon, lat, lon_pole, **kwargs):
super().__init__(lon, lat, lon_pole, **kwargs)
# Inputs are angles on the celestial sphere
self.inputs = ('alpha_C', 'delta_C')
# Outputs are angles on the native sphere
self.outputs = ('phi_N', 'theta_N')
def evaluate(self, alpha_C, delta_C, lon, lat, lon_pole):
"""
Parameters
----------
alpha_C, delta_C : float (deg) or `~astropy.units.Quantity`
Angles in the Celestial coordinate frame.
lon, lat, lon_pole : float (deg) or `~astropy.units.Quantity`
Parameter values when the model was initialized.
Returns
-------
phi_N, theta_N : float (deg) or `~astropy.units.Quantity`
Angles on the Native sphere.
"""
if isinstance(lon, u.Quantity):
lon = lon.value
lat = lat.value
lon_pole = lon_pole.value
# Convert to Euler angles
phi = (np.pi / 2 + lon)
theta = (np.pi / 2 - lat)
psi = -(lon_pole - np.pi / 2)
phi_N, theta_N = super()._evaluate(alpha_C, delta_C, phi, theta, psi)
return phi_N, theta_N
@property
def inverse(self):
return RotateNative2Celestial(self.lon, self.lat, self.lon_pole)
class Rotation2D(Model):
"""
Perform a 2D rotation given an angle.
Positive angles represent a counter-clockwise rotation and vice-versa.
Parameters
----------
angle : float or `~astropy.units.Quantity`
Angle of rotation (if float it should be in deg).
"""
n_inputs = 2
n_outputs = 2
_separable = False
angle = Parameter(default=0.0, getter=_to_orig_unit, setter=_to_radian)
def __init__(self, angle=angle, **kwargs):
super().__init__(angle=angle, **kwargs)
self._inputs = ("x", "y")
self._outputs = ("x", "y")
@property
def inverse(self):
"""Inverse rotation."""
return self.__class__(angle=-self.angle)
@classmethod
def evaluate(cls, x, y, angle):
"""
Rotate (x, y) about ``angle``.
Parameters
----------
x, y : ndarray-like
Input quantities
angle : float (deg) or `~astropy.units.Quantity`
Angle of rotations.
"""
if x.shape != y.shape:
raise ValueError("Expected input arrays to have the same shape")
# If one argument has units, enforce they both have units and they are compatible.
x_unit = getattr(x, 'unit', None)
y_unit = getattr(y, 'unit', None)
has_units = x_unit is not None and y_unit is not None
if x_unit != y_unit:
if has_units and y_unit.is_equivalent(x_unit):
y = y.to(x_unit)
y_unit = x_unit
else:
raise u.UnitsError("x and y must have compatible units")
# Note: If the original shape was () (an array scalar) convert to a
# 1-element 1-D array on output for consistency with most other models
orig_shape = x.shape or (1,)
inarr = np.array([x.flatten(), y.flatten()])
if isinstance(angle, u.Quantity):
angle = angle.to_value(u.rad)
result = np.dot(cls._compute_matrix(angle), inarr)
x, y = result[0], result[1]
x.shape = y.shape = orig_shape
if has_units:
return u.Quantity(x, unit=x_unit), u.Quantity(y, unit=y_unit)
else:
return x, y
@staticmethod
def _compute_matrix(angle):
return np.array([[math.cos(angle), -math.sin(angle)],
[math.sin(angle), math.cos(angle)]],
dtype=np.float64)
| MSeifert04/astropy | astropy/modeling/rotations.py | Python | bsd-3-clause | 16,505 |
// Derived from http://golang.org/src/pkg/net/url/url.go
// Copyright 2012 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the QueryLICENSE file.
package query
func Escape(s string) string {
hexCount := 0
for i := 0; i < len(s); i++ {
c := s[i]
if shouldEscape(c) {
hexCount++
}
}
if hexCount == 0 {
return s
}
t := make([]byte, len(s)+2*hexCount)
j := 0
for i := 0; i < len(s); i++ {
switch c := s[i]; {
case shouldEscape(c):
t[j] = '%'
t[j+1] = "0123456789ABCDEF"[c>>4]
t[j+2] = "0123456789ABCDEF"[c&15]
j += 3
default:
t[j] = s[i]
j++
}
}
return string(t)
}
func shouldEscape(c byte) bool {
// §2.3 Unreserved characters (alphanum)
if 'A' <= c && c <= 'Z' || 'a' <= c && c <= 'z' || '0' <= c && c <= '9' {
return false
}
switch c {
case '-', '_', '.', '~': // §2.3 Unreserved characters (mark)
return false
}
// Everything else must be escaped.
return true
}
| zumper/aws | query/query.go | GO | bsd-3-clause | 1,005 |
<?php
/**
* User: timur
* Date: 6/8/14
* Time: 2:48 PM
*/
namespace API\Model;
use Zend\Db\Adapter\Adapter;
use Zend\Db\Sql\Select;
class SessionTable extends CoreTable
{
protected $table ='session';
public function __construct(Adapter $adapter)
{
parent::__construct($adapter, new Session());
}
/**
* Киносеанс
* @param $idSession int
* @return Session
*/
public function get($idSession)
{
$where = array(
'id_session' => $idSession
);
$rowset = $this->select($where);
return $rowset->current();
}
/**
* Все актуальные сеансы для данного кинотеатра и зала.
* @param $idCinema integer
* @param $idHall integer
* @param $date String День, когда нужно посмотреть сеансы
* @return Session[]
*/
public function getSessions($idCinema, $idHall = null, $date = null)
{
$today = date('Y:m:d H:i:s');
if (!is_null($date)) {
$today = $date;
}
$where = array(
'id_cinema' => $idCinema,
'start_date > ?' => $today,
'start_date <= ?' => date('Y:m:d H:i:s', strtotime('+1 day'))
);
if (!is_null($idHall)) {
$where['id_hall'] = $idHall;
}
$rowset = $this->select(function (Select $select) use ($where) {
$select->where($where);
$select->order('start_date ASC');
});
return $rowset;
}
}
| lilbegginbee/DemoApiMovies | module/API/src/API/Model/SessionTable.php | PHP | bsd-3-clause | 1,620 |
/*L
* Copyright Moxie Informatics.
*
* Distributed under the OSI-approved BSD 3-Clause License.
* See http://ncip.github.com/calims/LICENSE.txt for details.
*/
/**
*
*/
package gov.nih.nci.calims2.util.enumeration;
import java.util.Locale;
/**
* @author viseem
*
*/
public enum I18nTestEnumeration implements I18nEnumeration {
/** Test value 1. */
VALUE1,
/** Test value 2. */
VALUE2,
/** Test value 3. */
VALUE3,
/** Test value 4. */
VALUE4,
/** Test value 5. */
VALUE5;
/**
* {@inheritDoc}
*/
public String getLocalizedValue(Locale locale) {
return I18nEnumerationHelper.getLocalizedValue(I18nTestEnumerationBundle.class, locale, this);
}
/**
* {@inheritDoc}
*/
public String getName() {
return name();
}
}
| NCIP/calims | calims2-util/test/unit/java/gov/nih/nci/calims2/util/enumeration/I18nTestEnumeration.java | Java | bsd-3-clause | 777 |
<?php
use yii\db\Migration;
class m161230_063949_add_column_number_network extends Migration
{
public function up()
{
$this->addColumn('network','number_network','varchar(100)');
}
public function down()
{
echo "m161230_063949_add_column_number_network cannot be reverted.\n";
return false;
}
/*
// Use safeUp/safeDown to run migration code within a transaction
public function safeUp()
{
}
public function safeDown()
{
}
*/
}
| hungnd1/sms_brand | console/migrations/m161230_063949_add_column_number_network.php | PHP | bsd-3-clause | 517 |
# -*-coding:Utf-8 -*
# Copyright (c) 2013 LE GOFF Vincent
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
# * Neither the name of the copyright holder nor the names of its contributors
# may be used to endorse or promote products derived from this software
# without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO Ematelot SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
# OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
"""Fichier contenant le paramètre 'liste' de la commande 'matelot'."""
from primaires.format.fonctions import supprimer_accents
from primaires.format.tableau import Tableau
from primaires.interpreteur.masque.parametre import Parametre
from secondaires.navigation.equipage.postes.hierarchie import ORDRE
class PrmListe(Parametre):
"""Commande 'matelot liste'.
"""
def __init__(self):
"""Constructeur du paramètre"""
Parametre.__init__(self, "liste", "list")
self.tronquer = True
self.aide_courte = "liste les matelots de l'équipage"
self.aide_longue = \
"Cette commande liste les matelots de votre équipage. " \
"Elle permet d'obtenir rapidement des informations pratiques " \
"sur le nom du matelot ainsi que l'endroit où il se trouve."
def interpreter(self, personnage, dic_masques):
"""Interprétation du paramètre"""
salle = personnage.salle
if not hasattr(salle, "navire"):
personnage << "|err|Vous n'êtes pas sur un navire.|ff|"
return
navire = salle.navire
equipage = navire.equipage
if not navire.a_le_droit(personnage, "officier"):
personnage << "|err|Vous ne pouvez donner d'ordre sur ce " \
"navire.|ff|"
return
matelots = tuple((m, m.nom_poste) for m in \
equipage.matelots.values())
matelots += tuple(equipage.joueurs.items())
matelots = sorted(matelots, \
key=lambda couple: ORDRE.index(couple[1]), reverse=True)
if len(matelots) == 0:
personnage << "|err|Votre équipage ne comprend aucun matelot.|ff|"
return
tableau = Tableau()
tableau.ajouter_colonne("Nom")
tableau.ajouter_colonne("Poste")
tableau.ajouter_colonne("Affectation")
for matelot, nom_poste in matelots:
nom = matelot.nom
nom_poste = nom_poste.capitalize()
titre = "Aucune"
if hasattr(matelot, "personnage"):
titre = matelot.personnage.salle.titre_court.capitalize()
tableau.ajouter_ligne(nom, nom_poste, titre)
personnage << tableau.afficher()
| stormi/tsunami | src/secondaires/navigation/commandes/matelot/liste.py | Python | bsd-3-clause | 3,827 |
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2012 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 麦当苗儿 <zuojiazi.cn@gmail.com> <http://www.zjzit.cn>
// +----------------------------------------------------------------------
// config.php 2013-02-25
//定义回调URL通用的URL
define('URL_CALLBACK', 'http://demo.cn/index.php?m=Index&a=callback&type=');
return array(
//腾讯QQ登录配置
'THINK_SDK_QQ' => array(
'APP_KEY' => '', //应用注册成功后分配的 APP ID
'APP_SECRET' => '', //应用注册成功后分配的KEY
'CALLBACK' => URL_CALLBACK . 'qq',
),
//腾讯微博配置
'THINK_SDK_TENCENT' => array(
'APP_KEY' => '', //应用注册成功后分配的 APP ID
'APP_SECRET' => '', //应用注册成功后分配的KEY
'CALLBACK' => URL_CALLBACK . 'tencent',
),
//新浪微博配置
'THINK_SDK_SINA' => array(
'APP_KEY' => '', //应用注册成功后分配的 APP ID
'APP_SECRET' => '', //应用注册成功后分配的KEY
'CALLBACK' => URL_CALLBACK . 'sina',
),
//网易微博配置
'THINK_SDK_T163' => array(
'APP_KEY' => '', //应用注册成功后分配的 APP ID
'APP_SECRET' => '', //应用注册成功后分配的KEY
'CALLBACK' => URL_CALLBACK . 't163',
),
//人人网配置
'THINK_SDK_RENREN' => array(
'APP_KEY' => '', //应用注册成功后分配的 APP ID
'APP_SECRET' => '', //应用注册成功后分配的KEY
'CALLBACK' => URL_CALLBACK . 'renren',
),
//360配置
'THINK_SDK_X360' => array(
'APP_KEY' => '', //应用注册成功后分配的 APP ID
'APP_SECRET' => '', //应用注册成功后分配的KEY
'CALLBACK' => URL_CALLBACK . 'x360',
),
//豆瓣配置
'THINK_SDK_DOUBAN' => array(
'APP_KEY' => '', //应用注册成功后分配的 APP ID
'APP_SECRET' => '', //应用注册成功后分配的KEY
'CALLBACK' => URL_CALLBACK . 'douban',
),
//Github配置
'THINK_SDK_GITHUB' => array(
'APP_KEY' => '', //应用注册成功后分配的 APP ID
'APP_SECRET' => '', //应用注册成功后分配的KEY
'CALLBACK' => URL_CALLBACK . 'github',
),
//Google配置
'THINK_SDK_GOOGLE' => array(
'APP_KEY' => '', //应用注册成功后分配的 APP ID
'APP_SECRET' => '', //应用注册成功后分配的KEY
'CALLBACK' => URL_CALLBACK . 'google',
),
//MSN配置
'THINK_SDK_MSN' => array(
'APP_KEY' => '', //应用注册成功后分配的 APP ID
'APP_SECRET' => '', //应用注册成功后分配的KEY
'CALLBACK' => URL_CALLBACK . 'msn',
),
//点点配置
'THINK_SDK_DIANDIAN' => array(
'APP_KEY' => '', //应用注册成功后分配的 APP ID
'APP_SECRET' => '', //应用注册成功后分配的KEY
'CALLBACK' => URL_CALLBACK . 'diandian',
),
//淘宝网配置
'THINK_SDK_TAOBAO' => array(
'APP_KEY' => '', //应用注册成功后分配的 APP ID
'APP_SECRET' => '', //应用注册成功后分配的KEY
'CALLBACK' => URL_CALLBACK . 'taobao',
),
//百度配置
'THINK_SDK_BAIDU' => array(
'APP_KEY' => '', //应用注册成功后分配的 APP ID
'APP_SECRET' => '', //应用注册成功后分配的KEY
'CALLBACK' => URL_CALLBACK . 'baidu',
),
//开心网配置
'THINK_SDK_KAIXIN' => array(
'APP_KEY' => '', //应用注册成功后分配的 APP ID
'APP_SECRET' => '', //应用注册成功后分配的KEY
'CALLBACK' => URL_CALLBACK . 'kaixin',
),
//搜狐微博配置
'THINK_SDK_SOHU' => array(
'APP_KEY' => '', //应用注册成功后分配的 APP ID
'APP_SECRET' => '', //应用注册成功后分配的KEY
'CALLBACK' => URL_CALLBACK . 'sohu',
),
); | westeast/yii-extension-opensdkandapi | snsopenapi/demo/App/Conf/config.php | PHP | bsd-3-clause | 4,088 |
import Subject from "parsers/Subject";
describe("parsers/Subject", () => {
it("should split valid subject lines into object hash", () => {
let subject = "type(scope): summary summary summary";
let pull = { commits: [{ commit: { message: subject } }] };
expect((new Subject()).parse(pull)).toEqual({
type: "type",
scope: "scope",
summary: "summary summary summary"
});
});
it("should return object with null values on invalid message", () => {
let subject = "type(scope) summary summary summary";
let pull = { commits: [{ commit: { message: subject } }] };
expect((new Subject()).parse(pull)).toEqual({
type: null,
scope: null,
summary: null
});
});
it("should parse subjects with special characters", () => {
let subject = "type($state!): summary summary summary";
let pull = { commits: [{ commit: { message: subject } }] };
expect((new Subject()).parse(pull).scope).toBe("$state!");
});
}); | radify/PR.js | spec/parsers/Subject.js | JavaScript | bsd-3-clause | 988 |
//
// detail/reactive_socket_recvmsg_op.hpp
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2013 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef BOOST_ASIO_DETAIL_REACTIVE_SOCKET_RECVMSG_OP_HPP
#define BOOST_ASIO_DETAIL_REACTIVE_SOCKET_RECVMSG_OP_HPP
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <boost/asio/detail/config.hpp>
#include <boost/asio/detail/addressof.hpp>
#include <boost/asio/detail/bind_handler.hpp>
#include <boost/asio/detail/buffer_sequence_adapter.hpp>
#include <boost/asio/detail/fenced_block.hpp>
#include <boost/asio/detail/reactor_op.hpp>
#include <boost/asio/detail/socket_ops.hpp>
#include <boost/asio/socket_base.hpp>
#include <boost/asio/detail/push_options.hpp>
namespace pdalboost {} namespace boost = pdalboost; namespace pdalboost {
namespace asio {
namespace detail {
template <typename MutableBufferSequence>
class reactive_socket_recvmsg_op_base : public reactor_op
{
public:
reactive_socket_recvmsg_op_base(socket_type socket,
const MutableBufferSequence& buffers, socket_base::message_flags in_flags,
socket_base::message_flags& out_flags, func_type complete_func)
: reactor_op(&reactive_socket_recvmsg_op_base::do_perform, complete_func),
socket_(socket),
buffers_(buffers),
in_flags_(in_flags),
out_flags_(out_flags)
{
}
static bool do_perform(reactor_op* base)
{
reactive_socket_recvmsg_op_base* o(
static_cast<reactive_socket_recvmsg_op_base*>(base));
buffer_sequence_adapter<pdalboost::asio::mutable_buffer,
MutableBufferSequence> bufs(o->buffers_);
return socket_ops::non_blocking_recvmsg(o->socket_,
bufs.buffers(), bufs.count(),
o->in_flags_, o->out_flags_,
o->ec_, o->bytes_transferred_);
}
private:
socket_type socket_;
MutableBufferSequence buffers_;
socket_base::message_flags in_flags_;
socket_base::message_flags& out_flags_;
};
template <typename MutableBufferSequence, typename Handler>
class reactive_socket_recvmsg_op :
public reactive_socket_recvmsg_op_base<MutableBufferSequence>
{
public:
BOOST_ASIO_DEFINE_HANDLER_PTR(reactive_socket_recvmsg_op);
reactive_socket_recvmsg_op(socket_type socket,
const MutableBufferSequence& buffers, socket_base::message_flags in_flags,
socket_base::message_flags& out_flags, Handler& handler)
: reactive_socket_recvmsg_op_base<MutableBufferSequence>(socket, buffers,
in_flags, out_flags, &reactive_socket_recvmsg_op::do_complete),
handler_(BOOST_ASIO_MOVE_CAST(Handler)(handler))
{
}
static void do_complete(io_service_impl* owner, operation* base,
const pdalboost::system::error_code& /*ec*/,
std::size_t /*bytes_transferred*/)
{
// Take ownership of the handler object.
reactive_socket_recvmsg_op* o(
static_cast<reactive_socket_recvmsg_op*>(base));
ptr p = { pdalboost::asio::detail::addressof(o->handler_), o, o };
BOOST_ASIO_HANDLER_COMPLETION((o));
// Make a copy of the handler so that the memory can be deallocated before
// the upcall is made. Even if we're not about to make an upcall, a
// sub-object of the handler may be the true owner of the memory associated
// with the handler. Consequently, a local copy of the handler is required
// to ensure that any owning sub-object remains valid until after we have
// deallocated the memory here.
detail::binder2<Handler, pdalboost::system::error_code, std::size_t>
handler(o->handler_, o->ec_, o->bytes_transferred_);
p.h = pdalboost::asio::detail::addressof(handler.handler_);
p.reset();
// Make the upcall if required.
if (owner)
{
fenced_block b(fenced_block::half);
BOOST_ASIO_HANDLER_INVOCATION_BEGIN((handler.arg1_, handler.arg2_));
pdalboost_asio_handler_invoke_helpers::invoke(handler, handler.handler_);
BOOST_ASIO_HANDLER_INVOCATION_END;
}
}
private:
Handler handler_;
};
} // namespace detail
} // namespace asio
} // namespace pdalboost
#include <boost/asio/detail/pop_options.hpp>
#endif // BOOST_ASIO_DETAIL_REACTIVE_SOCKET_RECVMSG_OP_HPP
| verma/PDAL | boost/boost/asio/detail/reactive_socket_recvmsg_op.hpp | C++ | bsd-3-clause | 4,363 |
<?php
/**
* Test for net::stubbles::ipo::request::stubRedirectRequest.
*
* @package stubbles
* @subpackage ipo_request_test
* @version $Id: stubRedirectRequestTestCase.php 2679 2010-08-23 21:26:55Z mikey $
*/
stubClassLoader::load('net::stubbles::ipo::request::stubRedirectRequest');
/**
* Helper class for the tests.
*
* @package stubbles
* @subpackage ipo_request_test
*/
class TestRedirectRequest extends stubRedirectRequest
{
/**
* direct access to unsecure params data
*
* @return array<string,string>
*/
public function getUnsecureParams()
{
return $this->unsecureParams;
}
/**
* direct access to unsecure headers data
*
* @return array<string,string>
*/
public function getUnsecureHeaders()
{
return $this->unsecureHeaders;
}
/**
* direct access to unsecure cookies data
*
* @return array<string,string>
*/
public function getUnsecureCookies()
{
return $this->unsecureCookies;
}
}
/**
* Test for net::stubbles::ipo::request::stubRedirectRequest.
*
* @package stubbles
* @subpackage ipo_request_test
* @group ipo
* @group ipo_request
*/
class stubRedirectRequestTestCase extends PHPUnit_Framework_TestCase
{
/**
* on a non redirected query the get params should be used
*
* @test
*/
public function nonRedirectedQuery()
{
$_GET = array('foo' => 'bar', 'baz' => array('one', 'two'));
$_POST = array('foo' => 'baz', 'bar' => 'foo');
$_SERVER = array('key' => 'value');
$_COOKIE = array('name' => 'value');
$request = new TestRedirectRequest($this->getMock('stubFilterFactory'));
$this->assertEquals(array('foo' => 'bar', 'baz' => array('one', 'two')), $request->getUnsecureParams());
$this->assertEquals(array('key' => 'value'), $request->getUnsecureHeaders());
$this->assertEquals(array('name' => 'value'), $request->getUnsecureCookies());
}
/**
* on a redirected query the params should be extracted from the redirect query string
*
* @test
*/
public function redirectedQuery()
{
$_GET = array('foo' => 'bar', 'baz' => array('one', 'two'));
$_POST = array('foo' => 'baz', 'bar' => 'foo');
$_SERVER = array('key' => 'value', 'REDIRECT_QUERY_STRING' => 'foo[]=bar&foo[]=baz&bar=onetwo');
$_COOKIE = array('name' => 'value');
$request = new TestRedirectRequest($this->getMock('stubFilterFactory'));
$this->assertEquals(array('foo' => array('bar', 'baz'), 'bar' => 'onetwo'), $request->getUnsecureParams());
$this->assertEquals(array('key' => 'value', 'REDIRECT_QUERY_STRING' => 'foo[]=bar&foo[]=baz&bar=onetwo'), $request->getUnsecureHeaders());
$this->assertEquals(array('name' => 'value'), $request->getUnsecureCookies());
}
}
?> | stubbles/stubbles-1.x | src/test/php/net/stubbles/ipo/request/stubRedirectRequestTestCase.php | PHP | bsd-3-clause | 2,931 |
<?php
/**
* Created by PhpStorm.
* User: rem
* Date: 29.01.2015
* Time: 17:55
*/
namespace app\commands;
use Yii;
use yii\console\Controller;
class VipsratingController extends Controller
{
public function actionIndex()
{
echo "OK\n";
return true;
}
} | remk-wadriga/vicesisters-yii2-project | commands/VipsratingController.php | PHP | bsd-3-clause | 288 |
#include "hooks/hooks.H"
#include <errno.h>
#include <fcntl.h>
#include <unistd.h>
#include "libdft_api.h"
#include "tagmap.h"
#include "pin.H"
#include "provlog.H"
#include "dtracker.H"
#include "osutils.H"
/* tracks whether path existed before the execution of syscall */
static struct {
std::string pathname;
int existed_before_syscall;
} exist_status;
/*
* open(2)/creat(2) handlers
*
* Signatures:
* int open(const char *pathname, int flags);
* int open(const char *pathname, int flags, mode_t mode);
* int creat(const char *pathname, mode_t mode);
*/
#define DEF_SYSCALL_OPEN
#include "hooks/syscall_args.h"
template<>
void pre_open_hook<libdft_tag_bitset>(syscall_ctx_t *ctx) {
/* Check the status of the pathname we are about to open/create. */
exist_status.pathname = std::string(_PATHNAME);
exist_status.existed_before_syscall = path_exists(exist_status.pathname);
//std::cerr << exist_status.pathname << std::endl;
//std::cerr << exist_status.existed_before_syscall << std::endl;
}
template<>
void post_open_hook<libdft_tag_bitset>(syscall_ctx_t *ctx) {
/* not successful; optimized branch */
if (unlikely(_FD < 0)) {
LOG("ERROR " _CALL_LOG_STR + " (" + strerror(errno) + ")\n");
return;
}
/* Resolve fd to full pathname. Use this instead of syscall argument. */
const std::string fdn = fdname(_FD);
if ( !in_dtracker_whitelist(fdn) && !path_isdir(fdn) ) {
const PROVLOG::ufd_t ufd = PROVLOG::ufdmap[_FD];
fdset.insert(_FD);
int created = (
exist_status.existed_before_syscall != 1 &&
(_FLAGS & O_CREAT) &&
exist_status.pathname == std::string(_PATHNAME)
);
LOG("OK " _CALL_LOG_STR + "\n");
LOG("INFO mapped fd" + decstr(_FD) + ":ufd" + decstr(ufd) + "\n");
PROVLOG::open(ufd, fdn, _FLAGS, created);
}
else {
LOG("INFO ignoring fd" + decstr(_FD) + " (" + fdn + ")\n");
}
/* reset the exist_status */
exist_status.existed_before_syscall = 0;
}
#define UNDEF_SYSCALL_OPEN
#include "hooks/syscall_args.h"
/*
* close(2) handler - updates watched fds
*
* Signature: int close(int fd);
*/
#define DEF_SYSCALL_CLOSE
#include "hooks/syscall_args.h"
template<>
void post_close_hook<libdft_tag_bitset>(syscall_ctx_t *ctx) {
/* not successful; optimized branch */
if (unlikely(_RET_STATUS < 0)) {
LOG("ERROR " _CALL_LOG_STR + " (" + strerror(errno) + ")\n");
return;
}
LOG("OK " _CALL_LOG_STR + "\n");
std::set<int>::iterator it = fdset.find(_FD);
if (it == fdset.end()) return;
const PROVLOG::ufd_t ufd = PROVLOG::ufdmap[_FD];
fdset.erase(it);
PROVLOG::ufdmap.del(_FD);
if (IS_STDFD(_FD)) stdcount[_FD] = 0;
LOG("INFO removed mapping fd" + decstr(_FD) + ":ufd" + decstr(ufd) + "\n");
PROVLOG::close(ufd);
}
#define UNDEF_SYSCALL_CLOSE
#include "hooks/syscall_args.h"
/* vim: set noet ts=4 sts=4 sw=4 ai : */
| m000/dtracker | hooks/libdft_tag_bitset/openclose.cpp | C++ | bsd-3-clause | 2,810 |
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "net/quic/quic_chromium_client_session.h"
#include <memory>
#include <utility>
#include "base/bind.h"
#include "base/containers/contains.h"
#include "base/feature_list.h"
#include "base/location.h"
#include "base/memory/ptr_util.h"
#include "base/metrics/histogram_functions.h"
#include "base/metrics/histogram_macros.h"
#include "base/metrics/sparse_histogram.h"
#include "base/no_destructor.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/stringprintf.h"
#include "base/task/post_task.h"
#include "base/task/single_thread_task_runner.h"
#include "base/threading/thread_task_runner_handle.h"
#include "base/time/tick_clock.h"
#include "base/trace_event/memory_usage_estimator.h"
#include "base/values.h"
#include "net/base/features.h"
#include "net/base/io_buffer.h"
#include "net/base/net_errors.h"
#include "net/base/network_activity_monitor.h"
#include "net/base/network_isolation_key.h"
#include "net/base/privacy_mode.h"
#include "net/base/url_util.h"
#include "net/cert/signed_certificate_timestamp_and_status.h"
#include "net/http/transport_security_state.h"
#include "net/log/net_log_event_type.h"
#include "net/log/net_log_source_type.h"
#include "net/quic/address_utils.h"
#include "net/quic/crypto/proof_verifier_chromium.h"
#include "net/quic/quic_chromium_connection_helper.h"
#include "net/quic/quic_chromium_packet_writer.h"
#include "net/quic/quic_connectivity_probing_manager.h"
#include "net/quic/quic_crypto_client_stream_factory.h"
#include "net/quic/quic_server_info.h"
#include "net/quic/quic_stream_factory.h"
#include "net/socket/datagram_client_socket.h"
#include "net/spdy/spdy_http_utils.h"
#include "net/spdy/spdy_log_util.h"
#include "net/spdy/spdy_session.h"
#include "net/ssl/ssl_connection_status_flags.h"
#include "net/ssl/ssl_info.h"
#include "net/third_party/quiche/src/quic/core/http/quic_client_promised_info.h"
#include "net/third_party/quiche/src/quic/core/http/spdy_server_push_utils.h"
#include "net/third_party/quiche/src/quic/core/quic_utils.h"
#include "net/third_party/quiche/src/quic/platform/api/quic_flags.h"
#include "net/traffic_annotation/network_traffic_annotation.h"
#include "third_party/boringssl/src/include/openssl/ssl.h"
#include "url/origin.h"
#include "url/scheme_host_port.h"
namespace net {
namespace {
// IPv6 packets have an additional 20 bytes of overhead than IPv4 packets.
const size_t kAdditionalOverheadForIPv6 = 20;
// Maximum number of Readers that are created for any session due to
// connection migration. A new Reader is created every time this endpoint's
// IP address changes.
const size_t kMaxReadersPerQuicSession = 5;
// Time to wait (in seconds) when no networks are available and
// migrating sessions need to wait for a new network to connect.
const size_t kWaitTimeForNewNetworkSecs = 10;
const size_t kMinRetryTimeForDefaultNetworkSecs = 1;
// Maximum RTT time for this session when set initial timeout for probing
// network.
const int kDefaultRTTMilliSecs = 300;
// These values are persisted to logs. Entries should not be renumbered,
// and numeric values should never be reused.
enum class AcceptChEntries {
kNoEntries = 0,
kOnlyValidEntries = 1,
kOnlyInvalidEntries = 2,
kBothValidAndInvalidEntries = 3,
kMaxValue = kBothValidAndInvalidEntries,
};
void LogAcceptChFrameReceivedHistogram(bool has_valid_entry,
bool has_invalid_entry) {
AcceptChEntries value;
if (has_valid_entry) {
if (has_invalid_entry) {
value = AcceptChEntries::kBothValidAndInvalidEntries;
} else {
value = AcceptChEntries::kOnlyValidEntries;
}
} else {
if (has_invalid_entry) {
value = AcceptChEntries::kOnlyInvalidEntries;
} else {
value = AcceptChEntries::kNoEntries;
}
}
base::UmaHistogramEnumeration("Net.QuicSession.AcceptChFrameReceivedViaAlps",
value);
}
void LogAcceptChForOriginHistogram(bool value) {
base::UmaHistogramBoolean("Net.QuicSession.AcceptChForOrigin", value);
}
void RecordConnectionCloseErrorCodeImpl(const std::string& histogram,
uint64_t error,
bool is_google_host,
bool handshake_confirmed) {
base::UmaHistogramSparse(histogram, error);
if (handshake_confirmed) {
base::UmaHistogramSparse(histogram + ".HandshakeConfirmed", error);
} else {
base::UmaHistogramSparse(histogram + ".HandshakeNotConfirmed", error);
}
if (is_google_host) {
base::UmaHistogramSparse(histogram + "Google", error);
if (handshake_confirmed) {
base::UmaHistogramSparse(histogram + "Google.HandshakeConfirmed", error);
} else {
base::UmaHistogramSparse(histogram + "Google.HandshakeNotConfirmed",
error);
}
}
}
void LogMigrateToSocketStatus(bool success) {
UMA_HISTOGRAM_BOOLEAN("Net.QuicSession.MigrateToSocketSuccess", success);
}
void RecordConnectionCloseErrorCode(const quic::QuicConnectionCloseFrame& frame,
quic::ConnectionCloseSource source,
const std::string& hostname,
bool handshake_confirmed) {
bool is_google_host = IsGoogleHost(hostname);
std::string histogram = "Net.QuicSession.ConnectionCloseErrorCode";
if (source == quic::ConnectionCloseSource::FROM_SELF) {
// When sending a CONNECTION_CLOSE frame, it is sufficient to record
// |quic_error_code|.
histogram += "Client";
RecordConnectionCloseErrorCodeImpl(histogram, frame.quic_error_code,
is_google_host, handshake_confirmed);
return;
}
histogram += "Server";
// Record |quic_error_code|. Note that when using IETF QUIC, this is
// extracted from the CONNECTION_CLOSE frame reason phrase, and might be
// QUIC_IETF_GQUIC_ERROR_MISSING.
RecordConnectionCloseErrorCodeImpl(histogram, frame.quic_error_code,
is_google_host, handshake_confirmed);
// For IETF QUIC frames, also record the error code received on the wire.
if (frame.close_type == quic::IETF_QUIC_TRANSPORT_CONNECTION_CLOSE) {
histogram += "IetfTransport";
RecordConnectionCloseErrorCodeImpl(histogram, frame.wire_error_code,
is_google_host, handshake_confirmed);
if (frame.quic_error_code == quic::QUIC_IETF_GQUIC_ERROR_MISSING) {
histogram += "GQuicErrorMissing";
RecordConnectionCloseErrorCodeImpl(histogram, frame.wire_error_code,
is_google_host, handshake_confirmed);
}
} else if (frame.close_type == quic::IETF_QUIC_APPLICATION_CONNECTION_CLOSE) {
histogram += "IetfApplication";
RecordConnectionCloseErrorCodeImpl(histogram, frame.wire_error_code,
is_google_host, handshake_confirmed);
if (frame.quic_error_code == quic::QUIC_IETF_GQUIC_ERROR_MISSING) {
histogram += "GQuicErrorMissing";
RecordConnectionCloseErrorCodeImpl(histogram, frame.wire_error_code,
is_google_host, handshake_confirmed);
}
}
}
base::Value NetLogQuicMigrationFailureParams(
quic::QuicConnectionId connection_id,
base::StringPiece reason) {
base::DictionaryValue dict;
dict.SetString("connection_id", connection_id.ToString());
dict.SetString("reason", reason);
return std::move(dict);
}
base::Value NetLogQuicMigrationSuccessParams(
quic::QuicConnectionId connection_id) {
base::DictionaryValue dict;
dict.SetString("connection_id", connection_id.ToString());
return std::move(dict);
}
base::Value NetLogProbingResultParams(
NetworkChangeNotifier::NetworkHandle network,
const quic::QuicSocketAddress* peer_address,
bool is_success) {
base::DictionaryValue dict;
dict.SetString("network", base::NumberToString(network));
dict.SetString("peer address", peer_address->ToString());
dict.SetBoolean("is_success", is_success);
return std::move(dict);
}
// Histogram for recording the different reasons that a QUIC session is unable
// to complete the handshake.
enum HandshakeFailureReason {
HANDSHAKE_FAILURE_UNKNOWN = 0,
HANDSHAKE_FAILURE_BLACK_HOLE = 1,
HANDSHAKE_FAILURE_PUBLIC_RESET = 2,
NUM_HANDSHAKE_FAILURE_REASONS = 3,
};
void RecordHandshakeFailureReason(HandshakeFailureReason reason) {
UMA_HISTOGRAM_ENUMERATION(
"Net.QuicSession.ConnectionClose.HandshakeNotConfirmed.Reason", reason,
NUM_HANDSHAKE_FAILURE_REASONS);
}
// Note: these values must be kept in sync with the corresponding values in:
// tools/metrics/histograms/histograms.xml
enum HandshakeState {
STATE_STARTED = 0,
STATE_ENCRYPTION_ESTABLISHED = 1,
STATE_HANDSHAKE_CONFIRMED = 2,
STATE_FAILED = 3,
NUM_HANDSHAKE_STATES = 4
};
enum class ZeroRttState {
kAttemptedAndSucceeded = 0,
kAttemptedAndRejected = 1,
kNotAttempted = 2,
kMaxValue = kNotAttempted,
};
void RecordHandshakeState(HandshakeState state) {
UMA_HISTOGRAM_ENUMERATION("Net.QuicHandshakeState", state,
NUM_HANDSHAKE_STATES);
}
std::string MigrationCauseToString(MigrationCause cause) {
switch (cause) {
case UNKNOWN_CAUSE:
return "Unknown";
case ON_NETWORK_CONNECTED:
return "OnNetworkConnected";
case ON_NETWORK_DISCONNECTED:
return "OnNetworkDisconnected";
case ON_WRITE_ERROR:
return "OnWriteError";
case ON_NETWORK_MADE_DEFAULT:
return "OnNetworkMadeDefault";
case ON_MIGRATE_BACK_TO_DEFAULT_NETWORK:
return "OnMigrateBackToDefaultNetwork";
case CHANGE_NETWORK_ON_PATH_DEGRADING:
return "OnPathDegrading";
case CHANGE_PORT_ON_PATH_DEGRADING:
return "ChangePortOnPathDegrading";
case NEW_NETWORK_CONNECTED_POST_PATH_DEGRADING:
return "NewNetworkConnectedPostPathDegrading";
default:
QUIC_NOTREACHED();
break;
}
return "InvalidCause";
}
base::Value NetLogQuicClientSessionParams(
const QuicSessionKey* session_key,
const quic::QuicConnectionId& connection_id,
const quic::QuicConnectionId& client_connection_id,
const quic::ParsedQuicVersionVector& supported_versions,
int cert_verify_flags,
bool require_confirmation) {
base::Value dict(base::Value::Type::DICTIONARY);
dict.SetStringKey("host", session_key->server_id().host());
dict.SetIntKey("port", session_key->server_id().port());
dict.SetStringKey("privacy_mode",
PrivacyModeToDebugString(session_key->privacy_mode()));
dict.SetStringKey("network_isolation_key",
session_key->network_isolation_key().ToDebugString());
dict.SetBoolKey("require_confirmation", require_confirmation);
dict.SetIntKey("cert_verify_flags", cert_verify_flags);
dict.SetStringKey("connection_id", connection_id.ToString());
if (!client_connection_id.IsEmpty()) {
dict.SetStringKey("client_connection_id", client_connection_id.ToString());
}
dict.SetStringKey("versions",
ParsedQuicVersionVectorToString(supported_versions));
return dict;
}
base::Value NetLogQuicPushPromiseReceivedParams(
const spdy::Http2HeaderBlock* headers,
spdy::SpdyStreamId stream_id,
spdy::SpdyStreamId promised_stream_id,
NetLogCaptureMode capture_mode) {
base::DictionaryValue dict;
dict.SetKey("headers",
ElideHttp2HeaderBlockForNetLog(*headers, capture_mode));
dict.SetInteger("id", stream_id);
dict.SetInteger("promised_stream_id", promised_stream_id);
return std::move(dict);
}
// TODO(fayang): Remove this when necessary data is collected.
void LogProbeResultToHistogram(MigrationCause cause, bool success) {
UMA_HISTOGRAM_BOOLEAN("Net.QuicSession.PathValidationSuccess", success);
const std::string histogram_name =
"Net.QuicSession.PathValidationSuccess." + MigrationCauseToString(cause);
STATIC_HISTOGRAM_POINTER_GROUP(
histogram_name, cause, MIGRATION_CAUSE_MAX, AddBoolean(success),
base::BooleanHistogram::FactoryGet(
histogram_name, base::HistogramBase::kUmaTargetedHistogramFlag));
}
class QuicServerPushHelper : public ServerPushDelegate::ServerPushHelper {
public:
explicit QuicServerPushHelper(
base::WeakPtr<QuicChromiumClientSession> session,
const GURL& url)
: session_(session), request_url_(url) {}
void Cancel() override {
if (session_) {
session_->CancelPush(request_url_);
}
}
const GURL& GetURL() const override { return request_url_; }
NetworkIsolationKey GetNetworkIsolationKey() const override {
if (session_) {
return session_->quic_session_key().network_isolation_key();
}
return NetworkIsolationKey();
}
private:
base::WeakPtr<QuicChromiumClientSession> session_;
const GURL request_url_;
};
} // namespace
QuicChromiumClientSession::Handle::Handle(
const base::WeakPtr<QuicChromiumClientSession>& session,
url::SchemeHostPort destination)
: MultiplexedSessionHandle(session),
session_(session),
destination_(std::move(destination)),
net_log_(session_->net_log()),
was_handshake_confirmed_(session->OneRttKeysAvailable()),
net_error_(OK),
quic_error_(quic::QUIC_NO_ERROR),
port_migration_detected_(false),
server_id_(session_->server_id()),
quic_version_(session->connection()->version()),
push_handle_(nullptr),
was_ever_used_(false) {
DCHECK(session_);
session_->AddHandle(this);
}
QuicChromiumClientSession::Handle::~Handle() {
if (push_handle_) {
auto* push_handle = push_handle_;
push_handle_ = nullptr;
push_handle->Cancel();
}
if (session_)
session_->RemoveHandle(this);
}
void QuicChromiumClientSession::Handle::OnCryptoHandshakeConfirmed() {
was_handshake_confirmed_ = true;
}
void QuicChromiumClientSession::Handle::OnSessionClosed(
quic::ParsedQuicVersion quic_version,
int net_error,
quic::QuicErrorCode quic_error,
bool port_migration_detected,
LoadTimingInfo::ConnectTiming connect_timing,
bool was_ever_used) {
session_ = nullptr;
port_migration_detected_ = port_migration_detected;
net_error_ = net_error;
quic_error_ = quic_error;
quic_version_ = quic_version;
connect_timing_ = connect_timing;
push_handle_ = nullptr;
was_ever_used_ = was_ever_used;
}
bool QuicChromiumClientSession::Handle::IsConnected() const {
return session_ != nullptr;
}
bool QuicChromiumClientSession::Handle::OneRttKeysAvailable() const {
return was_handshake_confirmed_;
}
const LoadTimingInfo::ConnectTiming&
QuicChromiumClientSession::Handle::GetConnectTiming() {
if (!session_)
return connect_timing_;
return session_->GetConnectTiming();
}
void QuicChromiumClientSession::Handle::PopulateNetErrorDetails(
NetErrorDetails* details) const {
if (session_) {
session_->PopulateNetErrorDetails(details);
} else {
details->quic_port_migration_detected = port_migration_detected_;
details->quic_connection_error = quic_error_;
}
}
quic::ParsedQuicVersion QuicChromiumClientSession::Handle::GetQuicVersion()
const {
if (!session_)
return quic_version_;
return session_->GetQuicVersion();
}
void QuicChromiumClientSession::Handle::ResetPromised(
quic::QuicStreamId id,
quic::QuicRstStreamErrorCode error_code) {
if (session_)
session_->ResetPromised(id, error_code);
}
std::unique_ptr<quic::QuicConnection::ScopedPacketFlusher>
QuicChromiumClientSession::Handle::CreatePacketBundler() {
if (!session_)
return nullptr;
return std::make_unique<quic::QuicConnection::ScopedPacketFlusher>(
session_->connection());
}
bool QuicChromiumClientSession::Handle::SharesSameSession(
const Handle& other) const {
return session_.get() == other.session_.get();
}
int QuicChromiumClientSession::Handle::RendezvousWithPromised(
const spdy::Http2HeaderBlock& headers,
CompletionOnceCallback callback) {
if (!session_)
return ERR_CONNECTION_CLOSED;
quic::QuicAsyncStatus push_status =
session_->push_promise_index()->Try(headers, this, &push_handle_);
switch (push_status) {
case quic::QUIC_FAILURE:
return ERR_FAILED;
case quic::QUIC_SUCCESS:
return OK;
case quic::QUIC_PENDING:
push_callback_ = std::move(callback);
return ERR_IO_PENDING;
}
NOTREACHED();
return ERR_UNEXPECTED;
}
int QuicChromiumClientSession::Handle::RequestStream(
bool requires_confirmation,
CompletionOnceCallback callback,
const NetworkTrafficAnnotationTag& traffic_annotation) {
DCHECK(!stream_request_);
if (!session_)
return ERR_CONNECTION_CLOSED;
requires_confirmation |= session_->gquic_zero_rtt_disabled();
// std::make_unique does not work because the StreamRequest constructor
// is private.
stream_request_ = base::WrapUnique(
new StreamRequest(this, requires_confirmation, traffic_annotation));
return stream_request_->StartRequest(std::move(callback));
}
std::unique_ptr<QuicChromiumClientStream::Handle>
QuicChromiumClientSession::Handle::ReleaseStream() {
DCHECK(stream_request_);
auto handle = stream_request_->ReleaseStream();
stream_request_.reset();
return handle;
}
std::unique_ptr<QuicChromiumClientStream::Handle>
QuicChromiumClientSession::Handle::ReleasePromisedStream() {
DCHECK(push_stream_);
return std::move(push_stream_);
}
int QuicChromiumClientSession::Handle::WaitForHandshakeConfirmation(
CompletionOnceCallback callback) {
if (!session_)
return ERR_CONNECTION_CLOSED;
return session_->WaitForHandshakeConfirmation(std::move(callback));
}
void QuicChromiumClientSession::Handle::CancelRequest(StreamRequest* request) {
if (session_)
session_->CancelRequest(request);
}
int QuicChromiumClientSession::Handle::TryCreateStream(StreamRequest* request) {
if (!session_)
return ERR_CONNECTION_CLOSED;
return session_->TryCreateStream(request);
}
quic::QuicClientPushPromiseIndex*
QuicChromiumClientSession::Handle::GetPushPromiseIndex() {
if (!session_)
return push_promise_index_;
return session_->push_promise_index();
}
int QuicChromiumClientSession::Handle::GetPeerAddress(
IPEndPoint* address) const {
if (!session_)
return ERR_CONNECTION_CLOSED;
*address = ToIPEndPoint(session_->peer_address());
return OK;
}
int QuicChromiumClientSession::Handle::GetSelfAddress(
IPEndPoint* address) const {
if (!session_)
return ERR_CONNECTION_CLOSED;
*address = ToIPEndPoint(session_->self_address());
return OK;
}
bool QuicChromiumClientSession::Handle::WasEverUsed() const {
if (!session_)
return was_ever_used_;
return session_->WasConnectionEverUsed();
}
const std::vector<std::string>&
QuicChromiumClientSession::Handle::GetDnsAliasesForSessionKey(
const QuicSessionKey& key) const {
static const base::NoDestructor<std::vector<std::string>> emptyvector_result;
return session_ ? session_->GetDnsAliasesForSessionKey(key)
: *emptyvector_result;
}
bool QuicChromiumClientSession::Handle::CheckVary(
const spdy::Http2HeaderBlock& client_request,
const spdy::Http2HeaderBlock& promise_request,
const spdy::Http2HeaderBlock& promise_response) {
HttpRequestInfo promise_request_info;
ConvertHeaderBlockToHttpRequestHeaders(promise_request,
&promise_request_info.extra_headers);
HttpRequestInfo client_request_info;
ConvertHeaderBlockToHttpRequestHeaders(client_request,
&client_request_info.extra_headers);
HttpResponseInfo promise_response_info;
if (!SpdyHeadersToHttpResponse(promise_response, &promise_response_info)) {
DLOG(WARNING) << "Invalid headers";
return false;
}
HttpVaryData vary_data;
if (!vary_data.Init(promise_request_info,
*promise_response_info.headers.get())) {
// Promise didn't contain valid vary info, so URL match was sufficient.
return true;
}
// Now compare the client request for matching.
return vary_data.MatchesRequest(client_request_info,
*promise_response_info.headers.get());
}
void QuicChromiumClientSession::Handle::OnRendezvousResult(
quic::QuicSpdyStream* stream) {
DCHECK(!push_stream_);
int rv = ERR_FAILED;
if (stream) {
rv = OK;
push_stream_ =
static_cast<QuicChromiumClientStream*>(stream)->CreateHandle();
}
if (push_callback_) {
DCHECK(push_handle_);
push_handle_ = nullptr;
std::move(push_callback_).Run(rv);
}
}
QuicChromiumClientSession::StreamRequest::StreamRequest(
QuicChromiumClientSession::Handle* session,
bool requires_confirmation,
const NetworkTrafficAnnotationTag& traffic_annotation)
: session_(session),
requires_confirmation_(requires_confirmation),
stream_(nullptr),
traffic_annotation_(traffic_annotation) {}
QuicChromiumClientSession::StreamRequest::~StreamRequest() {
if (stream_)
stream_->Reset(quic::QUIC_STREAM_CANCELLED);
if (session_)
session_->CancelRequest(this);
}
int QuicChromiumClientSession::StreamRequest::StartRequest(
CompletionOnceCallback callback) {
if (!session_->IsConnected())
return ERR_CONNECTION_CLOSED;
next_state_ = STATE_WAIT_FOR_CONFIRMATION;
int rv = DoLoop(OK);
if (rv == ERR_IO_PENDING)
callback_ = std::move(callback);
return rv;
}
std::unique_ptr<QuicChromiumClientStream::Handle>
QuicChromiumClientSession::StreamRequest::ReleaseStream() {
DCHECK(stream_);
return std::move(stream_);
}
void QuicChromiumClientSession::StreamRequest::OnRequestCompleteSuccess(
std::unique_ptr<QuicChromiumClientStream::Handle> stream) {
DCHECK_EQ(STATE_REQUEST_STREAM_COMPLETE, next_state_);
stream_ = std::move(stream);
// This method is called even when the request completes synchronously.
if (callback_)
DoCallback(OK);
}
void QuicChromiumClientSession::StreamRequest::OnRequestCompleteFailure(
int rv) {
DCHECK_EQ(STATE_REQUEST_STREAM_COMPLETE, next_state_);
// This method is called even when the request completes synchronously.
if (callback_) {
// Avoid re-entrancy if the callback calls into the session.
base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE,
base::BindOnce(&QuicChromiumClientSession::StreamRequest::DoCallback,
weak_factory_.GetWeakPtr(), rv));
}
}
void QuicChromiumClientSession::StreamRequest::OnIOComplete(int rv) {
rv = DoLoop(rv);
if (rv != ERR_IO_PENDING && !callback_.is_null()) {
DoCallback(rv);
}
}
void QuicChromiumClientSession::StreamRequest::DoCallback(int rv) {
CHECK_NE(rv, ERR_IO_PENDING);
CHECK(!callback_.is_null());
// The client callback can do anything, including destroying this class,
// so any pending callback must be issued after everything else is done.
std::move(callback_).Run(rv);
}
int QuicChromiumClientSession::StreamRequest::DoLoop(int rv) {
do {
State state = next_state_;
next_state_ = STATE_NONE;
switch (state) {
case STATE_WAIT_FOR_CONFIRMATION:
CHECK_EQ(OK, rv);
rv = DoWaitForConfirmation();
break;
case STATE_WAIT_FOR_CONFIRMATION_COMPLETE:
rv = DoWaitForConfirmationComplete(rv);
break;
case STATE_REQUEST_STREAM:
CHECK_EQ(OK, rv);
rv = DoRequestStream();
break;
case STATE_REQUEST_STREAM_COMPLETE:
rv = DoRequestStreamComplete(rv);
break;
default:
NOTREACHED() << "next_state_: " << next_state_;
break;
}
} while (next_state_ != STATE_NONE && next_state_ && rv != ERR_IO_PENDING);
return rv;
}
int QuicChromiumClientSession::StreamRequest::DoWaitForConfirmation() {
next_state_ = STATE_WAIT_FOR_CONFIRMATION_COMPLETE;
if (requires_confirmation_) {
return session_->WaitForHandshakeConfirmation(
base::BindOnce(&QuicChromiumClientSession::StreamRequest::OnIOComplete,
weak_factory_.GetWeakPtr()));
}
return OK;
}
int QuicChromiumClientSession::StreamRequest::DoWaitForConfirmationComplete(
int rv) {
DCHECK_NE(ERR_IO_PENDING, rv);
if (rv < 0)
return rv;
next_state_ = STATE_REQUEST_STREAM;
return OK;
}
int QuicChromiumClientSession::StreamRequest::DoRequestStream() {
next_state_ = STATE_REQUEST_STREAM_COMPLETE;
return session_->TryCreateStream(this);
}
int QuicChromiumClientSession::StreamRequest::DoRequestStreamComplete(int rv) {
DCHECK(rv == OK || !stream_);
return rv;
}
QuicChromiumClientSession::QuicChromiumPathValidationContext::
QuicChromiumPathValidationContext(
const quic::QuicSocketAddress& self_address,
const quic::QuicSocketAddress& peer_address,
NetworkChangeNotifier::NetworkHandle network,
std::unique_ptr<DatagramClientSocket> socket,
std::unique_ptr<QuicChromiumPacketWriter> writer,
std::unique_ptr<QuicChromiumPacketReader> reader)
: QuicPathValidationContext(self_address, peer_address),
network_handle_(network),
socket_(std::move(socket)),
writer_(std::move(writer)),
reader_(std::move(reader)) {}
QuicChromiumClientSession::QuicChromiumPathValidationContext::
~QuicChromiumPathValidationContext() = default;
NetworkChangeNotifier::NetworkHandle
QuicChromiumClientSession::QuicChromiumPathValidationContext::network() {
return network_handle_;
}
quic::QuicPacketWriter*
QuicChromiumClientSession::QuicChromiumPathValidationContext::WriterToUse() {
return writer_.get();
}
std::unique_ptr<QuicChromiumPacketWriter>
QuicChromiumClientSession::QuicChromiumPathValidationContext::ReleaseWriter() {
return std::move(writer_);
}
std::unique_ptr<DatagramClientSocket>
QuicChromiumClientSession::QuicChromiumPathValidationContext::ReleaseSocket() {
return std::move(socket_);
}
std::unique_ptr<QuicChromiumPacketReader>
QuicChromiumClientSession::QuicChromiumPathValidationContext::ReleaseReader() {
return std::move(reader_);
}
QuicChromiumClientSession::ConnectionMigrationValidationResultDelegate::
ConnectionMigrationValidationResultDelegate(
QuicChromiumClientSession* session)
: session_(session) {}
void QuicChromiumClientSession::ConnectionMigrationValidationResultDelegate::
OnPathValidationSuccess(
std::unique_ptr<quic::QuicPathValidationContext> context) {
auto* chrome_context =
static_cast<QuicChromiumPathValidationContext*>(context.get());
session_->OnConnectionMigrationProbeSucceeded(
chrome_context->network(), chrome_context->peer_address(),
chrome_context->self_address(), chrome_context->ReleaseSocket(),
chrome_context->ReleaseWriter(), chrome_context->ReleaseReader());
}
void QuicChromiumClientSession::ConnectionMigrationValidationResultDelegate::
OnPathValidationFailure(
std::unique_ptr<quic::QuicPathValidationContext> context) {
session_->connection()->OnPathValidationFailureAtClient();
// Note that socket, packet writer, and packet reader in |context| will be
// discarded.
auto* chrome_context =
static_cast<QuicChromiumPathValidationContext*>(context.get());
session_->OnProbeFailed(chrome_context->network(),
chrome_context->peer_address());
}
QuicChromiumClientSession::PortMigrationValidationResultDelegate::
PortMigrationValidationResultDelegate(QuicChromiumClientSession* session)
: session_(session) {}
void QuicChromiumClientSession::PortMigrationValidationResultDelegate::
OnPathValidationSuccess(
std::unique_ptr<quic::QuicPathValidationContext> context) {
auto* chrome_context =
static_cast<QuicChromiumPathValidationContext*>(context.get());
session_->OnPortMigrationProbeSucceeded(
chrome_context->network(), chrome_context->peer_address(),
chrome_context->self_address(), chrome_context->ReleaseSocket(),
chrome_context->ReleaseWriter(), chrome_context->ReleaseReader());
}
void QuicChromiumClientSession::PortMigrationValidationResultDelegate::
OnPathValidationFailure(
std::unique_ptr<quic::QuicPathValidationContext> context) {
session_->connection()->OnPathValidationFailureAtClient();
// Note that socket, packet writer, and packet reader in |context| will be
// discarded.
auto* chrome_context =
static_cast<QuicChromiumPathValidationContext*>(context.get());
session_->OnProbeFailed(chrome_context->network(),
chrome_context->peer_address());
}
QuicChromiumClientSession::QuicChromiumPathValidationWriterDelegate::
QuicChromiumPathValidationWriterDelegate(
QuicChromiumClientSession* session,
base::SequencedTaskRunner* task_runner)
: session_(session),
task_runner_(task_runner),
network_(NetworkChangeNotifier::kInvalidNetworkHandle) {}
QuicChromiumClientSession::QuicChromiumPathValidationWriterDelegate::
~QuicChromiumPathValidationWriterDelegate() = default;
int QuicChromiumClientSession::QuicChromiumPathValidationWriterDelegate::
HandleWriteError(
int error_code,
scoped_refptr<QuicChromiumPacketWriter::ReusableIOBuffer> last_packet) {
// Write error on the probing network is not recoverable.
DVLOG(1) << "Probing packet encounters write error " << error_code;
// Post a task to notify |session_| that this probe failed and cancel
// undergoing probing, which will delete the packet writer.
task_runner_->PostTask(
FROM_HERE,
base::BindOnce(
&QuicChromiumPathValidationWriterDelegate::NotifySessionProbeFailed,
weak_factory_.GetWeakPtr(), network_));
return error_code;
}
void QuicChromiumClientSession::QuicChromiumPathValidationWriterDelegate::
OnWriteError(int error_code) {
NotifySessionProbeFailed(network_);
}
void QuicChromiumClientSession::QuicChromiumPathValidationWriterDelegate::
OnWriteUnblocked() {}
void QuicChromiumClientSession::QuicChromiumPathValidationWriterDelegate::
NotifySessionProbeFailed(NetworkChangeNotifier::NetworkHandle network) {
session_->OnProbeFailed(network, peer_address_);
}
void QuicChromiumClientSession::QuicChromiumPathValidationWriterDelegate::
set_peer_address(const quic::QuicSocketAddress& peer_address) {
peer_address_ = peer_address;
}
void QuicChromiumClientSession::QuicChromiumPathValidationWriterDelegate::
set_network(NetworkChangeNotifier::NetworkHandle network) {
network_ = network;
}
QuicChromiumClientSession::QuicChromiumClientSession(
quic::QuicConnection* connection,
std::unique_ptr<DatagramClientSocket> socket,
QuicStreamFactory* stream_factory,
QuicCryptoClientStreamFactory* crypto_client_stream_factory,
const quic::QuicClock* clock,
TransportSecurityState* transport_security_state,
SSLConfigService* ssl_config_service,
std::unique_ptr<QuicServerInfo> server_info,
const QuicSessionKey& session_key,
bool require_confirmation,
bool migrate_session_early_v2,
bool migrate_sessions_on_network_change_v2,
NetworkChangeNotifier::NetworkHandle default_network,
quic::QuicTime::Delta retransmittable_on_wire_timeout,
bool migrate_idle_session,
bool allow_port_migration,
base::TimeDelta idle_migration_period,
base::TimeDelta max_time_on_non_default_network,
int max_migrations_to_non_default_network_on_write_error,
int max_migrations_to_non_default_network_on_path_degrading,
int yield_after_packets,
quic::QuicTime::Delta yield_after_duration,
bool go_away_on_path_degrading,
bool headers_include_h2_stream_dependency,
int cert_verify_flags,
const quic::QuicConfig& config,
std::unique_ptr<QuicCryptoClientConfigHandle> crypto_config,
const char* const connection_description,
base::TimeTicks dns_resolution_start_time,
base::TimeTicks dns_resolution_end_time,
std::unique_ptr<quic::QuicClientPushPromiseIndex> push_promise_index,
ServerPushDelegate* push_delegate,
const base::TickClock* tick_clock,
base::SequencedTaskRunner* task_runner,
std::unique_ptr<SocketPerformanceWatcher> socket_performance_watcher,
NetLog* net_log)
: quic::QuicSpdyClientSessionBase(connection,
push_promise_index.get(),
config,
connection->supported_versions()),
session_key_(session_key),
require_confirmation_(require_confirmation),
migrate_session_early_v2_(migrate_session_early_v2),
migrate_session_on_network_change_v2_(
migrate_sessions_on_network_change_v2),
migrate_idle_session_(migrate_idle_session),
allow_port_migration_(allow_port_migration),
idle_migration_period_(idle_migration_period),
max_time_on_non_default_network_(max_time_on_non_default_network),
max_migrations_to_non_default_network_on_write_error_(
max_migrations_to_non_default_network_on_write_error),
current_migrations_to_non_default_network_on_write_error_(0),
max_migrations_to_non_default_network_on_path_degrading_(
max_migrations_to_non_default_network_on_path_degrading),
current_migrations_to_non_default_network_on_path_degrading_(0),
clock_(clock),
yield_after_packets_(yield_after_packets),
yield_after_duration_(yield_after_duration),
go_away_on_path_degrading_(go_away_on_path_degrading),
most_recent_path_degrading_timestamp_(base::TimeTicks()),
most_recent_network_disconnected_timestamp_(base::TimeTicks()),
tick_clock_(tick_clock),
most_recent_stream_close_time_(tick_clock_->NowTicks()),
most_recent_write_error_(0),
most_recent_write_error_timestamp_(base::TimeTicks()),
crypto_config_(std::move(crypto_config)),
stream_factory_(stream_factory),
transport_security_state_(transport_security_state),
ssl_config_service_(ssl_config_service),
server_info_(std::move(server_info)),
pkp_bypassed_(false),
is_fatal_cert_error_(false),
num_total_streams_(0),
task_runner_(task_runner),
net_log_(NetLogWithSource::Make(net_log, NetLogSourceType::QUIC_SESSION)),
logger_(new QuicConnectionLogger(this,
connection_description,
std::move(socket_performance_watcher),
net_log_)),
http3_logger_(VersionUsesHttp3(connection->transport_version())
? new QuicHttp3Logger(net_log_)
: nullptr),
going_away_(false),
port_migration_detected_(false),
push_delegate_(push_delegate),
streams_pushed_count_(0),
streams_pushed_and_claimed_count_(0),
bytes_pushed_count_(0),
bytes_pushed_and_unclaimed_count_(0),
probing_manager_(this, task_runner_),
retry_migrate_back_count_(0),
current_migration_cause_(UNKNOWN_CAUSE),
send_packet_after_migration_(false),
wait_for_new_network_(false),
ignore_read_error_(false),
headers_include_h2_stream_dependency_(
headers_include_h2_stream_dependency),
attempted_zero_rtt_(false),
num_migrations_(0),
last_key_update_reason_(quic::KeyUpdateReason::kInvalid),
push_promise_index_(std::move(push_promise_index)),
path_validation_writer_delegate_(this, task_runner_) {
// Make sure connection migration and goaway on path degrading are not turned
// on at the same time.
DCHECK(!(migrate_session_early_v2_ && go_away_on_path_degrading_));
DCHECK(!(allow_port_migration_ && go_away_on_path_degrading_));
default_network_ = default_network;
auto* socket_raw = socket.get();
sockets_.push_back(std::move(socket));
packet_readers_.push_back(std::make_unique<QuicChromiumPacketReader>(
sockets_.back().get(), clock, this, yield_after_packets,
yield_after_duration, net_log_));
CHECK_EQ(packet_readers_.size(), sockets_.size());
crypto_stream_.reset(
crypto_client_stream_factory->CreateQuicCryptoClientStream(
session_key.server_id(), this,
std::make_unique<ProofVerifyContextChromium>(cert_verify_flags,
net_log_),
crypto_config_->GetConfig()));
if (VersionUsesHttp3(transport_version()))
set_debug_visitor(http3_logger_.get());
connection->set_debug_visitor(logger_.get());
connection->set_creator_debug_delegate(logger_.get());
migrate_back_to_default_timer_.SetTaskRunner(task_runner_);
net_log_.BeginEvent(NetLogEventType::QUIC_SESSION, [&] {
return NetLogQuicClientSessionParams(
&session_key, connection_id(), connection->client_connection_id(),
supported_versions(), cert_verify_flags, require_confirmation_);
});
IPEndPoint address;
if (socket_raw && socket_raw->GetLocalAddress(&address) == OK &&
address.GetFamily() == ADDRESS_FAMILY_IPV6) {
connection->SetMaxPacketLength(connection->max_packet_length() -
kAdditionalOverheadForIPv6);
}
connect_timing_.dns_start = dns_resolution_start_time;
connect_timing_.dns_end = dns_resolution_end_time;
if (!retransmittable_on_wire_timeout.IsZero()) {
connection->set_initial_retransmittable_on_wire_timeout(
retransmittable_on_wire_timeout);
}
}
QuicChromiumClientSession::~QuicChromiumClientSession() {
// This is referenced by the parent class's destructor, so have to delete it
// asynchronously, unfortunately. Don't use DeleteSoon, since that leaks if
// the task is not run, which is often the case in tests.
base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE,
base::BindOnce([](std::unique_ptr<quic::QuicClientPushPromiseIndex>
push_promise_index) {},
std::move(push_promise_index_)));
DCHECK(callback_.is_null());
for (auto& observer : connectivity_observer_list_)
observer.OnSessionRemoved(this);
net_log_.EndEvent(NetLogEventType::QUIC_SESSION);
DCHECK(waiting_for_confirmation_callbacks_.empty());
DCHECK(!HasActiveRequestStreams());
DCHECK(handles_.empty());
if (!stream_requests_.empty()) {
// The session must be closed before it is destroyed.
CancelAllRequests(ERR_UNEXPECTED);
}
connection()->set_debug_visitor(nullptr);
if (connection()->connected()) {
// Ensure that the connection is closed by the time the session is
// destroyed.
connection()->CloseConnection(quic::QUIC_PEER_GOING_AWAY,
"session torn down",
quic::ConnectionCloseBehavior::SILENT_CLOSE);
}
if (IsEncryptionEstablished())
RecordHandshakeState(STATE_ENCRYPTION_ESTABLISHED);
if (OneRttKeysAvailable())
RecordHandshakeState(STATE_HANDSHAKE_CONFIRMED);
else
RecordHandshakeState(STATE_FAILED);
UMA_HISTOGRAM_COUNTS_1M("Net.QuicSession.NumTotalStreams",
num_total_streams_);
UMA_HISTOGRAM_COUNTS_1M("Net.QuicNumSentClientHellos",
crypto_stream_->num_sent_client_hellos());
UMA_HISTOGRAM_COUNTS_1M("Net.QuicSession.Pushed", streams_pushed_count_);
UMA_HISTOGRAM_COUNTS_1M("Net.QuicSession.PushedAndClaimed",
streams_pushed_and_claimed_count_);
UMA_HISTOGRAM_COUNTS_1M("Net.QuicSession.PushedBytes", bytes_pushed_count_);
DCHECK_LE(bytes_pushed_and_unclaimed_count_, bytes_pushed_count_);
UMA_HISTOGRAM_COUNTS_1M("Net.QuicSession.PushedAndUnclaimedBytes",
bytes_pushed_and_unclaimed_count_);
if (!OneRttKeysAvailable())
return;
// Sending one client_hello means we had zero handshake-round-trips.
int round_trip_handshakes = crypto_stream_->num_sent_client_hellos() - 1;
SSLInfo ssl_info;
// QUIC supports only secure urls.
if (GetSSLInfo(&ssl_info) && ssl_info.cert.get()) {
UMA_HISTOGRAM_CUSTOM_COUNTS("Net.QuicSession.ConnectRandomPortForHTTPS",
round_trip_handshakes, 1, 3, 4);
if (require_confirmation_) {
UMA_HISTOGRAM_CUSTOM_COUNTS(
"Net.QuicSession.ConnectRandomPortRequiringConfirmationForHTTPS",
round_trip_handshakes, 1, 3, 4);
}
}
const quic::QuicConnectionStats stats = connection()->GetStats();
// The MTU used by QUIC is limited to a fairly small set of predefined values
// (initial values and MTU discovery values), but does not fare well when
// bucketed. Because of that, a sparse histogram is used here.
base::UmaHistogramSparse("Net.QuicSession.ClientSideMtu", stats.egress_mtu);
base::UmaHistogramSparse("Net.QuicSession.ServerSideMtu", stats.ingress_mtu);
UMA_HISTOGRAM_COUNTS_1M("Net.QuicSession.MtuProbesSent",
connection()->mtu_probe_count());
if (stats.packets_sent >= 100) {
// Used to monitor for regressions that effect large uploads.
UMA_HISTOGRAM_COUNTS_1000(
"Net.QuicSession.PacketRetransmitsPerMille",
1000 * stats.packets_retransmitted / stats.packets_sent);
}
if (stats.max_sequence_reordering == 0)
return;
const base::HistogramBase::Sample kMaxReordering = 100;
base::HistogramBase::Sample reordering = kMaxReordering;
if (stats.min_rtt_us > 0) {
reordering = static_cast<base::HistogramBase::Sample>(
100 * stats.max_time_reordering_us / stats.min_rtt_us);
}
UMA_HISTOGRAM_CUSTOM_COUNTS("Net.QuicSession.MaxReorderingTime", reordering,
1, kMaxReordering, 50);
if (stats.min_rtt_us > 100 * 1000) {
UMA_HISTOGRAM_CUSTOM_COUNTS("Net.QuicSession.MaxReorderingTimeLongRtt",
reordering, 1, kMaxReordering, 50);
}
UMA_HISTOGRAM_COUNTS_1M(
"Net.QuicSession.MaxReordering",
static_cast<base::HistogramBase::Sample>(stats.max_sequence_reordering));
}
void QuicChromiumClientSession::Initialize() {
set_max_inbound_header_list_size(kQuicMaxHeaderListSize);
if (config()->HasClientRequestedIndependentOption(
quic::kQLVE, quic::Perspective::IS_CLIENT)) {
connection()->EnableLegacyVersionEncapsulation(session_key_.host());
}
quic::QuicSpdyClientSessionBase::Initialize();
}
size_t QuicChromiumClientSession::WriteHeadersOnHeadersStream(
quic::QuicStreamId id,
spdy::Http2HeaderBlock headers,
bool fin,
const spdy::SpdyStreamPrecedence& precedence,
quic::QuicReferenceCountedPointer<quic::QuicAckListenerInterface>
ack_listener) {
spdy::SpdyStreamId parent_stream_id = 0;
int weight = 0;
bool exclusive = false;
if (headers_include_h2_stream_dependency_) {
priority_dependency_state_.OnStreamCreation(id, precedence.spdy3_priority(),
&parent_stream_id, &weight,
&exclusive);
} else {
weight = spdy::Spdy3PriorityToHttp2Weight(precedence.spdy3_priority());
}
return WriteHeadersOnHeadersStreamImpl(id, std::move(headers), fin,
parent_stream_id, weight, exclusive,
std::move(ack_listener));
}
void QuicChromiumClientSession::UnregisterStreamPriority(quic::QuicStreamId id,
bool is_static) {
if (headers_include_h2_stream_dependency_ && !is_static) {
priority_dependency_state_.OnStreamDestruction(id);
}
quic::QuicSpdySession::UnregisterStreamPriority(id, is_static);
}
void QuicChromiumClientSession::UpdateStreamPriority(
quic::QuicStreamId id,
const spdy::SpdyStreamPrecedence& new_precedence) {
if (headers_include_h2_stream_dependency_ ||
VersionUsesHttp3(connection()->transport_version())) {
auto updates = priority_dependency_state_.OnStreamUpdate(
id, new_precedence.spdy3_priority());
for (auto update : updates) {
if (!VersionUsesHttp3(connection()->transport_version())) {
WritePriority(update.id, update.parent_stream_id, update.weight,
update.exclusive);
}
}
}
quic::QuicSpdySession::UpdateStreamPriority(id, new_precedence);
}
void QuicChromiumClientSession::OnHttp3GoAway(uint64_t id) {
quic::QuicSpdySession::OnHttp3GoAway(id);
NotifyFactoryOfSessionGoingAway();
PerformActionOnActiveStreams([id](quic::QuicStream* stream) {
if (stream->id() >= id) {
static_cast<QuicChromiumClientStream*>(stream)->OnError(
ERR_QUIC_GOAWAY_REQUEST_CAN_BE_RETRIED);
}
return true;
});
}
void QuicChromiumClientSession::OnAcceptChFrameReceivedViaAlps(
const quic::AcceptChFrame& frame) {
bool has_valid_entry = false;
bool has_invalid_entry = false;
for (const auto& entry : frame.entries) {
// |entry.origin| must be a valid origin.
GURL url(entry.origin);
if (!url.is_valid()) {
has_invalid_entry = true;
continue;
}
const url::Origin origin = url::Origin::Create(url);
std::string serialized = origin.Serialize();
if (serialized.empty() || entry.origin != serialized) {
has_invalid_entry = true;
continue;
}
has_valid_entry = true;
accept_ch_entries_received_via_alps_.insert(
std::make_pair(std::move(origin), entry.value));
}
LogAcceptChFrameReceivedHistogram(has_valid_entry, has_invalid_entry);
}
void QuicChromiumClientSession::AddHandle(Handle* handle) {
if (going_away_) {
handle->OnSessionClosed(connection()->version(), ERR_UNEXPECTED, error(),
port_migration_detected_, GetConnectTiming(),
WasConnectionEverUsed());
return;
}
DCHECK(!base::Contains(handles_, handle));
handles_.insert(handle);
}
void QuicChromiumClientSession::RemoveHandle(Handle* handle) {
DCHECK(base::Contains(handles_, handle));
handles_.erase(handle);
}
void QuicChromiumClientSession::AddConnectivityObserver(
ConnectivityObserver* observer) {
connectivity_observer_list_.AddObserver(observer);
observer->OnSessionRegistered(this, GetCurrentNetwork());
}
void QuicChromiumClientSession::RemoveConnectivityObserver(
ConnectivityObserver* observer) {
connectivity_observer_list_.RemoveObserver(observer);
}
// TODO(zhongyi): replace migration_session_* booleans with
// ConnectionMigrationMode.
ConnectionMigrationMode QuicChromiumClientSession::connection_migration_mode()
const {
if (migrate_session_early_v2_)
return ConnectionMigrationMode::FULL_MIGRATION_V2;
if (migrate_session_on_network_change_v2_)
return ConnectionMigrationMode::NO_MIGRATION_ON_PATH_DEGRADING_V2;
return ConnectionMigrationMode::NO_MIGRATION;
}
int QuicChromiumClientSession::WaitForHandshakeConfirmation(
CompletionOnceCallback callback) {
if (!connection()->connected())
return ERR_CONNECTION_CLOSED;
if (OneRttKeysAvailable())
return OK;
waiting_for_confirmation_callbacks_.push_back(std::move(callback));
return ERR_IO_PENDING;
}
int QuicChromiumClientSession::TryCreateStream(StreamRequest* request) {
if (goaway_received()) {
DVLOG(1) << "Going away.";
return ERR_CONNECTION_CLOSED;
}
if (!connection()->connected()) {
DVLOG(1) << "Already closed.";
return ERR_CONNECTION_CLOSED;
}
if (going_away_) {
return ERR_CONNECTION_CLOSED;
}
bool can_open_next = CanOpenNextOutgoingBidirectionalStream();
if (can_open_next) {
request->stream_ =
CreateOutgoingReliableStreamImpl(request->traffic_annotation())
->CreateHandle();
return OK;
}
request->pending_start_time_ = tick_clock_->NowTicks();
stream_requests_.push_back(request);
UMA_HISTOGRAM_COUNTS_1000("Net.QuicSession.NumPendingStreamRequests",
stream_requests_.size());
return ERR_IO_PENDING;
}
void QuicChromiumClientSession::CancelRequest(StreamRequest* request) {
// Remove |request| from the queue while preserving the order of the
// other elements.
auto it =
std::find(stream_requests_.begin(), stream_requests_.end(), request);
if (it != stream_requests_.end()) {
it = stream_requests_.erase(it);
}
}
bool QuicChromiumClientSession::ShouldCreateOutgoingBidirectionalStream() {
if (!crypto_stream_->encryption_established()) {
DVLOG(1) << "Encryption not active so no outgoing stream created.";
return false;
}
if (!CanOpenNextOutgoingBidirectionalStream()) {
DVLOG(1) << "Failed to create a new outgoing stream. "
<< "Already " << GetNumActiveStreams() << " open.";
return false;
}
if (goaway_received()) {
DVLOG(1) << "Failed to create a new outgoing stream. "
<< "Already received goaway.";
return false;
}
if (going_away_) {
return false;
}
return true;
}
bool QuicChromiumClientSession::ShouldCreateOutgoingUnidirectionalStream() {
NOTREACHED() << "Try to create outgoing unidirectional streams";
return false;
}
bool QuicChromiumClientSession::WasConnectionEverUsed() {
const quic::QuicConnectionStats& stats = connection()->GetStats();
return stats.bytes_sent > 0 || stats.bytes_received > 0;
}
QuicChromiumClientStream*
QuicChromiumClientSession::CreateOutgoingBidirectionalStream() {
NOTREACHED() << "CreateOutgoingReliableStreamImpl should be called directly";
return nullptr;
}
QuicChromiumClientStream*
QuicChromiumClientSession::CreateOutgoingUnidirectionalStream() {
NOTREACHED() << "Try to create outgoing unidirectional stream";
return nullptr;
}
QuicChromiumClientStream*
QuicChromiumClientSession::CreateOutgoingReliableStreamImpl(
const NetworkTrafficAnnotationTag& traffic_annotation) {
DCHECK(connection()->connected());
QuicChromiumClientStream* stream = new QuicChromiumClientStream(
GetNextOutgoingBidirectionalStreamId(), this, quic::BIDIRECTIONAL,
net_log_, traffic_annotation);
ActivateStream(base::WrapUnique(stream));
++num_total_streams_;
UMA_HISTOGRAM_COUNTS_1M("Net.QuicSession.NumOpenStreams",
GetNumActiveStreams());
// The previous histogram puts 100 in a bucket betweeen 86-113 which does
// not shed light on if chrome ever things it has more than 100 streams open.
UMA_HISTOGRAM_BOOLEAN("Net.QuicSession.TooManyOpenStreams",
GetNumActiveStreams() > 100);
return stream;
}
quic::QuicCryptoClientStream*
QuicChromiumClientSession::GetMutableCryptoStream() {
return crypto_stream_.get();
}
const quic::QuicCryptoClientStream* QuicChromiumClientSession::GetCryptoStream()
const {
return crypto_stream_.get();
}
bool QuicChromiumClientSession::GetRemoteEndpoint(IPEndPoint* endpoint) {
*endpoint = ToIPEndPoint(peer_address());
return true;
}
// TODO(rtenneti): Add unittests for GetSSLInfo which exercise the various ways
// we learn about SSL info (sync vs async vs cached).
bool QuicChromiumClientSession::GetSSLInfo(SSLInfo* ssl_info) const {
ssl_info->Reset();
if (!cert_verify_result_) {
return false;
}
ssl_info->cert_status = cert_verify_result_->cert_status;
ssl_info->cert = cert_verify_result_->verified_cert;
ssl_info->public_key_hashes = cert_verify_result_->public_key_hashes;
ssl_info->is_issued_by_known_root =
cert_verify_result_->is_issued_by_known_root;
ssl_info->pkp_bypassed = pkp_bypassed_;
ssl_info->client_cert_sent = false;
ssl_info->handshake_type = SSLInfo::HANDSHAKE_FULL;
ssl_info->pinning_failure_log = pinning_failure_log_;
ssl_info->is_fatal_cert_error = is_fatal_cert_error_;
ssl_info->signed_certificate_timestamps = cert_verify_result_->scts;
ssl_info->ct_policy_compliance = cert_verify_result_->policy_compliance;
const auto& crypto_params = crypto_stream_->crypto_negotiated_params();
uint16_t cipher_suite;
if (connection()->version().UsesTls()) {
cipher_suite = crypto_params.cipher_suite;
} else {
// Map QUIC AEADs to the corresponding TLS 1.3 cipher. OpenSSL's cipher
// suite numbers begin with a stray 0x03, so mask them off.
quic::QuicTag aead = crypto_params.aead;
switch (aead) {
case quic::kAESG:
cipher_suite = TLS1_CK_AES_128_GCM_SHA256 & 0xffff;
break;
case quic::kCC20:
cipher_suite = TLS1_CK_CHACHA20_POLY1305_SHA256 & 0xffff;
break;
default:
NOTREACHED();
return false;
}
}
int ssl_connection_status = 0;
SSLConnectionStatusSetCipherSuite(cipher_suite, &ssl_connection_status);
SSLConnectionStatusSetVersion(SSL_CONNECTION_VERSION_QUIC,
&ssl_connection_status);
ssl_info->connection_status = ssl_connection_status;
if (connection()->version().UsesTls()) {
ssl_info->key_exchange_group = crypto_params.key_exchange_group;
ssl_info->peer_signature_algorithm = crypto_params.peer_signature_algorithm;
return true;
}
// Report the QUIC key exchange as the corresponding TLS curve.
switch (crypto_stream_->crypto_negotiated_params().key_exchange) {
case quic::kP256:
ssl_info->key_exchange_group = SSL_CURVE_SECP256R1;
break;
case quic::kC255:
ssl_info->key_exchange_group = SSL_CURVE_X25519;
break;
default:
NOTREACHED();
return false;
}
// QUIC-Crypto always uses RSA-PSS or ECDSA with SHA-256.
size_t unused;
X509Certificate::PublicKeyType key_type;
X509Certificate::GetPublicKeyInfo(ssl_info->cert->cert_buffer(), &unused,
&key_type);
switch (key_type) {
case X509Certificate::kPublicKeyTypeRSA:
ssl_info->peer_signature_algorithm = SSL_SIGN_RSA_PSS_RSAE_SHA256;
break;
case X509Certificate::kPublicKeyTypeECDSA:
ssl_info->peer_signature_algorithm = SSL_SIGN_ECDSA_SECP256R1_SHA256;
break;
default:
NOTREACHED();
return false;
}
return true;
}
base::StringPiece QuicChromiumClientSession::GetAcceptChViaAlpsForOrigin(
const url::Origin& origin) const {
auto it = accept_ch_entries_received_via_alps_.find(origin);
if (it == accept_ch_entries_received_via_alps_.end()) {
LogAcceptChForOriginHistogram(false);
return {};
} else {
LogAcceptChForOriginHistogram(true);
return it->second;
}
}
int QuicChromiumClientSession::CryptoConnect(CompletionOnceCallback callback) {
connect_timing_.connect_start = tick_clock_->NowTicks();
RecordHandshakeState(STATE_STARTED);
DCHECK(flow_controller());
if (!crypto_stream_->CryptoConnect())
return ERR_QUIC_HANDSHAKE_FAILED;
if (OneRttKeysAvailable()) {
connect_timing_.connect_end = tick_clock_->NowTicks();
return OK;
}
// Unless we require handshake confirmation, activate the session if
// we have established initial encryption.
if (!require_confirmation_ && IsEncryptionEstablished())
return OK;
callback_ = std::move(callback);
return ERR_IO_PENDING;
}
int QuicChromiumClientSession::GetNumSentClientHellos() const {
return crypto_stream_->num_sent_client_hellos();
}
bool QuicChromiumClientSession::CanPool(
const std::string& hostname,
const QuicSessionKey& other_session_key) const {
DCHECK(connection()->connected());
if (!session_key_.CanUseForAliasing(other_session_key))
return false;
SSLInfo ssl_info;
if (!GetSSLInfo(&ssl_info) || !ssl_info.cert.get()) {
NOTREACHED() << "QUIC should always have certificates.";
return false;
}
return SpdySession::CanPool(transport_security_state_, ssl_info,
*ssl_config_service_, session_key_.host(),
hostname, session_key_.network_isolation_key());
}
bool QuicChromiumClientSession::ShouldCreateIncomingStream(
quic::QuicStreamId id) {
if (!connection()->connected()) {
LOG(DFATAL) << "ShouldCreateIncomingStream called when disconnected";
return false;
}
if (goaway_received()) {
DVLOG(1) << "Cannot create a new outgoing stream. "
<< "Already received goaway.";
return false;
}
if (going_away_) {
return false;
}
if (quic::QuicUtils::IsClientInitiatedStreamId(
connection()->transport_version(), id) ||
(connection()->version().HasIetfQuicFrames() &&
quic::QuicUtils::IsBidirectionalStreamId(id, connection()->version()))) {
LOG(WARNING) << "Received invalid push stream id " << id;
connection()->CloseConnection(
quic::QUIC_INVALID_STREAM_ID,
"Server created non write unidirectional stream",
quic::ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
return false;
}
return true;
}
QuicChromiumClientStream* QuicChromiumClientSession::CreateIncomingStream(
quic::QuicStreamId id) {
if (!ShouldCreateIncomingStream(id)) {
return nullptr;
}
net::NetworkTrafficAnnotationTag traffic_annotation =
net::DefineNetworkTrafficAnnotation("quic_chromium_incoming_session", R"(
semantics {
sender: "Quic Chromium Client Session"
description:
"When a web server needs to push a response to a client, an incoming "
"stream is created to reply the client with pushed message instead "
"of a message from the network."
trigger:
"A request by a server to push a response to the client."
data: "None."
destination: OTHER
destination_other:
"This stream is not used for sending data."
}
policy {
cookies_allowed: NO
setting: "This feature cannot be disabled in settings."
policy_exception_justification:
"Essential for network access."
}
)");
return CreateIncomingReliableStreamImpl(id, traffic_annotation);
}
QuicChromiumClientStream* QuicChromiumClientSession::CreateIncomingStream(
quic::PendingStream* pending) {
net::NetworkTrafficAnnotationTag traffic_annotation =
net::DefineNetworkTrafficAnnotation(
"quic_chromium_incoming_pending_session", R"(
semantics {
sender: "Quic Chromium Client Session Pending Stream"
description:
"When a web server needs to push a response to a client, an incoming "
"stream is created to reply to the client with pushed message instead "
"of a message from the network."
trigger:
"A request by a server to push a response to the client."
data: "This stream is only used to receive data from the server."
destination: OTHER
destination_other:
"The web server pushing the response."
}
policy {
cookies_allowed: NO
setting: "This feature cannot be disabled in settings."
policy_exception_justification:
"Essential for network access."
}
)");
return CreateIncomingReliableStreamImpl(pending, traffic_annotation);
}
QuicChromiumClientStream*
QuicChromiumClientSession::CreateIncomingReliableStreamImpl(
quic::QuicStreamId id,
const NetworkTrafficAnnotationTag& traffic_annotation) {
DCHECK(connection()->connected());
QuicChromiumClientStream* stream = new QuicChromiumClientStream(
id, this, quic::READ_UNIDIRECTIONAL, net_log_, traffic_annotation);
ActivateStream(base::WrapUnique(stream));
++num_total_streams_;
return stream;
}
QuicChromiumClientStream*
QuicChromiumClientSession::CreateIncomingReliableStreamImpl(
quic::PendingStream* pending,
const NetworkTrafficAnnotationTag& traffic_annotation) {
DCHECK(connection()->connected());
QuicChromiumClientStream* stream =
new QuicChromiumClientStream(pending, this, net_log_, traffic_annotation);
ActivateStream(base::WrapUnique(stream));
++num_total_streams_;
return stream;
}
void QuicChromiumClientSession::OnStreamClosed(quic::QuicStreamId stream_id) {
most_recent_stream_close_time_ = tick_clock_->NowTicks();
quic::QuicStream* stream = GetActiveStream(stream_id);
if (stream != nullptr) {
logger_->UpdateReceivedFrameCounts(stream_id, stream->num_frames_received(),
stream->num_duplicate_frames_received());
if (quic::QuicUtils::IsServerInitiatedStreamId(
connection()->transport_version(), stream_id)) {
bytes_pushed_count_ += stream->stream_bytes_read();
}
}
quic::QuicSpdyClientSessionBase::OnStreamClosed(stream_id);
}
void QuicChromiumClientSession::OnCanCreateNewOutgoingStream(
bool unidirectional) {
if (CanOpenNextOutgoingBidirectionalStream() && !stream_requests_.empty() &&
crypto_stream_->encryption_established() && !goaway_received() &&
!going_away_ && connection()->connected()) {
StreamRequest* request = stream_requests_.front();
// TODO(ckrasic) - analyze data and then add logic to mark QUIC
// broken if wait times are excessive.
UMA_HISTOGRAM_TIMES("Net.QuicSession.PendingStreamsWaitTime",
tick_clock_->NowTicks() - request->pending_start_time_);
stream_requests_.pop_front();
request->OnRequestCompleteSuccess(
CreateOutgoingReliableStreamImpl(request->traffic_annotation())
->CreateHandle());
}
}
void QuicChromiumClientSession::OnConfigNegotiated() {
quic::QuicSpdyClientSessionBase::OnConfigNegotiated();
if (!stream_factory_ || !stream_factory_->allow_server_migration()) {
if (connection()->connection_migration_use_new_cid()) {
if (!config()->HasReceivedPreferredAddressConnectionIdAndToken()) {
return;
}
} else {
if (!config()->HasReceivedIPv6AlternateServerAddress() &&
!config()->HasReceivedIPv4AlternateServerAddress()) {
return;
}
}
}
// Server has sent an alternate address to connect to.
IPEndPoint old_address;
GetDefaultSocket()->GetPeerAddress(&old_address);
// Migrate only if address families match.
IPEndPoint new_address;
if (old_address.GetFamily() == ADDRESS_FAMILY_IPV6) {
if (!config()->HasReceivedIPv6AlternateServerAddress()) {
return;
}
new_address = ToIPEndPoint(config()->ReceivedIPv6AlternateServerAddress());
} else if (old_address.GetFamily() == ADDRESS_FAMILY_IPV4) {
if (!config()->HasReceivedIPv4AlternateServerAddress()) {
return;
}
new_address = ToIPEndPoint(config()->ReceivedIPv4AlternateServerAddress());
}
DCHECK_EQ(new_address.GetFamily(), old_address.GetFamily());
// Specifying kInvalidNetworkHandle for the |network| parameter
// causes the session to use the default network for the new socket.
Migrate(NetworkChangeNotifier::kInvalidNetworkHandle, new_address,
/*close_session_on_error=*/true);
}
void QuicChromiumClientSession::SetDefaultEncryptionLevel(
quic::EncryptionLevel level) {
if (!callback_.is_null() &&
(!require_confirmation_ || level == quic::ENCRYPTION_FORWARD_SECURE ||
level == quic::ENCRYPTION_ZERO_RTT)) {
// Currently for all CryptoHandshakeEvent events, callback_
// could be called because there are no error events in CryptoHandshakeEvent
// enum. If error events are added to CryptoHandshakeEvent, then the
// following code needs to changed.
std::move(callback_).Run(OK);
}
if (level == quic::ENCRYPTION_FORWARD_SECURE) {
OnCryptoHandshakeComplete();
LogZeroRttStats();
}
if (level == quic::ENCRYPTION_ZERO_RTT)
attempted_zero_rtt_ = true;
quic::QuicSpdySession::SetDefaultEncryptionLevel(level);
}
void QuicChromiumClientSession::OnTlsHandshakeComplete() {
if (!callback_.is_null()) {
// Currently for all CryptoHandshakeEvent events, callback_
// could be called because there are no error events in CryptoHandshakeEvent
// enum. If error events are added to CryptoHandshakeEvent, then the
// following code needs to changed.
std::move(callback_).Run(OK);
}
OnCryptoHandshakeComplete();
LogZeroRttStats();
quic::QuicSpdySession::OnTlsHandshakeComplete();
}
void QuicChromiumClientSession::OnNewEncryptionKeyAvailable(
quic::EncryptionLevel level,
std::unique_ptr<quic::QuicEncrypter> encrypter) {
if (!attempted_zero_rtt_ && (level == quic::ENCRYPTION_ZERO_RTT ||
level == quic::ENCRYPTION_FORWARD_SECURE)) {
base::TimeTicks now = tick_clock_->NowTicks();
DCHECK_LE(connect_timing_.connect_start, now);
UMA_HISTOGRAM_TIMES("Net.QuicSession.EncryptionEstablishedTime",
now - connect_timing_.connect_start);
}
if (level == quic::ENCRYPTION_ZERO_RTT)
attempted_zero_rtt_ = true;
QuicSpdySession::OnNewEncryptionKeyAvailable(level, std::move(encrypter));
if (!callback_.is_null() &&
(!require_confirmation_ && level == quic::ENCRYPTION_ZERO_RTT)) {
// Currently for all CryptoHandshakeEvent events, callback_
// could be called because there are no error events in CryptoHandshakeEvent
// enum. If error events are added to CryptoHandshakeEvent, then the
// following code needs to changed.
std::move(callback_).Run(OK);
}
}
void QuicChromiumClientSession::LogZeroRttStats() {
DCHECK(OneRttKeysAvailable());
ZeroRttState state;
ssl_early_data_reason_t early_data_reason = crypto_stream_->EarlyDataReason();
if (early_data_reason == ssl_early_data_accepted) {
state = ZeroRttState::kAttemptedAndSucceeded;
} else if (early_data_reason == ssl_early_data_peer_declined ||
early_data_reason == ssl_early_data_session_not_resumed ||
early_data_reason == ssl_early_data_hello_retry_request) {
state = ZeroRttState::kAttemptedAndRejected;
} else {
state = ZeroRttState::kNotAttempted;
}
UMA_HISTOGRAM_ENUMERATION("Net.QuicSession.ZeroRttState", state);
UMA_HISTOGRAM_ENUMERATION("Net.QuicSession.ZeroRttReason", early_data_reason,
ssl_early_data_reason_max_value + 1);
if (IsGoogleHost(session_key_.host())) {
UMA_HISTOGRAM_ENUMERATION("Net.QuicSession.ZeroRttReasonGoogle",
early_data_reason,
ssl_early_data_reason_max_value + 1);
} else {
UMA_HISTOGRAM_ENUMERATION("Net.QuicSession.ZeroRttReasonNonGoogle",
early_data_reason,
ssl_early_data_reason_max_value + 1);
}
}
void QuicChromiumClientSession::OnCryptoHandshakeMessageSent(
const quic::CryptoHandshakeMessage& message) {
logger_->OnCryptoHandshakeMessageSent(message);
}
void QuicChromiumClientSession::OnCryptoHandshakeMessageReceived(
const quic::CryptoHandshakeMessage& message) {
logger_->OnCryptoHandshakeMessageReceived(message);
if (message.tag() == quic::kREJ) {
UMA_HISTOGRAM_CUSTOM_COUNTS("Net.QuicSession.RejectLength",
message.GetSerialized().length(), 1000, 10000,
50);
absl::string_view proof;
UMA_HISTOGRAM_BOOLEAN("Net.QuicSession.RejectHasProof",
message.GetStringPiece(quic::kPROF, &proof));
}
}
void QuicChromiumClientSession::OnGoAway(const quic::QuicGoAwayFrame& frame) {
quic::QuicSession::OnGoAway(frame);
NotifyFactoryOfSessionGoingAway();
port_migration_detected_ =
frame.error_code == quic::QUIC_ERROR_MIGRATING_PORT;
}
void QuicChromiumClientSession::OnConnectionClosed(
const quic::QuicConnectionCloseFrame& frame,
quic::ConnectionCloseSource source) {
DCHECK(!connection()->connected());
logger_->OnConnectionClosed(frame, source);
RecordConnectionCloseErrorCode(frame, source, session_key_.host(),
OneRttKeysAvailable());
if (OneRttKeysAvailable()) {
NetworkChangeNotifier::NetworkHandle current_network = GetCurrentNetwork();
for (auto& observer : connectivity_observer_list_)
observer.OnSessionClosedAfterHandshake(this, current_network, source,
frame.quic_error_code);
}
const quic::QuicErrorCode error = frame.quic_error_code;
const std::string& error_details = frame.error_details;
if (source == quic::ConnectionCloseSource::FROM_SELF &&
error == quic::QUIC_NETWORK_IDLE_TIMEOUT && ShouldKeepConnectionAlive()) {
quic::QuicStreamCount streams_waiting_to_write = 0;
PerformActionOnActiveStreams(
[&streams_waiting_to_write](quic::QuicStream* stream) {
if (stream->HasBufferedData())
++streams_waiting_to_write;
return true;
});
UMA_HISTOGRAM_COUNTS_100(
"Net.QuicSession.NumStreamsWaitingToWriteOnIdleTimeout",
streams_waiting_to_write);
UMA_HISTOGRAM_COUNTS_100("Net.QuicSession.NumActiveStreamsOnIdleTimeout",
GetNumActiveStreams());
}
if (source == quic::ConnectionCloseSource::FROM_PEER) {
if (error == quic::QUIC_PUBLIC_RESET) {
// is_from_google_server will be true if the received EPID is
// kEPIDGoogleFrontEnd or kEPIDGoogleFrontEnd0.
const bool is_from_google_server =
error_details.find(base::StringPrintf(
"From %s", quic::kEPIDGoogleFrontEnd)) != std::string::npos;
if (OneRttKeysAvailable()) {
UMA_HISTOGRAM_BOOLEAN(
"Net.QuicSession.ClosedByPublicReset.HandshakeConfirmed",
is_from_google_server);
} else {
UMA_HISTOGRAM_BOOLEAN("Net.QuicSession.ClosedByPublicReset",
is_from_google_server);
}
if (is_from_google_server) {
UMA_HISTOGRAM_COUNTS_100(
"Net.QuicSession.NumMigrationsExercisedBeforePublicReset",
sockets_.size() - 1);
}
base::UmaHistogramSparse(
"Net.QuicSession.LastSentPacketContentBeforePublicReset",
connection()
->sent_packet_manager()
.unacked_packets()
.GetLastPacketContent());
const quic::QuicTime last_in_flight_packet_sent_time =
connection()
->sent_packet_manager()
.unacked_packets()
.GetLastInFlightPacketSentTime();
const quic::QuicTime handshake_completion_time =
connection()->GetStats().handshake_completion_time;
if (last_in_flight_packet_sent_time.IsInitialized() &&
handshake_completion_time.IsInitialized() &&
last_in_flight_packet_sent_time >= handshake_completion_time) {
const quic::QuicTime::Delta delay =
last_in_flight_packet_sent_time - handshake_completion_time;
UMA_HISTOGRAM_LONG_TIMES_100(
"Net.QuicSession."
"LastInFlightPacketSentTimeFromHandshakeCompletionWithPublicReset",
base::Milliseconds(delay.ToMilliseconds()));
}
UMA_HISTOGRAM_LONG_TIMES_100(
"Net.QuicSession.ConnectionDurationWithPublicReset",
tick_clock_->NowTicks() - connect_timing_.connect_end);
}
if (OneRttKeysAvailable()) {
base::HistogramBase* histogram = base::SparseHistogram::FactoryGet(
"Net.QuicSession.StreamCloseErrorCodeServer.HandshakeConfirmed",
base::HistogramBase::kUmaTargetedHistogramFlag);
size_t num_streams = GetNumActiveStreams();
if (num_streams > 0)
histogram->AddCount(error, num_streams);
}
} else {
if (OneRttKeysAvailable()) {
base::HistogramBase* histogram = base::SparseHistogram::FactoryGet(
"Net.QuicSession.StreamCloseErrorCodeClient.HandshakeConfirmed",
base::HistogramBase::kUmaTargetedHistogramFlag);
size_t num_streams = GetNumActiveStreams();
if (num_streams > 0)
histogram->AddCount(error, num_streams);
} else {
if (error == quic::QUIC_HANDSHAKE_TIMEOUT) {
UMA_HISTOGRAM_BOOLEAN(
"Net.QuicSession.HandshakeTimeout.PathDegradingDetected",
connection()->IsPathDegrading());
}
}
if (error == quic::QUIC_TOO_MANY_RTOS) {
UMA_HISTOGRAM_COUNTS_1000(
"Net.QuicSession.ClosedByRtoAtClient.ReceivedPacketCount",
connection()->GetStats().packets_received);
UMA_HISTOGRAM_COUNTS_1000(
"Net.QuicSession.ClosedByRtoAtClient.SentPacketCount",
connection()->GetStats().packets_sent);
UMA_HISTOGRAM_COUNTS_100(
"Net.QuicSession."
"MaxConsecutiveRtoWithForwardProgressAndBlackholeDetected",
connection()->GetStats().max_consecutive_rto_with_forward_progress);
}
}
if (error == quic::QUIC_NETWORK_IDLE_TIMEOUT) {
UMA_HISTOGRAM_COUNTS_1M(
"Net.QuicSession.ConnectionClose.NumOpenStreams.TimedOut",
GetNumActiveStreams());
if (OneRttKeysAvailable()) {
if (GetNumActiveStreams() > 0) {
UMA_HISTOGRAM_BOOLEAN(
"Net.QuicSession.TimedOutWithOpenStreams.HasUnackedPackets",
connection()->sent_packet_manager().HasInFlightPackets());
UMA_HISTOGRAM_COUNTS_1M(
"Net.QuicSession.TimedOutWithOpenStreams.ConsecutiveRTOCount",
connection()->sent_packet_manager().GetConsecutiveRtoCount());
UMA_HISTOGRAM_COUNTS_1M(
"Net.QuicSession.TimedOutWithOpenStreams.ConsecutiveTLPCount",
connection()->sent_packet_manager().GetConsecutiveTlpCount());
base::UmaHistogramSparse(
"Net.QuicSession.TimedOutWithOpenStreams.LocalPort",
connection()->self_address().port());
}
} else {
UMA_HISTOGRAM_COUNTS_1M(
"Net.QuicSession.ConnectionClose.NumOpenStreams.HandshakeTimedOut",
GetNumActiveStreams());
UMA_HISTOGRAM_COUNTS_1M(
"Net.QuicSession.ConnectionClose.NumTotalStreams.HandshakeTimedOut",
num_total_streams_);
}
}
if (OneRttKeysAvailable()) {
// QUIC connections should not timeout while there are open streams,
// since PING frames are sent to prevent timeouts. If, however, the
// connection timed out with open streams then QUIC traffic has become
// blackholed. Alternatively, if too many retransmission timeouts occur
// then QUIC traffic has become blackholed.
if (stream_factory_ && (error == quic::QUIC_TOO_MANY_RTOS ||
(error == quic::QUIC_NETWORK_IDLE_TIMEOUT &&
GetNumActiveStreams() > 0))) {
stream_factory_->OnBlackholeAfterHandshakeConfirmed(this);
}
UMA_HISTOGRAM_COUNTS_100(
"Net.QuicSession.CryptoRetransmitCount.HandshakeConfirmed",
connection()->GetStats().crypto_retransmit_count);
UMA_HISTOGRAM_COUNTS_100(
"Net.QuicSession.MaxConsecutiveRtoWithForwardProgress",
connection()->GetStats().max_consecutive_rto_with_forward_progress);
UMA_HISTOGRAM_COUNTS_1000("Net.QuicSession.NumPingsSent",
connection()->GetStats().ping_frames_sent);
UMA_HISTOGRAM_LONG_TIMES_100(
"Net.QuicSession.ConnectionDuration",
tick_clock_->NowTicks() - connect_timing_.connect_end);
UMA_HISTOGRAM_COUNTS_100("Net.QuicSession.NumMigrations", num_migrations_);
// These values are persisted to logs. Entries should not be renumbered
// and numeric values should never be reused.
enum class KeyUpdateSupported {
kInvalid = 0,
kUnsupported = 1,
kSupported = 2,
kSupportedLocallyOnly = 3,
kSupportedRemotelyOnly = 4,
kMaxValue = kSupportedRemotelyOnly,
};
KeyUpdateSupported key_update_supported = KeyUpdateSupported::kInvalid;
if (config()->KeyUpdateSupportedForConnection()) {
key_update_supported = KeyUpdateSupported::kSupported;
} else if (config()->KeyUpdateSupportedLocally()) {
key_update_supported = KeyUpdateSupported::kSupportedLocallyOnly;
} else if (config()->KeyUpdateSupportedRemotely()) {
key_update_supported = KeyUpdateSupported::kSupportedRemotelyOnly;
} else {
key_update_supported = KeyUpdateSupported::kUnsupported;
}
base::UmaHistogramEnumeration("Net.QuicSession.KeyUpdate.Supported",
key_update_supported);
if (config()->KeyUpdateSupportedForConnection()) {
base::UmaHistogramCounts100("Net.QuicSession.KeyUpdate.PerConnection2",
connection()->GetStats().key_update_count);
base::UmaHistogramCounts100(
"Net.QuicSession.KeyUpdate.PotentialPeerKeyUpdateAttemptCount",
connection()->PotentialPeerKeyUpdateAttemptCount());
if (last_key_update_reason_ != quic::KeyUpdateReason::kInvalid) {
std::string suffix =
last_key_update_reason_ == quic::KeyUpdateReason::kRemote ? "Remote"
: "Local";
// These values are persisted to logs. Entries should not be renumbered
// and numeric values should never be reused.
enum class KeyUpdateSuccess {
kInvalid = 0,
kSuccess = 1,
kFailedInitial = 2,
kFailedNonInitial = 3,
kMaxValue = kFailedNonInitial,
};
KeyUpdateSuccess value = KeyUpdateSuccess::kInvalid;
if (connection()->HaveSentPacketsInCurrentKeyPhaseButNoneAcked()) {
if (connection()->GetStats().key_update_count >= 2) {
value = KeyUpdateSuccess::kFailedNonInitial;
} else {
value = KeyUpdateSuccess::kFailedInitial;
}
} else {
value = KeyUpdateSuccess::kSuccess;
}
base::UmaHistogramEnumeration(
"Net.QuicSession.KeyUpdate.Success." + suffix, value);
}
}
} else {
if (error == quic::QUIC_PUBLIC_RESET) {
RecordHandshakeFailureReason(HANDSHAKE_FAILURE_PUBLIC_RESET);
} else if (connection()->GetStats().packets_received == 0) {
RecordHandshakeFailureReason(HANDSHAKE_FAILURE_BLACK_HOLE);
base::UmaHistogramSparse(
"Net.QuicSession.ConnectionClose.HandshakeFailureBlackHole.QuicError",
error);
} else {
RecordHandshakeFailureReason(HANDSHAKE_FAILURE_UNKNOWN);
base::UmaHistogramSparse(
"Net.QuicSession.ConnectionClose.HandshakeFailureUnknown.QuicError",
error);
}
UMA_HISTOGRAM_COUNTS_100(
"Net.QuicSession.CryptoRetransmitCount.HandshakeNotConfirmed",
connection()->GetStats().crypto_retransmit_count);
}
base::UmaHistogramCounts1M(
"Net.QuicSession.UndecryptablePacketsReceivedWithDecrypter",
connection()->GetStats().num_failed_authentication_packets_received);
base::UmaHistogramSparse("Net.QuicSession.QuicVersion",
connection()->transport_version());
NotifyFactoryOfSessionGoingAway();
quic::QuicSession::OnConnectionClosed(frame, source);
if (!callback_.is_null()) {
std::move(callback_).Run(ERR_QUIC_PROTOCOL_ERROR);
}
CHECK_EQ(sockets_.size(), packet_readers_.size());
for (auto& socket : sockets_) {
socket->Close();
}
DCHECK(!HasActiveRequestStreams());
CloseAllHandles(ERR_UNEXPECTED);
CancelAllRequests(ERR_CONNECTION_CLOSED);
NotifyRequestsOfConfirmation(ERR_CONNECTION_CLOSED);
NotifyFactoryOfSessionClosedLater();
}
void QuicChromiumClientSession::OnSuccessfulVersionNegotiation(
const quic::ParsedQuicVersion& version) {
logger_->OnSuccessfulVersionNegotiation(version);
quic::QuicSpdySession::OnSuccessfulVersionNegotiation(version);
}
void QuicChromiumClientSession::OnPacketReceived(
const quic::QuicSocketAddress& self_address,
const quic::QuicSocketAddress& peer_address,
bool is_connectivity_probe) {
// Notify the probing manager that a new packet is received.
probing_manager_.OnPacketReceived(self_address, peer_address,
is_connectivity_probe);
}
int QuicChromiumClientSession::HandleWriteError(
int error_code,
scoped_refptr<QuicChromiumPacketWriter::ReusableIOBuffer> packet) {
current_migration_cause_ = ON_WRITE_ERROR;
LogHandshakeStatusOnMigrationSignal();
base::UmaHistogramSparse("Net.QuicSession.WriteError", -error_code);
if (OneRttKeysAvailable()) {
base::UmaHistogramSparse("Net.QuicSession.WriteError.HandshakeConfirmed",
-error_code);
}
// For now, skip reporting if there are multiple packet writers and
// connection migration is enabled.
if (sockets_.size() == 1u || !migrate_session_early_v2_) {
NetworkChangeNotifier::NetworkHandle current_network = GetCurrentNetwork();
for (auto& observer : connectivity_observer_list_) {
observer.OnSessionEncounteringWriteError(this, current_network,
error_code);
}
}
if (error_code == ERR_MSG_TOO_BIG || stream_factory_ == nullptr ||
!migrate_session_on_network_change_v2_ || !OneRttKeysAvailable()) {
return error_code;
}
NetworkChangeNotifier::NetworkHandle current_network = GetCurrentNetwork();
net_log_.AddEventWithInt64Params(
NetLogEventType::QUIC_CONNECTION_MIGRATION_ON_WRITE_ERROR, "network",
current_network);
DCHECK(packet != nullptr);
DCHECK_NE(ERR_IO_PENDING, error_code);
DCHECK_GT(0, error_code);
DCHECK(packet_ == nullptr);
// Post a task to migrate the session onto a new network.
task_runner_->PostTask(
FROM_HERE,
base::BindOnce(&QuicChromiumClientSession::MigrateSessionOnWriteError,
weak_factory_.GetWeakPtr(), error_code,
connection()->writer()));
// Only save packet from the old path for retransmission on the new path when
// the connection ID does not change.
if (!connection()->connection_migration_use_new_cid()) {
// Store packet in the session since the actual migration and packet rewrite
// can happen via this posted task or via an async network notification.
packet_ = std::move(packet);
}
ignore_read_error_ = true;
// Cause the packet writer to return ERR_IO_PENDING and block so
// that the actual migration happens from the message loop instead
// of under the call stack of quic::QuicConnection::WritePacket.
return ERR_IO_PENDING;
}
void QuicChromiumClientSession::MigrateSessionOnWriteError(
int error_code,
quic::QuicPacketWriter* writer) {
DCHECK(migrate_session_on_network_change_v2_);
// If |writer| is no longer actively in use, abort this migration attempt.
if (writer != connection()->writer())
return;
most_recent_write_error_timestamp_ = tick_clock_->NowTicks();
most_recent_write_error_ = error_code;
if (stream_factory_ == nullptr) {
// Close the connection if migration failed. Do not cause a
// connection close packet to be sent since socket may be borked.
connection()->CloseConnection(quic::QUIC_PACKET_WRITE_ERROR,
"Write error with nulled stream factory",
quic::ConnectionCloseBehavior::SILENT_CLOSE);
return;
}
current_migration_cause_ = ON_WRITE_ERROR;
if (migrate_idle_session_ && CheckIdleTimeExceedsIdleMigrationPeriod())
return;
if (!migrate_idle_session_ && !HasActiveRequestStreams()) {
// connection close packet to be sent since socket may be borked.
connection()->CloseConnection(quic::QUIC_PACKET_WRITE_ERROR,
"Write error for non-migratable session",
quic::ConnectionCloseBehavior::SILENT_CLOSE);
return;
}
// Do not migrate if connection migration is disabled.
if (config()->DisableConnectionMigration()) {
HistogramAndLogMigrationFailure(MIGRATION_STATUS_DISABLED_BY_CONFIG,
connection_id(),
"Migration disabled by config");
// Close the connection since migration was disabled. Do not cause a
// connection close packet to be sent since socket may be borked.
connection()->CloseConnection(quic::QUIC_PACKET_WRITE_ERROR,
"Write error for non-migratable session",
quic::ConnectionCloseBehavior::SILENT_CLOSE);
return;
}
NetworkChangeNotifier::NetworkHandle new_network =
stream_factory_->FindAlternateNetwork(GetCurrentNetwork());
if (new_network == NetworkChangeNotifier::kInvalidNetworkHandle) {
// No alternate network found.
HistogramAndLogMigrationFailure(MIGRATION_STATUS_NO_ALTERNATE_NETWORK,
connection_id(),
"No alternate network found");
OnNoNewNetwork();
return;
}
if (GetCurrentNetwork() == default_network_ &&
current_migrations_to_non_default_network_on_write_error_ >=
max_migrations_to_non_default_network_on_write_error_) {
HistogramAndLogMigrationFailure(
MIGRATION_STATUS_ON_WRITE_ERROR_DISABLED, connection_id(),
"Exceeds maximum number of migrations on write error");
connection()->CloseConnection(
quic::QUIC_PACKET_WRITE_ERROR,
"Too many migrations for write error for the same network",
quic::ConnectionCloseBehavior::SILENT_CLOSE);
return;
}
current_migrations_to_non_default_network_on_write_error_++;
net_log_.BeginEventWithStringParams(
NetLogEventType::QUIC_CONNECTION_MIGRATION_TRIGGERED, "trigger",
"WriteError");
MigrationResult result =
Migrate(new_network, ToIPEndPoint(connection()->peer_address()),
/*close_session_on_error=*/false);
net_log_.EndEvent(NetLogEventType::QUIC_CONNECTION_MIGRATION_TRIGGERED);
if (result == MigrationResult::FAILURE) {
// Close the connection if migration failed. Do not cause a
// connection close packet to be sent since socket may be borked.
connection()->CloseConnection(quic::QUIC_PACKET_WRITE_ERROR,
"Write and subsequent migration failed",
quic::ConnectionCloseBehavior::SILENT_CLOSE);
return;
}
if (new_network != default_network_) {
StartMigrateBackToDefaultNetworkTimer(
base::Seconds(kMinRetryTimeForDefaultNetworkSecs));
} else {
CancelMigrateBackToDefaultNetworkTimer();
}
}
void QuicChromiumClientSession::OnNoNewNetwork() {
DCHECK(OneRttKeysAvailable());
wait_for_new_network_ = true;
DVLOG(1) << "Force blocking the packet writer";
// Force blocking the packet writer to avoid any writes since there is no
// alternate network available.
static_cast<QuicChromiumPacketWriter*>(connection()->writer())
->set_force_write_blocked(true);
// Post a task to maybe close the session if the alarm fires.
task_runner_->PostDelayedTask(
FROM_HERE,
base::BindOnce(&QuicChromiumClientSession::OnMigrationTimeout,
weak_factory_.GetWeakPtr(), sockets_.size()),
base::Seconds(kWaitTimeForNewNetworkSecs));
}
void QuicChromiumClientSession::WriteToNewSocket() {
// Set |send_packet_after_migration_| to true so that a packet will be
// sent when the writer becomes unblocked.
send_packet_after_migration_ = true;
DVLOG(1) << "Cancel force blocking the packet writer";
// Notify writer that it is no longer forced blocked, which may call
// OnWriteUnblocked() if the writer has no write in progress.
static_cast<QuicChromiumPacketWriter*>(connection()->writer())
->set_force_write_blocked(false);
}
void QuicChromiumClientSession::OnMigrationTimeout(size_t num_sockets) {
// If number of sockets has changed, this migration task is stale.
if (num_sockets != sockets_.size())
return;
int net_error = current_migration_cause_ == ON_NETWORK_DISCONNECTED
? ERR_INTERNET_DISCONNECTED
: ERR_NETWORK_CHANGED;
// |current_migration_cause_| will be reset after logging.
LogMigrationResultToHistogram(MIGRATION_STATUS_TIMEOUT);
CloseSessionOnError(net_error, quic::QUIC_CONNECTION_MIGRATION_NO_NEW_NETWORK,
quic::ConnectionCloseBehavior::SILENT_CLOSE);
}
// TODO(renjietang): Deprecate this method once IETF QUIC supports connection
// migration.
void QuicChromiumClientSession::OnProbeSucceeded(
NetworkChangeNotifier::NetworkHandle network,
const quic::QuicSocketAddress& peer_address,
const quic::QuicSocketAddress& self_address,
std::unique_ptr<DatagramClientSocket> socket,
std::unique_ptr<QuicChromiumPacketWriter> writer,
std::unique_ptr<QuicChromiumPacketReader> reader) {
if (current_migration_cause_ == CHANGE_PORT_ON_PATH_DEGRADING) {
DCHECK(allow_port_migration_);
OnPortMigrationProbeSucceeded(network, peer_address, self_address,
std::move(socket), std::move(writer),
std::move(reader));
return;
}
OnConnectionMigrationProbeSucceeded(network, peer_address, self_address,
std::move(socket), std::move(writer),
std::move(reader));
}
void QuicChromiumClientSession::OnPortMigrationProbeSucceeded(
NetworkChangeNotifier::NetworkHandle network,
const quic::QuicSocketAddress& peer_address,
const quic::QuicSocketAddress& self_address,
std::unique_ptr<DatagramClientSocket> socket,
std::unique_ptr<QuicChromiumPacketWriter> writer,
std::unique_ptr<QuicChromiumPacketReader> reader) {
DCHECK(socket);
DCHECK(writer);
DCHECK(reader);
net_log_.AddEvent(NetLogEventType::QUIC_SESSION_CONNECTIVITY_PROBING_FINISHED,
[&] {
return NetLogProbingResultParams(network, &peer_address,
/*is_success=*/true);
});
LogProbeResultToHistogram(current_migration_cause_, true);
// Remove |this| as the old packet writer's delegate. Write error on old
// writers will be ignored.
// Set |this| to listen on socket write events on the packet writer
// that was used for probing.
static_cast<QuicChromiumPacketWriter*>(connection()->writer())
->set_delegate(nullptr);
writer->set_delegate(this);
if (!migrate_idle_session_ && !HasActiveRequestStreams()) {
// If idle sessions won't be migrated, close the connection.
CloseSessionOnErrorLater(
ERR_NETWORK_CHANGED,
quic::QUIC_CONNECTION_MIGRATION_NO_MIGRATABLE_STREAMS,
quic::ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
return;
}
if (migrate_idle_session_ && CheckIdleTimeExceedsIdleMigrationPeriod())
return;
// Migrate to the probed socket immediately: socket, writer and reader will
// be acquired by connection and used as default on success.
if (!MigrateToSocket(self_address, peer_address, std::move(socket),
std::move(reader), std::move(writer))) {
LogMigrateToSocketStatus(false);
net_log_.AddEvent(
NetLogEventType::QUIC_CONNECTION_MIGRATION_FAILURE_AFTER_PROBING);
return;
}
LogMigrateToSocketStatus(true);
num_migrations_++;
HistogramAndLogMigrationSuccess(connection_id());
}
void QuicChromiumClientSession::OnConnectionMigrationProbeSucceeded(
NetworkChangeNotifier::NetworkHandle network,
const quic::QuicSocketAddress& peer_address,
const quic::QuicSocketAddress& self_address,
std::unique_ptr<DatagramClientSocket> socket,
std::unique_ptr<QuicChromiumPacketWriter> writer,
std::unique_ptr<QuicChromiumPacketReader> reader) {
DCHECK(socket);
DCHECK(writer);
DCHECK(reader);
net_log_.AddEvent(NetLogEventType::QUIC_SESSION_CONNECTIVITY_PROBING_FINISHED,
[&] {
return NetLogProbingResultParams(network, &peer_address,
/*is_success=*/true);
});
if (network == NetworkChangeNotifier::kInvalidNetworkHandle)
return;
LogProbeResultToHistogram(current_migration_cause_, true);
// Remove |this| as the old packet writer's delegate. Write error on old
// writers will be ignored.
// Set |this| to listen on socket write events on the packet writer
// that was used for probing.
static_cast<QuicChromiumPacketWriter*>(connection()->writer())
->set_delegate(nullptr);
writer->set_delegate(this);
// Close streams that are not migratable to the probed |network|.
ResetNonMigratableStreams();
if (!migrate_idle_session_ && !HasActiveRequestStreams()) {
// If idle sessions won't be migrated, close the connection.
CloseSessionOnErrorLater(
ERR_NETWORK_CHANGED,
quic::QUIC_CONNECTION_MIGRATION_NO_MIGRATABLE_STREAMS,
quic::ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
return;
}
if (migrate_idle_session_ && CheckIdleTimeExceedsIdleMigrationPeriod())
return;
// Migrate to the probed socket immediately: socket, writer and reader will
// be acquired by connection and used as default on success.
if (!MigrateToSocket(self_address, peer_address, std::move(socket),
std::move(reader), std::move(writer))) {
LogMigrateToSocketStatus(false);
net_log_.AddEvent(
NetLogEventType::QUIC_CONNECTION_MIGRATION_FAILURE_AFTER_PROBING);
return;
}
LogMigrateToSocketStatus(true);
net_log_.AddEventWithInt64Params(
NetLogEventType::QUIC_CONNECTION_MIGRATION_SUCCESS_AFTER_PROBING,
"migrate_to_network", network);
num_migrations_++;
HistogramAndLogMigrationSuccess(connection_id());
if (network == default_network_) {
DVLOG(1) << "Client successfully migrated to default network: "
<< default_network_;
CancelMigrateBackToDefaultNetworkTimer();
return;
}
DVLOG(1) << "Client successfully got off default network after "
<< "successful probing network: " << network << ".";
current_migrations_to_non_default_network_on_path_degrading_++;
if (!migrate_back_to_default_timer_.IsRunning()) {
current_migration_cause_ = ON_MIGRATE_BACK_TO_DEFAULT_NETWORK;
// Session gets off the |default_network|, stay on |network| for now but
// try to migrate back to default network after 1 second.
StartMigrateBackToDefaultNetworkTimer(
base::Seconds(kMinRetryTimeForDefaultNetworkSecs));
}
}
void QuicChromiumClientSession::OnProbeFailed(
NetworkChangeNotifier::NetworkHandle network,
const quic::QuicSocketAddress& peer_address) {
net_log_.AddEvent(NetLogEventType::QUIC_SESSION_CONNECTIVITY_PROBING_FINISHED,
[&] {
return NetLogProbingResultParams(network, &peer_address,
/*is_success=*/false);
});
if (connection()->connection_migration_use_new_cid()) {
auto* context = static_cast<QuicChromiumPathValidationContext*>(
connection()->GetPathValidationContext());
if (!context)
return;
if (context->network() == network &&
context->peer_address() == peer_address) {
connection()->CancelPathValidation();
}
}
LogProbeResultToHistogram(current_migration_cause_, false);
if (network != NetworkChangeNotifier::kInvalidNetworkHandle) {
// Probing failure can be ignored.
DVLOG(1) << "Connectivity probing failed on <network: " << network
<< ", peer_address: " << peer_address.ToString() << ">.";
DVLOG_IF(1, network == default_network_ &&
GetCurrentNetwork() != default_network_)
<< "Client probing failed on the default network, still using "
"non-default network.";
}
}
bool QuicChromiumClientSession::OnSendConnectivityProbingPacket(
QuicChromiumPacketWriter* writer,
const quic::QuicSocketAddress& peer_address) {
return connection()->SendConnectivityProbingPacket(writer, peer_address);
}
void QuicChromiumClientSession::OnNetworkConnected(
NetworkChangeNotifier::NetworkHandle network) {
if (connection()->IsPathDegrading()) {
base::TimeDelta duration =
tick_clock_->NowTicks() - most_recent_path_degrading_timestamp_;
UMA_HISTOGRAM_CUSTOM_TIMES("Net.QuicNetworkDegradingDurationTillConnected",
duration, base::Milliseconds(1),
base::Minutes(10), 50);
}
if (!migrate_session_on_network_change_v2_)
return;
net_log_.AddEventWithInt64Params(
NetLogEventType::QUIC_CONNECTION_MIGRATION_ON_NETWORK_CONNECTED,
"connected_network", network);
// If there was no migration waiting for new network and the path is not
// degrading, ignore this signal.
if (!wait_for_new_network_ && !connection()->IsPathDegrading())
return;
if (connection()->IsPathDegrading())
current_migration_cause_ = NEW_NETWORK_CONNECTED_POST_PATH_DEGRADING;
if (wait_for_new_network_) {
wait_for_new_network_ = false;
if (current_migration_cause_ == ON_WRITE_ERROR)
current_migrations_to_non_default_network_on_write_error_++;
// |wait_for_new_network_| is true, there was no working network previously.
// |network| is now the only possible candidate, migrate immediately.
MigrateNetworkImmediately(network);
} else {
// The connection is path degrading.
DCHECK(connection()->IsPathDegrading());
MaybeMigrateToAlternateNetworkOnPathDegrading();
}
}
void QuicChromiumClientSession::OnNetworkDisconnectedV2(
NetworkChangeNotifier::NetworkHandle disconnected_network) {
LogMetricsOnNetworkDisconnected();
if (!migrate_session_on_network_change_v2_)
return;
net_log_.AddEventWithInt64Params(
NetLogEventType::QUIC_CONNECTION_MIGRATION_ON_NETWORK_DISCONNECTED,
"disconnected_network", disconnected_network);
// Stop probing the disconnected network if there is one.
if (connection()->connection_migration_use_new_cid()) {
auto* context = static_cast<QuicChromiumPathValidationContext*>(
connection()->GetPathValidationContext());
if (context && context->network() == disconnected_network &&
context->peer_address() == peer_address()) {
connection()->CancelPathValidation();
}
} else {
probing_manager_.CancelProbing(disconnected_network, peer_address());
}
if (disconnected_network == default_network_) {
DVLOG(1) << "Default network: " << default_network_ << " is disconnected.";
default_network_ = NetworkChangeNotifier::kInvalidNetworkHandle;
current_migrations_to_non_default_network_on_write_error_ = 0;
}
// Ignore the signal if the current active network is not affected.
if (GetCurrentNetwork() != disconnected_network) {
DVLOG(1) << "Client's current default network is not affected by the "
<< "disconnected one.";
return;
}
current_migration_cause_ = ON_NETWORK_DISCONNECTED;
LogHandshakeStatusOnMigrationSignal();
if (!OneRttKeysAvailable()) {
// Close the connection if handshake is not confirmed. Migration before
// handshake is not allowed.
CloseSessionOnErrorLater(
ERR_NETWORK_CHANGED,
quic::QUIC_CONNECTION_MIGRATION_HANDSHAKE_UNCONFIRMED,
quic::ConnectionCloseBehavior::SILENT_CLOSE);
return;
}
// Attempt to find alternative network.
NetworkChangeNotifier::NetworkHandle new_network =
stream_factory_->FindAlternateNetwork(disconnected_network);
if (new_network == NetworkChangeNotifier::kInvalidNetworkHandle) {
OnNoNewNetwork();
return;
}
// Current network is being disconnected, migrate immediately to the
// alternative network.
MigrateNetworkImmediately(new_network);
}
void QuicChromiumClientSession::OnNetworkMadeDefault(
NetworkChangeNotifier::NetworkHandle new_network) {
LogMetricsOnNetworkMadeDefault();
if (!migrate_session_on_network_change_v2_)
return;
DCHECK_NE(NetworkChangeNotifier::kInvalidNetworkHandle, new_network);
net_log_.AddEventWithInt64Params(
NetLogEventType::QUIC_CONNECTION_MIGRATION_ON_NETWORK_MADE_DEFAULT,
"new_default_network", new_network);
default_network_ = new_network;
DVLOG(1) << "Network: " << new_network
<< " becomes default, old default: " << default_network_;
current_migration_cause_ = ON_NETWORK_MADE_DEFAULT;
current_migrations_to_non_default_network_on_write_error_ = 0;
current_migrations_to_non_default_network_on_path_degrading_ = 0;
// Simply cancel the timer to migrate back to the default network if session
// is already on the default network.
if (GetCurrentNetwork() == new_network) {
CancelMigrateBackToDefaultNetworkTimer();
HistogramAndLogMigrationFailure(MIGRATION_STATUS_ALREADY_MIGRATED,
connection_id(),
"Already migrated on the new network");
return;
}
LogHandshakeStatusOnMigrationSignal();
// Stay on the current network. Try to migrate back to default network
// without any delay, which will start probing the new default network and
// migrate to the new network immediately on success.
StartMigrateBackToDefaultNetworkTimer(base::TimeDelta());
}
void QuicChromiumClientSession::MigrateNetworkImmediately(
NetworkChangeNotifier::NetworkHandle network) {
// There is no choice but to migrate to |network|. If any error encoutered,
// close the session. When migration succeeds:
// - if no longer on the default network, start timer to migrate back;
// - otherwise, it's brought to default network, cancel the running timer to
// migrate back.
if (!migrate_idle_session_ && !HasActiveRequestStreams()) {
HistogramAndLogMigrationFailure(MIGRATION_STATUS_NO_MIGRATABLE_STREAMS,
connection_id(), "No active streams");
CloseSessionOnErrorLater(
ERR_NETWORK_CHANGED,
quic::QUIC_CONNECTION_MIGRATION_NO_MIGRATABLE_STREAMS,
quic::ConnectionCloseBehavior::SILENT_CLOSE);
return;
}
if (migrate_idle_session_ && CheckIdleTimeExceedsIdleMigrationPeriod())
return;
// Do not migrate if connection migration is disabled.
if (config()->DisableConnectionMigration()) {
HistogramAndLogMigrationFailure(MIGRATION_STATUS_DISABLED_BY_CONFIG,
connection_id(),
"Migration disabled by config");
CloseSessionOnErrorLater(ERR_NETWORK_CHANGED,
quic::QUIC_CONNECTION_MIGRATION_DISABLED_BY_CONFIG,
quic::ConnectionCloseBehavior::SILENT_CLOSE);
return;
}
if (network == GetCurrentNetwork()) {
HistogramAndLogMigrationFailure(MIGRATION_STATUS_ALREADY_MIGRATED,
connection_id(),
"Already bound to new network");
return;
}
// Cancel probing on |network| if there is any.
if (connection()->connection_migration_use_new_cid()) {
auto* context = static_cast<QuicChromiumPathValidationContext*>(
connection()->GetPathValidationContext());
if (context && context->network() == network &&
context->peer_address() == peer_address()) {
connection()->CancelPathValidation();
}
} else {
probing_manager_.CancelProbing(network, peer_address());
}
MigrationResult result =
Migrate(network, ToIPEndPoint(connection()->peer_address()),
/*close_session_on_error=*/true);
if (result == MigrationResult::FAILURE)
return;
if (network == default_network_) {
CancelMigrateBackToDefaultNetworkTimer();
return;
}
// TODO(zhongyi): reconsider this, maybe we just want to hear back
// We are forced to migrate to |network|, probably |default_network_| is
// not working, start to migrate back to default network after 1 secs.
StartMigrateBackToDefaultNetworkTimer(
base::Seconds(kMinRetryTimeForDefaultNetworkSecs));
}
void QuicChromiumClientSession::OnWriteError(int error_code) {
DCHECK_NE(ERR_IO_PENDING, error_code);
DCHECK_GT(0, error_code);
connection()->OnWriteError(error_code);
}
void QuicChromiumClientSession::OnWriteUnblocked() {
DCHECK(!connection()->writer()->IsWriteBlocked());
// A new packet will be written after migration completes, unignore read
// errors.
if (ignore_read_error_)
ignore_read_error_ = false;
if (packet_) {
DCHECK(send_packet_after_migration_);
send_packet_after_migration_ = false;
static_cast<QuicChromiumPacketWriter*>(connection()->writer())
->WritePacketToSocket(std::move(packet_));
return;
}
// Unblock the connection, which may send queued packets.
connection()->OnCanWrite();
if (send_packet_after_migration_) {
send_packet_after_migration_ = false;
if (!connection()->writer()->IsWriteBlocked()) {
connection()->SendPing();
}
}
}
void QuicChromiumClientSession::OnPathDegrading() {
if (most_recent_path_degrading_timestamp_ == base::TimeTicks())
most_recent_path_degrading_timestamp_ = tick_clock_->NowTicks();
if (go_away_on_path_degrading_ && OneRttKeysAvailable()) {
net_log_.AddEvent(
NetLogEventType::QUIC_SESSION_CLIENT_GOAWAY_ON_PATH_DEGRADING);
NotifyFactoryOfSessionGoingAway();
UMA_HISTOGRAM_COUNTS_1M(
"Net.QuicSession.ActiveStreamsOnGoAwayAfterPathDegrading",
GetNumActiveStreams());
UMA_HISTOGRAM_COUNTS_1M(
"Net.QuicSession.DrainingStreamsOnGoAwayAfterPathDegrading",
num_outgoing_draining_streams());
return;
}
if (!go_away_on_path_degrading_) {
NetworkChangeNotifier::NetworkHandle current_network = GetCurrentNetwork();
for (auto& observer : connectivity_observer_list_)
observer.OnSessionPathDegrading(this, current_network);
}
if (!stream_factory_)
return;
if (allow_port_migration_) {
current_migration_cause_ = CHANGE_PORT_ON_PATH_DEGRADING;
MaybeMigrateToDifferentPortOnPathDegrading();
return;
}
MaybeMigrateToAlternateNetworkOnPathDegrading();
}
void QuicChromiumClientSession::OnForwardProgressMadeAfterPathDegrading() {
if (go_away_on_path_degrading_)
return;
NetworkChangeNotifier::NetworkHandle current_network = GetCurrentNetwork();
for (auto& observer : connectivity_observer_list_)
observer.OnSessionResumedPostPathDegrading(this, current_network);
}
void QuicChromiumClientSession::OnKeyUpdate(quic::KeyUpdateReason reason) {
net_log_.AddEventWithStringParams(NetLogEventType::QUIC_SESSION_KEY_UPDATE,
"reason",
quic::KeyUpdateReasonString(reason));
base::UmaHistogramEnumeration("Net.QuicSession.KeyUpdate.Reason", reason);
last_key_update_reason_ = reason;
}
void QuicChromiumClientSession::OnProofValid(
const quic::QuicCryptoClientConfig::CachedState& cached) {
DCHECK(cached.proof_valid());
if (!server_info_) {
return;
}
QuicServerInfo::State* state = server_info_->mutable_state();
state->server_config = cached.server_config();
state->source_address_token = cached.source_address_token();
state->cert_sct = cached.cert_sct();
state->chlo_hash = cached.chlo_hash();
state->server_config_sig = cached.signature();
state->certs = cached.certs();
server_info_->Persist();
}
void QuicChromiumClientSession::OnProofVerifyDetailsAvailable(
const quic::ProofVerifyDetails& verify_details) {
const ProofVerifyDetailsChromium* verify_details_chromium =
reinterpret_cast<const ProofVerifyDetailsChromium*>(&verify_details);
cert_verify_result_ = std::make_unique<CertVerifyResult>(
verify_details_chromium->cert_verify_result);
pinning_failure_log_ = verify_details_chromium->pinning_failure_log;
logger_->OnCertificateVerified(*cert_verify_result_);
pkp_bypassed_ = verify_details_chromium->pkp_bypassed;
is_fatal_cert_error_ = verify_details_chromium->is_fatal_cert_error;
}
void QuicChromiumClientSession::StartReading() {
for (auto& packet_reader : packet_readers_) {
packet_reader->StartReading();
}
}
void QuicChromiumClientSession::CloseSessionOnError(
int net_error,
quic::QuicErrorCode quic_error,
quic::ConnectionCloseBehavior behavior) {
base::UmaHistogramSparse("Net.QuicSession.CloseSessionOnError", -net_error);
if (!callback_.is_null()) {
std::move(callback_).Run(net_error);
}
NotifyAllStreamsOfError(net_error);
net_log_.AddEventWithIntParams(NetLogEventType::QUIC_SESSION_CLOSE_ON_ERROR,
"net_error", net_error);
if (connection()->connected())
connection()->CloseConnection(quic_error, "net error", behavior);
DCHECK(!connection()->connected());
CloseAllHandles(net_error);
NotifyFactoryOfSessionClosed();
}
void QuicChromiumClientSession::CloseSessionOnErrorLater(
int net_error,
quic::QuicErrorCode quic_error,
quic::ConnectionCloseBehavior behavior) {
base::UmaHistogramSparse("Net.QuicSession.CloseSessionOnError", -net_error);
if (!callback_.is_null()) {
std::move(callback_).Run(net_error);
}
NotifyAllStreamsOfError(net_error);
CloseAllHandles(net_error);
net_log_.AddEventWithIntParams(NetLogEventType::QUIC_SESSION_CLOSE_ON_ERROR,
"net_error", net_error);
if (connection()->connected())
connection()->CloseConnection(quic_error, "net error", behavior);
DCHECK(!connection()->connected());
NotifyFactoryOfSessionClosedLater();
}
void QuicChromiumClientSession::NotifyAllStreamsOfError(int net_error) {
PerformActionOnActiveStreams([net_error](quic::QuicStream* stream) {
static_cast<QuicChromiumClientStream*>(stream)->OnError(net_error);
return true;
});
}
void QuicChromiumClientSession::CloseAllHandles(int net_error) {
while (!handles_.empty()) {
Handle* handle = *handles_.begin();
handles_.erase(handle);
handle->OnSessionClosed(connection()->version(), net_error, error(),
port_migration_detected_, GetConnectTiming(),
WasConnectionEverUsed());
}
}
void QuicChromiumClientSession::CancelAllRequests(int net_error) {
UMA_HISTOGRAM_COUNTS_1000("Net.QuicSession.AbortedPendingStreamRequests",
stream_requests_.size());
while (!stream_requests_.empty()) {
StreamRequest* request = stream_requests_.front();
stream_requests_.pop_front();
request->OnRequestCompleteFailure(net_error);
}
}
void QuicChromiumClientSession::NotifyRequestsOfConfirmation(int net_error) {
// Post tasks to avoid reentrancy.
for (auto& callback : waiting_for_confirmation_callbacks_)
task_runner_->PostTask(FROM_HERE,
base::BindOnce(std::move(callback), net_error));
waiting_for_confirmation_callbacks_.clear();
}
void QuicChromiumClientSession::MaybeMigrateToDifferentPortOnPathDegrading() {
DCHECK(allow_port_migration_ && !migrate_session_early_v2_);
// Migration before handshake confirmed is not allowed.
const bool is_handshake_confirmed = version().UsesHttp3()
? connection()->IsHandshakeConfirmed()
: OneRttKeysAvailable();
if (!is_handshake_confirmed) {
HistogramAndLogMigrationFailure(
MIGRATION_STATUS_PATH_DEGRADING_BEFORE_HANDSHAKE_CONFIRMED,
connection_id(), "Path degrading before handshake confirmed");
return;
}
net_log_.BeginEvent(NetLogEventType::QUIC_PORT_MIGRATION_TRIGGERED);
if (!stream_factory_)
return;
// Probe a different port, session will migrate to the probed port on success.
StartProbing(default_network_, peer_address());
net_log_.EndEvent(NetLogEventType::QUIC_PORT_MIGRATION_TRIGGERED);
}
void QuicChromiumClientSession::
MaybeMigrateToAlternateNetworkOnPathDegrading() {
net_log_.AddEvent(
NetLogEventType::QUIC_CONNECTION_MIGRATION_ON_PATH_DEGRADING);
current_migration_cause_ = CHANGE_NETWORK_ON_PATH_DEGRADING;
if (!migrate_session_early_v2_) {
HistogramAndLogMigrationFailure(MIGRATION_STATUS_PATH_DEGRADING_NOT_ENABLED,
connection_id(),
"Migration on path degrading not enabled");
return;
}
if (GetCurrentNetwork() == default_network_ &&
current_migrations_to_non_default_network_on_path_degrading_ >=
max_migrations_to_non_default_network_on_path_degrading_) {
HistogramAndLogMigrationFailure(
MIGRATION_STATUS_ON_PATH_DEGRADING_DISABLED, connection_id(),
"Exceeds maximum number of migrations on path degrading");
return;
}
NetworkChangeNotifier::NetworkHandle alternate_network =
stream_factory_->FindAlternateNetwork(GetCurrentNetwork());
if (alternate_network == NetworkChangeNotifier::kInvalidNetworkHandle) {
HistogramAndLogMigrationFailure(MIGRATION_STATUS_NO_ALTERNATE_NETWORK,
connection_id(),
"No alternative network on path degrading");
return;
}
LogHandshakeStatusOnMigrationSignal();
const bool is_handshake_confirmed = version().UsesHttp3()
? connection()->IsHandshakeConfirmed()
: OneRttKeysAvailable();
if (!is_handshake_confirmed) {
HistogramAndLogMigrationFailure(
MIGRATION_STATUS_PATH_DEGRADING_BEFORE_HANDSHAKE_CONFIRMED,
connection_id(), "Path degrading before handshake confirmed");
return;
}
net_log_.BeginEventWithStringParams(
NetLogEventType::QUIC_CONNECTION_MIGRATION_TRIGGERED, "trigger",
"PathDegrading");
// Probe the alternative network, session will migrate to the probed
// network and decide whether it wants to migrate back to the default
// network on success.
MaybeStartProbing(alternate_network, peer_address());
net_log_.EndEvent(NetLogEventType::QUIC_CONNECTION_MIGRATION_TRIGGERED);
}
ProbingResult QuicChromiumClientSession::MaybeStartProbing(
NetworkChangeNotifier::NetworkHandle network,
const quic::QuicSocketAddress& peer_address) {
if (!stream_factory_)
return ProbingResult::FAILURE;
CHECK_NE(NetworkChangeNotifier::kInvalidNetworkHandle, network);
if (!migrate_idle_session_ && !HasActiveRequestStreams()) {
HistogramAndLogMigrationFailure(MIGRATION_STATUS_NO_MIGRATABLE_STREAMS,
connection_id(), "No active streams");
CloseSessionOnErrorLater(
ERR_NETWORK_CHANGED,
quic::QUIC_CONNECTION_MIGRATION_NO_MIGRATABLE_STREAMS,
quic::ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
return ProbingResult::DISABLED_WITH_IDLE_SESSION;
}
if (migrate_idle_session_ && CheckIdleTimeExceedsIdleMigrationPeriod())
return ProbingResult::DISABLED_WITH_IDLE_SESSION;
// Abort probing if connection migration is disabled by config.
if (version().HasIetfQuicFrames() &&
!connection()->connection_migration_use_new_cid()) {
DVLOG(1) << "Client IETF connection migration is not enabled.";
HistogramAndLogMigrationFailure(MIGRATION_STATUS_NOT_ENABLED,
connection_id(),
"IETF migration flag is false");
return ProbingResult::DISABLED_BY_CONFIG;
}
if (config()->DisableConnectionMigration()) {
DVLOG(1) << "Client disables probing network with connection migration "
<< "disabled by config";
HistogramAndLogMigrationFailure(MIGRATION_STATUS_DISABLED_BY_CONFIG,
connection_id(),
"Migration disabled by config");
return ProbingResult::DISABLED_BY_CONFIG;
}
return StartProbing(network, peer_address);
}
ProbingResult QuicChromiumClientSession::StartProbing(
NetworkChangeNotifier::NetworkHandle network,
const quic::QuicSocketAddress& peer_address) {
// Check if probing manager is probing the same path.
if (connection()->connection_migration_use_new_cid()) {
auto* context = static_cast<QuicChromiumPathValidationContext*>(
connection()->GetPathValidationContext());
if (context && context->network() == network &&
context->peer_address() == peer_address) {
return ProbingResult::PENDING;
}
} else if (probing_manager_.IsUnderProbing(network, peer_address)) {
return ProbingResult::PENDING;
}
// Create and configure socket on |network|.
std::unique_ptr<DatagramClientSocket> probing_socket =
stream_factory_->CreateSocket(net_log_.net_log(), net_log_.source());
if (stream_factory_->ConfigureSocket(probing_socket.get(),
ToIPEndPoint(peer_address), network,
session_key_.socket_tag()) != OK) {
HistogramAndLogMigrationFailure(MIGRATION_STATUS_INTERNAL_ERROR,
connection_id(),
"Socket configuration failed");
return ProbingResult::INTERNAL_ERROR;
}
// Create new packet writer and reader on the probing socket.
std::unique_ptr<QuicChromiumPacketWriter> probing_writer(
new QuicChromiumPacketWriter(probing_socket.get(), task_runner_));
std::unique_ptr<QuicChromiumPacketReader> probing_reader(
new QuicChromiumPacketReader(probing_socket.get(), clock_, this,
yield_after_packets_, yield_after_duration_,
net_log_));
int rtt_ms = connection()
->sent_packet_manager()
.GetRttStats()
->smoothed_rtt()
.ToMilliseconds();
if (rtt_ms == 0 || rtt_ms > kDefaultRTTMilliSecs)
rtt_ms = kDefaultRTTMilliSecs;
int timeout_ms = rtt_ms * 2;
if (connection()->connection_migration_use_new_cid() &&
version().HasIetfQuicFrames()) {
probing_reader->StartReading();
path_validation_writer_delegate_.set_network(network);
path_validation_writer_delegate_.set_peer_address(peer_address);
probing_writer->set_delegate(&path_validation_writer_delegate_);
IPEndPoint local_address;
probing_socket->GetLocalAddress(&local_address);
auto context = std::make_unique<QuicChromiumPathValidationContext>(
ToQuicSocketAddress(local_address), peer_address, network,
std::move(probing_socket), std::move(probing_writer),
std::move(probing_reader));
if (current_migration_cause_ != CHANGE_PORT_ON_PATH_DEGRADING) {
ValidatePath(
std::move(context),
std::make_unique<ConnectionMigrationValidationResultDelegate>(this));
return ProbingResult::PENDING;
}
ValidatePath(std::move(context),
std::make_unique<PortMigrationValidationResultDelegate>(this));
return ProbingResult::PENDING;
}
probing_manager_.StartProbing(
network, peer_address, std::move(probing_socket),
std::move(probing_writer), std::move(probing_reader),
base::Milliseconds(timeout_ms), net_log_);
return ProbingResult::PENDING;
}
void QuicChromiumClientSession::StartMigrateBackToDefaultNetworkTimer(
base::TimeDelta delay) {
if (current_migration_cause_ != ON_NETWORK_MADE_DEFAULT)
current_migration_cause_ = ON_MIGRATE_BACK_TO_DEFAULT_NETWORK;
CancelMigrateBackToDefaultNetworkTimer();
// Post a task to try migrate back to default network after |delay|.
migrate_back_to_default_timer_.Start(
FROM_HERE, delay,
base::BindOnce(
&QuicChromiumClientSession::MaybeRetryMigrateBackToDefaultNetwork,
weak_factory_.GetWeakPtr()));
}
void QuicChromiumClientSession::CancelMigrateBackToDefaultNetworkTimer() {
retry_migrate_back_count_ = 0;
migrate_back_to_default_timer_.Stop();
}
void QuicChromiumClientSession::TryMigrateBackToDefaultNetwork(
base::TimeDelta timeout) {
if (default_network_ == NetworkChangeNotifier::kInvalidNetworkHandle) {
DVLOG(1) << "Default network is not connected";
return;
}
net_log_.AddEventWithInt64Params(
NetLogEventType::QUIC_CONNECTION_MIGRATION_ON_MIGRATE_BACK, "retry_count",
retry_migrate_back_count_);
// Start probe default network immediately, if manager is probing
// the same network, this will be a no-op. Otherwise, previous probe
// will be cancelled and manager starts to probe |default_network_|
// immediately.
ProbingResult result = MaybeStartProbing(default_network_, peer_address());
if (result == ProbingResult::DISABLED_WITH_IDLE_SESSION)
return;
if (result != ProbingResult::PENDING) {
// Session is not allowed to migrate, mark session as going away, cancel
// migrate back to default timer.
NotifyFactoryOfSessionGoingAway();
CancelMigrateBackToDefaultNetworkTimer();
return;
}
retry_migrate_back_count_++;
migrate_back_to_default_timer_.Start(
FROM_HERE, timeout,
base::BindOnce(
&QuicChromiumClientSession::MaybeRetryMigrateBackToDefaultNetwork,
weak_factory_.GetWeakPtr()));
}
void QuicChromiumClientSession::MaybeRetryMigrateBackToDefaultNetwork() {
base::TimeDelta retry_migrate_back_timeout =
base::Seconds(UINT64_C(1) << retry_migrate_back_count_);
if (default_network_ == GetCurrentNetwork()) {
// If session has been back on the default already by other direct
// migration attempt, cancel migrate back now.
CancelMigrateBackToDefaultNetworkTimer();
return;
}
if (retry_migrate_back_timeout > max_time_on_non_default_network_) {
// Mark session as going away to accept no more streams.
NotifyFactoryOfSessionGoingAway();
return;
}
TryMigrateBackToDefaultNetwork(retry_migrate_back_timeout);
}
bool QuicChromiumClientSession::CheckIdleTimeExceedsIdleMigrationPeriod() {
if (!migrate_idle_session_)
return false;
if (HasActiveRequestStreams()) {
return false;
}
// There are no active/drainning streams, check the last stream's finish time.
if (tick_clock_->NowTicks() - most_recent_stream_close_time_ <
idle_migration_period_) {
// Still within the idle migration period.
return false;
}
HistogramAndLogMigrationFailure(MIGRATION_STATUS_IDLE_MIGRATION_TIMEOUT,
connection_id(),
"Ilde migration period exceeded");
CloseSessionOnErrorLater(ERR_NETWORK_CHANGED, quic::QUIC_NETWORK_IDLE_TIMEOUT,
quic::ConnectionCloseBehavior::SILENT_CLOSE);
return true;
}
void QuicChromiumClientSession::ResetNonMigratableStreams() {
// TODO(zhongyi): may close non-migratable draining streams as well to avoid
// sending additional data on alternate networks.
PerformActionOnActiveStreams([](quic::QuicStream* stream) {
QuicChromiumClientStream* chrome_stream =
static_cast<QuicChromiumClientStream*>(stream);
if (!chrome_stream->can_migrate_to_cellular_network()) {
// Close the stream in both direction by resetting the stream.
// TODO(zhongyi): use a different error code to reset streams for
// connection migration.
chrome_stream->Reset(quic::QUIC_STREAM_CANCELLED);
}
return true;
});
}
void QuicChromiumClientSession::LogMetricsOnNetworkDisconnected() {
if (most_recent_path_degrading_timestamp_ != base::TimeTicks()) {
most_recent_network_disconnected_timestamp_ = tick_clock_->NowTicks();
base::TimeDelta degrading_duration =
most_recent_network_disconnected_timestamp_ -
most_recent_path_degrading_timestamp_;
UMA_HISTOGRAM_CUSTOM_TIMES(
"Net.QuicNetworkDegradingDurationTillDisconnected", degrading_duration,
base::Milliseconds(1), base::Minutes(10), 100);
}
if (most_recent_write_error_timestamp_ != base::TimeTicks()) {
base::TimeDelta write_error_to_disconnection_gap =
most_recent_network_disconnected_timestamp_ -
most_recent_write_error_timestamp_;
UMA_HISTOGRAM_CUSTOM_TIMES(
"Net.QuicNetworkGapBetweenWriteErrorAndDisconnection",
write_error_to_disconnection_gap, base::Milliseconds(1),
base::Minutes(10), 100);
base::UmaHistogramSparse("Net.QuicSession.WriteError.NetworkDisconnected",
-most_recent_write_error_);
most_recent_write_error_ = 0;
most_recent_write_error_timestamp_ = base::TimeTicks();
}
}
void QuicChromiumClientSession::LogMetricsOnNetworkMadeDefault() {
if (most_recent_path_degrading_timestamp_ != base::TimeTicks()) {
if (most_recent_network_disconnected_timestamp_ != base::TimeTicks()) {
// NetworkDiscconected happens before NetworkMadeDefault, the platform
// is dropping WiFi.
base::TimeTicks now = tick_clock_->NowTicks();
base::TimeDelta disconnection_duration =
now - most_recent_network_disconnected_timestamp_;
base::TimeDelta degrading_duration =
now - most_recent_path_degrading_timestamp_;
UMA_HISTOGRAM_CUSTOM_TIMES("Net.QuicNetworkDisconnectionDuration",
disconnection_duration, base::Milliseconds(1),
base::Minutes(10), 100);
UMA_HISTOGRAM_CUSTOM_TIMES(
"Net.QuicNetworkDegradingDurationTillNewNetworkMadeDefault",
degrading_duration, base::Milliseconds(1), base::Minutes(10), 100);
most_recent_network_disconnected_timestamp_ = base::TimeTicks();
}
most_recent_path_degrading_timestamp_ = base::TimeTicks();
}
}
void QuicChromiumClientSession::LogMigrationResultToHistogram(
QuicConnectionMigrationStatus status) {
if (current_migration_cause_ == CHANGE_PORT_ON_PATH_DEGRADING) {
UMA_HISTOGRAM_ENUMERATION("Net.QuicSession.PortMigration", status,
MIGRATION_STATUS_MAX);
current_migration_cause_ = UNKNOWN_CAUSE;
return;
}
UMA_HISTOGRAM_ENUMERATION("Net.QuicSession.ConnectionMigration", status,
MIGRATION_STATUS_MAX);
// Log the connection migraiton result to different histograms based on the
// cause of the connection migration.
std::string histogram_name = "Net.QuicSession.ConnectionMigration." +
MigrationCauseToString(current_migration_cause_);
base::UmaHistogramEnumeration(histogram_name, status, MIGRATION_STATUS_MAX);
current_migration_cause_ = UNKNOWN_CAUSE;
}
void QuicChromiumClientSession::LogHandshakeStatusOnMigrationSignal() const {
if (current_migration_cause_ == CHANGE_PORT_ON_PATH_DEGRADING) {
UMA_HISTOGRAM_BOOLEAN("Net.QuicSession.HandshakeStatusOnPortMigration",
OneRttKeysAvailable());
return;
}
UMA_HISTOGRAM_BOOLEAN("Net.QuicSession.HandshakeStatusOnConnectionMigration",
OneRttKeysAvailable());
const std::string histogram_name =
"Net.QuicSession.HandshakeStatusOnConnectionMigration." +
MigrationCauseToString(current_migration_cause_);
STATIC_HISTOGRAM_POINTER_GROUP(
histogram_name, current_migration_cause_, MIGRATION_CAUSE_MAX,
AddBoolean(OneRttKeysAvailable()),
base::BooleanHistogram::FactoryGet(
histogram_name, base::HistogramBase::kUmaTargetedHistogramFlag));
}
void QuicChromiumClientSession::HistogramAndLogMigrationFailure(
QuicConnectionMigrationStatus status,
quic::QuicConnectionId connection_id,
const char* reason) {
NetLogEventType event_type =
current_migration_cause_ == CHANGE_PORT_ON_PATH_DEGRADING
? NetLogEventType::QUIC_PORT_MIGRATION_FAILURE
: NetLogEventType::QUIC_CONNECTION_MIGRATION_FAILURE;
net_log_.AddEvent(event_type, [&] {
return NetLogQuicMigrationFailureParams(connection_id, reason);
});
// |current_migration_cause_| will be reset afterwards.
LogMigrationResultToHistogram(status);
}
void QuicChromiumClientSession::HistogramAndLogMigrationSuccess(
quic::QuicConnectionId connection_id) {
NetLogEventType event_type =
current_migration_cause_ == CHANGE_PORT_ON_PATH_DEGRADING
? NetLogEventType::QUIC_PORT_MIGRATION_SUCCESS
: NetLogEventType::QUIC_CONNECTION_MIGRATION_SUCCESS;
net_log_.AddEvent(event_type, [&] {
return NetLogQuicMigrationSuccessParams(connection_id);
});
// |current_migration_cause_| will be reset afterwards.
LogMigrationResultToHistogram(MIGRATION_STATUS_SUCCESS);
}
base::Value QuicChromiumClientSession::GetInfoAsValue(
const std::set<HostPortPair>& aliases) {
base::DictionaryValue dict;
dict.SetString("version", ParsedQuicVersionToString(connection()->version()));
dict.SetInteger("open_streams", GetNumActiveStreams());
std::vector<base::Value> stream_list;
auto* stream_list_ptr = &stream_list;
PerformActionOnActiveStreams([stream_list_ptr](quic::QuicStream* stream) {
stream_list_ptr->emplace_back(base::NumberToString(stream->id()));
return true;
});
dict.SetKey("active_streams", base::Value(std::move(stream_list)));
dict.SetIntKey("total_streams", num_total_streams_);
dict.SetStringKey("peer_address", peer_address().ToString());
dict.SetStringKey("network_isolation_key",
session_key_.network_isolation_key().ToDebugString());
dict.SetStringKey("connection_id", connection_id().ToString());
if (!connection()->client_connection_id().IsEmpty()) {
dict.SetStringKey("client_connection_id",
connection()->client_connection_id().ToString());
}
dict.SetBoolKey("connected", connection()->connected());
const quic::QuicConnectionStats& stats = connection()->GetStats();
dict.SetIntKey("packets_sent", stats.packets_sent);
dict.SetIntKey("packets_received", stats.packets_received);
dict.SetIntKey("packets_lost", stats.packets_lost);
SSLInfo ssl_info;
std::vector<base::Value> alias_list;
for (const auto& alias : aliases) {
alias_list.emplace_back(alias.ToString());
}
dict.SetKey("aliases", base::Value(std::move(alias_list)));
return std::move(dict);
}
bool QuicChromiumClientSession::gquic_zero_rtt_disabled() const {
if (!stream_factory_)
return false;
return stream_factory_->gquic_zero_rtt_disabled();
}
std::unique_ptr<QuicChromiumClientSession::Handle>
QuicChromiumClientSession::CreateHandle(url::SchemeHostPort destination) {
return std::make_unique<QuicChromiumClientSession::Handle>(
weak_factory_.GetWeakPtr(), std::move(destination));
}
bool QuicChromiumClientSession::OnReadError(
int result,
const DatagramClientSocket* socket) {
DCHECK(socket != nullptr);
base::UmaHistogramSparse("Net.QuicSession.ReadError.AnyNetwork", -result);
if (socket != GetDefaultSocket()) {
DVLOG(1) << "Ignoring read error " << ErrorToString(result)
<< " on old socket";
base::UmaHistogramSparse("Net.QuicSession.ReadError.OtherNetworks",
-result);
// Ignore read errors from sockets that are not affecting the current
// network, i.e., sockets that are no longer active and probing socket.
// TODO(jri): Maybe clean up old sockets on error.
return false;
}
if (ignore_read_error_) {
DVLOG(1) << "Ignoring read error " << ErrorToString(result)
<< " during pending migration";
// Ignore read errors during pending migration. Connection will be closed if
// pending migration failed or timed out.
base::UmaHistogramSparse("Net.QuicSession.ReadError.PendingMigration",
-result);
return false;
}
base::UmaHistogramSparse("Net.QuicSession.ReadError.CurrentNetwork", -result);
if (OneRttKeysAvailable()) {
base::UmaHistogramSparse(
"Net.QuicSession.ReadError.CurrentNetwork.HandshakeConfirmed", -result);
}
DVLOG(1) << "Closing session on read error " << ErrorToString(result);
connection()->CloseConnection(quic::QUIC_PACKET_READ_ERROR,
ErrorToString(result),
quic::ConnectionCloseBehavior::SILENT_CLOSE);
return false;
}
bool QuicChromiumClientSession::OnPacket(
const quic::QuicReceivedPacket& packet,
const quic::QuicSocketAddress& local_address,
const quic::QuicSocketAddress& peer_address) {
ProcessUdpPacket(local_address, peer_address, packet);
if (!connection()->connected()) {
NotifyFactoryOfSessionClosedLater();
return false;
}
return true;
}
void QuicChromiumClientSession::NotifyFactoryOfSessionGoingAway() {
going_away_ = true;
if (stream_factory_)
stream_factory_->OnSessionGoingAway(this);
}
void QuicChromiumClientSession::NotifyFactoryOfSessionClosedLater() {
going_away_ = true;
DCHECK_EQ(0u, GetNumActiveStreams());
DCHECK(!connection()->connected());
task_runner_->PostTask(
FROM_HERE,
base::BindOnce(&QuicChromiumClientSession::NotifyFactoryOfSessionClosed,
weak_factory_.GetWeakPtr()));
}
void QuicChromiumClientSession::NotifyFactoryOfSessionClosed() {
going_away_ = true;
DCHECK_EQ(0u, GetNumActiveStreams());
// Will delete |this|.
if (stream_factory_)
stream_factory_->OnSessionClosed(this);
}
void QuicChromiumClientSession::OnCryptoHandshakeComplete() {
if (stream_factory_)
stream_factory_->set_is_quic_known_to_work_on_current_network(true);
// Update |connect_end| only when handshake is confirmed. This should also
// take care of any failed 0-RTT request.
connect_timing_.connect_end = tick_clock_->NowTicks();
DCHECK_LE(connect_timing_.connect_start, connect_timing_.connect_end);
UMA_HISTOGRAM_TIMES(
"Net.QuicSession.HandshakeConfirmedTime",
connect_timing_.connect_end - connect_timing_.connect_start);
// Track how long it has taken to finish handshake after we have finished
// DNS host resolution.
if (!connect_timing_.dns_end.is_null()) {
UMA_HISTOGRAM_TIMES("Net.QuicSession.HostResolution.HandshakeConfirmedTime",
tick_clock_->NowTicks() - connect_timing_.dns_end);
}
auto it = handles_.begin();
while (it != handles_.end()) {
Handle* handle = *it;
++it;
handle->OnCryptoHandshakeConfirmed();
}
NotifyRequestsOfConfirmation(OK);
// Attempt to migrate back to the default network after handshake has been
// confirmed if the session is not created on the default network.
if (migrate_session_on_network_change_v2_ &&
default_network_ != NetworkChangeNotifier::kInvalidNetworkHandle &&
GetCurrentNetwork() != default_network_) {
current_migration_cause_ = ON_MIGRATE_BACK_TO_DEFAULT_NETWORK;
StartMigrateBackToDefaultNetworkTimer(
base::Seconds(kMinRetryTimeForDefaultNetworkSecs));
}
}
MigrationResult QuicChromiumClientSession::Migrate(
NetworkChangeNotifier::NetworkHandle network,
IPEndPoint peer_address,
bool close_session_on_error) {
if (!stream_factory_)
return MigrationResult::FAILURE;
if (network != NetworkChangeNotifier::kInvalidNetworkHandle) {
// This is a migration attempt from connection migration.
ResetNonMigratableStreams();
if (!migrate_idle_session_ && !HasActiveRequestStreams()) {
// If idle sessions can not be migrated, close the session if needed.
if (close_session_on_error) {
CloseSessionOnErrorLater(
ERR_NETWORK_CHANGED,
quic::QUIC_CONNECTION_MIGRATION_NO_MIGRATABLE_STREAMS,
quic::ConnectionCloseBehavior::SILENT_CLOSE);
}
return MigrationResult::FAILURE;
}
}
// Create and configure socket on |network|.
std::unique_ptr<DatagramClientSocket> socket(
stream_factory_->CreateSocket(net_log_.net_log(), net_log_.source()));
if (stream_factory_->ConfigureSocket(socket.get(), peer_address, network,
session_key_.socket_tag()) != OK) {
HistogramAndLogMigrationFailure(MIGRATION_STATUS_INTERNAL_ERROR,
connection_id(),
"Socket configuration failed");
if (close_session_on_error) {
if (migrate_session_on_network_change_v2_) {
CloseSessionOnErrorLater(ERR_NETWORK_CHANGED,
quic::QUIC_CONNECTION_MIGRATION_INTERNAL_ERROR,
quic::ConnectionCloseBehavior::SILENT_CLOSE);
} else {
CloseSessionOnError(ERR_NETWORK_CHANGED,
quic::QUIC_CONNECTION_MIGRATION_INTERNAL_ERROR,
quic::ConnectionCloseBehavior::SILENT_CLOSE);
}
}
return MigrationResult::FAILURE;
}
// Create new packet reader and writer on the new socket.
std::unique_ptr<QuicChromiumPacketReader> new_reader(
new QuicChromiumPacketReader(socket.get(), clock_, this,
yield_after_packets_, yield_after_duration_,
net_log_));
new_reader->StartReading();
std::unique_ptr<QuicChromiumPacketWriter> new_writer(
new QuicChromiumPacketWriter(socket.get(), task_runner_));
static_cast<QuicChromiumPacketWriter*>(connection()->writer())
->set_delegate(nullptr);
new_writer->set_delegate(this);
IPEndPoint self_address;
socket->GetLocalAddress(&self_address);
// Migrate to the new socket.
if (!MigrateToSocket(ToQuicSocketAddress(self_address),
ToQuicSocketAddress(peer_address), std::move(socket),
std::move(new_reader), std::move(new_writer))) {
if (close_session_on_error) {
if (migrate_session_on_network_change_v2_) {
CloseSessionOnErrorLater(
ERR_NETWORK_CHANGED,
quic::QUIC_CONNECTION_MIGRATION_TOO_MANY_CHANGES,
quic::ConnectionCloseBehavior::SILENT_CLOSE);
} else {
CloseSessionOnError(ERR_NETWORK_CHANGED,
quic::QUIC_CONNECTION_MIGRATION_TOO_MANY_CHANGES,
quic::ConnectionCloseBehavior::SILENT_CLOSE);
}
}
return MigrationResult::FAILURE;
}
HistogramAndLogMigrationSuccess(connection_id());
return MigrationResult::SUCCESS;
}
bool QuicChromiumClientSession::MigrateToSocket(
const quic::QuicSocketAddress& self_address,
const quic::QuicSocketAddress& peer_address,
std::unique_ptr<DatagramClientSocket> socket,
std::unique_ptr<QuicChromiumPacketReader> reader,
std::unique_ptr<QuicChromiumPacketWriter> writer) {
CHECK_EQ(sockets_.size(), packet_readers_.size());
// TODO(zhongyi): figure out whether we want to limit the number of
// connection migrations for v2, which includes migration on platform signals,
// write error events, and path degrading on original network.
if (!migrate_session_on_network_change_v2_ &&
sockets_.size() >= kMaxReadersPerQuicSession) {
HistogramAndLogMigrationFailure(MIGRATION_STATUS_TOO_MANY_CHANGES,
connection_id(), "Too many changes");
return false;
}
packet_readers_.push_back(std::move(reader));
sockets_.push_back(std::move(socket));
// Froce the writer to be blocked to prevent it being used until
// WriteToNewSocket completes.
DVLOG(1) << "Force blocking the packet writer";
writer->set_force_write_blocked(true);
if (!MigratePath(self_address, peer_address, writer.release(),
/*owns_writer=*/true)) {
HistogramAndLogMigrationFailure(MIGRATION_STATUS_NO_UNUSED_CONNECTION_ID,
connection_id(),
"No unused server connection ID");
DVLOG(1) << "MigratePath fails as there is no CID available";
return false;
}
// Post task to write the pending packet or a PING packet to the new
// socket. This avoids reentrancy issues if there is a write error
// on the write to the new socket.
task_runner_->PostTask(
FROM_HERE, base::BindOnce(&QuicChromiumClientSession::WriteToNewSocket,
weak_factory_.GetWeakPtr()));
return true;
}
void QuicChromiumClientSession::PopulateNetErrorDetails(
NetErrorDetails* details) const {
details->quic_port_migration_detected = port_migration_detected_;
details->quic_connection_error = error();
}
const DatagramClientSocket* QuicChromiumClientSession::GetDefaultSocket()
const {
DCHECK(sockets_.back().get() != nullptr);
// The most recently added socket is the currently active one.
return sockets_.back().get();
}
NetworkChangeNotifier::NetworkHandle
QuicChromiumClientSession::GetCurrentNetwork() const {
// If connection migration is enabled, alternate network interface may be
// used to send packet, it is identified as the bound network of the default
// socket. Otherwise, always use |default_network_|.
return migrate_session_on_network_change_v2_
? GetDefaultSocket()->GetBoundNetwork()
: default_network_;
}
bool QuicChromiumClientSession::IsAuthorized(const std::string& hostname) {
bool result = CanPool(hostname, session_key_);
if (result)
streams_pushed_count_++;
return result;
}
bool QuicChromiumClientSession::HandlePromised(
quic::QuicStreamId id,
quic::QuicStreamId promised_id,
const spdy::Http2HeaderBlock& headers) {
bool result =
quic::QuicSpdyClientSessionBase::HandlePromised(id, promised_id, headers);
if (result) {
// The push promise is accepted, notify the push_delegate that a push
// promise has been received.
if (push_delegate_) {
std::string pushed_url =
quic::SpdyServerPushUtils::GetPromisedUrlFromHeaders(headers);
push_delegate_->OnPush(std::make_unique<QuicServerPushHelper>(
weak_factory_.GetWeakPtr(), GURL(pushed_url)),
net_log_);
}
if (headers_include_h2_stream_dependency_ ||
VersionUsesHttp3(connection()->transport_version())) {
// Even though the promised stream will not be created until after the
// push promise headers are received, send a PRIORITY frame for the
// promised stream ID. Send |kDefaultPriority| since that will be the
// initial spdy::SpdyPriority of the push promise stream when created.
const spdy::SpdyPriority priority = quic::QuicStream::kDefaultPriority;
spdy::SpdyStreamId parent_stream_id = 0;
int weight = 0;
bool exclusive = false;
priority_dependency_state_.OnStreamCreation(
promised_id, priority, &parent_stream_id, &weight, &exclusive);
if (!VersionUsesHttp3(connection()->transport_version())) {
WritePriority(promised_id, parent_stream_id, weight, exclusive);
}
}
}
net_log_.AddEvent(NetLogEventType::QUIC_SESSION_PUSH_PROMISE_RECEIVED,
[&](NetLogCaptureMode capture_mode) {
return NetLogQuicPushPromiseReceivedParams(
&headers, id, promised_id, capture_mode);
});
return result;
}
void QuicChromiumClientSession::DeletePromised(
quic::QuicClientPromisedInfo* promised) {
if (IsOpenStream(promised->id()))
streams_pushed_and_claimed_count_++;
quic::QuicSpdyClientSessionBase::DeletePromised(promised);
}
void QuicChromiumClientSession::OnPushStreamTimedOut(
quic::QuicStreamId stream_id) {
quic::QuicSpdyStream* stream = GetPromisedStream(stream_id);
if (stream != nullptr)
bytes_pushed_and_unclaimed_count_ += stream->stream_bytes_read();
}
void QuicChromiumClientSession::CancelPush(const GURL& url) {
quic::QuicClientPromisedInfo* promised_info =
quic::QuicSpdyClientSessionBase::GetPromisedByUrl(url.spec());
if (!promised_info || promised_info->is_validating()) {
// Push stream has already been claimed or is pending matched to a request.
return;
}
quic::QuicStreamId stream_id = promised_info->id();
// Collect data on the cancelled push stream.
quic::QuicSpdyStream* stream = GetPromisedStream(stream_id);
if (stream != nullptr)
bytes_pushed_and_unclaimed_count_ += stream->stream_bytes_read();
// Send the reset and remove the promised info from the promise index.
quic::QuicSpdyClientSessionBase::ResetPromised(stream_id,
quic::QUIC_STREAM_CANCELLED);
DeletePromised(promised_info);
}
const LoadTimingInfo::ConnectTiming&
QuicChromiumClientSession::GetConnectTiming() {
connect_timing_.ssl_start = connect_timing_.connect_start;
connect_timing_.ssl_end = connect_timing_.connect_end;
return connect_timing_;
}
quic::ParsedQuicVersion QuicChromiumClientSession::GetQuicVersion() const {
return connection()->version();
}
quic::QuicClientPromisedInfo* QuicChromiumClientSession::GetPromised(
const GURL& url,
const QuicSessionKey& session_key) {
if (!session_key_.CanUseForAliasing(session_key)) {
return nullptr;
}
return push_promise_index_->GetPromised(url.spec());
}
const std::vector<std::string>&
QuicChromiumClientSession::GetDnsAliasesForSessionKey(
const QuicSessionKey& key) const {
static const base::NoDestructor<std::vector<std::string>> emptyvector_result;
return stream_factory_ ? stream_factory_->GetDnsAliasesForSessionKey(key)
: *emptyvector_result;
}
bool QuicChromiumClientSession::ValidateStatelessReset(
const quic::QuicSocketAddress& self_address,
const quic::QuicSocketAddress& peer_address) {
if (probing_manager_.ValidateStatelessReset(self_address, peer_address)) {
// The stateless reset is received from probing path. We shouldn't close the
// connection, but should disable further port migration attempt.
if (allow_port_migration_)
allow_port_migration_ = false;
return false;
}
return true;
}
} // namespace net
| nwjs/chromium.src | net/quic/quic_chromium_client_session.cc | C++ | bsd-3-clause | 145,558 |
// FFXIVAPP.Plugin.Translator
// AboutView.xaml.cs
//
// Copyright © 2007 - 2015 Ryan Wilson - All Rights Reserved
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of SyndicatedLife nor the names of its contributors may
// be used to endorse or promote products derived from this software
// without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
namespace FFXIVAPP.Plugin.Translator.Views
{
/// <summary>
/// Interaction logic for AboutView.xaml
/// </summary>
public partial class AboutView
{
public static AboutView View;
public AboutView()
{
InitializeComponent();
View = this;
}
}
}
| Yaguar666/ffxivapp-plugin-translator | FFXIVAPP.Plugin.Translator/Views/AboutView.xaml.cs | C# | bsd-3-clause | 1,975 |
/******************************************************/
/* Funciones para manejo de datos del home */
/******************************************************/
var endpoint = 'http://localhost/RelemancoShopsWeb/api/web/v1/';
var rootURL = "/RelemancoShopsWeb/frontend/web";
var comercioMarkers = [];
var markersColors = ["blue", "brown", "green", "orange", "paleblue", "yellow", "pink",
"purple", "red", "darkgreen"];
var markersName = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "M", "N",
"O", "P", "Q", "R", "S", "T", "X"];
var map = null;
$( document ).ready(function() {
// localizarComercios();
initComerciosMap();
getRutasHistorico();
});
function getRutasHistorico() {
var user = $('#perfil-usuario').data('user');
if(user) {
$.ajax({
method: "GET",
url: endpoint + 'rutas/obtenerhistoricorutas',
data: {'id_relevador': user-1},
dataType: "json",
contentType: 'application/json'
}).done(function(data){
var rutas = jQuery.parseJSON(data);
dibujarTablaRutas(rutas, 'tabla-body');
}).fail(function(response){
alert(response.status);
});
}
}
function cambiarRutas() {
var id = this.id;
var ruta = $('#'+id).data('ruta');
clearComercios(comercioMarkers);
comercioMarkers.length = 0;
if(ruta && ruta.comercios && ruta.comercios.length > 0) {
var comercios = ruta.comercios;
geoService.clearRoutes(map);
for (var i = 0; i < comercios.length; i++) {
addComercio(comercios[i], 200, map);
}
geoService.createRoutes(comercios, map);
}
}
function dibujarTablaRutas(rutas, idTableBody) {
if(rutas.length > 0 ){
var tabla = $('#'+idTableBody);
rutas.forEach(function (val) {
tabla.append('<tr id="' + val.id + '"><td>' + val.fecha_asignada + '</td><td>' + val.estado.nombre + '</td></tr>');
var tr = $('#' + val.id);
tr.on('click', cambiarRutas);
tr.attr('id', val.id);
tr.data('ruta', val);
});
}
}
/**
* Returns a random integer between min (inclusive) and max (inclusive)
* Using Math.round() will give you a non-uniform distribution!
*/
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
function initComerciosMap() {
var myLatlng = {lat: -34.8059635, lng: -56.2145634};
map = new google.maps.Map(document.getElementById('mapa-comercios'), {
zoom: 15,
center: myLatlng
});
}
function dropComercios(comercios, map) {
clearComercios(comercioMarkers);
for (var i = 0; i < comercios.length; i++) {
addComercio(comercios[i], 2000, map);
}
}
function clearComercios(comercios) {
for (var i = 0; i < comercios.length; i++) {
comercios[i].setMap(null);
}
}
function markerAnimation(marker){
if (marker.getAnimation() !== null) {
marker.setAnimation(null);
} else {
marker.setAnimation(google.maps.Animation.BOUNCE);
}
}
/* Funcion para genera la lista de comercios en la ventana de informacion del
Comercio */
function generarInfoListaProductoComercio(productos){
if(productos != null){
var lista = "<ul>";
for (var i = 0; i < productos.length; i++){
lista += "<li>" + productos[i].nombre + "</li>";
}
lista += "</ul>";
return lista;
}
return "<li>Este comercio no tiene productos asignados.</li>";
}
function generarEnlaceComecio(comercio){
return " <a href='" + rootURL + '/comercio/view?id=' + comercio.id +
"'><i class='fa fa-eye'> </i>Ver Comercio</a>";
}
function generarInfoComercio(comercio){
if(comercio != null){
var info = "<h4>" + comercio.nombre + "</h4>";
info += "<hr/>";
info += generarInfoListaProductoComercio(comercio.productos);
info += "<hr/>";
info += generarEnlaceComecio(comercio);
return info;
}
return null;
}
function addComercio(comercio, timeout, map) {
var loc = comercio.localizacion;
var position = { lat : Number(loc.latitud), lng: Number(loc.longitud) };
var comercioMark = null;
comercioMark = new google.maps.Marker({
position: position,
map: map,
animation: google.maps.Animation.DROP,
title: comercio.nombre,
icon: rootURL + "/img/GMapsMarkers/" +
markersColors[getRandomInt(0,9)] + "_Marker" +
markersName[getRandomInt(0,19)] + ".png"
});
var infowindow = new google.maps.InfoWindow({
content: generarInfoComercio(comercio)
});
comercioMark.addListener('click', function() {
infowindow.addListener('closeclick', function(){
comercioMark.setAnimation(null);
});
markerAnimation(this);
infowindow.open(map, this);
});
comercioMarkers.push(comercioMark);
}
var geoService = {
createRoutes: function(markers, map) {
var directionsService = new google.maps.DirectionsService();
map._directions = [];
function renderDirections(result) {
var directionsRenderer = new google.maps.DirectionsRenderer({
suppressMarkers: true
});
directionsRenderer.setMap(map);
directionsRenderer.setDirections(result);
map._directions.push(directionsRenderer);
}
function requestDirections(start, end) {
directionsService.route({
origin: start,
destination: end,
travelMode: google.maps.DirectionsTravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.METRIC
}, function (result, status) {
renderDirections(result);
});
}
for (var i = 0; i < markers.length; i++) {
if (i < markers.length - 1) {
var origen = {lat: Number(markers[i].localizacion.latitud), lng: Number(markers[i].localizacion.longitud)};
var destino = {lat: Number(markers[i + 1].localizacion.latitud), lng: Number(markers[i + 1].localizacion.longitud)};
requestDirections(origen, destino);
}
}
},
clearRoutes: function (Gmap) {
if (Gmap._directions && Gmap._directions.length > 0) {
var directions = Gmap._directions;
directions.forEach(function (val) {
val.setMap(null);
});
}
}
}; | DRIMTIM/RelemancoShopsWeb | frontend/web/js/relemanco/site.js | JavaScript | bsd-3-clause | 6,678 |
package edu.utexas.cycic;
import javafx.scene.paint.Color;
import javafx.scene.shape.Line;
import javafx.scene.text.Font;
import javafx.scene.text.Text;
public class ConnectorLine extends Line {
{
setStroke(Color.BLACK);
}
Line right = new Line(){
{
setStrokeWidth(2);
setStroke(Color.BLACK);
}
};
Line left = new Line(){
{
setStrokeWidth(2);
setStroke(Color.BLACK);
}
};
Line right1 = new Line(){
{
setStrokeWidth(2);
setStroke(Color.BLACK);
}
};
Line left1 = new Line(){
{
setStrokeWidth(2);
setStroke(Color.BLACK);
}
};
Text text = new Text(){
{
setFill(Color.BLACK);
setFont(new Font(20));
}
};
public void updatePosition(){
double x1 = getEndX();
double y1 = getEndY();
double x2 = getStartX();
double y2 = getStartY();
right1.setStartX(x1 + (x2-x1)*0.33);
right1.setStartY(y1 + (y2-y1)*0.33);
right1.setEndX((x1 + (x2-x1)*0.38)+5.0*(y2-y1)/Math.sqrt(Math.pow((y2-y1), 2)+Math.pow(x2-x1, 2)));
right1.setEndY((y1 + (y2-y1)*0.38)-5.0*(x2-x1)/Math.sqrt(Math.pow((y2-y1), 2)+Math.pow(x2-x1, 2)));
left1.setStartX(x1 + (x2-x1)*0.33);
left1.setStartY(y1 + (y2-y1)*0.33);
left1.setEndX((x1 + (x2-x1)*0.38)-5.0*(y2-y1)/Math.sqrt(Math.pow((y2-y1), 2)+Math.pow(x2-x1, 2)));
left1.setEndY((y1 + (y2-y1)*0.38)+5.0*(x2-x1)/Math.sqrt(Math.pow((y2-y1), 2)+Math.pow(x2-x1, 2)));
right.setStartX(x1 + (x2-x1)*0.66);
right.setStartY(y1 + (y2-y1)*0.66);
right.setEndX((x1 + (x2-x1)*0.71)+5.0*(y2-y1)/Math.sqrt(Math.pow((y2-y1), 2)+Math.pow(x2-x1, 2)));
right.setEndY((y1 + (y2-y1)*0.71)-5.0*(x2-x1)/Math.sqrt(Math.pow((y2-y1), 2)+Math.pow(x2-x1, 2)));
left.setStartX(x1 + (x2-x1)*0.66);
left.setStartY(y1 + (y2-y1)*0.66);
left.setEndX((x1 + (x2-x1)*0.71)-5.0*(y2-y1)/Math.sqrt(Math.pow((y2-y1), 2)+Math.pow(x2-x1, 2)));
left.setEndY((y1 + (y2-y1)*0.71)+5.0*(x2-x1)/Math.sqrt(Math.pow((y2-y1), 2)+Math.pow(x2-x1, 2)));
text.setX(x1 + (x2-x1)*0.55+10.0*(y2-y1)/Math.sqrt(Math.pow((y2-y1), 2)+Math.pow(x2-x1, 2)));
text.setY(y1 + (y2-y1)*0.55+10.0*(x2-x1)/Math.sqrt(Math.pow((y2-y1), 2)+Math.pow(x2-x1, 2)));
}
public void updateColor(Color color){
this.setStroke(color);
right1.setStroke(color);
right.setStroke(color);
left1.setStroke(color);
left.setStroke(color);
text.setFill(color);
}
public void hideText(){
Cycic.pane.getChildren().remove(text);
}
public void showText(){
Cycic.pane.getChildren().add(text);
}
}
| cyclus/cyclist2 | cyclist/src/edu/utexas/cycic/ConnectorLine.java | Java | bsd-3-clause | 2,469 |
(function($){
$(function(){
$('#zen-gallery a').lightBox({
fixedNavigation:true,
imageLoading: 'zen-gallery/images/lightbox-btn-loading.gif',
imageBtnClose: 'zen-gallery/images/lightbox-btn-close.gif',
imageBtnPrev: 'zen-gallery/images/lightbox-btn-prev.gif',
imageBtnNext: 'zen-gallery/images/lightbox-btn-next.gif'
});
});
})(jQuery); | silverstripe-australia/council-demo | zen-gallery/javascript/zengallery.js | JavaScript | bsd-3-clause | 366 |
<?php
/**
* Firal
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://firal.org/licenses/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to firal-dev@googlegroups.com so we can send you a copy immediately.
*
* @category Firal
* @package Firal_Di
* @copyright Copyright (c) 2009-2010 Firal (http://firal.org/)
* @license http://firal.org/licenses/new-bsd New BSD License
*/
/**
* An event
*
* @category Firal
* @package Firal_Di
* @copyright Copyright (c) 2009-2010 Firal (http://firal.org/)
* @license http://firal.org/licenses/new-bsd New BSD License
*/
class Default_DiContainer extends Firal_Di_Container_ContainerAbstract
{
/**
* Get the user service
*
* @return Default_Service_User
*/
public function getUserService()
{
if (!isset($this->_storage['userService'])) {
$this->_storage['userService'] = new Default_Service_User($this->getUserMapper());
}
return $this->_storage['userService'];
}
/**
* Get the user mapper
*
* @return Default_Model_Mapper_UserInterface
*/
public function getUserMapper()
{
if (!isset($this->_storage['userMapper'])) {
$this->_storage['userMapper'] = new Default_Model_Mapper_UserCache(
new Default_Model_Mapper_User(),
$this->_config['mapper']['cache']
);
}
return $this->_storage['userMapper'];
}
/**
* Get the config service
*
* @return Default_Service_Config
*/
public function getConfigService()
{
if (!isset($this->_storage['configService'])) {
$this->_storage['configService'] = new Default_Service_Config($this->getConfigMapper());
}
return $this->_storage['configService'];
}
/**
* Get the config mapper
*
* @return Default_Model_Mapper_ConfigInterface
*/
public function getConfigMapper()
{
if (!isset($this->_storage['configMapper'])) {
$this->_storage['configMapper'] = new Default_Model_Mapper_ConfigCache(
new Default_Model_Mapper_Config(),
$this->_config['mapper']['cache']
);
}
return $this->_storage['configMapper'];
}
}
| firal/Firal | application/modules/default/DiContainer.php | PHP | bsd-3-clause | 2,542 |
// Generated by CoffeeScript 1.3.3
(function() {
var CMinion, Minion, port, restify, server;
restify = require("restify");
CMinion = require("../../minion");
Minion = new CMinion();
server = restify.createServer();
server.use(restify.queryParser());
server.get("/", function(req, res) {
res.send("Hello World.");
return Minion.logRequest(req.query);
});
port = process.env.PORT || 3000;
Minion.started();
server.listen(port, function() {
return console.log("Listening on port " + port);
});
}).call(this);
| thegoleffect/hapi-benchmarking | lib/servers/restify/helloworld.js | JavaScript | bsd-3-clause | 552 |
/*
* Copyright (C) 2012-2018 Doubango Telecom <http://www.doubango.org>
* License: BSD
* This file is part of Open Source sipML5 solution <http://www.sipml5.org>
*/
// http://tools.ietf.org/html/draft-uberti-rtcweb-jsep-02
// JSEP00: webkitPeerConnection00 (http://www.w3.org/TR/2012/WD-webrtc-20120209/)
// JSEP01: webkitRTCPeerConnection (http://www.w3.org/TR/webrtc/), https://webrtc-demos.appspot.com/html/pc1.html
// Mozilla: http://mozilla.github.com/webrtc-landing/pc_test.html
// Contraints: https://webrtc-demos.appspot.com/html/constraints-and-stats.html
// Android: https://groups.google.com/group/discuss-webrtc/browse_thread/thread/b8538c85df801b40
// Canary 'muted': https://groups.google.com/group/discuss-webrtc/browse_thread/thread/8200f2049c4de29f
// Canary state events: https://groups.google.com/group/discuss-webrtc/browse_thread/thread/bd30afc3e2f43f6d
// DTMF: https://groups.google.com/group/discuss-webrtc/browse_thread/thread/1354781f202adbf9
// IceRestart: https://groups.google.com/group/discuss-webrtc/browse_thread/thread/c189584d380eaa97
// Video Resolution: https://code.google.com/p/chromium/issues/detail?id=143631#c9
// Webrtc-Everywhere: https://github.com/sarandogou/webrtc-everywhere
// Adapter.js: https://github.com/sarandogou/webrtc
tmedia_session_jsep.prototype = Object.create(tmedia_session.prototype);
tmedia_session_jsep01.prototype = Object.create(tmedia_session_jsep.prototype);
tmedia_session_jsep.prototype.o_pc = null;
tmedia_session_jsep.prototype.b_cache_stream = false;
tmedia_session_jsep.prototype.o_local_stream = null;
tmedia_session_jsep.prototype.o_sdp_jsep_lo = null;
tmedia_session_jsep.prototype.o_sdp_lo = null;
tmedia_session_jsep.prototype.b_sdp_lo_pending = false;
tmedia_session_jsep.prototype.o_sdp_json_ro = null;
tmedia_session_jsep.prototype.o_sdp_ro = null;
tmedia_session_jsep.prototype.b_sdp_ro_pending = false;
tmedia_session_jsep.prototype.b_sdp_ro_offer = false;
tmedia_session_jsep.prototype.s_answererSessionId = null;
tmedia_session_jsep.prototype.s_offererSessionId = null;
tmedia_session_jsep.prototype.ao_ice_servers = null;
tmedia_session_jsep.prototype.o_bandwidth = { audio: undefined, video: undefined };
tmedia_session_jsep.prototype.o_video_size = { minWidth: undefined, minHeight: undefined, maxWidth: undefined, maxHeight: undefined };
tmedia_session_jsep.prototype.d_screencast_windowid = 0; // BFCP. #0 means entire desktop
tmedia_session_jsep.prototype.b_ro_changed = false;
tmedia_session_jsep.prototype.b_lo_held = false;
tmedia_session_jsep.prototype.b_ro_held = false;
//
// JSEP
//
tmedia_session_jsep.prototype.CreateInstance = function (o_mgr) {
return new tmedia_session_jsep01(o_mgr);
}
function tmedia_session_jsep(o_mgr) {
tmedia_session.call(this, o_mgr.e_type, o_mgr);
}
tmedia_session_jsep.prototype.__set = function (o_param) {
if (!o_param) {
return -1;
}
switch (o_param.s_key) {
case 'ice-servers':
{
this.ao_ice_servers = o_param.o_value;
return 0;
}
case 'cache-stream':
{
this.b_cache_stream = !!o_param.o_value;
return 0;
}
case 'bandwidth':
{
this.o_bandwidth = o_param.o_value;
return 0;
}
case 'video-size':
{
this.o_video_size = o_param.o_value;
return 0;
}
case 'screencast-windowid':
{
this.d_screencast_windowid = parseFloat(o_param.o_value.toString());
if (this.o_pc && this.o_pc.setScreencastSrcWindowId) {
this.o_pc.setScreencastSrcWindowId(this.d_screencast_windowid);
}
return 0;
}
case 'mute-audio':
case 'mute-video':
{
if (this.o_pc && typeof o_param.o_value == "boolean") {
if (this.o_pc.mute) {
this.o_pc.mute((o_param.s_key === 'mute-audio') ? "audio" : "video", o_param.o_value);
}
else if (this.o_local_stream) {
var tracks = (o_param.s_key === 'mute-audio') ? this.o_local_stream.getAudioTracks() : this.o_local_stream.getVideoTracks();
if (tracks) {
for (var i = 0; i < tracks.length; ++i) {
tracks[i].enabled = !o_param.o_value;
}
}
}
}
}
}
return -2;
}
tmedia_session_jsep.prototype.__prepare = function () {
return 0;
}
tmedia_session_jsep.prototype.__set_media_type = function (e_type) {
if (e_type != this.e_type) {
this.e_type = e_type;
this.o_sdp_lo = null;
}
return 0;
}
tmedia_session_jsep.prototype.__processContent = function (s_req_name, s_content_type, s_content_ptr, i_content_size) {
if (this.o_pc && this.o_pc.processContent) {
this.o_pc.processContent(s_req_name, s_content_type, s_content_ptr, i_content_size);
return 0;
}
return -1;
}
tmedia_session_jsep.prototype.__send_dtmf = function (s_digit) {
if (this.o_pc && this.o_pc.sendDTMF) {
this.o_pc.sendDTMF(s_digit);
return 0;
}
return -1;
}
tmedia_session_jsep.prototype.__start = function () {
if (this.o_local_stream && this.o_local_stream.start) {
// cached stream would be stopped in close()
this.o_local_stream.start();
}
return 0;
}
tmedia_session_jsep.prototype.__pause = function () {
if (this.o_local_stream && this.o_local_stream.pause) {
this.o_local_stream.pause();
}
return 0;
}
tmedia_session_jsep.prototype.__stop = function () {
this.close();
this.o_sdp_lo = null;
tsk_utils_log_info("PeerConnection::stop()");
return 0;
}
tmedia_session_jsep.prototype.decorate_lo = function () {
if (this.o_sdp_lo) {
/* Session name for debugging - Requires by webrtc2sip to set RTCWeb type */
var o_hdr_S;
if ((o_hdr_S = this.o_sdp_lo.get_header(tsdp_header_type_e.S))) {
o_hdr_S.s_value = "Doubango Telecom - " + tsk_utils_get_navigator_friendly_name();
}
/* HACK: https://bugzilla.mozilla.org/show_bug.cgi?id=1072384 */
var o_hdr_O;
if ((o_hdr_O = this.o_sdp_lo.get_header(tsdp_header_type_e.O))) {
if (o_hdr_O.s_addr === "0.0.0.0") {
o_hdr_O.s_addr = "127.0.0.1";
}
}
/* Remove 'video' media if not enabled (bug in chrome: doesn't honor 'has_video' parameter) */
if (!(this.e_type.i_id & tmedia_type_e.VIDEO.i_id)) {
this.o_sdp_lo.remove_media("video");
}
/* hold / resume, profile, bandwidth... */
var i_index = 0;
var o_hdr_M;
var b_fingerprint = !!this.o_sdp_lo.get_header_a("fingerprint"); // session-level fingerprint
while ((o_hdr_M = this.o_sdp_lo.get_header_at(tsdp_header_type_e.M, i_index++))) {
// hold/resume
o_hdr_M.set_holdresume_att(this.b_lo_held, this.b_ro_held);
// HACK: Nightly 20.0a1 uses RTP/SAVPF for DTLS-SRTP which is not correct. More info at https://bugzilla.mozilla.org/show_bug.cgi?id=827932.
if (o_hdr_M.find_a("crypto")) {
o_hdr_M.s_proto = "RTP/SAVPF";
}
else if (b_fingerprint || o_hdr_M.find_a("fingerprint")) {
o_hdr_M.s_proto = "UDP/TLS/RTP/SAVPF";
}
// HACK: https://bugzilla.mozilla.org/show_bug.cgi?id=1072384
if (o_hdr_M.o_hdr_C && o_hdr_M.o_hdr_C.s_addr === "0.0.0.0") {
o_hdr_M.o_hdr_C.s_addr = "127.0.0.1";
}
// bandwidth
if (this.o_bandwidth) {
if (this.o_bandwidth.audio && o_hdr_M.s_media.toLowerCase() == "audio") {
o_hdr_M.add_header(new tsdp_header_B("AS:" + this.o_bandwidth.audio));
}
else if (this.o_bandwidth.video && o_hdr_M.s_media.toLowerCase() == "video") {
o_hdr_M.add_header(new tsdp_header_B("AS:" + this.o_bandwidth.video));
}
}
}
}
return 0;
}
tmedia_session_jsep.prototype.decorate_ro = function (b_remove_bundle) {
if (this.o_sdp_ro) {
var o_hdr_M, o_hdr_A;
var i_index = 0, i;
// FIXME: Chrome fails to parse SDP with global SDP "a=" attributes
// Chrome 21.0.1154.0+ generate "a=group:BUNDLE audio video" but cannot parse it
// In fact, new the attribute is left the ice callback is called twice and the 2nd one trigger new INVITE then 200OK. The SYN_ERR is caused by the SDP in the 200 OK.
// Is it because of "a=rtcp:1 IN IP4 0.0.0.0"?
if (b_remove_bundle) {
this.o_sdp_ro.remove_header(tsdp_header_type_e.A);
}
// ==== START: RFC5939 utility functions ==== //
var rfc5939_get_acap_part = function (o_hdr_a, i_part/* i_part = 1: field, 2: value*/) {
var ao_match = o_hdr_a.s_value.match(/^\d\s+(\w+):([\D|\d]+)/i);
if (ao_match && ao_match.length == 3) {
return ao_match[i_part];
}
}
var rfc5939_acap_ensure = function (o_hdr_a) {
if (o_hdr_a && o_hdr_a.s_field == "acap") {
o_hdr_a.s_field = rfc5939_get_acap_part(o_hdr_a, 1);
o_hdr_a.s_value = rfc5939_get_acap_part(o_hdr_a, 2);
}
}
var rfc5939_get_headerA_at = function (o_msg, s_media, s_field, i_index) {
var i_pos = 0;
var get_headerA_at = function (o_sdp, s_field, i_index) {
if (o_sdp) {
var ao_headersA = (o_sdp.ao_headers || o_sdp.ao_hdr_A);
for (var i = 0; i < ao_headersA.length; ++i) {
if (ao_headersA[i].e_type == tsdp_header_type_e.A && ao_headersA[i].s_value) {
var b_found = (ao_headersA[i].s_field === s_field);
if (!b_found && ao_headersA[i].s_field == "acap") {
b_found = (rfc5939_get_acap_part(ao_headersA[i], 1) == s_field);
}
if (b_found && i_pos++ >= i_index) {
return ao_headersA[i];
}
}
}
}
}
var o_hdr_a = get_headerA_at(o_msg, s_field, i_index); // find at session level
if (!o_hdr_a) {
return get_headerA_at(o_msg.get_header_m_by_name(s_media), s_field, i_index); // find at media level
}
return o_hdr_a;
}
// ==== END: RFC5939 utility functions ==== //
// change profile if not secure
//!\ firefox nighly: DTLS-SRTP only, chrome: SDES-SRTP
var b_fingerprint = !!this.o_sdp_ro.get_header_a("fingerprint"); // session-level fingerprint
while ((o_hdr_M = this.o_sdp_ro.get_header_at(tsdp_header_type_e.M, i_index++))) {
// check for "crypto:"/"fingerprint:" lines (event if it's not valid to provide "crypto" lines in non-secure SDP many clients do it, so, just check)
if (o_hdr_M.s_proto.indexOf("SAVP") < 0) {
if (o_hdr_M.find_a("crypto")) {
o_hdr_M.s_proto = "RTP/SAVPF";
break;
}
else if (b_fingerprint || o_hdr_M.find_a("fingerprint")) {
o_hdr_M.s_proto = "UDP/TLS/RTP/SAVPF";
break;
}
}
// rfc5939: "acap:fingerprint,setup,connection"
if (o_hdr_M.s_proto.indexOf("SAVP") < 0) {
if ((o_hdr_A = rfc5939_get_headerA_at(this.o_sdp_ro, o_hdr_M.s_media, "fingerprint", 0))) {
rfc5939_acap_ensure(o_hdr_A);
if ((o_hdr_A = rfc5939_get_headerA_at(this.o_sdp_ro, o_hdr_M.s_media, "setup", 0))) {
rfc5939_acap_ensure(o_hdr_A);
}
if ((o_hdr_A = rfc5939_get_headerA_at(this.o_sdp_ro, o_hdr_M.s_media, "connection", 0))) {
rfc5939_acap_ensure(o_hdr_A);
}
o_hdr_M.s_proto = "UDP/TLS/RTP/SAVP";
}
}
// rfc5939: "acap:crypto". Only if DTLS is OFF
if (o_hdr_M.s_proto.indexOf("SAVP") < 0) {
i = 0;
while ((o_hdr_A = rfc5939_get_headerA_at(this.o_sdp_ro, o_hdr_M.s_media, "crypto", i++))) {
rfc5939_acap_ensure(o_hdr_A);
o_hdr_M.s_proto = "RTP/SAVPF";
// do not break => find next "acap:crypto" lines and ensure them
}
}
// HACK: Nightly 20.0a1 uses RTP/SAVPF for DTLS-SRTP which is not correct. More info at https://bugzilla.mozilla.org/show_bug.cgi?id=827932
// Same for chrome: https://code.google.com/p/sipml5/issues/detail?id=92
if (o_hdr_M.s_proto.indexOf("UDP/TLS/RTP/SAVP") != -1) {
o_hdr_M.s_proto = "RTP/SAVPF";
}
}
}
return 0;
}
tmedia_session_jsep.prototype.subscribe_stream_events = function () {
if (this.o_pc) {
var This = (tmedia_session_jsep01.mozThis || this);
this.o_pc.onaddstream = function (evt) {
tsk_utils_log_info("__on_add_stream");
This.o_remote_stream = evt.stream;
if (This.o_mgr) {
This.o_mgr.set_stream_remote(evt.stream);
}
}
this.o_pc.onremovestream = function (evt) {
tsk_utils_log_info("__on_remove_stream");
This.o_remote_stream = null;
if (This.o_mgr) {
This.o_mgr.set_stream_remote(null);
}
}
}
}
tmedia_session_jsep.prototype.close = function () {
if (this.o_mgr) { // 'onremovestream' not always called
this.o_mgr.set_stream_remote(null);
this.o_mgr.set_stream_local(null);
}
if (this.o_pc) {
if (this.o_local_stream) {
// TODO: On Firefox 26: Error: "removeStream not implemented yet"
try { this.o_pc.removeStream(this.o_local_stream); } catch (e) { tsk_utils_log_error(e); }
if (!this.b_cache_stream || (this.e_type == tmedia_type_e.SCREEN_SHARE)) { // only stop if caching is disabled or screenshare
try {
var tracks = this.o_local_stream.getTracks();
for (var track in tracks) {
tracks[track].stop();
}
} catch (e) { tsk_utils_log_error(e); }
try { this.o_local_stream.stop(); } catch (e) { } // Deprecated in Chrome 45: https://github.com/DoubangoTelecom/sipml5/issues/231
}
this.o_local_stream = null;
}
this.o_pc.close();
this.o_pc = null;
this.b_sdp_lo_pending = false;
this.b_sdp_ro_pending = false;
}
}
tmedia_session_jsep.prototype.__acked = function () {
return 0;
}
tmedia_session_jsep.prototype.__hold = function () {
if (this.b_lo_held) {
// tsk_utils_log_warn('already on hold');
return;
}
this.b_lo_held = true;
this.o_sdp_ro = null;
this.o_sdp_lo = null;
if (this.o_pc && this.o_local_stream) {
this.o_pc.removeStream(this.o_local_stream);
}
return 0;
}
tmedia_session_jsep.prototype.__resume = function () {
if (!this.b_lo_held) {
// tsk_utils_log_warn('not on hold');
return;
}
this.b_lo_held = false;
this.o_sdp_lo = null;
this.o_sdp_ro = null;
if (this.o_pc && this.o_local_stream) {
this.o_pc.addStream(this.o_local_stream);
}
return 0;
}
//
// JSEP01
//
function tmedia_session_jsep01(o_mgr) {
tmedia_session_jsep.call(this, o_mgr);
this.o_media_constraints =
{
'mandatory':
{
'OfferToReceiveAudio': !!(this.e_type.i_id & tmedia_type_e.AUDIO.i_id),
'OfferToReceiveVideo': !!(this.e_type.i_id & tmedia_type_e.VIDEO.i_id)
}
};
if (tsk_utils_get_navigator_friendly_name() == 'firefox') {
tmedia_session_jsep01.mozThis = this; // FIXME: no longer needed? At least not needed on FF 34.05
this.o_media_constraints.mandatory.MozDontOfferDataChannel = true;
}
}
tmedia_session_jsep01.mozThis = undefined;
tmedia_session_jsep01.onGetUserMediaSuccess = function (o_stream, _This) {
tsk_utils_log_info("onGetUserMediaSuccess");
var This = (tmedia_session_jsep01.mozThis || _This);
if (This && This.o_pc && This.o_mgr) {
if (!This.b_sdp_lo_pending) {
tsk_utils_log_warn("onGetUserMediaSuccess but no local sdp request is pending");
return;
}
if (o_stream) {
// save stream other next calls
if (o_stream.getAudioTracks().length > 0 && o_stream.getVideoTracks().length == 0) {
__o_jsep_stream_audio = o_stream;
}
else if (o_stream.getAudioTracks().length > 0 && o_stream.getVideoTracks().length > 0) {
__o_jsep_stream_audiovideo = o_stream;
}
if (!This.o_local_stream) {
This.o_mgr.callback(tmedia_session_events_e.STREAM_LOCAL_ACCEPTED, this.e_type);
}
// HACK: Firefox only allows to call gum one time
if (tmedia_session_jsep01.mozThis) {
__o_jsep_stream_audiovideo = __o_jsep_stream_audio = o_stream;
}
This.o_local_stream = o_stream;
This.o_pc.addStream(o_stream);
}
else {
// Probably call held
}
This.o_mgr.set_stream_local(o_stream);
var b_answer = ((This.b_sdp_ro_pending || This.b_sdp_ro_offer) && (This.o_sdp_ro != null));
if (b_answer) {
tsk_utils_log_info("createAnswer");
This.o_pc.createAnswer(
tmedia_session_jsep01.mozThis ? tmedia_session_jsep01.onCreateSdpSuccess : function (o_offer) { tmedia_session_jsep01.onCreateSdpSuccess(o_offer, This); },
tmedia_session_jsep01.mozThis ? tmedia_session_jsep01.onCreateSdpError : function (s_error) { tmedia_session_jsep01.onCreateSdpError(s_error, This); },
This.o_media_constraints,
false // createProvisionalAnswer
);
}
else {
tsk_utils_log_info("createOffer");
This.o_pc.createOffer(
tmedia_session_jsep01.mozThis ? tmedia_session_jsep01.onCreateSdpSuccess : function (o_offer) { tmedia_session_jsep01.onCreateSdpSuccess(o_offer, This); },
tmedia_session_jsep01.mozThis ? tmedia_session_jsep01.onCreateSdpError : function (s_error) { tmedia_session_jsep01.onCreateSdpError(s_error, This); },
This.o_media_constraints
);
}
}
}
tmedia_session_jsep01.onGetUserMediaError = function (s_error, _This) {
tsk_utils_log_info("onGetUserMediaError");
var This = (tmedia_session_jsep01.mozThis || _This);
if (This && This.o_mgr) {
tsk_utils_log_error(s_error);
This.o_mgr.callback(tmedia_session_events_e.STREAM_LOCAL_REFUSED, This.e_type);
}
}
tmedia_session_jsep01.onCreateSdpSuccess = function (o_sdp, _This) {
tsk_utils_log_info("onCreateSdpSuccess");
var This = (tmedia_session_jsep01.mozThis || _This);
if (This && This.o_pc) {
This.o_pc.setLocalDescription(o_sdp,
tmedia_session_jsep01.mozThis ? tmedia_session_jsep01.onSetLocalDescriptionSuccess : function () { tmedia_session_jsep01.onSetLocalDescriptionSuccess(This); },
tmedia_session_jsep01.mozThis ? tmedia_session_jsep01.onSetLocalDescriptionError : function (s_error) { tmedia_session_jsep01.onSetLocalDescriptionError(s_error, This); }
);
}
}
tmedia_session_jsep01.onCreateSdpError = function (s_error, _This) {
tsk_utils_log_info("onCreateSdpError");
var This = (tmedia_session_jsep01.mozThis || _This);
if (This && This.o_mgr) {
tsk_utils_log_error(s_error);
This.o_mgr.callback(tmedia_session_events_e.GET_LO_FAILED, This.e_type);
}
}
tmedia_session_jsep01.onSetLocalDescriptionSuccess = function (_This) {
tsk_utils_log_info("onSetLocalDescriptionSuccess");
var This = (tmedia_session_jsep01.mozThis || _This);
if (This && This.o_pc) {
if ((This.o_pc.iceGatheringState || This.o_pc.iceState) === "complete") {
tmedia_session_jsep01.onIceGatheringCompleted(This);
}
This.b_sdp_ro_offer = false; // reset until next incoming RO
}
}
tmedia_session_jsep01.onSetLocalDescriptionError = function (s_error, _This) {
tsk_utils_log_info("onSetLocalDescriptionError");
var This = (tmedia_session_jsep01.mozThis || _This);
if (This && This.o_mgr) {
tsk_utils_log_error(s_error.toString());
This.o_mgr.callback(tmedia_session_events_e.GET_LO_FAILED, This.e_type);
}
}
tmedia_session_jsep01.onSetRemoteDescriptionSuccess = function (_This) {
tsk_utils_log_info("onSetRemoteDescriptionSuccess");
var This = (tmedia_session_jsep01.mozThis || _This);
if (This) {
if (!This.b_sdp_ro_pending && This.b_sdp_ro_offer) {
This.o_sdp_lo = null; // to force new SDP when get_lo() is called
}
}
}
tmedia_session_jsep01.onSetRemoteDescriptionError = function (s_error, _This) {
tsk_utils_log_info("onSetRemoteDescriptionError");
var This = (tmedia_session_jsep01.mozThis || _This);
if (This) {
This.o_mgr.callback(tmedia_session_events_e.SET_RO_FAILED, This.e_type);
tsk_utils_log_error(s_error);
}
}
tmedia_session_jsep01.onIceGatheringCompleted = function (_This) {
tsk_utils_log_info("onIceGatheringCompleted");
var This = (tmedia_session_jsep01.mozThis || _This);
if (This && This.o_pc) {
if (!This.b_sdp_lo_pending) {
tsk_utils_log_warn("onIceGatheringCompleted but no local sdp request is pending");
return;
}
This.b_sdp_lo_pending = false;
// HACK: Firefox Nightly 20.0a1(2013-01-08): PeerConnection.localDescription has a wrong value (remote sdp). More info at https://bugzilla.mozilla.org/show_bug.cgi?id=828235
var localDescription = (This.localDescription || This.o_pc.localDescription);
if (localDescription) {
This.o_sdp_jsep_lo = localDescription;
This.o_sdp_lo = tsdp_message.prototype.Parse(This.o_sdp_jsep_lo.sdp);
This.decorate_lo();
if (This.o_mgr) {
This.o_mgr.callback(tmedia_session_events_e.GET_LO_SUCCESS, This.e_type);
}
}
else {
This.o_mgr.callback(tmedia_session_events_e.GET_LO_FAILED, This.e_type);
tsk_utils_log_error("localDescription is null");
}
}
}
tmedia_session_jsep01.onIceCandidate = function (o_event, _This) {
var This = (tmedia_session_jsep01.mozThis || _This);
if (!This || !This.o_pc) {
tsk_utils_log_error("This/PeerConnection is null: unexpected");
return;
}
var iceState = (This.o_pc.iceGatheringState || This.o_pc.iceState);
tsk_utils_log_info("onIceCandidate = " + iceState);
if (iceState === "complete" || (o_event && !o_event.candidate)) {
tsk_utils_log_info("ICE GATHERING COMPLETED!");
tmedia_session_jsep01.onIceGatheringCompleted(This);
}
else if (This.o_pc.iceState === "failed") {
tsk_utils_log_error("Ice state is 'failed'");
This.o_mgr.callback(tmedia_session_events_e.GET_LO_FAILED, This.e_type);
}
}
tmedia_session_jsep01.onNegotiationNeeded = function (o_event, _This) {
tsk_utils_log_info("onNegotiationNeeded");
var This = (tmedia_session_jsep01.mozThis || _This);
if (!This || !This.o_pc) {
// do not raise error: could happen after pc.close()
return;
}
if ((This.o_pc.iceGatheringState || This.o_pc.iceState) !== "new") {
tmedia_session_jsep01.onGetUserMediaSuccess(This.b_lo_held ? null : This.o_local_stream, This);
}
}
tmedia_session_jsep01.onSignalingstateChange = function (o_event, _This) {
var This = (tmedia_session_jsep01.mozThis || _This);
if (!This || !This.o_pc) {
// do not raise error: could happen after pc.close()
return;
}
tsk_utils_log_info("onSignalingstateChange:" + This.o_pc.signalingState);
if (This.o_local_stream && This.o_pc.signalingState === "have-remote-offer") {
tmedia_session_jsep01.onGetUserMediaSuccess(This.o_local_stream, This);
}
}
tmedia_session_jsep01.prototype.__get_lo = function () {
var This = this;
if (!this.o_pc && !this.b_lo_held) {
var o_video_constraints = {
mandatory: {},
optional: []
};
if ((this.e_type.i_id & tmedia_type_e.SCREEN_SHARE.i_id) == tmedia_type_e.SCREEN_SHARE.i_id) {
o_video_constraints.mandatory.chromeMediaSource = 'screen';
}
if (this.e_type.i_id & tmedia_type_e.VIDEO.i_id) {
if (this.o_video_size) {
if (this.o_video_size.minWidth) o_video_constraints.mandatory.minWidth = this.o_video_size.minWidth;
if (this.o_video_size.minHeight) o_video_constraints.mandatory.minHeight = this.o_video_size.minHeight;
if (this.o_video_size.maxWidth) o_video_constraints.mandatory.maxWidth = this.o_video_size.maxWidth;
if (this.o_video_size.maxHeight) o_video_constraints.mandatory.maxHeight = this.o_video_size.maxHeight;
}
try { tsk_utils_log_info("Video Contraints:" + JSON.stringify(o_video_constraints)); } catch (e) { }
}
var o_iceServers = this.ao_ice_servers;
if (!o_iceServers) { // defines default ICE servers only if none exist (because WebRTC requires ICE)
// HACK Nightly 21.0a1 (2013-02-18):
// - In RTCConfiguration passed to RTCPeerConnection constructor: FQDN not yet implemented (only IP-#s). Omitting "stun:stun.l.google.com:19302"
// - CHANGE-REQUEST not supported when using "numb.viagenie.ca"
// - (stun/ERR) Missing XOR-MAPPED-ADDRESS when using "stun.l.google.com"
// numb.viagenie.ca: 66.228.45.110:
// stun.l.google.com: 173.194.78.127
// stun.counterpath.net: 216.93.246.18
// "23.21.150.121" is the default STUN server used in Nightly
o_iceServers = tmedia_session_jsep01.mozThis
? [{ url: 'stun:23.21.150.121:3478' }, { url: 'stun:216.93.246.18:3478' }, { url: 'stun:66.228.45.110:3478' }, { url: 'stun:173.194.78.127:19302' }]
: [{ url: 'stun:stun.l.google.com:19302' }, { url: 'stun:stun.counterpath.net:3478' }, { url: 'stun:numb.viagenie.ca:3478' }];
}
try { tsk_utils_log_info("ICE servers:" + JSON.stringify(o_iceServers)); } catch (e) { }
this.o_pc = new window.RTCPeerConnection(
(o_iceServers && !o_iceServers.length) ? null : { iceServers: o_iceServers, rtcpMuxPolicy: "negotiate" }, // empty array is used to disable STUN/TURN.
this.o_media_constraints
);
this.o_pc.onicecandidate = tmedia_session_jsep01.mozThis ? tmedia_session_jsep01.onIceCandidate : function (o_event) { tmedia_session_jsep01.onIceCandidate(o_event, This); };
this.o_pc.onnegotiationneeded = tmedia_session_jsep01.mozThis ? tmedia_session_jsep01.onNegotiationNeeded : function (o_event) { tmedia_session_jsep01.onNegotiationNeeded(o_event, This); };
this.o_pc.onsignalingstatechange = tmedia_session_jsep01.mozThis ? tmedia_session_jsep01.onSignalingstateChange : function (o_event) { tmedia_session_jsep01.onSignalingstateChange(o_event, This); };
this.subscribe_stream_events();
}
if (!this.o_sdp_lo && !this.b_sdp_lo_pending) {
this.b_sdp_lo_pending = true;
// set penfing ro if there is one
if (this.b_sdp_ro_pending && this.o_sdp_ro) {
this.__set_ro(this.o_sdp_ro, true);
}
// get media stream
if (this.e_type == tmedia_type_e.AUDIO && (this.b_cache_stream && __o_jsep_stream_audio)) {
tmedia_session_jsep01.onGetUserMediaSuccess(__o_jsep_stream_audio, This);
}
else if (this.e_type == tmedia_type_e.AUDIO_VIDEO && (this.b_cache_stream && __o_jsep_stream_audiovideo)) {
tmedia_session_jsep01.onGetUserMediaSuccess(__o_jsep_stream_audiovideo, This);
}
else {
if (!this.b_lo_held && !this.o_local_stream) {
this.o_mgr.callback(tmedia_session_events_e.STREAM_LOCAL_REQUESTED, this.e_type);
navigator.getUserMedia(
{
audio: (this.e_type == tmedia_type_e.SCREEN_SHARE) ? false : !!(this.e_type.i_id & tmedia_type_e.AUDIO.i_id), // IMPORTANT: Chrome '28.0.1500.95 m' doesn't support using audio with screenshare
video: !!(this.e_type.i_id & tmedia_type_e.VIDEO.i_id) ? o_video_constraints : false, // "SCREEN_SHARE" contains "VIDEO" flag -> (VIDEO & SCREEN_SHARE) = VIDEO
data: false
},
tmedia_session_jsep01.mozThis ? tmedia_session_jsep01.onGetUserMediaSuccess : function (o_stream) { tmedia_session_jsep01.onGetUserMediaSuccess(o_stream, This); },
tmedia_session_jsep01.mozThis ? tmedia_session_jsep01.onGetUserMediaError : function (s_error) { tmedia_session_jsep01.onGetUserMediaError(s_error, This); }
);
}
}
}
return this.o_sdp_lo;
}
tmedia_session_jsep01.prototype.__set_ro = function (o_sdp, b_is_offer) {
if (!o_sdp) {
tsk_utils_log_error("Invalid argument");
return -1;
}
/* update remote offer */
this.o_sdp_ro = o_sdp;
this.b_sdp_ro_offer = b_is_offer;
/* reset local sdp */
if (b_is_offer) {
this.o_sdp_lo = null;
}
if (this.o_pc) {
try {
var This = this;
this.decorate_ro(false);
tsk_utils_log_info("setRemoteDescription(" + (b_is_offer ? "offer)" : "answer)") + "\n" + this.o_sdp_ro);
this.o_pc.setRemoteDescription(
new window.RTCSessionDescription({ type: b_is_offer ? "offer" : "answer", sdp: This.o_sdp_ro.toString() }),
tmedia_session_jsep01.mozThis ? tmedia_session_jsep01.onSetRemoteDescriptionSuccess : function () { tmedia_session_jsep01.onSetRemoteDescriptionSuccess(This); },
tmedia_session_jsep01.mozThis ? tmedia_session_jsep01.onSetRemoteDescriptionError : function (s_error) { tmedia_session_jsep01.onSetRemoteDescriptionError(s_error, This); }
);
}
catch (e) {
tsk_utils_log_error(e);
this.o_mgr.callback(tmedia_session_events_e.SET_RO_FAILED, this.e_type);
return -2;
}
finally {
this.b_sdp_ro_pending = false;
}
}
else {
this.b_sdp_ro_pending = true;
}
return 0;
}
| DoubangoTelecom/sipml5 | src/tinyMEDIA/src/tmedia_session_jsep.js | JavaScript | bsd-3-clause | 31,502 |
package org.team2168.commands.intake;
import org.team2168.RobotMap;
import org.team2168.commands.winch.WaitUntilBallNotPresent;
import org.team2168.commands.winch.WaitUntilBallPresent;
import edu.wpi.first.wpilibj.command.CommandGroup;
public class IntakeSingleBall extends CommandGroup {
public IntakeSingleBall() {
//Drive the motors to acquire ball
addParallel(new IntakeDriveMotor(
-RobotMap.intakeWheelVoltage.getDouble()));
//wait until you see a ball
addSequential(new WaitUntilBallPresent());
//wait until you don't see a ball
addSequential(new WaitUntilBallNotPresent());
//stop intake motors
addSequential(new IntakeDriveMotor(0.0), 0.1);
}
}
| Team2168/FRC2014_Main_Robot | src/org/team2168/commands/intake/IntakeSingleBall.java | Java | bsd-3-clause | 688 |
// varinput.js
// Javascript routines to handle variable rendering
// $Id: //dev/EPS/js/varinput.js#48 $
function inspect()
{
form1.xml.value = '1';
SubmitFormSpecial('table');
}
// global variable used for items that submit on change or selection
var autosubmit = '';
var autopublish = '';
var workspaceByPass = false;
function valueChanged(ident) {
var theField = document.getElementById('form1').variablechanged;
if (theField != null) {
theField.value = (theField.value == '') ? ',' + ident + ',' : (theField.value.indexOf(',' + ident + ',') > -1) ? theField.value : theField.value + ident + ',';
if (autopublish.indexOf(',' + ident + ',') > -1 && autosubmitting == 0) {
bypass_comment = 1; autosubmitting = 1;
document.form1.pubPress.value = 'pubPress';
document.form1.autopubvar.value = ident;
PreSubmit('autopublish');
}
else if (autosubmit.indexOf(',' + ident + ',') > -1 && autosubmitting == 0) {
bypass_comment = 1; autosubmitting = 1;
document.form1.subPress.value = 'subPress';
if (workspaceByPass == true) {
document.form1.bypassPress.value = 'bypassPress';
}
PreSubmit();
}
}
}
function valueUnChanged(ident) {
var theField = document.getElementById('form1').variablechanged;
if (theField != null) {
if (theField.value.indexOf(ident + ',') > -1) {
theField.value = theField.value.replace(ident + ',', '');
}
}
}
function processCmt(obj, ident) {
obj.value = obj.value.substring(0, 1999);
var theField = document.getElementById('form1').commentchanged;
theField.value = (theField.value == '') ? ',' + ident + ',' : (theField.value.indexOf(',' + ident + ',') > -1) ? theField.value : theField.value + ident + ',';
valueChanged(ident);
}
function addAutosubmit(ident) {
autosubmit = ((autosubmit == '') ? ',' + ident + ',' : autosubmit + ident + ',');
}
function hasAutoSubmit(ident) {
return (autosubmit.indexOf(',' + ident + ',') > -1);
}
function addAutoPublish(ident) {
autopublish = ((autopublish == '') ? ',' + ident + ',' : autopublish + ident + ',');
}
function hasVariableChanged() { return (document.getElementById('form1').variablechanged.value.length > 1); }
function hasCommentChanged() { return (document.getElementById('form1').commentchanged.value.length > 1); }
function keyPressed(f,e, acceptEnter) // can use as form or field handler
{
var keycode;
if (window.event) keycode = window.event.keyCode;
else if (e) keycode = e.which;
else return true;
if (keycode == 13)
return acceptEnter;
else
return true;
}
function SubmitFormSpecial(s, s2) {
var form1 = document.getElementById('form1');
if (s2 != null) {
if (s2 == 'table_image')
form1.table_image.value = 'true';
}
form1.act.value = s;
form1.submit();
}
function SubmitFormSpecialLarge(s,v) {
var form1 = document.getElementById('form1');
form1.act.value = s;
form1.sview.value = v;
form1.submit();
form1.act.value = '';
form1.sview.value = '';
}
function SubmitFormAndExcel() {
var form1 = document.getElementById('form1');
form1.act.value = 'Excel';
form1.submit();
form1.act.value = '';
form1.sview.value = '';
}
function ExcelandRestore(s, isPortForm, varMode) {
var form1 = document.getElementById('form1');
var formType = 'proj';
if (isPortForm == 'true') { formType = 'port'; }
if (varMode != 'output') { varMode = 'input'; }
var aspxPage = formType + varMode + '.aspx?var=';
form1.target = 'excel';
var oldact = form1.action;
form1.action = aspxPage + s + oldact.substring(oldact.indexOf('&')).replace(/var=(\w+)&/, '');
form1.act.value = 'Excel';
form1.submit();
form1.target = '_self';
form1.act.value = '';
form1.action = oldact;
}
function SubmitFormSpecialWithMenus(s) {
var d = new Date(), form1 = document.getElementById('form1');
var wName = d.getUTCSeconds() + '_' + d.getUTCMinutes() + '_'; //Create a unique name for the window
window.open('about:blank', wName, 'toolbar=yes,location=no,directories=yes,status=yes,menubar=yes,scrollbars=yes,resizable=yes,copyhistory=no,width=850,height=700');
form1.target = wName;
form1.act.value = s;
form1.submit();
form1.target = '_self';
form1.act.value = '';
}
function ReturnComment() {
PostSubmit();
}
function SubmitFormSpecialOnValue(field,s) {
if (field.value.length > 0) {
SubmitFormSpecial(s);
field.selectedIndex = 0;
}
}
function currTime() {
var now = new Date();
var hours = now.getHours();
var minutes = now.getMinutes();
var seconds = now.getSeconds();
var timeValue = '' + ((hours > 12) ? hours - 12 : hours);
if (timeValue == '0') timeValue = 12;
timeValue += ((minutes < 10) ? ':0' : ':') + minutes;
timeValue += ((seconds < 10) ? ':0' : ':') + seconds;
timeValue += (hours >= 12) ? ' PM' : ' AM';
return timeValue;
}
function showHandle() {
if (showHandleFlag == 0) {
showHandleFlag = 1;
$('img.frameHandle').show();
setTimeout("$('img.frameHandle').hide(); showHandleFlag=0;", 2600);
}
}
function frameResize() {
if (window.parent.document.getElementById('fs2').getAttribute('cols') == '200,*') {
window.parent.document.getElementById('fs2').setAttribute('cols', '0,*');
$('img.frameHandle').attr('src', 'images/dbl_r.gif').attr('alt', 'Restore the navigation bar').attr('title', 'Restore the navigation bar');
} else {
window.parent.document.getElementById('fs2').setAttribute('cols', '200,*');
$('img.frameHandle').attr('src', 'images/dbl_l.gif').attr('alt', 'Minimize the navigation bar').attr('title', 'Minimize the navigation bar');
}
}
function bindEvents() {
var justFocused;
$('.epsgrid input').mouseup(function(e) {if (justFocused == 1) {e.preventDefault(); justFocused = 0;} });
$('.epsgrid input[type!="checkbox"]').focus(function() {
origVals[this.name] = this.value;
this.select();
justFocused = 1;
setTimeout('justFocused = 0', 50);
}).blur(function() {
resizeCol(this);
}).keydown(function(e) {
return InputKeyPress(this, e);
}).keypress(function(e) {
return keyPressed(this, e, false);
}).change(function() {
fch(this, true, this.id.substring(0, this.id.lastIndexOf('_id')));
});
}
// LEAVE AT BOTTOM OF JS FILE //
// special jQuery to paint events onto inputs //
var showHandleFlag;
showHandleFlag = 0;
if (typeof jQuery != 'undefined') {
$(document).ready(function() {
setTimeout('bindEvents()', 1);
$('.epsvar').change(function() {
var cmdStr;
cmdStr = 'validate_' + $(this).attr('vname') + "($('#valueField_" + $(this).attr('vname') + "').val(),'" + $(this).attr('orig_value') + "',true)";
setTimeout(cmdStr, 1);
});
var textValue;
$('textarea.expanding').each(function() {
textValue = $(this).text();
while (textValue.indexOf('**br**') != -1) {
textValue = textValue.replace('**br**', '\n');
}
$(this).val(textValue);
});
$('textarea.expanding').autogrow();
if (window.parent.document.getElementById('fs2')) {
$('body').mousemove(function(e) {
if (e.pageX < 50 && e.pageY < 50) showHandle();
}).append('<img class="frameHandle" src="images/dbl_l.gif"/>');
$('img.frameHandle').bind('click', function() {frameResize()});
if (window.parent.document.getElementById('fs2').getAttribute('cols') == '0,*') {
$('img.frameHandle').attr('src', 'images/dbl_r.gif');
$('img.frameHandle').attr('alt', 'Restore the navigation bar');
$('img.frameHandle').attr('title', 'Restore the navigation bar');
} else {
$('img.frameHandle').attr('src', 'images/dbl_l.gif').attr('alt', 'Minimize the navigation bar').attr('title', 'Minimize the navigation bar');
}
}
});
}
function openShortcutNode(aspxfile, sc_tid, sc_pid, sc_var, formcls)
{
var urlStr;
urlStr = aspxfile + '?' + 'tempid=' + sc_tid + '\&modelid=' + sc_pid + '\&var=' + sc_var + '\&form_class=' + formcls;
urlStr = urlStr + '\&shortcut_popup=true';
window.open(urlStr, 'shortcut_popup', 'toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes,copyhistory=no,width=650,height=550');
/*
// TODO: thread this into comment and form submit logic
// fixup close button not working
$("#shortcutdiv").load(urlStr).dialog(
{ autoOpen: false ,
modal:true,
height: 650,
width: 800,
buttons: [ {text: "Cancel",
click: function() { $(this).dialog("close"); alert('closing'); }
},
{ text: "Submit",
click: function() { var thisForm = $("#shortcutdiv form"); thisForm.submit(); }
}
]
}
);
$("#shortcutdiv").dialog("open");
*/
}
| danenrich/d3_training | js/varinput.js | JavaScript | bsd-3-clause | 8,742 |
import time, copy
import os, os.path
import sys
import numpy
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from scipy import optimize
from echem_plate_ui import *
from echem_plate_math import *
import pickle
p1='C:/Users/Gregoire/Documents/CaltechWork/echemdrop/2012-9_FeCoNiTi/results/echemplots/2012-9_FeCoNiTi_500C_fastCPCV_plate1_dlist_1066.dat'
p2='C:/Users/Gregoire/Documents/CaltechWork/echemdrop/2012-9_FeCoNiTi/results/echemplots/2012-9_FeCoNiTi_500C_fastCPCV_plate1_dlist_1662.dat'
pill='C:/Users/Gregoire/Documents/CaltechWork/echemdrop/2012-9_FeCoNiTi/results/echemplots/2012-9FeCoNiTi_500C_CAill_plate1_dlist_1164.dat'
os.chdir('C:/Users/Gregoire/Documents/CaltechWork/echemdrop/2012-9_FeCoNiTi/results/echemplots')
vshift=-.24
imult=1.e6
cai0, cai1=(0, 6500)
f=open(p1, mode='r')
d1=pickle.load(f)
f.close()
f=open(p2, mode='r')
d2=pickle.load(f)
f.close()
f=open(pill, mode='r')
dill=pickle.load(f)
f.close()
segd1up, segd1dn=d1['segprops_dlist']
i1up=d1['I(A)'][segd1up['inds']][4:]
lin1up=i1up-d1['I(A)_LinSub'][segd1up['inds']][4:]
v1up=d1['Ewe(V)'][segd1up['inds']][4:]+vshift
i1dn=d1['I(A)'][segd1dn['inds']]
v1dn=d1['Ewe(V)'][segd1dn['inds']]+vshift
i1up*=imult
i1dn*=imult
lin1up*=imult
segd2up, segd2dn=d2['segprops_dlist']
i2up=d2['I(A)'][segd2up['inds']][4:]
lin2up=i2up-d2['I(A)_LinSub'][segd2up['inds']][4:]
v2up=d2['Ewe(V)'][segd2up['inds']][4:]+vshift
i2dn=d2['I(A)'][segd2dn['inds']]
v2dn=d2['Ewe(V)'][segd2dn['inds']]+vshift
i2up*=imult
i2dn*=imult
lin2up*=imult
ica=dill['I(A)_SG'][cai0:cai1]*imult
icadiff=dill['Idiff_time'][cai0:cai1]*imult
tca=dill['t(s)'][cai0:cai1]
tca_cycs=dill['till_cycs']
cycinds=numpy.where((tca_cycs>=tca.min())&(tca_cycs<=tca.max()))[0]
tca_cycs=tca_cycs[cycinds]
iphoto_cycs=dill['Photocurrent_cycs(A)'][cycinds]*imult
pylab.rc('font', family='serif', serif='Times New Roman', size=11)
fig=pylab.figure(figsize=(3.5, 4.5))
#ax1=pylab.subplot(211)
#ax2=pylab.subplot(212)
ax1=fig.add_axes((.2, .6, .74, .35))
ax2=fig.add_axes((.2, .11, .6, .35))
ax3=ax2.twinx()
ax1.plot(v1up, i1up, 'g-', linewidth=1.)
ax1.plot(v1up, lin1up, 'g:', linewidth=1.)
ax1.plot(v1dn, i1dn, 'g--', linewidth=1.)
ax1.plot(v2up, i2up, 'b-', linewidth=1.)
ax1.plot(v2up, lin2up, 'b:', linewidth=1.)
ax1.plot(v2dn, i2dn, 'b--', linewidth=1.)
ax1.set_xlim((-.1, .62))
ax1.set_ylim((-40, 130))
ax1.set_xlabel('Potential (V vs H$_2$O/O$_2$)', fontsize=12)
ax1.set_ylabel('Current ($\mu$A)', fontsize=12)
ax2.plot(tca, ica, 'k-')
ax2.plot(tca, icadiff, 'b--', linewidth=2)
ax2.set_xlim((0, 6.5))
ax2.set_ylim((0, 0.4))
ax3.plot(tca_cycs, iphoto_cycs, 'ro-')
ax3.set_ylim((0, 0.1))
ax2.set_xlabel('Elapsed time (s)', fontsize=12)
ax2.set_ylabel('Current ($\mu$A)', fontsize=12)
ax3.set_ylabel('Photocurrent ($\mu$A)', fontsize=12)
pylab.show()
print ''.join(['%s%.3f' %tup for tup in zip(dill['elements'], dill['compositions'])])
print ''.join(['%s%.3f' %tup for tup in zip(d1['elements'], d1['compositions'])])
print ''.join(['%s%.3f' %tup for tup in zip(d2['elements'], d2['compositions'])])
| johnmgregoire/JCAPdatavis | echem_paperplots.py | Python | bsd-3-clause | 3,052 |
<?php
/**
* @link http://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/
namespace yii\mongodb;
use Yii;
use yii\base\InvalidConfigException;
use yii\test\BaseActiveFixture;
/**
* ActiveFixture represents a fixture backed up by a [[modelClass|MongoDB ActiveRecord class]] or a [[collectionName|MongoDB collection]].
*
* Either [[modelClass]] or [[collectionName]] must be set. You should also provide fixture data in the file
* specified by [[dataFile]] or overriding [[getData()]] if you want to use code to generate the fixture data.
*
* When the fixture is being loaded, it will first call [[resetCollection()]] to remove any existing data in the collection.
* It will then populate the table with the data returned by [[getData()]].
*
* After the fixture is loaded, you can access the loaded data via the [[data]] property. If you set [[modelClass]],
* you will also be able to retrieve an instance of [[modelClass]] with the populated data via [[getModel()]].
*
* @author Paul Klimov <klimov.paul@gmail.com>
* @since 2.0
*/
class ActiveFixture extends BaseActiveFixture
{
/**
* @var Connection|string the DB connection object or the application component ID of the DB connection.
*/
public $db = 'mongodb';
/**
* @var string|array the collection name that this fixture is about. If this property is not set,
* the table name will be determined via [[modelClass]].
* @see Connection::getCollection()
*/
public $collectionName;
/**
* @inheritdoc
*/
public function init()
{
parent::init();
if (!isset($this->modelClass) && !isset($this->collectionName)) {
throw new InvalidConfigException('Either "modelClass" or "collectionName" must be set.');
}
}
/**
* Loads the fixture data.
* The default implementation will first reset the DB table and then populate it with the data
* returned by [[getData()]].
*/
public function load()
{
$this->resetCollection();
$this->data = [];
$data = $this->getData();
$this->getCollection()->batchInsert($data);
foreach ($data as $alias => $row) {
$this->data[$alias] = $row;
}
}
protected function getCollection()
{
return $this->db->getCollection($this->getCollectionName());
}
protected function getCollectionName()
{
if ($this->collectionName) {
return $this->collectionName;
} else {
/* @var $modelClass ActiveRecord */
$modelClass = $this->modelClass;
return $modelClass::collectionName();
}
}
/**
* Returns the fixture data.
*
* This method is called by [[loadData()]] to get the needed fixture data.
*
* The default implementation will try to return the fixture data by including the external file specified by [[dataFile]].
* The file should return an array of data rows (column name => column value), each corresponding to a row in the table.
*
* If the data file does not exist, an empty array will be returned.
*
* @return array the data rows to be inserted into the collection.
*/
protected function getData()
{
if ($this->dataFile === null) {
$class = new \ReflectionClass($this);
$dataFile = dirname($class->getFileName()) . '/data/' . $this->getCollectionName() . '.php';
return is_file($dataFile) ? require($dataFile) : [];
} else {
return parent::getData();
}
}
/**
* Removes all existing data from the specified collection and resets sequence number if any.
* This method is called before populating fixture data into the collection associated with this fixture.
*/
protected function resetCollection()
{
$this->getCollection()->remove();
}
}
| avron99/delayed-orders | var/www/yii/vendor/yiisoft/yii2-mongodb/ActiveFixture.php | PHP | bsd-3-clause | 4,111 |
/* Sirikata Object Host
* MeshListener.hpp
*
* Copyright (c) 2009, Daniel Reiter Horn
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Sirikata nor the names of its contributors may
* be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
* OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef _SIRIKATA_MESH_LISTENER_HPP_
#define _SIRIKATA_MESH_LISTENER_HPP_
#include <sirikata/core/transfer/URI.hpp>
#include <sirikata/mesh/Meshdata.hpp>
#include <sirikata/proxyobject/ProxyObject.hpp>
namespace Sirikata {
class SIRIKATA_PROXYOBJECT_EXPORT MeshListener
{
public:
virtual ~MeshListener() {}
virtual void onSetMesh (ProxyObjectPtr proxy, Transfer::URI const& newMesh, const SpaceObjectReference& sporef) = 0;
virtual void onSetScale (ProxyObjectPtr proxy, float32 newScale,const SpaceObjectReference& sporef ) = 0;
virtual void onSetPhysics (ProxyObjectPtr proxy, const String& phy,const SpaceObjectReference& sporef ) {};
virtual void onSetIsAggregate (ProxyObjectPtr proxy, bool isAggregate, const SpaceObjectReference& sporef ) = 0;
};
} // namespace Sirikata
#endif
| sirikata/sirikata | libproxyobject/include/sirikata/proxyobject/MeshListener.hpp | C++ | bsd-3-clause | 2,464 |
#ifndef PWN_ENGINE_GAMEIMP_HPP
#define PWN_ENGINE_GAMEIMP_HPP
#include <vector>
#include <map>
#include <boost/shared_ptr.hpp>
#include <pwn/math/types.h>
//#include <events/event.h>
#include <pwn/engine/key.h>
namespace pwn
{
namespace render
{
class VirtualDisplay;
}
namespace engine
{
class System;
class Display;
/** Implementation of the Game class.
* This class sort of follows the pimpl idiom, except the "private" is private at librariy-scope, and not at class-scope
*/
class GameImp
{
public:
GameImp();
~GameImp();
void
install(System* system); // assumes ownership
void
updateSystems();
// only associate, ownership has to be handled somewhere else
void
display_add(int id, Display* disp);
void
display(int id, render::VirtualDisplay& world);
void
display_remove(int id, Display* disp);
// post events
void
handleKey(Key::Code key, bool isDown);
void
handleMouse(const math::vec2 movement);
typedef boost::shared_ptr<System> SystemPtr;
private:
std::vector<SystemPtr> systems;
typedef std::map<int, Display*> DisplayMap;
DisplayMap displays;
};
}
}
#endif
| madeso/pwn-engine | src/engine/gameimp.hpp | C++ | bsd-3-clause | 1,295 |
/*
-- MAGMA (version 1.6.2) --
Univ. of Tennessee, Knoxville
Univ. of California, Berkeley
Univ. of Colorado, Denver
@date May 2015
@generated from magma_zsolverinfo.cpp normal z -> c, Sun May 3 11:23:01 2015
@author Hartwig Anzt
*/
#include "common_magmasparse.h"
#define RTOLERANCE lapackf77_slamch( "E" )
#define ATOLERANCE lapackf77_slamch( "E" )
/**
Purpose
-------
Prints information about a previously called solver.
Arguments
---------
@param[in]
solver_par magma_c_solver_par*
structure containing all solver information
@param[in,out]
precond_par magma_c_preconditioner*
structure containing all preconditioner information
@param[in]
queue magma_queue_t
Queue to execute in.
@ingroup magmasparse_caux
********************************************************************/
extern "C" magma_int_t
magma_csolverinfo(
magma_c_solver_par *solver_par,
magma_c_preconditioner *precond_par,
magma_queue_t queue )
{
if( solver_par->verbose > 0 ){
magma_int_t k = solver_par->verbose;
printf("%%======================================================="
"======%%\n");
switch( solver_par->solver ) {
case Magma_CG:
printf("%% CG performance analysis every %d iteration\n",
(int) k); break;
case Magma_PCG:
printf("%% CG performance analysis every %d iteration\n",
(int) k); break;
case Magma_CGMERGE:
printf("%% CG (merged) performance analysis every %d iteration\n",
(int) k); break;
case Magma_BICGSTAB:
printf("%% BiCGSTAB performance analysis every %d iteration\n",
(int) k); break;
case Magma_PBICGSTAB:
printf("%% BiCGSTAB performance analysis every %d iteration\n",
(int) k); break;
case Magma_BICGSTABMERGE:
printf("%% BiCGSTAB (merged) performance analysis every %d iteration\n",
(int) k); break;
case Magma_BICGSTABMERGE2:
printf("%% BiCGSTAB (merged) performance analysis every %d iteration\n",
(int) k); break;
case Magma_GMRES:
printf("%% GMRES(%d) performance analysis every %d iteration\n",
(int) solver_par->restart, (int) k); break;
case Magma_PGMRES:
printf("%% GMRES(%d) performance analysis every %d iteration\n",
(int) solver_par->restart, (int) k); break;
case Magma_ITERREF:
printf("%% Iterative refinement performance analysis every %d iteration\n",
(int) k); break;
default:
printf("%% Detailed performance analysis not supported.\n"); break;
}
switch( precond_par->solver ) {
case Magma_CG:
printf("%% Preconditioner used: CG.\n"); break;
case Magma_BICGSTAB:
printf("%% Preconditioner used: BiCGSTAB.\n"); break;
case Magma_GMRES:
printf("%% Preconditioner used: GMRES.\n"); break;
case Magma_JACOBI:
printf("%% Preconditioner used: Jacobi.\n"); break;
case Magma_BAITER:
printf("%% Preconditioner used: Block-asynchronous iteration.\n"); break;
case Magma_ILU:
printf("%% Preconditioner used: ILU(%d).\n", precond_par->levels); break;
case Magma_AILU:
printf("%% Preconditioner used: iterative ILU(%d).\n", precond_par->levels); break;
case Magma_ICC:
printf("%% Preconditioner used: IC(%d).\n", precond_par->levels); break;
case Magma_AICC:
printf("%% Preconditioner used: iterative IC(%d).\n", precond_par->levels); break;
default:
break;
}
printf("%%======================================================="
"======%%\n");
switch( solver_par->solver ) {
case Magma_CG:
printf("%% iter || residual-nrm2 || runtime \n");
printf("%%======================================================="
"======%%\n");
for( int j=0; j<(solver_par->numiter)/k+1; j++ ) {
printf(" %4d || %e || %f\n",
(int) (j*k), solver_par->res_vec[j], solver_par->timing[j]);
}
printf("%%======================================================="
"======%%\n"); break;
case Magma_PCG:
printf("%% iter || residual-nrm2 || runtime \n");
printf("%%======================================================="
"======%%\n");
for( int j=0; j<(solver_par->numiter)/k+1; j++ ) {
printf(" %4d || %e || %f\n",
(int) (j*k), solver_par->res_vec[j], solver_par->timing[j]);
}
printf("%%======================================================="
"======%%\n"); break;
case Magma_CGMERGE:
printf("%% iter || residual-nrm2 || runtime \n");
printf("%%======================================================="
"======%%\n");
for( int j=0; j<(solver_par->numiter)/k+1; j++ ) {
printf(" %4d || %e || %f\n",
(int) (j*k), solver_par->res_vec[j], solver_par->timing[j]);
}
printf("%%======================================================="
"======%%\n"); break;
case Magma_BICGSTAB:
printf("%% iter || residual-nrm2 || runtime \n");
printf("%%======================================================="
"======%%\n");
for( int j=0; j<(solver_par->numiter)/k+1; j++ ) {
printf(" %4d || %e || %f\n",
(int) (j*k), solver_par->res_vec[j], solver_par->timing[j]);
}
printf("%%======================================================="
"======%%\n"); break;
case Magma_PBICGSTAB:
printf("%% iter || residual-nrm2 || runtime \n");
printf("%%======================================================="
"======%%\n");
for( int j=0; j<(solver_par->numiter)/k+1; j++ ) {
printf(" %4d || %e || %f\n",
(int) (j*k), solver_par->res_vec[j], solver_par->timing[j]);
}
printf("%%======================================================="
"======%%\n"); break;
case Magma_BICGSTABMERGE:
printf("%% iter || residual-nrm2 || runtime \n");
printf("%%======================================================="
"======%%\n");
for( int j=0; j<(solver_par->numiter)/k+1; j++ ) {
printf(" %4d || %e || %f\n",
(int) (j*k), solver_par->res_vec[j], solver_par->timing[j]);
}
printf("%%======================================================="
"======%%\n"); break;
case Magma_BICGSTABMERGE2:
printf("%% iter || residual-nrm2 || runtime \n");
printf("%%======================================================="
"======%%\n");
for( int j=0; j<(solver_par->numiter)/k+1; j++ ) {
printf(" %4d || %e || %f\n",
(int) (j*k), solver_par->res_vec[j], solver_par->timing[j]);
}
printf("%%======================================================="
"======%%\n"); break;
case Magma_GMRES:
printf("%% iter || residual-nrm2 || runtime \n");
printf("%%======================================================="
"======%%\n");
for( int j=0; j<(solver_par->numiter)/k+1; j++ ) {
printf(" %4d || %e || %f\n",
(int) (j*k), solver_par->res_vec[j], solver_par->timing[j]);
}
printf("%%======================================================="
"======%%\n"); break;
case Magma_PGMRES:
printf("%% iter || residual-nrm2 || runtime \n");
printf("%%======================================================="
"======%%\n");
for( int j=0; j<(solver_par->numiter)/k+1; j++ ) {
printf(" %4d || %e || %f\n",
(int) (j*k), solver_par->res_vec[j], solver_par->timing[j]);
}
printf("%%======================================================="
"======%%\n"); break;
case Magma_ITERREF:
printf("%% iter || residual-nrm2 || runtime \n");
printf("%%======================================================="
"======%%\n");
for( int j=0; j<(solver_par->numiter)/k+1; j++ ) {
printf(" %4d || %e || %f\n",
(int) (j*k), solver_par->res_vec[j], solver_par->timing[j]);
}
printf("%%======================================================="
"======%%\n"); break;
default:
printf("%%======================================================="
"======%%\n"); break;
}
}
printf("\n%%======================================================="
"======%%\n");
switch( solver_par->solver ) {
case Magma_CG:
printf("%% CG solver summary:\n"); break;
case Magma_PCG:
printf("%% PCG solver summary:\n"); break;
case Magma_CGMERGE:
printf("%% CG solver summary:\n"); break;
case Magma_BICGSTAB:
printf("%% BiCGSTAB solver summary:\n"); break;
case Magma_PBICGSTAB:
printf("%% PBiCGSTAB solver summary:\n"); break;
case Magma_BICGSTABMERGE:
printf("%% BiCGSTAB solver summary:\n"); break;
case Magma_BICGSTABMERGE2:
printf("%% BiCGSTAB solver summary:\n"); break;
case Magma_GMRES:
printf("%% GMRES(%d) solver summary:\n", solver_par->restart); break;
case Magma_PGMRES:
printf("%% PGMRES(%d) solver summary:\n", solver_par->restart); break;
case Magma_ITERREF:
printf("%% Iterative refinement solver summary:\n"); break;
case Magma_JACOBI:
printf("%% CG solver summary:\n"); break;
case Magma_BAITER:
printf("%% Block-asynchronous iteration solver summary:\n"); break;
case Magma_LOBPCG:
printf("%% LOBPCG iteration solver summary:\n"); break;
default:
printf("%% Solver info not supported.\n"); goto cleanup;
}
printf("%% initial residual: %e\n", solver_par->init_res );
printf("%% iterations: %4d\n", (int) (solver_par->numiter) );
printf("%% exact final residual: %e\n%% runtime: %.4f sec\n",
solver_par->final_res, solver_par->runtime);
cleanup:
printf("%%======================================================="
"======%%\n");
return MAGMA_SUCCESS;
}
/**
Purpose
-------
Frees any memory assocoiated with the verbose mode of solver_par. The
other values are set to default.
Arguments
---------
@param[in,out]
solver_par magma_c_solver_par*
structure containing all solver information
@param[in,out]
precond_par magma_c_preconditioner*
structure containing all preconditioner information
@param[in]
queue magma_queue_t
Queue to execute in.
@ingroup magmasparse_caux
********************************************************************/
extern "C" magma_int_t
magma_csolverinfo_free(
magma_c_solver_par *solver_par,
magma_c_preconditioner *precond_par,
magma_queue_t queue )
{
solver_par->init_res = 0.0;
solver_par->iter_res = 0.0;
solver_par->final_res = 0.0;
if ( solver_par->res_vec != NULL ) {
magma_free_cpu( solver_par->res_vec );
solver_par->res_vec = NULL;
}
if ( solver_par->timing != NULL ) {
magma_free_cpu( solver_par->timing );
solver_par->timing = NULL;
}
if ( solver_par->eigenvectors != NULL ) {
magma_free( solver_par->eigenvectors );
solver_par->eigenvectors = NULL;
}
if ( solver_par->eigenvalues != NULL ) {
magma_free_cpu( solver_par->eigenvalues );
solver_par->eigenvalues = NULL;
}
if ( precond_par->d.val != NULL ) {
magma_free( precond_par->d.val );
precond_par->d.val = NULL;
}
if ( precond_par->d2.val != NULL ) {
magma_free( precond_par->d2.val );
precond_par->d2.val = NULL;
}
if ( precond_par->work1.val != NULL ) {
magma_free( precond_par->work1.val );
precond_par->work1.val = NULL;
}
if ( precond_par->work2.val != NULL ) {
magma_free( precond_par->work2.val );
precond_par->work2.val = NULL;
}
if ( precond_par->M.val != NULL ) {
if ( precond_par->M.memory_location == Magma_DEV )
magma_free( precond_par->M.dval );
else
magma_free_cpu( precond_par->M.val );
precond_par->M.val = NULL;
}
if ( precond_par->M.col != NULL ) {
if ( precond_par->M.memory_location == Magma_DEV )
magma_free( precond_par->M.dcol );
else
magma_free_cpu( precond_par->M.col );
precond_par->M.col = NULL;
}
if ( precond_par->M.row != NULL ) {
if ( precond_par->M.memory_location == Magma_DEV )
magma_free( precond_par->M.drow );
else
magma_free_cpu( precond_par->M.row );
precond_par->M.row = NULL;
}
if ( precond_par->M.blockinfo != NULL ) {
magma_free_cpu( precond_par->M.blockinfo );
precond_par->M.blockinfo = NULL;
}
if ( precond_par->L.val != NULL ) {
if ( precond_par->L.memory_location == Magma_DEV )
magma_free( precond_par->L.dval );
else
magma_free_cpu( precond_par->L.val );
precond_par->L.val = NULL;
}
if ( precond_par->L.col != NULL ) {
if ( precond_par->L.memory_location == Magma_DEV )
magma_free( precond_par->L.col );
else
magma_free_cpu( precond_par->L.dcol );
precond_par->L.col = NULL;
}
if ( precond_par->L.row != NULL ) {
if ( precond_par->L.memory_location == Magma_DEV )
magma_free( precond_par->L.drow );
else
magma_free_cpu( precond_par->L.row );
precond_par->L.row = NULL;
}
if ( precond_par->L.blockinfo != NULL ) {
magma_free_cpu( precond_par->L.blockinfo );
precond_par->L.blockinfo = NULL;
}
if ( precond_par->U.val != NULL ) {
if ( precond_par->U.memory_location == Magma_DEV )
magma_free( precond_par->U.dval );
else
magma_free_cpu( precond_par->U.val );
precond_par->U.val = NULL;
}
if ( precond_par->U.col != NULL ) {
if ( precond_par->U.memory_location == Magma_DEV )
magma_free( precond_par->U.dcol );
else
magma_free_cpu( precond_par->U.col );
precond_par->U.col = NULL;
}
if ( precond_par->U.row != NULL ) {
if ( precond_par->U.memory_location == Magma_DEV )
magma_free( precond_par->U.drow );
else
magma_free_cpu( precond_par->U.row );
precond_par->U.row = NULL;
}
if ( precond_par->U.blockinfo != NULL ) {
magma_free_cpu( precond_par->U.blockinfo );
precond_par->U.blockinfo = NULL;
}
if ( precond_par->solver == Magma_ILU ||
precond_par->solver == Magma_AILU ||
precond_par->solver == Magma_ICC||
precond_par->solver == Magma_AICC ) {
cusparseDestroySolveAnalysisInfo( precond_par->cuinfoL );
cusparseDestroySolveAnalysisInfo( precond_par->cuinfoU );
precond_par->cuinfoL = NULL;
precond_par->cuinfoU = NULL;
}
if ( precond_par->LD.val != NULL ) {
if ( precond_par->LD.memory_location == Magma_DEV )
magma_free( precond_par->LD.dval );
else
magma_free_cpu( precond_par->LD.val );
precond_par->LD.val = NULL;
}
if ( precond_par->LD.col != NULL ) {
if ( precond_par->LD.memory_location == Magma_DEV )
magma_free( precond_par->LD.dcol );
else
magma_free_cpu( precond_par->LD.col );
precond_par->LD.col = NULL;
}
if ( precond_par->LD.row != NULL ) {
if ( precond_par->LD.memory_location == Magma_DEV )
magma_free( precond_par->LD.drow );
else
magma_free_cpu( precond_par->LD.row );
precond_par->LD.row = NULL;
}
if ( precond_par->LD.blockinfo != NULL ) {
magma_free_cpu( precond_par->LD.blockinfo );
precond_par->LD.blockinfo = NULL;
}
if ( precond_par->UD.val != NULL ) {
if ( precond_par->UD.memory_location == Magma_DEV )
magma_free( precond_par->UD.dval );
else
magma_free_cpu( precond_par->UD.val );
precond_par->UD.val = NULL;
}
if ( precond_par->UD.col != NULL ) {
if ( precond_par->UD.memory_location == Magma_DEV )
magma_free( precond_par->UD.dcol );
else
magma_free_cpu( precond_par->UD.col );
precond_par->UD.col = NULL;
}
if ( precond_par->UD.row != NULL ) {
if ( precond_par->UD.memory_location == Magma_DEV )
magma_free( precond_par->UD.drow );
else
magma_free_cpu( precond_par->UD.row );
precond_par->UD.row = NULL;
}
if ( precond_par->UD.blockinfo != NULL ) {
magma_free_cpu( precond_par->UD.blockinfo );
precond_par->UD.blockinfo = NULL;
}
precond_par->solver = Magma_NONE;
return MAGMA_SUCCESS;
}
/**
Purpose
-------
Initializes all solver and preconditioner parameters.
Arguments
---------
@param[in,out]
solver_par magma_c_solver_par*
structure containing all solver information
@param[in,out]
precond_par magma_c_preconditioner*
structure containing all preconditioner information
@param[in]
queue magma_queue_t
Queue to execute in.
@ingroup magmasparse_caux
********************************************************************/
extern "C" magma_int_t
magma_csolverinfo_init(
magma_c_solver_par *solver_par,
magma_c_preconditioner *precond_par,
magma_queue_t queue )
{
magma_int_t info = 0;
solver_par->res_vec = NULL;
solver_par->timing = NULL;
solver_par->eigenvectors = NULL;
solver_par->eigenvalues = NULL;
if( solver_par->maxiter == 0 )
solver_par->maxiter = 1000;
if( solver_par->version == 0 )
solver_par->version = 0;
if( solver_par->restart == 0 )
solver_par->restart = 30;
if( solver_par->solver == 0 )
solver_par->solver = Magma_CG;
if ( solver_par->verbose > 0 ) {
CHECK( magma_malloc_cpu( (void **)&solver_par->res_vec, sizeof(real_Double_t)
* ( (solver_par->maxiter)/(solver_par->verbose)+1) ));
CHECK( magma_malloc_cpu( (void **)&solver_par->timing, sizeof(real_Double_t)
*( (solver_par->maxiter)/(solver_par->verbose)+1) ));
} else {
solver_par->res_vec = NULL;
solver_par->timing = NULL;
}
precond_par->d.val = NULL;
precond_par->d2.val = NULL;
precond_par->work1.val = NULL;
precond_par->work2.val = NULL;
precond_par->M.val = NULL;
precond_par->M.col = NULL;
precond_par->M.row = NULL;
precond_par->M.blockinfo = NULL;
precond_par->L.val = NULL;
precond_par->L.col = NULL;
precond_par->L.row = NULL;
precond_par->L.blockinfo = NULL;
precond_par->U.val = NULL;
precond_par->U.col = NULL;
precond_par->U.row = NULL;
precond_par->U.blockinfo = NULL;
precond_par->LD.val = NULL;
precond_par->LD.col = NULL;
precond_par->LD.row = NULL;
precond_par->LD.blockinfo = NULL;
precond_par->UD.val = NULL;
precond_par->UD.col = NULL;
precond_par->UD.row = NULL;
precond_par->UD.blockinfo = NULL;
precond_par->cuinfoL = NULL;
precond_par->cuinfoU = NULL;
cleanup:
if( info != 0 ){
magma_free( solver_par->timing );
magma_free( solver_par->res_vec );
}
return info;
}
/**
Purpose
-------
Initializes space for eigensolvers.
Arguments
---------
@param[in,out]
solver_par magma_c_solver_par*
structure containing all solver information
@param[in]
queue magma_queue_t
Queue to execute in.
@ingroup magmasparse_caux
********************************************************************/
extern "C" magma_int_t
magma_ceigensolverinfo_init(
magma_c_solver_par *solver_par,
magma_queue_t queue )
{
magma_int_t info = 0;
magmaFloatComplex *initial_guess=NULL;
solver_par->eigenvectors = NULL;
solver_par->eigenvalues = NULL;
if ( solver_par->solver == Magma_LOBPCG ) {
CHECK( magma_smalloc_cpu( &solver_par->eigenvalues ,
3*solver_par->num_eigenvalues ));
// setup initial guess EV using lapack
// then copy to GPU
magma_int_t ev = solver_par->num_eigenvalues * solver_par->ev_length;
CHECK( magma_cmalloc_cpu( &initial_guess, ev ));
CHECK( magma_cmalloc( &solver_par->eigenvectors, ev ));
magma_int_t ISEED[4] = {0,0,0,1}, ione = 1;
lapackf77_clarnv( &ione, ISEED, &ev, initial_guess );
magma_csetmatrix( solver_par->ev_length, solver_par->num_eigenvalues,
initial_guess, solver_par->ev_length, solver_par->eigenvectors,
solver_par->ev_length );
} else {
solver_par->eigenvectors = NULL;
solver_par->eigenvalues = NULL;
}
cleanup:
if( info != 0 ){
magma_free( solver_par->eigenvectors );
magma_free( solver_par->eigenvalues );
}
magma_free_cpu( initial_guess );
return info;
}
| kjbartel/magma | sparse-iter/control/magma_csolverinfo.cpp | C++ | bsd-3-clause | 24,120 |
#------------------------------------------------------------------------------
# Copyright (c) 2013 The University of Manchester, UK.
#
# BSD Licenced. See LICENCE.rdoc for details.
#
# Taverna Player was developed in the BioVeL project, funded by the European
# Commission 7th Framework Programme (FP7), through grant agreement
# number 283359.
#
# Author: Robert Haines
#------------------------------------------------------------------------------
module TavernaPlayer
module Concerns
module Callback
extend ActiveSupport::Concern
def callback(cb, *params)
if cb.is_a? Proc
cb.call(*params)
else
method(cb).call(*params)
end
end
end
end
end
| myGrid/taverna-player | lib/taverna_player/concerns/callback.rb | Ruby | bsd-3-clause | 724 |
""" Documentation package """
import neuroptikon
import wx, wx.html
import os.path, sys, urllib
_sharedFrame = None
def baseURL():
if neuroptikon.runningFromSource:
basePath = os.path.join(neuroptikon.rootDir, 'documentation', 'build', 'Documentation')
else:
basePath = os.path.join(neuroptikon.rootDir, 'documentation')
return 'file:' + urllib.pathname2url(basePath) + '/'
def showPage(page):
pageURL = baseURL() + page
# Try to open an embedded WebKit-based help browser.
try:
import documentation_frame
documentation_frame.showPage(pageURL)
except:
# Fall back to using the user's default browser outside of Neuroptikon.
wx.LaunchDefaultBrowser(pageURL)
| JaneliaSciComp/Neuroptikon | Source/documentation/__init__.py | Python | bsd-3-clause | 747 |
#ifndef __PY_CHOOSE__
#define __PY_CHOOSE__
//---------------------------------------------------------------------------
//<inline(py_choose)>
//---------------------------------------------------------------------------
uint32 idaapi choose_sizer(void *self)
{
PYW_GIL_GET;
newref_t pyres(PyObject_CallMethod((PyObject *)self, "sizer", ""));
return PyInt_AsLong(pyres.o);
}
//---------------------------------------------------------------------------
char *idaapi choose_getl(void *self, uint32 n, char *buf)
{
PYW_GIL_GET;
newref_t pyres(
PyObject_CallMethod(
(PyObject *)self,
"getl",
"l",
n));
const char *res;
if ( pyres == NULL || (res = PyString_AsString(pyres.o)) == NULL )
qstrncpy(buf, "<Empty>", MAXSTR);
else
qstrncpy(buf, res, MAXSTR);
return buf;
}
//---------------------------------------------------------------------------
void idaapi choose_enter(void *self, uint32 n)
{
PYW_GIL_GET;
newref_t res(PyObject_CallMethod((PyObject *)self, "enter", "l", n));
}
//---------------------------------------------------------------------------
uint32 choose_choose(
void *self,
int flags,
int x0,int y0,
int x1,int y1,
int width,
int deflt,
int icon)
{
PYW_GIL_CHECK_LOCKED_SCOPE();
newref_t pytitle(PyObject_GetAttrString((PyObject *)self, "title"));
const char *title = pytitle != NULL ? PyString_AsString(pytitle.o) : "Choose";
int r = choose(
flags,
x0, y0,
x1, y1,
self,
width,
choose_sizer,
choose_getl,
title,
icon,
deflt,
NULL, /* del */
NULL, /* inst */
NULL, /* update */
NULL, /* edit */
choose_enter,
NULL, /* destroy */
NULL, /* popup_names */
NULL);/* get_icon */
return r;
}
//</inline(py_choose)>
#endif // __PY_CHOOSE__
| nihilus/src | pywraps/py_choose.hpp | C++ | bsd-3-clause | 1,878 |
package models
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
strfmt "github.com/go-openapi/strfmt"
"github.com/go-openapi/errors"
"github.com/go-openapi/swag"
"github.com/go-openapi/validate"
manifold "github.com/manifoldco/go-manifold"
)
// OAuthCredentialCreateRequest o auth credential create request
// swagger:model OAuthCredentialCreateRequest
type OAuthCredentialCreateRequest struct {
// A human readable description of this credential pair.
//
// Required: true
// Max Length: 256
// Min Length: 3
Description *string `json:"description"`
// Product identifier to scope the credential to a single product.
//
ProductID *manifold.ID `json:"product_id,omitempty"`
// **ALPHA** Provider identifier to scope the credential to
// all products of a provider.
//
ProviderID *manifold.ID `json:"provider_id,omitempty"`
}
// Validate validates this o auth credential create request
func (m *OAuthCredentialCreateRequest) Validate(formats strfmt.Registry) error {
var res []error
if err := m.validateDescription(formats); err != nil {
// prop
res = append(res, err)
}
if err := m.validateProductID(formats); err != nil {
// prop
res = append(res, err)
}
if err := m.validateProviderID(formats); err != nil {
// prop
res = append(res, err)
}
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}
return nil
}
func (m *OAuthCredentialCreateRequest) validateDescription(formats strfmt.Registry) error {
if err := validate.Required("description", "body", m.Description); err != nil {
return err
}
if err := validate.MinLength("description", "body", string(*m.Description), 3); err != nil {
return err
}
if err := validate.MaxLength("description", "body", string(*m.Description), 256); err != nil {
return err
}
return nil
}
func (m *OAuthCredentialCreateRequest) validateProductID(formats strfmt.Registry) error {
if swag.IsZero(m.ProductID) { // not required
return nil
}
if m.ProductID != nil {
if err := m.ProductID.Validate(formats); err != nil {
if ve, ok := err.(*errors.Validation); ok {
return ve.ValidateName("product_id")
}
return err
}
}
return nil
}
func (m *OAuthCredentialCreateRequest) validateProviderID(formats strfmt.Registry) error {
if swag.IsZero(m.ProviderID) { // not required
return nil
}
if m.ProviderID != nil {
if err := m.ProviderID.Validate(formats); err != nil {
if ve, ok := err.(*errors.Validation); ok {
return ve.ValidateName("provider_id")
}
return err
}
}
return nil
}
| manifoldco/grafton | generated/connector/models/o_auth_credential_create_request.go | GO | bsd-3-clause | 2,640 |
var _ = require('underscore');
module.exports = function () {
beforeEach(function () {
spyOn(_, 'debounce').and.callFake(function (func) { return function () { func.apply(this, arguments); }; });
this.geometryView.render();
});
describe('when the model is removed', function () {
it('should remove each geometry', function () {
this.geometry.geometries.each(function (polygon) {
spyOn(polygon, 'remove');
});
this.geometry.remove();
expect(this.geometry.geometries.all(function (geometry) {
return geometry.remove.calls.count() === 1;
})).toBe(true);
});
it('should remove the view', function () {
spyOn(this.geometryView, 'remove');
this.geometry.remove();
expect(this.geometryView.remove).toHaveBeenCalled();
});
});
};
| splashblot/cartodb.js | test/spec/geo/geometry-views/shared-tests-for-multi-geometry-views.js | JavaScript | bsd-3-clause | 826 |
// Version: $Id$
//
//
// Commentary:
//
//
// Change Log:
//
//
// Code:
#include "dtkPluginGeneratorPage.h"
#include "ui_dtkPluginGeneratorPage.h"
dtkPluginGeneratorPage::dtkPluginGeneratorPage(QWidget *parent) : QWizardPage(parent), ui(new Ui::dtkPluginGeneratorPage)
{
ui->setupUi(this);
registerField("plugin.prefix", ui->m_prefix);
registerField("plugin.suffix", ui->m_suffix);
registerField("plugin.name", ui->m_name);
connect(ui->m_prefix, SIGNAL(textChanged(QString)), this, SLOT(refresh()));
connect(ui->m_suffix, SIGNAL(textChanged(QString)), this, SLOT(refresh()));
}
dtkPluginGeneratorPage::~dtkPluginGeneratorPage(void)
{
delete ui;
}
void dtkPluginGeneratorPage::initializePage(void)
{
ui->m_prefix->setText(field("new.prefix").toString());
ui->m_name->setText(ui->m_prefix->text() + field("new.name").toString());
}
void dtkPluginGeneratorPage::refresh(void)
{
ui->m_name->setText(ui->m_prefix->text() + field("new.name").toString() + ui->m_suffix->text());
}
//
// dtkPluginGeneratorPage.cpp ends here
| d-tk/dtk | app/dtkConceptGenerator/dtkPluginGeneratorPage.cpp | C++ | bsd-3-clause | 1,071 |
<?php
/* @var $this yii\web\View */
?>
<h1>region/view</h1>
<p>
You may change the content of this page by modifying
the file <code><?= __FILE__; ?></code>.
</p>
| romaten1/yii2-vk-mongodb | modules/vk/views/region/view.php | PHP | bsd-3-clause | 171 |
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "net/base/multi_threaded_cert_verifier.h"
#include "base/bind.h"
#include "base/files/file_path.h"
#include "base/format_macros.h"
#include "base/stringprintf.h"
#include "net/base/cert_test_util.h"
#include "net/base/cert_trust_anchor_provider.h"
#include "net/base/cert_verify_proc.h"
#include "net/base/cert_verify_result.h"
#include "net/base/net_errors.h"
#include "net/base/net_log.h"
#include "net/base/test_completion_callback.h"
#include "net/base/test_data_directory.h"
#include "net/base/x509_certificate.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
using testing::Mock;
using testing::ReturnRef;
namespace net {
namespace {
void FailTest(int /* result */) {
FAIL();
}
class MockCertVerifyProc : public CertVerifyProc {
public:
MockCertVerifyProc() {}
private:
virtual ~MockCertVerifyProc() {}
// CertVerifyProc implementation
virtual bool SupportsAdditionalTrustAnchors() const OVERRIDE {
return false;
}
virtual int VerifyInternal(X509Certificate* cert,
const std::string& hostname,
int flags,
CRLSet* crl_set,
const CertificateList& additional_trust_anchors,
CertVerifyResult* verify_result) OVERRIDE {
verify_result->Reset();
verify_result->verified_cert = cert;
verify_result->cert_status = CERT_STATUS_COMMON_NAME_INVALID;
return ERR_CERT_COMMON_NAME_INVALID;
}
};
class MockCertTrustAnchorProvider : public CertTrustAnchorProvider {
public:
MockCertTrustAnchorProvider() {}
virtual ~MockCertTrustAnchorProvider() {}
MOCK_METHOD0(GetAdditionalTrustAnchors, const CertificateList&());
};
} // namespace
class MultiThreadedCertVerifierTest : public ::testing::Test {
public:
MultiThreadedCertVerifierTest() : verifier_(new MockCertVerifyProc()) {}
virtual ~MultiThreadedCertVerifierTest() {}
protected:
MultiThreadedCertVerifier verifier_;
};
TEST_F(MultiThreadedCertVerifierTest, CacheHit) {
base::FilePath certs_dir = GetTestCertsDirectory();
scoped_refptr<X509Certificate> test_cert(
ImportCertFromFile(certs_dir, "ok_cert.pem"));
ASSERT_NE(static_cast<X509Certificate*>(NULL), test_cert);
int error;
CertVerifyResult verify_result;
TestCompletionCallback callback;
CertVerifier::RequestHandle request_handle;
error = verifier_.Verify(test_cert, "www.example.com", 0, NULL,
&verify_result, callback.callback(),
&request_handle, BoundNetLog());
ASSERT_EQ(ERR_IO_PENDING, error);
ASSERT_TRUE(request_handle != NULL);
error = callback.WaitForResult();
ASSERT_TRUE(IsCertificateError(error));
ASSERT_EQ(1u, verifier_.requests());
ASSERT_EQ(0u, verifier_.cache_hits());
ASSERT_EQ(0u, verifier_.inflight_joins());
ASSERT_EQ(1u, verifier_.GetCacheSize());
error = verifier_.Verify(test_cert, "www.example.com", 0, NULL,
&verify_result, callback.callback(),
&request_handle, BoundNetLog());
// Synchronous completion.
ASSERT_NE(ERR_IO_PENDING, error);
ASSERT_TRUE(IsCertificateError(error));
ASSERT_TRUE(request_handle == NULL);
ASSERT_EQ(2u, verifier_.requests());
ASSERT_EQ(1u, verifier_.cache_hits());
ASSERT_EQ(0u, verifier_.inflight_joins());
ASSERT_EQ(1u, verifier_.GetCacheSize());
}
// Tests the same server certificate with different intermediate CA
// certificates. These should be treated as different certificate chains even
// though the two X509Certificate objects contain the same server certificate.
TEST_F(MultiThreadedCertVerifierTest, DifferentCACerts) {
base::FilePath certs_dir = GetTestCertsDirectory();
scoped_refptr<X509Certificate> server_cert =
ImportCertFromFile(certs_dir, "salesforce_com_test.pem");
ASSERT_NE(static_cast<X509Certificate*>(NULL), server_cert);
scoped_refptr<X509Certificate> intermediate_cert1 =
ImportCertFromFile(certs_dir, "verisign_intermediate_ca_2011.pem");
ASSERT_NE(static_cast<X509Certificate*>(NULL), intermediate_cert1);
scoped_refptr<X509Certificate> intermediate_cert2 =
ImportCertFromFile(certs_dir, "verisign_intermediate_ca_2016.pem");
ASSERT_NE(static_cast<X509Certificate*>(NULL), intermediate_cert2);
X509Certificate::OSCertHandles intermediates;
intermediates.push_back(intermediate_cert1->os_cert_handle());
scoped_refptr<X509Certificate> cert_chain1 =
X509Certificate::CreateFromHandle(server_cert->os_cert_handle(),
intermediates);
intermediates.clear();
intermediates.push_back(intermediate_cert2->os_cert_handle());
scoped_refptr<X509Certificate> cert_chain2 =
X509Certificate::CreateFromHandle(server_cert->os_cert_handle(),
intermediates);
int error;
CertVerifyResult verify_result;
TestCompletionCallback callback;
CertVerifier::RequestHandle request_handle;
error = verifier_.Verify(cert_chain1, "www.example.com", 0, NULL,
&verify_result, callback.callback(),
&request_handle, BoundNetLog());
ASSERT_EQ(ERR_IO_PENDING, error);
ASSERT_TRUE(request_handle != NULL);
error = callback.WaitForResult();
ASSERT_TRUE(IsCertificateError(error));
ASSERT_EQ(1u, verifier_.requests());
ASSERT_EQ(0u, verifier_.cache_hits());
ASSERT_EQ(0u, verifier_.inflight_joins());
ASSERT_EQ(1u, verifier_.GetCacheSize());
error = verifier_.Verify(cert_chain2, "www.example.com", 0, NULL,
&verify_result, callback.callback(),
&request_handle, BoundNetLog());
ASSERT_EQ(ERR_IO_PENDING, error);
ASSERT_TRUE(request_handle != NULL);
error = callback.WaitForResult();
ASSERT_TRUE(IsCertificateError(error));
ASSERT_EQ(2u, verifier_.requests());
ASSERT_EQ(0u, verifier_.cache_hits());
ASSERT_EQ(0u, verifier_.inflight_joins());
ASSERT_EQ(2u, verifier_.GetCacheSize());
}
// Tests an inflight join.
TEST_F(MultiThreadedCertVerifierTest, InflightJoin) {
base::FilePath certs_dir = GetTestCertsDirectory();
scoped_refptr<X509Certificate> test_cert(
ImportCertFromFile(certs_dir, "ok_cert.pem"));
ASSERT_NE(static_cast<X509Certificate*>(NULL), test_cert);
int error;
CertVerifyResult verify_result;
TestCompletionCallback callback;
CertVerifier::RequestHandle request_handle;
CertVerifyResult verify_result2;
TestCompletionCallback callback2;
CertVerifier::RequestHandle request_handle2;
error = verifier_.Verify(test_cert, "www.example.com", 0, NULL,
&verify_result, callback.callback(),
&request_handle, BoundNetLog());
ASSERT_EQ(ERR_IO_PENDING, error);
ASSERT_TRUE(request_handle != NULL);
error = verifier_.Verify(
test_cert, "www.example.com", 0, NULL, &verify_result2,
callback2.callback(), &request_handle2, BoundNetLog());
ASSERT_EQ(ERR_IO_PENDING, error);
ASSERT_TRUE(request_handle2 != NULL);
error = callback.WaitForResult();
ASSERT_TRUE(IsCertificateError(error));
error = callback2.WaitForResult();
ASSERT_TRUE(IsCertificateError(error));
ASSERT_EQ(2u, verifier_.requests());
ASSERT_EQ(0u, verifier_.cache_hits());
ASSERT_EQ(1u, verifier_.inflight_joins());
}
// Tests that the callback of a canceled request is never made.
TEST_F(MultiThreadedCertVerifierTest, CancelRequest) {
base::FilePath certs_dir = GetTestCertsDirectory();
scoped_refptr<X509Certificate> test_cert(
ImportCertFromFile(certs_dir, "ok_cert.pem"));
ASSERT_NE(static_cast<X509Certificate*>(NULL), test_cert);
int error;
CertVerifyResult verify_result;
CertVerifier::RequestHandle request_handle;
error = verifier_.Verify(
test_cert, "www.example.com", 0, NULL, &verify_result,
base::Bind(&FailTest), &request_handle, BoundNetLog());
ASSERT_EQ(ERR_IO_PENDING, error);
ASSERT_TRUE(request_handle != NULL);
verifier_.CancelRequest(request_handle);
// Issue a few more requests to the worker pool and wait for their
// completion, so that the task of the canceled request (which runs on a
// worker thread) is likely to complete by the end of this test.
TestCompletionCallback callback;
for (int i = 0; i < 5; ++i) {
error = verifier_.Verify(
test_cert, "www2.example.com", 0, NULL, &verify_result,
callback.callback(), &request_handle, BoundNetLog());
ASSERT_EQ(ERR_IO_PENDING, error);
ASSERT_TRUE(request_handle != NULL);
error = callback.WaitForResult();
verifier_.ClearCache();
}
}
// Tests that a canceled request is not leaked.
TEST_F(MultiThreadedCertVerifierTest, CancelRequestThenQuit) {
base::FilePath certs_dir = GetTestCertsDirectory();
scoped_refptr<X509Certificate> test_cert(
ImportCertFromFile(certs_dir, "ok_cert.pem"));
ASSERT_NE(static_cast<X509Certificate*>(NULL), test_cert);
int error;
CertVerifyResult verify_result;
TestCompletionCallback callback;
CertVerifier::RequestHandle request_handle;
error = verifier_.Verify(test_cert, "www.example.com", 0, NULL,
&verify_result, callback.callback(),
&request_handle, BoundNetLog());
ASSERT_EQ(ERR_IO_PENDING, error);
ASSERT_TRUE(request_handle != NULL);
verifier_.CancelRequest(request_handle);
// Destroy |verifier| by going out of scope.
}
TEST_F(MultiThreadedCertVerifierTest, RequestParamsComparators) {
SHA1HashValue a_key;
memset(a_key.data, 'a', sizeof(a_key.data));
SHA1HashValue z_key;
memset(z_key.data, 'z', sizeof(z_key.data));
const CertificateList empty_list;
CertificateList test_list;
test_list.push_back(
ImportCertFromFile(GetTestCertsDirectory(), "ok_cert.pem"));
struct {
// Keys to test
MultiThreadedCertVerifier::RequestParams key1;
MultiThreadedCertVerifier::RequestParams key2;
// Expectation:
// -1 means key1 is less than key2
// 0 means key1 equals key2
// 1 means key1 is greater than key2
int expected_result;
} tests[] = {
{ // Test for basic equivalence.
MultiThreadedCertVerifier::RequestParams(a_key, a_key, "www.example.test",
0, test_list),
MultiThreadedCertVerifier::RequestParams(a_key, a_key, "www.example.test",
0, test_list),
0,
},
{ // Test that different certificates but with the same CA and for
// the same host are different validation keys.
MultiThreadedCertVerifier::RequestParams(a_key, a_key, "www.example.test",
0, test_list),
MultiThreadedCertVerifier::RequestParams(z_key, a_key, "www.example.test",
0, test_list),
-1,
},
{ // Test that the same EE certificate for the same host, but with
// different chains are different validation keys.
MultiThreadedCertVerifier::RequestParams(a_key, z_key, "www.example.test",
0, test_list),
MultiThreadedCertVerifier::RequestParams(a_key, a_key, "www.example.test",
0, test_list),
1,
},
{ // The same certificate, with the same chain, but for different
// hosts are different validation keys.
MultiThreadedCertVerifier::RequestParams(a_key, a_key,
"www1.example.test", 0,
test_list),
MultiThreadedCertVerifier::RequestParams(a_key, a_key,
"www2.example.test", 0,
test_list),
-1,
},
{ // The same certificate, chain, and host, but with different flags
// are different validation keys.
MultiThreadedCertVerifier::RequestParams(a_key, a_key, "www.example.test",
CertVerifier::VERIFY_EV_CERT,
test_list),
MultiThreadedCertVerifier::RequestParams(a_key, a_key, "www.example.test",
0, test_list),
1,
},
{ // Different additional_trust_anchors.
MultiThreadedCertVerifier::RequestParams(a_key, a_key, "www.example.test",
0, empty_list),
MultiThreadedCertVerifier::RequestParams(a_key, a_key, "www.example.test",
0, test_list),
-1,
},
};
for (size_t i = 0; i < ARRAYSIZE_UNSAFE(tests); ++i) {
SCOPED_TRACE(base::StringPrintf("Test[%" PRIuS "]", i));
const MultiThreadedCertVerifier::RequestParams& key1 = tests[i].key1;
const MultiThreadedCertVerifier::RequestParams& key2 = tests[i].key2;
switch (tests[i].expected_result) {
case -1:
EXPECT_TRUE(key1 < key2);
EXPECT_FALSE(key2 < key1);
break;
case 0:
EXPECT_FALSE(key1 < key2);
EXPECT_FALSE(key2 < key1);
break;
case 1:
EXPECT_FALSE(key1 < key2);
EXPECT_TRUE(key2 < key1);
break;
default:
FAIL() << "Invalid expectation. Can be only -1, 0, 1";
}
}
}
TEST_F(MultiThreadedCertVerifierTest, CertTrustAnchorProvider) {
MockCertTrustAnchorProvider trust_provider;
verifier_.SetCertTrustAnchorProvider(&trust_provider);
scoped_refptr<X509Certificate> test_cert(
ImportCertFromFile(GetTestCertsDirectory(), "ok_cert.pem"));
ASSERT_TRUE(test_cert);
const CertificateList empty_cert_list;
CertificateList cert_list;
cert_list.push_back(test_cert);
// Check that Verify() asks the |trust_provider| for the current list of
// additional trust anchors.
int error;
CertVerifyResult verify_result;
TestCompletionCallback callback;
CertVerifier::RequestHandle request_handle;
EXPECT_CALL(trust_provider, GetAdditionalTrustAnchors())
.WillOnce(ReturnRef(empty_cert_list));
error = verifier_.Verify(test_cert, "www.example.com", 0, NULL,
&verify_result, callback.callback(),
&request_handle, BoundNetLog());
Mock::VerifyAndClearExpectations(&trust_provider);
ASSERT_EQ(ERR_IO_PENDING, error);
ASSERT_TRUE(request_handle);
error = callback.WaitForResult();
EXPECT_EQ(ERR_CERT_COMMON_NAME_INVALID, error);
ASSERT_EQ(1u, verifier_.requests());
ASSERT_EQ(0u, verifier_.cache_hits());
// The next Verify() uses the cached result.
EXPECT_CALL(trust_provider, GetAdditionalTrustAnchors())
.WillOnce(ReturnRef(empty_cert_list));
error = verifier_.Verify(test_cert, "www.example.com", 0, NULL,
&verify_result, callback.callback(),
&request_handle, BoundNetLog());
Mock::VerifyAndClearExpectations(&trust_provider);
EXPECT_EQ(ERR_CERT_COMMON_NAME_INVALID, error);
EXPECT_FALSE(request_handle);
ASSERT_EQ(2u, verifier_.requests());
ASSERT_EQ(1u, verifier_.cache_hits());
// Another Verify() for the same certificate but with a different list of
// trust anchors will not reuse the cache.
EXPECT_CALL(trust_provider, GetAdditionalTrustAnchors())
.WillOnce(ReturnRef(cert_list));
error = verifier_.Verify(test_cert, "www.example.com", 0, NULL,
&verify_result, callback.callback(),
&request_handle, BoundNetLog());
Mock::VerifyAndClearExpectations(&trust_provider);
ASSERT_EQ(ERR_IO_PENDING, error);
ASSERT_TRUE(request_handle != NULL);
error = callback.WaitForResult();
EXPECT_EQ(ERR_CERT_COMMON_NAME_INVALID, error);
ASSERT_EQ(3u, verifier_.requests());
ASSERT_EQ(1u, verifier_.cache_hits());
}
} // namespace net
| timopulkkinen/BubbleFish | net/base/multi_threaded_cert_verifier_unittest.cc | C++ | bsd-3-clause | 16,093 |
/***********************************************************************************************************************
**
** Copyright (c) 2011, 2014 ETH Zurich
** All rights reserved.
**
** Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
** following conditions are met:
**
** * Redistributions of source code must retain the above copyright notice, this list of conditions and the following
** disclaimer.
** * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
** following disclaimer in the documentation and/or other materials provided with the distribution.
** * Neither the name of the ETH Zurich nor the names of its contributors may be used to endorse or promote products
** derived from this software without specific prior written permission.
**
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
** INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
** SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
**
***********************************************************************************************************************/
#include "items/VInteger.h"
#include "ModelBase/src/model/Model.h"
namespace Visualization {
ITEM_COMMON_DEFINITIONS(VInteger, "item")
VInteger::VInteger(Item* parent, NodeType *node, const StyleType *style) :
Super(parent, node, style)
{
TextRenderer::setText( QString::number(node->get()) );
}
bool VInteger::setText(const QString& newText)
{
bool ok = false;
int value = newText.toInt(&ok);
if (ok)
{
node()->model()->beginModification(node(), "Set integer");
node()->set(value);
node()->model()->endModification();
TextRenderer::setText(newText);
return true;
}
else return false;
}
QString VInteger::currentText()
{
return QString::number( node()->get() );
}
}
| patrick-luethi/Envision | VisualizationBase/src/items/VInteger.cpp | C++ | bsd-3-clause | 2,500 |
/**
* Copyright (c) 2011, University of Konstanz, Distributed Systems Group
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the University of Konstanz nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
*
*/
package org.treetank.service.jaxrx.util;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.testng.annotations.Guice;
import org.treetank.testutil.ModuleFactory;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;
/**
* This class gets a stream and builds of it a Document object to perform tests
* for an expected streaming result.
*
* @author Lukas Lewandowski, University of Konstanz
*
*/
@Guice(moduleFactory = ModuleFactory.class)
public final class DOMHelper {
/**
* private contructor.
*/
private DOMHelper() {
// private no instantiation
}
/**
* This method gets an output stream from the streaming output and converts
* it to a Document type to perform test cases.
*
* @param output
* The output stream that has to be packed into the document.
* @return The parsed document.
* @throws ParserConfigurationException
* The error occurred.
* @throws SAXException
* XML parsing exception.
* @throws IOException
* An exception occurred.
*/
public static Document buildDocument(final ByteArrayOutputStream output)
throws ParserConfigurationException, SAXException, IOException {
final DocumentBuilder docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
final ByteArrayInputStream bais = new ByteArrayInputStream(output.toByteArray());
final Document document = docBuilder.parse(bais);
return document;
}
}
| sebastiangraf/treetank | interfacemodules/jax-rx/src/test/java/org/treetank/service/jaxrx/util/DOMHelper.java | Java | bsd-3-clause | 3,354 |
/*================================================================================
Copyright (c) 2009 VMware, Inc. All Rights Reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of VMware, Inc. nor the names of its contributors may be used
to endorse or promote products derived from this software without specific prior
written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL VMWARE, INC. OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
================================================================================*/
package com.vmware.vim25;
/**
@author Steve Jin (sjin@vmware.com)
*/
public class VmConfigInfo extends DynamicData
{
public VAppProductInfo[] product;
public VAppPropertyInfo[] property;
public VAppIPAssignmentInfo ipAssignment;
public String[] eula;
public VAppOvfSectionInfo[] ovfSection;
public String[] ovfEnvironmentTransport;
public boolean installBootRequired;
public int installBootStopDelay;
public VAppProductInfo[] getProduct()
{
return this.product;
}
public VAppPropertyInfo[] getProperty()
{
return this.property;
}
public VAppIPAssignmentInfo getIpAssignment()
{
return this.ipAssignment;
}
public String[] getEula()
{
return this.eula;
}
public VAppOvfSectionInfo[] getOvfSection()
{
return this.ovfSection;
}
public String[] getOvfEnvironmentTransport()
{
return this.ovfEnvironmentTransport;
}
public boolean isInstallBootRequired()
{
return this.installBootRequired;
}
public int getInstallBootStopDelay()
{
return this.installBootStopDelay;
}
public void setProduct(VAppProductInfo[] product)
{
this.product=product;
}
public void setProperty(VAppPropertyInfo[] property)
{
this.property=property;
}
public void setIpAssignment(VAppIPAssignmentInfo ipAssignment)
{
this.ipAssignment=ipAssignment;
}
public void setEula(String[] eula)
{
this.eula=eula;
}
public void setOvfSection(VAppOvfSectionInfo[] ovfSection)
{
this.ovfSection=ovfSection;
}
public void setOvfEnvironmentTransport(String[] ovfEnvironmentTransport)
{
this.ovfEnvironmentTransport=ovfEnvironmentTransport;
}
public void setInstallBootRequired(boolean installBootRequired)
{
this.installBootRequired=installBootRequired;
}
public void setInstallBootStopDelay(int installBootStopDelay)
{
this.installBootStopDelay=installBootStopDelay;
}
} | mikem2005/vijava | src/com/vmware/vim25/VmConfigInfo.java | Java | bsd-3-clause | 3,563 |
from __future__ import unicode_literals
from django.forms import ValidationError
from django.core.exceptions import NON_FIELD_ERRORS
from django.forms.formsets import TOTAL_FORM_COUNT
from django.forms.models import (
BaseModelFormSet, modelformset_factory,
ModelForm, _get_foreign_key, ModelFormMetaclass, ModelFormOptions
)
from django.db.models.fields.related import ForeignObjectRel
from modelcluster.models import get_all_child_relations
class BaseTransientModelFormSet(BaseModelFormSet):
""" A ModelFormSet that doesn't assume that all its initial data instances exist in the db """
def _construct_form(self, i, **kwargs):
# Need to override _construct_form to avoid calling to_python on an empty string PK value
if self.is_bound and i < self.initial_form_count():
pk_key = "%s-%s" % (self.add_prefix(i), self.model._meta.pk.name)
pk = self.data[pk_key]
if pk == '':
kwargs['instance'] = self.model()
else:
pk_field = self.model._meta.pk
to_python = self._get_to_python(pk_field)
pk = to_python(pk)
kwargs['instance'] = self._existing_object(pk)
if i < self.initial_form_count() and 'instance' not in kwargs:
kwargs['instance'] = self.get_queryset()[i]
if i >= self.initial_form_count() and self.initial_extra:
# Set initial values for extra forms
try:
kwargs['initial'] = self.initial_extra[i - self.initial_form_count()]
except IndexError:
pass
# bypass BaseModelFormSet's own _construct_form
return super(BaseModelFormSet, self)._construct_form(i, **kwargs)
def save_existing_objects(self, commit=True):
# Need to override _construct_form so that it doesn't skip over initial forms whose instance
# has a blank PK (which is taken as an indication that the form was constructed with an
# instance not present in our queryset)
self.changed_objects = []
self.deleted_objects = []
if not self.initial_forms:
return []
saved_instances = []
forms_to_delete = self.deleted_forms
for form in self.initial_forms:
obj = form.instance
if form in forms_to_delete:
if obj.pk is None:
# no action to be taken to delete an object which isn't in the database
continue
self.deleted_objects.append(obj)
self.delete_existing(obj, commit=commit)
elif form.has_changed():
self.changed_objects.append((obj, form.changed_data))
saved_instances.append(self.save_existing(form, obj, commit=commit))
if not commit:
self.saved_forms.append(form)
return saved_instances
def transientmodelformset_factory(model, formset=BaseTransientModelFormSet, **kwargs):
return modelformset_factory(model, formset=formset, **kwargs)
class BaseChildFormSet(BaseTransientModelFormSet):
def __init__(self, data=None, files=None, instance=None, queryset=None, **kwargs):
if instance is None:
self.instance = self.fk.remote_field.model()
else:
self.instance = instance
self.rel_name = ForeignObjectRel(self.fk, self.fk.remote_field.model, related_name=self.fk.remote_field.related_name).get_accessor_name()
if queryset is None:
queryset = getattr(self.instance, self.rel_name).all()
super(BaseChildFormSet, self).__init__(data, files, queryset=queryset, **kwargs)
def save(self, commit=True):
# The base ModelFormSet's save(commit=False) will populate the lists
# self.changed_objects, self.deleted_objects and self.new_objects;
# use these to perform the appropriate updates on the relation's manager.
saved_instances = super(BaseChildFormSet, self).save(commit=False)
manager = getattr(self.instance, self.rel_name)
# if model has a sort_order_field defined, assign order indexes to the attribute
# named in it
if self.can_order and hasattr(self.model, 'sort_order_field'):
sort_order_field = getattr(self.model, 'sort_order_field')
for i, form in enumerate(self.ordered_forms):
setattr(form.instance, sort_order_field, i)
# If the manager has existing instances with a blank ID, we have no way of knowing
# whether these correspond to items in the submitted data. We'll assume that they do,
# as that's the most common case (i.e. the formset contains the full set of child objects,
# not just a selection of additions / updates) and so we delete all ID-less objects here
# on the basis that they will be re-added by the formset saving mechanism.
no_id_instances = [obj for obj in manager.all() if obj.pk is None]
if no_id_instances:
manager.remove(*no_id_instances)
manager.add(*saved_instances)
manager.remove(*self.deleted_objects)
self.save_m2m() # ensures any parental-m2m fields are saved.
if commit:
manager.commit()
return saved_instances
def clean(self, *args, **kwargs):
self.validate_unique()
return super(BaseChildFormSet, self).clean(*args, **kwargs)
def validate_unique(self):
'''This clean method will check for unique_together condition'''
# Collect unique_checks and to run from all the forms.
all_unique_checks = set()
all_date_checks = set()
forms_to_delete = self.deleted_forms
valid_forms = [form for form in self.forms if form.is_valid() and form not in forms_to_delete]
for form in valid_forms:
unique_checks, date_checks = form.instance._get_unique_checks()
all_unique_checks.update(unique_checks)
all_date_checks.update(date_checks)
errors = []
# Do each of the unique checks (unique and unique_together)
for uclass, unique_check in all_unique_checks:
seen_data = set()
for form in valid_forms:
# Get the data for the set of fields that must be unique among the forms.
row_data = (
field if field in self.unique_fields else form.cleaned_data[field]
for field in unique_check if field in form.cleaned_data
)
# Reduce Model instances to their primary key values
row_data = tuple(d._get_pk_val() if hasattr(d, '_get_pk_val') else d
for d in row_data)
if row_data and None not in row_data:
# if we've already seen it then we have a uniqueness failure
if row_data in seen_data:
# poke error messages into the right places and mark
# the form as invalid
errors.append(self.get_unique_error_message(unique_check))
form._errors[NON_FIELD_ERRORS] = self.error_class([self.get_form_error()])
# remove the data from the cleaned_data dict since it was invalid
for field in unique_check:
if field in form.cleaned_data:
del form.cleaned_data[field]
# mark the data as seen
seen_data.add(row_data)
if errors:
raise ValidationError(errors)
def childformset_factory(
parent_model, model, form=ModelForm,
formset=BaseChildFormSet, fk_name=None, fields=None, exclude=None,
extra=3, can_order=False, can_delete=True, max_num=None, validate_max=False,
formfield_callback=None, widgets=None, min_num=None, validate_min=False
):
fk = _get_foreign_key(parent_model, model, fk_name=fk_name)
# enforce a max_num=1 when the foreign key to the parent model is unique.
if fk.unique:
max_num = 1
validate_max = True
if exclude is None:
exclude = []
exclude += [fk.name]
kwargs = {
'form': form,
'formfield_callback': formfield_callback,
'formset': formset,
'extra': extra,
'can_delete': can_delete,
# if the model supplies a sort_order_field, enable ordering regardless of
# the current setting of can_order
'can_order': (can_order or hasattr(model, 'sort_order_field')),
'fields': fields,
'exclude': exclude,
'max_num': max_num,
'validate_max': validate_max,
'widgets': widgets,
'min_num': min_num,
'validate_min': validate_min,
}
FormSet = transientmodelformset_factory(model, **kwargs)
FormSet.fk = fk
return FormSet
class ClusterFormOptions(ModelFormOptions):
def __init__(self, options=None):
super(ClusterFormOptions, self).__init__(options=options)
self.formsets = getattr(options, 'formsets', None)
self.exclude_formsets = getattr(options, 'exclude_formsets', None)
class ClusterFormMetaclass(ModelFormMetaclass):
extra_form_count = 3
@classmethod
def child_form(cls):
return ClusterForm
def __new__(cls, name, bases, attrs):
try:
parents = [b for b in bases if issubclass(b, ClusterForm)]
except NameError:
# We are defining ClusterForm itself.
parents = None
# grab any formfield_callback that happens to be defined in attrs -
# so that we can pass it on to child formsets - before ModelFormMetaclass deletes it.
# BAD METACLASS NO BISCUIT.
formfield_callback = attrs.get('formfield_callback')
new_class = super(ClusterFormMetaclass, cls).__new__(cls, name, bases, attrs)
if not parents:
return new_class
# ModelFormMetaclass will have set up new_class._meta as a ModelFormOptions instance;
# replace that with ClusterFormOptions so that we can access _meta.formsets
opts = new_class._meta = ClusterFormOptions(getattr(new_class, 'Meta', None))
if opts.model:
formsets = {}
for rel in get_all_child_relations(opts.model):
# to build a childformset class from this relation, we need to specify:
# - the base model (opts.model)
# - the child model (rel.field.model)
# - the fk_name from the child model to the base (rel.field.name)
rel_name = rel.get_accessor_name()
# apply 'formsets' and 'exclude_formsets' rules from meta
if opts.formsets is not None and rel_name not in opts.formsets:
continue
if opts.exclude_formsets and rel_name in opts.exclude_formsets:
continue
try:
widgets = opts.widgets.get(rel_name)
except AttributeError: # thrown if opts.widgets is None
widgets = None
kwargs = {
'extra': cls.extra_form_count,
'form': cls.child_form(),
'formfield_callback': formfield_callback,
'fk_name': rel.field.name,
'widgets': widgets
}
# see if opts.formsets looks like a dict; if so, allow the value
# to override kwargs
try:
kwargs.update(opts.formsets.get(rel_name))
except AttributeError:
pass
formset = childformset_factory(opts.model, rel.field.model, **kwargs)
formsets[rel_name] = formset
new_class.formsets = formsets
new_class._has_explicit_formsets = (opts.formsets is not None or opts.exclude_formsets is not None)
return new_class
class ClusterForm(ModelForm, metaclass=ClusterFormMetaclass):
def __init__(self, data=None, files=None, instance=None, prefix=None, **kwargs):
super(ClusterForm, self).__init__(data, files, instance=instance, prefix=prefix, **kwargs)
self.formsets = {}
for rel_name, formset_class in self.__class__.formsets.items():
if prefix:
formset_prefix = "%s-%s" % (prefix, rel_name)
else:
formset_prefix = rel_name
self.formsets[rel_name] = formset_class(data, files, instance=instance, prefix=formset_prefix)
if self.is_bound and not self._has_explicit_formsets:
# check which formsets have actually been provided as part of the form submission -
# if no `formsets` or `exclude_formsets` was specified, we allow them to be omitted
# (https://github.com/wagtail/wagtail/issues/5414#issuecomment-567468127).
self._posted_formsets = [
formset
for formset in self.formsets.values()
if '%s-%s' % (formset.prefix, TOTAL_FORM_COUNT) in self.data
]
else:
# expect all defined formsets to be part of the post
self._posted_formsets = self.formsets.values()
def as_p(self):
form_as_p = super(ClusterForm, self).as_p()
return form_as_p + ''.join([formset.as_p() for formset in self.formsets.values()])
def is_valid(self):
form_is_valid = super(ClusterForm, self).is_valid()
formsets_are_valid = all(formset.is_valid() for formset in self._posted_formsets)
return form_is_valid and formsets_are_valid
def is_multipart(self):
return (
super(ClusterForm, self).is_multipart()
or any(formset.is_multipart() for formset in self.formsets.values())
)
@property
def media(self):
media = super(ClusterForm, self).media
for formset in self.formsets.values():
media = media + formset.media
return media
def save(self, commit=True):
# do we have any fields that expect us to call save_m2m immediately?
save_m2m_now = False
exclude = self._meta.exclude
fields = self._meta.fields
for f in self.instance._meta.get_fields():
if fields and f.name not in fields:
continue
if exclude and f.name in exclude:
continue
if getattr(f, '_need_commit_after_assignment', False):
save_m2m_now = True
break
instance = super(ClusterForm, self).save(commit=(commit and not save_m2m_now))
# The M2M-like fields designed for use with ClusterForm (currently
# ParentalManyToManyField and ClusterTaggableManager) will manage their own in-memory
# relations, and not immediately write to the database when we assign to them.
# For these fields (identified by the _need_commit_after_assignment
# flag), save_m2m() is a safe operation that does not affect the database and is thus
# valid for commit=False. In the commit=True case, committing to the database happens
# in the subsequent instance.save (so this needs to happen after save_m2m to ensure
# we have the updated relation data in place).
# For annoying legacy reasons we sometimes need to accommodate 'classic' M2M fields
# (particularly taggit.TaggableManager) within ClusterForm. These fields
# generally do require our instance to exist in the database at the point we call
# save_m2m() - for this reason, we only proceed with the customisation described above
# (i.e. postpone the instance.save() operation until after save_m2m) if there's a
# _need_commit_after_assignment field on the form that demands it.
if save_m2m_now:
self.save_m2m()
if commit:
instance.save()
for formset in self._posted_formsets:
formset.instance = instance
formset.save(commit=commit)
return instance
def has_changed(self):
"""Return True if data differs from initial."""
# Need to recurse over nested formsets so that the form is saved if there are changes
# to child forms but not the parent
if self.formsets:
for formset in self._posted_formsets:
for form in formset.forms:
if form.has_changed():
return True
return bool(self.changed_data)
| torchbox/django-modelcluster | modelcluster/forms.py | Python | bsd-3-clause | 16,632 |
/*
* Copyright (c) 2015 Kendanware
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. Neither the name of onegui, Kendanware nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.kendanware.onegui.core;
import java.util.List;
/**
* Contains various validation methods.
*
* @author Daniel Johansson, Kendanware
* @author Kenny Colliander Nordin, Kendanware
*
* @since 0.0.1
*/
public class Validation {
/**
* Check that the id is unique. Scan the tree of components for the id
*
* @param id
* the id to check
* @throws IllegalArgumentException
* if the id is invalid
*/
public static void checkId(final Component component, final String id) {
if ((id == null) || id.trim().isEmpty()) {
throw new IllegalArgumentException("Invalid id: " + id);
}
if (component == null) {
return;
}
Component parent = component;
while (parent.getParent() != null) {
parent = parent.getParent();
}
Validation.checkIdTraverse(parent, id);
}
protected static void checkIdTraverse(final Component component, final String id) {
if (id.equals(component.getId())) {
throw new IllegalArgumentException("Invalid id; already in use: " + id);
}
if (component instanceof Container) {
final Container container = (Container) component;
final List<Component> list = container.getChildren();
for (final Component child : list) {
Validation.checkIdTraverse(child, id);
}
}
}
}
| Kendanware/onegui | onegui-core/src/main/java/com/kendanware/onegui/core/Validation.java | Java | bsd-3-clause | 3,116 |
"""
See http://pbpython.com/advanced-excel-workbooks.html for details on this script
"""
from __future__ import print_function
import pandas as pd
from xlsxwriter.utility import xl_rowcol_to_cell
def format_excel(writer, df_size):
""" Add Excel specific formatting to the workbook
df_size is a tuple representing the size of the dataframe - typically called
by df.shape -> (20,3)
"""
# Get the workbook and the summary sheet so we can add the formatting
workbook = writer.book
worksheet = writer.sheets['summary']
# Add currency formatting and apply it
money_fmt = workbook.add_format({'num_format': 42, 'align': 'center'})
worksheet.set_column('A:A', 20)
worksheet.set_column('B:C', 15, money_fmt)
# Add 1 to row so we can include a total
# subtract 1 from the column to handle because we don't care about index
table_end = xl_rowcol_to_cell(df_size[0] + 1, df_size[1] - 1)
# This assumes we start in the left hand corner
table_range = 'A1:{}'.format(table_end)
worksheet.add_table(table_range, {'columns': [{'header': 'account',
'total_string': 'Total'},
{'header': 'Total Sales',
'total_function': 'sum'},
{'header': 'Average Sales',
'total_function': 'average'}],
'autofilter': False,
'total_row': True,
'style': 'Table Style Medium 20'})
if __name__ == "__main__":
sales_df = pd.read_excel('https://github.com/chris1610/pbpython/blob/master/data/sample-salesv3.xlsx?raw=true')
sales_summary = sales_df.groupby(['name'])['ext price'].agg(['sum', 'mean'])
# Reset the index for consistency when saving in Excel
sales_summary.reset_index(inplace=True)
writer = pd.ExcelWriter('sales_summary.xlsx', engine='xlsxwriter')
sales_summary.to_excel(writer, 'summary', index=False)
format_excel(writer, sales_summary.shape)
writer.save()
| chris1610/pbpython | code/advanced_excel.py | Python | bsd-3-clause | 2,204 |
// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "third_party/blink/public/platform/modules/mediastream/web_media_stream_audio_sink.h"
#include "base/check.h"
#include "third_party/blink/public/platform/web_media_stream_source.h"
#include "third_party/blink/public/platform/web_media_stream_track.h"
#include "third_party/blink/renderer/platform/mediastream/media_stream_audio_track.h"
namespace blink {
void WebMediaStreamAudioSink::AddToAudioTrack(
WebMediaStreamAudioSink* sink,
const blink::WebMediaStreamTrack& track) {
DCHECK(track.Source().GetType() == blink::WebMediaStreamSource::kTypeAudio);
MediaStreamAudioTrack* native_track = MediaStreamAudioTrack::From(track);
DCHECK(native_track);
native_track->AddSink(sink);
}
void WebMediaStreamAudioSink::RemoveFromAudioTrack(
WebMediaStreamAudioSink* sink,
const blink::WebMediaStreamTrack& track) {
MediaStreamAudioTrack* native_track = MediaStreamAudioTrack::From(track);
DCHECK(native_track);
native_track->RemoveSink(sink);
}
media::AudioParameters WebMediaStreamAudioSink::GetFormatFromAudioTrack(
const blink::WebMediaStreamTrack& track) {
MediaStreamAudioTrack* native_track = MediaStreamAudioTrack::From(track);
DCHECK(native_track);
return native_track->GetOutputFormat();
}
} // namespace blink
| endlessm/chromium-browser | third_party/blink/renderer/platform/exported/web_media_stream_audio_sink.cc | C++ | bsd-3-clause | 1,433 |
package edu.northwestern.bioinformatics.studycalendar.web.accesscontrol;
import org.springframework.validation.Errors;
import java.util.Collection;
/**
* @author Rhett Sutphin
*/
public interface PscAuthorizedCommand {
/**
* Return the set of authorizations describing a user which could have
* access to the action described by this command.
* <p>
* The command is not guaranteed to be in a consistent state when this
* method is called -- if there are binding problems, there could be
* missing field values. This method should provide a best-effort
* set of authorizations in that case.
*
* @see PscAuthorizedHandler
* @param bindErrors
*/
Collection<ResourceAuthorization> authorizations(Errors bindErrors);
}
| NUBIC/psc-mirror | web/src/main/java/edu/northwestern/bioinformatics/studycalendar/web/accesscontrol/PscAuthorizedCommand.java | Java | bsd-3-clause | 783 |
/*
* image_math.cpp
* PHD Guiding
*
* Created by Craig Stark.
* Copyright (c) 2006-2010 Craig Stark.
* All rights reserved.
*
* This source code is distributed under the following "BSD" license
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* Neither the name of Craig Stark, Stark Labs nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
#include "phd.h"
#include "image_math.h"
#include <wx/wfstream.h>
#include <wx/txtstrm.h>
#include <wx/tokenzr.h>
#include <algorithm>
int dbl_sort_func (double *first, double *second)
{
if (*first < *second)
return -1;
else if (*first > *second)
return 1;
return 0;
}
double CalcSlope(const ArrayOfDbl& y)
{
// Does a linear regression to calculate the slope
int nn = (int) y.GetCount();
if (nn < 2)
return 0.;
double s_xy = 0.0;
double s_y = 0.0;
for (int x = 0; x < nn; x++)
{
s_xy += (double)(x + 1) * y[x];
s_y += y[x];
}
int sx = (nn * (nn + 1)) / 2;
int sxx = sx * (2 * nn + 1) / 3;
double s_x = (double) sx;
double s_xx = (double) sxx;
double n = (double) nn;
return (n * s_xy - (s_x * s_y)) / (n * s_xx - (s_x * s_x));
}
bool QuickLRecon(usImage& img)
{
// Does a simple debayer of luminance data only -- sliding 2x2 window
usImage tmp;
if (tmp.Init(img.Size))
{
pFrame->Alert(_("Memory allocation error"));
return true;
}
int const W = img.Size.GetWidth();
int RX, RY, RW, RH;
if (img.Subframe.IsEmpty())
{
RX = RY = 0;
RW = img.Size.GetWidth();
RH = img.Size.GetHeight();
}
else
{
RX = img.Subframe.GetX();
RY = img.Subframe.GetY();
RW = img.Subframe.GetWidth();
RH = img.Subframe.GetHeight();
tmp.Clear();
}
#define IX(x_, y_) ((RY + (y_)) * W + RX + (x_))
unsigned short *d;
unsigned int t;
for (int y = 0; y <= RH - 2; y++)
{
d = &tmp.ImageData[IX(0, y)];
for (int x = 0; x <= RW - 2; x++)
{
t = img.ImageData[IX(x , y )];
t += img.ImageData[IX(x + 1, y )];
t += img.ImageData[IX(x , y + 1)];
t += img.ImageData[IX(x + 1, y + 1)];
*d++ = (unsigned short)(t >> 2);
}
// last col
t = img.ImageData[IX(RW - 1, y )];
t += img.ImageData[IX(RW - 1, y + 1)];
*d = (unsigned short)(t >> 1);
}
// last row
d = &tmp.ImageData[IX(0, RH - 1)];
for (int x = 0; x <= RW - 2; x++)
{
t = img.ImageData[IX(x , RH - 1)];
t += img.ImageData[IX(x + 1, RH - 1)];
*d++ = (unsigned short)(t >> 1);
}
// bottom-right pixel
*d = img.ImageData[IX(RW - 1, RH - 1)];
#undef IX
img.SwapImageData(tmp);
return false;
}
bool Median3(usImage& img)
{
usImage tmp;
tmp.Init(img.Size);
bool err;
if (img.Subframe.IsEmpty())
{
err = Median3(tmp.ImageData, img.ImageData, img.Size, wxRect(img.Size));
}
else
{
tmp.Clear();
err = Median3(tmp.ImageData, img.ImageData, img.Size, img.Subframe);
}
img.SwapImageData(tmp);
return err;
}
inline static void swap(unsigned short& a, unsigned short& b)
{
unsigned short const t = a;
a = b;
b = t;
}
inline static unsigned short median9(const unsigned short l[9])
{
unsigned short l0 = l[0], l1 = l[1], l2 = l[2], l3 = l[3], l4 = l[4];
unsigned short x;
x = l[5];
if (x < l0) swap(x, l0);
if (x < l1) swap(x, l1);
if (x < l2) swap(x, l2);
if (x < l3) swap(x, l3);
if (x < l4) swap(x, l4);
x = l[6];
if (x < l0) swap(x, l0);
if (x < l1) swap(x, l1);
if (x < l2) swap(x, l2);
if (x < l3) swap(x, l3);
if (x < l4) swap(x, l4);
x = l[7];
if (x < l0) swap(x, l0);
if (x < l1) swap(x, l1);
if (x < l2) swap(x, l2);
if (x < l3) swap(x, l3);
if (x < l4) swap(x, l4);
x = l[8];
if (x < l0) swap(x, l0);
if (x < l1) swap(x, l1);
if (x < l2) swap(x, l2);
if (x < l3) swap(x, l3);
if (x < l4) swap(x, l4);
if (l1 > l0) l0 = l1;
if (l2 > l0) l0 = l2;
if (l3 > l0) l0 = l3;
if (l4 > l0) l0 = l4;
return l0;
}
inline static unsigned short median8(const unsigned short l[8])
{
unsigned short l0 = l[0], l1 = l[1], l2 = l[2], l3 = l[3], l4 = l[4];
unsigned short x;
x = l[5];
if (x < l0) swap(x, l0);
if (x < l1) swap(x, l1);
if (x < l2) swap(x, l2);
if (x < l3) swap(x, l3);
if (x < l4) swap(x, l4);
x = l[6];
if (x < l0) swap(x, l0);
if (x < l1) swap(x, l1);
if (x < l2) swap(x, l2);
if (x < l3) swap(x, l3);
if (x < l4) swap(x, l4);
x = l[7];
if (x < l0) swap(x, l0);
if (x < l1) swap(x, l1);
if (x < l2) swap(x, l2);
if (x < l3) swap(x, l3);
if (x < l4) swap(x, l4);
if (l2 > l0) swap(l2, l0);
if (l2 > l1) swap(l2, l1);
if (l3 > l0) swap(l3, l0);
if (l3 > l1) swap(l3, l1);
if (l4 > l0) swap(l4, l0);
if (l4 > l1) swap(l4, l1);
return (unsigned short)(((unsigned int) l0 + (unsigned int) l1) / 2);
}
inline static unsigned short median6(const unsigned short l[6])
{
unsigned short l0 = l[0], l1 = l[1], l2 = l[2], l3 = l[3];
unsigned short x;
x = l[4];
if (x < l0) swap(x, l0);
if (x < l1) swap(x, l1);
if (x < l2) swap(x, l2);
if (x < l3) swap(x, l3);
x = l[5];
if (x < l0) swap(x, l0);
if (x < l1) swap(x, l1);
if (x < l2) swap(x, l2);
if (x < l3) swap(x, l3);
if (l2 > l0) swap(l2, l0);
if (l2 > l1) swap(l2, l1);
if (l3 > l0) swap(l3, l0);
if (l3 > l1) swap(l3, l1);
return (unsigned short)(((unsigned int) l0 + (unsigned int) l1) / 2);
}
inline static unsigned short median5(const unsigned short l[5])
{
unsigned short l0 = l[0], l1 = l[1], l2 = l[2];
unsigned short x;
x = l[3];
if (x < l0) swap(x, l0);
if (x < l1) swap(x, l1);
if (x < l2) swap(x, l2);
x = l[4];
if (x < l0) swap(x, l0);
if (x < l1) swap(x, l1);
if (x < l2) swap(x, l2);
if (l1 > l0) l0 = l1;
if (l2 > l0) l0 = l2;
return l0;
}
inline static unsigned short median4(const unsigned short l[4])
{
unsigned short l0 = l[0], l1 = l[1], l2 = l[2];
unsigned short x;
x = l[3];
if (x < l0) swap(x, l0);
if (x < l1) swap(x, l1);
if (x < l2) swap(x, l2);
if (l2 > l0) swap(l2, l0);
if (l2 > l1) swap(l2, l1);
return (unsigned short)(((unsigned int) l0 + (unsigned int) l1) / 2);
}
inline static unsigned short median3(const unsigned short l[3])
{
unsigned short l0 = l[0], l1 = l[1], l2 = l[2];
if (l2 < l0) swap(l2, l0);
if (l2 < l1) swap(l2, l1);
if (l1 > l0) l0 = l1;
return l0;
}
bool Median3(unsigned short *dst, const unsigned short *src, const wxSize& size, const wxRect& rect)
{
int const W = size.GetWidth();
int const RX = rect.GetX();
int const RY = rect.GetY();
int const RW = rect.GetWidth();
int const RH = rect.GetHeight();
unsigned short a[9];
unsigned short *d;
#define IX(x_, y_) ((RY + (y_)) * W + RX + (x_))
// top row
d = &dst[IX(0, 0)];
// top-left corner
a[0] = src[IX(0, 0)];
a[1] = src[IX(1, 0)];
a[2] = src[IX(0, 1)];
a[3] = src[IX(1, 1)];
*d++ = median4(a);
// top row middle pixels
for (int x = 1; x <= RW - 2; x++)
{
a[0] = src[IX(x - 1, 0)];
a[1] = src[IX(x, 0)];
a[2] = src[IX(x + 1, 0)];
a[3] = src[IX(x - 1, 1)];
a[4] = src[IX(x, 1)];
a[5] = src[IX(x + 1, 1)];
*d++ = median6(a);
}
// top-right corner
a[0] = src[IX(RW - 2, 0)];
a[1] = src[IX(RW - 1, 0)];
a[2] = src[IX(RW - 2, 1)];
a[3] = src[IX(RW - 1, 1)];
*d = median4(a);
for (int y = 1; y <= RH - 2; y++)
{
d = &dst[IX(0, y)];
// leftmost pixel
a[0] = src[IX(0, y - 1)];
a[1] = src[IX(1, y - 1)];
a[2] = src[IX(0, y )];
a[3] = src[IX(1, y )];
a[4] = src[IX(0, y + 1)];
a[5] = src[IX(1, y + 1)];
*d++ = median6(a);
for (int x = 1; x <= RW - 2; x++)
{
a[0] = src[IX(x - 1, y - 1)];
a[1] = src[IX(x , y - 1)];
a[2] = src[IX(x + 1, y - 1)];
a[3] = src[IX(x - 1, y )];
a[4] = src[IX(x , y )];
a[5] = src[IX(x + 1, y )];
a[6] = src[IX(x - 1, y + 1)];
a[7] = src[IX(x , y + 1)];
a[8] = src[IX(x + 1, y + 1)];
*d++ = median9(a);
}
// rightmost pixel
a[0] = src[IX(RW - 2, y - 1)];
a[1] = src[IX(RW - 1, y - 1)];
a[2] = src[IX(RW - 2, y )];
a[3] = src[IX(RW - 1, y )];
a[4] = src[IX(RW - 2, y + 1)];
a[5] = src[IX(RW - 1, y + 1)];
*d++ = median6(a);
}
// bottom row
d = &dst[IX(0, RH - 1)];
// bottom-left corner
a[0] = src[IX(0, RH - 2)];
a[1] = src[IX(1, RH - 2)];
a[2] = src[IX(0, RH - 1)];
a[3] = src[IX(1, RH - 1)];
*d++ = median4(a);
// bottom row middle pixels
for (int x = 1; x <= RW - 2; x++)
{
a[0] = src[IX(x - 1, RH - 2)];
a[1] = src[IX(x , RH - 2)];
a[2] = src[IX(x + 1, RH - 2)];
a[3] = src[IX(x - 1, RH - 1)];
a[4] = src[IX(x , RH - 1)];
a[5] = src[IX(x + 1, RH - 1)];
*d++ = median6(a);
}
// bottom-right corner
a[0] = src[IX(RW - 2, RH - 2)];
a[1] = src[IX(RW - 1, RH - 2)];
a[2] = src[IX(RW - 2, RH - 1)];
a[3] = src[IX(RW - 1, RH - 1)];
*d = median4(a);
#undef IX
return false;
}
static unsigned short MedianBorderingPixels(const usImage& img, int x, int y)
{
unsigned short array[8];
int const xsize = img.Size.GetWidth();
int const ysize = img.Size.GetHeight();
if (x > 0 && y > 0 && x < xsize - 1 && y < ysize - 1)
{
array[0] = img.ImageData[(x-1) + (y-1) * xsize];
array[1] = img.ImageData[(x) + (y-1) * xsize];
array[2] = img.ImageData[(x+1) + (y-1) * xsize];
array[3] = img.ImageData[(x-1) + (y) * xsize];
array[4] = img.ImageData[(x+1) + (y) * xsize];
array[5] = img.ImageData[(x-1) + (y+1) * xsize];
array[6] = img.ImageData[(x) + (y+1) * xsize];
array[7] = img.ImageData[(x+1) + (y+1) * xsize];
return median8(array);
}
if (x == 0 && y > 0 && y < ysize - 1)
{
// On left edge
array[0] = img.ImageData[(x) + (y - 1) * xsize];
array[1] = img.ImageData[(x) + (y + 1) * xsize];
array[2] = img.ImageData[(x + 1) + (y - 1) * xsize];
array[3] = img.ImageData[(x + 1) + (y) * xsize];
array[4] = img.ImageData[(x + 1) + (y + 1) * xsize];
return median5(array);
}
if (x == xsize - 1 && y > 0 && y < ysize - 1)
{
// On right edge
array[0] = img.ImageData[(x) + (y - 1) * xsize];
array[1] = img.ImageData[(x) + (y + 1) * xsize];
array[2] = img.ImageData[(x - 1) + (y - 1) * xsize];
array[3] = img.ImageData[(x - 1) + (y) * xsize];
array[4] = img.ImageData[(x - 1) + (y + 1) * xsize];
return median5(array);
}
if (y == 0 && x > 0 && x < xsize - 1)
{
// On bottom edge
array[0] = img.ImageData[(x - 1) + (y) * xsize];
array[1] = img.ImageData[(x - 1) + (y + 1) * xsize];
array[2] = img.ImageData[(x) + (y + 1) * xsize];
array[3] = img.ImageData[(x + 1) + (y) * xsize];
array[4] = img.ImageData[(x + 1) + (y + 1) * xsize];
return median5(array);
}
if (y == ysize - 1 && x > 0 && x < xsize - 1)
{
// On top edge
array[0] = img.ImageData[(x - 1) + (y) * xsize];
array[1] = img.ImageData[(x - 1) + (y - 1) * xsize];
array[2] = img.ImageData[(x) + (y - 1) * xsize];
array[3] = img.ImageData[(x + 1) + (y) * xsize];
array[4] = img.ImageData[(x + 1) + (y - 1) * xsize];
return median5(array);
}
if (x == 0 && y == 0)
{
// At lower left corner
array[0] = img.ImageData[(x + 1) + (y) * xsize];
array[1] = img.ImageData[(x) + (y + 1) * xsize];
array[2] = img.ImageData[(x + 1) + (y + 1) * xsize];
}
else if (x == 0 && y == ysize - 1)
{
// At upper left corner
array[0] = img.ImageData[(x + 1) + (y) * xsize];
array[1] = img.ImageData[(x) + (y - 1) * xsize];
array[2] = img.ImageData[(x + 1) + (y - 1) * xsize];
}
else if (x == xsize - 1 && y == ysize - 1)
{
// At upper right corner
array[0] = img.ImageData[(x - 1) + (y) * xsize];
array[1] = img.ImageData[(x) + (y - 1) * xsize];
array[2] = img.ImageData[(x - 1) + (y - 1) * xsize];
}
else if (x == xsize - 1 && y == 0)
{
// At lower right corner
array[0] = img.ImageData[(x - 1) + (y) * xsize];
array[1] = img.ImageData[(x) + (y + 1) * xsize];
array[2] = img.ImageData[(x - 1) + (y + 1) * xsize];
}
else
{
// unreachable
return 0;
}
return median3(array);
}
bool SquarePixels(usImage& img, float xsize, float ysize)
{
// Stretches one dimension to square up pixels
if (!img.ImageData)
return true;
if (xsize <= ysize)
return false;
// Move the existing data to a temp image
usImage tempimg;
if (tempimg.Init(img.Size))
{
pFrame->Alert(_("Memory allocation error"));
return true;
}
tempimg.SwapImageData(img);
// if X > Y, when viewing stock, Y is unnaturally stretched, so stretch X to match
double ratio = ysize / xsize;
int newsize = ROUND((float) tempimg.Size.GetWidth() * (1.0/ratio)); // make new image correct size
img.Init(newsize,tempimg.Size.GetHeight());
unsigned short *optr = img.ImageData;
int linesize = tempimg.Size.GetWidth(); // size of an original line
for (int y = 0; y < img.Size.GetHeight(); y++)
{
for (int x = 0; x < newsize; x++, optr++)
{
double oldposition = x * ratio;
int ind1 = (unsigned int) floor(oldposition);
int ind2 = (unsigned int) ceil(oldposition);
if (ind2 > (tempimg.Size.GetWidth() - 1))
ind2 = tempimg.Size.GetWidth() - 1;
double weight = ceil(oldposition) - oldposition;
*optr = (unsigned short) (((float) *(tempimg.ImageData + y*linesize + ind1) * weight) + ((float) *(tempimg.ImageData + y*linesize + ind1) * (1.0 - weight)));
}
}
return false;
}
bool Subtract(usImage& light, const usImage& dark)
{
if (!light.ImageData || !dark.ImageData)
return true;
if (light.Size != dark.Size)
return true;
unsigned int left, top, width, height;
if (!light.Subframe.IsEmpty())
{
left = light.Subframe.GetLeft();
width = light.Subframe.GetWidth();
top = light.Subframe.GetTop();
height = light.Subframe.GetHeight();
}
else
{
left = top = 0;
width = light.Size.GetWidth();
height = light.Size.GetHeight();
}
int mindiff = 65535;
unsigned short *pl0 = &light.Pixel(left, top);
const unsigned short *pd0 = &dark.Pixel(left, top);
for (unsigned int r = 0; r < height;
r++, pl0 += light.Size.GetWidth(), pd0 += light.Size.GetWidth())
{
unsigned short *const endl = pl0 + width;
unsigned short *pl;
const unsigned short *pd;
for (pl = pl0, pd = pd0; pl < endl; pl++, pd++)
{
int diff = (int) *pl - (int) *pd;
if (diff < mindiff)
mindiff = diff;
}
}
int offset = 0;
if (mindiff < 0) // dark was lighter than light
offset = -mindiff;
pl0 = &light.Pixel(left, top);
pd0 = &dark.Pixel(left, top);
for (unsigned int r = 0; r < height;
r++, pl0 += light.Size.GetWidth(), pd0 += light.Size.GetWidth())
{
unsigned short *const endl = pl0 + width;
unsigned short *pl;
const unsigned short *pd;
for (pl = pl0, pd = pd0; pl < endl; pl++, pd++)
{
int newval = (int) *pl - (int) *pd + offset;
if (newval < 0) newval = 0; // shouldn't hit this...
else if (newval > 65535) newval = 65535;
*pl = (unsigned short) newval;
}
}
return false;
}
inline static unsigned short histo_median(unsigned short histo1[256], unsigned short histo2[65536], int n)
{
n /= 2;
unsigned int i;
for (i = 0; i < 256; i++)
{
if (histo1[i] > n)
break;
n -= histo1[i];
}
for (i <<= 8; i < 65536; i++)
{
if (histo2[i] > n)
break;
n -= histo2[i];
}
return i;
}
static void MedianFilter(usImage& dst, const usImage& src, int halfWidth)
{
dst.Init(src.Size);
unsigned short *d = &dst.ImageData[0];
int const width = src.Size.GetWidth();
int const height = src.Size.GetHeight();
for (int y = 0; y < height; y++)
{
int top = std::max(0, y - halfWidth);
int bot = std::min(y + halfWidth, height - 1);
int left = 0;
int right = halfWidth;
// TODO: we initialize the histogram at the start of each row, but we could make this faster
// if we scan left to right, move down, scan right to left, move down so we never need to
// reinitialize the histogram
// initialize 2-level histogram
unsigned short histo1[256];
unsigned short histo2[65536];
memset(&histo1[0], 0, sizeof(histo1));
memset(&histo2[0], 0, sizeof(histo2));
for (int j = top; j <= bot; j++)
{
const unsigned short *p = &src.Pixel(left, j);
for (int i = left; i <= right; i++, p++)
{
++histo1[*p >> 8];
++histo2[*p];
}
}
unsigned int n = (right - left + 1) * (bot - top + 1);
// read off first value for this row
*d++ = histo_median(histo1, histo2, n);
// loop across remaining columns for this row
for (int i = 1; i < width; i++)
{
left = std::max(0, i - halfWidth);
right = std::min(i + halfWidth, width - 1);
// remove leftmost column
if (left > 0)
{
const unsigned short *p = &src.Pixel(left - 1, top);
for (int j = top; j <= bot; j++, p += width)
{
--histo1[*p >> 8];
--histo2[*p];
}
n -= (bot - top + 1);
}
// add new column on right
if (i + halfWidth <= width - 1)
{
const unsigned short *p = &src.Pixel(right, top);
for (int j = top; j <= bot; j++, p += width)
{
++histo1[*p >> 8];
++histo2[*p];
}
n += (bot - top + 1);
}
*d++ = histo_median(histo1, histo2, n);
}
}
}
struct ImageStatsWork
{
ImageStats stats;
usImage temp;
};
static void GetImageStats(ImageStatsWork& w, const usImage& img, const wxRect& win)
{
w.temp.Init(img.Size);
// Determine the mean and standard deviation
double sum = 0.0;
double a = 0.0;
double q = 0.0;
double k = 1.0;
double km1 = 0.0;
const unsigned short *p0 = &img.Pixel(win.GetLeft(), win.GetTop());
unsigned short *dst = &w.temp.ImageData[0];
for (int y = 0; y < win.GetHeight(); y++)
{
const unsigned short *end = p0 + win.GetWidth();
for (const unsigned short *p = p0; p < end; p++)
{
*dst++ = *p;
double const x = (double) *p;
sum += x;
double const a0 = a;
a += (x - a) / k;
q += (x - a0) * (x - a);
km1 = k;
k += 1.0;
}
p0 += img.Size.GetWidth();
}
w.stats.mean = sum / km1;
w.stats.stdev = sqrt(q / km1);
int winPixels = win.GetWidth() * win.GetHeight();
unsigned short *tmp = &w.temp.ImageData[0];
std::nth_element(tmp, tmp + winPixels / 2, tmp + winPixels);
w.stats.median = tmp[winPixels / 2];
// replace each pixel with the absolute deviation from the median
unsigned short *p = tmp;
for (int i = 0; i < winPixels; i++)
{
unsigned short ad = (unsigned short) std::abs((int) *p - (int) w.stats.median);
*p++ = ad;
}
std::nth_element(tmp, tmp + winPixels / 2, tmp + winPixels);
w.stats.mad = tmp[winPixels / 2];
}
void DefectMapDarks::BuildFilteredDark()
{
enum { WINDOW = 15 };
filteredDark.Init(masterDark.Size);
MedianFilter(filteredDark, masterDark, WINDOW);
}
static wxString DefectMapMasterPath(int profileId)
{
int inst = pFrame->GetInstanceNumber();
return MyFrame::GetDarksDir() + PATHSEPSTR +
wxString::Format("PHD2_defect_map_master%s_%d.fit", inst > 1 ? wxString::Format("_%d", inst) : "", profileId);
}
static wxString DefectMapMasterPath()
{
return DefectMapMasterPath(pConfig->GetCurrentProfileId());
}
static wxString DefectMapFilterPath(int profileId)
{
int inst = pFrame->GetInstanceNumber();
return MyFrame::GetDarksDir() + PATHSEPSTR +
wxString::Format("PHD2_defect_map_master_filt%s_%d.fit", inst > 1 ? wxString::Format("_%d", inst) : "", profileId);
}
static wxString DefectMapFilterPath()
{
return DefectMapFilterPath(pConfig->GetCurrentProfileId());
}
void DefectMapDarks::SaveDarks(const wxString& notes)
{
masterDark.Save(DefectMapMasterPath(), notes);
filteredDark.Save(DefectMapFilterPath());
}
void DefectMapDarks::LoadDarks()
{
masterDark.Load(DefectMapMasterPath());
filteredDark.Load(DefectMapFilterPath());
}
struct BadPx
{
unsigned short x;
unsigned short y;
int v;
BadPx();
BadPx(int x_, int y_, int v_) : x(x_), y(y_), v(v_) { }
bool operator<(const BadPx& rhs) const { return v < rhs.v; }
};
typedef std::set<BadPx> BadPxSet;
struct DefectMapBuilderImpl
{
DefectMapDarks *darks;
ImageStatsWork w;
wxArrayString mapInfo;
int aggrCold;
int aggrHot;
BadPxSet coldPx;
BadPxSet hotPx;
BadPxSet::const_iterator coldPxThresh;
BadPxSet::const_iterator hotPxThresh;
unsigned int coldPxSelected;
unsigned int hotPxSelected;
bool threshValid;
DefectMapBuilderImpl()
:
darks(0),
aggrCold(100),
aggrHot(100),
threshValid(false)
{ }
};
DefectMapBuilder::DefectMapBuilder()
: m_impl(new DefectMapBuilderImpl())
{
}
DefectMapBuilder::~DefectMapBuilder()
{
delete m_impl;
}
inline static double AggrToSigma(int val)
{
// Aggressiveness of 0 to 100 maps to signma factor from 8.0 to 0.125
return exp2(3.0 - (6.0 / 100.0) * (double)val);
}
void DefectMapBuilder::Init(DefectMapDarks& darks)
{
m_impl->darks = &darks;
Debug.AddLine("DefectMapBuilder: Init");
::GetImageStats(m_impl->w, darks.masterDark,
wxRect(0, 0, darks.masterDark.Size.GetWidth(), darks.masterDark.Size.GetHeight()));
const ImageStats& stats = m_impl->w.stats;
Debug.AddLine("DefectMapBuilder: Dark N = %d Mean = %.f Median = %d Standard Deviation = %.f MAD=%d",
darks.masterDark.NPixels, stats.mean, stats.median, stats.stdev, stats.mad);
// load potential defects
int thresh = (int)(AggrToSigma(100) * stats.stdev);
Debug.AddLine("DefectMapBuilder: load potential defects thresh = %d", thresh);
usImage& dark = m_impl->darks->masterDark;
usImage& medianFilt = m_impl->darks->filteredDark;
m_impl->coldPx.clear();
m_impl->hotPx.clear();
for (int y = 0; y < dark.Size.GetHeight(); y++)
{
for (int x = 0; x < dark.Size.GetWidth(); x++)
{
int filt = (int) medianFilt.Pixel(x, y);
int val = (int) dark.Pixel(x, y);
int v = val - filt;
if (v > thresh)
{
m_impl->hotPx.insert(BadPx(x, y, v));
}
else if (-v > thresh)
{
m_impl->coldPx.insert(BadPx(x, y, -v));
}
}
}
Debug.AddLine("DefectMapBuilder: Loaded %d cold %d hot", m_impl->coldPx.size(), m_impl->hotPx.size());
}
const ImageStats& DefectMapBuilder::GetImageStats() const
{
return m_impl->w.stats;
}
void DefectMapBuilder::SetAggressiveness(int aggrCold, int aggrHot)
{
m_impl->aggrCold = std::max(0, std::min(100, aggrCold));
m_impl->aggrHot = std::max(0, std::min(100, aggrHot));
m_impl->threshValid = false;
}
static void FindThresh(DefectMapBuilderImpl *impl)
{
if (impl->threshValid)
return;
double multCold = AggrToSigma(impl->aggrCold);
double multHot = AggrToSigma(impl->aggrHot);
int coldThresh = (int) (multCold * impl->w.stats.stdev);
int hotThresh = (int) (multHot * impl->w.stats.stdev);
Debug.AddLine("DefectMap: find thresholds aggr:(%d,%d) sigma:(%.1f,%.1f) px:(%+d,%+d)",
impl->aggrCold, impl->aggrHot, multCold, multHot, -coldThresh, hotThresh);
impl->coldPxThresh = impl->coldPx.lower_bound(BadPx(0, 0, coldThresh));
impl->hotPxThresh = impl->hotPx.lower_bound(BadPx(0, 0, hotThresh));
impl->coldPxSelected = std::distance(impl->coldPxThresh, impl->coldPx.end());
impl->hotPxSelected = std::distance(impl->hotPxThresh, impl->hotPx.end());
Debug.AddLine("DefectMap: find thresholds found (%d,%d)", impl->coldPxSelected, impl->hotPxSelected);
impl->threshValid = true;
}
int DefectMapBuilder::GetColdPixelCnt() const
{
FindThresh(m_impl);
return m_impl->coldPxSelected;
}
int DefectMapBuilder::GetHotPixelCnt() const
{
FindThresh(m_impl);
return m_impl->hotPxSelected;
}
inline static unsigned int emit_defects(DefectMap& defectMap, BadPxSet::const_iterator p0, BadPxSet::const_iterator p1, double stdev, int sign, bool verbose)
{
unsigned int cnt = 0;
for (BadPxSet::const_iterator it = p0; it != p1; ++it, ++cnt)
{
if (verbose)
{
int v = sign * it->v;
Debug.AddLine("DefectMap: defect @ (%d, %d) val = %d (%+.1f sigma)", it->x, it->y, v, stdev > 0.1 ? (double)v / stdev : 0.0);
}
defectMap.push_back(wxPoint(it->x, it->y));
}
return cnt;
}
void DefectMapBuilder::BuildDefectMap(DefectMap& defectMap, bool verbose) const
{
wxArrayString& info = m_impl->mapInfo;
double multCold = AggrToSigma(m_impl->aggrCold);
double multHot = AggrToSigma(m_impl->aggrHot);
const ImageStats& stats = m_impl->w.stats;
info.Clear();
info.push_back(wxString::Format("Generated: %s", wxDateTime::UNow().FormatISOCombined(' ')));
info.push_back(wxString::Format("Camera: %s", pCamera->Name));
info.push_back(wxString::Format("Dark Exposure Time: %d ms", m_impl->darks->masterDark.ImgExpDur));
info.push_back(wxString::Format("Dark Frame Count: %d", m_impl->darks->masterDark.ImgStackCnt));
info.push_back(wxString::Format("Aggressiveness, cold: %d", m_impl->aggrCold));
info.push_back(wxString::Format("Aggressiveness, hot: %d", m_impl->aggrHot));
info.push_back(wxString::Format("Sigma Thresh, cold: %.2f", multCold));
info.push_back(wxString::Format("Sigma Thresh, hot: %.2f", multHot));
info.push_back(wxString::Format("Mean: %.f", stats.mean));
info.push_back(wxString::Format("Stdev: %.f", stats.stdev));
info.push_back(wxString::Format("Median: %d", stats.median));
info.push_back(wxString::Format("MAD: %d", stats.mad));
int deltaCold = (int)(multCold * stats.stdev);
int deltaHot = (int)(multHot * stats.stdev);
info.push_back(wxString::Format("DeltaCold: %+d", -deltaCold));
info.push_back(wxString::Format("DeltaHot: %+d", deltaHot));
if (verbose) Debug.AddLine("DefectMap: deltaCold = %+d deltaHot = %+d", -deltaCold, deltaHot);
FindThresh(m_impl);
defectMap.clear();
unsigned int nr_cold = emit_defects(defectMap, m_impl->coldPxThresh, m_impl->coldPx.end(), stats.stdev, -1, verbose);
unsigned int nr_hot = emit_defects(defectMap, m_impl->hotPxThresh, m_impl->hotPx.end(), stats.stdev, +1, verbose);
if (verbose) Debug.AddLine("New defect map created, count=%d (cold=%d, hot=%d)", defectMap.size(), nr_cold, nr_hot);
}
const wxArrayString& DefectMapBuilder::GetMapInfo() const
{
return m_impl->mapInfo;
}
bool RemoveDefects(usImage& light, const DefectMap& defectMap)
{
// Check to make sure the light frame is valid
if (!light.ImageData)
return true;
if (!light.Subframe.IsEmpty())
{
// Step over each defect and replace the light value
// with the median of the surrounding pixels
for (DefectMap::const_iterator it = defectMap.begin(); it != defectMap.end(); ++it)
{
const wxPoint& pt = *it;
// Check to see if we are within the subframe before correcting the defect
if (light.Subframe.Contains(pt))
{
light.Pixel(pt.x, pt.y) = MedianBorderingPixels(light, pt.x, pt.y);
}
}
}
else
{
// Step over each defect and replace the light value
// with the median of the surrounding pixels
for (DefectMap::const_iterator it = defectMap.begin(); it != defectMap.end(); ++it)
{
int const x = it->x;
int const y = it->y;
if (x >= 0 && x < light.Size.GetWidth() && y >= 0 && y < light.Size.GetHeight())
{
light.Pixel(x, y) = MedianBorderingPixels(light, x, y);
}
}
}
return false;
}
wxString DefectMap::DefectMapFileName(int profileId)
{
int inst = pFrame->GetInstanceNumber();
return MyFrame::GetDarksDir() + PATHSEPSTR +
wxString::Format("PHD2_defect_map%s_%d.txt", inst > 1 ? wxString::Format("_%d", inst) : "", profileId);
}
bool DefectMap::ImportFromProfile(int srcId, int destId)
{
wxString sourceName;
wxString destName;
int rslt;
sourceName = DefectMapFileName(srcId);
destName = DefectMapFileName(destId);
rslt = wxCopyFile(sourceName, destName, true);
if (rslt != 1)
{
Debug.Write(wxString::Format("DefectMap::ImportFromProfile failed on defect map copy of %s to %s\n", sourceName, destName));
return false;
}
sourceName = DefectMapMasterPath(srcId);
destName = DefectMapMasterPath(destId);
rslt = wxCopyFile(sourceName, destName, true);
if (rslt != 1)
{
Debug.Write(wxString::Format("DefectMap::ImportFromProfile failed on defect map master dark copy of %s to %s\n", sourceName, destName));
return false;
}
sourceName = DefectMapFilterPath(srcId);
destName = DefectMapFilterPath(destId);
rslt = wxCopyFile(sourceName, destName, true);
if (rslt != 1)
{
Debug.Write(wxString::Format("DefectMap::ImportFromProfile failed on defect map master filtered dark copy of %s to %s\n", sourceName, destName));
return false;
}
return (true);
}
bool DefectMap::DefectMapExists(int profileId, bool showAlert)
{
bool bOk = false;
if (wxFileExists(DefectMapFileName(profileId)))
{
wxString fName = DefectMapMasterPath(profileId);
const wxSize& sensorSize = pCamera->DarkFrameSize();
if (sensorSize == UNDEFINED_FRAME_SIZE)
{
bOk = true;
Debug.AddLine("BPM check: undefined frame size for current camera");
}
else
{
fitsfile *fptr;
int status = 0; // CFITSIO status value MUST be initialized to zero!
if (PHD_fits_open_diskfile(&fptr, fName, READONLY, &status) == 0)
{
long fsize[2];
fits_get_img_size(fptr, 2, fsize, &status);
if (status == 0 && fsize[0] == sensorSize.x && fsize[1] == sensorSize.y)
bOk = true;
else
{
Debug.AddLine(wxString::Format("BPM check: failed geometry check - fits status = %d, cam dimensions = {%d,%d}, "
" BPM dimensions = {%d,%d}", status, sensorSize.x, sensorSize.y, fsize[0], fsize[1]));
if (showAlert)
pFrame->Alert(_("Bad-pixel map does not match the camera in this profile - it needs to be replaced."));
}
PHD_fits_close_file(fptr);
}
else
Debug.AddLine(wxString::Format("BPM check: fitsio error on open_diskfile = %d", status));
}
}
return bOk;
}
void DefectMap::Save(const wxArrayString& info) const
{
wxString filename = DefectMapFileName(m_profileId);
wxFileOutputStream oStream(filename);
wxTextOutputStream outText(oStream);
if (oStream.GetLastError() != wxSTREAM_NO_ERROR)
{
Debug.AddLine(wxString::Format("Failed to save defect map to %s", filename));
return;
}
outText << "# PHD2 Defect Map v1\n";
for (wxArrayString::const_iterator it = info.begin(); it != info.end(); ++it)
{
outText << "# " << *it << "\n";
}
outText << "# Defect count: " << ((unsigned int) size()) << "\n";
for (const_iterator it = begin(); it != end(); ++it)
{
outText << it->x << " " << it->y << "\n";
}
oStream.Close();
Debug.AddLine(wxString::Format("Saved defect map to %s", filename));
}
DefectMap::DefectMap()
: m_profileId(pConfig->GetCurrentProfileId())
{
}
DefectMap::DefectMap(int profileId)
: m_profileId(profileId)
{
}
bool DefectMap::FindDefect(const wxPoint& pt) const
{
return std::find(begin(), end(), pt) != end();
}
void DefectMap::AddDefect(const wxPoint& pt)
{
// first add the point
push_back(pt);
wxString filename = DefectMapFileName(m_profileId);
wxFile file(filename, wxFile::write_append);
wxFileOutputStream oStream(file);
wxTextOutputStream outText(oStream);
if (oStream.GetLastError() != wxSTREAM_NO_ERROR)
{
Debug.AddLine(wxString::Format("Failed to save defect map to %s", filename));
return;
}
outText << pt.x << " " << pt.y << "\n";
oStream.Close();
Debug.AddLine(wxString::Format("Saved defect map to %s", filename));
}
DefectMap *DefectMap::LoadDefectMap(int profileId)
{
wxString filename = DefectMapFileName(profileId);
Debug.AddLine(wxString::Format("Loading defect map file %s", filename));
if (!wxFileExists(filename))
{
Debug.AddLine(wxString::Format("Defect map file not found: %s", filename));
return 0;
}
wxFileInputStream iStream(filename);
wxTextInputStream inText(iStream);
// Re-initialize the defect map and parse the defect map file
if (iStream.GetLastError() != wxSTREAM_NO_ERROR)
{
Debug.AddLine(wxString::Format("Unexpected eof on defect map file %s", filename));
return 0;
}
DefectMap *defectMap = new DefectMap(profileId);
int linenum = 0;
while (!inText.GetInputStream().Eof())
{
wxString line = inText.ReadLine();
++linenum;
line.Trim(false); // trim leading whitespace
if (line.IsEmpty())
continue;
if (line.StartsWith("#"))
continue;
wxStringTokenizer tok(line);
wxString s1 = tok.GetNextToken();
wxString s2 = tok.GetNextToken();
long x, y;
if (s1.ToLong(&x) && s2.ToLong(&y))
{
defectMap->push_back(wxPoint(x, y));
}
else
{
Debug.AddLine(wxString::Format("DefectMap: ignore junk on line %d: %s", linenum, line));
}
}
Debug.AddLine(wxString::Format("Loaded %d defects", defectMap->size()));
return defectMap;
}
void DefectMap::DeleteDefectMap(int profileId)
{
wxString filename = DefectMapFileName(profileId);
if (wxFileExists(filename))
{
Debug.AddLine("Removing defect map file: " + filename);
wxRemoveFile(filename);
}
}
| lynxdeterra/open-phd-guiding | image_math.cpp | C++ | bsd-3-clause | 39,037 |
/* _______ __ __ __ ______ __ __ _______ __ __
* / _____/\ / /\ / /\ / /\ / ____/\ / /\ / /\ / ___ /\ / |\/ /\
* / /\____\// / // / // / // /\___\// /_// / // /\_/ / // , |/ / /
* / / /__ / / // / // / // / / / ___ / // ___ / // /| ' / /
* / /_// /\ / /_// / // / // /_/_ / / // / // /\_/ / // / | / /
* /______/ //______/ //_/ //_____/\ /_/ //_/ //_/ //_/ //_/ /|_/ /
* \______\/ \______\/ \_\/ \_____\/ \_\/ \_\/ \_\/ \_\/ \_\/ \_\/
*
* Copyright (c) 2004 - 2008 Olof Naessén and Per Larsson
*
*
* Per Larsson a.k.a finalman
* Olof Naessén a.k.a jansem/yakslem
*
* Visit: http://guichan.sourceforge.net
*
* License: (BSD)
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* 3. Neither the name of Guichan nor the names of its contributors may
* be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
* TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef GCN_OPENGL3GRAPHICS_HPP
#define GCN_OPENGL3GRAPHICS_HPP
#if defined (_WIN32)
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#endif
#if defined (__amigaos4__)
#include <mgl/gl.h>
#elif defined (__APPLE__)
#include <OpenGL/gl.h>
#else
#include <GL/gl.h>
#endif
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>
#include "guichan/color.hpp"
#include "guichan/graphics.hpp"
#include "guichan/platform.hpp"
namespace gcn
{
/**
* OpenGL3 implementation of the Graphics.
*/
class GCN_EXTENSION_DECLSPEC OpenGL3Graphics: public Graphics
{
public:
// Needed so that drawImage(gcn::Image *, int, int) is visible.
using Graphics::drawImage;
/**
* Constructor.
*/
OpenGL3Graphics();
/**
* Constructor.
*
* @param width the width of the logical drawing surface. Should be the
* same as the screen resolution.
*
* @param height the height ot the logical drawing surface. Should be
* the same as the screen resolution.
*/
OpenGL3Graphics(int width, int height);
/**
* Destructor.
*/
virtual ~OpenGL3Graphics();
/**
* Sets the target plane on where to draw.
*
* @param width the width of the logical drawing surface. Should be the
* same as the screen resolution.
* @param height the height ot the logical drawing surface. Should be
* the same as the screen resolution.
*/
virtual void setTargetPlane(int width, int height);
/**
* Gets the target plane width.
*
* @return The target plane width.
*/
virtual int getTargetPlaneWidth() const;
/**
* Gets the target plane height.
*
* @return The target plane height.
*/
virtual int getTargetPlaneHeight() const;
// Inherited from Graphics
virtual void _beginDraw();
virtual void _endDraw();
virtual bool pushClipArea(Rectangle area);
virtual void popClipArea();
virtual void drawImage(const Image* image,
int srcX,
int srcY,
int dstX,
int dstY,
int width,
int height);
virtual void drawPoint(int x, int y);
virtual void drawLine(int x1, int y1, int x2, int y2);
virtual void drawRectangle(const Rectangle& rectangle);
virtual void fillRectangle(const Rectangle& rectangle);
virtual void setColor(const Color& color);
virtual const Color& getColor() const;
protected:
int mWidth, mHeight;
bool mAlpha;
Color mColor;
GLuint mVBO;
GLuint mImageShader;
GLuint mLineShader;
glm::mat4 mProjection;
mutable bool mInitialize;
private:
GLuint createShaderProgram(const std::string& vs, const std::string& fs);
};
}
#endif // end GCN_OPENGL3GRAPHICS_HPP
| wheybags/guichan | include/guichan/opengl3/opengl3graphics.hpp | C++ | bsd-3-clause | 5,351 |
// Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "media/gpu/vaapi/vaapi_picture_native_pixmap_angle.h"
#include "media/gpu/vaapi/va_surface.h"
#include "media/gpu/vaapi/vaapi_wrapper.h"
#include "ui/gfx/x/connection.h"
#include "ui/gfx/x/future.h"
#include "ui/gfx/x/xproto.h"
#include "ui/gl/gl_bindings.h"
#include "ui/gl/gl_image_egl_pixmap.h"
#include "ui/gl/scoped_binders.h"
namespace media {
namespace {
x11::Pixmap CreatePixmap(const gfx::Size& size) {
auto* connection = x11::Connection::Get();
if (!connection->Ready())
return x11::Pixmap::None;
auto root = connection->default_root();
uint8_t depth = 0;
if (auto reply = connection->GetGeometry(root).Sync())
depth = reply->depth;
else
return x11::Pixmap::None;
// TODO(tmathmeyer) should we use the depth from libva instead of root window?
auto pixmap = connection->GenerateId<x11::Pixmap>();
uint16_t pixmap_width, pixmap_height;
if (!base::CheckedNumeric<int>(size.width()).AssignIfValid(&pixmap_width) ||
!base::CheckedNumeric<int>(size.height()).AssignIfValid(&pixmap_height)) {
return x11::Pixmap::None;
}
auto req = connection->CreatePixmap(
{depth, pixmap, root, pixmap_width, pixmap_height});
if (req.Sync().error)
pixmap = x11::Pixmap::None;
return pixmap;
}
} // namespace
VaapiPictureNativePixmapAngle::VaapiPictureNativePixmapAngle(
scoped_refptr<VaapiWrapper> vaapi_wrapper,
const MakeGLContextCurrentCallback& make_context_current_cb,
const BindGLImageCallback& bind_image_cb,
int32_t picture_buffer_id,
const gfx::Size& size,
const gfx::Size& visible_size,
uint32_t service_texture_id,
uint32_t client_texture_id,
uint32_t texture_target)
: VaapiPictureNativePixmap(std::move(vaapi_wrapper),
make_context_current_cb,
bind_image_cb,
picture_buffer_id,
size,
visible_size,
service_texture_id,
client_texture_id,
texture_target) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
// Check that they're both not 0
DCHECK(service_texture_id);
DCHECK(client_texture_id);
}
VaapiPictureNativePixmapAngle::~VaapiPictureNativePixmapAngle() {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
if (gl_image_ && make_context_current_cb_.Run()) {
gl_image_->ReleaseTexImage(texture_target_);
DCHECK_EQ(glGetError(), static_cast<GLenum>(GL_NO_ERROR));
}
if (x_pixmap_ != x11::Pixmap::None)
x11::Connection::Get()->FreePixmap({x_pixmap_});
}
Status VaapiPictureNativePixmapAngle::Allocate(gfx::BufferFormat format) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
if (!(texture_id_ || client_texture_id_))
return StatusCode::kVaapiNoTexture;
if (!make_context_current_cb_ || !make_context_current_cb_.Run())
return StatusCode::kVaapiBadContext;
auto image =
base::MakeRefCounted<gl::GLImageEGLPixmap>(visible_size_, format);
if (!image)
return StatusCode::kVaapiNoImage;
x_pixmap_ = CreatePixmap(visible_size_);
if (x_pixmap_ == x11::Pixmap::None)
return StatusCode::kVaapiNoPixmap;
if (!image->Initialize(x_pixmap_))
return StatusCode::kVaapiFailedToInitializeImage;
gl::ScopedTextureBinder texture_binder(texture_target_, texture_id_);
if (!image->BindTexImage(texture_target_))
return StatusCode::kVaapiFailedToBindTexture;
gl_image_ = image;
DCHECK(bind_image_cb_);
if (!bind_image_cb_.Run(client_texture_id_, texture_target_, gl_image_,
/*can_bind_to_sampler=*/true)) {
return StatusCode::kVaapiFailedToBindImage;
}
return OkStatus();
}
bool VaapiPictureNativePixmapAngle::ImportGpuMemoryBufferHandle(
gfx::BufferFormat format,
gfx::GpuMemoryBufferHandle gpu_memory_buffer_handle) {
NOTREACHED();
return false;
}
bool VaapiPictureNativePixmapAngle::DownloadFromSurface(
scoped_refptr<VASurface> va_surface) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
if (!make_context_current_cb_ || !make_context_current_cb_.Run())
return false;
DCHECK(texture_id_);
gl::ScopedTextureBinder texture_binder(texture_target_, texture_id_);
// GL needs to re-bind the texture after the pixmap content is updated so that
// the compositor sees the updated contents (we found this out experimentally)
gl_image_->ReleaseTexImage(texture_target_);
DCHECK(gfx::Rect(va_surface->size()).Contains(gfx::Rect(visible_size_)));
if (!vaapi_wrapper_->PutSurfaceIntoPixmap(va_surface->id(), x_pixmap_,
visible_size_)) {
return false;
}
return gl_image_->BindTexImage(texture_target_);
}
VASurfaceID VaapiPictureNativePixmapAngle::va_surface_id() const {
return VA_INVALID_ID;
}
} // namespace media
| youtube/cobalt | third_party/chromium/media/gpu/vaapi/vaapi_picture_native_pixmap_angle.cc | C++ | bsd-3-clause | 5,069 |
<?php
/**
* Copyright (c) 2013, EBANX Tecnologia da Informação Ltda.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* Neither the name of EBANX nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
namespace Mock\Http;
class Client extends \Ebanx\Http\AbstractClient
{
/**
* Returns the request options/parameters instead of sending the request
* @return array
*/
public function send()
{
return array(
'method' => $this->method
, 'action' => $this->action
, 'params' => $this->requestParams
, 'decode' => $this->hasToDecodeResponse
);
}
}
| ebanx-integration/ebanx-php | test/Mock/Http/Client.php | PHP | bsd-3-clause | 2,009 |
<?php
use yii\helpers\Html;
use yii\widgets\DetailView;
/* @var $this yii\web\View */
/* @var $model app\models\Books */
$this->title = $model->name;
$this->params['breadcrumbs'][] = ['label' => 'Книги', 'url' => ['index']];
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="books-view">
<h1><?= Html::encode($this->title) ?></h1>
<?= DetailView::widget([
'model' => $model,
'attributes' => [
'id',
'name',
[
'attribute' => 'date_create',
'format' => ['date', 'd MMMM yyyy']
],
'date_update',
[
'attribute' => 'Превью',
'format' => 'html',
'value' => Html::img($model->getPreviewUrl(), ['width' => '100']),
],
'date',
'author.FullName'
],
]) ?>
</div>
| xenm321/test | views/book/view.php | PHP | bsd-3-clause | 905 |
import os
from subprocess import call, Popen, PIPE
import sys
from . import Command
from . import utils
class OpenSequenceInRV(Command):
"""%prog [options] [paths]
Open the latest version for each given entity.
"""
def run(self, sgfs, opts, args):
# Parse them all.
arg_to_movie = {}
arg_to_entity = {}
for arg in args:
if os.path.exists(arg):
arg_to_movie[arg] = arg
continue
print 'Parsing %r...' % arg
data = utils.parse_spec(sgfs, arg.split(), ['Shot'])
type_ = data.get('type')
id_ = data.get('id')
if not (type_ or id_):
print 'no entities found for', repr(arg)
return 1
arg_to_entity.setdefault(type_, {})[arg] = sgfs.session.merge(dict(type=type_, id=id_))
tasks = arg_to_entity.pop('Task', {})
shots = arg_to_entity.pop('Shot', {})
if arg_to_entity:
print 'found entities that were not Task or Shot:', ', '.join(sorted(arg_to_entity))
return 2
if tasks:
print 'Getting shots from tasks...'
sgfs.session.fetch(tasks.values(), 'entity')
for arg, task in tasks.iteritems():
shots[arg] = task['entity']
if shots:
print 'Getting versions from shots...'
sgfs.session.fetch(shots.values(), ('sg_latest_version.Version.sg_path_to_movie', 'sg_latest_version.Version.sg_path_to_frames'))
for arg, shot in shots.iteritems():
version = shot.get('sg_latest_version')
if not version:
print 'no version for', shot
return 3
path = version.get('sg_path_to_movie') or version.get('sg_path_to_frames')
if not path:
print 'no movie or frames for', version
return 4
arg_to_movie[arg] = path
movies = [arg_to_movie[arg] for arg in args]
print 'Opening:'
print '\t' + '\n\t'.join(movies)
rvlink = Popen(['rv', '-bakeURL'] + movies, stderr=PIPE).communicate()[1].strip().split()[-1]
self.open(rvlink)
def open(self, x):
if sys.platform.startswith('darwin'):
call(['open', x])
else:
call(['xdg-open', x])
run = OpenSequenceInRV()
| westernx/sgfs | sgfs/commands/rv.py | Python | bsd-3-clause | 2,458 |
/*
MIT License
Copyright (C) 2006 The Mono.Xna Team
All rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
// The functions in this file are a port of an MIT licensed library: MonoGame - Vector2.cs.
#include <FslBase/Math/Quaternion.hpp>
#include <FslBase/Math/Vector3.hpp>
#include <FslBase/Math/Matrix.hpp>
#include <FslBase/Math/MatrixFields.hpp>
#include <FslBase/Exceptions.hpp>
#include <cassert>
#include <cmath>
#include <cstddef>
namespace Fsl
{
using namespace MatrixFields;
Quaternion::Quaternion(const Vector3& vectorPart, const float scalarPart)
: X(vectorPart.X)
, Y(vectorPart.Y)
, Z(vectorPart.Z)
, W(scalarPart)
{
}
Quaternion Quaternion::Add(const Quaternion& lhs, const Quaternion& rhs)
{
return {lhs.X + rhs.X, lhs.Y + rhs.Y, lhs.Z + rhs.Z, lhs.W + rhs.W};
}
void Quaternion::Add(Quaternion& rResult, const Quaternion& lhs, const Quaternion& rhs)
{
rResult.X = lhs.X + rhs.X;
rResult.Y = lhs.Y + rhs.Y;
rResult.Z = lhs.Z + rhs.Z;
rResult.W = lhs.W + rhs.W;
}
Quaternion Quaternion::Concatenate(const Quaternion& lhs, const Quaternion& rhs)
{
float x = rhs.X;
float y = rhs.Y;
float z = rhs.Z;
float w = rhs.W;
float num4 = lhs.X;
float num3 = lhs.Y;
float num2 = lhs.Z;
float num = lhs.W;
float num12 = (y * num2) - (z * num3);
float num11 = (z * num4) - (x * num2);
float num10 = (x * num3) - (y * num4);
float num9 = ((x * num4) + (y * num3)) + (z * num2);
// Quaternion quaternion(OptimizationFlag::NoInitialization);
Quaternion quaternion;
quaternion.X = ((x * num) + (num4 * w)) + num12;
quaternion.Y = ((y * num) + (num3 * w)) + num11;
quaternion.Z = ((z * num) + (num2 * w)) + num10;
quaternion.W = (w * num) - num9;
return quaternion;
}
void Quaternion::Concatenate(Quaternion& rResult, const Quaternion& lhs, const Quaternion& rhs)
{
const float x = rhs.X;
const float y = rhs.Y;
const float z = rhs.Z;
const float w = rhs.W;
const float num4 = lhs.X;
const float num3 = lhs.Y;
const float num2 = lhs.Z;
const float num = lhs.W;
const float num12 = (y * num2) - (z * num3);
const float num11 = (z * num4) - (x * num2);
const float num10 = (x * num3) - (y * num4);
const float num9 = ((x * num4) + (y * num3)) + (z * num2);
rResult.X = ((x * num) + (num4 * w)) + num12;
rResult.Y = ((y * num) + (num3 * w)) + num11;
rResult.Z = ((z * num) + (num2 * w)) + num10;
rResult.W = (w * num) - num9;
}
void Quaternion::Conjugate()
{
X = -X;
Y = -Y;
Z = -Z;
}
Quaternion Quaternion::Conjugate(const Quaternion& value)
{
// Quaternion quaternion(OptimizationFlag::NoInitialization);
Quaternion quaternion;
quaternion.X = -value.X;
quaternion.Y = -value.Y;
quaternion.Z = -value.Z;
quaternion.W = value.W;
return quaternion;
}
void Quaternion::Conjugate(Quaternion& rResult, const Quaternion& value)
{
rResult.X = -value.X;
rResult.Y = -value.Y;
rResult.Z = -value.Z;
rResult.W = value.W;
}
Quaternion Quaternion::CreateFromAxisAngle(const Vector3& axis, const float angle)
{
const float num2 = angle * 0.5f;
const auto num = static_cast<float>(std::sin(static_cast<double>(num2)));
// Quaternion quaternion(OptimizationFlag::NoInitialization);
Quaternion quaternion;
quaternion.X = axis.X * num;
quaternion.Y = axis.Y * num;
quaternion.Z = axis.Z * num;
quaternion.W = static_cast<float>(std::cos(static_cast<double>(num2)));
return quaternion;
}
void Quaternion::CreateFromAxisAngle(Quaternion& rResult, const Vector3& axis, const float angle)
{
const float num2 = angle * 0.5f;
const auto num = static_cast<float>(std::sin(static_cast<double>(num2)));
rResult.X = axis.X * num;
rResult.Y = axis.Y * num;
rResult.Z = axis.Z * num;
rResult.W = static_cast<float>(std::cos(static_cast<double>(num2)));
}
Quaternion Quaternion::CreateFromRotationMatrix(const Matrix& matrix)
{
const float* const pMatrix = matrix.DirectAccess();
float num8 = (pMatrix[_M11] + pMatrix[_M22]) + pMatrix[_M33];
// Quaternion quaternion(OptimizationFlag::NoInitialization);
Quaternion quaternion;
if (num8 > 0.0f)
{
auto num = std::sqrt(num8 + 1.0f);
quaternion.W = num * 0.5f;
num = 0.5f / num;
quaternion.X = (pMatrix[_M23] - pMatrix[_M32]) * num;
quaternion.Y = (pMatrix[_M31] - pMatrix[_M13]) * num;
quaternion.Z = (pMatrix[_M12] - pMatrix[_M21]) * num;
return quaternion;
}
if ((pMatrix[_M11] >= pMatrix[_M22]) && (pMatrix[_M11] >= pMatrix[_M33]))
{
const auto num7 = std::sqrt(((1.0f + pMatrix[_M11]) - pMatrix[_M22]) - pMatrix[_M33]);
const float num4 = 0.5f / num7;
quaternion.X = 0.5f * num7;
quaternion.Y = (pMatrix[_M12] + pMatrix[_M21]) * num4;
quaternion.Z = (pMatrix[_M13] + pMatrix[_M31]) * num4;
quaternion.W = (pMatrix[_M23] - pMatrix[_M32]) * num4;
return quaternion;
}
if (pMatrix[_M22] > pMatrix[_M33])
{
const auto num6 = std::sqrt(((1.0f + pMatrix[_M22]) - pMatrix[_M11]) - pMatrix[_M33]);
const float num3 = 0.5f / num6;
quaternion.X = (pMatrix[_M21] + pMatrix[_M12]) * num3;
quaternion.Y = 0.5f * num6;
quaternion.Z = (pMatrix[_M32] + pMatrix[_M23]) * num3;
quaternion.W = (pMatrix[_M31] - pMatrix[_M13]) * num3;
return quaternion;
}
const auto num5 = std::sqrt(((1.0f + pMatrix[_M33]) - pMatrix[_M11]) - pMatrix[_M22]);
const float num2 = 0.5f / num5;
quaternion.X = (pMatrix[_M31] + pMatrix[_M13]) * num2;
quaternion.Y = (pMatrix[_M32] + pMatrix[_M23]) * num2;
quaternion.Z = 0.5f * num5;
quaternion.W = (pMatrix[_M12] - pMatrix[_M21]) * num2;
return quaternion;
}
void Quaternion::CreateFromRotationMatrix(Quaternion& rResult, const Matrix& matrix)
{
const float* const pMatrix = matrix.DirectAccess();
const float num8 = (pMatrix[_M11] + pMatrix[_M22]) + pMatrix[_M33];
if (num8 > 0.0f)
{
auto num = static_cast<float>(std::sqrt(static_cast<double>(num8 + 1.0f)));
rResult.W = num * 0.5f;
num = 0.5f / num;
rResult.X = (pMatrix[_M23] - pMatrix[_M32]) * num;
rResult.Y = (pMatrix[_M31] - pMatrix[_M13]) * num;
rResult.Z = (pMatrix[_M12] - pMatrix[_M21]) * num;
}
else if ((pMatrix[_M11] >= pMatrix[_M22]) && (pMatrix[_M11] >= pMatrix[_M33]))
{
const auto num7 = static_cast<float>(std::sqrt(static_cast<double>(((1.0f + pMatrix[_M11]) - pMatrix[_M22]) - pMatrix[_M33])));
const float num4 = 0.5f / num7;
rResult.X = 0.5f * num7;
rResult.Y = (pMatrix[_M12] + pMatrix[_M21]) * num4;
rResult.Z = (pMatrix[_M13] + pMatrix[_M31]) * num4;
rResult.W = (pMatrix[_M23] - pMatrix[_M32]) * num4;
}
else if (pMatrix[_M22] > pMatrix[_M33])
{
const auto num6 = static_cast<float>(std::sqrt(static_cast<double>(((1.0f + pMatrix[_M22]) - pMatrix[_M11]) - pMatrix[_M33])));
const float num3 = 0.5f / num6;
rResult.X = (pMatrix[_M21] + pMatrix[_M12]) * num3;
rResult.Y = 0.5f * num6;
rResult.Z = (pMatrix[_M32] + pMatrix[_M23]) * num3;
rResult.W = (pMatrix[_M31] - pMatrix[_M13]) * num3;
}
else
{
const auto num5 = static_cast<float>(std::sqrt(static_cast<double>(((1.0f + pMatrix[_M33]) - pMatrix[_M11]) - pMatrix[_M22])));
const float num2 = 0.5f / num5;
rResult.X = (pMatrix[_M31] + pMatrix[_M13]) * num2;
rResult.Y = (pMatrix[_M32] + pMatrix[_M23]) * num2;
rResult.Z = 0.5f * num5;
rResult.W = (pMatrix[_M12] - pMatrix[_M21]) * num2;
}
}
Quaternion Quaternion::CreateFromYawPitchRoll(const float yaw, const float pitch, const float roll)
{
const float num9 = roll * 0.5f;
const auto num6 = static_cast<float>(std::sin(static_cast<double>(num9)));
const auto num5 = static_cast<float>(std::cos(static_cast<double>(num9)));
const float num8 = pitch * 0.5f;
const auto num4 = static_cast<float>(std::sin(static_cast<double>(num8)));
const auto num3 = static_cast<float>(std::cos(static_cast<double>(num8)));
const float num7 = yaw * 0.5f;
const auto num2 = static_cast<float>(std::sin(static_cast<double>(num7)));
const auto num = static_cast<float>(std::cos(static_cast<double>(num7)));
// Quaternion quaternion(OptimizationFlag::NoInitialization);
Quaternion quaternion;
quaternion.X = ((num * num4) * num5) + ((num2 * num3) * num6);
quaternion.Y = ((num2 * num3) * num5) - ((num * num4) * num6);
quaternion.Z = ((num * num3) * num6) - ((num2 * num4) * num5);
quaternion.W = ((num * num3) * num5) + ((num2 * num4) * num6);
return quaternion;
}
void Quaternion::CreateFromYawPitchRoll(Quaternion& rResult, const float yaw, const float pitch, const float roll)
{
const float num9 = roll * 0.5f;
const auto num6 = static_cast<float>(std::sin(static_cast<double>(num9)));
const auto num5 = static_cast<float>(std::cos(static_cast<double>(num9)));
const float num8 = pitch * 0.5f;
const auto num4 = static_cast<float>(std::sin(static_cast<double>(num8)));
const auto num3 = static_cast<float>(std::cos(static_cast<double>(num8)));
const float num7 = yaw * 0.5f;
const auto num2 = static_cast<float>(std::sin(static_cast<double>(num7)));
const auto num = static_cast<float>(std::cos(static_cast<double>(num7)));
rResult.X = ((num * num4) * num5) + ((num2 * num3) * num6);
rResult.Y = ((num2 * num3) * num5) - ((num * num4) * num6);
rResult.Z = ((num * num3) * num6) - ((num2 * num4) * num5);
rResult.W = ((num * num3) * num5) + ((num2 * num4) * num6);
}
Quaternion Quaternion::Divide(const Quaternion& lhs, const Quaternion& rhs)
{
const float x = lhs.X;
const float y = lhs.Y;
const float z = lhs.Z;
const float w = lhs.W;
const float num14 = (((rhs.X * rhs.X) + (rhs.Y * rhs.Y)) + (rhs.Z * rhs.Z)) + (rhs.W * rhs.W);
const float num5 = 1.0f / num14;
const float num4 = -rhs.X * num5;
const float num3 = -rhs.Y * num5;
const float num2 = -rhs.Z * num5;
const float num = rhs.W * num5;
const float num13 = (y * num2) - (z * num3);
const float num12 = (z * num4) - (x * num2);
const float num11 = (x * num3) - (y * num4);
const float num10 = ((x * num4) + (y * num3)) + (z * num2);
// Quaternion quaternion(OptimizationFlag::NoInitialization);
Quaternion quaternion;
quaternion.X = ((x * num) + (num4 * w)) + num13;
quaternion.Y = ((y * num) + (num3 * w)) + num12;
quaternion.Z = ((z * num) + (num2 * w)) + num11;
quaternion.W = (w * num) - num10;
return quaternion;
}
void Quaternion::Divide(Quaternion& rResult, const Quaternion& lhs, const Quaternion& rhs)
{
const float x = lhs.X;
const float y = lhs.Y;
const float z = lhs.Z;
const float w = lhs.W;
const float num14 = (((rhs.X * rhs.X) + (rhs.Y * rhs.Y)) + (rhs.Z * rhs.Z)) + (rhs.W * rhs.W);
const float num5 = 1.0f / num14;
const float num4 = -rhs.X * num5;
const float num3 = -rhs.Y * num5;
const float num2 = -rhs.Z * num5;
const float num = rhs.W * num5;
const float num13 = (y * num2) - (z * num3);
const float num12 = (z * num4) - (x * num2);
const float num11 = (x * num3) - (y * num4);
const float num10 = ((x * num4) + (y * num3)) + (z * num2);
rResult.X = ((x * num) + (num4 * w)) + num13;
rResult.Y = ((y * num) + (num3 * w)) + num12;
rResult.Z = ((z * num) + (num2 * w)) + num11;
rResult.W = (w * num) - num10;
}
float Quaternion::Dot(const Quaternion& lhs, const Quaternion& rhs)
{
return ((((lhs.X * rhs.X) + (lhs.Y * rhs.Y)) + (lhs.Z * rhs.Z)) + (lhs.W * rhs.W));
}
void Quaternion::Dot(float& rResult, const Quaternion& lhs, const Quaternion& rhs)
{
rResult = (((lhs.X * rhs.X) + (lhs.Y * rhs.Y)) + (lhs.Z * rhs.Z)) + (lhs.W * rhs.W);
}
// public bool Equals(Quaternion other)
//{
// return ((((this.X == other.X) && (this.Y == other.Y)) && (this.Z == other.Z)) && (this.W == other.W));
//}
// public override int GetHashCode()
//{
// return (((this.X.GetHashCode() + this.Y.GetHashCode()) + this.Z.GetHashCode()) + this.W.GetHashCode());
//}
Quaternion Quaternion::Inverse(const Quaternion& quaternion)
{
const float num2 =
(((quaternion.X * quaternion.X) + (quaternion.Y * quaternion.Y)) + (quaternion.Z * quaternion.Z)) + (quaternion.W * quaternion.W);
const float num = 1.0f / num2;
// Quaternion result(OptimizationFlag::NoInitialization);
Quaternion result;
result.X = -quaternion.X * num;
result.Y = -quaternion.Y * num;
result.Z = -quaternion.Z * num;
result.W = quaternion.W * num;
return result;
}
void Quaternion::Inverse(Quaternion& rResult, const Quaternion& quaternion)
{
const float num2 =
(((quaternion.X * quaternion.X) + (quaternion.Y * quaternion.Y)) + (quaternion.Z * quaternion.Z)) + (quaternion.W * quaternion.W);
const float num = 1.0f / num2;
rResult.X = -quaternion.X * num;
rResult.Y = -quaternion.Y * num;
rResult.Z = -quaternion.Z * num;
rResult.W = quaternion.W * num;
}
float Quaternion::Length() const
{
const float lenSquared = (((X * X) + (Y * Y)) + (Z * Z)) + (W * W);
return std::sqrt(lenSquared);
}
float Quaternion::LengthSquared() const
{
return ((((X * X) + (Y * Y)) + (Z * Z)) + (W * W));
}
Quaternion Quaternion::Lerp(const Quaternion& quaternion1, const Quaternion& quaternion2, const float amount)
{
const float num = amount;
const float num2 = 1.0f - num;
// Quaternion quaternion(OptimizationFlag::NoInitialization);
Quaternion quaternion;
float num5 =
(((quaternion1.X * quaternion2.X) + (quaternion1.Y * quaternion2.Y)) + (quaternion1.Z * quaternion2.Z)) + (quaternion1.W * quaternion2.W);
if (num5 >= 0.0f)
{
quaternion.X = (num2 * quaternion1.X) + (num * quaternion2.X);
quaternion.Y = (num2 * quaternion1.Y) + (num * quaternion2.Y);
quaternion.Z = (num2 * quaternion1.Z) + (num * quaternion2.Z);
quaternion.W = (num2 * quaternion1.W) + (num * quaternion2.W);
}
else
{
quaternion.X = (num2 * quaternion1.X) - (num * quaternion2.X);
quaternion.Y = (num2 * quaternion1.Y) - (num * quaternion2.Y);
quaternion.Z = (num2 * quaternion1.Z) - (num * quaternion2.Z);
quaternion.W = (num2 * quaternion1.W) - (num * quaternion2.W);
}
float num4 = (((quaternion.X * quaternion.X) + (quaternion.Y * quaternion.Y)) + (quaternion.Z * quaternion.Z)) + (quaternion.W * quaternion.W);
float num3 = 1.0f / (std::sqrt(num4));
quaternion.X *= num3;
quaternion.Y *= num3;
quaternion.Z *= num3;
quaternion.W *= num3;
return quaternion;
}
void Quaternion::Lerp(Quaternion& rResult, const Quaternion& quaternion1, const Quaternion& quaternion2, const float amount)
{
const float num = amount;
const float num2 = 1.0f - num;
const float num5 =
(((quaternion1.X * quaternion2.X) + (quaternion1.Y * quaternion2.Y)) + (quaternion1.Z * quaternion2.Z)) + (quaternion1.W * quaternion2.W);
if (num5 >= 0.0f)
{
rResult.X = (num2 * quaternion1.X) + (num * quaternion2.X);
rResult.Y = (num2 * quaternion1.Y) + (num * quaternion2.Y);
rResult.Z = (num2 * quaternion1.Z) + (num * quaternion2.Z);
rResult.W = (num2 * quaternion1.W) + (num * quaternion2.W);
}
else
{
rResult.X = (num2 * quaternion1.X) - (num * quaternion2.X);
rResult.Y = (num2 * quaternion1.Y) - (num * quaternion2.Y);
rResult.Z = (num2 * quaternion1.Z) - (num * quaternion2.Z);
rResult.W = (num2 * quaternion1.W) - (num * quaternion2.W);
}
const float num4 = (((rResult.X * rResult.X) + (rResult.Y * rResult.Y)) + (rResult.Z * rResult.Z)) + (rResult.W * rResult.W);
const float num3 = 1.0f / (static_cast<float>(std::sqrt(static_cast<double>(num4))));
rResult.X *= num3;
rResult.Y *= num3;
rResult.Z *= num3;
rResult.W *= num3;
}
Quaternion Quaternion::Slerp(const Quaternion& quaternion1, const Quaternion& quaternion2, const float amount)
{
float num2;
float num3;
float num = amount;
float num4 =
(((quaternion1.X * quaternion2.X) + (quaternion1.Y * quaternion2.Y)) + (quaternion1.Z * quaternion2.Z)) + (quaternion1.W * quaternion2.W);
bool flag = false;
if (num4 < 0.0f)
{
flag = true;
num4 = -num4;
}
if (num4 > 0.999999f)
{
num3 = 1.0f - num;
num2 = flag ? -num : num;
}
else
{
auto num5 = static_cast<float>(std::acos(static_cast<double>(num4)));
auto num6 = static_cast<float>(1.0 / std::sin(static_cast<double>(num5)));
num3 = (static_cast<float>(std::sin(static_cast<double>((1.0f - num) * num5)))) * num6;
num2 = flag ? ((static_cast<float>(-std::sin(static_cast<double>(num * num5)))) * num6)
: ((static_cast<float>(std::sin(static_cast<double>(num * num5)))) * num6);
}
// Quaternion quaternion(OptimizationFlag::NoInitialization);
Quaternion quaternion;
quaternion.X = (num3 * quaternion1.X) + (num2 * quaternion2.X);
quaternion.Y = (num3 * quaternion1.Y) + (num2 * quaternion2.Y);
quaternion.Z = (num3 * quaternion1.Z) + (num2 * quaternion2.Z);
quaternion.W = (num3 * quaternion1.W) + (num2 * quaternion2.W);
return quaternion;
}
void Quaternion::Slerp(Quaternion& rResult, const Quaternion& quaternion1, const Quaternion& quaternion2, const float amount)
{
float num2;
float num3;
float num = amount;
float num4 =
(((quaternion1.X * quaternion2.X) + (quaternion1.Y * quaternion2.Y)) + (quaternion1.Z * quaternion2.Z)) + (quaternion1.W * quaternion2.W);
bool flag = false;
if (num4 < 0.0f)
{
flag = true;
num4 = -num4;
}
if (num4 > 0.999999f)
{
num3 = 1.0f - num;
num2 = flag ? -num : num;
}
else
{
auto num5 = static_cast<float>(std::acos(static_cast<double>(num4)));
auto num6 = static_cast<float>(1.0 / std::sin(static_cast<double>(num5)));
num3 = (static_cast<float>(std::sin(static_cast<double>((1.0f - num) * num5)))) * num6;
num2 = flag ? ((static_cast<float>(-std::sin(static_cast<double>(num * num5)))) * num6)
: ((static_cast<float>(std::sin(static_cast<double>(num * num5)))) * num6);
}
rResult.X = (num3 * quaternion1.X) + (num2 * quaternion2.X);
rResult.Y = (num3 * quaternion1.Y) + (num2 * quaternion2.Y);
rResult.Z = (num3 * quaternion1.Z) + (num2 * quaternion2.Z);
rResult.W = (num3 * quaternion1.W) + (num2 * quaternion2.W);
}
Quaternion Quaternion::Subtract(const Quaternion& lhs, const Quaternion& rhs)
{
// Quaternion quaternion(OptimizationFlag::NoInitialization);
Quaternion quaternion;
quaternion.X = lhs.X - rhs.X;
quaternion.Y = lhs.Y - rhs.Y;
quaternion.Z = lhs.Z - rhs.Z;
quaternion.W = lhs.W - rhs.W;
return quaternion;
}
void Quaternion::Subtract(Quaternion& rResult, const Quaternion& lhs, const Quaternion& rhs)
{
rResult.X = lhs.X - rhs.X;
rResult.Y = lhs.Y - rhs.Y;
rResult.Z = lhs.Z - rhs.Z;
rResult.W = lhs.W - rhs.W;
}
Quaternion Quaternion::Multiply(const Quaternion& lhs, const Quaternion& rhs)
{
const float x = lhs.X;
const float y = lhs.Y;
const float z = lhs.Z;
const float w = lhs.W;
const float num4 = rhs.X;
const float num3 = rhs.Y;
const float num2 = rhs.Z;
const float num = rhs.W;
const float num12 = (y * num2) - (z * num3);
const float num11 = (z * num4) - (x * num2);
const float num10 = (x * num3) - (y * num4);
const float num9 = ((x * num4) + (y * num3)) + (z * num2);
// Quaternion quaternion(OptimizationFlag::NoInitialization);
Quaternion quaternion;
quaternion.X = ((x * num) + (num4 * w)) + num12;
quaternion.Y = ((y * num) + (num3 * w)) + num11;
quaternion.Z = ((z * num) + (num2 * w)) + num10;
quaternion.W = (w * num) - num9;
return quaternion;
}
Quaternion Quaternion::Multiply(const Quaternion& lhs, const float scaleFactor)
{
// Quaternion quaternion(OptimizationFlag::NoInitialization);
Quaternion quaternion;
quaternion.X = lhs.X * scaleFactor;
quaternion.Y = lhs.Y * scaleFactor;
quaternion.Z = lhs.Z * scaleFactor;
quaternion.W = lhs.W * scaleFactor;
return quaternion;
}
void Quaternion::Multiply(Quaternion& rResult, const Quaternion& lhs, const float& scaleFactor)
{
rResult.X = lhs.X * scaleFactor;
rResult.Y = lhs.Y * scaleFactor;
rResult.Z = lhs.Z * scaleFactor;
rResult.W = lhs.W * scaleFactor;
}
void Quaternion::Multiply(Quaternion& rResult, const Quaternion& lhs, const Quaternion& rhs)
{
const float x = lhs.X;
const float y = lhs.Y;
const float z = lhs.Z;
const float w = lhs.W;
const float num4 = rhs.X;
const float num3 = rhs.Y;
const float num2 = rhs.Z;
const float num = rhs.W;
const float num12 = (y * num2) - (z * num3);
const float num11 = (z * num4) - (x * num2);
const float num10 = (x * num3) - (y * num4);
const float num9 = ((x * num4) + (y * num3)) + (z * num2);
rResult.X = ((x * num) + (num4 * w)) + num12;
rResult.Y = ((y * num) + (num3 * w)) + num11;
rResult.Z = ((z * num) + (num2 * w)) + num10;
rResult.W = (w * num) - num9;
}
Quaternion Quaternion::Negate(const Quaternion& quaternion)
{
// Quaternion result(OptimizationFlag::NoInitialization);
Quaternion result;
result.X = -quaternion.X;
result.Y = -quaternion.Y;
result.Z = -quaternion.Z;
result.W = -quaternion.W;
return result;
}
void Quaternion::Negate(Quaternion& rResult, const Quaternion& quaternion)
{
rResult.X = -quaternion.X;
rResult.Y = -quaternion.Y;
rResult.Z = -quaternion.Z;
rResult.W = -quaternion.W;
}
void Quaternion::Normalize()
{
const float num2 = (((X * X) + (Y * Y)) + (Z * Z)) + (W * W);
const float num = 1.0f / (static_cast<float>(std::sqrt(static_cast<double>(num2))));
X *= num;
Y *= num;
Z *= num;
W *= num;
}
Quaternion Quaternion::Normalize(const Quaternion& quaternion)
{
const float num2 =
(((quaternion.X * quaternion.X) + (quaternion.Y * quaternion.Y)) + (quaternion.Z * quaternion.Z)) + (quaternion.W * quaternion.W);
const float num = 1.0f / (static_cast<float>(std::sqrt(static_cast<double>(num2))));
// Quaternion result(OptimizationFlag::NoInitialization);
Quaternion result;
result.X = quaternion.X * num;
result.Y = quaternion.Y * num;
result.Z = quaternion.Z * num;
result.W = quaternion.W * num;
return result;
}
void Quaternion::Normalize(Quaternion& rResult, const Quaternion& quaternion)
{
const float num2 =
(((quaternion.X * quaternion.X) + (quaternion.Y * quaternion.Y)) + (quaternion.Z * quaternion.Z)) + (quaternion.W * quaternion.W);
const float num = 1.0f / (static_cast<float>(std::sqrt(static_cast<double>(num2))));
rResult.X = quaternion.X * num;
rResult.Y = quaternion.Y * num;
rResult.Z = quaternion.Z * num;
rResult.W = quaternion.W * num;
}
// public static Quaternion Quaternion::operator -(Quaternion quaternion)
//{
// Quaternion result;
// result.X = -quaternion.X;
// result.Y = -quaternion.Y;
// result.Z = -quaternion.Z;
// result.W = -quaternion.W;
// return result;
//}
// internal string Quaternion::DebugDisplayString
//{
// get
// {
// if (this == Quaternion.identity)
// {
// return "Identity";
// }
// return string.Concat(
// this.X.ToString(), " ",
// this.Y.ToString(), " ",
// this.Z.ToString(), " ",
// this.W.ToString()
// );
// }
//}
// public override string Quaternion::ToString()
// {
// System.Text.StringBuilder sb = new System.Text.StringBuilder(32);
// sb.Append("{X:");
// sb.Append(this.X);
// sb.Append(" Y:");
// sb.Append(this.Y);
// sb.Append(" Z:");
// sb.Append(this.Z);
// sb.Append(" W:");
// sb.Append(this.W);
// sb.Append("}");
// return sb.ToString();
// }
// internal Matrix Quaternion::ToMatrix()
// {
// Matrix matrix = Matrix.Identity;
// ToMatrix(out matrix);
// return matrix;
// }
// internal void Quaternion::ToMatrix(out Matrix matrix)
// {
// Quaternion.ToMatrix(this, out matrix);
// }
// internal static void Quaternion::ToMatrix(Quaternion quaternion, out Matrix matrix)
// {
// // source -> http://content.gpwiki.org/index.php/OpenGL:Tutorials:Using_Quaternions_to_represent_rotation#Quaternion_to_Matrix
// float x2 = quaternion.X * quaternion.X;
// float y2 = quaternion.Y * quaternion.Y;
// float z2 = quaternion.Z * quaternion.Z;
// float xy = quaternion.X * quaternion.Y;
// float xz = quaternion.X * quaternion.Z;
// float yz = quaternion.Y * quaternion.Z;
// float wx = quaternion.W * quaternion.X;
// float wy = quaternion.W * quaternion.Y;
// float wz = quaternion.W * quaternion.Z;
// // This calculation would be a lot more complicated for non-unit length quaternions
// // Note: The constructor of Matrix4 expects the Matrix in column-major format like expected by
// // OpenGL
// pMatrix[_M11] = 1.0f - 2.0f * (y2 + z2);
// pMatrix[_M12] = 2.0f * (xy - wz);
// pMatrix[_M13] = 2.0f * (xz + wy);
// pMatrix[_M14] = 0.0f;
// pMatrix[_M21] = 2.0f * (xy + wz);
// pMatrix[_M22] = 1.0f - 2.0f * (x2 + z2);
// pMatrix[_M23] = 2.0f * (yz - wx);
// pMatrix[_M24] = 0.0f;
// pMatrix[_M31] = 2.0f * (xz - wy);
// pMatrix[_M32] = 2.0f * (yz + wx);
// pMatrix[_M33] = 1.0f - 2.0f * (x2 + y2);
// pMatrix[_M34] = 0.0f;
// pMatrix[_M41] = 2.0f * (xz - wy);
// pMatrix[_M42] = 2.0f * (yz + wx);
// pMatrix[_M43] = 1.0f - 2.0f * (x2 + y2);
// pMatrix[_M44] = 0.0f;
// //return Matrix4( 1.0f - 2.0f * (y2 + z2), 2.0f * (xy - wz), 2.0f * (xz + wy), 0.0f,
// // 2.0f * (xy + wz), 1.0f - 2.0f * (x2 + z2), 2.0f * (yz - wx), 0.0f,
// // 2.0f * (xz - wy), 2.0f * (yz + wx), 1.0f - 2.0f * (x2 + y2), 0.0f,
// // 0.0f, 0.0f, 0.0f, 1.0f)
// // }
// }
// internal Vector3 Xyz
// {
// get{
// return new Vector3(X, Y, Z);
// }
// set{
// X = value.X;
// Y = value.Y;
// Z = value.Z;
// }
// }
}
Fsl::Quaternion operator/(const Fsl::Quaternion lhs, const Fsl::Quaternion& rhs)
{
const float x = lhs.X;
const float y = lhs.Y;
const float z = lhs.Z;
const float w = lhs.W;
const float num14 = (((rhs.X * rhs.X) + (rhs.Y * rhs.Y)) + (rhs.Z * rhs.Z)) + (rhs.W * rhs.W);
const float num5 = 1.0f / num14;
const float num4 = -rhs.X * num5;
const float num3 = -rhs.Y * num5;
const float num2 = -rhs.Z * num5;
const float num = rhs.W * num5;
const float num13 = (y * num2) - (z * num3);
const float num12 = (z * num4) - (x * num2);
const float num11 = (x * num3) - (y * num4);
const float num10 = ((x * num4) + (y * num3)) + (z * num2);
// Fsl::Quaternion quaternion(Fsl::OptimizationFlag::NoInitialization);
Fsl::Quaternion quaternion;
quaternion.X = ((x * num) + (num4 * w)) + num13;
quaternion.Y = ((y * num) + (num3 * w)) + num12;
quaternion.Z = ((z * num) + (num2 * w)) + num11;
quaternion.W = (w * num) - num10;
return quaternion;
}
Fsl::Quaternion operator*(const Fsl::Quaternion lhs, const Fsl::Quaternion& rhs)
{
const float x = lhs.X;
const float y = lhs.Y;
const float z = lhs.Z;
const float w = lhs.W;
const float num4 = rhs.X;
const float num3 = rhs.Y;
const float num2 = rhs.Z;
const float num = rhs.W;
const float num12 = (y * num2) - (z * num3);
const float num11 = (z * num4) - (x * num2);
const float num10 = (x * num3) - (y * num4);
const float num9 = ((x * num4) + (y * num3)) + (z * num2);
// Fsl::Quaternion quaternion(Fsl::OptimizationFlag::NoInitialization);
Fsl::Quaternion quaternion;
quaternion.X = ((x * num) + (num4 * w)) + num12;
quaternion.Y = ((y * num) + (num3 * w)) + num11;
quaternion.Z = ((z * num) + (num2 * w)) + num10;
quaternion.W = (w * num) - num9;
return quaternion;
}
| Unarmed1000/RAIIGen | source/FslBase/Math/Quaternion.cpp | C++ | bsd-3-clause | 29,575 |
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/views/view.h"
#include <algorithm>
#include "base/debug/trace_event.h"
#include "base/logging.h"
#include "base/memory/scoped_ptr.h"
#include "base/message_loop.h"
#include "base/stringprintf.h"
#include "base/utf_string_conversions.h"
#include "third_party/skia/include/core/SkRect.h"
#include "ui/base/accessibility/accessibility_types.h"
#include "ui/base/dragdrop/drag_drop_types.h"
#include "ui/compositor/compositor.h"
#include "ui/compositor/layer.h"
#include "ui/compositor/layer_animator.h"
#include "ui/gfx/canvas.h"
#include "ui/gfx/interpolated_transform.h"
#include "ui/gfx/path.h"
#include "ui/gfx/point3.h"
#include "ui/gfx/transform.h"
#include "ui/views/background.h"
#include "ui/views/context_menu_controller.h"
#include "ui/views/drag_controller.h"
#include "ui/views/layout/layout_manager.h"
#include "ui/views/views_delegate.h"
#include "ui/views/widget/native_widget_private.h"
#include "ui/views/widget/root_view.h"
#include "ui/views/widget/tooltip_manager.h"
#include "ui/views/widget/widget.h"
#if defined(OS_WIN)
#include "base/win/scoped_gdi_object.h"
#include "ui/views/accessibility/native_view_accessibility_win.h"
#endif
namespace {
// Whether to use accelerated compositing when necessary (e.g. when a view has a
// transformation).
#if defined(USE_AURA)
bool use_acceleration_when_possible = true;
#else
bool use_acceleration_when_possible = false;
#endif
// Saves the drawing state, and restores the state when going out of scope.
class ScopedCanvas {
public:
explicit ScopedCanvas(gfx::Canvas* canvas) : canvas_(canvas) {
if (canvas_)
canvas_->Save();
}
~ScopedCanvas() {
if (canvas_)
canvas_->Restore();
}
void SetCanvas(gfx::Canvas* canvas) {
if (canvas_)
canvas_->Restore();
canvas_ = canvas;
canvas_->Save();
}
private:
gfx::Canvas* canvas_;
DISALLOW_COPY_AND_ASSIGN(ScopedCanvas);
};
// Returns the top view in |view|'s hierarchy.
const views::View* GetHierarchyRoot(const views::View* view) {
const views::View* root = view;
while (root && root->parent())
root = root->parent();
return root;
}
} // namespace
namespace views {
// static
ViewsDelegate* ViewsDelegate::views_delegate = NULL;
// static
const char View::kViewClassName[] = "views/View";
////////////////////////////////////////////////////////////////////////////////
// View, public:
// Creation and lifetime -------------------------------------------------------
View::View()
: owned_by_client_(false),
id_(0),
group_(-1),
parent_(NULL),
visible_(true),
enabled_(true),
painting_enabled_(true),
notify_enter_exit_on_child_(false),
registered_for_visible_bounds_notification_(false),
clip_insets_(0, 0, 0, 0),
needs_layout_(true),
flip_canvas_on_paint_for_rtl_ui_(false),
paint_to_layer_(false),
accelerator_registration_delayed_(false),
accelerator_focus_manager_(NULL),
registered_accelerator_count_(0),
next_focusable_view_(NULL),
previous_focusable_view_(NULL),
focusable_(false),
accessibility_focusable_(false),
context_menu_controller_(NULL),
drag_controller_(NULL) {
}
View::~View() {
if (parent_)
parent_->RemoveChildView(this);
for (Views::const_iterator i(children_.begin()); i != children_.end(); ++i) {
(*i)->parent_ = NULL;
if (!(*i)->owned_by_client_)
delete *i;
}
#if defined(OS_WIN)
if (native_view_accessibility_win_.get())
native_view_accessibility_win_->set_view(NULL);
#endif
}
// Tree operations -------------------------------------------------------------
const Widget* View::GetWidget() const {
// The root view holds a reference to this view hierarchy's Widget.
return parent_ ? parent_->GetWidget() : NULL;
}
Widget* View::GetWidget() {
return const_cast<Widget*>(const_cast<const View*>(this)->GetWidget());
}
void View::AddChildView(View* view) {
if (view->parent_ == this)
return;
AddChildViewAt(view, child_count());
}
void View::AddChildViewAt(View* view, int index) {
CHECK_NE(view, this) << "You cannot add a view as its own child";
DCHECK_GE(index, 0);
DCHECK_LE(index, child_count());
// If |view| has a parent, remove it from its parent.
View* parent = view->parent_;
if (parent) {
if (parent == this) {
ReorderChildView(view, index);
return;
}
parent->RemoveChildView(view);
}
// Sets the prev/next focus views.
InitFocusSiblings(view, index);
// Let's insert the view.
view->parent_ = this;
children_.insert(children_.begin() + index, view);
for (View* v = this; v; v = v->parent_)
v->ViewHierarchyChangedImpl(false, true, this, view);
view->PropagateAddNotifications(this, view);
UpdateTooltip();
if (GetWidget())
RegisterChildrenForVisibleBoundsNotification(view);
if (layout_manager_.get())
layout_manager_->ViewAdded(this, view);
if (use_acceleration_when_possible)
ReorderLayers();
// Make sure the visibility of the child layers are correct.
// If any of the parent View is hidden, then the layers of the subtree
// rooted at |this| should be hidden. Otherwise, all the child layers should
// inherit the visibility of the owner View.
UpdateLayerVisibility();
}
void View::ReorderChildView(View* view, int index) {
DCHECK_EQ(view->parent_, this);
if (index < 0)
index = child_count() - 1;
else if (index >= child_count())
return;
if (children_[index] == view)
return;
const Views::iterator i(std::find(children_.begin(), children_.end(), view));
DCHECK(i != children_.end());
children_.erase(i);
// Unlink the view first
View* next_focusable = view->next_focusable_view_;
View* prev_focusable = view->previous_focusable_view_;
if (prev_focusable)
prev_focusable->next_focusable_view_ = next_focusable;
if (next_focusable)
next_focusable->previous_focusable_view_ = prev_focusable;
// Add it in the specified index now.
InitFocusSiblings(view, index);
children_.insert(children_.begin() + index, view);
if (use_acceleration_when_possible)
ReorderLayers();
}
void View::RemoveChildView(View* view) {
DoRemoveChildView(view, true, true, false);
}
void View::RemoveAllChildViews(bool delete_children) {
while (!children_.empty())
DoRemoveChildView(children_.front(), false, false, delete_children);
UpdateTooltip();
}
bool View::Contains(const View* view) const {
for (const View* v = view; v; v = v->parent_) {
if (v == this)
return true;
}
return false;
}
int View::GetIndexOf(const View* view) const {
Views::const_iterator i(std::find(children_.begin(), children_.end(), view));
return i != children_.end() ? static_cast<int>(i - children_.begin()) : -1;
}
// Size and disposition --------------------------------------------------------
void View::SetBounds(int x, int y, int width, int height) {
SetBoundsRect(gfx::Rect(x, y, std::max(0, width), std::max(0, height)));
}
void View::SetBoundsRect(const gfx::Rect& bounds) {
if (bounds == bounds_) {
if (needs_layout_) {
needs_layout_ = false;
Layout();
SchedulePaint();
}
return;
}
if (visible_) {
// Paint where the view is currently.
SchedulePaintBoundsChanged(
bounds_.size() == bounds.size() ? SCHEDULE_PAINT_SIZE_SAME :
SCHEDULE_PAINT_SIZE_CHANGED);
}
gfx::Rect prev = bounds_;
bounds_ = bounds;
BoundsChanged(prev);
}
void View::SetSize(const gfx::Size& size) {
SetBounds(x(), y(), size.width(), size.height());
}
void View::SetPosition(const gfx::Point& position) {
SetBounds(position.x(), position.y(), width(), height());
}
void View::SetX(int x) {
SetBounds(x, y(), width(), height());
}
void View::SetY(int y) {
SetBounds(x(), y, width(), height());
}
gfx::Rect View::GetContentsBounds() const {
gfx::Rect contents_bounds(GetLocalBounds());
if (border_.get()) {
gfx::Insets insets;
border_->GetInsets(&insets);
contents_bounds.Inset(insets);
}
return contents_bounds;
}
gfx::Rect View::GetLocalBounds() const {
return gfx::Rect(size());
}
gfx::Rect View::GetLayerBoundsInPixel() const {
return layer()->GetTargetBounds();
}
gfx::Insets View::GetInsets() const {
gfx::Insets insets;
if (border_.get())
border_->GetInsets(&insets);
return insets;
}
gfx::Rect View::GetVisibleBounds() const {
if (!IsDrawn())
return gfx::Rect();
gfx::Rect vis_bounds(GetLocalBounds());
gfx::Rect ancestor_bounds;
const View* view = this;
ui::Transform transform;
while (view != NULL && !vis_bounds.IsEmpty()) {
transform.ConcatTransform(view->GetTransform());
transform.ConcatTranslate(static_cast<float>(view->GetMirroredX()),
static_cast<float>(view->y()));
vis_bounds = view->ConvertRectToParent(vis_bounds);
const View* ancestor = view->parent_;
if (ancestor != NULL) {
ancestor_bounds.SetRect(0, 0, ancestor->width(), ancestor->height());
vis_bounds = vis_bounds.Intersect(ancestor_bounds);
} else if (!view->GetWidget()) {
// If the view has no Widget, we're not visible. Return an empty rect.
return gfx::Rect();
}
view = ancestor;
}
if (vis_bounds.IsEmpty())
return vis_bounds;
// Convert back to this views coordinate system.
transform.TransformRectReverse(&vis_bounds);
return vis_bounds;
}
gfx::Rect View::GetBoundsInScreen() const {
gfx::Point origin;
View::ConvertPointToScreen(this, &origin);
return gfx::Rect(origin, size());
}
gfx::Size View::GetPreferredSize() {
if (layout_manager_.get())
return layout_manager_->GetPreferredSize(this);
return gfx::Size();
}
int View::GetBaseline() const {
return -1;
}
void View::SizeToPreferredSize() {
gfx::Size prefsize = GetPreferredSize();
if ((prefsize.width() != width()) || (prefsize.height() != height()))
SetBounds(x(), y(), prefsize.width(), prefsize.height());
}
gfx::Size View::GetMinimumSize() {
return GetPreferredSize();
}
gfx::Size View::GetMaximumSize() {
return gfx::Size();
}
int View::GetHeightForWidth(int w) {
if (layout_manager_.get())
return layout_manager_->GetPreferredHeightForWidth(this, w);
return GetPreferredSize().height();
}
void View::SetVisible(bool visible) {
if (visible != visible_) {
// If the View is currently visible, schedule paint to refresh parent.
// TODO(beng): not sure we should be doing this if we have a layer.
if (visible_)
SchedulePaint();
visible_ = visible;
// Notify the parent.
if (parent_)
parent_->ChildVisibilityChanged(this);
// This notifies all sub-views recursively.
PropagateVisibilityNotifications(this, visible_);
UpdateLayerVisibility();
// If we are newly visible, schedule paint.
if (visible_)
SchedulePaint();
}
}
bool View::IsDrawn() const {
return visible_ && parent_ ? parent_->IsDrawn() : false;
}
void View::SetEnabled(bool enabled) {
if (enabled != enabled_) {
enabled_ = enabled;
OnEnabledChanged();
}
}
void View::OnEnabledChanged() {
SchedulePaint();
}
// Transformations -------------------------------------------------------------
const ui::Transform& View::GetTransform() const {
static const ui::Transform* no_op = new ui::Transform;
return layer() ? layer()->transform() : *no_op;
}
void View::SetTransform(const ui::Transform& transform) {
if (!transform.HasChange()) {
if (layer()) {
layer()->SetTransform(transform);
if (!paint_to_layer_)
DestroyLayer();
} else {
// Nothing.
}
} else {
if (!layer())
CreateLayer();
layer()->SetTransform(transform);
layer()->ScheduleDraw();
}
}
void View::SetPaintToLayer(bool paint_to_layer) {
paint_to_layer_ = paint_to_layer;
if (paint_to_layer_ && !layer()) {
CreateLayer();
} else if (!paint_to_layer_ && layer()) {
DestroyLayer();
}
}
ui::Layer* View::RecreateLayer() {
ui::Layer* layer = AcquireLayer();
if (!layer)
return NULL;
CreateLayer();
layer_->set_scale_content(layer->scale_content());
return layer;
}
// RTL positioning -------------------------------------------------------------
gfx::Rect View::GetMirroredBounds() const {
gfx::Rect bounds(bounds_);
bounds.set_x(GetMirroredX());
return bounds;
}
gfx::Point View::GetMirroredPosition() const {
return gfx::Point(GetMirroredX(), y());
}
int View::GetMirroredX() const {
return parent_ ? parent_->GetMirroredXForRect(bounds_) : x();
}
int View::GetMirroredXForRect(const gfx::Rect& bounds) const {
return base::i18n::IsRTL() ?
(width() - bounds.x() - bounds.width()) : bounds.x();
}
int View::GetMirroredXInView(int x) const {
return base::i18n::IsRTL() ? width() - x : x;
}
int View::GetMirroredXWithWidthInView(int x, int w) const {
return base::i18n::IsRTL() ? width() - x - w : x;
}
// Layout ----------------------------------------------------------------------
void View::Layout() {
needs_layout_ = false;
// If we have a layout manager, let it handle the layout for us.
if (layout_manager_.get())
layout_manager_->Layout(this);
// Make sure to propagate the Layout() call to any children that haven't
// received it yet through the layout manager and need to be laid out. This
// is needed for the case when the child requires a layout but its bounds
// weren't changed by the layout manager. If there is no layout manager, we
// just propagate the Layout() call down the hierarchy, so whoever receives
// the call can take appropriate action.
for (int i = 0, count = child_count(); i < count; ++i) {
View* child = child_at(i);
if (child->needs_layout_ || !layout_manager_.get()) {
child->needs_layout_ = false;
child->Layout();
}
}
}
void View::InvalidateLayout() {
// Always invalidate up. This is needed to handle the case of us already being
// valid, but not our parent.
needs_layout_ = true;
if (parent_)
parent_->InvalidateLayout();
}
LayoutManager* View::GetLayoutManager() const {
return layout_manager_.get();
}
void View::SetLayoutManager(LayoutManager* layout_manager) {
if (layout_manager_.get())
layout_manager_->Uninstalled(this);
layout_manager_.reset(layout_manager);
if (layout_manager_.get())
layout_manager_->Installed(this);
}
// Attributes ------------------------------------------------------------------
std::string View::GetClassName() const {
return kViewClassName;
}
View* View::GetAncestorWithClassName(const std::string& name) {
for (View* view = this; view; view = view->parent_) {
if (view->GetClassName() == name)
return view;
}
return NULL;
}
const View* View::GetViewByID(int id) const {
if (id == id_)
return const_cast<View*>(this);
for (int i = 0, count = child_count(); i < count; ++i) {
const View* view = child_at(i)->GetViewByID(id);
if (view)
return view;
}
return NULL;
}
View* View::GetViewByID(int id) {
return const_cast<View*>(const_cast<const View*>(this)->GetViewByID(id));
}
void View::SetGroup(int gid) {
// Don't change the group id once it's set.
DCHECK(group_ == -1 || group_ == gid);
group_ = gid;
}
int View::GetGroup() const {
return group_;
}
bool View::IsGroupFocusTraversable() const {
return true;
}
void View::GetViewsInGroup(int group, Views* views) {
if (group_ == group)
views->push_back(this);
for (int i = 0, count = child_count(); i < count; ++i)
child_at(i)->GetViewsInGroup(group, views);
}
View* View::GetSelectedViewForGroup(int group) {
Views views;
GetWidget()->GetRootView()->GetViewsInGroup(group, &views);
return views.empty() ? NULL : views[0];
}
// Coordinate conversion -------------------------------------------------------
// static
void View::ConvertPointToView(const View* source,
const View* target,
gfx::Point* point) {
if (source == target)
return;
// |source| can be NULL.
const View* root = GetHierarchyRoot(target);
if (source) {
CHECK_EQ(GetHierarchyRoot(source), root);
if (source != root)
source->ConvertPointForAncestor(root, point);
}
if (target != root)
target->ConvertPointFromAncestor(root, point);
// API defines NULL |source| as returning the point in screen coordinates.
if (!source) {
*point = point->Subtract(
root->GetWidget()->GetClientAreaBoundsInScreen().origin());
}
}
// static
void View::ConvertPointToWidget(const View* src, gfx::Point* p) {
DCHECK(src);
DCHECK(p);
src->ConvertPointForAncestor(NULL, p);
}
// static
void View::ConvertPointFromWidget(const View* dest, gfx::Point* p) {
DCHECK(dest);
DCHECK(p);
dest->ConvertPointFromAncestor(NULL, p);
}
// static
void View::ConvertPointToScreen(const View* src, gfx::Point* p) {
DCHECK(src);
DCHECK(p);
// If the view is not connected to a tree, there's nothing we can do.
const Widget* widget = src->GetWidget();
if (widget) {
ConvertPointToWidget(src, p);
gfx::Rect r = widget->GetClientAreaBoundsInScreen();
p->SetPoint(p->x() + r.x(), p->y() + r.y());
}
}
// static
void View::ConvertPointFromScreen(const View* dst, gfx::Point* p) {
DCHECK(dst);
DCHECK(p);
const views::Widget* widget = dst->GetWidget();
if (!widget)
return;
const gfx::Rect r = widget->GetClientAreaBoundsInScreen();
p->Offset(-r.x(), -r.y());
views::View::ConvertPointFromWidget(dst, p);
}
gfx::Rect View::ConvertRectToParent(const gfx::Rect& rect) const {
gfx::Rect x_rect = rect;
GetTransform().TransformRect(&x_rect);
x_rect.Offset(GetMirroredPosition());
return x_rect;
}
gfx::Rect View::ConvertRectToWidget(const gfx::Rect& rect) const {
gfx::Rect x_rect = rect;
for (const View* v = this; v; v = v->parent_)
x_rect = v->ConvertRectToParent(x_rect);
return x_rect;
}
// Painting --------------------------------------------------------------------
void View::SchedulePaint() {
SchedulePaintInRect(GetLocalBounds());
}
void View::SchedulePaintInRect(const gfx::Rect& rect) {
if (!visible_ || !painting_enabled_)
return;
if (layer()) {
layer()->SchedulePaint(rect);
} else if (parent_) {
// Translate the requested paint rect to the parent's coordinate system
// then pass this notification up to the parent.
parent_->SchedulePaintInRect(ConvertRectToParent(rect));
}
}
void View::Paint(gfx::Canvas* canvas) {
TRACE_EVENT0("views", "View::Paint");
ScopedCanvas scoped_canvas(canvas);
// Paint this View and its children, setting the clip rect to the bounds
// of this View and translating the origin to the local bounds' top left
// point.
//
// Note that the X (or left) position we pass to ClipRectInt takes into
// consideration whether or not the view uses a right-to-left layout so that
// we paint our view in its mirrored position if need be.
gfx::Rect clip_rect = bounds();
clip_rect.Inset(clip_insets_);
if (parent_)
clip_rect.set_x(parent_->GetMirroredXForRect(clip_rect));
if (!canvas->ClipRect(clip_rect))
return;
// Non-empty clip, translate the graphics such that 0,0 corresponds to
// where this view is located (related to its parent).
canvas->Translate(GetMirroredPosition());
canvas->Transform(GetTransform());
PaintCommon(canvas);
}
ThemeProvider* View::GetThemeProvider() const {
const Widget* widget = GetWidget();
return widget ? widget->GetThemeProvider() : NULL;
}
// Accelerated Painting --------------------------------------------------------
// static
void View::set_use_acceleration_when_possible(bool use) {
use_acceleration_when_possible = use;
}
// static
bool View::get_use_acceleration_when_possible() {
return use_acceleration_when_possible;
}
// Input -----------------------------------------------------------------------
View* View::GetEventHandlerForPoint(const gfx::Point& point) {
// Walk the child Views recursively looking for the View that most
// tightly encloses the specified point.
for (int i = child_count() - 1; i >= 0; --i) {
View* child = child_at(i);
if (!child->visible())
continue;
gfx::Point point_in_child_coords(point);
View::ConvertPointToView(this, child, &point_in_child_coords);
if (child->HitTest(point_in_child_coords))
return child->GetEventHandlerForPoint(point_in_child_coords);
}
return this;
}
gfx::NativeCursor View::GetCursor(const MouseEvent& event) {
#if defined(OS_WIN) && !defined(USE_AURA)
static HCURSOR arrow = LoadCursor(NULL, IDC_ARROW);
return arrow;
#else
return gfx::kNullCursor;
#endif
}
bool View::HitTest(const gfx::Point& l) const {
if (GetLocalBounds().Contains(l)) {
if (HasHitTestMask()) {
gfx::Path mask;
GetHitTestMask(&mask);
#if defined(USE_AURA)
// TODO: should we use this every where?
SkRegion clip_region;
clip_region.setRect(0, 0, width(), height());
SkRegion mask_region;
return mask_region.setPath(mask, clip_region) &&
mask_region.contains(l.x(), l.y());
#elif defined(OS_WIN)
base::win::ScopedRegion rgn(mask.CreateNativeRegion());
return !!PtInRegion(rgn, l.x(), l.y());
#endif
}
// No mask, but inside our bounds.
return true;
}
// Outside our bounds.
return false;
}
bool View::OnMousePressed(const MouseEvent& event) {
return false;
}
bool View::OnMouseDragged(const MouseEvent& event) {
return false;
}
void View::OnMouseReleased(const MouseEvent& event) {
}
void View::OnMouseCaptureLost() {
}
void View::OnMouseMoved(const MouseEvent& event) {
}
void View::OnMouseEntered(const MouseEvent& event) {
}
void View::OnMouseExited(const MouseEvent& event) {
}
ui::TouchStatus View::OnTouchEvent(const TouchEvent& event) {
return ui::TOUCH_STATUS_UNKNOWN;
}
ui::GestureStatus View::OnGestureEvent(const GestureEvent& event) {
return ui::GESTURE_STATUS_UNKNOWN;
}
void View::SetMouseHandler(View* new_mouse_handler) {
// |new_mouse_handler| may be NULL.
if (parent_)
parent_->SetMouseHandler(new_mouse_handler);
}
bool View::OnKeyPressed(const KeyEvent& event) {
return false;
}
bool View::OnKeyReleased(const KeyEvent& event) {
return false;
}
bool View::OnMouseWheel(const MouseWheelEvent& event) {
return false;
}
bool View::OnScrollEvent(const ScrollEvent& event) {
return false;
}
ui::TextInputClient* View::GetTextInputClient() {
return NULL;
}
InputMethod* View::GetInputMethod() {
Widget* widget = GetWidget();
return widget ? widget->GetInputMethod() : NULL;
}
// Accelerators ----------------------------------------------------------------
void View::AddAccelerator(const ui::Accelerator& accelerator) {
if (!accelerators_.get())
accelerators_.reset(new std::vector<ui::Accelerator>());
if (std::find(accelerators_->begin(), accelerators_->end(), accelerator) ==
accelerators_->end()) {
accelerators_->push_back(accelerator);
}
RegisterPendingAccelerators();
}
void View::RemoveAccelerator(const ui::Accelerator& accelerator) {
if (!accelerators_.get()) {
NOTREACHED() << "Removing non-existing accelerator";
return;
}
std::vector<ui::Accelerator>::iterator i(
std::find(accelerators_->begin(), accelerators_->end(), accelerator));
if (i == accelerators_->end()) {
NOTREACHED() << "Removing non-existing accelerator";
return;
}
size_t index = i - accelerators_->begin();
accelerators_->erase(i);
if (index >= registered_accelerator_count_) {
// The accelerator is not registered to FocusManager.
return;
}
--registered_accelerator_count_;
// Providing we are attached to a Widget and registered with a focus manager,
// we should de-register from that focus manager now.
if (GetWidget() && accelerator_focus_manager_)
accelerator_focus_manager_->UnregisterAccelerator(accelerator, this);
}
void View::ResetAccelerators() {
if (accelerators_.get())
UnregisterAccelerators(false);
}
bool View::AcceleratorPressed(const ui::Accelerator& accelerator) {
return false;
}
bool View::CanHandleAccelerators() const {
return enabled() && IsDrawn() && GetWidget() && GetWidget()->IsVisible();
}
// Focus -----------------------------------------------------------------------
bool View::HasFocus() const {
const FocusManager* focus_manager = GetFocusManager();
return focus_manager && (focus_manager->GetFocusedView() == this);
}
View* View::GetNextFocusableView() {
return next_focusable_view_;
}
const View* View::GetNextFocusableView() const {
return next_focusable_view_;
}
View* View::GetPreviousFocusableView() {
return previous_focusable_view_;
}
void View::SetNextFocusableView(View* view) {
if (view)
view->previous_focusable_view_ = this;
next_focusable_view_ = view;
}
bool View::IsFocusable() const {
return focusable_ && enabled_ && IsDrawn();
}
bool View::IsAccessibilityFocusable() const {
return (focusable_ || accessibility_focusable_) && enabled_ && IsDrawn();
}
FocusManager* View::GetFocusManager() {
Widget* widget = GetWidget();
return widget ? widget->GetFocusManager() : NULL;
}
const FocusManager* View::GetFocusManager() const {
const Widget* widget = GetWidget();
return widget ? widget->GetFocusManager() : NULL;
}
void View::RequestFocus() {
FocusManager* focus_manager = GetFocusManager();
if (focus_manager && IsFocusable())
focus_manager->SetFocusedView(this);
}
bool View::SkipDefaultKeyEventProcessing(const KeyEvent& event) {
return false;
}
FocusTraversable* View::GetFocusTraversable() {
return NULL;
}
FocusTraversable* View::GetPaneFocusTraversable() {
return NULL;
}
// Tooltips --------------------------------------------------------------------
bool View::GetTooltipText(const gfx::Point& p, string16* tooltip) const {
return false;
}
bool View::GetTooltipTextOrigin(const gfx::Point& p, gfx::Point* loc) const {
return false;
}
// Context menus ---------------------------------------------------------------
void View::ShowContextMenu(const gfx::Point& p, bool is_mouse_gesture) {
if (!context_menu_controller_)
return;
context_menu_controller_->ShowContextMenuForView(this, p);
}
// Drag and drop ---------------------------------------------------------------
bool View::GetDropFormats(
int* formats,
std::set<OSExchangeData::CustomFormat>* custom_formats) {
return false;
}
bool View::AreDropTypesRequired() {
return false;
}
bool View::CanDrop(const OSExchangeData& data) {
// TODO(sky): when I finish up migration, this should default to true.
return false;
}
void View::OnDragEntered(const DropTargetEvent& event) {
}
int View::OnDragUpdated(const DropTargetEvent& event) {
return ui::DragDropTypes::DRAG_NONE;
}
void View::OnDragExited() {
}
int View::OnPerformDrop(const DropTargetEvent& event) {
return ui::DragDropTypes::DRAG_NONE;
}
void View::OnDragDone() {
}
// static
bool View::ExceededDragThreshold(int delta_x, int delta_y) {
return (abs(delta_x) > GetHorizontalDragThreshold() ||
abs(delta_y) > GetVerticalDragThreshold());
}
// Scrolling -------------------------------------------------------------------
void View::ScrollRectToVisible(const gfx::Rect& rect) {
// We must take RTL UI mirroring into account when adjusting the position of
// the region.
if (parent_) {
gfx::Rect scroll_rect(rect);
scroll_rect.Offset(GetMirroredX(), y());
parent_->ScrollRectToVisible(scroll_rect);
}
}
int View::GetPageScrollIncrement(ScrollView* scroll_view,
bool is_horizontal, bool is_positive) {
return 0;
}
int View::GetLineScrollIncrement(ScrollView* scroll_view,
bool is_horizontal, bool is_positive) {
return 0;
}
////////////////////////////////////////////////////////////////////////////////
// View, protected:
// Size and disposition --------------------------------------------------------
void View::OnBoundsChanged(const gfx::Rect& previous_bounds) {
}
void View::PreferredSizeChanged() {
InvalidateLayout();
if (parent_)
parent_->ChildPreferredSizeChanged(this);
}
bool View::NeedsNotificationWhenVisibleBoundsChange() const {
return false;
}
void View::OnVisibleBoundsChanged() {
}
// Tree operations -------------------------------------------------------------
void View::ViewHierarchyChanged(bool is_add, View* parent, View* child) {
}
void View::VisibilityChanged(View* starting_from, bool is_visible) {
}
void View::NativeViewHierarchyChanged(bool attached,
gfx::NativeView native_view,
internal::RootView* root_view) {
FocusManager* focus_manager = GetFocusManager();
if (!accelerator_registration_delayed_ &&
accelerator_focus_manager_ &&
accelerator_focus_manager_ != focus_manager) {
UnregisterAccelerators(true);
accelerator_registration_delayed_ = true;
}
if (accelerator_registration_delayed_ && attached) {
if (focus_manager) {
RegisterPendingAccelerators();
accelerator_registration_delayed_ = false;
}
}
}
// Painting --------------------------------------------------------------------
void View::PaintChildren(gfx::Canvas* canvas) {
TRACE_EVENT0("views", "View::PaintChildren");
for (int i = 0, count = child_count(); i < count; ++i)
if (!child_at(i)->layer())
child_at(i)->Paint(canvas);
}
void View::OnPaint(gfx::Canvas* canvas) {
TRACE_EVENT0("views", "View::OnPaint");
OnPaintBackground(canvas);
OnPaintFocusBorder(canvas);
OnPaintBorder(canvas);
}
void View::OnPaintBackground(gfx::Canvas* canvas) {
if (background_.get()) {
TRACE_EVENT2("views", "View::OnPaintBackground",
"width", canvas->sk_canvas()->getDevice()->width(),
"height", canvas->sk_canvas()->getDevice()->height());
background_->Paint(canvas, this);
}
}
void View::OnPaintBorder(gfx::Canvas* canvas) {
if (border_.get()) {
TRACE_EVENT2("views", "View::OnPaintBorder",
"width", canvas->sk_canvas()->getDevice()->width(),
"height", canvas->sk_canvas()->getDevice()->height());
border_->Paint(*this, canvas);
}
}
void View::OnPaintFocusBorder(gfx::Canvas* canvas) {
if (HasFocus() && (focusable() || IsAccessibilityFocusable())) {
TRACE_EVENT2("views", "views::OnPaintFocusBorder",
"width", canvas->sk_canvas()->getDevice()->width(),
"height", canvas->sk_canvas()->getDevice()->height());
canvas->DrawFocusRect(GetLocalBounds());
}
}
// Accelerated Painting --------------------------------------------------------
void View::SetFillsBoundsOpaquely(bool fills_bounds_opaquely) {
// This method should not have the side-effect of creating the layer.
if (layer())
layer()->SetFillsBoundsOpaquely(fills_bounds_opaquely);
}
bool View::SetExternalTexture(ui::Texture* texture) {
DCHECK(texture);
SetPaintToLayer(true);
layer()->SetExternalTexture(texture);
// Child views must not paint into the external texture. So make sure each
// child view has its own layer to paint into.
for (Views::iterator i = children_.begin(); i != children_.end(); ++i)
(*i)->SetPaintToLayer(true);
SchedulePaintInRect(GetLocalBounds());
return true;
}
void View::CalculateOffsetToAncestorWithLayer(gfx::Point* offset,
ui::Layer** layer_parent) {
if (layer()) {
if (layer_parent)
*layer_parent = layer();
return;
}
if (!parent_)
return;
offset->Offset(GetMirroredX(), y());
parent_->CalculateOffsetToAncestorWithLayer(offset, layer_parent);
}
void View::MoveLayerToParent(ui::Layer* parent_layer,
const gfx::Point& point) {
gfx::Point local_point(point);
if (parent_layer != layer())
local_point.Offset(GetMirroredX(), y());
if (layer() && parent_layer != layer()) {
parent_layer->Add(layer());
SetLayerBounds(gfx::Rect(local_point.x(), local_point.y(),
width(), height()));
} else {
for (int i = 0, count = child_count(); i < count; ++i)
child_at(i)->MoveLayerToParent(parent_layer, local_point);
}
}
void View::UpdateLayerVisibility() {
if (!use_acceleration_when_possible)
return;
bool visible = visible_;
for (const View* v = parent_; visible && v && !v->layer(); v = v->parent_)
visible = v->visible();
UpdateChildLayerVisibility(visible);
}
void View::UpdateChildLayerVisibility(bool ancestor_visible) {
if (layer()) {
layer()->SetVisible(ancestor_visible && visible_);
} else {
for (int i = 0, count = child_count(); i < count; ++i)
child_at(i)->UpdateChildLayerVisibility(ancestor_visible && visible_);
}
}
void View::UpdateChildLayerBounds(const gfx::Point& offset) {
if (layer()) {
SetLayerBounds(gfx::Rect(offset.x(), offset.y(), width(), height()));
} else {
for (int i = 0, count = child_count(); i < count; ++i) {
gfx::Point new_offset(offset.x() + child_at(i)->GetMirroredX(),
offset.y() + child_at(i)->y());
child_at(i)->UpdateChildLayerBounds(new_offset);
}
}
}
void View::OnPaintLayer(gfx::Canvas* canvas) {
if (!layer() || !layer()->fills_bounds_opaquely())
canvas->DrawColor(SK_ColorBLACK, SkXfermode::kClear_Mode);
PaintCommon(canvas);
}
void View::OnDeviceScaleFactorChanged(float device_scale_factor) {
// Repainting with new scale factor will paint the content at the right scale.
}
base::Closure View::PrepareForLayerBoundsChange() {
return base::Closure();
}
void View::ReorderLayers() {
View* v = this;
while (v && !v->layer())
v = v->parent();
// Forward to widget in case we're in a NativeWidgetAura.
if (!v) {
if (GetWidget())
GetWidget()->ReorderLayers();
} else {
for (Views::const_iterator i(v->children_.begin());
i != v->children_.end();
++i)
(*i)->ReorderChildLayers(v->layer());
}
}
void View::ReorderChildLayers(ui::Layer* parent_layer) {
if (layer()) {
DCHECK_EQ(parent_layer, layer()->parent());
parent_layer->StackAtTop(layer());
} else {
for (Views::const_iterator i(children_.begin()); i != children_.end(); ++i)
(*i)->ReorderChildLayers(parent_layer);
}
}
// Input -----------------------------------------------------------------------
bool View::HasHitTestMask() const {
return false;
}
void View::GetHitTestMask(gfx::Path* mask) const {
DCHECK(mask);
}
// Focus -----------------------------------------------------------------------
void View::OnFocus() {
// TODO(beng): Investigate whether it's possible for us to move this to
// Focus().
// By default, we clear the native focus. This ensures that no visible native
// view as the focus and that we still receive keyboard inputs.
FocusManager* focus_manager = GetFocusManager();
if (focus_manager)
focus_manager->ClearNativeFocus();
// TODO(beng): Investigate whether it's possible for us to move this to
// Focus().
// Notify assistive technologies of the focus change.
GetWidget()->NotifyAccessibilityEvent(
this, ui::AccessibilityTypes::EVENT_FOCUS, true);
}
void View::OnBlur() {
}
void View::Focus() {
SchedulePaint();
OnFocus();
}
void View::Blur() {
SchedulePaint();
OnBlur();
}
// Tooltips --------------------------------------------------------------------
void View::TooltipTextChanged() {
Widget* widget = GetWidget();
// TooltipManager may be null if there is a problem creating it.
if (widget && widget->native_widget_private()->GetTooltipManager()) {
widget->native_widget_private()->GetTooltipManager()->
TooltipTextChanged(this);
}
}
// Context menus ---------------------------------------------------------------
gfx::Point View::GetKeyboardContextMenuLocation() {
gfx::Rect vis_bounds = GetVisibleBounds();
gfx::Point screen_point(vis_bounds.x() + vis_bounds.width() / 2,
vis_bounds.y() + vis_bounds.height() / 2);
ConvertPointToScreen(this, &screen_point);
return screen_point;
}
// Drag and drop ---------------------------------------------------------------
int View::GetDragOperations(const gfx::Point& press_pt) {
return drag_controller_ ?
drag_controller_->GetDragOperationsForView(this, press_pt) :
ui::DragDropTypes::DRAG_NONE;
}
void View::WriteDragData(const gfx::Point& press_pt, OSExchangeData* data) {
DCHECK(drag_controller_);
drag_controller_->WriteDragDataForView(this, press_pt, data);
}
bool View::InDrag() {
Widget* widget = GetWidget();
return widget ? widget->dragged_view() == this : false;
}
// Debugging -------------------------------------------------------------------
#if !defined(NDEBUG)
std::string View::PrintViewGraph(bool first) {
return DoPrintViewGraph(first, this);
}
std::string View::DoPrintViewGraph(bool first, View* view_with_children) {
// 64-bit pointer = 16 bytes of hex + "0x" + '\0' = 19.
const size_t kMaxPointerStringLength = 19;
std::string result;
if (first)
result.append("digraph {\n");
// Node characteristics.
char p[kMaxPointerStringLength];
size_t baseNameIndex = GetClassName().find_last_of('/');
if (baseNameIndex == std::string::npos)
baseNameIndex = 0;
else
baseNameIndex++;
char bounds_buffer[512];
// Information about current node.
base::snprintf(p, arraysize(bounds_buffer), "%p", view_with_children);
result.append(" N");
result.append(p+2);
result.append(" [label=\"");
result.append(GetClassName().substr(baseNameIndex).c_str());
base::snprintf(bounds_buffer,
arraysize(bounds_buffer),
"\\n bounds: (%d, %d), (%dx%d)",
this->bounds().x(),
this->bounds().y(),
this->bounds().width(),
this->bounds().height());
result.append(bounds_buffer);
if (GetTransform().HasChange()) {
gfx::Point translation;
float rotation;
gfx::Point3f scale;
if (ui::InterpolatedTransform::FactorTRS(GetTransform(),
&translation,
&rotation,
&scale)) {
if (translation != gfx::Point(0, 0)) {
base::snprintf(bounds_buffer,
arraysize(bounds_buffer),
"\\n translation: (%d, %d)",
translation.x(),
translation.y());
result.append(bounds_buffer);
}
if (fabs(rotation) > 1e-5) {
base::snprintf(bounds_buffer,
arraysize(bounds_buffer),
"\\n rotation: %3.2f", rotation);
result.append(bounds_buffer);
}
if (scale.AsPoint() != gfx::Point(0, 0)) {
base::snprintf(bounds_buffer,
arraysize(bounds_buffer),
"\\n scale: (%2.4f, %2.4f)",
scale.x(),
scale.y());
result.append(bounds_buffer);
}
}
}
result.append("\"");
if (!parent_)
result.append(", shape=box");
if (layer()) {
if (layer()->texture())
result.append(", color=green");
else
result.append(", color=red");
if (layer()->fills_bounds_opaquely())
result.append(", style=filled");
}
result.append("]\n");
// Link to parent.
if (parent_) {
char pp[kMaxPointerStringLength];
base::snprintf(pp, kMaxPointerStringLength, "%p", parent_);
result.append(" N");
result.append(pp+2);
result.append(" -> N");
result.append(p+2);
result.append("\n");
}
// Children.
for (int i = 0, count = view_with_children->child_count(); i < count; ++i)
result.append(view_with_children->child_at(i)->PrintViewGraph(false));
if (first)
result.append("}\n");
return result;
}
#endif
////////////////////////////////////////////////////////////////////////////////
// View, private:
// DropInfo --------------------------------------------------------------------
void View::DragInfo::Reset() {
possible_drag = false;
start_pt = gfx::Point();
}
void View::DragInfo::PossibleDrag(const gfx::Point& p) {
possible_drag = true;
start_pt = p;
}
// Painting --------------------------------------------------------------------
void View::SchedulePaintBoundsChanged(SchedulePaintType type) {
// If we have a layer and the View's size did not change, we do not need to
// schedule any paints since the layer will be redrawn at its new location
// during the next Draw() cycle in the compositor.
if (!layer() || type == SCHEDULE_PAINT_SIZE_CHANGED) {
// Otherwise, if the size changes or we don't have a layer then we need to
// use SchedulePaint to invalidate the area occupied by the View.
SchedulePaint();
} else if (parent_ && type == SCHEDULE_PAINT_SIZE_SAME) {
// The compositor doesn't Draw() until something on screen changes, so
// if our position changes but nothing is being animated on screen, then
// tell the compositor to redraw the scene. We know layer() exists due to
// the above if clause.
layer()->ScheduleDraw();
}
}
void View::PaintCommon(gfx::Canvas* canvas) {
if (!visible_ || !painting_enabled_)
return;
{
// If the View we are about to paint requested the canvas to be flipped, we
// should change the transform appropriately.
// The canvas mirroring is undone once the View is done painting so that we
// don't pass the canvas with the mirrored transform to Views that didn't
// request the canvas to be flipped.
ScopedCanvas scoped(canvas);
if (FlipCanvasOnPaintForRTLUI()) {
canvas->Translate(gfx::Point(width(), 0));
canvas->Scale(-1, 1);
}
OnPaint(canvas);
}
PaintChildren(canvas);
}
// Tree operations -------------------------------------------------------------
void View::DoRemoveChildView(View* view,
bool update_focus_cycle,
bool update_tool_tip,
bool delete_removed_view) {
DCHECK(view);
const Views::iterator i(std::find(children_.begin(), children_.end(), view));
scoped_ptr<View> view_to_be_deleted;
if (i != children_.end()) {
if (update_focus_cycle) {
// Let's remove the view from the focus traversal.
View* next_focusable = view->next_focusable_view_;
View* prev_focusable = view->previous_focusable_view_;
if (prev_focusable)
prev_focusable->next_focusable_view_ = next_focusable;
if (next_focusable)
next_focusable->previous_focusable_view_ = prev_focusable;
}
if (GetWidget())
UnregisterChildrenForVisibleBoundsNotification(view);
view->PropagateRemoveNotifications(this);
view->parent_ = NULL;
view->UpdateLayerVisibility();
if (delete_removed_view && !view->owned_by_client_)
view_to_be_deleted.reset(view);
children_.erase(i);
}
if (update_tool_tip)
UpdateTooltip();
if (layout_manager_.get())
layout_manager_->ViewRemoved(this, view);
}
void View::PropagateRemoveNotifications(View* parent) {
for (int i = 0, count = child_count(); i < count; ++i)
child_at(i)->PropagateRemoveNotifications(parent);
for (View* v = this; v; v = v->parent_)
v->ViewHierarchyChangedImpl(true, false, parent, this);
}
void View::PropagateAddNotifications(View* parent, View* child) {
for (int i = 0, count = child_count(); i < count; ++i)
child_at(i)->PropagateAddNotifications(parent, child);
ViewHierarchyChangedImpl(true, true, parent, child);
}
void View::PropagateNativeViewHierarchyChanged(bool attached,
gfx::NativeView native_view,
internal::RootView* root_view) {
for (int i = 0, count = child_count(); i < count; ++i)
child_at(i)->PropagateNativeViewHierarchyChanged(attached,
native_view,
root_view);
NativeViewHierarchyChanged(attached, native_view, root_view);
}
void View::ViewHierarchyChangedImpl(bool register_accelerators,
bool is_add,
View* parent,
View* child) {
if (register_accelerators) {
if (is_add) {
// If you get this registration, you are part of a subtree that has been
// added to the view hierarchy.
if (GetFocusManager()) {
RegisterPendingAccelerators();
} else {
// Delay accelerator registration until visible as we do not have
// focus manager until then.
accelerator_registration_delayed_ = true;
}
} else {
if (child == this)
UnregisterAccelerators(true);
}
}
if (is_add && layer() && !layer()->parent()) {
UpdateParentLayer();
Widget* widget = GetWidget();
if (widget)
widget->UpdateRootLayers();
} else if (!is_add && child == this) {
// Make sure the layers beloning to the subtree rooted at |child| get
// removed from layers that do not belong in the same subtree.
OrphanLayers();
if (use_acceleration_when_possible) {
Widget* widget = GetWidget();
if (widget)
widget->UpdateRootLayers();
}
}
ViewHierarchyChanged(is_add, parent, child);
parent->needs_layout_ = true;
}
// Size and disposition --------------------------------------------------------
void View::PropagateVisibilityNotifications(View* start, bool is_visible) {
for (int i = 0, count = child_count(); i < count; ++i)
child_at(i)->PropagateVisibilityNotifications(start, is_visible);
VisibilityChangedImpl(start, is_visible);
}
void View::VisibilityChangedImpl(View* starting_from, bool is_visible) {
VisibilityChanged(starting_from, is_visible);
}
void View::BoundsChanged(const gfx::Rect& previous_bounds) {
if (visible_) {
// Paint the new bounds.
SchedulePaintBoundsChanged(
bounds_.size() == previous_bounds.size() ? SCHEDULE_PAINT_SIZE_SAME :
SCHEDULE_PAINT_SIZE_CHANGED);
}
if (use_acceleration_when_possible) {
if (layer()) {
if (parent_) {
gfx::Point offset;
parent_->CalculateOffsetToAncestorWithLayer(&offset, NULL);
offset.Offset(GetMirroredX(), y());
SetLayerBounds(gfx::Rect(offset, size()));
} else {
SetLayerBounds(bounds_);
}
// TODO(beng): this seems redundant with the SchedulePaint at the top of
// this function. explore collapsing.
if (previous_bounds.size() != bounds_.size() &&
!layer()->layer_updated_externally()) {
// If our bounds have changed then we need to update the complete
// texture.
layer()->SchedulePaint(GetLocalBounds());
}
} else {
// If our bounds have changed, then any descendant layer bounds may
// have changed. Update them accordingly.
gfx::Point offset;
CalculateOffsetToAncestorWithLayer(&offset, NULL);
UpdateChildLayerBounds(offset);
}
}
OnBoundsChanged(previous_bounds);
if (previous_bounds.size() != size()) {
needs_layout_ = false;
Layout();
}
if (NeedsNotificationWhenVisibleBoundsChange())
OnVisibleBoundsChanged();
// Notify interested Views that visible bounds within the root view may have
// changed.
if (descendants_to_notify_.get()) {
for (Views::iterator i(descendants_to_notify_->begin());
i != descendants_to_notify_->end(); ++i) {
(*i)->OnVisibleBoundsChanged();
}
}
}
// static
void View::RegisterChildrenForVisibleBoundsNotification(View* view) {
if (view->NeedsNotificationWhenVisibleBoundsChange())
view->RegisterForVisibleBoundsNotification();
for (int i = 0; i < view->child_count(); ++i)
RegisterChildrenForVisibleBoundsNotification(view->child_at(i));
}
// static
void View::UnregisterChildrenForVisibleBoundsNotification(View* view) {
if (view->NeedsNotificationWhenVisibleBoundsChange())
view->UnregisterForVisibleBoundsNotification();
for (int i = 0; i < view->child_count(); ++i)
UnregisterChildrenForVisibleBoundsNotification(view->child_at(i));
}
void View::RegisterForVisibleBoundsNotification() {
if (registered_for_visible_bounds_notification_)
return;
registered_for_visible_bounds_notification_ = true;
for (View* ancestor = parent_; ancestor; ancestor = ancestor->parent_)
ancestor->AddDescendantToNotify(this);
}
void View::UnregisterForVisibleBoundsNotification() {
if (!registered_for_visible_bounds_notification_)
return;
registered_for_visible_bounds_notification_ = false;
for (View* ancestor = parent_; ancestor; ancestor = ancestor->parent_)
ancestor->RemoveDescendantToNotify(this);
}
void View::AddDescendantToNotify(View* view) {
DCHECK(view);
if (!descendants_to_notify_.get())
descendants_to_notify_.reset(new Views);
descendants_to_notify_->push_back(view);
}
void View::RemoveDescendantToNotify(View* view) {
DCHECK(view && descendants_to_notify_.get());
Views::iterator i(std::find(
descendants_to_notify_->begin(), descendants_to_notify_->end(), view));
DCHECK(i != descendants_to_notify_->end());
descendants_to_notify_->erase(i);
if (descendants_to_notify_->empty())
descendants_to_notify_.reset();
}
void View::SetLayerBounds(const gfx::Rect& bounds) {
layer()->SetBounds(bounds);
}
// Transformations -------------------------------------------------------------
bool View::GetTransformRelativeTo(const View* ancestor,
ui::Transform* transform) const {
const View* p = this;
while (p && p != ancestor) {
transform->ConcatTransform(p->GetTransform());
transform->ConcatTranslate(static_cast<float>(p->GetMirroredX()),
static_cast<float>(p->y()));
p = p->parent_;
}
return p == ancestor;
}
// Coordinate conversion -------------------------------------------------------
bool View::ConvertPointForAncestor(const View* ancestor,
gfx::Point* point) const {
ui::Transform trans;
// TODO(sad): Have some way of caching the transformation results.
bool result = GetTransformRelativeTo(ancestor, &trans);
gfx::Point3f p(*point);
trans.TransformPoint(p);
*point = p.AsPoint();
return result;
}
bool View::ConvertPointFromAncestor(const View* ancestor,
gfx::Point* point) const {
ui::Transform trans;
bool result = GetTransformRelativeTo(ancestor, &trans);
gfx::Point3f p(*point);
trans.TransformPointReverse(p);
*point = p.AsPoint();
return result;
}
// Accelerated painting --------------------------------------------------------
void View::CreateLayer() {
// A new layer is being created for the view. So all the layers of the
// sub-tree can inherit the visibility of the corresponding view.
for (int i = 0, count = child_count(); i < count; ++i)
child_at(i)->UpdateChildLayerVisibility(true);
layer_ = new ui::Layer();
layer_owner_.reset(layer_);
layer_->set_delegate(this);
#if !defined(NDEBUG)
layer_->set_name(GetClassName());
#endif
UpdateParentLayers();
UpdateLayerVisibility();
// The new layer needs to be ordered in the layer tree according
// to the view tree. Children of this layer were added in order
// in UpdateParentLayers().
if (parent())
parent()->ReorderLayers();
Widget* widget = GetWidget();
if (widget)
widget->UpdateRootLayers();
}
void View::UpdateParentLayers() {
// Attach all top-level un-parented layers.
if (layer() && !layer()->parent()) {
UpdateParentLayer();
} else {
for (int i = 0, count = child_count(); i < count; ++i)
child_at(i)->UpdateParentLayers();
}
}
void View::UpdateParentLayer() {
if (!layer())
return;
ui::Layer* parent_layer = NULL;
gfx::Point offset(GetMirroredX(), y());
// TODO(sad): The NULL check here for parent_ essentially is to check if this
// is the RootView. Instead of doing this, this function should be made
// virtual and overridden from the RootView.
if (parent_)
parent_->CalculateOffsetToAncestorWithLayer(&offset, &parent_layer);
else if (!parent_ && GetWidget())
GetWidget()->CalculateOffsetToAncestorWithLayer(&offset, &parent_layer);
ReparentLayer(offset, parent_layer);
}
void View::OrphanLayers() {
if (layer()) {
if (layer()->parent())
layer()->parent()->Remove(layer());
// The layer belonging to this View has already been orphaned. It is not
// necessary to orphan the child layers.
return;
}
for (int i = 0, count = child_count(); i < count; ++i)
child_at(i)->OrphanLayers();
}
void View::ReparentLayer(const gfx::Point& offset, ui::Layer* parent_layer) {
layer_->SetBounds(gfx::Rect(offset.x(), offset.y(), width(), height()));
DCHECK_NE(layer(), parent_layer);
if (parent_layer)
parent_layer->Add(layer());
layer_->SchedulePaint(GetLocalBounds());
MoveLayerToParent(layer(), gfx::Point());
}
void View::DestroyLayer() {
ui::Layer* new_parent = layer()->parent();
std::vector<ui::Layer*> children = layer()->children();
for (size_t i = 0; i < children.size(); ++i) {
layer()->Remove(children[i]);
if (new_parent)
new_parent->Add(children[i]);
}
layer_ = NULL;
layer_owner_.reset();
if (new_parent)
ReorderLayers();
gfx::Point offset;
CalculateOffsetToAncestorWithLayer(&offset, NULL);
UpdateChildLayerBounds(offset);
SchedulePaint();
Widget* widget = GetWidget();
if (widget)
widget->UpdateRootLayers();
}
// Input -----------------------------------------------------------------------
bool View::ProcessMousePressed(const MouseEvent& event, DragInfo* drag_info) {
int drag_operations =
(enabled_ && event.IsOnlyLeftMouseButton() && HitTest(event.location())) ?
GetDragOperations(event.location()) : 0;
ContextMenuController* context_menu_controller = event.IsRightMouseButton() ?
context_menu_controller_ : 0;
const bool enabled = enabled_;
const bool result = OnMousePressed(event);
// WARNING: we may have been deleted, don't use any View variables.
if (!enabled)
return result;
if (drag_operations != ui::DragDropTypes::DRAG_NONE) {
drag_info->PossibleDrag(event.location());
return true;
}
return !!context_menu_controller || result;
}
bool View::ProcessMouseDragged(const MouseEvent& event, DragInfo* drag_info) {
// Copy the field, that way if we're deleted after drag and drop no harm is
// done.
ContextMenuController* context_menu_controller = context_menu_controller_;
const bool possible_drag = drag_info->possible_drag;
if (possible_drag && ExceededDragThreshold(
drag_info->start_pt.x() - event.x(),
drag_info->start_pt.y() - event.y())) {
if (!drag_controller_ ||
drag_controller_->CanStartDragForView(
this, drag_info->start_pt, event.location()))
DoDrag(event, drag_info->start_pt);
} else {
if (OnMouseDragged(event))
return true;
// Fall through to return value based on context menu controller.
}
// WARNING: we may have been deleted.
return (context_menu_controller != NULL) || possible_drag;
}
void View::ProcessMouseReleased(const MouseEvent& event) {
if (context_menu_controller_ && event.IsOnlyRightMouseButton()) {
// Assume that if there is a context menu controller we won't be deleted
// from mouse released.
gfx::Point location(event.location());
OnMouseReleased(event);
if (HitTest(location)) {
ConvertPointToScreen(this, &location);
ShowContextMenu(location, true);
}
} else {
OnMouseReleased(event);
}
// WARNING: we may have been deleted.
}
ui::TouchStatus View::ProcessTouchEvent(const TouchEvent& event) {
// TODO(rjkroege): Implement a grab scheme similar to as as is found in
// MousePressed.
return OnTouchEvent(event);
}
ui::GestureStatus View::ProcessGestureEvent(const GestureEvent& event) {
if (context_menu_controller_ &&
(event.type() == ui::ET_GESTURE_LONG_PRESS ||
event.type() == ui::ET_GESTURE_TWO_FINGER_TAP)) {
gfx::Point location(event.location());
ConvertPointToScreen(this, &location);
ShowContextMenu(location, true);
return ui::GESTURE_STATUS_CONSUMED;
}
return OnGestureEvent(event);
}
// Accelerators ----------------------------------------------------------------
void View::RegisterPendingAccelerators() {
if (!accelerators_.get() ||
registered_accelerator_count_ == accelerators_->size()) {
// No accelerators are waiting for registration.
return;
}
if (!GetWidget()) {
// The view is not yet attached to a widget, defer registration until then.
return;
}
accelerator_focus_manager_ = GetFocusManager();
if (!accelerator_focus_manager_) {
// Some crash reports seem to show that we may get cases where we have no
// focus manager (see bug #1291225). This should never be the case, just
// making sure we don't crash.
NOTREACHED();
return;
}
for (std::vector<ui::Accelerator>::const_iterator i(
accelerators_->begin() + registered_accelerator_count_);
i != accelerators_->end(); ++i) {
accelerator_focus_manager_->RegisterAccelerator(
*i, ui::AcceleratorManager::kNormalPriority, this);
}
registered_accelerator_count_ = accelerators_->size();
}
void View::UnregisterAccelerators(bool leave_data_intact) {
if (!accelerators_.get())
return;
if (GetWidget()) {
if (accelerator_focus_manager_) {
// We may not have a FocusManager if the window containing us is being
// closed, in which case the FocusManager is being deleted so there is
// nothing to unregister.
accelerator_focus_manager_->UnregisterAccelerators(this);
accelerator_focus_manager_ = NULL;
}
if (!leave_data_intact) {
accelerators_->clear();
accelerators_.reset();
}
registered_accelerator_count_ = 0;
}
}
// Focus -----------------------------------------------------------------------
void View::InitFocusSiblings(View* v, int index) {
int count = child_count();
if (count == 0) {
v->next_focusable_view_ = NULL;
v->previous_focusable_view_ = NULL;
} else {
if (index == count) {
// We are inserting at the end, but the end of the child list may not be
// the last focusable element. Let's try to find an element with no next
// focusable element to link to.
View* last_focusable_view = NULL;
for (Views::iterator i(children_.begin()); i != children_.end(); ++i) {
if (!(*i)->next_focusable_view_) {
last_focusable_view = *i;
break;
}
}
if (last_focusable_view == NULL) {
// Hum... there is a cycle in the focus list. Let's just insert ourself
// after the last child.
View* prev = children_[index - 1];
v->previous_focusable_view_ = prev;
v->next_focusable_view_ = prev->next_focusable_view_;
prev->next_focusable_view_->previous_focusable_view_ = v;
prev->next_focusable_view_ = v;
} else {
last_focusable_view->next_focusable_view_ = v;
v->next_focusable_view_ = NULL;
v->previous_focusable_view_ = last_focusable_view;
}
} else {
View* prev = children_[index]->GetPreviousFocusableView();
v->previous_focusable_view_ = prev;
v->next_focusable_view_ = children_[index];
if (prev)
prev->next_focusable_view_ = v;
children_[index]->previous_focusable_view_ = v;
}
}
}
// System events ---------------------------------------------------------------
void View::PropagateThemeChanged() {
for (int i = child_count() - 1; i >= 0; --i)
child_at(i)->PropagateThemeChanged();
OnThemeChanged();
}
void View::PropagateLocaleChanged() {
for (int i = child_count() - 1; i >= 0; --i)
child_at(i)->PropagateLocaleChanged();
OnLocaleChanged();
}
// Tooltips --------------------------------------------------------------------
void View::UpdateTooltip() {
Widget* widget = GetWidget();
// TODO(beng): The TooltipManager NULL check can be removed when we
// consolidate Init() methods and make views_unittests Init() all
// Widgets that it uses.
if (widget && widget->native_widget_private()->GetTooltipManager())
widget->native_widget_private()->GetTooltipManager()->UpdateTooltip();
}
// Drag and drop ---------------------------------------------------------------
bool View::DoDrag(const LocatedEvent& event, const gfx::Point& press_pt) {
#if !defined(OS_MACOSX)
int drag_operations = GetDragOperations(press_pt);
if (drag_operations == ui::DragDropTypes::DRAG_NONE)
return false;
OSExchangeData data;
WriteDragData(press_pt, &data);
// Message the RootView to do the drag and drop. That way if we're removed
// the RootView can detect it and avoid calling us back.
gfx::Point widget_location(event.location());
ConvertPointToWidget(this, &widget_location);
GetWidget()->RunShellDrag(this, data, widget_location, drag_operations);
return true;
#else
return false;
#endif // !defined(OS_MACOSX)
}
} // namespace views
| keishi/chromium | ui/views/view.cc | C++ | bsd-3-clause | 61,719 |
//
// Implements iLQR (on a traditional chain) for nonlinear dynamics and cost.
//
// Arun Venkatraman (arunvenk@cs.cmu.edu)
// December 2016
//
#pragma once
#include <ilqr/ilqr_taylor_expansions.hh>
#include <Eigen/Dense>
#include <tuple>
#include <vector>
namespace ilqr
{
class iLQR
{
public:
// Stores linearization points x, u and the Taylor expansions of the dynamics and cost.
using TaylorExpansion = std::tuple<Eigen::VectorXd, Eigen::VectorXd, ilqr::Dynamics, ilqr::Cost>;
iLQR(const DynamicsFunc &dynamics, const CostFunc &cost,
const std::vector<Eigen::VectorXd> &Xs,
const std::vector<Eigen::VectorXd> &Us);
void backwards_pass();
void forward_pass(std::vector<double> &costs,
std::vector<Eigen::VectorXd> &states,
std::vector<Eigen::VectorXd> &controls,
bool update_linearizations
);
std::vector<Eigen::VectorXd> states();
std::vector<Eigen::VectorXd> controls();
private:
int state_dim_ = -1;
int control_dim_ = -1;
int T_ = -1; // time horizon
DynamicsFunc true_dynamics_;
CostFunc true_cost_;
// Taylor series expansion points and expanded dynamics, cost.
std::vector<TaylorExpansion> expansions_;
// Feedback control gains.
std::vector<Eigen::MatrixXd> Ks_;
std::vector<Eigen::VectorXd> ks_;
};
} // namespace lqr
| LAIRLAB/qr_trees | src/ilqr/iLQR.hh | C++ | bsd-3-clause | 1,395 |
<?php
/**
* Command line interface items class file.
*
* PHP version 5.3
*
* @category CLI
* @package FeedAPI
* @author Igor Rzegocki <igor@rzegocki.pl>
* @license http://opensource.org/licenses/BSD-3-Clause The BSD 3-Clause License
* @link https://github.com/ajgon/feed-api
*/
namespace FeedAPI\CLI;
/**
* Class used to handle CLI commands.
*
* @category CLI
* @package FeedAPI
* @author Igor Rzegocki <igor@rzegocki.pl>
* @license http://opensource.org/licenses/BSD-3-Clause The BSD 3-Clause License
* @link https://github.com/ajgon/feed-api
*/
class CLI extends Base
{
/**
* Constructor
*
* @param array $args CLI arguments, basically $argv
*
* @return null
*/
public function __construct($args)
{
parent::$command = isset($args[0]) ? $args[0] : false;
parent::$object = isset($args[1]) ? $args[1] : false;
parent::$action = isset($args[2]) ? $args[2] : false;
parent::$param = isset($args[3]) ? $args[3] : false;
parent::$extra = isset($args[4]) ? $args[4] : false;
$this->initDatabase();
}
/**
* Processes CLI invocation, launches corresponding action.
*
* @return null
*/
public function process()
{
if (empty(self::$object) || empty(self::$action)) {
$this->showUsage();
return;
}
try {
switch(self::$object) {
case 'feed':
$feed = new Feed();
switch(self::$action) {
case 'add':
$feed->add();
break;
case 'fetch':
$feed->fetch();
break;
case 'show':
$feed->show();
break;
case 'remove':
$feed->remove();
break;
case 'help':
$feed->help();
break;
default:
$this->error('Unknown action.');
}
break;
case 'group':
$group = new Group();
switch(self::$action) {
case 'add':
$group->add();
break;
case 'attach':
$group->attach();
break;
case 'detach':
$group->detach();
break;
case 'show':
$group->show();
break;
case 'remove':
$group->remove();
break;
case 'help':
$group->help();
break;
default:
$this->error('Unknown action.');
}
break;
case 'user':
$user = new User();
switch(self::$action) {
case 'add':
$user->add();
break;
case 'addsuper':
$user->add(true);
break;
case 'attach':
$user->attach();
break;
case 'detach':
$user->detach();
break;
case 'show':
$user->show();
break;
case 'remove':
$user->remove();
break;
case 'help':
$user->help();
break;
default:
$this->error('Unknown action.');
}
break;
default:
$this->error('Unknown object.');
}
} catch (\FeedAPI\Exception $e) {
$this->error($e->getMessage(), false);
}
}
/**
* Inits database for CLI.
*
* @return null
*/
private function initDatabase() {
$base = new \FeedAPI\Base();
$base->initDatabase();
}
}
| ajgon/feed-api | app/classes/FeedAPI/CLI/CLI.php | PHP | bsd-3-clause | 4,168 |
using System;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using Moscrif.IDE.Iface.Entities;
namespace Moscrif.IDE.Tool
{
public static class FileUtility
{
internal readonly static char[] separators = { Path.DirectorySeparatorChar, Path.VolumeSeparatorChar };
/// <summary>
/// Removes trailing '.' character from a path.
/// </summary>
/// <param name="path">The path from which to remove the trailing
/// '.' character.</param>
/// <returns>A path without any trailing '.'.</returns>
public static string TrimTrailingDotCharacter(string path)
{
if (path.Length > 0 && path [path.Length - 1] == '.')
return path.Remove(path.Length - 1, 1);
else
return path;
}
/// <summary>
/// Removes trailing '\' or '/' from a path.
/// </summary>
/// <param name="path">The path from which to remove the trailing
/// directory separator.</param>
/// <returns>A path without any trailing directory separator.</returns>
public static string TrimTrailingDirectorySeparator(string path)
{
if (path.Length == 0)
return path;
if ((path [path.Length - 1] == separators [0]) || (path [path.Length - 1] == separators [1])){
path = path.Remove(path.Length - 1, 1);
}
return path;
}
/// <summary>
/// Removes starting '\' or '/' from a path.
/// </summary>
/// <param name="path">The path from which to remove the starting
/// directory separator.</param>
/// <returns>A path without any starting directory separator.</returns>
public static string TrimStartingDirectorySeparator(string path) {
if (path.Length == 0)
return path;
if ((path [0] == separators [0]) || (path [0] == separators [1])) {
path = path.Remove(0, 1);
TrimStartingDirectorySeparator(path);
}
return path;
}
/// <summary>
/// Removes starting '.' character from a path.
/// </summary>
/// <param name="path">The path from which to remove the starting
/// '.' character.</param>
/// <returns>A path without any starting '.'.</returns>
public static string TrimStartingDotCharacter(string path)
{
if (path.Length > 0 && path [0] == '.') {
path = path.Remove(0, 1);
TrimStartingDotCharacter(path);
//return path;
}
return path;
}
/// <summary>
/// Converts a given absolute path and a given base path to a path that leads
/// from the base path to the absoulte path. (as a relative path)
/// </summary>
/// <remarks>
/// <para>The returned relative path will be of the form:</para>
/// <para><code>
/// .\Test
/// .\Test\Test.prjx
/// .\Test.prjx
/// .\
/// ..\bin
/// ..\..\bin\debug
/// </code>
/// </para>
/// </remarks>
public static string AbsoluteToRelativePath(string baseDirectoryPath, string absPath)
{
//absPath = absPath.Replace('/',Path.DirectorySeparatorChar);
//absPath = absPath.Replace('\\',Path.DirectorySeparatorChar);
// Remove trailing '.'
baseDirectoryPath = TrimTrailingDotCharacter(baseDirectoryPath);
// Remove trailing directory separators.
baseDirectoryPath = TrimTrailingDirectorySeparator(baseDirectoryPath);
absPath = TrimTrailingDirectorySeparator(absPath);
// Remove ".\" occurrences.
absPath = absPath.Replace(String.Concat(".", separators [0]), String.Empty);
absPath = absPath.Replace(String.Concat(".", separators [1]), String.Empty);
string[] bPath = baseDirectoryPath.Split(separators);
string[] aPath = absPath.Split(separators);
int indx = 0;
for (; indx < Math.Min(bPath.Length, aPath.Length); ++indx)
//if(!bPath[indx].Equals(aPath[indx]))
if (String.Compare(bPath [indx], aPath [indx], true) != 0)
break;
if (indx == 0)
return absPath;
StringBuilder erg = new StringBuilder();
if (indx == bPath.Length) {
erg.Append('.');
erg.Append(Path.DirectorySeparatorChar);
} else
for (int i = indx; i < bPath.Length; ++i) {
erg.Append("..");
erg.Append(Path.DirectorySeparatorChar);
}
erg.Append(String.Join(Path.DirectorySeparatorChar.ToString(), aPath, indx, aPath.Length - indx));
return erg.ToString();
}
/// <summary>
/// Converts a given relative path and a given base path to a path that leads
/// to the relative path absoulte.
/// </summary>
public static string RelativeToAbsolutePath(string baseDirectoryPath, string relPath)
{
relPath = relPath.Replace('/', Path.DirectorySeparatorChar);
relPath = relPath.Replace('\\', Path.DirectorySeparatorChar);
if (separators [0] != separators [1] && relPath.IndexOf(separators [1]) != -1)
return relPath;
string[] bPath = baseDirectoryPath.Split(separators [0]);
string[] rPath = relPath.Split(separators [0]);
int indx = 0;
for (; indx < rPath.Length; ++indx)
if (!rPath[indx].Equals("..")) {
break;
}
if (indx == 0)
return baseDirectoryPath + separators[0] + String.Join(Path.DirectorySeparatorChar.ToString(), rPath, 1, rPath.Length - 1);
string erg = String.Join(Path.DirectorySeparatorChar.ToString(), bPath, 0, Math.Max(0, bPath.Length - indx));
erg += separators [0] + String.Join(Path.DirectorySeparatorChar.ToString(), rPath, indx, rPath.Length - indx);
return erg;
}
public static string GetSystemPath(string path)
{
if(String.IsNullOrEmpty(path))
return path;
string sysPath = path.Replace('/', Path.DirectorySeparatorChar);
sysPath = sysPath.Replace('\\', Path.DirectorySeparatorChar);
return sysPath;
}
public static MatchCollection FindInFileRegEx(string filePath, string expresion)
{
if (!System.IO.File.Exists(filePath))
return null;
FileAttributes fa = File.GetAttributes(filePath);
if ((fa & FileAttributes.System) == FileAttributes.System) {
return null;
}
if ((fa & FileAttributes.ReadOnly) == FileAttributes.ReadOnly) {
return null;
}
try{
StreamReader reader = new StreamReader(filePath);
string content = reader.ReadToEnd();
reader.Close();
Regex regexBar = new Regex(expresion, RegexOptions.IgnorePatternWhitespace | RegexOptions.Compiled | RegexOptions.CultureInvariant);
MatchCollection mcAll =regexBar.Matches(content);//Regex.Matches(content, expresion);
return mcAll;
}catch {
return null;
}
}
public static List<FindResult> FindInFile(string filePath, string expresion, bool caseSensitve, bool wholeWorlds, string replaceExpresion)
{
if (!System.IO.File.Exists(filePath))
return null;
FileAttributes fa = File.GetAttributes(filePath);
if ((fa & FileAttributes.System) == FileAttributes.System) {
return null;
}
if ((fa & FileAttributes.ReadOnly) == FileAttributes.ReadOnly) {
return null;
}
List<FindResult> result = new List<FindResult>();
StreamReader reader = new StreamReader(filePath);
bool isChanged = false;
StringBuilder sb = new StringBuilder();
int indx = 0;
do {
string line = reader.ReadLine();
if(String.IsNullOrEmpty(line)){
indx++;
continue;
}
var comparison = caseSensitve ? StringComparison.Ordinal : StringComparison.OrdinalIgnoreCase;
int idx = 0;
int delta = 0;
while ((idx = line.IndexOf (expresion, idx, line.Length - idx, comparison)) >= 0) {
if (!wholeWorlds || IsWholeWordAt(line, idx, expresion.Length))
if (replaceExpresion != null) {
Replace(ref line, idx + delta, expresion.Length, replaceExpresion);
isChanged = true;
//yield return new SearchResult (provider, idx + delta, replacePattern.Length);
result.Add(new FindResult((object)indx, (object)line));
delta += replaceExpresion.Length - expresion.Length;
} else
result.Add(new FindResult( (object)(indx+1),(object)line));
//yield return new SearchResult (provider, idx, pattern.Length);
idx += expresion.Length;
}
sb.AppendLine(line);
/* if(caseSensitve && !wholeWorlds){
if(line.Contains(expresion) )
result.Add(indx,line);
} else if(!caseSensitve && !wholeWorlds ){
if(lineUpper.Contains(expresion.ToUpper()) )
result.Add(indx,line);
} else if(!caseSensitve && wholeWorlds){
if(lineUpper.Split(separators).Contains(expresion.ToUpper()))
result.Add(indx,line);
} else if(caseSensitve && wholeWorlds){
if(line.Split(separators).Contains(expresion))
result.Add(indx,line);
}*/
//line.Contains("string", StringComparison.CurrentCultureIgnoreCase);
indx++;
} while (reader.Peek() != -1);
reader.Close();
if (isChanged)
try {
StreamWriter writer = new StreamWriter(filePath);
writer.Write(sb.ToString());
writer.Close();
} catch (Exception ex) {
Tool.Logger.Error(ex.Message);
}
return result;
}
public static bool IsWordSeparator(char ch)
{
return !Char.IsLetterOrDigit(ch) && ch != '_';
}
public static bool ContainsPath(string baseDirectoryPath, string secondPath)
{
// Remove trailing '.'
baseDirectoryPath = TrimTrailingDotCharacter(baseDirectoryPath);
// Remove trailing directory separators.
baseDirectoryPath = TrimTrailingDirectorySeparator(baseDirectoryPath);
secondPath = TrimTrailingDirectorySeparator(secondPath);
// Remove ".\" occurrences.
secondPath = secondPath.Replace(String.Concat(".", separators [0]), String.Empty);
secondPath = secondPath.Replace(String.Concat(".", separators [1]), String.Empty);
string[] bPath = baseDirectoryPath.Split(separators);
string[] aPath = secondPath.Split(separators);
int indx = 0;
for (; indx < Math.Min(bPath.Length, aPath.Length); ++indx)
if (String.Compare(bPath [indx], aPath [indx], true) != 0)//if(!bPath[indx].Equals(aPath[indx]))
break;
if (indx == bPath.Length)
return true;
return false;
}
public static void GetAllFiles(ref List<string> filesList,string path)
{
if (!Directory.Exists(path))
return;
DirectoryInfo di = new DirectoryInfo(path);
foreach (DirectoryInfo d in di.GetDirectories()) {
int indx = -1;
indx = MainClass.Settings.IgnoresFolders.FindIndex(x => x.Folder == d.Name && x.IsForIde);
if (indx < 0)
GetAllFiles(ref filesList, d.FullName);
}
foreach (FileInfo f in di.GetFiles()){
int indx = -1;
indx = MainClass.Settings.IgnoresFiles.FindIndex(x => x.Folder == f.Name && x.IsForIde);
if(indx >-1)continue;
filesList.Add(f.FullName);
}
}
public static string DeleteItem(string fileName, bool isDir)
{
if (isDir) {
if (!System.IO.Directory.Exists(fileName))
return "";
try {
List<string> listFile = new List<string>();
GetAllFiles(ref listFile, fileName);
System.IO.Directory.Delete(fileName, true);
foreach (string file in listFile)
MainClass.MainWindow.EditorNotebook.ClosePage(file, true);
} catch (Exception ex){
return ex.Message;
}
} else {
if (!System.IO.File.Exists(fileName))
return "";
try {
System.IO.File.Delete(fileName);
MainClass.MainWindow.EditorNotebook.ClosePage(fileName, true);
} catch (Exception ex) {
return ex.Message;
}
}
return "";
}
public static string RenameItem(string fileName, bool isDir, string newName,out string newPath)
{
newPath = "";
if (isDir) {
if (!System.IO.Directory.Exists(fileName)){
return "";
}
string path = System.IO.Path.GetDirectoryName(fileName);
newPath = System.IO.Path.Combine(path, newName);
if (System.IO.Directory.Exists(newPath)){
return "";
}
try {
List<string> listFile = new List<string>();
FileUtility.GetAllFiles(ref listFile, fileName);
foreach (string file in listFile)
MainClass.MainWindow.EditorNotebook.ClosePage(file, true);
System.IO.Directory.Move(fileName, newPath);
} catch(Exception ex) {
return ex.Message;
}
} else {// Rename File
if (!System.IO.File.Exists(fileName)){
return "";
}
string path = System.IO.Path.GetDirectoryName(fileName);
string extension = System.IO.Path.GetExtension(fileName);
string newExt = System.IO.Path.GetExtension(newName);
if (string.IsNullOrEmpty(newExt))
newName = newName + extension;
newPath = System.IO.Path.Combine(path, newName);
if (System.IO.Directory.Exists(newPath)){
return "";
}
try {
System.IO.File.Move(fileName, newPath);
MainClass.MainWindow.EditorNotebook.RenameFile(fileName, newPath);
} catch (Exception ex){
return ex.Message;
}
}
return "";
}
public static void CreateDirectory(string newFile)
{
string fileName = System.IO.Path.GetFileName(newFile);
string dir = System.IO.Path.GetDirectoryName (newFile);
if (System.IO.Directory.Exists(newFile))
newFile = System.IO.Path.Combine(dir, fileName+"_1");
Directory.CreateDirectory(newFile);
}
public static void CreateFile(string newFile, string content)
{
string dir = System.IO.Path.GetDirectoryName(newFile);
string nameExtens = System.IO.Path.GetExtension(newFile);
string nameClear = System.IO.Path.GetFileNameWithoutExtension(newFile);
if (System.IO.File.Exists(newFile))
newFile = System.IO.Path.Combine(dir, nameClear+"_1"+nameExtens);
string ext = System.IO.Path.GetExtension(newFile);
if (ext == ".db"){
using (FileStream fs = System.IO.File.Create(newFile))
fs.Close();
SqlLiteDal sqlld = new SqlLiteDal(newFile);
//Console.WriteLine(content);
sqlld.RunSqlScalar(content);
} else {
using (StreamWriter file = new StreamWriter(newFile)) {
file.Write(content);
file.Close();
file.Dispose();
}
}
}
#region private
private static bool IsWholeWordAt(string text, int offset, int length)
{
return (offset <= 0 || IsWordSeparator(text [offset - 1])) &&
(offset + length >= text.Length || IsWordSeparator(text [offset + length]));
}
private static void Replace(ref string text, int offset, int length, string replacement)
{
text = text.Remove(offset, length);
text = text.Insert(offset, replacement);
/*if (document != null) {
Gtk.Application.Invoke (delegate {
document.Editor.Replace (offset, length, replacement);
});
return;
}*/
}
#endregion
}
}
| moscrif/ide | tool/FileUtility.cs | C# | bsd-3-clause | 14,386 |
module("support", {teardown: moduleTeardown});
var computedSupport = getComputedSupport(jQuery.support);
function getComputedSupport(support) {
var prop,
result = {};
for (prop in support) {
if (typeof support[prop] === "function") {
result[prop] = support[prop]();
} else {
result[prop] = support[prop];
}
}
return result;
}
if (jQuery.css) {
testIframeWithCallback("body background is not lost if set prior to loading jQuery (#9239)", "support/bodyBackground.html", function (color, support) {
expect(2);
var okValue = {
"#000000": true,
"rgb(0, 0, 0)": true
};
ok(okValue[color], "color was not reset (" + color + ")");
deepEqual(jQuery.extend({}, support), computedSupport, "Same support properties");
});
}
// This test checkes CSP only for browsers with "Content-Security-Policy" header support
// i.e. no old WebKit or old Firefox
testIframeWithCallback("Check CSP (https://developer.mozilla.org/en-US/docs/Security/CSP) restrictions",
"support/csp.php",
function (support) {
expect(2);
deepEqual(jQuery.extend({}, support), computedSupport, "No violations of CSP polices");
stop();
supportjQuery.get("data/support/csp.log").done(function (data) {
equal(data, "", "No log request should be sent");
supportjQuery.get("data/support/csp-clean.php").done(start);
});
}
);
(function () {
var expected,
userAgent = window.navigator.userAgent;
if (/chrome/i.test(userAgent)) {
expected = {
"ajax": true,
"boxSizingReliable": true,
"checkClone": true,
"checkOn": true,
"clearCloneStyle": true,
"cors": true,
"focusinBubbles": false,
"noCloneChecked": true,
"optDisabled": true,
"optSelected": true,
"pixelPosition": true,
"radioValue": true,
"reliableMarginRight": true
};
} else if (/opera.*version\/12\.1/i.test(userAgent)) {
expected = {
"ajax": true,
"boxSizingReliable": true,
"checkClone": true,
"checkOn": true,
"clearCloneStyle": true,
"cors": true,
"focusinBubbles": false,
"noCloneChecked": true,
"optDisabled": true,
"optSelected": true,
"pixelPosition": true,
"radioValue": false,
"reliableMarginRight": true
};
} else if (/trident\/7\.0/i.test(userAgent)) {
expected = {
"ajax": true,
"boxSizingReliable": false,
"checkClone": true,
"checkOn": true,
"clearCloneStyle": false,
"cors": true,
"focusinBubbles": true,
"noCloneChecked": false,
"optDisabled": true,
"optSelected": false,
"pixelPosition": true,
"radioValue": false,
"reliableMarginRight": true
};
} else if (/msie 10\.0/i.test(userAgent)) {
expected = {
"ajax": true,
"boxSizingReliable": false,
"checkClone": true,
"checkOn": true,
"clearCloneStyle": false,
"cors": true,
"focusinBubbles": true,
"noCloneChecked": false,
"optDisabled": true,
"optSelected": false,
"pixelPosition": true,
"radioValue": false,
"reliableMarginRight": true
};
} else if (/msie 9\.0/i.test(userAgent)) {
expected = {
"ajax": true,
"boxSizingReliable": false,
"checkClone": true,
"checkOn": true,
"clearCloneStyle": false,
"cors": false,
"focusinBubbles": true,
"noCloneChecked": false,
"optDisabled": true,
"optSelected": false,
"pixelPosition": true,
"radioValue": false,
"reliableMarginRight": true
};
} else if (/7\.0(\.\d+|) safari/i.test(userAgent)) {
expected = {
"ajax": true,
"boxSizingReliable": true,
"checkClone": true,
"checkOn": true,
"clearCloneStyle": true,
"cors": true,
"focusinBubbles": false,
"noCloneChecked": true,
"optDisabled": true,
"optSelected": true,
"pixelPosition": false,
"radioValue": true,
"reliableMarginRight": true
};
} else if (/6\.0(\.\d+|) safari/i.test(userAgent)) {
expected = {
"ajax": true,
"boxSizingReliable": true,
"checkClone": true,
"checkOn": true,
"clearCloneStyle": true,
"cors": true,
"focusinBubbles": false,
"noCloneChecked": true,
"optDisabled": true,
"optSelected": true,
"pixelPosition": false,
"radioValue": true,
"reliableMarginRight": true
};
} else if (/5\.1(\.\d+|) safari/i.test(userAgent)) {
expected = {
"ajax": true,
"boxSizingReliable": true,
"checkClone": false,
"checkOn": false,
"clearCloneStyle": true,
"cors": true,
"focusinBubbles": false,
"noCloneChecked": true,
"optDisabled": true,
"optSelected": true,
"pixelPosition": false,
"radioValue": true,
"reliableMarginRight": true
};
} else if (/firefox/i.test(userAgent)) {
expected = {
"ajax": true,
"boxSizingReliable": true,
"checkClone": true,
"checkOn": true,
"clearCloneStyle": true,
"cors": true,
"focusinBubbles": false,
"noCloneChecked": true,
"optDisabled": true,
"optSelected": true,
"pixelPosition": true,
"radioValue": true,
"reliableMarginRight": true
};
} else if (/iphone os (?:6|7)_/i.test(userAgent)) {
expected = {
"ajax": true,
"boxSizingReliable": true,
"checkClone": true,
"checkOn": true,
"clearCloneStyle": true,
"cors": true,
"focusinBubbles": false,
"noCloneChecked": true,
"optDisabled": true,
"optSelected": true,
"pixelPosition": false,
"radioValue": true,
"reliableMarginRight": true
};
} else if (/android 2\.3/i.test(userAgent)) {
expected = {
"ajax": true,
"boxSizingReliable": true,
"checkClone": true,
"checkOn": false,
"clearCloneStyle": false,
"cors": true,
"focusinBubbles": false,
"noCloneChecked": true,
"optDisabled": false,
"optSelected": true,
"pixelPosition": false,
"radioValue": true,
"reliableMarginRight": false
};
} else if (/android 4\.[0-3]/i.test(userAgent)) {
expected = {
"ajax": true,
"boxSizingReliable": true,
"checkClone": false,
"checkOn": false,
"clearCloneStyle": true,
"cors": true,
"focusinBubbles": false,
"noCloneChecked": true,
"optDisabled": true,
"optSelected": true,
"pixelPosition": false,
"radioValue": true,
"reliableMarginRight": true
};
}
if (expected) {
test("Verify that the support tests resolve as expected per browser", function () {
var i, prop,
j = 0;
for (prop in computedSupport) {
j++;
}
expect(j);
for (i in expected) {
// TODO check for all modules containing support properties
if (jQuery.ajax || i !== "ajax" && i !== "cors") {
equal(computedSupport[i], expected[i],
"jQuery.support['" + i + "']: " + computedSupport[i] +
", expected['" + i + "']: " + expected[i]);
} else {
ok(true, "no ajax; skipping jQuery.support[' " + i + " ']");
}
}
});
}
})();
| malvinder/glscode | vendor/bower-asset/jquery/test/unit/support.js | JavaScript | bsd-3-clause | 8,655 |
public class Room {
private RoomType roomType;
private boolean available;
private String guest;
public RoomType getRoomType() {
return this.roomType;
}
public String getGuest() throws NotBookedException {
if (isAvailable()) {
throw new NotBookedException();
}
return this.guest;
}
public boolean isAvailable() {
return this.available;
}
synchronized public void book(String guest) throws NotAvailableException {
if (!isAvailable()) {
throw new NotAvailableException("This room is not available");
}
this.available = false;
this.guest = guest;
}
public Room (RoomType roomType) {
this.roomType = roomType;
this.available = true;
this.guest = null;
}
}
| martijnvermaat/network-programming | assignment-3/Room.java | Java | bsd-3-clause | 840 |
"""
External serialization for testing remote module loading.
"""
from tiddlyweb.serializations import SerializationInterface
class Serialization(SerializationInterface):
def list_recipes(self, recipes):
print recipes
def list_bags(self, bags):
print bags
def recipe_as(self, recipe):
print "r_as: %s" % recipe
def as_recipe(self, recipe, input):
print "as_r: %s" % input
def bag_as(self, bag):
print "b_as: %s" % bag
def as_bag(self, bag, input):
print "as_b: %s" % input
def tiddler_as(self, tiddler):
print "t_as: %s" % tiddler
def as_tiddler(self, tiddler, input):
print "as_t: %s" % input
| funkyeah/tiddlyweb | test/other/tiddlyweb/serializations/debug.py | Python | bsd-3-clause | 701 |
// Copyright Daniel Wallin, Arvid Norberg 2006. Use, modification and distribution is
// subject to the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#include <boost/python.hpp>
#include <list>
#include <string>
#include <libtorrent/session.hpp>
#include <libtorrent/settings.hpp> // for bencode_map_entry
#include <libtorrent/storage.hpp>
#include <libtorrent/ip_filter.hpp>
#include <libtorrent/disk_io_thread.hpp>
#include <libtorrent/extensions.hpp>
#include <libtorrent/lazy_entry.hpp>
#include <libtorrent/bencode.hpp>
#include <libtorrent/aux_/session_impl.hpp> // for settings_map()
#include <libtorrent/extensions/lt_trackers.hpp>
#include <libtorrent/extensions/metadata_transfer.hpp>
#include <libtorrent/extensions/smart_ban.hpp>
#include <libtorrent/extensions/ut_metadata.hpp>
#include <libtorrent/extensions/ut_pex.hpp>
#include "gil.hpp"
using namespace boost::python;
using namespace libtorrent;
namespace
{
void listen_on(session& s, int min_, int max_, char const* interface, int flags)
{
allow_threading_guard guard;
error_code ec;
s.listen_on(std::make_pair(min_, max_), ec, interface, flags);
if (ec) throw libtorrent_exception(ec);
}
void outgoing_ports(session& s, int _min, int _max)
{
allow_threading_guard guard;
session_settings settings = s.settings();
settings.outgoing_ports = std::make_pair(_min, _max);
s.set_settings(settings);
return;
}
#ifndef TORRENT_DISABLE_DHT
void add_dht_node(session& s, tuple n)
{
std::string ip = extract<std::string>(n[0]);
int port = extract<int>(n[1]);
s.add_dht_node(std::make_pair(ip, port));
}
void add_dht_router(session& s, std::string router_, int port_)
{
allow_threading_guard guard;
return s.add_dht_router(std::make_pair(router_, port_));
}
#endif
void add_extension(session& s, object const& e)
{
#ifndef TORRENT_DISABLE_EXTENSIONS
if (!extract<std::string>(e).check()) return;
std::string name = extract<std::string>(e);
if (name == "ut_metadata")
s.add_extension(create_ut_metadata_plugin);
else if (name == "ut_pex")
s.add_extension(create_ut_pex_plugin);
else if (name == "smart_ban")
s.add_extension(create_smart_ban_plugin);
else if (name == "lt_trackers")
s.add_extension(create_lt_trackers_plugin);
#ifndef TORRENT_NO_DEPRECATE
else if (name == "metadata_transfer")
s.add_extension(create_metadata_plugin);
#endif // TORRENT_NO_DEPRECATE
#endif // TORRENT_DISABLE_EXTENSIONS
}
void session_set_settings(session& ses, dict const& sett_dict)
{
bencode_map_entry* map;
int len;
boost::tie(map, len) = aux::settings_map();
session_settings sett;
for (int i = 0; i < len; ++i)
{
if (!sett_dict.has_key(map[i].name)) continue;
void* dest = ((char*)&sett) + map[i].offset;
char const* name = map[i].name;
switch (map[i].type)
{
case std_string:
*((std::string*)dest) = extract<std::string>(sett_dict[name]);
break;
case character:
*((char*)dest) = extract<char>(sett_dict[name]);
break;
case boolean:
*((bool*)dest) = extract<bool>(sett_dict[name]);
break;
case integer:
*((int*)dest) = extract<int>(sett_dict[name]);
break;
case floating_point:
*((float*)dest) = extract<float>(sett_dict[name]);
break;
}
}
if (!sett_dict.has_key("outgoing_port"))
sett.outgoing_ports.first = extract<int>(sett_dict["outgoing_port"]);
if (!sett_dict.has_key("num_outgoing_ports"))
sett.outgoing_ports.second = sett.outgoing_ports.first + extract<int>(sett_dict["num_outgoing_ports"]);
ses.set_settings(sett);
}
dict session_get_settings(session const& ses)
{
session_settings sett;
{
allow_threading_guard guard;
sett = ses.settings();
}
dict sett_dict;
bencode_map_entry* map;
int len;
boost::tie(map, len) = aux::settings_map();
for (int i = 0; i < len; ++i)
{
void const* dest = ((char const*)&sett) + map[i].offset;
char const* name = map[i].name;
switch (map[i].type)
{
case std_string:
sett_dict[name] = *((std::string const*)dest);
break;
case character:
sett_dict[name] = *((char const*)dest);
break;
case boolean:
sett_dict[name] = *((bool const*)dest);
break;
case integer:
sett_dict[name] = *((int const*)dest);
break;
case floating_point:
sett_dict[name] = *((float const*)dest);
break;
}
}
sett_dict["outgoing_port"] = sett.outgoing_ports.first;
sett_dict["num_outgoing_ports"] = sett.outgoing_ports.second - sett.outgoing_ports.first + 1;
return sett_dict;
}
#ifndef BOOST_NO_EXCEPTIONS
#ifndef TORRENT_NO_DEPRECATE
torrent_handle add_torrent_depr(session& s, torrent_info const& ti
, std::string const& save, entry const& resume
, storage_mode_t storage_mode, bool paused)
{
allow_threading_guard guard;
return s.add_torrent(ti, save, resume, storage_mode, paused, default_storage_constructor);
}
#endif
#endif
}
void dict_to_add_torrent_params(dict params, add_torrent_params& p)
{
// torrent_info objects are always held by an intrusive_ptr in the python binding
if (params.has_key("ti") && params.get("ti") != boost::python::object())
p.ti = extract<boost::intrusive_ptr<torrent_info> >(params["ti"]);
if (params.has_key("info_hash"))
p.info_hash = extract<sha1_hash>(params["info_hash"]);
if (params.has_key("name"))
p.name = extract<std::string>(params["name"]);
p.save_path = extract<std::string>(params["save_path"]);
if (params.has_key("resume_data"))
{
std::string resume = extract<std::string>(params["resume_data"]);
p.resume_data.assign(resume.begin(), resume.end());
}
if (params.has_key("storage_mode"))
p.storage_mode = extract<storage_mode_t>(params["storage_mode"]);
if (params.has_key("trackers"))
{
list l = extract<list>(params["trackers"]);
int n = boost::python::len(l);
for(int i = 0; i < n; i++)
p.trackers.push_back(extract<std::string>(l[i]));
}
if (params.has_key("dht_nodes"))
{
list l = extract<list>(params["dht_nodes"]);
int n = boost::python::len(l);
for(int i = 0; i < n; i++)
p.dht_nodes.push_back(extract<std::pair<std::string, int> >(l[i]));
}
#ifndef TORRENT_NO_DEPRECATE
std::string url;
if (params.has_key("tracker_url"))
p.trackers.push_back(extract<std::string>(params["tracker_url"]));
if (params.has_key("seed_mode"))
p.seed_mode = params["seed_mode"];
if (params.has_key("upload_mode"))
p.upload_mode = params["upload_mode"];
if (params.has_key("share_mode"))
p.upload_mode = params["share_mode"];
if (params.has_key("override_resume_data"))
p.override_resume_data = params["override_resume_data"];
if (params.has_key("apply_ip_filter"))
p.apply_ip_filter = params["apply_ip_filter"];
if (params.has_key("paused"))
p.paused = params["paused"];
if (params.has_key("auto_managed"))
p.auto_managed = params["auto_managed"];
if (params.has_key("duplicate_is_error"))
p.duplicate_is_error = params["duplicate_is_error"];
if (params.has_key("merge_resume_trackers"))
p.merge_resume_trackers = params["merge_resume_trackers"];
#endif
if (params.has_key("flags"))
p.flags = extract<boost::uint64_t>(params["flags"]);
if (params.has_key("trackerid"))
p.trackerid = extract<std::string>(params["trackerid"]);
if (params.has_key("url"))
p.url = extract<std::string>(params["url"]);
if (params.has_key("source_feed_url"))
p.source_feed_url = extract<std::string>(params["source_feed_url"]);
if (params.has_key("uuid"))
p.uuid = extract<std::string>(params["uuid"]);
if (params.has_key("file_priorities"))
{
list l = extract<list>(params["file_priorities"]);
int n = boost::python::len(l);
for(int i = 0; i < n; i++)
p.file_priorities.push_back(extract<boost::uint8_t>(l[i]));
p.file_priorities.clear();
}
}
namespace
{
torrent_handle add_torrent(session& s, dict params)
{
add_torrent_params p;
dict_to_add_torrent_params(params, p);
allow_threading_guard guard;
#ifndef BOOST_NO_EXCEPTIONS
return s.add_torrent(p);
#else
error_code ec;
return s.add_torrent(p, ec);
#endif
}
void async_add_torrent(session& s, dict params)
{
add_torrent_params p;
dict_to_add_torrent_params(params, p);
allow_threading_guard guard;
#ifndef BOOST_NO_EXCEPTIONS
s.async_add_torrent(p);
#else
error_code ec;
s.async_add_torrent(p, ec);
#endif
}
void dict_to_feed_settings(dict params, feed_settings& feed)
{
if (params.has_key("auto_download"))
feed.auto_download = extract<bool>(params["auto_download"]);
if (params.has_key("default_ttl"))
feed.default_ttl = extract<int>(params["default_ttl"]);
if (params.has_key("url"))
feed.url = extract<std::string>(params["url"]);
if (params.has_key("add_args"))
dict_to_add_torrent_params(dict(params["add_args"]), feed.add_args);
}
feed_handle add_feed(session& s, dict params)
{
feed_settings feed;
// this static here is a bit of a hack. It will
// probably work for the most part
dict_to_feed_settings(params, feed);
allow_threading_guard guard;
return s.add_feed(feed);
}
dict get_feed_status(feed_handle const& h)
{
feed_status s;
{
allow_threading_guard guard;
s = h.get_feed_status();
}
dict ret;
ret["url"] = s.url;
ret["title"] = s.title;
ret["description"] = s.description;
ret["last_update"] = s.last_update;
ret["next_update"] = s.next_update;
ret["updating"] = s.updating;
ret["error"] = s.error ? s.error.message() : "";
ret["ttl"] = s.ttl;
list items;
for (std::vector<feed_item>::iterator i = s.items.begin()
, end(s.items.end()); i != end; ++i)
{
dict item;
item["url"] = i->url;
item["uuid"] = i->uuid;
item["title"] = i->title;
item["description"] = i->description;
item["comment"] = i->comment;
item["category"] = i->category;
item["size"] = i->size;
item["handle"] = i->handle;
item["info_hash"] = i->info_hash.to_string();
items.append(item);
}
ret["items"] = items;
return ret;
}
void set_feed_settings(feed_handle& h, dict sett)
{
feed_settings feed;
dict_to_feed_settings(sett, feed);
h.set_settings(feed);
}
dict get_feed_settings(feed_handle& h)
{
feed_settings s;
{
allow_threading_guard guard;
s = h.settings();
}
dict ret;
ret["url"] = s.url;
ret["auto_download"] = s.auto_download;
ret["default_ttl"] = s.default_ttl;
return ret;
}
void start_natpmp(session& s)
{
allow_threading_guard guard;
s.start_natpmp();
}
void start_upnp(session& s)
{
allow_threading_guard guard;
s.start_upnp();
}
alert const* wait_for_alert(session& s, int ms)
{
allow_threading_guard guard;
return s.wait_for_alert(milliseconds(ms));
}
list get_torrents(session& s)
{
list ret;
std::vector<torrent_handle> torrents;
{
allow_threading_guard guard;
torrents = s.get_torrents();
}
for (std::vector<torrent_handle>::iterator i = torrents.begin(); i != torrents.end(); ++i)
{
ret.append(*i);
}
return ret;
}
dict get_utp_stats(session_status const& st)
{
dict ret;
ret["num_idle"] = st.utp_stats.num_idle;
ret["num_syn_sent"] = st.utp_stats.num_syn_sent;
ret["num_connected"] = st.utp_stats.num_connected;
ret["num_fin_sent"] = st.utp_stats.num_fin_sent;
ret["num_close_wait"] = st.utp_stats.num_close_wait;
return ret;
}
list get_cache_info(session& ses, sha1_hash ih)
{
std::vector<cached_piece_info> ret;
{
allow_threading_guard guard;
ses.get_cache_info(ih, ret);
}
list pieces;
ptime now = time_now();
for (std::vector<cached_piece_info>::iterator i = ret.begin()
, end(ret.end()); i != end; ++i)
{
dict d;
d["piece"] = i->piece;
d["last_use"] = total_milliseconds(now - i->last_use) / 1000.f;
d["next_to_hash"] = i->next_to_hash;
d["kind"] = i->kind;
pieces.append(d);
}
return pieces;
}
#ifndef TORRENT_DISABLE_GEO_IP
void load_asnum_db(session& s, std::string file)
{
allow_threading_guard guard;
s.load_asnum_db(file.c_str());
}
void load_country_db(session& s, std::string file)
{
allow_threading_guard guard;
s.load_country_db(file.c_str());
}
#endif
entry save_state(session const& s, boost::uint32_t flags)
{
allow_threading_guard guard;
entry e;
s.save_state(e, flags);
return e;
}
object pop_alert(session& ses)
{
std::auto_ptr<alert> a;
{
allow_threading_guard guard;
a = ses.pop_alert();
}
return object(boost::shared_ptr<alert>(a.release()));
}
list pop_alerts(session& ses)
{
std::deque<alert*> alerts;
{
allow_threading_guard guard;
ses.pop_alerts(&alerts);
}
list ret;
for (std::deque<alert*>::iterator i = alerts.begin()
, end(alerts.end()); i != end; ++i)
{
ret.append(boost::shared_ptr<alert>(*i));
}
return ret;
}
void load_state(session& ses, entry const& st)
{
allow_threading_guard guard;
std::vector<char> buf;
bencode(std::back_inserter(buf), st);
lazy_entry e;
error_code ec;
lazy_bdecode(&buf[0], &buf[0] + buf.size(), e, ec);
TORRENT_ASSERT(!ec);
ses.load_state(e);
}
} // namespace unnamed
void bind_session()
{
#ifndef TORRENT_DISABLE_DHT
void (session::*start_dht0)() = &session::start_dht;
#ifndef TORRENT_NO_DEPRECATE
void (session::*start_dht1)(entry const&) = &session::start_dht;
#endif
#endif
class_<session_status>("session_status")
.def_readonly("has_incoming_connections", &session_status::has_incoming_connections)
.def_readonly("upload_rate", &session_status::upload_rate)
.def_readonly("download_rate", &session_status::download_rate)
.def_readonly("total_download", &session_status::total_download)
.def_readonly("total_upload", &session_status::total_upload)
.def_readonly("payload_upload_rate", &session_status::payload_upload_rate)
.def_readonly("payload_download_rate", &session_status::payload_download_rate)
.def_readonly("total_payload_download", &session_status::total_payload_download)
.def_readonly("total_payload_upload", &session_status::total_payload_upload)
.def_readonly("ip_overhead_upload_rate", &session_status::ip_overhead_upload_rate)
.def_readonly("ip_overhead_download_rate", &session_status::ip_overhead_download_rate)
.def_readonly("total_ip_overhead_download", &session_status::total_ip_overhead_download)
.def_readonly("total_ip_overhead_upload", &session_status::total_ip_overhead_upload)
.def_readonly("dht_upload_rate", &session_status::dht_upload_rate)
.def_readonly("dht_download_rate", &session_status::dht_download_rate)
.def_readonly("total_dht_download", &session_status::total_dht_download)
.def_readonly("total_dht_upload", &session_status::total_dht_upload)
.def_readonly("tracker_upload_rate", &session_status::tracker_upload_rate)
.def_readonly("tracker_download_rate", &session_status::tracker_download_rate)
.def_readonly("total_tracker_download", &session_status::total_tracker_download)
.def_readonly("total_tracker_upload", &session_status::total_tracker_upload)
.def_readonly("total_redundant_bytes", &session_status::total_redundant_bytes)
.def_readonly("total_failed_bytes", &session_status::total_failed_bytes)
.def_readonly("num_peers", &session_status::num_peers)
.def_readonly("num_unchoked", &session_status::num_unchoked)
.def_readonly("allowed_upload_slots", &session_status::allowed_upload_slots)
.def_readonly("up_bandwidth_queue", &session_status::up_bandwidth_queue)
.def_readonly("down_bandwidth_queue", &session_status::down_bandwidth_queue)
.def_readonly("up_bandwidth_bytes_queue", &session_status::up_bandwidth_bytes_queue)
.def_readonly("down_bandwidth_bytes_queue", &session_status::down_bandwidth_bytes_queue)
.def_readonly("optimistic_unchoke_counter", &session_status::optimistic_unchoke_counter)
.def_readonly("unchoke_counter", &session_status::unchoke_counter)
#ifndef TORRENT_DISABLE_DHT
.def_readonly("dht_nodes", &session_status::dht_nodes)
.def_readonly("dht_node_cache", &session_status::dht_node_cache)
.def_readonly("dht_torrents", &session_status::dht_torrents)
.def_readonly("dht_global_nodes", &session_status::dht_global_nodes)
.def_readonly("active_requests", &session_status::active_requests)
.def_readonly("dht_total_allocations", &session_status::dht_total_allocations)
#endif
.add_property("utp_stats", &get_utp_stats)
;
#ifndef TORRENT_DISABLE_DHT
class_<dht_lookup>("dht_lookup")
.def_readonly("type", &dht_lookup::type)
.def_readonly("outstanding_requests", &dht_lookup::outstanding_requests)
.def_readonly("timeouts", &dht_lookup::timeouts)
.def_readonly("response", &dht_lookup::responses)
.def_readonly("branch_factor", &dht_lookup::branch_factor)
;
#endif
enum_<storage_mode_t>("storage_mode_t")
.value("storage_mode_allocate", storage_mode_allocate)
.value("storage_mode_sparse", storage_mode_sparse)
#ifndef TORRENT_NO_DEPRECATE
.value("storage_mode_compact", storage_mode_compact)
#endif
;
enum_<session::options_t>("options_t")
.value("delete_files", session::delete_files)
;
enum_<session::session_flags_t>("session_flags_t")
.value("add_default_plugins", session::add_default_plugins)
.value("start_default_features", session::start_default_features)
;
enum_<add_torrent_params::flags_t>("add_torrent_params_flags_t")
.value("flag_seed_mode", add_torrent_params::flag_seed_mode)
.value("flag_override_resume_data", add_torrent_params::flag_override_resume_data)
.value("flag_upload_mode", add_torrent_params::flag_upload_mode)
.value("flag_share_mode", add_torrent_params::flag_share_mode)
.value("flag_apply_ip_filter", add_torrent_params::flag_apply_ip_filter)
.value("flag_paused", add_torrent_params::flag_paused)
.value("flag_auto_managed", add_torrent_params::flag_auto_managed)
.value("flag_duplicate_is_error", add_torrent_params::flag_duplicate_is_error)
.value("flag_merge_resume_trackers", add_torrent_params::flag_merge_resume_trackers)
.value("flag_update_subscribe", add_torrent_params::flag_update_subscribe)
;
class_<cache_status>("cache_status")
.def_readonly("blocks_written", &cache_status::blocks_written)
.def_readonly("writes", &cache_status::writes)
.def_readonly("blocks_read", &cache_status::blocks_read)
.def_readonly("blocks_read_hit", &cache_status::blocks_read_hit)
.def_readonly("reads", &cache_status::reads)
.def_readonly("queued_bytes", &cache_status::queued_bytes)
.def_readonly("cache_size", &cache_status::cache_size)
.def_readonly("read_cache_size", &cache_status::read_cache_size)
.def_readonly("total_used_buffers", &cache_status::total_used_buffers)
.def_readonly("average_queue_time", &cache_status::average_queue_time)
.def_readonly("average_read_time", &cache_status::average_read_time)
.def_readonly("average_write_time", &cache_status::average_write_time)
.def_readonly("average_hash_time", &cache_status::average_hash_time)
.def_readonly("average_job_time", &cache_status::average_job_time)
.def_readonly("average_sort_time", &cache_status::average_sort_time)
.def_readonly("job_queue_length", &cache_status::job_queue_length)
.def_readonly("cumulative_job_time", &cache_status::cumulative_job_time)
.def_readonly("cumulative_read_time", &cache_status::cumulative_read_time)
.def_readonly("cumulative_write_time", &cache_status::cumulative_write_time)
.def_readonly("cumulative_hash_time", &cache_status::cumulative_hash_time)
.def_readonly("cumulative_sort_time", &cache_status::cumulative_sort_time)
.def_readonly("total_read_back", &cache_status::total_read_back)
.def_readonly("read_queue_size", &cache_status::read_queue_size)
;
class_<session, boost::noncopyable>("session", no_init)
.def(
init<fingerprint, int>((
arg("fingerprint")=fingerprint("LT",0,1,0,0)
, arg("flags")=session::start_default_features | session::add_default_plugins))
)
.def("post_torrent_updates", allow_threads(&session::post_torrent_updates))
.def(
"listen_on", &listen_on
, (arg("min"), "max", arg("interface") = (char const*)0, arg("flags") = 0)
)
.def("outgoing_ports", &outgoing_ports)
.def("is_listening", allow_threads(&session::is_listening))
.def("listen_port", allow_threads(&session::listen_port))
.def("status", allow_threads(&session::status))
#ifndef TORRENT_DISABLE_DHT
.def("add_dht_node", add_dht_node)
.def(
"add_dht_router", &add_dht_router
, (arg("router"), "port")
)
.def("is_dht_running", allow_threads(&session::is_dht_running))
.def("set_dht_settings", allow_threads(&session::set_dht_settings))
.def("start_dht", allow_threads(start_dht0))
.def("stop_dht", allow_threads(&session::stop_dht))
#ifndef TORRENT_NO_DEPRECATE
.def("start_dht", allow_threads(start_dht1))
.def("dht_state", allow_threads(&session::dht_state))
.def("set_dht_proxy", allow_threads(&session::set_dht_proxy))
.def("dht_proxy", allow_threads(&session::dht_proxy))
#endif
#endif
.def("add_torrent", &add_torrent)
.def("async_add_torrent", &async_add_torrent)
#ifndef BOOST_NO_EXCEPTIONS
#ifndef TORRENT_NO_DEPRECATE
.def(
"add_torrent", &add_torrent_depr
, (
arg("resume_data") = entry(),
arg("storage_mode") = storage_mode_sparse,
arg("paused") = false
)
)
#endif
#endif
.def("add_feed", &add_feed)
.def("remove_torrent", allow_threads(&session::remove_torrent), arg("option") = 0)
#ifndef TORRENT_NO_DEPRECATE
.def("set_local_download_rate_limit", allow_threads(&session::set_local_download_rate_limit))
.def("local_download_rate_limit", allow_threads(&session::local_download_rate_limit))
.def("set_local_upload_rate_limit", allow_threads(&session::set_local_upload_rate_limit))
.def("local_upload_rate_limit", allow_threads(&session::local_upload_rate_limit))
.def("set_download_rate_limit", allow_threads(&session::set_download_rate_limit))
.def("download_rate_limit", allow_threads(&session::download_rate_limit))
.def("set_upload_rate_limit", allow_threads(&session::set_upload_rate_limit))
.def("upload_rate_limit", allow_threads(&session::upload_rate_limit))
.def("set_max_uploads", allow_threads(&session::set_max_uploads))
.def("set_max_connections", allow_threads(&session::set_max_connections))
.def("max_connections", allow_threads(&session::max_connections))
.def("set_max_half_open_connections", allow_threads(&session::set_max_half_open_connections))
.def("num_connections", allow_threads(&session::num_connections))
.def("set_settings", &session::set_settings)
.def("settings", &session::settings)
.def("get_settings", &session_get_settings)
#else
.def("settings", &session_get_settings)
.def("get_settings", &session_get_settings)
#endif
.def("set_settings", &session_set_settings)
#ifndef TORRENT_DISABLE_ENCRYPTION
.def("set_pe_settings", allow_threads(&session::set_pe_settings))
.def("get_pe_settings", allow_threads(&session::get_pe_settings))
#endif
#ifndef TORRENT_DISABLE_GEO_IP
.def("load_asnum_db", &load_asnum_db)
.def("load_country_db", &load_country_db)
#endif
.def("load_state", &load_state)
.def("save_state", &save_state, (arg("entry"), arg("flags") = 0xffffffff))
#ifndef TORRENT_NO_DEPRECATE
.def("set_severity_level", allow_threads(&session::set_severity_level))
.def("set_alert_queue_size_limit", allow_threads(&session::set_alert_queue_size_limit))
#endif
.def("set_alert_mask", allow_threads(&session::set_alert_mask))
.def("pop_alert", &pop_alert)
.def("pop_alerts", &pop_alerts)
.def("wait_for_alert", &wait_for_alert, return_internal_reference<>())
.def("add_extension", &add_extension)
#ifndef TORRENT_NO_DEPRECATE
.def("set_peer_proxy", allow_threads(&session::set_peer_proxy))
.def("set_tracker_proxy", allow_threads(&session::set_tracker_proxy))
.def("set_web_seed_proxy", allow_threads(&session::set_web_seed_proxy))
.def("peer_proxy", allow_threads(&session::peer_proxy))
.def("tracker_proxy", allow_threads(&session::tracker_proxy))
.def("web_seed_proxy", allow_threads(&session::web_seed_proxy))
#endif
#if TORRENT_USE_I2P
.def("set_i2p_proxy", allow_threads(&session::set_i2p_proxy))
.def("i2p_proxy", allow_threads(&session::i2p_proxy))
#endif
.def("set_proxy", allow_threads(&session::set_proxy))
.def("proxy", allow_threads(&session::proxy))
.def("start_upnp", &start_upnp)
.def("stop_upnp", allow_threads(&session::stop_upnp))
.def("start_lsd", allow_threads(&session::start_lsd))
.def("stop_lsd", allow_threads(&session::stop_lsd))
.def("start_natpmp", &start_natpmp)
.def("stop_natpmp", allow_threads(&session::stop_natpmp))
.def("set_ip_filter", allow_threads(&session::set_ip_filter))
.def("get_ip_filter", allow_threads(&session::get_ip_filter))
.def("find_torrent", allow_threads(&session::find_torrent))
.def("get_torrents", &get_torrents)
.def("pause", allow_threads(&session::pause))
.def("resume", allow_threads(&session::resume))
.def("is_paused", allow_threads(&session::is_paused))
.def("id", allow_threads(&session::id))
.def("get_cache_status", allow_threads(&session::get_cache_status))
.def("get_cache_info", get_cache_info)
.def("set_peer_id", allow_threads(&session::set_peer_id))
;
enum_<session::save_state_flags_t>("save_state_flags_t")
.value("save_settings", session::save_settings)
.value("save_dht_settings", session::save_dht_settings)
.value("save_dht_state", session::save_dht_state)
.value("save_i2p_proxy", session::save_i2p_proxy)
.value("save_encryption_settings", session:: save_encryption_settings)
.value("save_as_map", session::save_as_map)
.value("save_proxy", session::save_proxy)
#ifndef TORRENT_NO_DEPRECATE
.value("save_dht_proxy", session::save_dht_proxy)
.value("save_peer_proxy", session::save_peer_proxy)
.value("save_web_proxy", session::save_web_proxy)
.value("save_tracker_proxy", session::save_tracker_proxy)
#endif
;
enum_<session::listen_on_flags_t>("listen_on_flags_t")
#ifndef TORRENT_NO_DEPRECATE
.value("listen_reuse_address", session::listen_reuse_address)
#endif
.value("listen_no_system_port", session::listen_no_system_port)
;
class_<feed_handle>("feed_handle")
.def("update_feed", &feed_handle::update_feed)
.def("get_feed_status", &get_feed_status)
.def("set_settings", &set_feed_settings)
.def("settings", &get_feed_settings)
;
register_ptr_to_python<std::auto_ptr<alert> >();
def("high_performance_seed", high_performance_seed);
def("min_memory_usage", min_memory_usage);
scope().attr("create_metadata_plugin") = "metadata_transfer";
scope().attr("create_ut_metadata_plugin") = "ut_metadata";
scope().attr("create_ut_pex_plugin") = "ut_pex";
scope().attr("create_smart_ban_plugin") = "smart_ban";
}
| deluge-clone/libtorrent | bindings/python/src/session.cpp | C++ | bsd-3-clause | 29,951 |
<?php
$this->breadcrumbs=array(
UserModule::t('Users')=>array('admin'),
UserModule::t('Create'),
);
/*$this->menu=array(
array('label'=>UserModule::t('Manage Users'), 'url'=>array('admin')),
array('label'=>UserModule::t('Manage Profile Field'), 'url'=>array('profileField/admin')),
array('label'=>UserModule::t('List User'), 'url'=>array('/user')),
);*/
?>
<section class="panel">
<header class="panel-heading"><?php echo UserModule::t("Create User"); ?></header>
<div class="panel-body">
<div class="clearfix">
<div class="pull-right"> <?php echo CHtml::link(UserModule::t('Manage Users'),array('admin'),array('class'=>'btn btn-primary')); ?> </div>
</div>
<?php echo $this->renderPartial('_form', array('model'=>$model,'profile'=>$profile)); ?>
</div>
</section>
| mazhariqbal49/thebenchmark | app/protected/modules/user/views/admin/create.php | PHP | bsd-3-clause | 806 |
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "components/sync/test/fake_server/fake_server_verifier.h"
#include <map>
#include <memory>
#include <set>
#include <vector>
#include "base/json/json_writer.h"
#include "components/sync/test/fake_server/fake_server.h"
using base::JSONWriter;
using std::string;
using testing::AssertionFailure;
using testing::AssertionResult;
using testing::AssertionSuccess;
namespace fake_server {
namespace {
AssertionResult DictionaryCreationAssertionFailure() {
return AssertionFailure() << "FakeServer failed to create an entities "
<< "dictionary.";
}
AssertionResult VerificationCountAssertionFailure(size_t actual_count,
size_t expected_count) {
return AssertionFailure() << "Actual count: " << actual_count << "; "
<< "Expected count: " << expected_count;
}
AssertionResult UnknownTypeAssertionFailure(const string& model_type) {
return AssertionFailure() << "Verification not attempted. Unknown ModelType: "
<< model_type;
}
AssertionResult VerifySessionsHierarchyEquality(
const SessionsHierarchy& expected,
const SessionsHierarchy& actual) {
if (expected.Equals(actual))
return AssertionSuccess() << "Sessions hierarchies are equal.";
return AssertionFailure() << "Sessions hierarchies are not equal. "
<< "FakeServer contents: " << actual.ToString()
<< "; Expected contents: " << expected.ToString();
}
// Caller maintains ownership of |entities|.
string ConvertFakeServerContentsToString(
const base::DictionaryValue& entities) {
string entities_str;
if (!JSONWriter::WriteWithOptions(entities, JSONWriter::OPTIONS_PRETTY_PRINT,
&entities_str)) {
entities_str = "Could not convert FakeServer contents to string.";
}
return "FakeServer contents:\n" + entities_str;
}
} // namespace
FakeServerVerifier::FakeServerVerifier(FakeServer* fake_server)
: fake_server_(fake_server) {}
FakeServerVerifier::~FakeServerVerifier() {}
AssertionResult FakeServerVerifier::VerifyEntityCountByType(
size_t expected_count,
syncer::ModelType model_type) const {
std::unique_ptr<base::DictionaryValue> entities =
fake_server_->GetEntitiesAsDictionaryValue();
if (!entities) {
return DictionaryCreationAssertionFailure();
}
string model_type_string = ModelTypeToString(model_type);
base::ListValue* entity_list = nullptr;
if (!entities->GetList(model_type_string, &entity_list)) {
return UnknownTypeAssertionFailure(model_type_string);
} else if (expected_count != entity_list->GetSize()) {
return VerificationCountAssertionFailure(entity_list->GetSize(),
expected_count)
<< "\n\n"
<< ConvertFakeServerContentsToString(*entities);
}
return AssertionSuccess();
}
AssertionResult FakeServerVerifier::VerifyEntityCountByTypeAndName(
size_t expected_count,
syncer::ModelType model_type,
const string& name) const {
std::unique_ptr<base::DictionaryValue> entities =
fake_server_->GetEntitiesAsDictionaryValue();
if (!entities) {
return DictionaryCreationAssertionFailure();
}
string model_type_string = ModelTypeToString(model_type);
base::ListValue* entity_list = nullptr;
size_t actual_count = 0;
if (entities->GetList(model_type_string, &entity_list)) {
base::Value name_value(name);
for (const auto& entity : *entity_list) {
if (name_value.Equals(&entity))
actual_count++;
}
}
if (!entity_list) {
return UnknownTypeAssertionFailure(model_type_string);
} else if (actual_count != expected_count) {
return VerificationCountAssertionFailure(actual_count, expected_count)
<< "; Name: " << name << "\n\n"
<< ConvertFakeServerContentsToString(*entities);
}
return AssertionSuccess();
}
AssertionResult FakeServerVerifier::VerifySessions(
const SessionsHierarchy& expected_sessions) {
std::vector<sync_pb::SyncEntity> sessions =
fake_server_->GetSyncEntitiesByModelType(syncer::SESSIONS);
// Look for the sessions entity containing a SessionHeader and cache all tab
// IDs/URLs. These will be used later to construct a SessionsHierarchy.
sync_pb::SessionHeader session_header;
std::map<int, int> tab_ids_to_window_ids;
std::map<int, std::string> tab_ids_to_urls;
std::string session_tag;
for (const auto& entity : sessions) {
sync_pb::SessionSpecifics session_specifics = entity.specifics().session();
// Ensure that all session tags match the first entity. Only one session is
// supported for verification at this time.
if (session_tag.empty()) {
session_tag = session_specifics.session_tag();
} else if (session_specifics.session_tag() != session_tag) {
return AssertionFailure() << "Multiple session tags found.";
}
if (session_specifics.has_header()) {
session_header = session_specifics.header();
} else if (session_specifics.has_tab()) {
const sync_pb::SessionTab& tab = session_specifics.tab();
const sync_pb::TabNavigation& nav =
tab.navigation(tab.current_navigation_index());
// Only read from tabs that have a title on their current navigation
// entry. This the result of an oddity around the timing of sessions
// related changes. Sometimes when opening a new window, the first
// navigation will be committed before the title has been set. Then a
// subsequent commit will go through for that same navigation. Because
// this logic is used to ensure synchronization, we are going to exclude
// partially omitted navigations. The full navigation should typically be
// committed in full immediately after we fail a check because of this.
if (nav.has_title()) {
tab_ids_to_window_ids[tab.tab_id()] = tab.window_id();
tab_ids_to_urls[tab.tab_id()] = nav.virtual_url();
}
}
}
// Create a SessionsHierarchy from the cached SyncEntity data. This loop over
// the SessionHeader also ensures its data corresponds to the data stored in
// each SessionTab.
SessionsHierarchy actual_sessions;
for (const auto& window : session_header.window()) {
std::multiset<std::string> tab_urls;
for (int tab_id : window.tab()) {
if (tab_ids_to_window_ids.find(tab_id) == tab_ids_to_window_ids.end()) {
return AssertionFailure() << "Malformed data: Tab entity not found.";
}
tab_urls.insert(tab_ids_to_urls[tab_id]);
}
actual_sessions.AddWindow(tab_urls);
}
return VerifySessionsHierarchyEquality(expected_sessions, actual_sessions);
}
} // namespace fake_server
| endlessm/chromium-browser | components/sync/test/fake_server/fake_server_verifier.cc | C++ | bsd-3-clause | 6,942 |
; IBM905 UCS-2 decoding rule
; source: ftp://dkuug.dk/i18n/charmaps/IBM905
any [
#{009C} (insert tail result #{04}) |
#{0009} (insert tail result #{05}) |
#{0086} (insert tail result #{06}) |
#{0097} (insert tail result #{08}) |
#{008D} (insert tail result #{09}) |
#{008E} (insert tail result #{0A}) |
#{009D} (insert tail result #{14}) |
#{0085} (insert tail result #{15}) |
#{0008} (insert tail result #{16}) |
#{0087} (insert tail result #{17}) |
#{0092} (insert tail result #{1A}) |
#{008F} (insert tail result #{1B}) |
#{0080} (insert tail result #{20}) |
#{0081} (insert tail result #{21}) |
#{0082} (insert tail result #{22}) |
#{0083} (insert tail result #{23}) |
#{0084} (insert tail result #{24}) |
#{000A} (insert tail result #{25}) |
#{0017} (insert tail result #{26}) |
#{001B} (insert tail result #{27}) |
#{0088} (insert tail result #{28}) |
#{0089} (insert tail result #{29}) |
#{008A} (insert tail result #{2A}) |
#{008B} (insert tail result #{2B}) |
#{008C} (insert tail result #{2C}) |
#{0005} (insert tail result #{2D}) |
#{0006} (insert tail result #{2E}) |
#{0007} (insert tail result #{2F}) |
#{0090} (insert tail result #{30}) |
#{0091} (insert tail result #{31}) |
#{0016} (insert tail result #{32}) |
#{0093} (insert tail result #{33}) |
#{0094} (insert tail result #{34}) |
#{0095} (insert tail result #{35}) |
#{0096} (insert tail result #{36}) |
#{0004} (insert tail result #{37}) |
#{0098} (insert tail result #{38}) |
#{0099} (insert tail result #{39}) |
#{009A} (insert tail result #{3A}) |
#{009B} (insert tail result #{3B}) |
#{0014} (insert tail result #{3C}) |
#{0015} (insert tail result #{3D}) |
#{009E} (insert tail result #{3E}) |
#{001A} (insert tail result #{3F}) |
#{0020} (insert tail result #{40}) |
#{00E2} (insert tail result #{42}) |
#{00E4} (insert tail result #{43}) |
#{00E0} (insert tail result #{44}) |
#{00E1} (insert tail result #{45}) |
#{010B} (insert tail result #{47}) |
#{007B} (insert tail result #{48}) |
#{00F1} (insert tail result #{49}) |
#{00C7} (insert tail result #{4A}) |
#{002E} (insert tail result #{4B}) |
#{003C} (insert tail result #{4C}) |
#{0028} (insert tail result #{4D}) |
#{002B} (insert tail result #{4E}) |
#{0021} (insert tail result #{4F}) |
#{0026} (insert tail result #{50}) |
#{00E9} (insert tail result #{51}) |
#{00EA} (insert tail result #{52}) |
#{00EB} (insert tail result #{53}) |
#{00E8} (insert tail result #{54}) |
#{00ED} (insert tail result #{55}) |
#{00EE} (insert tail result #{56}) |
#{00EF} (insert tail result #{57}) |
#{00EC} (insert tail result #{58}) |
#{00DF} (insert tail result #{59}) |
#{011E} (insert tail result #{5A}) |
#{0130} (insert tail result #{5B}) |
#{002A} (insert tail result #{5C}) |
#{0029} (insert tail result #{5D}) |
#{003B} (insert tail result #{5E}) |
#{005E} (insert tail result #{5F}) |
#{002D} (insert tail result #{60}) |
#{002F} (insert tail result #{61}) |
#{00C2} (insert tail result #{62}) |
#{00C4} (insert tail result #{63}) |
#{00C0} (insert tail result #{64}) |
#{00C1} (insert tail result #{65}) |
#{010A} (insert tail result #{67}) |
#{005B} (insert tail result #{68}) |
#{00D1} (insert tail result #{69}) |
#{015F} (insert tail result #{6A}) |
#{002C} (insert tail result #{6B}) |
#{0025} (insert tail result #{6C}) |
#{005F} (insert tail result #{6D}) |
#{003E} (insert tail result #{6E}) |
#{003F} (insert tail result #{6F}) |
#{00C9} (insert tail result #{71}) |
#{00CA} (insert tail result #{72}) |
#{00CB} (insert tail result #{73}) |
#{00C8} (insert tail result #{74}) |
#{00CD} (insert tail result #{75}) |
#{00CE} (insert tail result #{76}) |
#{00CF} (insert tail result #{77}) |
#{00CC} (insert tail result #{78}) |
#{0131} (insert tail result #{79}) |
#{003A} (insert tail result #{7A}) |
#{00D6} (insert tail result #{7B}) |
#{015E} (insert tail result #{7C}) |
#{0027} (insert tail result #{7D}) |
#{003D} (insert tail result #{7E}) |
#{00DC} (insert tail result #{7F}) |
#{02D8} (insert tail result #{80}) |
#{0061} (insert tail result #{81}) |
#{0062} (insert tail result #{82}) |
#{0063} (insert tail result #{83}) |
#{0064} (insert tail result #{84}) |
#{0065} (insert tail result #{85}) |
#{0066} (insert tail result #{86}) |
#{0067} (insert tail result #{87}) |
#{0068} (insert tail result #{88}) |
#{0069} (insert tail result #{89}) |
#{0127} (insert tail result #{8A}) |
#{0109} (insert tail result #{8B}) |
#{015D} (insert tail result #{8C}) |
#{016D} (insert tail result #{8D}) |
#{007C} (insert tail result #{8F}) |
#{00B0} (insert tail result #{90}) |
#{006A} (insert tail result #{91}) |
#{006B} (insert tail result #{92}) |
#{006C} (insert tail result #{93}) |
#{006D} (insert tail result #{94}) |
#{006E} (insert tail result #{95}) |
#{006F} (insert tail result #{96}) |
#{0070} (insert tail result #{97}) |
#{0071} (insert tail result #{98}) |
#{0072} (insert tail result #{99}) |
#{0125} (insert tail result #{9A}) |
#{011D} (insert tail result #{9B}) |
#{0135} (insert tail result #{9C}) |
#{02DB} (insert tail result #{9D}) |
#{00A4} (insert tail result #{9F}) |
#{00B5} (insert tail result #{A0}) |
#{00F6} (insert tail result #{A1}) |
#{0073} (insert tail result #{A2}) |
#{0074} (insert tail result #{A3}) |
#{0075} (insert tail result #{A4}) |
#{0076} (insert tail result #{A5}) |
#{0077} (insert tail result #{A6}) |
#{0078} (insert tail result #{A7}) |
#{0079} (insert tail result #{A8}) |
#{007A} (insert tail result #{A9}) |
#{0126} (insert tail result #{AA}) |
#{0108} (insert tail result #{AB}) |
#{015C} (insert tail result #{AC}) |
#{016C} (insert tail result #{AD}) |
#{0040} (insert tail result #{AF}) |
#{00B7} (insert tail result #{B0}) |
#{00A3} (insert tail result #{B1}) |
#{017C} (insert tail result #{B2}) |
#{007D} (insert tail result #{B3}) |
#{017B} (insert tail result #{B4}) |
#{00A7} (insert tail result #{B5}) |
#{005D} (insert tail result #{B6}) |
#{00BD} (insert tail result #{B8}) |
#{0024} (insert tail result #{B9}) |
#{0124} (insert tail result #{BA}) |
#{011C} (insert tail result #{BB}) |
#{0134} (insert tail result #{BC}) |
#{00A8} (insert tail result #{BD}) |
#{00B4} (insert tail result #{BE}) |
#{00D7} (insert tail result #{BF}) |
#{00E7} (insert tail result #{C0}) |
#{0041} (insert tail result #{C1}) |
#{0042} (insert tail result #{C2}) |
#{0043} (insert tail result #{C3}) |
#{0044} (insert tail result #{C4}) |
#{0045} (insert tail result #{C5}) |
#{0046} (insert tail result #{C6}) |
#{0047} (insert tail result #{C7}) |
#{0048} (insert tail result #{C8}) |
#{0049} (insert tail result #{C9}) |
#{00AD} (insert tail result #{CA}) |
#{00F4} (insert tail result #{CB}) |
#{007E} (insert tail result #{CC}) |
#{00F2} (insert tail result #{CD}) |
#{00F3} (insert tail result #{CE}) |
#{0121} (insert tail result #{CF}) |
#{011F} (insert tail result #{D0}) |
#{004A} (insert tail result #{D1}) |
#{004B} (insert tail result #{D2}) |
#{004C} (insert tail result #{D3}) |
#{004D} (insert tail result #{D4}) |
#{004E} (insert tail result #{D5}) |
#{004F} (insert tail result #{D6}) |
#{0050} (insert tail result #{D7}) |
#{0051} (insert tail result #{D8}) |
#{0052} (insert tail result #{D9}) |
#{0060} (insert tail result #{DA}) |
#{00FB} (insert tail result #{DB}) |
#{005C} (insert tail result #{DC}) |
#{00F9} (insert tail result #{DD}) |
#{00FA} (insert tail result #{DE}) |
#{00FC} (insert tail result #{E0}) |
#{00F7} (insert tail result #{E1}) |
#{0053} (insert tail result #{E2}) |
#{0054} (insert tail result #{E3}) |
#{0055} (insert tail result #{E4}) |
#{0056} (insert tail result #{E5}) |
#{0057} (insert tail result #{E6}) |
#{0058} (insert tail result #{E7}) |
#{0059} (insert tail result #{E8}) |
#{005A} (insert tail result #{E9}) |
#{00B2} (insert tail result #{EA}) |
#{00D4} (insert tail result #{EB}) |
#{0023} (insert tail result #{EC}) |
#{00D2} (insert tail result #{ED}) |
#{00D3} (insert tail result #{EE}) |
#{0120} (insert tail result #{EF}) |
#{0030} (insert tail result #{F0}) |
#{0031} (insert tail result #{F1}) |
#{0032} (insert tail result #{F2}) |
#{0033} (insert tail result #{F3}) |
#{0034} (insert tail result #{F4}) |
#{0035} (insert tail result #{F5}) |
#{0036} (insert tail result #{F6}) |
#{0037} (insert tail result #{F7}) |
#{0038} (insert tail result #{F8}) |
#{0039} (insert tail result #{F9}) |
#{00B3} (insert tail result #{FA}) |
#{00DB} (insert tail result #{FB}) |
#{0022} (insert tail result #{FC}) |
#{00D9} (insert tail result #{FD}) |
#{00DA} (insert tail result #{FE}) |
#{009F} (insert tail result #{FF}) |
#{0004} (insert tail result #{37}) |
#{0005} (insert tail result #{2D}) |
#{0006} (insert tail result #{2E}) |
#{0007} (insert tail result #{2F}) |
#{0007} (insert tail result #{2F}) |
#{0008} (insert tail result #{16}) |
#{0009} (insert tail result #{05}) |
#{000A} (insert tail result #{25}) |
#{0014} (insert tail result #{3C}) |
#{0015} (insert tail result #{3D}) |
#{0016} (insert tail result #{32}) |
#{0017} (insert tail result #{26}) |
#{001A} (insert tail result #{3F}) |
#{001B} (insert tail result #{27}) |
#{0020} (insert tail result #{40}) |
#{0021} (insert tail result #{4F}) |
#{0022} (insert tail result #{FC}) |
#{0023} (insert tail result #{EC}) |
#{0024} (insert tail result #{B9}) |
#{0025} (insert tail result #{6C}) |
#{0026} (insert tail result #{50}) |
#{0027} (insert tail result #{7D}) |
#{0028} (insert tail result #{4D}) |
#{0029} (insert tail result #{5D}) |
#{002A} (insert tail result #{5C}) |
#{002B} (insert tail result #{4E}) |
#{002C} (insert tail result #{6B}) |
#{002D} (insert tail result #{60}) |
#{002D} (insert tail result #{60}) |
#{002E} (insert tail result #{4B}) |
#{002E} (insert tail result #{4B}) |
#{002F} (insert tail result #{61}) |
#{002F} (insert tail result #{61}) |
#{0030} (insert tail result #{F0}) |
#{0031} (insert tail result #{F1}) |
#{0032} (insert tail result #{F2}) |
#{0033} (insert tail result #{F3}) |
#{0034} (insert tail result #{F4}) |
#{0035} (insert tail result #{F5}) |
#{0036} (insert tail result #{F6}) |
#{0037} (insert tail result #{F7}) |
#{0038} (insert tail result #{F8}) |
#{0039} (insert tail result #{F9}) |
#{003A} (insert tail result #{7A}) |
#{003B} (insert tail result #{5E}) |
#{003C} (insert tail result #{4C}) |
#{003D} (insert tail result #{7E}) |
#{003E} (insert tail result #{6E}) |
#{003F} (insert tail result #{6F}) |
#{0040} (insert tail result #{AF}) |
#{005B} (insert tail result #{68}) |
#{005C} (insert tail result #{DC}) |
#{005C} (insert tail result #{DC}) |
#{005D} (insert tail result #{B6}) |
#{005E} (insert tail result #{5F}) |
#{005E} (insert tail result #{5F}) |
#{005F} (insert tail result #{6D}) |
#{005F} (insert tail result #{6D}) |
#{0060} (insert tail result #{DA}) |
#{007B} (insert tail result #{48}) |
#{007B} (insert tail result #{48}) |
#{007C} (insert tail result #{8F}) |
#{007D} (insert tail result #{B3}) |
#{007D} (insert tail result #{B3}) |
#{007E} (insert tail result #{CC}) |
#{00} copy c 1 skip (insert tail result c) |
copy c 2 skip (decodeUnknownChar c)
] | Oldes/rs | projects/ucs2/latest/charmaps/IBM905.d.rb | Ruby | bsd-3-clause | 11,261 |
// (C) Copyright Steve Cleary, Beman Dawes, Howard Hinnant & John Maddock 2000.
// Use, modification and distribution are subject to the Boost Software License,
// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt).
//
// See http://www.boost.org/libs/type_traits for most recent version including documentation.
#ifndef BOOST_TT_IS_STATELESS_HPP_INCLUDED
#define BOOST_TT_IS_STATELESS_HPP_INCLUDED
#include <boost/type_traits/has_trivial_constructor.hpp>
#include <boost/type_traits/has_trivial_copy.hpp>
#include <boost/type_traits/has_trivial_destructor.hpp>
#include <boost/type_traits/is_class.hpp>
#include <boost/type_traits/is_empty.hpp>
#include <boost/type_traits/detail/ice_and.hpp>
#include <boost/config.hpp>
// should be the last #include
#include <boost/type_traits/detail/bool_trait_def.hpp>
namespace pdalboost {} namespace boost = pdalboost; namespace pdalboost {
namespace detail {
template <typename T>
struct is_stateless_impl
{
BOOST_STATIC_CONSTANT(bool, value =
(::pdalboost::type_traits::ice_and<
::pdalboost::has_trivial_constructor<T>::value,
::pdalboost::has_trivial_copy<T>::value,
::pdalboost::has_trivial_destructor<T>::value,
::pdalboost::is_class<T>::value,
::pdalboost::is_empty<T>::value
>::value));
};
} // namespace detail
BOOST_TT_AUX_BOOL_TRAIT_DEF1(is_stateless,T,::pdalboost::detail::is_stateless_impl<T>::value)
} // namespace pdalboost
#include <boost/type_traits/detail/bool_trait_undef.hpp>
#endif // BOOST_TT_IS_STATELESS_HPP_INCLUDED
| verma/PDAL | boost/boost/type_traits/is_stateless.hpp | C++ | bsd-3-clause | 1,598 |
<?php
namespace app\models;
/*
DROP TABLE IF EXISTS wx_suggest;
CREATE TABLE wx_suggest (
id int(10) unsigned NOT NULL AUTO_INCREMENT PRIMARY KEY,
gh_id VARCHAR(32) NOT NULL DEFAULT '',
openid VARCHAR(32) NOT NULL DEFAULT '',
nickname VARCHAR(64) NOT NULL DEFAULT '',
headimgurl VARCHAR(256) NOT NULL DEFAULT '',
detail TEXT NOT NULL DEFAULT '',
create_time TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
KEY idx_gh_id_open_id(gh_id, openid)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
*/
use Yii;
use yii\db\ActiveRecord;
use yii\helpers\Security;
use yii\web\IdentityInterface;
use yii\behaviors\TimestampBehavior;
use yii\db\Expression;
class MSuggest extends ActiveRecord
{
public static function tableName()
{
return 'wx_suggest';
}
public function rules()
{
return [
//['title', 'filter', 'filter' => 'trim'],
//['title', 'required'],
//['title', 'string', 'min' => 2, 'max' => 128],
['detail', 'filter', 'filter' => 'trim'],
['detail', 'required'],
['detail', 'string', 'min' => 2, 'max' => 512],
[['nickname', 'headimgurl'], 'safe'],
//['mobile', 'filter', 'filter' => 'trim'],
//['mobile', 'required'],
//['mobile', 'match', 'pattern' => '/((\d{11})|^((\d{7,8})|(\d{4}|\d{3})-(\d{7,8})|(\d{4}|\d{3})-(\d{7,8})-(\d{4}|\d{3}|\d{2}|\d{1})|(\d{7,8})-(\d{4}|\d{3}|\d{2}|\d{1}))$)/' ],
];
}
public function attributeLabels()
{
return [
'mobile'=>'手机号',
'title'=>'吐槽标题',
'detail'=>'消息内容',
];
}
}
/*
title VARCHAR(128) NOT NULL DEFAULT '',
mobile VARCHAR(16) NOT NULL DEFAULT '',
*/
| yjhu/wowewe | models/MSuggest.php | PHP | bsd-3-clause | 1,866 |
<?php
/*
* Original code based on the CommonMark PHP parser (https://github.com/thephpleague/commonmark/)
* - (c) Colin O'Dell
*/
namespace OneMoreThing\CommonMark\Strikethrough;
use League\CommonMark\Delimiter\Delimiter;
use League\CommonMark\Inline\Element\Text;
use League\CommonMark\Inline\Parser\AbstractInlineParser;
use League\CommonMark\InlineParserContext;
use League\CommonMark\Util\RegexHelper;
class StrikethroughParser extends AbstractInlineParser
{
/**
* @return string[]
*/
public function getCharacters()
{
return ['~'];
}
/**
* @param InlineParserContext $inlineContext
*
* @return bool
*/
public function parse(InlineParserContext $inlineContext)
{
$character = $inlineContext->getCursor()->getCharacter();
if ($character !== '~') {
return false;
}
$numDelims = 0;
$cursor = $inlineContext->getCursor();
$charBefore = $cursor->peek(-1);
if ($charBefore === null) {
$charBefore = "\n";
}
while ($cursor->peek($numDelims) === '~') {
++$numDelims;
}
// Skip single delims
if ($numDelims === 1) {
return false;
}
$cursor->advanceBy($numDelims);
$charAfter = $cursor->getCharacter();
if ($charAfter === null) {
$charAfter = "\n";
}
$afterIsWhitespace = preg_match('/\pZ|\s/u', $charAfter);
$afterIsPunctuation = preg_match(RegexHelper::REGEX_PUNCTUATION, $charAfter);
$beforeIsWhitespace = preg_match('/\pZ|\s/u', $charBefore);
$beforeIsPunctuation = preg_match(RegexHelper::REGEX_PUNCTUATION, $charBefore);
$leftFlanking = $numDelims > 0 && !$afterIsWhitespace &&
!($afterIsPunctuation &&
!$beforeIsWhitespace &&
!$beforeIsPunctuation);
$rightFlanking = $numDelims > 0 && !$beforeIsWhitespace &&
!($beforeIsPunctuation &&
!$afterIsWhitespace &&
!$afterIsPunctuation);
if ($character === '_') {
$canOpen = $leftFlanking && (!$rightFlanking || $beforeIsPunctuation);
$canClose = $rightFlanking && (!$leftFlanking || $afterIsPunctuation);
} else {
$canOpen = $leftFlanking;
$canClose = $rightFlanking;
}
$node = new Text($cursor->getPreviousText(), [
'delim' => true
]);
$inlineContext->getContainer()->appendChild($node);
// Add entry to stack to this opener
$delimiter = new Delimiter($character, $numDelims, $node, $canOpen, $canClose);
$inlineContext->getDelimiterStack()->push($delimiter);
return true;
}
}
| omt/commonmark-strikethrough-extension | src/StrikethroughParser.php | PHP | bsd-3-clause | 2,787 |
<?php
namespace Jp\CriminalLaw\Entity\罪;
interface 不真正不作為犯 extends 不作為犯
{
}
| 77web/JpCriminalLaw | src/Entity/罪/不真正不作為犯.php | PHP | bsd-3-clause | 105 |
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "components/ntp_snippets/ntp_snippets_service.h"
#include <algorithm>
#include <utility>
#include "base/command_line.h"
#include "base/files/file_path.h"
#include "base/files/file_util.h"
#include "base/json/json_reader.h"
#include "base/location.h"
#include "base/path_service.h"
#include "base/strings/string_number_conversions.h"
#include "base/task_runner_util.h"
#include "base/time/time.h"
#include "base/values.h"
#include "components/ntp_snippets/pref_names.h"
#include "components/ntp_snippets/switches.h"
#include "components/prefs/pref_registry_simple.h"
#include "components/prefs/pref_service.h"
#include "components/suggestions/proto/suggestions.pb.h"
using suggestions::ChromeSuggestion;
using suggestions::SuggestionsProfile;
using suggestions::SuggestionsService;
namespace ntp_snippets {
namespace {
const int kFetchingIntervalWifiChargingSeconds = 30 * 60;
const int kFetchingIntervalWifiSeconds = 2 * 60 * 60;
const int kFetchingIntervalFallbackSeconds = 24 * 60 * 60;
const int kDefaultExpiryTimeMins = 24 * 60;
base::TimeDelta GetFetchingInterval(const char* switch_name,
int default_value_seconds) {
int value_seconds = default_value_seconds;
const base::CommandLine& cmdline = *base::CommandLine::ForCurrentProcess();
if (cmdline.HasSwitch(switch_name)) {
std::string str = cmdline.GetSwitchValueASCII(switch_name);
int switch_value_seconds = 0;
if (base::StringToInt(str, &switch_value_seconds))
value_seconds = switch_value_seconds;
else
LOG(WARNING) << "Invalid value for switch " << switch_name;
}
return base::TimeDelta::FromSeconds(value_seconds);
}
base::TimeDelta GetFetchingIntervalWifiCharging() {
return GetFetchingInterval(switches::kFetchingIntervalWifiChargingSeconds,
kFetchingIntervalWifiChargingSeconds);
}
base::TimeDelta GetFetchingIntervalWifi() {
return GetFetchingInterval(switches::kFetchingIntervalWifiSeconds,
kFetchingIntervalWifiSeconds);
}
base::TimeDelta GetFetchingIntervalFallback() {
return GetFetchingInterval(switches::kFetchingIntervalFallbackSeconds,
kFetchingIntervalFallbackSeconds);
}
// Extracts the hosts from |suggestions| and returns them in a set.
std::set<std::string> GetSuggestionsHosts(
const SuggestionsProfile& suggestions) {
std::set<std::string> hosts;
for (int i = 0; i < suggestions.suggestions_size(); ++i) {
const ChromeSuggestion& suggestion = suggestions.suggestions(i);
GURL url(suggestion.url());
if (url.is_valid())
hosts.insert(url.host());
}
return hosts;
}
const char kContentInfo[] = "contentInfo";
// Parses snippets from |list| and adds them to |snippets|. Returns true on
// success, false if anything went wrong.
bool AddSnippetsFromListValue(const base::ListValue& list,
NTPSnippetsService::NTPSnippetStorage* snippets) {
for (const base::Value* const value : list) {
const base::DictionaryValue* dict = nullptr;
if (!value->GetAsDictionary(&dict))
return false;
const base::DictionaryValue* content = nullptr;
if (!dict->GetDictionary(kContentInfo, &content))
return false;
scoped_ptr<NTPSnippet> snippet = NTPSnippet::CreateFromDictionary(*content);
if (!snippet)
return false;
snippets->push_back(std::move(snippet));
}
return true;
}
scoped_ptr<base::ListValue> SnippetsToListValue(
const NTPSnippetsService::NTPSnippetStorage& snippets) {
scoped_ptr<base::ListValue> list(new base::ListValue);
for (const auto& snippet : snippets) {
scoped_ptr<base::DictionaryValue> dict(new base::DictionaryValue);
dict->Set(kContentInfo, snippet->ToDictionary());
list->Append(std::move(dict));
}
return list;
}
} // namespace
NTPSnippetsService::NTPSnippetsService(
PrefService* pref_service,
SuggestionsService* suggestions_service,
scoped_refptr<base::SequencedTaskRunner> file_task_runner,
const std::string& application_language_code,
NTPSnippetsScheduler* scheduler,
scoped_ptr<NTPSnippetsFetcher> snippets_fetcher,
const ParseJSONCallback& parse_json_callback)
: pref_service_(pref_service),
suggestions_service_(suggestions_service),
file_task_runner_(file_task_runner),
application_language_code_(application_language_code),
scheduler_(scheduler),
snippets_fetcher_(std::move(snippets_fetcher)),
parse_json_callback_(parse_json_callback),
weak_ptr_factory_(this) {
snippets_fetcher_subscription_ = snippets_fetcher_->AddCallback(base::Bind(
&NTPSnippetsService::OnSnippetsDownloaded, base::Unretained(this)));
}
NTPSnippetsService::~NTPSnippetsService() {}
// static
void NTPSnippetsService::RegisterProfilePrefs(PrefRegistrySimple* registry) {
registry->RegisterListPref(prefs::kSnippets);
registry->RegisterListPref(prefs::kDiscardedSnippets);
registry->RegisterListPref(prefs::kSnippetHosts);
}
void NTPSnippetsService::Init(bool enabled) {
if (enabled) {
// |suggestions_service_| can be null in tests.
if (suggestions_service_) {
suggestions_service_subscription_ = suggestions_service_->AddCallback(
base::Bind(&NTPSnippetsService::OnSuggestionsChanged,
base::Unretained(this)));
}
// Get any existing snippets immediately from prefs.
LoadDiscardedSnippetsFromPrefs();
LoadSnippetsFromPrefs();
// If we don't have any snippets yet, start a fetch.
if (snippets_.empty())
FetchSnippets();
}
// The scheduler only exists on Android so far, it's null on other platforms.
if (!scheduler_)
return;
if (enabled) {
scheduler_->Schedule(GetFetchingIntervalWifiCharging(),
GetFetchingIntervalWifi(),
GetFetchingIntervalFallback());
} else {
scheduler_->Unschedule();
}
}
void NTPSnippetsService::Shutdown() {
FOR_EACH_OBSERVER(NTPSnippetsServiceObserver, observers_,
NTPSnippetsServiceShutdown());
}
void NTPSnippetsService::FetchSnippets() {
// |suggestions_service_| can be null in tests.
if (!suggestions_service_)
return;
FetchSnippetsImpl(GetSuggestionsHosts(
suggestions_service_->GetSuggestionsDataFromCache()));
}
bool NTPSnippetsService::DiscardSnippet(const GURL& url) {
auto it = std::find_if(snippets_.begin(), snippets_.end(),
[&url](const scoped_ptr<NTPSnippet>& snippet) {
return snippet->url() == url;
});
if (it == snippets_.end())
return false;
discarded_snippets_.push_back(std::move(*it));
snippets_.erase(it);
StoreDiscardedSnippetsToPrefs();
StoreSnippetsToPrefs();
return true;
}
void NTPSnippetsService::AddObserver(NTPSnippetsServiceObserver* observer) {
observers_.AddObserver(observer);
observer->NTPSnippetsServiceLoaded();
}
void NTPSnippetsService::RemoveObserver(NTPSnippetsServiceObserver* observer) {
observers_.RemoveObserver(observer);
}
void NTPSnippetsService::OnSuggestionsChanged(
const SuggestionsProfile& suggestions) {
std::set<std::string> hosts = GetSuggestionsHosts(suggestions);
if (hosts == GetSnippetHostsFromPrefs())
return;
// Remove existing snippets that aren't in the suggestions anymore.
snippets_.erase(
std::remove_if(snippets_.begin(), snippets_.end(),
[&hosts](const scoped_ptr<NTPSnippet>& snippet) {
return !hosts.count(snippet->url().host());
}),
snippets_.end());
StoreSnippetsToPrefs();
StoreSnippetHostsToPrefs(hosts);
FOR_EACH_OBSERVER(NTPSnippetsServiceObserver, observers_,
NTPSnippetsServiceLoaded());
FetchSnippetsImpl(hosts);
}
void NTPSnippetsService::OnSnippetsDownloaded(
const std::string& snippets_json) {
parse_json_callback_.Run(
snippets_json, base::Bind(&NTPSnippetsService::OnJsonParsed,
weak_ptr_factory_.GetWeakPtr(), snippets_json),
base::Bind(&NTPSnippetsService::OnJsonError,
weak_ptr_factory_.GetWeakPtr(), snippets_json));
}
void NTPSnippetsService::OnJsonParsed(const std::string& snippets_json,
scoped_ptr<base::Value> parsed) {
LOG_IF(WARNING, !LoadFromValue(*parsed)) << "Received invalid snippets: "
<< snippets_json;
}
void NTPSnippetsService::OnJsonError(const std::string& snippets_json,
const std::string& error) {
LOG(WARNING) << "Received invalid JSON (" << error << "): " << snippets_json;
}
void NTPSnippetsService::FetchSnippetsImpl(
const std::set<std::string>& hosts) {
if (base::CommandLine::ForCurrentProcess()->HasSwitch(
switches::kDontRestrict)) {
snippets_fetcher_->FetchSnippets(std::set<std::string>());
return;
}
if (!hosts.empty())
snippets_fetcher_->FetchSnippets(hosts);
}
bool NTPSnippetsService::LoadFromValue(const base::Value& value) {
const base::DictionaryValue* top_dict = nullptr;
if (!value.GetAsDictionary(&top_dict))
return false;
const base::ListValue* list = nullptr;
if (!top_dict->GetList("recos", &list))
return false;
return LoadFromListValue(*list);
}
bool NTPSnippetsService::LoadFromListValue(const base::ListValue& list) {
NTPSnippetStorage new_snippets;
if (!AddSnippetsFromListValue(list, &new_snippets))
return false;
for (scoped_ptr<NTPSnippet>& snippet : new_snippets) {
// If this snippet has previously been discarded, don't add it again.
if (HasDiscardedSnippet(snippet->url()))
continue;
// If the snippet has no publish/expiry dates, fill in defaults.
if (snippet->publish_date().is_null())
snippet->set_publish_date(base::Time::Now());
if (snippet->expiry_date().is_null()) {
snippet->set_expiry_date(
snippet->publish_date() +
base::TimeDelta::FromMinutes(kDefaultExpiryTimeMins));
}
// Check if we already have a snippet with the same URL. If so, replace it
// rather than adding a duplicate.
const GURL& url = snippet->url();
auto it = std::find_if(snippets_.begin(), snippets_.end(),
[&url](const scoped_ptr<NTPSnippet>& old_snippet) {
return old_snippet->url() == url;
});
if (it != snippets_.end())
*it = std::move(snippet);
else
snippets_.push_back(std::move(snippet));
}
// Immediately remove any already-expired snippets. This will also notify our
// observers and schedule the expiry timer.
RemoveExpiredSnippets();
return true;
}
void NTPSnippetsService::LoadSnippetsFromPrefs() {
bool success = LoadFromListValue(*pref_service_->GetList(prefs::kSnippets));
DCHECK(success) << "Failed to parse snippets from prefs";
}
void NTPSnippetsService::StoreSnippetsToPrefs() {
pref_service_->Set(prefs::kSnippets, *SnippetsToListValue(snippets_));
}
void NTPSnippetsService::LoadDiscardedSnippetsFromPrefs() {
discarded_snippets_.clear();
bool success = AddSnippetsFromListValue(
*pref_service_->GetList(prefs::kDiscardedSnippets),
&discarded_snippets_);
DCHECK(success) << "Failed to parse discarded snippets from prefs";
}
void NTPSnippetsService::StoreDiscardedSnippetsToPrefs() {
pref_service_->Set(prefs::kDiscardedSnippets,
*SnippetsToListValue(discarded_snippets_));
}
std::set<std::string> NTPSnippetsService::GetSnippetHostsFromPrefs() const {
std::set<std::string> hosts;
const base::ListValue* list = pref_service_->GetList(prefs::kSnippetHosts);
for (const base::Value* value : *list) {
std::string str;
bool success = value->GetAsString(&str);
DCHECK(success) << "Failed to parse snippet host from prefs";
hosts.insert(std::move(str));
}
return hosts;
}
void NTPSnippetsService::StoreSnippetHostsToPrefs(
const std::set<std::string>& hosts) {
base::ListValue list;
for (const std::string& host : hosts)
list.AppendString(host);
pref_service_->Set(prefs::kSnippetHosts, list);
}
bool NTPSnippetsService::HasDiscardedSnippet(const GURL& url) const {
auto it = std::find_if(discarded_snippets_.begin(), discarded_snippets_.end(),
[&url](const scoped_ptr<NTPSnippet>& snippet) {
return snippet->url() == url;
});
return it != discarded_snippets_.end();
}
void NTPSnippetsService::RemoveExpiredSnippets() {
base::Time expiry = base::Time::Now();
snippets_.erase(
std::remove_if(snippets_.begin(), snippets_.end(),
[&expiry](const scoped_ptr<NTPSnippet>& snippet) {
return snippet->expiry_date() <= expiry;
}),
snippets_.end());
StoreSnippetsToPrefs();
discarded_snippets_.erase(
std::remove_if(discarded_snippets_.begin(), discarded_snippets_.end(),
[&expiry](const scoped_ptr<NTPSnippet>& snippet) {
return snippet->expiry_date() <= expiry;
}),
discarded_snippets_.end());
StoreDiscardedSnippetsToPrefs();
FOR_EACH_OBSERVER(NTPSnippetsServiceObserver, observers_,
NTPSnippetsServiceLoaded());
// If there are any snippets left, schedule a timer for the next expiry.
if (snippets_.empty() && discarded_snippets_.empty())
return;
base::Time next_expiry = base::Time::Max();
for (const auto& snippet : snippets_) {
if (snippet->expiry_date() < next_expiry)
next_expiry = snippet->expiry_date();
}
for (const auto& snippet : discarded_snippets_) {
if (snippet->expiry_date() < next_expiry)
next_expiry = snippet->expiry_date();
}
DCHECK_GT(next_expiry, expiry);
expiry_timer_.Start(FROM_HERE, next_expiry - expiry,
base::Bind(&NTPSnippetsService::RemoveExpiredSnippets,
base::Unretained(this)));
}
} // namespace ntp_snippets
| was4444/chromium.src | components/ntp_snippets/ntp_snippets_service.cc | C++ | bsd-3-clause | 14,318 |
<?php
// This file will be included by data.php
// The path of the file should be set as METADATAPATH in config.php.
// What are session_vars ?
// When generating a URL to a page using the URL class (in url.php), any
// GET variables for the page whose keys are listed in its session_vars below
// will automatically be put in the URL.
// For example, in this metadata we might have:
// 'search' => array (
// 'url' => 'search/',
// 'sidebar' => 'search',
// 'session_vars' => array ('s')
// ),
// If we are at the URL www.domain.org/search/?s=blair&page=2
// and we used the URL class to generate a link to the search page like this:
// $URL = new URL('search');
// $newurl = $URL->generate();
// then $newurl would be: /search/?s=blair
//
// sidebar:
// If you have a 'sidebar' element for a page then that page will have its content
// set to a restricted width and a sidebar will be inserted. The contents of this
// will be include()d from a file in template/sidebars/ of the name of the 'sidebar'
// value ('search.php' in the example above).
/* Items a page might have:
menu An array of 'text' and 'title' which are used if the page
appears in the site menu.
title Used for the <title> and the page's heading on the page.
heading If present *this* is used for the page's heading on the page, in
in place of the title.
url The URL from the site webroot for this page.
parent What page is this page's parent (see below).
session_vars If present, whenever a URL is generated to this page using the
URL class, any POST/GET variables with matching names are
automatically appended to the url.
track (deprecated) Do we want to include the Extreme Tracker javascript on this page?
rss Does the content of this page (or some of it) have an RSS version?
If so, 'rss' should be set to '/a/path/to/the/feed.rdf'.
PARENTS
The site's menu has a top menu and a bottom, sub-menu. What is displayed in the
sub-menu depends on which page is selected in the top menu. This is worked out
from the bottom up, by looking at pages' parents. Here's an example top and bottom
menu, with the capitalised items hilited:
Home HANSARD Glossary Help
DEBATES Written Answers
If we were viewing a particular debate, we would be on the 'debate' page. The parent
of this is 'debatesfront', which is the DEBATES link in the bottom menu - hence its
hilite. The parent of 'debatesfront' is 'hansard', hence its hilite in the top menu.
This may, of course, make no sense at all...
If a page has no parent it is either in the top menu or no menu items should be hilited.
The actual contents of each menu is determined in $PAGE->menu().
*/
$this->page = array (
// Things used on EVERY page, unless overridden for a page:
'default' => array (
'parent' => '',
'session_vars' => array('super_debug'),
'sitetitle' => 'TheyWorkForYou.com',
),
// Every page on the site should have an entry below...
// KEEP THE PAGES IN ALPHABETICAL ORDER! TA.
'about' => array (
'title' => 'About us',
'url' => 'about/'
),
'parliaments' => array (
'title' => 'Parliaments and assemblies',
'url' => 'parliaments/'
),
'addcomment' => array (
'url' => 'addcomment/',
),
'admin_alerts' => array (
'title' => 'Email alerts',
'parent' => 'admin',
'url' => 'admin/alerts.php',
),
'alert_stats' => array (
'title' => 'Email alerts',
'parent' => 'admin',
'url' => 'admin/alert_stats.php',
),
'admin_badusers' => array (
'title' => 'Bad users',
'parent' => 'admin',
'url' => 'admin/badusers.php'
),
'admin_home' => array (
'title' => 'Home',
'parent' => 'admin',
'url' => 'admin/'
),
'admin_comments' => array (
'title' => 'Recent comments',
'parent' => 'admin',
'url' => 'admin/comments.php'
),
'admin_commentreport' => array (
'title' => 'Processing a comment report',
'parent' => 'admin',
'url' => 'admin/report.php',
'session_vars' => array ('rid', 'cid')
),
'admin_commentreports' => array (
'title' => 'Outstanding comment reports',
'parent' => 'admin',
'url' => 'admin/reports.php'
),
'admin_failedsearches' => array (
'title' => 'Failed searches',
'parent' => 'admin',
'url' => 'admin/failedsearches.php'
),
'admin_glossary' => array (
'title' => 'Manage glossary entries',
'parent' => 'admin',
'url' => 'admin/glossary.php'
),
'admin_glossary_pending' => array (
'title' => 'Review pending glossary entries',
'parent' => 'admin',
'url' => 'admin/glossary_pending.php'
),
'admin_searchlogs' => array (
'title' => 'Recent searches',
'parent' => 'admin',
'url' => 'admin/searchlogs.php'
),
'admin_popularsearches' => array (
'title' => 'Popular searches in last 30 days (first 1000)',
'parent' => 'admin',
'url' => 'admin/popularsearches.php'
),
'admin_statistics' => array (
'title' => 'General statistics',
'parent' => 'admin',
'url' => 'admin/statistics.php'
),
'admin_trackbacks' => array (
'title' => 'Recent trackbacks',
'parent' => 'admin',
'url' => 'admin/trackbacks.php'
),
'admin_photos' => array (
'title' => 'Photo upload',
'parent' => 'admin',
'url' => 'admin/photos.php',
),
'admin_mpurls' => array (
'title' => 'MP Websites',
'parent' => 'admin',
'url' => 'admin/websites.php',
),
// Added by Richard Allan for email alert functions
'alert' => array (
'menu' => array (
'text' => 'Email Alerts',
'title' => "Set up alerts for updates on an MP or Peer by email",
'sidebar' => 'alert'
),
'title' => 'TheyWorkForYou Email Alerts',
'url' => 'alert/',
),
'alertconfirm' => array (
'url' => 'alert/confirm/'
),
'alertconfirmfailed' => array (
'title' => 'Oops!',
'url' => 'alert/confirm/'
),
'alertconfirmsucceeded' => array (
'title' => 'Alert Confirmed!',
'url' => 'alert/confirm/'
),
'alertdelete' => array (
'url' => 'alert/delete/'
),
'alertdeletefailed' => array (
'title' => 'Oops!',
'url' => 'alert/delete/'
),
'alertdeletesucceeded' => array (
'title' => 'Alert Deleted!',
'url' => 'alert/delete/'
),
'alertundeletesucceeded' => array (
'title' => 'Alert Undeleted!',
'url' => 'alert/undelete/'
),
'alertundeletefailed' => array (
'title' => 'Oops!',
'url' => 'alert/undelete/'
),
'alertwelcome' => array (
'title' => 'Email Alerts',
'url' => 'alert/',
),
// End of ALERTS additions
'api_front' => array (
'menu' => array (
'text' => 'API',
'title' => 'Access our data'
),
'title' => 'TheyWorkForYou API',
'url' => 'api/'
),
'api_doc_front' => array (
'menu' => array (
'text' => 'API',
'title' => 'Access our data'
),
'parent' => 'api_front',
'url' => 'api/'
),
'api_key' => array (
'title' => 'API Keys',
'parent' => 'api_front',
'url' => 'api/key'
),
'cards' => array (
'title' => 'MP Stats Cards',
'url' => 'cards/'
),
'campaign_foi' => array (
'title' => 'Freedom of Information (Parliament) Order 2009',
'url' => 'foiorder2009/'
),
'campaign' => array (
'title' => '', #Free Our Bills!',
'url' => 'freeourbills/'
),
'campaign_edm' => array (
'title' => 'Early Day Motion',
'parent' => 'campaign',
'url' => 'freeourbills/'
),
'commentreport' => array (
'title' => 'Reporting a comment',
'url' => 'report/',
'session_vars' => array ('id')
),
'comments_recent' => array (
'menu' => array (
'text' => 'Recent comments',
'title' => "Recently posted comments"
),
'parent' => 'home',
'title' => "Recent comments",
'url' => 'comments/recent/'
),
'contact' => array (
'title' => 'Contact',
'url' => 'contact/'
),
'news' => array(
'title' => 'News',
'url' => 'http://www.mysociety.org/category/projects/theyworkforyou/'
),
'debate' => array (
'parent' => 'debatesfront',
'url' => 'debate/',
'session_vars' => array ('id'),
),
'debates' => array (
'parent' => 'debatesfront',
'url' => 'debates/',
'session_vars' => array ('id'),
),
'debatesday' => array (
'parent' => 'debatesfront',
'session_vars' => array ('d'),
'url' => 'debates/',
),
'alldebatesfront' => array (
'menu' => array (
'text' => 'Debates',
'title' => "Debates in the House of Commons, Westminster Hall, and the House of Lords"
),
'parent' => 'hansard',
'title' => 'UK Parliament Debates',
'rss' => 'debates/debates.rss',
'url' => 'debates/'
),
'debatesfront' => array (
'menu' => array (
'text' => 'Commons debates',
'title' => "Debates in the House of Commons"
),
'parent' => 'alldebatesfront',
'title' => 'House of Commons debates',
'rss' => 'debates/debates.rss',
'url' => 'debates/'
),
'debatesyear' => array (
'parent' => 'debatesfront',
'title' => 'Debates for ',
'url' => 'debates/'
),
'epvote' => array (
'url' => 'vote/'
),
'gadget' => array(
'url' => 'gadget/',
'title' => 'TheyWorkForYou Google gadget',
),
'glossary' => array (
'heading' => 'Glossary',
'parent' => 'help_us_out',
'url' => 'glossary/'
),
'glossary_addterm' => array (
'menu' => array (
'text' => 'Add a term',
'title' => "Add a definition for a term to the glossary"
),
'parent' => 'help_us_out',
'title' => 'Add a glossary item',
'url' => 'addterm/',
'session_vars' => array ('g')
),
'glossary_addlink' => array (
'menu' => array (
'text' => 'Add a link',
'title' => "Add an external link"
),
'parent' => 'help_us_out',
'title' => 'Add a link',
'url' => 'addlink/',
'session_vars' => array ('g')
),
'glossary_item' => array (
'heading' => 'Glossary heading',
'parent' => 'help_us_out',
'url' => 'glossary/',
'session_vars' => array ('g')
),
'hansard' => array (
'menu' => array (
'text' => 'UK Parliament',
'title' => "Houses of Parliament debates, Written Answers, Statements, Westminster Hall debates, and Bill Committees"
),
'title' => '',
'url' => ''
),
'hansard_date' => array (
'parent' => 'hansard',
'title' => 'House of Commons, House of Lords, Northern Ireland Assembly, and the Scottish Parliament',
'url' => 'hansard/'
),
'help' => array (
'title' => 'Help',
'url' => 'help/'
),
'help_us_out' => array (
'menu' => array (
'text' => 'Glossary',
'title' => "Parliament's jargon explained"
),
'title' => 'Glossary',
'heading' => 'Add a glossary item',
'url' => 'addterm/',
'sidebar' => 'glossary_add'
),
'home' => array (
'title' => "UK Parliament",
'rss' => 'news/index.rdf',
'url' => ''
),
'houserules' => array (
'title' => 'House rules',
'url' => 'houserules/'
),
'linktous' => array (
'title' => 'Link to us',
'heading' => 'How to link to us',
'url' => 'help/linktous/'
),
'api' => array (
'title' => 'API',
'heading' => 'API',
'url' => 'api/'
),
'data' => array (
'title' => 'Raw Data',
'heading' => 'Raw data (XML)',
'url' => 'http://ukparse.kforge.net/parlparse'
),
'devmailinglist' => array (
'title' => 'Developer mailing list',
'heading' => 'Developer mailing list',
'url' => 'https://secure.mysociety.org/admin/lists/mailman/listinfo/developers-public'
),
'code' => array (
'title' => 'Source code',
'heading' => 'Source code',
'url' => 'https://secure.mysociety.org/cvstrac/dir?d=mysociety/twfy'
),
'irc' => array (
'title' => 'IRC chat channel',
'heading' => 'IRC chat channel',
'url' => 'http://www.irc.mysociety.org/'
),
'newzealand' => array (
'title' => 'New Zealand',
'heading' => 'They Work For You - New Zealand',
'url' => 'http://www.theyworkforyou.co.nz/'
),
'australia' => array (
'title' => 'Australia',
'heading' => 'Open Australia',
'url' => 'http://www.openaustralia.org/'
),
'ireland' => array (
'title' => 'Ireland',
'heading' => 'TheyWorkForYou for the Houses of the Oireachtas',
'url' => 'http://www.kildarestreet.com/'
),
'lordsdebate' => array (
'parent' => 'lordsdebatesfront',
'url' => 'lords/',
'session_vars' => array ('gid'),
),
'lordsdebates' => array (
'parent' => 'lordsdebatesfront',
'url' => 'lords/',
'session_vars' => array ('id'),
),
'lordsdebatesday' => array (
'parent' => 'lordsdebatesfront',
'session_vars' => array ('d'),
'url' => 'lords/',
),
'lordsdebatesfront' => array (
'menu' => array (
'text' => 'Lords debates',
'title' => "House of Lords debates"
),
'parent' => 'alldebatesfront',
'title' => 'House of Lords debates',
'rss' => 'lords/lords.rss',
'url' => 'lords/'
),
'lordsdebatesyear' => array (
'parent' => 'lordsdebatesfront',
'title' => 'Debates for ',
'url' => 'lords/'
),
'peer' => array (
'parent' => 'peers',
'title' => 'Peer',
'url' => 'peer/'
),
'peers' => array (
'menu' => array (
'text' => 'Lords',
'title' => "List of all Lords"
),
'parent' => 'hansard',
'title' => 'All Lords',
'url' => 'peers/'
),
'overview' => array (
'menu' => array (
'text' => 'Overview',
'title' => "Overview of the UK Parliament"
),
'parent' => 'hansard',
'title' => "Are your MPs and Peers working for you in the UK's Parliament?",
'rss' => 'news/index.rdf',
'url' => ''
),
'mla' => array (
'parent' => 'mlas',
'title' => 'MLA',
'url' => 'mla/'
),
'mlas' => array (
'parent' => 'ni_home',
'menu' => array (
'text' => 'MLAs',
'title' => "List of all Members of the Northern Ireland Assembly (MLAs)"
),
'title' => 'All MLAs',
'url' => 'mlas/'
),
'msps' => array (
'parent' => 'sp_home',
'menu' => array (
'text' => 'MSPs',
'title' => "List of Members of the Scottish Parliament (MSPs)"
),
'title' => 'Current MSPs',
'url' => 'msps/'
),
'msp' => array (
'parent' => 'msps',
'title' => 'MSP',
'url' => 'msp/'
),
/* Not 'Your MP', whose name is 'yourmp'... */
'mp' => array (
'parent' => 'mps',
'title' => 'MP',
'url' => 'mp/'
),
'emailfriend' => array (
'title' => 'Send this page to a friend',
'url' => 'email/'
),
'c4_mp' => array (
'title' => 'MP',
'url' => 'mp/c4/'
),
'c4x_mp' => array (
'title' => 'MP',
'url' => 'mp/c4x/'
),
// The directory MPs' RSS feeds are stored in.
'mp_rss' => array (
'url' => 'rss/mp/'
),
'mps' => array (
'menu' => array (
'text' => 'MPs',
'title' => "List of all Members of Parliament (MPs)"
),
'parent' => 'hansard',
'title' => '',
'url' => 'mps/'
),
'c4_mps' => array (
'title' => 'All MPs',
'url' => 'mps/c4/'
),
'c4x_mps' => array (
'title' => 'All MPs',
'url' => 'mps/c4x/'
),
/* Northern Ireland Assembly */
'ni_home' => array(
'menu' => array (
'text' => 'Northern Ireland Assembly',
'title' => 'Full authority over <em>transferred matters</em>, which include agriculture, education, employment, the environment and health'
),
'title' => 'Northern Ireland Assembly',
'url' => 'ni/'
),
'nioverview' => array (
'parent' => 'ni_home',
'menu' => array (
'text' => 'Debates',
'title' => "Overview of the Northern Ireland Assembly debates"
),
'title' => 'Overview of the Northern Ireland Assembly',
'url' => 'ni/'
),
'nidebate' => array (
'parent' => 'nidebatesfront',
'url' => 'ni/',
'session_vars' => array ('gid'),
),
'nidebates' => array (
'parent' => 'nidebatesfront',
'url' => 'ni/',
'session_vars' => array ('id'),
),
'nidebatesday' => array (
'parent' => 'nidebatesfront',
'session_vars' => array ('d'),
'url' => 'ni/',
),
'nidebatesfront' => array (
'menu' => array (
'text' => 'Debates',
'title' => "Northern Ireland Assembly debates"
),
'parent' => 'ni_home',
'title' => 'Northern Ireland Assembly debates',
'rss' => 'ni/ni.rss',
'url' => 'ni/'
),
'nidebatesyear' => array (
'parent' => 'nidebatesfront',
'title' => 'Debates for ',
'url' => 'ni/'
),
'otheruseredit' => array (
'pg' => 'editother',
'title' => "Editing a user's data",
'url' => 'user/'
),
'privacy' => array (
'title' => 'Privacy Policy',
'url' => 'privacy/'
),
/* Public bill committees */
'pbc_front' => array (
'menu' => array (
'text' => 'Bill Committees',
'title' => "Public Bill Committees (formerly Standing Committees) debates"
),
'parent' => 'hansard',
'title' => 'Public Bill Committees',
'rss' => 'pbc/pbc.rss',
'url' => 'pbc/'
),
'pbc_session' => array(
'title' => 'Session',
'url' => 'pbc/',
'parent' => 'pbc_front',
),
'pbc_bill' => array(
'title' => '',
'url' => 'pbc/',
'parent' => 'pbc_front',
'session_vars' => array ('bill'),
),
'pbc_clause' => array(
'parent' => 'pbc_front',
'url' => 'pbc/',
'session_vars' => array ('id'),
),
'pbc_speech' => array(
'parent' => 'pbc_front',
'url' => 'pbc/',
'session_vars' => array ('id'),
),
'people' => array(
'menu' => array(
'text' => 'People',
'title' => '',
),
'title' => 'Representatives',
'url' => '',
),
'raw' => array (
'title' => 'Raw data',
'url' => 'raw/'
),
'regmem' => array (
'title' => 'Changes to the Register of Members\' Interests',
'url' => 'regmem/'
),
'regmem_date' => array (
'url' => 'regmem/',
'parent' => 'regmem'
),
'regmem_mp' => array (
'url' => 'regmem/',
'parent' => 'regmem'
),
'regmem_diff' => array (
'url' => 'regmem/',
'parent' => 'regmem'
),
'royal' => array (
'title' => 'Royal',
'url' => 'royal/'
),
'search' => array (
'sidebar' => 'search',
'url' => 'search/',
'robots' => 'noindex, nofollow',
'heading' => '',
'session_vars' => array ('s', 'pid', 'o', 'pop')
),
'search_help' => array (
'sidebar' => 'search',
'title' => 'Help with searching',
'url' => 'search/'
),
'sitenews' => array (
'menu' => array (
'text' => 'TheyWorkForYou news',
'title' => "News about changes to this website"
),
'parent' => 'home',
'rss' => 'news/index.rdf',
'sidebar' => 'sitenews',
'title' => 'TheyWorkForYou news',
'url' => 'news/'
),
'sitenews_archive' => array (
'parent' => 'sitenews',
'rss' => 'news/index.rdf',
'sidebar' => 'sitenews',
'title' => 'Archive',
'url' => 'news/archives/'
),
'sitenews_atom' => array (
'url' => 'news/atom.xml'
),
'sitenews_date' => array (
'parent' => 'sitenews',
'rss' => 'news/index.rdf',
'sidebar' => 'sitenews'
),
'sitenews_individual' => array (
'parent' => 'sitenews',
'rss' => 'news/index.rdf',
'sidebar' => 'sitenews',
),
'sitenews_rss1' => array (
'url' => 'news/index.rdf'
),
'sitenews_rss2' => array (
'url' => 'news/index.xml'
),
'skin' => array (
'title' => 'Skin this site',
'url' => 'skin/'
),
/* Scottish Parliament */
'sp_home' => array(
'menu' => array (
'text' => 'Scottish Parliament',
'title' => 'Scottish education, health, agriculture, justice, prisons and other devolved areas. Some tax-varying powers'
),
'title' => 'Scottish Parliament',
'url' => 'scotland/'
),
'spoverview' => array (
'parent' => 'sp_home',
'menu' => array (
'text' => 'Overview',
'title' => "Overview of the Scottish Parliament"
),
'title' => 'Overview of the Scottish Parliament',
'url' => 'scotland/'
),
'spdebate' => array (
'parent' => 'spdebatesfront',
'url' => 'sp/',
'session_vars' => array ('id'),
),
'spdebates' => array (
'parent' => 'spdebatesfront',
'url' => 'sp/',
'session_vars' => array ('id'),
),
'spdebatesday' => array (
'parent' => 'spdebatesfront',
'session_vars' => array ('d'),
'url' => 'sp/',
),
'spdebatesfront' => array (
'menu' => array (
'text' => 'Debates',
'title' => ''
),
'parent' => 'sp_home',
'title' => 'Scottish Parliament debates',
'rss' => 'sp/sp.rss',
'url' => 'sp/'
),
'spdebatesyear' => array (
'parent' => 'spdebatesfront',
'title' => 'Debates for ',
'url' => 'sp/'
),
'spwrans' => array (
'parent' => 'spwransfront',
'url' => 'spwrans/',
#'session_vars' => array ('id'),
),
'spwransday' => array (
'parent' => 'spwransfront',
'url' => 'spwrans/'
),
'spwransfront' => array (
'menu' => array (
'text' => 'Written Answers',
'title' => ''
),
'parent' => 'sp_home',
'title' => 'Scottish Parliament Written answers',
'url' => 'spwrans/'
),
'spwransmp' => array(
'parent' => 'spwransfront',
'title' => 'For questions asked by ',
'url' => 'spwrans/'
),
'spwransyear' => array (
'parent' => 'spwransfront',
'title' => 'Scottish Parliament Written answers for ',
'url' => 'spwrans/'
),
// The URL 3rd parties need to ping something here.
'trackback' => array (
'url' => 'trackback/'
),
'useralerts' => array(
'menu' => array(
'text' => 'Email Alerts',
'title' => 'Check your email alerts'
),
'title' => 'Your Email Alerts',
'url' => 'user/alerts/',
'parent' => 'userviewself'
),
'userchangepc' => array (
'title' => 'Change your postcode',
'url' => 'user/changepc/'
),
'userconfirm' => array (
'url' => 'user/confirm/'
),
'userconfirmed' => array (
'sidebar' => 'userconfirmed',
'title' => 'Welcome to TheyWorkForYou!',
'url' => 'user/confirm/'
),
'userconfirmfailed' => array (
'title' => 'Oops!',
'url' => 'user/confirm/'
),
'useredit' => array (
'pg' => 'edit',
'title' => 'Edit your details',
'url' => 'user/'
),'userjoin' => array (
'menu' => array (
'text' => 'Join',
'title' => "Joining is free and allows you to annotate speeches"
),
'pg' => 'join',
'sidebar' => 'userjoin',
'title' => 'Join TheyWorkForYou',
'url' => 'user/'
),
'getinvolved' => array (
'menu' => array (
'text' => 'Get involved',
'title' => "Contribute to TheyWorkForYou"
),
'pg' => 'getinvolved',
'sidebar' => 'userjoin',
'title' => 'Contribute to TheyWorkForYou',
'url' => 'getinvolved/'
),
'userlogin' => array (
'menu' => array (
'text' => 'Sign in',
'title' => "If you've already joined , sign in to add annotations"
),
'sidebar' => 'userlogin',
'title' => 'Sign in',
'url' => 'user/login/'
),
'userlogout' => array (
'menu' => array (
'text' => 'Sign out',
'title' => "Sign out"
),
'url' => 'user/logout/'
),
'userpassword' => array (
'title' => 'Change password',
'url' => 'user/password/'
),
'userprompt' => array (
'title' => 'Please sign in',
'url' => 'user/prompt/'
),
'userview' => array (
'session_vars' => array('u'),
'url' => 'user/'
),
'userviewself' => array (
'menu' => array (
'text' => 'Your details',
'title' => "View and edit your details"
),
'url' => 'user/'
),
'userwelcome' => array (
'title' => 'Welcome!',
'url' => 'user/'
),
'video_front' => array(
'title' => 'Video speech matching'
),
'video_main' => array(
'title' => 'Video speech matching'
),
/* Welsh Assembly */
'wales_home' => array(
'menu' => array(
'text' => 'Welsh Assembly',
'title' => 'Welsh economic development, transport, finance, local government, health, housing, the Welsh Language and other devolved areas',
),
'title' => 'Welsh Assembly',
'url' => 'wales/',
),
'wales_overview' => array(
'title' => 'Welsh Assembly',
'url' => 'wales/',
'parent' => 'wales_home',
),
/* Westminster Hall */
'whall' => array (
'parent' => 'whallfront',
'url' => 'whall/',
'session_vars' => array ('id'),
),
'whalls' => array (
'parent' => 'whallfront',
'url' => 'whall/',
'session_vars' => array ('id'),
),
'whallday' => array (
'parent' => 'whallfront',
'session_vars' => array ('d'),
'url' => 'whall/',
),
'whallfront' => array (
'menu' => array (
'text' => 'Westminster Hall',
'title' => "Westminster Hall debates"
),
'parent' => 'alldebatesfront',
'title' => 'Westminster Hall debates',
'rss' => 'whall/whall.rss',
'url' => 'whall/'
),
'whallyear' => array (
'parent' => 'whallfront',
'title' => 'Westminster Hall debates for ',
'url' => 'whall/'
),
'wms' => array (
'parent' => 'wranswmsfront',
'url' => 'wms/',
'session_vars' => array('id')
),
'wmsday' => array (
'parent' => 'wmsfront',
'session_vars' => array('d'),
'url' => 'wms/'
),
'wmsfront' => array (
'menu' => array (
'text' => 'Written Ministerial Statements',
'title' => ''
),
'parent' => 'wranswmsfront',
'title' => 'Written Ministerial Statements',
'rss' => 'wms/wms.rss',
'url' => 'wms/'
),
'wmsyear' => array (
'parent' => 'wmsfront',
'title' => 'Written Ministerial Statements for ',
'url' => 'wms/'
),
'wrans' => array (
'parent' => 'wranswmsfront',
'url' => 'wrans/',
'session_vars' => array ('id')
),
'wransday' => array (
'parent' => 'wransfront',
'url' => 'wrans/'
),
'wransfront' => array (
'menu' => array (
'text' => 'Written Answers',
'title' => "Written Answers"
),
'parent' => 'wranswmsfront',
'title' => 'Written answers',
'url' => 'wrans/'
),
'wransmp' => array(
'parent' => 'wransfront',
'title' => 'For questions asked by ',
'url' => 'wrans/'
),
'wransyear' => array (
'parent' => 'wransfront',
'title' => 'Written answers for ',
'url' => 'wrans/'
),
'wranswmsfront' => array (
'menu' => array (
'text' => 'Written Answers and Statements',
'title' => '',
),
'parent' => 'hansard',
'title' => 'Written answers and statements',
'url' => 'written-answers-and-statements/'
),
'yourreps' => array(
'menu' => array(
'text' => 'Your representative',
'title' => '',
),
'title' => 'Your representative',
'url' => 'your/',
),
'yourmp' => array (
'menu' => array (
'text' => 'Your MP',
'title' => "Find out about your Member of Parliament"
),
'sidebar' => 'yourmp',
'title' => 'Your MP',
'url' => 'mp/',
'parent' => 'mps',
),
'yourmp_recent' => array (
'menu' => array (
'text' => 'Recent appearances',
'title' => "Recent speeches and written answers by this MP"
),
'parent' => 'yourmp',
'title' => "Your MP's recent appearances in parliament",
'url' => 'mp/?recent=1'
),
'yourmsp' => array (
'menu' => array (
'text' => 'Your MSPs',
'title' => "Find out about your Members of the Scottish Parliament"
),
#'parent' => 'yourreps',
'sidebar' => 'yourmsp',
'title' => 'Your MSPs',
'url' => 'msp/'
),
'yourmla' => array (
'menu' => array (
'text' => 'Your MLAs',
'title' => "Find out about your Members of the Legislative Assembly"
),
#'parent' => 'yourreps',
'sidebar' => 'yourmla',
'title' => 'Your MLAs',
'url' => 'mla/'
),
);
// We just use the sections for creating page headings/titles.
// The 'title' is always used for the <title> tag of the page.
// The text displayed on the page itself will also be this,
// UNLESS the section has a 'heading', in which case that's used instead.
$this->section = array (
'about' => array (
'title' => 'About Us'
),
'admin' => array (
'title' => 'Admin'
),
'debates' => array (
'title' => 'Debates',
'heading' => 'House of Commons Debates'
),
'help_us_out' => array (
'title' => 'Help Us Out'
),
'hansard' => array (
'title' => 'Hansard'
),
'home' => array (
'title' => 'Home'
),
'mp' => array (
'title' => 'Your MP'
),
'search' => array (
'title' => 'Search'
),
'sitenews' => array (
'title' => 'TheyWorkForYou news'
),
'wrans' => array (
'title' => 'Written Answers'
)
);
?>
| palfrey/twfy | www/includes/easyparliament/metadata.php | PHP | bsd-3-clause | 28,559 |
/*
*Resize the graph container
*/
function resizegraph(){
var windowHeight = $( window ).innerHeight();
$("#stacked").css('min-height',(windowHeight * 0.35) );
}
//From facebook
window.fbAsyncInit = function(){
FB.init({
appId: facebook_api_key, status: true, cookie: true, xfbml: true });
};
(function(d, debug){var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
if(d.getElementById(id)) {return;}
js = d.createElement('script'); js.id = id;
js.async = true;js.src = "//connect.facebook.net/fr_CA/all" + (debug ? "/debug" : "") + ".js";
ref.parentNode.insertBefore(js, ref);}(document, /*debug*/ false));
function postToFeed(title, desc, url, image){
desc = desc + url;
var obj = {method: 'feed',link: url, picture: image,name: title,description: desc};
function callback(response){}
FB.ui(obj, callback);
}
/*
* Sharing functions
* @param {string} url - An url
* @param {string} desc - A small description
* @param {int} winWidth - Width of the popup
* @param {int} winHeight - height of the popup
*/
function twittershare(url, descr, winWidth, winHeight) {
var winTop = (screen.height / 2) - (winHeight / 2);
var winLeft = (screen.width / 2) - (winWidth / 2);
descr = encodeURIComponent(descr);
url = encodeURIComponent(url);
window.open('https://twitter.com/share?url=' + url + '&text='+ descr , 'Partage', 'top=' + winTop + ',left=' + winLeft + ',toolbar=0,status=0,width='+winWidth+',height='+winHeight);
}
function linkedinshare(url, title, descr, winWidth, winHeight) {
var winTop = (screen.height / 2) - (winHeight / 2);
var winLeft = (screen.width / 2) - (winWidth / 2);
title = encodeURIComponent(title);
descr = encodeURIComponent(descr + url);
window.open('http://www.linkedin.com/shareArticle?mini=true&url=' + url + '&title='+ title + '&summary='+ descr , 'Partage', 'top=' + winTop + ',left=' + winLeft + ',toolbar=0,status=0,width='+winWidth+',height='+winHeight);
}
/*
* Sharing functions
* @param {string} url - An url
* Set sharing functions to contracts by ID
*/
function setSocialMedia(contractId){
var base_url = window.location.protocol + '//' + window.location.hostname + location.pathname;
var url = base_url + '?q=' + contractId + '&type='+$('[name=type]:checked').val();
var image_url = base_url + 'img/rosette.jpg';
var info = $("#contract_"+contractId);
var titlet = "Vue sur les contrats. Consultez les contrats et subventions octroyés par la Ville de Montréal.";
var titlefb = "Vue sur les contrats de la ville de Montréal";
var descriptionfb = "Vue sur les contrats est un outil de visualisation qui permet de consulter les contrats et les subventions octroyés par la Ville de façon simple et conviviale. ";
var titleli = "Vue sur les contrats de la Ville de Montréal";
var descriptionli = "Vue sur les contrats est un outil de visualisation qui permet de consulter les contrats et les subventions octroyés par la Ville de façon simple et conviviale. ";
var formattedBody = encodeURIComponent("Vue sur les contrats est un outil de visualisation qui permet de consulter les contrats et les subventions octroyés par la Ville de façon simple et conviviale. \n \n "+ url);
var box = $("#modalsocialmedia");
box.find(".sharetwitter").attr("href",'javascript:twittershare("'+url+'", "'+titlet+'", 520, 350);');
box.find(".sharefacebook").attr("href",'javascript:postToFeed("'+titlefb+'", "'+descriptionfb+'","'+url+'", "'+image_url+'");');
box.find(".sharelinkedin").attr("href",'javascript:linkedinshare("'+url+'", "'+titleli+'", "'+descriptionli+'", 520, 350);');
box.find(".shareemail").attr('href','mailto:?body='+formattedBody+'&subject=Vue sur les contrats de la Ville de Montréal');
box.find(".sharelink").val(url);
box.modal('show');
}
/*
* @param {string} result - object from the API
* @return {{ boolean }}
* Define if data was received
*/
function results_accepted(results) {
if (results && results.meta) {
if (results.meta.count) {
$(".graph-container").css('visibility','visible');
$(".mainContent").show();
$(".filters").show();
$(".noResults").hide();
return true;
}else{
$('html, body').animate({ scrollTop: 0 }, 300);
$(".mainContent").hide();
$(".graph-container").css('visibility','hidden');
$(".filters").hide();
$(".noResults").show();
return false;
}
}else{
$('html, body').animate({ scrollTop: 0 }, 300);
$(".mainContent").hide();
$(".graph-container").css('visibility','hidden');
$(".filters").hide();
$(".noResults").show();
return false;
}
}
/*
* @param {string} text
* @param {int} length
* @return {{ text }}
* add an ellipsis if needed
*/
function TextAbstract(text, length) {
if (text == null) {
return "";
}
if (text.length <= length) {
return text;
}
text = text.substring(0, length);
return text + "...";
}
/*
*bootstrap-selectpicker init
*/
$.fn.selectpicker.defaults = {
mobile : false,
selectAllText: "Tout sélectionner",
deselectAllText: "Désélectionner",
noneSelectedText: "Aucune sélection",
countSelectedText: function (numSelected, numTotal) {
if (numTotal == numSelected) {
return "Tous";
}else{
return (numSelected == 1) ? "{0} sélection" : "{0} sélections";
}
},
}
/*
* Clear the form
*/
function clearForm()
{
$(':input').not(':button, :submit, :reset, :checkbox, :radio, [name="limit"]').val('');
$(':checkbox, :radio').prop('checked', false);
$("#offset").val('0');
}
function renameLabels(){
if ($( ".switchgraph span" ).hasClass('value')) {
$( ".switchgraph span" ).html('Voir nombre de '+defTypeName()+'s par mois');
$(".graphTitle").html('Montant total des '+defTypeName()+'s par mois');
}else if($( ".switchgraph span" ).hasClass('count')) {
$( ".switchgraph span" ).html('Voir montant des '+defTypeName()+'s par mois');
$(".graphTitle").html('Nombre total de '+defTypeName()+'s par mois');
}
}
/*
* Add a buyer ID to the request
*/
function bybuyer(buyerid, reset) {
init = true;
$('.searchboxLabel').html("Octroyé par");
$("input#offset").val('0');
$("input#supplier").val('');
$("input#buyer").val(buyerid);
$('.searchboxhidden').tagsinput('removeAll');
$('.searchboxhidden').tagsinput('add', buyerid);
$(".bootstrap-tagsinput").find('.tag').addClass('buyer');
}
/*
* Add a supplier ID to the request
*/
function bysupplier(supplierid, reset) {
init = true;
$('.searchboxLabel').html("Fournisseur");
$("input#offset").val('0');
$("input#buyer").val('');
$("input#supplier").val(supplierid);
$('.searchboxhidden').tagsinput('removeAll');
$('.searchboxhidden').tagsinput('add', supplierid);
$(".bootstrap-tagsinput").find('.tag').addClass('supplier');
}
var previousPoint = null, previousLabel = null;
var monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
/*
* Tooltip
*/
$.fn.UseTooltip = function () {
if($(window).width() > 768){
$(this).bind("plothover", function (event, pos, item) {
if (item) {
if ((previousLabel != item.series.label) || (previousPoint != item.dataIndex)) {
previousPoint = item.dataIndex;
previousLabel = item.series.label;
$("#tooltip").remove();
var color = item.series.color;
showTooltip(item.pageX, item.pageY, item.series.color, getTemplateForToolip(item));
}
} else {
$("#tooltip").remove();
previousPoint = null;
}
});
}
};
function showTooltip(x, y, color, contents) {
var tooltip = $('<div id="tooltip">' + contents + '</div>').css({
'border-color': color
});
tooltip.find('#tooltip-arrow').css('border-top-color', color);
tooltip.appendTo("body").fadeIn(200);
tooltip.css({
top: y - (tooltip[0].offsetHeight + 10),
left: x - (tooltip[0].offsetWidth - 18)
});
}
function getTemplateForToolip(item){
if(dataSet == 'amount'){
var amount = formatedData.value[item.seriesIndex].data[item.dataIndex][1];
var count = formatedData.value_count[item.seriesIndex].data[item.dataIndex][1];
}else{
var count = formatedData.count[item.seriesIndex].data[item.dataIndex][1];
var amount = formatedData.count_value[item.seriesIndex].data[item.dataIndex][1];
}
var x = item.datapoint[0];
labelContrat = (count == 1) ? " "+defTypeName() : " "+defTypeName()+'s';
var text = "";
text += "<div style='position: relative;'>";
text += " <div style='' class='domaineName'><strong>{month}</strong></div>";
text += " <h5 style='margin: 0;'>{label}</h5 style='margin: 0;'>";
text += " <div><strong>{money} - {count} "+labelContrat+"</strong></div>";
text += " <div id='tooltip-arrow'></div>";
text += "</div>";
var amountFormatted = amount.formatMoney('0', ',', ' ')+ ' $';
return text
.replace('{month}', new Date(x).toLongFrenchFormatMonth())
.replace('{label}', item.series.label)
.replace('{money}', amountFormatted)
.replace('{count}', count);
}
/*
* from http://stackoverflow.com/a/14994860
* Transform Y labels - money
*/
function valueFormatter(num) {
if (num >= 1000000000) {
return (num / 1000000000).toFixed(1).replace(/\.0$/, '') + ' G $';
}
if (num >= 1000000) {
return (num / 1000000).toFixed(1).replace(/\.0$/, '') + ' M $';
}
if (num >= 1000) {
return (num / 1000).toFixed(1).replace(/\.0$/, '') + ' K $';
}
return num + ' $';
}
/*
* from http://stackoverflow.com/a/14994860
* Transform Y labels
*/
function countFormatter(num) {
if (num >= 1000000000) {
return (num / 1000000000).toFixed(1).replace(/\.0$/, '') + ' G';
}
if (num >= 1000000) {
return (num / 1000000).toFixed(1).replace(/\.0$/, '') + ' M';
}
if (num >= 1000) {
return (num / 1000).toFixed(1).replace(/\.0$/, '') + ' K';
}
if (num === +num && num !== (num|0)) {
return num.toFixed(1);
}
return num;
}
/*
* Init plot
*/
function plotWithOptions(formatedData,options) {
if (formatedData.length > 0) {
window.plot = $.plot("#stacked", formatedData, options);
$("#stacked").UseTooltip();
}
}
/*
* Refresh the plot with a new width
*/
function resizedw(){
resizegraph();
plotWithOptions(wg(formatedData), options);
}
/*
* define which graph is currently displayed
*/
function wgcheck() {
if ($(".switchgraph span").hasClass('value')) {
return 'value';
}else{
return 'count';
}
}
/*
* define which graph is currently displayed
* return the good dataset
*/
function wg(data) {
if (data) {
if ($(".switchgraph span").hasClass('value')) {
return data.value;
}else{
return data.count;
}
}return {};
}
/*
* Plot configuration
*/
var options = {
series: {
grow: {
active: true,
duration: 400,
reanimate: false,
valueIndex: 1
},
stack: true,
lines: {
show: false,
fill: true,
steps: false
},
bars: {
align: "left",
lineWidth: 0,
fill: 0.7,
show: true,
barWidth: 800 * 60 * 60 * 24 * 30
}
},
yaxis:{
min: 0,
tickFormatter: valueFormatter
},
xaxis: {
mode: "time",
timeformat: "%Y",
timezone: "browser",
minTickSize: [1, "year"]
},
grid: {
hoverable: true,
mouseActiveRadius:1,
},
legend: {
container: "#legend",
labelFormatter: function (label, series) {
$('<div class="labelG col-lg-4 col-md-6 col-sm-12"><i class="fa fa-circle-o colorG" style="color:'+series.color+'"></i><span class="innerTextG">'+label+'</span></div>').appendTo("#legend");
return false;
}
//sorted: "ascending",
}
};
/*
* Launch a query with the selected page
* linked with simplepagination
*/
function page(num) {
$('html, body').animate({ scrollTop: $(".filters").offset().top - 150 }, 600);
var limit = $("#limit").val();
var offset = (num - 1)*limit;
$("#offset").val(offset);
$("#offset").trigger('change');
}
/*
* Launch a query with the selected page
* Linked with simplepagination
*/
function calculHeight() {
if ($(window).width() > 1200) {
return {
padding:150,
height:150
}
}else if($(window).width() <= 1200 && $(window).width() > 992){
return {
padding:240,
height:240
}
}else if($(window).width() <= 992) {
return {
padding:60,
height:60
}
}else {
return {
padding:60,
height:60
}
}
}
/*
* Return the french translation of the current type
*/
function defTypeName(){
if ($("input[type='radio'][name=type]:checked").val() == 'contract') {
return 'contrat';
}else{
return 'subvention';
}
}
/*
*Global variables
*/
var dataSet = 'amount';
var formatedData;
var ovc;
var init = true;
var navmod;
resizegraph();
$(function() {
$(".noResults").hide();
$(".searchbar").sticky({
responsiveWidth: true,
topSpacing: 0,
})
/*
//Uncomment if you want to have the "filters bar" sticky
$(".filters").sticky({
responsiveWidth: true,
topSpacing: 0,
})
.on('sticky-start', function() {
$(".toolbars.filters").css('padding-top', calculHeight().padding);
$(".toolbars.filters").parent().css('height',calculHeight().height);
})
.on('sticky-end', function() {
$(".toolbars.filters").css('padding-top', '60px');
$(".toolbars.filters").parent().css('height','auto');
});
$(".toolbars.filters").css('padding-top', '60px');
$(".toolbars.filters").parent().css('height','auto');
*/
// Init API client
ovc = new OvcMtlApi();
if (ovc_api_url) {
ovc.base_url = ovc_api_url;
}
ovc.init();
// Init pagination
var pages = $(ovc.paginationSelector).pagination({
displayedPages : 3,
edges: 1,
prevText: '<',
nextText: '>',
hrefTextPrefix : "javascript:page('",
hrefTextSuffix : "')",
});
// the default request
if(ovc.historyState()){
var apiData = ovc.byMonthActivity();
if (results_accepted(apiData.stats)) {
formatedData = ovc.flotChartsFormat(apiData.stats);
var links = ovc.export();
for (var l in links) {
if(links[l].enabled){
$(".export."+l).attr('href',links[l].link_to);
$(".export."+l).css('cursor','pointer');
$(".export."+l).attr('title','Exportation limitée à '+links[l].limit +' fiches');
}else{
$(".export."+l).css('cursor','not-allowed');
$(".export."+l).attr('title','Exportation limitée à '+links[l].limit +' fiches');
}
}
pages.pagination('updateItemsOnPage', ovc.itemsOnPage);
pages.pagination('updateItems', ovc.items);
pages.pagination('selectPage', ovc.currentPageByOffset());
renameLabels();
}
}
//Needed - Growraf is not enough fast to calculate on each screen resize, Y axis bug
var doit;
$( window ).resize(function() {
if (window.plot) {
window.plot.shutdown();
clearTimeout(doit);
doit = setTimeout(resizedw, 1000);
}
});
$('#procuring_entity').selectpicker('render');
$('#activity').selectpicker('render');
if( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) {
$('#procuring_entity').selectpicker('mobile');
$('#activity').selectpicker('mobile');
}
/*
* On each request
*/
if (ovc.detectIE() > 9 || !ovc.detectIE()) {
$(window).bind('popstate', function(event){
init = false
navmod = 'popstate';
if(ovc.refresh()){
var apiData = ovc.byMonthActivity();
if (results_accepted(apiData.stats)) {
formatedData = ovc.flotChartsFormat(apiData.stats);
var links = ovc.export();
for (var l in links) {
if(links[l].enabled){
$(".export."+l).attr('href',links[l].link_to);
$(".export."+l).css('cursor','pointer');
$(".export."+l).attr('title','Exportation limitée à '+links[l].limit +' fiches');
}else{
$(".export."+l).css('cursor','not-allowed');
$(".export."+l).attr('title','Exportation limitée à '+links[l].limit +' fiches');
}
}
pages.pagination('updateItemsOnPage', ovc.itemsOnPage);
pages.pagination('updateItems', ovc.items);
pages.pagination('selectPage', ovc.currentPageByOffset());
plotWithOptions(wg(formatedData), options);
}
var qd = ovc.paramsExtract();
$('.searchboxhidden').tagsinput('removeAll');
if (qd.supplier) {
$('.searchboxLabel').html("Fournisseur");
$(".bootstrap-tagsinput").find('.searchbox').hide();
$(".bootstrap-tagsinput").find('.searchbutton').hide();
$('.searchboxhidden').tagsinput('removeAll');
$('.searchboxhidden').tagsinput('add', ovc.decode(qd).supplier);
$(".bootstrap-tagsinput").find('.tag').addClass('supplier');
}else if(qd.buyer) {
$('.searchboxLabel').html("Octroyé par");
$(".bootstrap-tagsinput").find('.searchbox').hide();
$(".bootstrap-tagsinput").find('.searchbutton').hide();
$('.searchboxhidden').tagsinput('add', ovc.decode(qd).buyer);
$(".bootstrap-tagsinput").find('.tag').addClass('buyer');
}else if(qd.q){
$('.searchboxLabel').html("Mots clés");
$(".bootstrap-tagsinput").find('.searchbox').hide();
$(".bootstrap-tagsinput").find('.searchbutton').hide();
$('.searchboxhidden').tagsinput('add',ovc.decode(qd).q);
}else{
$('.searchboxLabel').html("Mots clés");
$("#theMainTag").css('display','none');
$(".bootstrap-tagsinput").find('.searchbox').show();
$(".bootstrap-tagsinput").find('.searchbutton').show();
}
$('#procuring_entity').selectpicker('refresh');
$('#activity').selectpicker('refresh');
renameLabels();
}
});
}else{
$(window).bind('hashchange', function() {
init = false
navmod = 'hashchange';
if(ovc.refresh()){
var apiData = ovc.byMonthActivity();
if (results_accepted(apiData.stats)) {
formatedData = ovc.flotChartsFormat(apiData.stats);
var links = ovc.export();
for (var l in links) {
if(links[l].enabled){
$(".export."+l).attr('href',links[l].link_to);
$(".export."+l).css('cursor','pointer');
$(".export."+l).attr('title','Exportation limitée à '+links[l].limit +' fiches');
}else{
$(".export."+l).css('cursor','not-allowed');
$(".export."+l).attr('title','Exportation limitée à '+links[l].limit +' fiches');
}
}
pages.pagination('updateItemsOnPage', ovc.itemsOnPage);
pages.pagination('updateItems', ovc.items);
pages.pagination('selectPage', ovc.currentPageByOffset());
plotWithOptions(wg(formatedData), options);
}
var qd = ovc.paramsExtract();
$('.searchboxhidden').tagsinput('removeAll');
if (qd.supplier) {
$('.searchboxLabel').html("Fournisseur");
$(".bootstrap-tagsinput").find('.searchbox').hide();
$(".bootstrap-tagsinput").find('.searchbutton').hide();
$('.searchboxhidden').tagsinput('removeAll');
$('.searchboxhidden').tagsinput('add', ovc.decode(qd).supplier);
$(".bootstrap-tagsinput").find('.tag').addClass('supplier');
}else if(qd.buyer) {
$('.searchboxLabel').html("Octroyé par");
$(".bootstrap-tagsinput").find('.searchbox').hide();
$(".bootstrap-tagsinput").find('.searchbutton').hide();
$('.searchboxhidden').tagsinput('add', ovc.decode(qd).buyer);
$(".bootstrap-tagsinput").find('.tag').addClass('buyer');
}else if(qd.q){
$('.searchboxLabel').html("Mots clés");
$(".bootstrap-tagsinput").find('.searchbox').hide();
$(".bootstrap-tagsinput").find('.searchbutton').hide();
$('.searchboxhidden').tagsinput('add',ovc.decode(qd).q);
}else{
$('.searchboxLabel').html("Mots clés");
$("#theMainTag").css('display','none');
$(".bootstrap-tagsinput").find('.searchbox').show();
$(".bootstrap-tagsinput").find('.searchbutton').show();
}
$('#procuring_entity').selectpicker('refresh');
$('#activity').selectpicker('refresh');
renameLabels();
}
});
}
$("input, select, textarea").not('[name=q]').not("[type=hidden]").not('.loading').change(function(event){
//offset to zero, it is a new search
if (!$(event.currentTarget).hasClass('loading')) {
$(ovc.currOffsetFieldSelector).val(0);
//remove buyer and supplier input values
if(ovc.historyState()){
var apiData = ovc.byMonthActivity();
if (results_accepted(apiData.stats)) {
formatedData = ovc.flotChartsFormat(apiData.stats);
var links = ovc.export();
for (var l in links) {
if(links[l].enabled){
$(".export."+l).attr('href',links[l].link_to);
$(".export."+l).css('cursor','pointer');
$(".export."+l).attr('title','Exportation limitée à '+links[l].limit +' fiches');
}else{
$(".export."+l).css('cursor','not-allowed');
$(".export."+l).attr('title','Exportation limitée à '+links[l].limit +' fiches');
}
}
}
}
pages.pagination('updateItems', ovc.items);
pages.pagination('selectPage', ovc.currentPageByOffset());
plotWithOptions(wg(formatedData), options);
$('html, body').animate({ scrollTop: 0 }, 300);
}
}).keyup(function(event){
if(event.keyCode == 13){
$("[name=q]").trigger("change");
}
});
$("input[type='hidden']").not(".buyer").not(".supplier").change(function(event){
if(event.currentTarget.name == 'date_lt' || event.currentTarget.name == 'date_gt' || event.currentTarget.name == 'order_by'){
$(ovc.currOffsetFieldSelector).val(0);
pages.pagination('selectPage', '1');
}
console.log('keyword');
$("[name=q]").val($("[name=q]").val().replace(/\?/g,'').replace(/&/g,'').replace(/%/g,''));
if(ovc.historyState()){
var apiData = ovc.byMonthActivity();
if (results_accepted(apiData.stats)) {
formatedData = ovc.flotChartsFormat(apiData.stats);
var links = ovc.export();
for (var l in links) {
if(links[l].enabled){
$(".export."+l).attr('href',links[l].link_to);
$(".export."+l).css('cursor','pointer');
$(".export."+l).attr('title','Exportation limitée à '+links[l].limit +' fiches');
}else{
$(".export."+l).css('cursor','not-allowed');
$(".export."+l).attr('title','Exportation limitée à '+links[l].limit +' fiches');
}
}
}
}
pages.pagination('updateItems', ovc.items);
plotWithOptions(wg(formatedData), options);
});
plotWithOptions(wg(formatedData), options);
$("#date_gt_view").datepicker( {
format: "yyyy-mm",
viewMode: "months",
minViewMode: "months",
minDate: '2012/01/01',
}).on('changeDate', function(ev){
var unix_timestamp = ev.date.valueOf();
formatedDate = new Date(unix_timestamp ).yyyymmdd();
$("#date_gt").val(formatedDate);
$("#date_gt").trigger('change');
$(this).datepicker('hide');
});
$("#date_lt_view").datepicker( {
format: "yyyy-mm",
viewMode: "months",
minViewMode: "months",
minDate: '2012/01/01',
}).on('changeDate', function(ev){
var unix_timestamp = ev.date.valueOf();
formatedDate = new Date(unix_timestamp ).yyyymmlastdd();
$("#date_lt").val(formatedDate);
$("#date_lt").trigger('change');
$(this).datepicker('hide');
});
$("#ob_value").on('click', function(){
$("#order_by").val('value');
$("#order_dir").val('desc');
$("#order_by").trigger('change');
$(".orderby").removeClass("active");
$(this).addClass("active");
});
$("#ob_date").on('click', function(){
$("#order_by").val('date');
$("#order_dir").val('desc');
$("#order_by").trigger('change');
$(".orderby").removeClass("active");
$(this).addClass("active");
});
$("#od_supplier").on('click', function(){
$("#order_by").val('supplier');
$("#order_dir").val('asc');
$("#order_by").trigger('change');
$(".orderby").removeClass("active");
$(this).addClass("active");
});
$( ".upbtn-container" ).click(function() {
$(".graph-container").toggle(function(e){
if ($(this).is(":visible") ) {
$(".filters").css("padding-top","0px");
$("#toggleGraph").find('i').removeClass('fa-angle-double-down');
$("#toggleGraph").find('i').addClass('fa-angle-double-up');
$('html, body').animate({ scrollTop: 0 }, 300);
}else{
$(".filters").css("padding-top","70px");
$("#toggleGraph").find('i').removeClass('fa-angle-double-up');
$("#toggleGraph").find('i').addClass('fa-angle-double-down');
}
$(".filters").sticky('update');
});
});
$(".btnmenu").on('click', function(){
if (!$(".searchbar").is(':visible')) {
$(".searchbar").show();
$(".btnmenu i").removeClass('fa-bars');
$(".btnmenu i").addClass('fa-close');
}else {
$(".searchbar").hide();
$(".btnmenu i").removeClass('fa-close');
$(".btnmenu i").addClass('fa-bars');
}
return false;
});
$('.money').mask('00000000000000', {reverse: true});
$( ".switchgraph span" ).click(function() {
var optionsx = options;
if ($(this).hasClass('count')) {
var apiData = ovc.byMonthActivity('count');
$(this).removeClass('count');
$(this).addClass('value');
$(this).html('Voir nombre de '+defTypeName()+'s par mois');
$(".graphTitle").html('Montant total des '+defTypeName()+'s par mois');
dataSet = 'amount';
optionsx.yaxis.tickFormatter = valueFormatter;
}else if($(this).hasClass('value')) {
var apiData = ovc.byMonthActivity('value');
$(this).removeClass('value');
$(this).addClass('count');
$(this).html('Voir montant des '+defTypeName()+'s par mois');
$(".graphTitle").html('Nombre total de '+defTypeName()+'s par mois');
dataSet = 'count';
optionsx.yaxis.tickFormatter = countFormatter;
}
formatedData = ovc.flotChartsFormat(apiData.stats);
plotWithOptions(wg(formatedData), options);
});
$('.searchboxhidden').tagsinput({
maxTags: 1,
trimValue: true,
addOnBlur: false,
});
if ($(".searchboxhidden").val()) {
$(".bootstrap-tagsinput").find('.searchbox').hide();
$(".bootstrap-tagsinput").find('.searchbutton').hide();
//$('.searchboxhidden').tagsinput('refresh');
}
$('.searchboxhidden').on('beforeItemAdd', function(event) {
$(".bootstrap-tagsinput").find('.searchbox').hide();
$(".bootstrap-tagsinput").find('.searchbutton').hide();
$("input#offset").val('0');
pages.pagination('selectPage', '1');
})
$('.searchboxhidden').on('itemAdded', function(event) {
if (init || (ovc.decode(ovc.paramsExtract()).q != event.item && navmod == 'hashchange') || /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) {
$("#supplier").trigger('change');
}
init = true;
})
$('.searchboxhidden').on('itemRemoved', function(event) {
$('.searchboxLabel').html("Mots clés");
$(".bootstrap-tagsinput").find('.searchbox').show();
$(".bootstrap-tagsinput").find('.searchbutton').show();
$("#buyer").val('');
$("#supplier").val('');
if (init) {
$("#supplier").trigger('change');
}
init = true;
});
if ($('#supplier').val()) {
bysupplier($('#supplier').val());
}
if ($('#buyer').val()) {
bybuyer($('#buyer').val());
}
$(".scrolltop").on('click', function(){
$('html, body').animate({ scrollTop: 0 }, 300);
});
$(".scrolldown").on('click', function(){
$('html, body').animate({ scrollTop: $(".filters").offset().top - 140 }, 600);
});
$(".searchbutton i.fa").on('click', function(){
$('.searchbox').trigger($.Event( "keypress", { which: 13 } ));
});
$("[name=type]").on('change', function(){renameLabels()});
$(".export").hover(
function() // on mouseover
{
$(".exportInfo").html($(this).attr('title'));
},
function() // on mouseout
{
$(".exportInfo").html('');
});
});
$(window).load(function() {
$(".loading").fadeOut(500);
}) | opennorth/ovc-vdm | static/js/main.js | JavaScript | bsd-3-clause | 33,353 |
#! /usr/bin/python
# Copyright 2004-2008 Roman Yakovenko.
# Distributed under the Boost Software License, Version 1.0. (See
# accompanying file LICENSE_1_0.txt or copy at
# http://www.boost.org/LICENSE_1_0.txt)
import unittest
import autoconfig
import pygccxml
from pygccxml.utils import *
from pygccxml.parser import *
from pygccxml import declarations
class tester_t( unittest.TestCase ):
def __init__(self, *args ):
unittest.TestCase.__init__( self, *args )
def __test_split_impl(self, decl_string, name, args):
self.failUnless( ( name, args ) == declarations.call_invocation.split( decl_string ) )
def __test_split_recursive_impl(self, decl_string, control_seq):
self.failUnless( control_seq == declarations.call_invocation.split_recursive( decl_string ) )
def __test_is_call_invocation_impl( self, decl_string ):
self.failUnless( declarations.call_invocation.is_call_invocation( decl_string ) )
def test_split_on_vector(self):
self.__test_is_call_invocation_impl( "vector(int,std::allocator(int) )" )
self.__test_split_impl( "vector(int,std::allocator(int) )"
, "vector"
, [ "int", "std::allocator(int)" ] )
self.__test_split_recursive_impl( "vector(int,std::allocator(int) )"
, [ ( "vector", [ "int", "std::allocator(int)" ] )
, ( "std::allocator", ["int"] ) ] )
def test_split_on_string(self):
self.__test_is_call_invocation_impl( "basic_string(char,std::char_traits(char),std::allocator(char) )" )
self.__test_split_impl( "basic_string(char,std::char_traits(char),std::allocator(char) )"
, "basic_string"
, [ "char", "std::char_traits(char)", "std::allocator(char)" ] )
def test_split_on_map(self):
self.__test_is_call_invocation_impl( "map(long int,std::vector(int, std::allocator(int) ),std::less(long int),std::allocator(std::pair(const long int, std::vector(int, std::allocator(int) ) ) ) )" )
self.__test_split_impl( "map(long int,std::vector(int, std::allocator(int) ),std::less(long int),std::allocator(std::pair(const long int, std::vector(int, std::allocator(int) ) ) ) )"
, "map"
, [ "long int"
, "std::vector(int, std::allocator(int) )"
, "std::less(long int)"
, "std::allocator(std::pair(const long int, std::vector(int, std::allocator(int) ) ) )" ] )
def test_join_on_vector(self):
self.failUnless( "vector( int, std::allocator(int) )"
== declarations.call_invocation.join("vector", ( "int", "std::allocator(int)" ) ) )
def test_find_args(self):
temp = 'x()()'
found = declarations.call_invocation.find_args( temp )
self.failUnless( (1,2) == found )
found = declarations.call_invocation.find_args( temp, found[1]+1 )
self.failUnless( (3, 4) == found )
temp = 'x(int,int)(1,2)'
found = declarations.call_invocation.find_args( temp )
self.failUnless( (1,9) == found )
found = declarations.call_invocation.find_args( temp, found[1]+1 )
self.failUnless( (10, 14) == found )
def test_bug_unmatched_brace( self ):
src = 'AlternativeName((&string("")), (&string("")), (&string("")))'
self.__test_split_impl( src
, 'AlternativeName'
, ['(&string(""))', '(&string(""))', '(&string(""))'] )
def create_suite():
suite = unittest.TestSuite()
suite.addTest( unittest.makeSuite(tester_t))
return suite
def run_suite():
unittest.TextTestRunner(verbosity=2).run( create_suite() )
if __name__ == "__main__":
run_suite()
| avaitla/Haskell-to-C---Bridge | pygccxml-1.0.0/unittests/call_invocation_tester.py | Python | bsd-3-clause | 4,057 |
/////////////////////////////////////////////////////////////////////////////
// Name: src/common/dynlib.cpp
// Purpose: Dynamic library management
// Author: Guilhem Lavaux
// Modified by:
// Created: 20/07/98
// Copyright: (c) 1998 Guilhem Lavaux
// 2000-2005 Vadim Zeitlin
// Licence: wxWindows licence
/////////////////////////////////////////////////////////////////////////////
//FIXME: This class isn't really common at all, it should be moved into
// platform dependent files (already done for Windows and Unix)
// ============================================================================
// declarations
// ============================================================================
// ----------------------------------------------------------------------------
// headers
// ----------------------------------------------------------------------------
#include "wx/wxprec.h"
#if wxUSE_DYNLIB_CLASS
#include "wx/dynlib.h"
#ifndef WX_PRECOMP
#include "wx/intl.h"
#include "wx/log.h"
#include "wx/app.h"
#include "wx/utils.h"
#endif //WX_PRECOMP
#include "wx/filefn.h"
#include "wx/filename.h" // for SplitPath()
#include "wx/platinfo.h"
#include "wx/arrimpl.cpp"
WX_DEFINE_USER_EXPORTED_OBJARRAY(wxDynamicLibraryDetailsArray)
// ============================================================================
// implementation
// ============================================================================
// ---------------------------------------------------------------------------
// wxDynamicLibrary
// ---------------------------------------------------------------------------
// for MSW/Unix it is defined in platform-specific file
#if !(defined(__WINDOWS__) || defined(__UNIX__))
wxDllType wxDynamicLibrary::GetProgramHandle()
{
wxFAIL_MSG( wxT("GetProgramHandle() is not implemented under this platform"));
return 0;
}
#endif // __WINDOWS__ || __UNIX__
bool wxDynamicLibrary::Load(const wxString& libnameOrig, int flags)
{
wxASSERT_MSG(m_handle == 0, wxT("Library already loaded."));
// add the proper extension for the DLL ourselves unless told not to
wxString libname = libnameOrig;
if ( !(flags & wxDL_VERBATIM) )
{
// and also check that the libname doesn't already have it
wxString ext;
wxFileName::SplitPath(libname, NULL, NULL, &ext);
if ( ext.empty() )
{
libname += GetDllExt(wxDL_MODULE);
}
}
m_handle = RawLoad(libname, flags);
if ( m_handle == 0 && !(flags & wxDL_QUIET) )
{
ReportError(_("Failed to load shared library '%s'"), libname);
}
return IsLoaded();
}
void *wxDynamicLibrary::DoGetSymbol(const wxString &name, bool *success) const
{
wxCHECK_MSG( IsLoaded(), NULL,
wxT("Can't load symbol from unloaded library") );
void *symbol = RawGetSymbol(m_handle, name);
if ( success )
*success = symbol != NULL;
return symbol;
}
void *wxDynamicLibrary::GetSymbol(const wxString& name, bool *success) const
{
void *symbol = DoGetSymbol(name, success);
if ( !symbol )
{
ReportError(_("Couldn't find symbol '%s' in a dynamic library"), name);
}
return symbol;
}
// ----------------------------------------------------------------------------
// informational methods
// ----------------------------------------------------------------------------
/*static*/
wxString wxDynamicLibrary::GetDllExt(wxDynamicLibraryCategory cat)
{
wxUnusedVar(cat);
#if defined(__WINDOWS__)
return ".dll";
#elif defined(__HPUX__)
return ".sl";
#elif defined(__DARWIN__)
switch ( cat )
{
case wxDL_LIBRARY:
return ".dylib";
case wxDL_MODULE:
return ".bundle";
}
wxFAIL_MSG("unreachable");
return wxString(); // silence gcc warning
#else
return ".so";
#endif
}
/*static*/
wxString
wxDynamicLibrary::CanonicalizeName(const wxString& name,
wxDynamicLibraryCategory cat)
{
wxString nameCanonic;
// under Unix the library names usually start with "lib" prefix, add it
#if defined(__UNIX__)
switch ( cat )
{
case wxDL_LIBRARY:
// Library names should start with "lib" under Unix.
nameCanonic = "lib";
break;
case wxDL_MODULE:
// Module names are arbitrary and should have no prefix added.
break;
}
#endif
nameCanonic << name << GetDllExt(cat);
return nameCanonic;
}
/*static*/
wxString wxDynamicLibrary::CanonicalizePluginName(const wxString& name,
wxPluginCategory cat)
{
wxString suffix;
if ( cat == wxDL_PLUGIN_GUI )
{
suffix = wxPlatformInfo::Get().GetPortIdShortName();
}
#if wxUSE_UNICODE
suffix << wxT('u');
#endif
#ifdef __WXDEBUG__
suffix << wxT('d');
#endif
if ( !suffix.empty() )
suffix = wxString(wxT("_")) + suffix;
#define WXSTRINGIZE(x) #x
#if defined(__UNIX__)
#if (wxMINOR_VERSION % 2) == 0
#define wxDLLVER(x,y,z) "-" WXSTRINGIZE(x) "." WXSTRINGIZE(y)
#else
#define wxDLLVER(x,y,z) "-" WXSTRINGIZE(x) "." WXSTRINGIZE(y) "." WXSTRINGIZE(z)
#endif
#else
#if (wxMINOR_VERSION % 2) == 0
#define wxDLLVER(x,y,z) WXSTRINGIZE(x) WXSTRINGIZE(y)
#else
#define wxDLLVER(x,y,z) WXSTRINGIZE(x) WXSTRINGIZE(y) WXSTRINGIZE(z)
#endif
#endif
suffix << wxString::FromAscii(wxDLLVER(wxMAJOR_VERSION, wxMINOR_VERSION,
wxRELEASE_NUMBER));
#undef wxDLLVER
#undef WXSTRINGIZE
#ifdef __WINDOWS__
// Add compiler identification:
#if defined(__GNUG__)
suffix << wxT("_gcc");
#elif defined(__VISUALC__)
suffix << wxT("_vc");
#endif
#endif
return CanonicalizeName(name + suffix, wxDL_MODULE);
}
/*static*/
wxString wxDynamicLibrary::GetPluginsDirectory()
{
#ifdef __UNIX__
wxString format = wxGetInstallPrefix();
if ( format.empty() )
return wxEmptyString;
wxString dir;
format << wxFILE_SEP_PATH
<< wxT("lib") << wxFILE_SEP_PATH
<< wxT("wx") << wxFILE_SEP_PATH
#if (wxMINOR_VERSION % 2) == 0
<< wxT("%i.%i");
dir.Printf(format.c_str(), wxMAJOR_VERSION, wxMINOR_VERSION);
#else
<< wxT("%i.%i.%i");
dir.Printf(format.c_str(),
wxMAJOR_VERSION, wxMINOR_VERSION, wxRELEASE_NUMBER);
#endif
return dir;
#else // ! __UNIX__
return wxEmptyString;
#endif
}
#endif // wxUSE_DYNLIB_CLASS
| ric2b/Vivaldi-browser | update_notifier/thirdparty/wxWidgets/src/common/dynlib.cpp | C++ | bsd-3-clause | 6,621 |