text stringlengths 2 99k | meta dict |
|---|---|
!function(d3) {
var mpld3 = {
_mpld3IsLoaded: true,
figures: [],
plugin_map: {}
};
mpld3.version = "0.4.2";
mpld3.register_plugin = function(name, obj) {
mpld3.plugin_map[name] = obj;
};
mpld3.remove_figure = function(figid) {
var element = document.getElementById(figid);
if (element !== null) {
element.innerHTML = "";
}
for (var i = 0; i < mpld3.figures.length; i++) {
var fig = mpld3.figures[i];
if (fig.figid === figid) {
mpld3.figures.splice(i, 1);
}
}
return true;
};
mpld3.draw_figure = function(figid, spec, process, clearElem) {
var element = document.getElementById(figid);
clearElem = typeof clearElem !== "undefined" ? clearElem : false;
if (clearElem) {
mpld3.remove_figure(figid);
}
if (element === null) {
throw figid + " is not a valid id";
}
var fig = new mpld3.Figure(figid, spec);
if (process) {
process(fig, element);
}
mpld3.figures.push(fig);
fig.draw();
return fig;
};
mpld3.cloneObj = mpld3_cloneObj;
function mpld3_cloneObj(oldObj) {
var newObj = {};
for (var key in oldObj) {
newObj[key] = oldObj[key];
}
return newObj;
}
mpld3.boundsToTransform = function(fig, bounds) {
var width = fig.width;
var height = fig.height;
var dx = bounds[1][0] - bounds[0][0];
var dy = bounds[1][1] - bounds[0][1];
var x = (bounds[0][0] + bounds[1][0]) / 2;
var y = (bounds[0][1] + bounds[1][1]) / 2;
var scale = Math.max(1, Math.min(8, .9 / Math.max(dx / width, dy / height)));
var translate = [ width / 2 - scale * x, height / 2 - scale * y ];
return {
translate: translate,
scale: scale
};
};
mpld3.getTransformation = function(transform) {
var g = document.createElementNS("http://www.w3.org/2000/svg", "g");
g.setAttributeNS(null, "transform", transform);
var matrix = g.transform.baseVal.consolidate().matrix;
var a = matrix.a, b = matrix.b, c = matrix.c, d = matrix.d, e = matrix.e, f = matrix.f;
var scaleX, scaleY, skewX;
if (scaleX = Math.sqrt(a * a + b * b)) a /= scaleX, b /= scaleX;
if (skewX = a * c + b * d) c -= a * skewX, d -= b * skewX;
if (scaleY = Math.sqrt(c * c + d * d)) c /= scaleY, d /= scaleY, skewX /= scaleY;
if (a * d < b * c) a = -a, b = -b, skewX = -skewX, scaleX = -scaleX;
var transformObj = {
translateX: e,
translateY: f,
rotate: Math.atan2(b, a) * 180 / Math.PI,
skewX: Math.atan(skewX) * 180 / Math.PI,
scaleX: scaleX,
scaleY: scaleY
};
var transformStr = "" + "translate(" + transformObj.translateX + "," + transformObj.translateY + ")" + "rotate(" + transformObj.rotate + ")" + "skewX(" + transformObj.skewX + ")" + "scale(" + transformObj.scaleX + "," + transformObj.scaleY + ")";
return transformStr;
};
mpld3.merge_objects = function(_) {
var output = {};
var obj;
for (var i = 0; i < arguments.length; i++) {
obj = arguments[i];
for (var attr in obj) {
output[attr] = obj[attr];
}
}
return output;
};
mpld3.generate_id = function(N, chars) {
console.warn("mpld3.generate_id is deprecated. " + "Use mpld3.generateId instead.");
return mpld3_generateId(N, chars);
};
mpld3.generateId = mpld3_generateId;
function mpld3_generateId(N, chars) {
N = typeof N !== "undefined" ? N : 10;
chars = typeof chars !== "undefined" ? chars : "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
var id = chars.charAt(Math.round(Math.random() * (chars.length - 11)));
for (var i = 1; i < N; i++) id += chars.charAt(Math.round(Math.random() * (chars.length - 1)));
return id;
}
mpld3.get_element = function(id, fig) {
var figs_to_search, ax, el;
if (typeof fig === "undefined") {
figs_to_search = mpld3.figures;
} else if (typeof fig.length === "undefined") {
figs_to_search = [ fig ];
} else {
figs_to_search = fig;
}
for (var i = 0; i < figs_to_search.length; i++) {
fig = figs_to_search[i];
if (fig.props.id === id) {
return fig;
}
for (var j = 0; j < fig.axes.length; j++) {
ax = fig.axes[j];
if (ax.props.id === id) {
return ax;
}
for (var k = 0; k < ax.elements.length; k++) {
el = ax.elements[k];
if (el.props.id === id) {
return el;
}
}
}
}
return null;
};
mpld3.insert_css = function(selector, attributes) {
var head = document.head || document.getElementsByTagName("head")[0];
var style = document.createElement("style");
var css = selector + " {";
for (var prop in attributes) {
css += prop + ":" + attributes[prop] + "; ";
}
css += "}";
style.type = "text/css";
if (style.styleSheet) {
style.styleSheet.cssText = css;
} else {
style.appendChild(document.createTextNode(css));
}
head.appendChild(style);
};
mpld3.process_props = function(obj, properties, defaults, required) {
console.warn("mpld3.process_props is deprecated. " + "Plot elements should derive from mpld3.PlotElement");
Element.prototype = Object.create(mpld3_PlotElement.prototype);
Element.prototype.constructor = Element;
Element.prototype.requiredProps = required;
Element.prototype.defaultProps = defaults;
function Element(props) {
mpld3_PlotElement.call(this, null, props);
}
var el = new Element(properties);
return el.props;
};
mpld3.interpolateDates = mpld3_interpolateDates;
function mpld3_interpolateDates(a, b) {
var interp = d3.interpolate([ a[0].valueOf(), a[1].valueOf() ], [ b[0].valueOf(), b[1].valueOf() ]);
return function(t) {
var i = interp(t);
return [ new Date(i[0]), new Date(i[1]) ];
};
}
function isUndefined(x) {
return typeof x === "undefined";
}
function isUndefinedOrNull(x) {
return x == null || isUndefined(x);
}
function getMod(L, i) {
return L.length > 0 ? L[i % L.length] : null;
}
mpld3.path = function() {
return mpld3_path();
};
function mpld3_path(_) {
var x = function(d, i) {
return d[0];
};
var y = function(d, i) {
return d[1];
};
var defined = function(d, i) {
return true;
};
var n_vertices = {
M: 1,
m: 1,
L: 1,
l: 1,
Q: 2,
q: 2,
T: 1,
t: 1,
S: 2,
s: 2,
C: 3,
c: 3,
Z: 0,
z: 0
};
function path(vertices, pathcodes) {
var functor = function(x) {
if (typeof x == "function") {
return x;
}
return function() {
return x;
};
};
var fx = functor(x), fy = functor(y);
var points = [], segments = [], i_v = 0, i_c = -1, halt = 0, nullpath = false;
if (!pathcodes) {
pathcodes = [ "M" ];
for (var i = 1; i < vertices.length; i++) pathcodes.push("L");
}
while (++i_c < pathcodes.length) {
halt = i_v + n_vertices[pathcodes[i_c]];
points = [];
while (i_v < halt) {
if (defined.call(this, vertices[i_v], i_v)) {
points.push(fx.call(this, vertices[i_v], i_v), fy.call(this, vertices[i_v], i_v));
i_v++;
} else {
points = null;
i_v = halt;
}
}
if (!points) {
nullpath = true;
} else if (nullpath && points.length > 0) {
segments.push("M", points[0], points[1]);
nullpath = false;
} else {
segments.push(pathcodes[i_c]);
segments = segments.concat(points);
}
}
if (i_v != vertices.length) console.warn("Warning: not all vertices used in Path");
return segments.join(" ");
}
path.x = function(_) {
if (!arguments.length) return x;
x = _;
return path;
};
path.y = function(_) {
if (!arguments.length) return y;
y = _;
return path;
};
path.defined = function(_) {
if (!arguments.length) return defined;
defined = _;
return path;
};
path.call = path;
return path;
}
mpld3.multiscale = mpld3_multiscale;
function mpld3_multiscale(_) {
var args = Array.prototype.slice.call(arguments, 0);
var N = args.length;
function scale(x) {
args.forEach(function(mapping) {
x = mapping(x);
});
return x;
}
scale.domain = function(x) {
if (!arguments.length) return args[0].domain();
args[0].domain(x);
return scale;
};
scale.range = function(x) {
if (!arguments.length) return args[N - 1].range();
args[N - 1].range(x);
return scale;
};
scale.step = function(i) {
return args[i];
};
return scale;
}
mpld3.icons = {
reset: "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABmJLR0QA/wD/AP+gvaeTAAAACXBI\nWXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH3gIcACMoD/OzIwAAAJhJREFUOMtjYKAx4KDUgNsMDAx7\nyNV8i4GB4T8U76VEM8mGYNNMtCH4NBM0hBjNMIwSsMzQ0MamcDkDA8NmQi6xggpUoikwQbIkHk2u\nE0rLI7vCBknBSyxeRDZAE6qHgQkq+ZeBgYERSfFPAoHNDNUDN4BswIRmKgxwEasP2dlsDAwMYlA/\n/mVgYHiBpkkGKscIDaPfVMmuAGnOTaGsXF0MAAAAAElFTkSuQmCC\n",
move: "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABmJLR0QA/wD/AP+gvaeTAAAACXBI\nWXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH3gIcACQMfLHBNQAAANZJREFUOMud07FKA0EQBuAviaKB\nlFr7COJrpAyYRlKn8hECEkFEn8ROCCm0sBMRYgh5EgVFtEhsRjiO27vkBoZd/vn5d3b+XcrjFI9q\nxgXWkc8pUjOB93GMd3zgB9d1unjDSxmhWSHQqOJki+MtOuv/b3ZifUqctIrMxwhHuG1gim4Ma5kR\nWuEkXFgU4B0MW1Ho4TeyjX3s4TDq3zn8ALvZ7q5wX9DqLOHCDA95cFBAnOO1AL/ZdNopgY3fQcqF\nyriMe37hM9w521ZkkvlMo7o/8g7nZYQ/QDctp1nTCf0AAAAASUVORK5CYII=\n",
zoom: "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABmJLR0QA/wD/AP+gvaeTAAAACXBI\nWXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH3gMPDiIRPL/2oQAAANBJREFUOMvF0b9KgzEcheHHVnCT\nKoI4uXbtLXgB3oJDJxevw1VwkoJ/NjepQ2/BrZRCx0ILFURQKV2kyOeSQpAmn7WDB0Lg955zEhLy\n2scdXlBggits+4WOQqjAJ3qYR7NGLrwXGU9+sGbEtlIF18FwmuBngZ+nCt6CIacC3Rx8LSl4xzgF\nn0tusBn4UyVhuA/7ZYIv5g+pE3ail25hN/qdmzCfpsJVjKKCZesDBwtzrAqGOMQj6vhCDRsY4ALH\nmOVObltR/xeG/jph6OD2r+Fv5lZBWEhMx58AAAAASUVORK5CYII=\n",
brush: "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABmJLR0QA/wD/AP+gvaeTAAAACXBI\nWXMAAEQkAABEJAFAZ8RUAAAAB3RJTUUH3gMCEiQKB9YaAgAAAWtJREFUOMuN0r1qVVEQhuFn700k\nnfEvBq0iNiIiOKXgH4KCaBeIhWARK/EibLwFCwVLjyAWaQzRGG9grC3URkHUBKKgRuWohWvL5pjj\nyTSLxcz7rZlZHyMiItqzFxGTEVF18/UoODNFxDIO4x12dkXqTcBPsCUzD+AK3ndFqhHwEsYz82gn\nN4dbmMRK9R/4KY7jAvbiWmYeHBT5Z4QCP8J1rGAeN3GvU3Mbl/Gq3qCDcxjLzOV+v78fq/iFIxFx\nPyJ2lNJpfBy2g59YzMyzEbEVLzGBJjOriLiBq5gaJrCIU3hcRCbwAtuwjm/Yg/V6I9NgDA1OR8RC\nZq6Vcd7iUwtn5h8fdMBdETGPE+Xe4ExELDRNs4bX2NfCUHe+7UExyfkCP8MhzOA7PuAkvrbwXyNF\nxF3MDqxiqlhXC7SPdaOKiN14g0u4g3H0MvOiTUSNY3iemb0ywmfMdfYyUmAJ2yPiBx6Wr/oy2Oqw\n+A1SupBzAOuE/AAAAABJRU5ErkJggg==\n"
};
mpld3.Grid = mpld3_Grid;
mpld3_Grid.prototype = Object.create(mpld3_PlotElement.prototype);
mpld3_Grid.prototype.constructor = mpld3_Grid;
mpld3_Grid.prototype.requiredProps = [ "xy" ];
mpld3_Grid.prototype.defaultProps = {
color: "gray",
dasharray: "2,2",
alpha: "0.5",
nticks: 10,
gridOn: true,
tickvalues: null,
zorder: 0
};
function mpld3_Grid(ax, prop) {
mpld3_PlotElement.call(this, ax, prop);
this.cssclass = "mpld3-" + this.props.xy + "grid";
if (this.props.xy == "x") {
this.transform = "translate(0," + this.ax.height + ")";
this.position = "bottom";
this.scale = this.ax.xdom;
this.tickSize = -this.ax.height;
} else if (this.props.xy == "y") {
this.transform = "translate(0,0)";
this.position = "left";
this.scale = this.ax.ydom;
this.tickSize = -this.ax.width;
} else {
throw "unrecognized grid xy specifier: should be 'x' or 'y'";
}
}
mpld3_Grid.prototype.draw = function() {
var scaleMethod = {
left: "axisLeft",
right: "axisRight",
top: "axisTop",
bottom: "axisBottom"
}[this.position];
this.grid = d3[scaleMethod](this.scale).ticks(this.props.nticks).tickValues(this.props.tickvalues).tickSize(this.tickSize, 0, 0).tickFormat("");
this.elem = this.ax.axes.append("g").attr("class", this.cssclass).attr("transform", this.transform).call(this.grid);
mpld3.insert_css("div#" + this.ax.fig.figid + " ." + this.cssclass + " .tick", {
stroke: this.props.color,
"stroke-dasharray": this.props.dasharray,
"stroke-opacity": this.props.alpha
});
mpld3.insert_css("div#" + this.ax.fig.figid + " ." + this.cssclass + " path", {
"stroke-width": 0
});
mpld3.insert_css("div#" + this.ax.fig.figid + " ." + this.cssclass + " .domain", {
"pointer-events": "none"
});
};
mpld3_Grid.prototype.zoomed = function(transform) {
if (transform) {
if (this.props.xy == "x") {
this.elem.call(this.grid.scale(transform.rescaleX(this.scale)));
} else {
this.elem.call(this.grid.scale(transform.rescaleY(this.scale)));
}
} else {
this.elem.call(this.grid);
}
};
mpld3.Axis = mpld3_Axis;
mpld3_Axis.prototype = Object.create(mpld3_PlotElement.prototype);
mpld3_Axis.prototype.constructor = mpld3_Axis;
mpld3_Axis.prototype.requiredProps = [ "position" ];
mpld3_Axis.prototype.defaultProps = {
nticks: 10,
tickvalues: null,
tickformat: null,
tickformat_formatter: null,
fontsize: "11px",
fontcolor: "black",
axiscolor: "black",
scale: "linear",
grid: {},
zorder: 0,
visible: true
};
function mpld3_Axis(ax, props) {
mpld3_PlotElement.call(this, ax, props);
var trans = {
bottom: [ 0, this.ax.height ],
top: [ 0, 0 ],
left: [ 0, 0 ],
right: [ this.ax.width, 0 ]
};
var xy = {
bottom: "x",
top: "x",
left: "y",
right: "y"
};
this.ax = ax;
this.transform = "translate(" + trans[this.props.position] + ")";
this.props.xy = xy[this.props.position];
this.cssclass = "mpld3-" + this.props.xy + "axis";
this.scale = this.ax[this.props.xy + "dom"];
this.tickNr = null;
this.tickFormat = null;
}
mpld3_Axis.prototype.getGrid = function() {
var gridprop = {
nticks: this.props.nticks,
zorder: this.props.zorder,
tickvalues: null,
xy: this.props.xy
};
if (this.props.grid) {
for (var key in this.props.grid) {
gridprop[key] = this.props.grid[key];
}
}
return new mpld3_Grid(this.ax, gridprop);
};
mpld3_Axis.prototype.wrapTicks = function() {
function wrap(text, width, lineHeight) {
lineHeight = lineHeight || 1.2;
text.each(function() {
var text = d3.select(this);
var bbox = text.node().getBBox();
var textHeight = bbox.height;
var words = text.text().split(/\s+/).reverse();
var word;
var line = [];
var lineNumber = 0;
var y = text.attr("y");
var dy = textHeight;
var tspan = text.text(null).append("tspan").attr("x", 0).attr("y", y).attr("dy", dy);
while (word = words.pop()) {
line.push(word);
tspan.text(line.join(" "));
if (tspan.node().getComputedTextLength() > width) {
line.pop();
tspan.text(line.join(" "));
line = [ word ];
tspan = text.append("tspan").attr("x", 0).attr("y", y).attr("dy", ++lineNumber * (textHeight * lineHeight) + dy).text(word);
}
}
});
}
var TEXT_WIDTH = 80;
if (this.props.xy == "x") {
this.elem.selectAll("text").call(wrap, TEXT_WIDTH);
}
};
mpld3_Axis.prototype.draw = function() {
var scale = this.props.xy === "x" ? this.parent.props.xscale : this.parent.props.yscale;
if (scale === "date" && this.props.tickvalues) {
var domain = this.props.xy === "x" ? this.parent.x.domain() : this.parent.y.domain();
var range = this.props.xy === "x" ? this.parent.xdom.domain() : this.parent.ydom.domain();
var ordinal_to_js_date = d3.scaleLinear().domain(domain).range(range);
this.props.tickvalues = this.props.tickvalues.map(function(value) {
return new Date(ordinal_to_js_date(value));
});
}
var scaleMethod = {
left: "axisLeft",
right: "axisRight",
top: "axisTop",
bottom: "axisBottom"
}[this.props.position];
this.axis = d3[scaleMethod](this.scale);
var that = this;
if (this.props.tickformat_formatter == "index") {
this.axis = this.axis.tickFormat(function(d, i) {
return that.props.tickformat[d];
});
} else if (this.props.tickformat_formatter == "percent") {
this.axis = this.axis.tickFormat(function(d, i) {
var value = d / that.props.tickformat.xmax * 100;
var decimals = that.props.tickformat.decimals || 0;
var formatted_string = d3.format("." + decimals + "f")(value);
return formatted_string + that.props.tickformat.symbol;
});
} else if (this.props.tickformat_formatter == "str_method") {
this.axis = this.axis.tickFormat(function(d, i) {
var formatted_string = d3.format(that.props.tickformat.format_string)(d);
return that.props.tickformat.prefix + formatted_string + that.props.tickformat.suffix;
});
} else if (this.props.tickformat_formatter == "fixed") {
this.axis = this.axis.tickFormat(function(d, i) {
return that.props.tickformat[i];
});
} else if (this.tickFormat) {
this.axis = this.axis.tickFormat(this.tickFormat);
}
if (this.tickNr) {
this.axis = this.axis.ticks(this.tickNr);
}
if (this.props.tickvalues) {
this.axis = this.axis.tickValues(this.props.tickvalues);
this.filter_ticks(this.axis.tickValues, this.axis.scale().domain());
}
this.elem = this.ax.baseaxes.append("g").attr("transform", this.transform).attr("class", this.cssclass).call(this.axis);
this.wrapTicks();
mpld3.insert_css("div#" + this.ax.fig.figid + " ." + this.cssclass + " line, " + " ." + this.cssclass + " path", {
"shape-rendering": "crispEdges",
stroke: this.props.axiscolor,
fill: "none"
});
mpld3.insert_css("div#" + this.ax.fig.figid + " ." + this.cssclass + " text", {
"font-family": "sans-serif",
"font-size": this.props.fontsize + "px",
fill: this.props.fontcolor,
stroke: "none"
});
};
mpld3_Axis.prototype.zoomed = function(transform) {
if (this.props.tickvalues) {
this.filter_ticks(this.axis.tickValues, this.axis.scale().domain());
}
if (transform) {
if (this.props.xy == "x") {
this.elem.call(this.axis.scale(transform.rescaleX(this.scale)));
} else {
this.elem.call(this.axis.scale(transform.rescaleY(this.scale)));
}
this.wrapTicks();
} else {
this.elem.call(this.axis);
}
};
mpld3_Axis.prototype.setTicks = function(nr, format) {
this.tickNr = nr;
this.tickFormat = format;
};
mpld3_Axis.prototype.filter_ticks = function(tickValues, domain) {
if (this.props.tickvalues != null) {
tickValues(this.props.tickvalues.filter(function(v) {
return v >= domain[0] && v <= domain[1];
}));
}
};
mpld3.Coordinates = mpld3_Coordinates;
function mpld3_Coordinates(trans, ax) {
this.trans = trans;
if (typeof ax === "undefined") {
this.ax = null;
this.fig = null;
if (this.trans !== "display") throw "ax must be defined if transform != 'display'";
} else {
this.ax = ax;
this.fig = ax.fig;
}
this.zoomable = this.trans === "data";
this.x = this["x_" + this.trans];
this.y = this["y_" + this.trans];
if (typeof this.x === "undefined" || typeof this.y === "undefined") throw "unrecognized coordinate code: " + this.trans;
}
mpld3_Coordinates.prototype.xy = function(d, ix, iy) {
ix = typeof ix === "undefined" ? 0 : ix;
iy = typeof iy === "undefined" ? 1 : iy;
return [ this.x(d[ix]), this.y(d[iy]) ];
};
mpld3_Coordinates.prototype.x_data = function(x) {
return this.ax.x(x);
};
mpld3_Coordinates.prototype.y_data = function(y) {
return this.ax.y(y);
};
mpld3_Coordinates.prototype.x_display = function(x) {
return x;
};
mpld3_Coordinates.prototype.y_display = function(y) {
return y;
};
mpld3_Coordinates.prototype.x_axes = function(x) {
return x * this.ax.width;
};
mpld3_Coordinates.prototype.y_axes = function(y) {
return this.ax.height * (1 - y);
};
mpld3_Coordinates.prototype.x_figure = function(x) {
return x * this.fig.width - this.ax.position[0];
};
mpld3_Coordinates.prototype.y_figure = function(y) {
return (1 - y) * this.fig.height - this.ax.position[1];
};
mpld3.Path = mpld3_Path;
mpld3_Path.prototype = Object.create(mpld3_PlotElement.prototype);
mpld3_Path.prototype.constructor = mpld3_Path;
mpld3_Path.prototype.requiredProps = [ "data" ];
mpld3_Path.prototype.defaultProps = {
xindex: 0,
yindex: 1,
coordinates: "data",
facecolor: "green",
edgecolor: "black",
edgewidth: 1,
dasharray: "none",
pathcodes: null,
offset: null,
offsetcoordinates: "data",
alpha: 1,
drawstyle: "none",
zorder: 1
};
function mpld3_Path(ax, props) {
mpld3_PlotElement.call(this, ax, props);
this.data = ax.fig.get_data(this.props.data);
this.pathcodes = this.props.pathcodes;
this.pathcoords = new mpld3_Coordinates(this.props.coordinates, this.ax);
this.offsetcoords = new mpld3_Coordinates(this.props.offsetcoordinates, this.ax);
this.datafunc = mpld3_path();
}
mpld3_Path.prototype.finiteFilter = function(d, i) {
return isFinite(this.pathcoords.x(d[this.props.xindex])) && isFinite(this.pathcoords.y(d[this.props.yindex]));
};
mpld3_Path.prototype.draw = function() {
this.datafunc.defined(this.finiteFilter.bind(this)).x(function(d) {
return this.pathcoords.x(d[this.props.xindex]);
}.bind(this)).y(function(d) {
return this.pathcoords.y(d[this.props.yindex]);
}.bind(this));
if (this.pathcoords.zoomable) {
this.path = this.ax.paths.append("svg:path");
} else {
this.path = this.ax.staticPaths.append("svg:path");
}
this.path = this.path.attr("d", this.datafunc(this.data, this.pathcodes)).attr("class", "mpld3-path").style("stroke", this.props.edgecolor).style("stroke-width", this.props.edgewidth).style("stroke-dasharray", this.props.dasharray).style("stroke-opacity", this.props.alpha).style("fill", this.props.facecolor).style("fill-opacity", this.props.alpha).attr("vector-effect", "non-scaling-stroke");
if (this.props.offset !== null) {
var offset = this.offsetcoords.xy(this.props.offset);
this.path.attr("transform", "translate(" + offset + ")");
}
};
mpld3_Path.prototype.elements = function(d) {
return this.path;
};
mpld3.PathCollection = mpld3_PathCollection;
mpld3_PathCollection.prototype = Object.create(mpld3_PlotElement.prototype);
mpld3_PathCollection.prototype.constructor = mpld3_PathCollection;
mpld3_PathCollection.prototype.requiredProps = [ "paths", "offsets" ];
mpld3_PathCollection.prototype.defaultProps = {
xindex: 0,
yindex: 1,
pathtransforms: [],
pathcoordinates: "display",
offsetcoordinates: "data",
offsetorder: "before",
edgecolors: [ "#000000" ],
drawstyle: "none",
edgewidths: [ 1 ],
facecolors: [ "#0000FF" ],
alphas: [ 1 ],
zorder: 2
};
function mpld3_PathCollection(ax, props) {
mpld3_PlotElement.call(this, ax, props);
if (this.props.facecolors == null || this.props.facecolors.length == 0) {
this.props.facecolors = [ "none" ];
}
if (this.props.edgecolors == null || this.props.edgecolors.length == 0) {
this.props.edgecolors = [ "none" ];
}
var offsets = this.ax.fig.get_data(this.props.offsets);
if (offsets === null || offsets.length === 0) offsets = [ null ];
var N = Math.max(this.props.paths.length, offsets.length);
if (offsets.length === N) {
this.offsets = offsets;
} else {
this.offsets = [];
for (var i = 0; i < N; i++) this.offsets.push(getMod(offsets, i));
}
this.pathcoords = new mpld3_Coordinates(this.props.pathcoordinates, this.ax);
this.offsetcoords = new mpld3_Coordinates(this.props.offsetcoordinates, this.ax);
}
mpld3_PathCollection.prototype.transformFunc = function(d, i) {
var t = this.props.pathtransforms;
var transform = t.length == 0 ? "" : mpld3.getTransformation("matrix(" + getMod(t, i) + ")").toString();
var offset = d === null || typeof d === "undefined" ? "translate(0, 0)" : "translate(" + this.offsetcoords.xy(d, this.props.xindex, this.props.yindex) + ")";
return this.props.offsetorder === "after" ? transform + offset : offset + transform;
};
mpld3_PathCollection.prototype.pathFunc = function(d, i) {
return mpld3_path().x(function(d) {
return this.pathcoords.x(d[0]);
}.bind(this)).y(function(d) {
return this.pathcoords.y(d[1]);
}.bind(this)).apply(this, getMod(this.props.paths, i));
};
mpld3_PathCollection.prototype.styleFunc = function(d, i) {
var styles = {
stroke: getMod(this.props.edgecolors, i),
"stroke-width": getMod(this.props.edgewidths, i),
"stroke-opacity": getMod(this.props.alphas, i),
fill: getMod(this.props.facecolors, i),
"fill-opacity": getMod(this.props.alphas, i)
};
var ret = "";
for (var key in styles) {
ret += key + ":" + styles[key] + ";";
}
return ret;
};
mpld3_PathCollection.prototype.allFinite = function(d) {
if (d instanceof Array) {
return d.length == d.filter(isFinite).length;
} else {
return true;
}
};
mpld3_PathCollection.prototype.draw = function() {
if (this.offsetcoords.zoomable || this.pathcoords.zoomable) {
this.group = this.ax.paths.append("svg:g");
} else {
this.group = this.ax.staticPaths.append("svg:g");
}
this.pathsobj = this.group.selectAll("paths").data(this.offsets.filter(this.allFinite)).enter().append("svg:path").attr("d", this.pathFunc.bind(this)).attr("class", "mpld3-path").attr("transform", this.transformFunc.bind(this)).attr("style", this.styleFunc.bind(this)).attr("vector-effect", "non-scaling-stroke");
};
mpld3_PathCollection.prototype.elements = function(d) {
return this.group.selectAll("path");
};
mpld3.Line = mpld3_Line;
mpld3_Line.prototype = Object.create(mpld3_Path.prototype);
mpld3_Line.prototype.constructor = mpld3_Line;
mpld3_Line.prototype.requiredProps = [ "data" ];
mpld3_Line.prototype.defaultProps = {
xindex: 0,
yindex: 1,
coordinates: "data",
color: "salmon",
linewidth: 2,
dasharray: "none",
alpha: 1,
zorder: 2,
drawstyle: "none"
};
function mpld3_Line(ax, props) {
mpld3_PlotElement.call(this, ax, props);
var pathProps = this.props;
pathProps.facecolor = "none";
pathProps.edgecolor = pathProps.color;
delete pathProps.color;
pathProps.edgewidth = pathProps.linewidth;
delete pathProps.linewidth;
const drawstyle = pathProps.drawstyle;
delete pathProps.drawstyle;
this.defaultProps = mpld3_Path.prototype.defaultProps;
mpld3_Path.call(this, ax, pathProps);
switch (drawstyle) {
case "steps":
case "steps-pre":
this.datafunc = d3.line().curve(d3.curveStepBefore);
break;
case "steps-post":
this.datafunc = d3.line().curve(d3.curveStepAfter);
break;
case "steps-mid":
this.datafunc = d3.line().curve(d3.curveStep);
break;
default:
this.datafunc = d3.line().curve(d3.curveLinear);
}
}
mpld3.Markers = mpld3_Markers;
mpld3_Markers.prototype = Object.create(mpld3_PathCollection.prototype);
mpld3_Markers.prototype.constructor = mpld3_Markers;
mpld3_Markers.prototype.requiredProps = [ "data" ];
mpld3_Markers.prototype.defaultProps = {
xindex: 0,
yindex: 1,
coordinates: "data",
facecolor: "salmon",
edgecolor: "black",
edgewidth: 1,
alpha: 1,
markersize: 6,
markername: "circle",
drawstyle: "none",
markerpath: null,
zorder: 3
};
function mpld3_Markers(ax, props) {
mpld3_PlotElement.call(this, ax, props);
if (this.props.markerpath !== null) {
this.marker = this.props.markerpath[0].length == 0 ? null : mpld3.path().call(this.props.markerpath[0], this.props.markerpath[1]);
} else {
this.marker = this.props.markername === null ? null : d3.symbol(this.props.markername).size(Math.pow(this.props.markersize, 2))();
}
var PCprops = {
paths: [ this.props.markerpath ],
offsets: ax.fig.parse_offsets(ax.fig.get_data(this.props.data, true)),
xindex: this.props.xindex,
yindex: this.props.yindex,
offsetcoordinates: this.props.coordinates,
edgecolors: [ this.props.edgecolor ],
edgewidths: [ this.props.edgewidth ],
facecolors: [ this.props.facecolor ],
alphas: [ this.props.alpha ],
zorder: this.props.zorder,
id: this.props.id
};
this.requiredProps = mpld3_PathCollection.prototype.requiredProps;
this.defaultProps = mpld3_PathCollection.prototype.defaultProps;
mpld3_PathCollection.call(this, ax, PCprops);
}
mpld3_Markers.prototype.pathFunc = function(d, i) {
return this.marker;
};
mpld3.Image = mpld3_Image;
mpld3_Image.prototype = Object.create(mpld3_PlotElement.prototype);
mpld3_Image.prototype.constructor = mpld3_Image;
mpld3_Image.prototype.requiredProps = [ "data", "extent" ];
mpld3_Image.prototype.defaultProps = {
alpha: 1,
coordinates: "data",
drawstyle: "none",
zorder: 1
};
function mpld3_Image(ax, props) {
mpld3_PlotElement.call(this, ax, props);
this.coords = new mpld3_Coordinates(this.props.coordinates, this.ax);
}
mpld3_Image.prototype.draw = function() {
this.image = this.ax.paths.append("svg:image");
this.image = this.image.attr("class", "mpld3-image").attr("xlink:href", "data:image/png;base64," + this.props.data).style("opacity", this.props.alpha).attr("preserveAspectRatio", "none");
this.updateDimensions();
};
mpld3_Image.prototype.elements = function(d) {
return d3.select(this.image);
};
mpld3_Image.prototype.updateDimensions = function() {
var extent = this.props.extent;
this.image.attr("x", this.coords.x(extent[0])).attr("y", this.coords.y(extent[3])).attr("width", this.coords.x(extent[1]) - this.coords.x(extent[0])).attr("height", this.coords.y(extent[2]) - this.coords.y(extent[3]));
};
mpld3.Text = mpld3_Text;
mpld3_Text.prototype = Object.create(mpld3_PlotElement.prototype);
mpld3_Text.prototype.constructor = mpld3_Text;
mpld3_Text.prototype.requiredProps = [ "text", "position" ];
mpld3_Text.prototype.defaultProps = {
coordinates: "data",
h_anchor: "start",
v_baseline: "auto",
rotation: 0,
fontsize: 11,
drawstyle: "none",
color: "black",
alpha: 1,
zorder: 3
};
function mpld3_Text(ax, props) {
mpld3_PlotElement.call(this, ax, props);
this.text = this.props.text;
this.position = this.props.position;
this.coords = new mpld3_Coordinates(this.props.coordinates, this.ax);
}
mpld3_Text.prototype.draw = function() {
if (this.props.coordinates == "data") {
if (this.coords.zoomable) {
this.obj = this.ax.paths.append("text");
} else {
this.obj = this.ax.staticPaths.append("text");
}
} else {
this.obj = this.ax.baseaxes.append("text");
}
this.obj.attr("class", "mpld3-text").text(this.text).style("text-anchor", this.props.h_anchor).style("dominant-baseline", this.props.v_baseline).style("font-size", this.props.fontsize).style("fill", this.props.color).style("opacity", this.props.alpha);
this.applyTransform();
};
mpld3_Text.prototype.elements = function(d) {
return d3.select(this.obj);
};
mpld3_Text.prototype.applyTransform = function() {
var pos = this.coords.xy(this.position);
this.obj.attr("x", pos[0]).attr("y", pos[1]);
if (this.props.rotation) this.obj.attr("transform", "rotate(" + this.props.rotation + "," + pos + ")");
};
mpld3.Axes = mpld3_Axes;
mpld3_Axes.prototype = Object.create(mpld3_PlotElement.prototype);
mpld3_Axes.prototype.constructor = mpld3_Axes;
mpld3_Axes.prototype.requiredProps = [ "xlim", "ylim" ];
mpld3_Axes.prototype.defaultProps = {
bbox: [ .1, .1, .8, .8 ],
axesbg: "#FFFFFF",
axesbgalpha: 1,
gridOn: false,
xdomain: null,
ydomain: null,
xscale: "linear",
yscale: "linear",
zoomable: true,
axes: [ {
position: "left"
}, {
position: "bottom"
} ],
lines: [],
paths: [],
markers: [],
texts: [],
collections: [],
sharex: [],
sharey: [],
images: []
};
function mpld3_Axes(fig, props) {
mpld3_PlotElement.call(this, fig, props);
this.axnum = this.fig.axes.length;
this.axid = this.fig.figid + "_ax" + (this.axnum + 1);
this.clipid = this.axid + "_clip";
this.props.xdomain = this.props.xdomain || this.props.xlim;
this.props.ydomain = this.props.ydomain || this.props.ylim;
this.sharex = [];
this.sharey = [];
this.elements = [];
this.axisList = [];
var bbox = this.props.bbox;
this.position = [ bbox[0] * this.fig.width, (1 - bbox[1] - bbox[3]) * this.fig.height ];
this.width = bbox[2] * this.fig.width;
this.height = bbox[3] * this.fig.height;
this.isZoomEnabled = null;
this.zoom = null;
this.lastTransform = d3.zoomIdentity;
this.isBoxzoomEnabled = null;
this.isLinkedBrushEnabled = null;
this.isCurrentLinkedBrushTarget = false;
this.brushG = null;
function buildDate(d) {
return new Date(d[0], d[1], d[2], d[3], d[4], d[5]);
}
function setDomain(scale, domain) {
return scale !== "date" ? domain : [ buildDate(domain[0]), buildDate(domain[1]) ];
}
this.props.xdomain = setDomain(this.props.xscale, this.props.xdomain);
this.props.ydomain = setDomain(this.props.yscale, this.props.ydomain);
function build_scale(scale, domain, range) {
var dom = scale === "date" ? d3.scaleTime() : scale === "log" ? d3.scaleLog() : d3.scaleLinear();
return dom.domain(domain).range(range);
}
this.x = this.xdom = build_scale(this.props.xscale, this.props.xdomain, [ 0, this.width ]);
this.y = this.ydom = build_scale(this.props.yscale, this.props.ydomain, [ this.height, 0 ]);
if (this.props.xscale === "date") {
this.x = mpld3.multiscale(d3.scaleLinear().domain(this.props.xlim).range(this.props.xdomain.map(Number)), this.xdom);
}
if (this.props.yscale === "date") {
this.y = mpld3.multiscale(d3.scaleLinear().domain(this.props.ylim).range(this.props.ydomain.map(Number)), this.ydom);
}
var axes = this.props.axes;
for (var i = 0; i < axes.length; i++) {
var axis = new mpld3.Axis(this, axes[i]);
this.axisList.push(axis);
this.elements.push(axis);
if (this.props.gridOn || axis.props.grid.gridOn) {
this.elements.push(axis.getGrid());
}
}
var paths = this.props.paths;
for (var i = 0; i < paths.length; i++) {
this.elements.push(new mpld3.Path(this, paths[i]));
}
var lines = this.props.lines;
for (var i = 0; i < lines.length; i++) {
this.elements.push(new mpld3.Line(this, lines[i]));
}
var markers = this.props.markers;
for (var i = 0; i < markers.length; i++) {
this.elements.push(new mpld3.Markers(this, markers[i]));
}
var texts = this.props.texts;
for (var i = 0; i < texts.length; i++) {
this.elements.push(new mpld3.Text(this, texts[i]));
}
var collections = this.props.collections;
for (var i = 0; i < collections.length; i++) {
this.elements.push(new mpld3.PathCollection(this, collections[i]));
}
var images = this.props.images;
for (var i = 0; i < images.length; i++) {
this.elements.push(new mpld3.Image(this, images[i]));
}
this.elements.sort(function(a, b) {
return a.props.zorder - b.props.zorder;
});
}
mpld3_Axes.prototype.draw = function() {
for (var i = 0; i < this.props.sharex.length; i++) {
this.sharex.push(mpld3.get_element(this.props.sharex[i]));
}
for (var i = 0; i < this.props.sharey.length; i++) {
this.sharey.push(mpld3.get_element(this.props.sharey[i]));
}
this.baseaxes = this.fig.canvas.append("g").attr("transform", "translate(" + this.position[0] + "," + this.position[1] + ")").attr("width", this.width).attr("height", this.height).attr("class", "mpld3-baseaxes");
this.axes = this.baseaxes.append("g").attr("class", "mpld3-axes").style("pointer-events", "visiblefill");
this.clip = this.axes.append("svg:clipPath").attr("id", this.clipid).append("svg:rect").attr("x", 0).attr("y", 0).attr("width", this.width).attr("height", this.height);
this.axesbg = this.axes.append("svg:rect").attr("width", this.width).attr("height", this.height).attr("class", "mpld3-axesbg").style("fill", this.props.axesbg).style("fill-opacity", this.props.axesbgalpha);
this.pathsContainer = this.axes.append("g").attr("clip-path", "url(#" + this.clipid + ")").attr("x", 0).attr("y", 0).attr("width", this.width).attr("height", this.height).attr("class", "mpld3-paths-container");
this.paths = this.pathsContainer.append("g").attr("class", "mpld3-paths");
this.staticPaths = this.axes.append("g").attr("class", "mpld3-staticpaths");
this.brush = d3.brush().extent([ [ 0, 0 ], [ this.fig.width, this.fig.height ] ]).on("start", this.brushStart.bind(this)).on("brush", this.brushMove.bind(this)).on("end", this.brushEnd.bind(this)).on("start.nokey", function() {
d3.select(window).on("keydown.brush keyup.brush", null);
});
for (var i = 0; i < this.elements.length; i++) {
this.elements[i].draw();
}
};
mpld3_Axes.prototype.bindZoom = function() {
if (!this.zoom) {
this.zoom = d3.zoom();
this.zoom.on("zoom", this.zoomed.bind(this));
this.axes.call(this.zoom);
}
};
mpld3_Axes.prototype.unbindZoom = function() {
if (this.zoom) {
this.zoom.on("zoom", null);
this.axes.on(".zoom", null);
this.zoom = null;
}
};
mpld3_Axes.prototype.bindBrush = function() {
if (!this.brushG) {
this.brushG = this.axes.append("g").attr("class", "mpld3-brush").call(this.brush);
}
};
mpld3_Axes.prototype.unbindBrush = function() {
if (this.brushG) {
this.brushG.remove();
this.brushG.on(".brush", null);
this.brushG = null;
}
};
mpld3_Axes.prototype.reset = function() {
if (this.zoom) {
this.doZoom(false, d3.zoomIdentity, 750);
} else {
this.bindZoom();
this.doZoom(false, d3.zoomIdentity, 750, function() {
if (this.isSomeTypeOfZoomEnabled) {
return;
}
this.unbindZoom();
}.bind(this));
}
};
mpld3_Axes.prototype.enableOrDisableBrushing = function() {
if (this.isBoxzoomEnabled || this.isLinkedBrushEnabled) {
this.bindBrush();
} else {
this.unbindBrush();
}
};
mpld3_Axes.prototype.isSomeTypeOfZoomEnabled = function() {
return this.isZoomEnabled || this.isBoxzoomEnabled;
};
mpld3_Axes.prototype.enableOrDisableZooming = function() {
if (this.isSomeTypeOfZoomEnabled()) {
this.bindZoom();
} else {
this.unbindZoom();
}
};
mpld3_Axes.prototype.enableLinkedBrush = function() {
this.isLinkedBrushEnabled = true;
this.enableOrDisableBrushing();
};
mpld3_Axes.prototype.disableLinkedBrush = function() {
this.isLinkedBrushEnabled = false;
this.enableOrDisableBrushing();
};
mpld3_Axes.prototype.enableBoxzoom = function() {
this.isBoxzoomEnabled = true;
this.enableOrDisableBrushing();
this.enableOrDisableZooming();
};
mpld3_Axes.prototype.disableBoxzoom = function() {
this.isBoxzoomEnabled = false;
this.enableOrDisableBrushing();
this.enableOrDisableZooming();
};
mpld3_Axes.prototype.enableZoom = function() {
this.isZoomEnabled = true;
this.enableOrDisableZooming();
this.axes.style("cursor", "move");
};
mpld3_Axes.prototype.disableZoom = function() {
this.isZoomEnabled = false;
this.enableOrDisableZooming();
this.axes.style("cursor", null);
};
mpld3_Axes.prototype.doZoom = function(propagate, transform, duration, onTransitionEnd) {
if (!this.props.zoomable || !this.zoom) {
return;
}
if (duration) {
var transition = this.axes.transition().duration(duration).call(this.zoom.transform, transform);
if (onTransitionEnd) {
transition.on("end", onTransitionEnd);
}
} else {
this.axes.call(this.zoom.transform, transform);
}
if (propagate) {
this.lastTransform = transform;
this.sharex.forEach(function(sharedAxes) {
sharedAxes.doZoom(false, transform, duration);
});
this.sharey.forEach(function(sharedAxes) {
sharedAxes.doZoom(false, transform, duration);
});
} else {
this.lastTransform = transform;
}
};
mpld3_Axes.prototype.zoomed = function() {
var isProgrammatic = d3.event.sourceEvent && d3.event.sourceEvent.type != "zoom";
if (isProgrammatic) {
this.doZoom(true, d3.event.transform, false);
} else {
var transform = d3.event.transform;
this.paths.attr("transform", transform);
this.elements.forEach(function(element) {
if (element.zoomed) {
element.zoomed(transform);
}
}.bind(this));
}
};
mpld3_Axes.prototype.resetBrush = function() {
this.brushG.call(this.brush.move, null);
};
mpld3_Axes.prototype.doBoxzoom = function(selection) {
if (!selection || !this.brushG) {
return;
}
var sel = selection.map(this.lastTransform.invert, this.lastTransform);
var dx = sel[1][0] - sel[0][0];
var dy = sel[1][1] - sel[0][1];
var cx = (sel[0][0] + sel[1][0]) / 2;
var cy = (sel[0][1] + sel[1][1]) / 2;
var scale = dx > dy ? this.width / dx : this.height / dy;
var transX = this.width / 2 - scale * cx;
var transY = this.height / 2 - scale * cy;
var transform = d3.zoomIdentity.translate(transX, transY).scale(scale);
this.doZoom(true, transform, 750);
this.resetBrush();
};
mpld3_Axes.prototype.brushStart = function() {
if (this.isLinkedBrushEnabled) {
this.isCurrentLinkedBrushTarget = d3.event.sourceEvent.constructor.name == "MouseEvent";
if (this.isCurrentLinkedBrushTarget) {
this.fig.resetBrushForOtherAxes(this.axid);
}
}
};
mpld3_Axes.prototype.brushMove = function() {
var selection = d3.event.selection;
if (this.isLinkedBrushEnabled) {
this.fig.updateLinkedBrush(selection);
}
};
mpld3_Axes.prototype.brushEnd = function() {
var selection = d3.event.selection;
if (this.isBoxzoomEnabled) {
this.doBoxzoom(selection);
}
if (this.isLinkedBrushEnabled) {
if (!selection) {
this.fig.endLinkedBrush();
}
this.isCurrentLinkedBrushTarget = false;
}
};
mpld3_Axes.prototype.setTicks = function(xy, nr, format) {
this.axisList.forEach(function(axis) {
if (axis.props.xy == xy) {
axis.setTicks(nr, format);
}
});
};
mpld3.Toolbar = mpld3_Toolbar;
mpld3_Toolbar.prototype = Object.create(mpld3_PlotElement.prototype);
mpld3_Toolbar.prototype.constructor = mpld3_Toolbar;
mpld3_Toolbar.prototype.defaultProps = {
buttons: [ "reset", "move" ]
};
function mpld3_Toolbar(fig, props) {
mpld3_PlotElement.call(this, fig, props);
this.buttons = [];
this.props.buttons.forEach(this.addButton.bind(this));
}
mpld3_Toolbar.prototype.addButton = function(button) {
this.buttons.push(new button(this));
};
mpld3_Toolbar.prototype.draw = function() {
mpld3.insert_css("div#" + this.fig.figid + " .mpld3-toolbar image", {
cursor: "pointer",
opacity: .2,
display: "inline-block",
margin: "0px"
});
mpld3.insert_css("div#" + this.fig.figid + " .mpld3-toolbar image.active", {
opacity: .4
});
mpld3.insert_css("div#" + this.fig.figid + " .mpld3-toolbar image.pressed", {
opacity: .6
});
function showButtons() {
this.buttonsobj.transition(750).attr("y", 0);
}
function hideButtons() {
this.buttonsobj.transition(750).delay(250).attr("y", 16);
}
this.fig.canvas.on("mouseenter", showButtons.bind(this)).on("mouseleave", hideButtons.bind(this)).on("touchenter", showButtons.bind(this)).on("touchstart", showButtons.bind(this));
this.toolbar = this.fig.canvas.append("svg:svg").attr("width", 16 * this.buttons.length).attr("height", 16).attr("x", 2).attr("y", this.fig.height - 16 - 2).attr("class", "mpld3-toolbar");
this.buttonsobj = this.toolbar.append("svg:g").selectAll("buttons").data(this.buttons).enter().append("svg:image").attr("class", function(d) {
return d.cssclass;
}).attr("xlink:href", function(d) {
return d.icon();
}).attr("width", 16).attr("height", 16).attr("x", function(d, i) {
return i * 16;
}).attr("y", 16).on("click", function(d) {
d.click();
}).on("mouseenter", function() {
d3.select(this).classed("active", true);
}).on("mouseleave", function() {
d3.select(this).classed("active", false);
});
for (var i = 0; i < this.buttons.length; i++) this.buttons[i].onDraw();
};
mpld3_Toolbar.prototype.deactivate_all = function() {
this.buttons.forEach(function(b) {
b.deactivate();
});
};
mpld3_Toolbar.prototype.deactivate_by_action = function(actions) {
function filt(e) {
return actions.indexOf(e) !== -1;
}
if (actions.length > 0) {
this.buttons.forEach(function(button) {
if (button.actions.filter(filt).length > 0) button.deactivate();
});
}
};
mpld3.Button = mpld3_Button;
mpld3_Button.prototype = Object.create(mpld3_PlotElement.prototype);
mpld3_Button.prototype.constructor = mpld3_Button;
function mpld3_Button(toolbar, key) {
mpld3_PlotElement.call(this, toolbar);
this.toolbar = toolbar;
this.fig = this.toolbar.fig;
this.cssclass = "mpld3-" + key + "button";
this.active = false;
}
mpld3_Button.prototype.setState = function(state) {
state ? this.activate() : this.deactivate();
};
mpld3_Button.prototype.click = function() {
this.active ? this.deactivate() : this.activate();
};
mpld3_Button.prototype.activate = function() {
this.toolbar.deactivate_by_action(this.actions);
this.onActivate();
this.active = true;
this.toolbar.toolbar.select("." + this.cssclass).classed("pressed", true);
if (!this.sticky) {
this.deactivate();
}
};
mpld3_Button.prototype.deactivate = function() {
this.onDeactivate();
this.active = false;
this.toolbar.toolbar.select("." + this.cssclass).classed("pressed", false);
};
mpld3_Button.prototype.sticky = false;
mpld3_Button.prototype.actions = [];
mpld3_Button.prototype.icon = function() {
return "";
};
mpld3_Button.prototype.onActivate = function() {};
mpld3_Button.prototype.onDeactivate = function() {};
mpld3_Button.prototype.onDraw = function() {};
mpld3.ButtonFactory = function(members) {
if (typeof members.buttonID !== "string") {
throw "ButtonFactory: buttonID must be present and be a string";
}
function B(toolbar) {
mpld3_Button.call(this, toolbar, this.buttonID);
}
B.prototype = Object.create(mpld3_Button.prototype);
B.prototype.constructor = B;
for (var key in members) {
B.prototype[key] = members[key];
}
return B;
};
mpld3.Plugin = mpld3_Plugin;
mpld3_Plugin.prototype = Object.create(mpld3_PlotElement.prototype);
mpld3_Plugin.prototype.constructor = mpld3_Plugin;
mpld3_Plugin.prototype.requiredProps = [];
mpld3_Plugin.prototype.defaultProps = {};
function mpld3_Plugin(fig, props) {
mpld3_PlotElement.call(this, fig, props);
}
mpld3_Plugin.prototype.draw = function() {};
mpld3.ResetPlugin = mpld3_ResetPlugin;
mpld3.register_plugin("reset", mpld3_ResetPlugin);
mpld3_ResetPlugin.prototype = Object.create(mpld3_Plugin.prototype);
mpld3_ResetPlugin.prototype.constructor = mpld3_ResetPlugin;
mpld3_ResetPlugin.prototype.requiredProps = [];
mpld3_ResetPlugin.prototype.defaultProps = {};
function mpld3_ResetPlugin(fig, props) {
mpld3_Plugin.call(this, fig, props);
var ResetButton = mpld3.ButtonFactory({
buttonID: "reset",
sticky: false,
onActivate: function() {
this.toolbar.fig.reset();
},
icon: function() {
return mpld3.icons["reset"];
}
});
this.fig.buttons.push(ResetButton);
}
mpld3.ZoomPlugin = mpld3_ZoomPlugin;
mpld3.register_plugin("zoom", mpld3_ZoomPlugin);
mpld3_ZoomPlugin.prototype = Object.create(mpld3_Plugin.prototype);
mpld3_ZoomPlugin.prototype.constructor = mpld3_ZoomPlugin;
mpld3_ZoomPlugin.prototype.requiredProps = [];
mpld3_ZoomPlugin.prototype.defaultProps = {
button: true,
enabled: null
};
function mpld3_ZoomPlugin(fig, props) {
mpld3_Plugin.call(this, fig, props);
if (this.props.enabled === null) {
this.props.enabled = !this.props.button;
}
var enabled = this.props.enabled;
if (this.props.button) {
var ZoomButton = mpld3.ButtonFactory({
buttonID: "zoom",
sticky: true,
actions: [ "scroll", "drag" ],
onActivate: this.activate.bind(this),
onDeactivate: this.deactivate.bind(this),
onDraw: function() {
this.setState(enabled);
},
icon: function() {
return mpld3.icons["move"];
}
});
this.fig.buttons.push(ZoomButton);
}
}
mpld3_ZoomPlugin.prototype.activate = function() {
this.fig.enableZoom();
};
mpld3_ZoomPlugin.prototype.deactivate = function() {
this.fig.disableZoom();
};
mpld3_ZoomPlugin.prototype.draw = function() {
if (this.props.enabled) {
this.activate();
} else {
this.deactivate();
}
};
mpld3.BoxZoomPlugin = mpld3_BoxZoomPlugin;
mpld3.register_plugin("boxzoom", mpld3_BoxZoomPlugin);
mpld3_BoxZoomPlugin.prototype = Object.create(mpld3_Plugin.prototype);
mpld3_BoxZoomPlugin.prototype.constructor = mpld3_BoxZoomPlugin;
mpld3_BoxZoomPlugin.prototype.requiredProps = [];
mpld3_BoxZoomPlugin.prototype.defaultProps = {
button: true,
enabled: null
};
function mpld3_BoxZoomPlugin(fig, props) {
mpld3_Plugin.call(this, fig, props);
if (this.props.enabled === null) {
this.props.enabled = !this.props.button;
}
var enabled = this.props.enabled;
if (this.props.button) {
var BoxZoomButton = mpld3.ButtonFactory({
buttonID: "boxzoom",
sticky: true,
actions: [ "drag" ],
onActivate: this.activate.bind(this),
onDeactivate: this.deactivate.bind(this),
onDraw: function() {
this.setState(enabled);
},
icon: function() {
return mpld3.icons["zoom"];
}
});
this.fig.buttons.push(BoxZoomButton);
}
this.extentClass = "boxzoombrush";
}
mpld3_BoxZoomPlugin.prototype.activate = function() {
this.fig.enableBoxzoom();
};
mpld3_BoxZoomPlugin.prototype.deactivate = function() {
this.fig.disableBoxzoom();
};
mpld3_BoxZoomPlugin.prototype.draw = function() {
if (this.props.enabled) {
this.activate();
} else {
this.deactivate();
}
};
mpld3.TooltipPlugin = mpld3_TooltipPlugin;
mpld3.register_plugin("tooltip", mpld3_TooltipPlugin);
mpld3_TooltipPlugin.prototype = Object.create(mpld3_Plugin.prototype);
mpld3_TooltipPlugin.prototype.constructor = mpld3_TooltipPlugin;
mpld3_TooltipPlugin.prototype.requiredProps = [ "id" ];
mpld3_TooltipPlugin.prototype.defaultProps = {
labels: null,
hoffset: 0,
voffset: 10,
location: "mouse"
};
function mpld3_TooltipPlugin(fig, props) {
mpld3_Plugin.call(this, fig, props);
}
mpld3_TooltipPlugin.prototype.draw = function() {
var obj = mpld3.get_element(this.props.id, this.fig);
var labels = this.props.labels;
var loc = this.props.location;
this.tooltip = this.fig.canvas.append("text").attr("class", "mpld3-tooltip-text").attr("x", 0).attr("y", 0).text("").style("visibility", "hidden");
if (loc == "bottom left" || loc == "top left") {
this.x = obj.ax.position[0] + 5 + this.props.hoffset;
this.tooltip.style("text-anchor", "beginning");
} else if (loc == "bottom right" || loc == "top right") {
this.x = obj.ax.position[0] + obj.ax.width - 5 + this.props.hoffset;
this.tooltip.style("text-anchor", "end");
} else {
this.tooltip.style("text-anchor", "middle");
}
if (loc == "bottom left" || loc == "bottom right") {
this.y = obj.ax.position[1] + obj.ax.height - 5 + this.props.voffset;
} else if (loc == "top left" || loc == "top right") {
this.y = obj.ax.position[1] + 5 + this.props.voffset;
}
function mouseover(d, i) {
this.tooltip.style("visibility", "visible").text(labels === null ? "(" + d + ")" : getMod(labels, i));
}
function mousemove(d, i) {
if (loc === "mouse") {
var pos = d3.mouse(this.fig.canvas.node());
this.x = pos[0] + this.props.hoffset;
this.y = pos[1] - this.props.voffset;
}
this.tooltip.attr("x", this.x).attr("y", this.y);
}
function mouseout(d, i) {
this.tooltip.style("visibility", "hidden");
}
obj.elements().on("mouseover", mouseover.bind(this)).on("mousemove", mousemove.bind(this)).on("mouseout", mouseout.bind(this));
};
mpld3.LinkedBrushPlugin = mpld3_LinkedBrushPlugin;
mpld3.register_plugin("linkedbrush", mpld3_LinkedBrushPlugin);
mpld3_LinkedBrushPlugin.prototype = Object.create(mpld3.Plugin.prototype);
mpld3_LinkedBrushPlugin.prototype.constructor = mpld3_LinkedBrushPlugin;
mpld3_LinkedBrushPlugin.prototype.requiredProps = [ "id" ];
mpld3_LinkedBrushPlugin.prototype.defaultProps = {
button: true,
enabled: null
};
function mpld3_LinkedBrushPlugin(fig, props) {
mpld3.Plugin.call(this, fig, props);
if (this.props.enabled === null) {
this.props.enabled = !this.props.button;
}
var enabled = this.props.enabled;
if (this.props.button) {
var BrushButton = mpld3.ButtonFactory({
buttonID: "linkedbrush",
sticky: true,
actions: [ "drag" ],
onActivate: this.activate.bind(this),
onDeactivate: this.deactivate.bind(this),
onDraw: function() {
this.setState(enabled);
},
icon: function() {
return mpld3.icons["brush"];
}
});
this.fig.buttons.push(BrushButton);
}
this.pathCollectionsByAxes = [];
this.objectsByAxes = [];
this.allObjects = [];
this.extentClass = "linkedbrush";
this.dataKey = "offsets";
this.objectClass = null;
}
mpld3_LinkedBrushPlugin.prototype.activate = function() {
this.fig.enableLinkedBrush();
};
mpld3_LinkedBrushPlugin.prototype.deactivate = function() {
this.fig.disableLinkedBrush();
};
mpld3_LinkedBrushPlugin.prototype.isPathInSelection = function(path, ix, iy, sel) {
var result = sel[0][0] < path[ix] && sel[1][0] > path[ix] && sel[0][1] < path[iy] && sel[1][1] > path[iy];
return result;
};
mpld3_LinkedBrushPlugin.prototype.invertSelection = function(sel, axes) {
var xs = [ axes.x.invert(sel[0][0]), axes.x.invert(sel[1][0]) ];
var ys = [ axes.y.invert(sel[1][1]), axes.y.invert(sel[0][1]) ];
return [ [ Math.min.apply(Math, xs), Math.min.apply(Math, ys) ], [ Math.max.apply(Math, xs), Math.max.apply(Math, ys) ] ];
};
mpld3_LinkedBrushPlugin.prototype.update = function(selection) {
if (!selection) {
return;
}
this.pathCollectionsByAxes.forEach(function(axesColls, axesIndex) {
var pathCollection = axesColls[0];
var objects = this.objectsByAxes[axesIndex];
var invertedSelection = this.invertSelection(selection, this.fig.axes[axesIndex]);
var ix = pathCollection.props.xindex;
var iy = pathCollection.props.yindex;
objects.selectAll("path").classed("mpld3-hidden", function(path, idx) {
return !this.isPathInSelection(path, ix, iy, invertedSelection);
}.bind(this));
}.bind(this));
};
mpld3_LinkedBrushPlugin.prototype.end = function() {
this.allObjects.selectAll("path").classed("mpld3-hidden", false);
};
mpld3_LinkedBrushPlugin.prototype.draw = function() {
mpld3.insert_css("#" + this.fig.figid + " path.mpld3-hidden", {
stroke: "#ccc !important",
fill: "#ccc !important"
});
var pathCollection = mpld3.get_element(this.props.id);
if (!pathCollection) {
throw new Error("[LinkedBrush] Could not find path collection");
}
if (!("offsets" in pathCollection.props)) {
throw new Error("[LinkedBrush] Figure is not a scatter plot.");
}
this.objectClass = "mpld3-brushtarget-" + pathCollection.props[this.dataKey];
this.pathCollectionsByAxes = this.fig.axes.map(function(axes) {
return axes.elements.map(function(el) {
if (el.props[this.dataKey] == pathCollection.props[this.dataKey]) {
el.group.classed(this.objectClass, true);
return el;
}
}.bind(this)).filter(function(d) {
return d;
});
}.bind(this));
this.objectsByAxes = this.fig.axes.map(function(axes) {
return axes.axes.selectAll("." + this.objectClass);
}.bind(this));
this.allObjects = this.fig.canvas.selectAll("." + this.objectClass);
};
mpld3.register_plugin("mouseposition", MousePositionPlugin);
MousePositionPlugin.prototype = Object.create(mpld3.Plugin.prototype);
MousePositionPlugin.prototype.constructor = MousePositionPlugin;
MousePositionPlugin.prototype.requiredProps = [];
MousePositionPlugin.prototype.defaultProps = {
fontsize: 12,
fmt: ".3g"
};
function MousePositionPlugin(fig, props) {
mpld3.Plugin.call(this, fig, props);
}
MousePositionPlugin.prototype.draw = function() {
var fig = this.fig;
var fmt = d3.format(this.props.fmt);
var coords = fig.canvas.append("text").attr("class", "mpld3-coordinates").style("text-anchor", "end").style("font-size", this.props.fontsize).attr("x", this.fig.width - 5).attr("y", this.fig.height - 5);
for (var i = 0; i < this.fig.axes.length; i++) {
var update_coords = function() {
var ax = fig.axes[i];
return function() {
var pos = d3.mouse(this), x = ax.x.invert(pos[0]), y = ax.y.invert(pos[1]);
coords.text("(" + fmt(x) + ", " + fmt(y) + ")");
};
}();
fig.axes[i].baseaxes.on("mousemove", update_coords).on("mouseout", function() {
coords.text("");
});
}
};
mpld3.Figure = mpld3_Figure;
mpld3_Figure.prototype = Object.create(mpld3_PlotElement.prototype);
mpld3_Figure.prototype.constructor = mpld3_Figure;
mpld3_Figure.prototype.requiredProps = [ "width", "height" ];
mpld3_Figure.prototype.defaultProps = {
data: {},
axes: [],
plugins: [ {
type: "reset"
}, {
type: "zoom"
}, {
type: "boxzoom"
} ]
};
function mpld3_Figure(figid, props) {
mpld3_PlotElement.call(this, null, props);
this.figid = figid;
this.width = this.props.width;
this.height = this.props.height;
this.data = this.props.data;
this.buttons = [];
this.root = d3.select("#" + figid).append("div").style("position", "relative");
this.axes = [];
for (var i = 0; i < this.props.axes.length; i++) this.axes.push(new mpld3_Axes(this, this.props.axes[i]));
this.plugins = [];
this.pluginsByType = {};
this.props.plugins.forEach(function(plugin) {
this.addPlugin(plugin);
}.bind(this));
this.toolbar = new mpld3.Toolbar(this, {
buttons: this.buttons
});
}
mpld3_Figure.prototype.addPlugin = function(pluginInfo) {
if (!pluginInfo.type) {
return console.warn("unspecified plugin type. Skipping this");
}
var plugin;
if (pluginInfo.type in mpld3.plugin_map) {
plugin = mpld3.plugin_map[pluginInfo.type];
} else {
return console.warn("Skipping unrecognized plugin: " + plugin);
}
if (pluginInfo.clear_toolbar || pluginInfo.buttons) {
console.warn("DEPRECATION WARNING: " + "You are using pluginInfo.clear_toolbar or pluginInfo, which " + "have been deprecated. Please see the build-in plugins for the new " + "method to add buttons, otherwise contact the mpld3 maintainers.");
}
var pluginInfoNoType = mpld3_cloneObj(pluginInfo);
delete pluginInfoNoType.type;
var pluginInstance = new plugin(this, pluginInfoNoType);
this.plugins.push(pluginInstance);
this.pluginsByType[pluginInfo.type] = pluginInstance;
};
mpld3_Figure.prototype.draw = function() {
mpld3.insert_css("div#" + this.figid, {
"font-family": "Helvetica, sans-serif"
});
this.canvas = this.root.append("svg:svg").attr("class", "mpld3-figure").attr("width", this.width).attr("height", this.height);
for (var i = 0; i < this.axes.length; i++) {
this.axes[i].draw();
}
this.disableZoom();
for (var i = 0; i < this.plugins.length; i++) {
this.plugins[i].draw();
}
this.toolbar.draw();
};
mpld3_Figure.prototype.resetBrushForOtherAxes = function(currentAxid) {
this.axes.forEach(function(axes) {
if (axes.axid != currentAxid) {
axes.resetBrush();
}
});
};
mpld3_Figure.prototype.updateLinkedBrush = function(selection) {
if (!this.pluginsByType.linkedbrush) {
return;
}
this.pluginsByType.linkedbrush.update(selection);
};
mpld3_Figure.prototype.endLinkedBrush = function() {
if (!this.pluginsByType.linkedbrush) {
return;
}
this.pluginsByType.linkedbrush.end();
};
mpld3_Figure.prototype.reset = function(duration) {
this.axes.forEach(function(axes) {
axes.reset();
});
};
mpld3_Figure.prototype.enableLinkedBrush = function() {
this.axes.forEach(function(axes) {
axes.enableLinkedBrush();
});
};
mpld3_Figure.prototype.disableLinkedBrush = function() {
this.axes.forEach(function(axes) {
axes.disableLinkedBrush();
});
};
mpld3_Figure.prototype.enableBoxzoom = function() {
this.axes.forEach(function(axes) {
axes.enableBoxzoom();
});
};
mpld3_Figure.prototype.disableBoxzoom = function() {
this.axes.forEach(function(axes) {
axes.disableBoxzoom();
});
};
mpld3_Figure.prototype.enableZoom = function() {
this.axes.forEach(function(axes) {
axes.enableZoom();
});
};
mpld3_Figure.prototype.disableZoom = function() {
this.axes.forEach(function(axes) {
axes.disableZoom();
});
};
mpld3_Figure.prototype.toggleZoom = function() {
if (this.isZoomEnabled) {
this.disableZoom();
} else {
this.enableZoom();
}
};
mpld3_Figure.prototype.setTicks = function(xy, nr, format) {
this.axes.forEach(function(axes) {
axes.setTicks(xy, nr, format);
});
};
mpld3_Figure.prototype.setXTicks = function(nr, format) {
this.setTicks("x", nr, format);
};
mpld3_Figure.prototype.setYTicks = function(nr, format) {
this.setTicks("y", nr, format);
};
mpld3_Figure.prototype.removeNaN = function(data) {
output = output.map(function(offsets) {
return offsets.map(function(value) {
if (typeof value == "number" && isNaN(value)) {
return 0;
} else {
return value;
}
});
});
};
mpld3_Figure.prototype.parse_offsets = function(data) {
return data.map(function(offsets) {
return offsets.map(function(value) {
if (typeof value == "number" && isNaN(value)) {
return 0;
} else {
return value;
}
});
});
};
mpld3_Figure.prototype.get_data = function(data) {
var output = data;
if (data === null || typeof data === "undefined") {
output = null;
} else if (typeof data === "string") {
output = this.data[data];
}
return output;
};
mpld3.PlotElement = mpld3_PlotElement;
function mpld3_PlotElement(parent, props) {
this.parent = isUndefinedOrNull(parent) ? null : parent;
this.props = isUndefinedOrNull(props) ? {} : this.processProps(props);
this.fig = parent instanceof mpld3_Figure ? parent : parent && "fig" in parent ? parent.fig : null;
this.ax = parent instanceof mpld3_Axes ? parent : parent && "ax" in parent ? parent.ax : null;
}
mpld3_PlotElement.prototype.requiredProps = [];
mpld3_PlotElement.prototype.defaultProps = {};
mpld3_PlotElement.prototype.processProps = function(props) {
props = mpld3_cloneObj(props);
var finalProps = {};
var this_name = this.name();
this.requiredProps.forEach(function(p) {
if (!(p in props)) {
throw "property '" + p + "' " + "must be specified for " + this_name;
}
finalProps[p] = props[p];
delete props[p];
});
for (var p in this.defaultProps) {
if (p in props) {
finalProps[p] = props[p];
delete props[p];
} else {
finalProps[p] = this.defaultProps[p];
}
}
if ("id" in props) {
finalProps.id = props.id;
delete props.id;
} else if (!("id" in finalProps)) {
finalProps.id = mpld3.generateId();
}
for (var p in props) {
console.warn("Unrecognized property '" + p + "' " + "for object " + this.name() + " (value = " + props[p] + ").");
}
return finalProps;
};
mpld3_PlotElement.prototype.name = function() {
var funcNameRegex = /function (.{1,})\(/;
var results = funcNameRegex.exec(this.constructor.toString());
return results && results.length > 1 ? results[1] : "";
};
if (typeof module === "object" && module.exports) {
module.exports = mpld3;
} else {
this.mpld3 = mpld3;
}
console.log("Loaded mpld3 version " + mpld3.version);
}(d3); | {
"pile_set_name": "Github"
} |
/**
* Copyright 2015 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@function strip-units($number) {
@return $number / ($number * 0 + 1);
}
| {
"pile_set_name": "Github"
} |
/*
* Copyright (c) Minh Loi.
*
* This file is part of Ulangi which is released under GPL v3.0.
* See LICENSE or go to https://www.gnu.org/licenses/gpl-3.0.txt
*/
import {
ButtonSize,
Theme,
VocabularySortType,
VocabularyStatus,
} from '@ulangi/ulangi-common/enums';
import {
ObservableCategory,
ObservableScreenLayout,
} from '@ulangi/ulangi-observable';
import * as _ from 'lodash';
import { IObservableValue } from 'mobx';
import { observer } from 'mobx-react';
import * as React from 'react';
import { TouchableOpacity, View } from 'react-native';
import { config } from '../../constants/config';
import { CategoryDetailScreenIds } from '../../constants/ids/CategoryDetailScreenIds';
import { fullRoundedButtonStyles } from '../../styles/FullRoundedButtonStyles';
import { DefaultButton } from '../common/DefaultButton';
import { DefaultText } from '../common/DefaultText';
import {
CategoryDetailHeaderStyles,
categoryDetailHeaderResponsiveStyles,
} from './CategoryDetailHeader.style';
export interface CategoryDetailHeaderProps {
theme: Theme;
screenLayout: ObservableScreenLayout;
category: ObservableCategory;
selectedVocabularyStatus: IObservableValue<VocabularyStatus>;
selectedSortType: IObservableValue<VocabularySortType>;
showVocabularySortMenu: () => void;
showVocabularyFilterMenu: () => void;
}
@observer
export class CategoryDetailHeader extends React.Component<
CategoryDetailHeaderProps
> {
private get styles(): CategoryDetailHeaderStyles {
return categoryDetailHeaderResponsiveStyles.compile(
this.props.screenLayout,
this.props.theme,
);
}
public render(): React.ReactElement<any> {
return (
<View style={this.styles.container}>
<TouchableOpacity
testID={CategoryDetailScreenIds.SHOW_VOCABULARY_SORT_MENU_BTN}
onPress={this.props.showVocabularySortMenu}
hitSlop={{ top: 10, bottom: 10, left: 5, right: 5 }}
style={this.styles.button}>
<DefaultText
ellipsizeMode="tail"
numberOfLines={1}
style={this.styles.button_text}>
{_.upperFirst(
config.vocabulary.sortMap[this.props.selectedSortType.get()].name,
)}
</DefaultText>
</TouchableOpacity>
<DefaultButton
testID={CategoryDetailScreenIds.SHOW_VOCABULARY_FILTER_MENU_BTN}
text={_.upperFirst(
config.vocabulary.statusMap[
this.props.selectedVocabularyStatus.get()
].shortName,
)}
onPress={this.props.showVocabularyFilterMenu}
styles={fullRoundedButtonStyles.getOutlineStyles(
ButtonSize.SMALL,
this.getColorByStatus(this.props.selectedVocabularyStatus.get()),
this.props.theme,
this.props.screenLayout,
)}
/>
</View>
);
}
private getColorByStatus(selectedVocabularyStatus: VocabularyStatus): string {
return config.vocabulary.statusMap[selectedVocabularyStatus].textColor;
}
}
| {
"pile_set_name": "Github"
} |
#!/usr/bin/perl
#------------------------------------------------------------------------------
# Copyright and Licence
#------------------------------------------------------------------------------
# CGI-Telnet Version 1.0 for NT and Unix : Run Commands on your Web Server
#
# Copyright (C) 2001 Rohitab Batra
# Permission is granted to use, distribute and modify this script so long
# as this copyright notice is left intact. If you make changes to the script
# please document them and inform me. If you would like any changes to be made
# in this script, you can e-mail me.
#
# Author: Rohitab Batra
# Author e-mail: rohitab@rohitab.com
# Author Homepage: http://www.rohitab.com/
# Script Homepage: http://www.rohitab.com/cgiscripts/cgitelnet.html
# Product Support: http://www.rohitab.com/support/
# Discussion Forum: http://www.rohitab.com/discuss/
# Mailing List: http://www.rohitab.com/mlist/
#------------------------------------------------------------------------------
#------------------------------------------------------------------------------
# Installation
#------------------------------------------------------------------------------
# To install this script
#
# 1. Modify the first line "#!/usr/bin/perl" to point to the correct path on
# your server. For most servers, you may not need to modify this.
# 2. Change the password in the Configuration section below.
# 3. If you're running the script under Windows NT, set $WinNT = 1 in the
# Configuration Section below.
# 4. Upload the script to a directory on your server which has permissions to
# execute CGI scripts. This is usually cgi-bin. Make sure that you upload
# the script in ASCII mode.
# 5. Change the permission (CHMOD) of the script to 755.
# 6. Open the script in your web browser. If you uploaded the script in
# cgi-bin, this should be http://www.yourserver.com/cgi-bin/cgitelnet.pl
# 7. Login using the password that you specified in Step 2.
#------------------------------------------------------------------------------
#------------------------------------------------------------------------------
# Configuration: You need to change only $Password and $WinNT. The other
# values should work fine for most systems.
#------------------------------------------------------------------------------
$Password = ""; # Change this. You will need to enter this
# to login.
$WinNT = 0; # You need to change the value of this to 1 if
# you're running this script on a Windows NT
# machine. If you're running it on Unix, you
# can leave the value as it is.
$NTCmdSep = "&"; # This character is used to seperate 2 commands
# in a command line on Windows NT.
$UnixCmdSep = ";"; # This character is used to seperate 2 commands
# in a command line on Unix.
$CommandTimeoutDuration = 100000; # Time in seconds after commands will be killed
# Don't set this to a very large value. This is
# useful for commands that may hang or that
# take very long to execute, like "find /".
# This is valid only on Unix servers. It is
# ignored on NT Servers.
$ShowDynamicOutput = 1; # If this is 1, then data is sent to the
# browser as soon as it is output, otherwise
# it is buffered and send when the command
# completes. This is useful for commands like
# ping, so that you can see the output as it
# is being generated.
# DON'T CHANGE ANYTHING BELOW THIS LINE UNLESS YOU KNOW WHAT YOU'RE DOING !!
$CmdSep = ($WinNT ? $NTCmdSep : $UnixCmdSep);
$CmdPwd = ($WinNT ? "cd" : "pwd");
$PathSep = ($WinNT ? "\\" : "/");
$Redirector = ($WinNT ? " 2>&1 1>&2" : " 1>&1 2>&1");
#------------------------------------------------------------------------------
# Reads the input sent by the browser and parses the input variables. It
# parses GET, POST and multipart/form-data that is used for uploading files.
# The filename is stored in $in{'f'} and the data is stored in $in{'filedata'}.
# Other variables can be accessed using $in{'var'}, where var is the name of
# the variable. Note: Most of the code in this function is taken from other CGI
# scripts.
#------------------------------------------------------------------------------
sub ReadParse
{
local (*in) = @_ if @_;
local ($i, $loc, $key, $val);
$MultipartFormData = $ENV{'CONTENT_TYPE'} =~ /multipart\/form-data; boundary=(.+)$/;
if($ENV{'REQUEST_METHOD'} eq "GET")
{
$in = $ENV{'QUERY_STRING'};
}
elsif($ENV{'REQUEST_METHOD'} eq "POST")
{
binmode(STDIN) if $MultipartFormData & $WinNT;
read(STDIN, $in, $ENV{'CONTENT_LENGTH'});
}
# handle file upload data
if($ENV{'CONTENT_TYPE'} =~ /multipart\/form-data; boundary=(.+)$/)
{
$Boundary = '--'.$1; # please refer to RFC1867
@list = split(/$Boundary/, $in);
$HeaderBody = $list[1];
$HeaderBody =~ /\r\n\r\n|\n\n/;
$Header = $`;
$Body = $';
$Body =~ s/\r\n$//; # the last \r\n was put in by Netscape
$in{'filedata'} = $Body;
$Header =~ /filename=\"(.+)\"/;
$in{'f'} = $1;
$in{'f'} =~ s/\"//g;
$in{'f'} =~ s/\s//g;
# parse trailer
for($i=2; $list[$i]; $i++)
{
$list[$i] =~ s/^.+name=$//;
$list[$i] =~ /\"(\w+)\"/;
$key = $1;
$val = $';
$val =~ s/(^(\r\n\r\n|\n\n))|(\r\n$|\n$)//g;
$val =~ s/%(..)/pack("c", hex($1))/ge;
$in{$key} = $val;
}
}
else # standard post data (url encoded, not multipart)
{
@in = split(/&/, $in);
foreach $i (0 .. $#in)
{
$in[$i] =~ s/\+/ /g;
($key, $val) = split(/=/, $in[$i], 2);
$key =~ s/%(..)/pack("c", hex($1))/ge;
$val =~ s/%(..)/pack("c", hex($1))/ge;
$in{$key} .= "\0" if (defined($in{$key}));
$in{$key} .= $val;
}
}
}
#------------------------------------------------------------------------------
# Prints the HTML Page Header
# Argument 1: Form item name to which focus should be set
#------------------------------------------------------------------------------
sub PrintPageHeader
{
$EncodedCurrentDir = $CurrentDir;
$EncodedCurrentDir =~ s/([^a-zA-Z0-9])/'%'.unpack("H*",$1)/eg;
print "Content-type: text/html\n\n";
print <<END;
<html>
<head>
<title>CGI-Telnet Version 1.0</title>
$HtmlMetaHeader
</head>
<body onLoad="document.f.@_.focus()" bgcolor="#000000" topmargin="0" leftmargin="0" marginwidth="0" marginheight="0">
<table border="1" width="100%" cellspacing="0" cellpadding="2">
<tr>
<td bgcolor="#C2BFA5" bordercolor="#000080" align="center">
<b><font color="#000080" size="2">#</font></b></td>
<td bgcolor="#000080"><font face="Verdana" size="2" color="#FFFFFF"><b>CGI-Telnet Version 1.0 - Connected to
$ServerName</b></font></td>
</tr>
<tr>
<td colspan="2" bgcolor="#C2BFA5"><font face="Verdana" size="2">
<a href="$ScriptLocation?a=upload&d=$EncodedCurrentDir">Upload File</a> |
<a href="$ScriptLocation?a=download&d=$EncodedCurrentDir">Download File</a> |
<a href="$ScriptLocation?a=logout">Disconnect</a> |
<a href="http://www.rohitab.com/cgiscripts/cgitelnet.html">Help</a>
</font></td>
</tr>
</table>
<font color="#C0C0C0" size="3">
END
}
#------------------------------------------------------------------------------
# Prints the Login Screen
#------------------------------------------------------------------------------
sub PrintLoginScreen
{
$Message = q$<pre><font color="#669999"> _____ _____ _____ _____ _ _
/ __ \| __ \|_ _| |_ _| | | | |
| / \/| | \/ | | ______ | | ___ | | _ __ ___ | |_
| | | | __ | | |______| | | / _ \| || '_ \ / _ \| __|
| \__/\| |_\ \ _| |_ | | | __/| || | | || __/| |_
\____/ \____/ \___/ \_/ \___||_||_| |_| \___| \__| 1.0
</font><font color="#FF0000"> ______ </font><font color="#AE8300">© 2001, Rohitab
Batra</font><font color="#FF0000">
.-" "-.
/ \
| |
|, .-. .-. ,|
| )(_o/ \o_)( |
|/ /\ \|
(@_ (_ ^^ _)
_ ) \</font><font color="#808080">_______</font><font color="#FF0000">\</font><font
color="#808080">__</font><font color="#FF0000">|IIIIII|</font><font color="#808080">__</font><font
color="#FF0000">/</font><font color="#808080">_______________________
</font><font color="#FF0000"> (_)</font><font color="#808080">@8@8</font><font color="#FF0000">{}</font><font
color="#808080"><________</font><font color="#FF0000">|-\IIIIII/-|</font><font
color="#808080">________________________></font><font color="#FF0000">
)_/ \ /
(@ `--------`
</font><font color="#AE8300">W A R N I N G: Private Server</font></pre>
$;
#'
print <<END;
<code>
Trying $ServerName...<br>
Connected to $ServerName<br>
Escape character is ^]
<code>$Message
END
}
#------------------------------------------------------------------------------
# Prints the message that informs the user of a failed login
#------------------------------------------------------------------------------
sub PrintLoginFailedMessage
{
print <<END;
<code>
<br>login: admin<br>
password:<br>
Login incorrect<br><br>
</code>
END
}
#------------------------------------------------------------------------------
# Prints the HTML form for logging in
#------------------------------------------------------------------------------
sub PrintLoginForm
{
print <<END;
<code>
<form name="f" method="POST" action="$ScriptLocation">
<input type="hidden" name="a" value="login">
login: admin<br>
password:<input type="password" name="p">
<input type="submit" value="Enter">
</form>
</code>
END
}
#------------------------------------------------------------------------------
# Prints the footer for the HTML Page
#------------------------------------------------------------------------------
sub PrintPageFooter
{
print "</font></body></html>";
}
#------------------------------------------------------------------------------
# Retreives the values of all cookies. The cookies can be accesses using the
# variable $Cookies{''}
#------------------------------------------------------------------------------
sub GetCookies
{
@httpcookies = split(/; /,$ENV{'HTTP_COOKIE'});
foreach $cookie(@httpcookies)
{
($id, $val) = split(/=/, $cookie);
$Cookies{$id} = $val;
}
}
#------------------------------------------------------------------------------
# Prints the screen when the user logs out
#------------------------------------------------------------------------------
sub PrintLogoutScreen
{
print "<code>Connection closed by foreign host.<br><br></code>";
}
#------------------------------------------------------------------------------
# Logs out the user and allows the user to login again
#------------------------------------------------------------------------------
sub PerformLogout
{
print "Set-Cookie: SAVEDPWD=;\n"; # remove password cookie
&PrintPageHeader("p");
&PrintLogoutScreen;
&PrintLoginScreen;
&PrintLoginForm;
&PrintPageFooter;
}
#------------------------------------------------------------------------------
# This function is called to login the user. If the password matches, it
# displays a page that allows the user to run commands. If the password doens't
# match or if no password is entered, it displays a form that allows the user
# to login
#------------------------------------------------------------------------------
sub PerformLogin
{
if($LoginPassword eq $Password) # password matched
{
print "Set-Cookie: SAVEDPWD=$LoginPassword;\n";
&PrintPageHeader("c");
&PrintCommandLineInputForm;
&PrintPageFooter;
}
else # password didn't match
{
&PrintPageHeader("p");
&PrintLoginScreen;
if($LoginPassword ne "") # some password was entered
{
&PrintLoginFailedMessage;
}
&PrintLoginForm;
&PrintPageFooter;
}
}
#------------------------------------------------------------------------------
# Prints the HTML form that allows the user to enter commands
#------------------------------------------------------------------------------
sub PrintCommandLineInputForm
{
$Prompt = $WinNT ? "$CurrentDir> " : "[admin\@$ServerName $CurrentDir]\$ ";
print <<END;
<code>
<form name="f" method="POST" action="$ScriptLocation">
<input type="hidden" name="a" value="command">
<input type="hidden" name="d" value="$CurrentDir">
$Prompt
<input type="text" name="c">
<input type="submit" value="Enter">
</form>
</code>
END
}
#------------------------------------------------------------------------------
# Prints the HTML form that allows the user to download files
#------------------------------------------------------------------------------
sub PrintFileDownloadForm
{
$Prompt = $WinNT ? "$CurrentDir> " : "[admin\@$ServerName $CurrentDir]\$ ";
print <<END;
<code>
<form name="f" method="POST" action="$ScriptLocation">
<input type="hidden" name="d" value="$CurrentDir">
<input type="hidden" name="a" value="download">
$Prompt download<br><br>
Filename: <input type="text" name="f" size="35"><br><br>
Download: <input type="submit" value="Begin">
</form>
</code>
END
}
#------------------------------------------------------------------------------
# Prints the HTML form that allows the user to upload files
#------------------------------------------------------------------------------
sub PrintFileUploadForm
{
$Prompt = $WinNT ? "$CurrentDir> " : "[admin\@$ServerName $CurrentDir]\$ ";
print <<END;
<code>
<form name="f" enctype="multipart/form-data" method="POST" action="$ScriptLocation">
$Prompt upload<br><br>
Filename: <input type="file" name="f" size="35"><br><br>
Options: <input type="checkbox" name="o" value="overwrite">
Overwrite if it Exists<br><br>
Upload: <input type="submit" value="Begin">
<input type="hidden" name="d" value="$CurrentDir">
<input type="hidden" name="a" value="upload">
</form>
</code>
END
}
#------------------------------------------------------------------------------
# This function is called when the timeout for a command expires. We need to
# terminate the script immediately. This function is valid only on Unix. It is
# never called when the script is running on NT.
#------------------------------------------------------------------------------
sub CommandTimeout
{
if(!$WinNT)
{
alarm(0);
print <<END;
</xmp>
<code>
Command exceeded maximum time of $CommandTimeoutDuration second(s).
<br>Killed it!
<code>
END
&PrintCommandLineInputForm;
&PrintPageFooter;
exit;
}
}
#------------------------------------------------------------------------------
# This function is called to execute commands. It displays the output of the
# command and allows the user to enter another command. The change directory
# command is handled differently. In this case, the new directory is stored in
# an internal variable and is used each time a command has to be executed. The
# output of the change directory command is not displayed to the users
# therefore error messages cannot be displayed.
#------------------------------------------------------------------------------
sub ExecuteCommand
{
if($RunCommand =~ m/^\s*cd\s+(.+)/) # it is a change dir command
{
# we change the directory internally. The output of the
# command is not displayed.
$OldDir = $CurrentDir;
$Command = "cd \"$CurrentDir\"".$CmdSep."cd $1".$CmdSep.$CmdPwd;
chop($CurrentDir = `$Command`);
&PrintPageHeader("c");
$Prompt = $WinNT ? "$OldDir> " : "[admin\@$ServerName $OldDir]\$ ";
print "<code>$Prompt $RunCommand</code>";
}
else # some other command, display the output
{
&PrintPageHeader("c");
$Prompt = $WinNT ? "$CurrentDir> " : "[admin\@$ServerName $CurrentDir]\$ ";
print "<code>$Prompt $RunCommand</code><xmp>";
$Command = "cd \"$CurrentDir\"".$CmdSep.$RunCommand.$Redirector;
if(!$WinNT)
{
$SIG{'ALRM'} = \&CommandTimeout;
alarm($CommandTimeoutDuration);
}
if($ShowDynamicOutput) # show output as it is generated
{
$|=1;
$Command .= " |";
open(CommandOutput, $Command);
while(<CommandOutput>)
{
$_ =~ s/(\n|\r\n)$//;
print "$_\n";
}
$|=0;
}
else # show output after command completes
{
print `$Command`;
}
if(!$WinNT)
{
alarm(0);
}
print "</xmp>";
}
&PrintCommandLineInputForm;
&PrintPageFooter;
}
#------------------------------------------------------------------------------
# This function displays the page that contains a link which allows the user
# to download the specified file. The page also contains a auto-refresh
# feature that starts the download automatically.
# Argument 1: Fully qualified filename of the file to be downloaded
#------------------------------------------------------------------------------
sub PrintDownloadLinkPage
{
local($FileUrl) = @_;
if(-e $FileUrl) # if the file exists
{
# encode the file link so we can send it to the browser
$FileUrl =~ s/([^a-zA-Z0-9])/'%'.unpack("H*",$1)/eg;
$DownloadLink = "$ScriptLocation?a=download&f=$FileUrl&o=go";
$HtmlMetaHeader = "<meta HTTP-EQUIV=\"Refresh\" CONTENT=\"1; URL=$DownloadLink\">";
&PrintPageHeader("c");
print <<END;
<code>
Sending File $TransferFile...<br>
If the download does not start automatically,
<a href="$DownloadLink">Click Here</a>.
</code>
END
&PrintCommandLineInputForm;
&PrintPageFooter;
}
else # file doesn't exist
{
&PrintPageHeader("f");
print "<code>Failed to download $FileUrl: $!</code>";
&PrintFileDownloadForm;
&PrintPageFooter;
}
}
#------------------------------------------------------------------------------
# This function reads the specified file from the disk and sends it to the
# browser, so that it can be downloaded by the user.
# Argument 1: Fully qualified pathname of the file to be sent.
#------------------------------------------------------------------------------
sub SendFileToBrowser
{
local($SendFile) = @_;
if(open(SENDFILE, $SendFile)) # file opened for reading
{
if($WinNT)
{
binmode(SENDFILE);
binmode(STDOUT);
}
$FileSize = (stat($SendFile))[7];
($Filename = $SendFile) =~ m!([^/^\\]*)$!;
print "Content-Type: application/x-unknown\n";
print "Content-Length: $FileSize\n";
print "Content-Disposition: attachment; filename=$1\n\n";
print while(<SENDFILE>);
close(SENDFILE);
}
else # failed to open file
{
&PrintPageHeader("f");
print "<code>Failed to download $SendFile: $!</code>";
&PrintFileDownloadForm;
&PrintPageFooter;
}
}
#------------------------------------------------------------------------------
# This function is called when the user downloads a file. It displays a message
# to the user and provides a link through which the file can be downloaded.
# This function is also called when the user clicks on that link. In this case,
# the file is read and sent to the browser.
#------------------------------------------------------------------------------
sub BeginDownload
{
# get fully qualified path of the file to be downloaded
if(($WinNT & ($TransferFile =~ m/^\\|^.:/)) |
(!$WinNT & ($TransferFile =~ m/^\//))) # path is absolute
{
$TargetFile = $TransferFile;
}
else # path is relative
{
chop($TargetFile) if($TargetFile = $CurrentDir) =~ m/[\\\/]$/;
$TargetFile .= $PathSep.$TransferFile;
}
if($Options eq "go") # we have to send the file
{
&SendFileToBrowser($TargetFile);
}
else # we have to send only the link page
{
&PrintDownloadLinkPage($TargetFile);
}
}
#------------------------------------------------------------------------------
# This function is called when the user wants to upload a file. If the
# file is not specified, it displays a form allowing the user to specify a
# file, otherwise it starts the upload process.
#------------------------------------------------------------------------------
sub UploadFile
{
# if no file is specified, print the upload form again
if($TransferFile eq "")
{
&PrintPageHeader("f");
&PrintFileUploadForm;
&PrintPageFooter;
return;
}
&PrintPageHeader("c");
# start the uploading process
print "<code>Uploading $TransferFile to $CurrentDir...<br>";
# get the fullly qualified pathname of the file to be created
chop($TargetName) if ($TargetName = $CurrentDir) =~ m/[\\\/]$/;
$TransferFile =~ m!([^/^\\]*)$!;
$TargetName .= $PathSep.$1;
$TargetFileSize = length($in{'filedata'});
# if the file exists and we are not supposed to overwrite it
if(-e $TargetName && $Options ne "overwrite")
{
print "Failed: Destination file already exists.<br>";
}
else # file is not present
{
if(open(UPLOADFILE, ">$TargetName"))
{
binmode(UPLOADFILE) if $WinNT;
print UPLOADFILE $in{'filedata'};
close(UPLOADFILE);
print "Transfered $TargetFileSize Bytes.<br>";
print "File Path: $TargetName<br>";
}
else
{
print "Failed: $!<br>";
}
}
print "</code>";
&PrintCommandLineInputForm;
&PrintPageFooter;
}
#------------------------------------------------------------------------------
# This function is called when the user wants to download a file. If the
# filename is not specified, it displays a form allowing the user to specify a
# file, otherwise it displays a message to the user and provides a link
# through which the file can be downloaded.
#------------------------------------------------------------------------------
sub DownloadFile
{
# if no file is specified, print the download form again
if($TransferFile eq "")
{
&PrintPageHeader("f");
&PrintFileDownloadForm;
&PrintPageFooter;
return;
}
# get fully qualified path of the file to be downloaded
if(($WinNT & ($TransferFile =~ m/^\\|^.:/)) |
(!$WinNT & ($TransferFile =~ m/^\//))) # path is absolute
{
$TargetFile = $TransferFile;
}
else # path is relative
{
chop($TargetFile) if($TargetFile = $CurrentDir) =~ m/[\\\/]$/;
$TargetFile .= $PathSep.$TransferFile;
}
if($Options eq "go") # we have to send the file
{
&SendFileToBrowser($TargetFile);
}
else # we have to send only the link page
{
&PrintDownloadLinkPage($TargetFile);
}
}
#------------------------------------------------------------------------------
# Main Program - Execution Starts Here
#------------------------------------------------------------------------------
&ReadParse;
&GetCookies;
$ScriptLocation = $ENV{'SCRIPT_NAME'};
$ServerName = $ENV{'SERVER_NAME'};
$LoginPassword = $in{'p'};
$RunCommand = $in{'c'};
$TransferFile = $in{'f'};
$Options = $in{'o'};
$Action = $in{'a'};
$Action = "login" if($Action eq ""); # no action specified, use default
# get the directory in which the commands will be executed
$CurrentDir = $in{'d'};
chop($CurrentDir = `$CmdPwd`) if($CurrentDir eq "");
$LoggedIn = $Cookies{'SAVEDPWD'} eq $Password;
if($Action eq "login" || !$LoggedIn) # user needs/has to login
{
&PerformLogin;
}
elsif($Action eq "command") # user wants to run a command
{
&ExecuteCommand;
}
elsif($Action eq "upload") # user wants to upload a file
{
&UploadFile;
}
elsif($Action eq "download") # user wants to download a file
{
&DownloadFile;
}
elsif($Action eq "logout") # user wants to logout
{
&PerformLogout;
}
| {
"pile_set_name": "Github"
} |
[packaging]
auto_update = false | {
"pile_set_name": "Github"
} |
{
"iconName": "gradle"
}
| {
"pile_set_name": "Github"
} |
/*
* Author: commy2
*
* Adjust the grenades throwing direction and speed to the selected throwing mode.
*
* Argument:
* input from "Fired" eventhandler
*
* Return value:
* Nothing
*/
private ["_unit", "_weapon", "_projectile"];
_unit = _this select 0;
_weapon = _this select 1;
_projectile = _this select 6;
if (_weapon != "Throw") exitWith {};
private "_mode";
_mode = missionNamespace getVariable ["AGM_Grenades_Mode", 0];
if (_mode != 0) then {
private "_velocity";
_velocity = velocity _projectile;
switch (_mode) do {
//high throw
case 1 : {
_velocity = [
0.5 * (_velocity select 0),
0.5 * (_velocity select 1),
[0, 0, 0] distance (_velocity vectorMultiply 0.5)
];
};
//precise throw
case 2 : {
_velocity = (_unit weaponDirection _weapon) vectorMultiply (vectorMagnitude _velocity);
};
//roll grande
case 3 : {
//@todo
};
//drop grenade
case 4 : {
_velocity = [0, 0, 0];
};
};
_projectile setVelocity _velocity;
};
if (typeOf _projectile == "AGM_G_M84") then {
_this spawn {
_projectile = _this select 6;
sleep getNumber (configFile >> "CfgAmmo" >> typeOf _projectile >> "fuseDistance");
if (alive _projectile) then {
playSound3D ["A3\Sounds_F\weapons\Explosion\explosion_mine_1.wss", _projectile, false, getPosASL _projectile, 5, 1.2, 400];
_affected = _projectile nearEntities ["CAManBase", 50];
{
[[_x, _projectile], "AGM_Grenades_fnc_flashbangEffect", _x] call AGM_Core_fnc_execRemoteFnc;
} forEach _affected;
};
};
};
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="utf-8"?>
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFrameworks>net35-client;net40-client;netstandard2.0</TargetFrameworks>
</PropertyGroup>
</Project> | {
"pile_set_name": "Github"
} |
// 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.
#ifndef CHROME_BROWSER_SUPERVISED_USER_CHILD_ACCOUNTS_PERMISSION_REQUEST_CREATOR_APIARY_H_
#define CHROME_BROWSER_SUPERVISED_USER_CHILD_ACCOUNTS_PERMISSION_REQUEST_CREATOR_APIARY_H_
#include <memory>
#include <string>
#include "base/macros.h"
#include "base/memory/scoped_vector.h"
#include "chrome/browser/supervised_user/permission_request_creator.h"
#include "google_apis/gaia/oauth2_token_service.h"
#include "net/url_request/url_fetcher_delegate.h"
class GURL;
class Profile;
namespace base {
class Time;
}
namespace net {
class URLFetcher;
class URLRequestContextGetter;
}
class PermissionRequestCreatorApiary : public PermissionRequestCreator,
public OAuth2TokenService::Consumer,
public net::URLFetcherDelegate {
public:
PermissionRequestCreatorApiary(
OAuth2TokenService* oauth2_token_service,
const std::string& account_id,
net::URLRequestContextGetter* context);
~PermissionRequestCreatorApiary() override;
static std::unique_ptr<PermissionRequestCreator> CreateWithProfile(
Profile* profile);
// PermissionRequestCreator implementation:
bool IsEnabled() const override;
void CreateURLAccessRequest(const GURL& url_requested,
const SuccessCallback& callback) override;
void CreateExtensionInstallRequest(const std::string& id,
const SuccessCallback& callback) override;
void CreateExtensionUpdateRequest(const std::string& id,
const SuccessCallback& callback) override;
void set_url_fetcher_id_for_testing(int id) { url_fetcher_id_ = id; }
private:
struct Request;
using RequestIterator = ScopedVector<Request>::iterator;
// OAuth2TokenService::Consumer implementation:
void OnGetTokenSuccess(const OAuth2TokenService::Request* request,
const std::string& access_token,
const base::Time& expiration_time) override;
void OnGetTokenFailure(const OAuth2TokenService::Request* request,
const GoogleServiceAuthError& error) override;
// net::URLFetcherDelegate implementation.
void OnURLFetchComplete(const net::URLFetcher* source) override;
GURL GetApiUrl() const;
std::string GetApiScope() const;
void CreateRequest(const std::string& request_type,
const std::string& object_ref,
const SuccessCallback& callback);
// Requests an access token, which is the first thing we need. This is where
// we restart when the returned access token has expired.
void StartFetching(Request* request);
void DispatchResult(RequestIterator it, bool success);
OAuth2TokenService* oauth2_token_service_;
std::string account_id_;
net::URLRequestContextGetter* context_;
int url_fetcher_id_;
ScopedVector<Request> requests_;
DISALLOW_COPY_AND_ASSIGN(PermissionRequestCreatorApiary);
};
#endif // CHROME_BROWSER_SUPERVISED_USER_CHILD_ACCOUNTS_PERMISSION_REQUEST_CREATOR_APIARY_H_
| {
"pile_set_name": "Github"
} |
/* Copyright 2017-2020 PaGMO development team
This file is part of the PaGMO library.
The PaGMO library is free software; you can redistribute it and/or modify
it under the terms of either:
* the GNU Lesser General Public License as published by the Free
Software Foundation; either version 3 of the License, or (at your
option) any later version.
or
* the GNU General Public License as published by the Free Software
Foundation; either version 3 of the License, or (at your option) any
later version.
or both in parallel, as here.
The PaGMO library is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
for more details.
You should have received copies of the GNU General Public License and the
GNU Lesser General Public License along with the PaGMO library. If not,
see https://www.gnu.org/licenses/. */
#ifndef PAGMO_ALGORITHMS_IHS_HPP
#define PAGMO_ALGORITHMS_IHS_HPP
#include <string>
#include <tuple>
#include <vector>
#include <pagmo/algorithm.hpp>
#include <pagmo/detail/visibility.hpp>
#include <pagmo/population.hpp>
#include <pagmo/rng.hpp>
#include <pagmo/types.hpp>
namespace pagmo
{
/// Improved Harmony Search
/**
* \image html ihs.gif
*
* Harmony search (HS) is a metaheuristic algorithm said to mimick the improvisation process of musicians.
* In the metaphor, each musician (i.e., each variable) plays (i.e., generates) a note (i.e., a value)
* for finding a best harmony (i.e., the global optimum) all together.
*
* This code implements the so-called improved harmony search algorithm (IHS), in which the probability
* of picking the variables from the decision vector and the amount of mutation to which they are subject
* vary (respectively linearly and exponentially) at each call of the ``evolve()`` method.
*
* In this algorithm the number of fitness function evaluations is equal to the number of iterations.
* All the individuals in the input population participate in the evolution. A new individual is generated
* at every iteration, substituting the current worst individual of the population if better.
**
*
* \verbatim embed:rst:leading-asterisk
*
* .. warning::
*
* The HS algorithm can and has been criticized, not for its performances,
* but for the use of a metaphor that does not add anything to existing ones. The HS
* algorithm essentially applies mutation and crossover operators to a background population and as such
* should have been developed in the context of Evolutionary Strategies or Genetic Algorithms and studied
* in that context. The use of the musicians metaphor only obscures its internal functioning
* making theoretical results from ES and GA erroneously seem as unapplicable to HS.
*
* .. note::
*
* The original IHS algorithm was designed to solve unconstrained, deterministic single objective problems.
* In pagmo, the algorithm was modified to tackle also multi-objective (unconstrained), constrained
* (single-objective), mixed-integer and stochastic problems. Such extension is original with pagmo.
*
* .. seealso::
*
* https://en.wikipedia.org/wiki/Harmony_search for an introduction on harmony search.
*
* .. seealso::
*
* https://linkinghub.elsevier.com/retrieve/pii/S0096300306015098 for the paper that introduces and explains improved
* harmony search.
*
* \endverbatim
*/
class PAGMO_DLL_PUBLIC ihs
{
public:
/// Single data line for the algorithm's log.
/**
* A log data line is a tuple consisting of:
* - the number of objective function evaluations made so far,
* - the pitch adjustment rate,
* - the distance bandwidth
* - the population flatness evaluated as the distance between the decisions vector of the best and of the worst
* individual (or -1 in a multiobjective case),
* - the population flatness evaluated as the distance between the fitness of the best and of the worst individual
* (or -1 in a multiobjective case),
* - the number of constraints violated by the current decision vector,
* - the constraints violation norm for the current decision vector,
* - the objective value of the best solution or, in the multiobjective case, the ideal point
*/
typedef std::tuple<unsigned long long, double, double, double, double, vector_double::size_type, double,
vector_double>
log_line_type;
/// Log type.
/**
* The algorithm log is a collection of ihs::log_line_type data lines, stored in chronological order
* during the optimisation if the verbosity of the algorithm is set to a nonzero value
* (see ihs::set_verbosity()).
*/
typedef std::vector<log_line_type> log_type;
/// Constructor
/**
* Constructs ihs
*
* @param gen Number of generations to consider. Each generation will compute the objective function once.
* @param phmcr probability of choosing from memory (similar to a crossover probability)
* @param ppar_min minimum pitch adjustment rate. (similar to a mutation rate)
* @param ppar_max maximum pitch adjustment rate. (similar to a mutation rate)
* @param bw_min minimum distance bandwidth. (similar to a mutation width)
* @param bw_max maximum distance bandwidth. (similar to a mutation width)
* @param seed seed used by the internal random number generator
*
* @throws value_error if phmcr is not in the ]0,1[ interval, ppar min/max are not in the ]0,1[
* interval, min/max quantities are less than/greater than max/min quantities, bw_min is negative.
*/
ihs(unsigned gen = 1u, double phmcr = 0.85, double ppar_min = 0.35, double ppar_max = 0.99, double bw_min = 1E-5,
double bw_max = 1., unsigned seed = pagmo::random_device::next());
// Algorithm evolve method
population evolve(population) const;
/// Set verbosity.
/**
* This method will set the algorithm's verbosity. If \p n is zero, no output is produced during the optimisation
* and no logging is performed. If \p n is nonzero, then every \p n objective function evaluations the status
* of the optimisation will be both printed to screen and recorded internally. See ihs::log_line_type and
* ihs::log_type for information on the logging format. The internal log can be fetched via get_log().
*
* Example (verbosity 100, a constrained problem):
* @code{.unparsed}
* Fevals: ppar: bw: dx: df: Violated: Viol. Norm: ideal1:
* 1 0.35064 0.988553 5.17002 68.4027 1 0.0495288 85.1946
* 101 0.41464 0.312608 4.21626 46.248 1 0.0495288 85.1946
* 201 0.47864 0.0988553 2.27851 8.00679 1 0.0495288 85.1946
* 301 0.54264 0.0312608 3.94453 31.9834 1 0.0495288 85.1946
* 401 0.60664 0.00988553 4.74834 40.188 1 0.0495288 85.1946
* 501 0.67064 0.00312608 2.91583 6.53575 1 0.00904482 90.3601
* 601 0.73464 0.000988553 2.98691 10.6425 1 0.000760728 110.121
* 701 0.79864 0.000312608 2.27775 39.7507 1 0.000760728 110.121
* 801 0.86264 9.88553e-05 0.265908 4.5488 1 0.000760728 110.121
* 901 0.92664 3.12608e-05 0.566348 0.354253 1 0.000760728 110.121
* @endcode
* Feasibility is checked against the problem's tolerance.
*
* By default, the verbosity level is zero.
*
* @param n the desired verbosity level.
*/
void set_verbosity(unsigned n)
{
m_verbosity = n;
}
/// Gets the verbosity level
/**
* @return the verbosity level
*/
unsigned get_verbosity() const
{
return m_verbosity;
}
// Sets the seed
void set_seed(unsigned);
/// Gets the seed
/**
* @return the seed controlling the algorithm stochastic behaviour
*/
unsigned get_seed() const
{
return m_seed;
}
/// Algorithm name
/**
* One of the optional methods of any user-defined algorithm (UDA).
*
* @return a string containing the algorithm name
*/
std::string get_name() const
{
return "IHS: Improved Harmony Search";
}
// Extra info
std::string get_extra_info() const;
/// Get the optimisation log.
/**
* See ihs::log_type for a description of the optimisation log. Logging is turned on/off via
* set_verbosity().
*
* @return a const reference to the log.
*/
const log_type &get_log() const
{
return m_log;
}
// Object serialization
template <typename Archive>
void serialize(Archive &, unsigned);
private:
// logging is complex fir ihs as the algorithm is an "any-problem" wannabe
PAGMO_DLL_LOCAL void log_a_line(const population &, unsigned &, unsigned long long, double, double) const;
unsigned m_gen;
double m_phmcr;
double m_ppar_min;
double m_ppar_max;
double m_bw_min;
double m_bw_max;
mutable detail::random_engine_type m_e;
unsigned m_seed;
unsigned m_verbosity;
mutable log_type m_log;
};
} // namespace pagmo
PAGMO_S11N_ALGORITHM_EXPORT_KEY(pagmo::ihs)
#endif
| {
"pile_set_name": "Github"
} |
// Algorithm extensions -*- C++ -*-
// Copyright (C) 2001-2014 Free Software Foundation, Inc.
//
// This file is part of the GNU ISO C++ Library. This library is free
// software; you can redistribute it and/or modify it under the
// terms of the GNU General Public License as published by the
// Free Software Foundation; either version 3, or (at your option)
// any later version.
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// Under Section 7 of GPL version 3, you are granted additional
// permissions described in the GCC Runtime Library Exception, version
// 3.1, as published by the Free Software Foundation.
// You should have received a copy of the GNU General Public License and
// a copy of the GCC Runtime Library Exception along with this program;
// see the files COPYING3 and COPYING.RUNTIME respectively. If not, see
// <http://www.gnu.org/licenses/>.
/*
*
* Copyright (c) 1994
* Hewlett-Packard Company
*
* Permission to use, copy, modify, distribute and sell this software
* and its documentation for any purpose is hereby granted without fee,
* provided that the above copyright notice appear in all copies and
* that both that copyright notice and this permission notice appear
* in supporting documentation. Hewlett-Packard Company makes no
* representations about the suitability of this software for any
* purpose. It is provided "as is" without express or implied warranty.
*
*
* Copyright (c) 1996
* Silicon Graphics Computer Systems, Inc.
*
* Permission to use, copy, modify, distribute and sell this software
* and its documentation for any purpose is hereby granted without fee,
* provided that the above copyright notice appear in all copies and
* that both that copyright notice and this permission notice appear
* in supporting documentation. Silicon Graphics makes no
* representations about the suitability of this software for any
* purpose. It is provided "as is" without express or implied warranty.
*/
/** @file ext/algorithm
* This file is a GNU extension to the Standard C++ Library (possibly
* containing extensions from the HP/SGI STL subset).
*/
#ifndef _EXT_ALGORITHM
#define _EXT_ALGORITHM 1
#pragma GCC system_header
#include <algorithm>
namespace __gnu_cxx _GLIBCXX_VISIBILITY(default)
{
_GLIBCXX_BEGIN_NAMESPACE_VERSION
using std::ptrdiff_t;
using std::min;
using std::pair;
using std::input_iterator_tag;
using std::random_access_iterator_tag;
using std::iterator_traits;
//--------------------------------------------------
// copy_n (not part of the C++ standard)
template<typename _InputIterator, typename _Size, typename _OutputIterator>
pair<_InputIterator, _OutputIterator>
__copy_n(_InputIterator __first, _Size __count,
_OutputIterator __result,
input_iterator_tag)
{
for ( ; __count > 0; --__count)
{
*__result = *__first;
++__first;
++__result;
}
return pair<_InputIterator, _OutputIterator>(__first, __result);
}
template<typename _RAIterator, typename _Size, typename _OutputIterator>
inline pair<_RAIterator, _OutputIterator>
__copy_n(_RAIterator __first, _Size __count,
_OutputIterator __result,
random_access_iterator_tag)
{
_RAIterator __last = __first + __count;
return pair<_RAIterator, _OutputIterator>(__last, std::copy(__first,
__last,
__result));
}
/**
* @brief Copies the range [first,first+count) into [result,result+count).
* @param __first An input iterator.
* @param __count The number of elements to copy.
* @param __result An output iterator.
* @return A std::pair composed of first+count and result+count.
*
* This is an SGI extension.
* This inline function will boil down to a call to @c memmove whenever
* possible. Failing that, if random access iterators are passed, then the
* loop count will be known (and therefore a candidate for compiler
* optimizations such as unrolling).
* @ingroup SGIextensions
*/
template<typename _InputIterator, typename _Size, typename _OutputIterator>
inline pair<_InputIterator, _OutputIterator>
copy_n(_InputIterator __first, _Size __count, _OutputIterator __result)
{
// concept requirements
__glibcxx_function_requires(_InputIteratorConcept<_InputIterator>)
__glibcxx_function_requires(_OutputIteratorConcept<_OutputIterator,
typename iterator_traits<_InputIterator>::value_type>)
return __gnu_cxx::__copy_n(__first, __count, __result,
std::__iterator_category(__first));
}
template<typename _InputIterator1, typename _InputIterator2>
int
__lexicographical_compare_3way(_InputIterator1 __first1,
_InputIterator1 __last1,
_InputIterator2 __first2,
_InputIterator2 __last2)
{
while (__first1 != __last1 && __first2 != __last2)
{
if (*__first1 < *__first2)
return -1;
if (*__first2 < *__first1)
return 1;
++__first1;
++__first2;
}
if (__first2 == __last2)
return !(__first1 == __last1);
else
return -1;
}
inline int
__lexicographical_compare_3way(const unsigned char* __first1,
const unsigned char* __last1,
const unsigned char* __first2,
const unsigned char* __last2)
{
const ptrdiff_t __len1 = __last1 - __first1;
const ptrdiff_t __len2 = __last2 - __first2;
const int __result = __builtin_memcmp(__first1, __first2,
min(__len1, __len2));
return __result != 0 ? __result
: (__len1 == __len2 ? 0 : (__len1 < __len2 ? -1 : 1));
}
inline int
__lexicographical_compare_3way(const char* __first1, const char* __last1,
const char* __first2, const char* __last2)
{
#if CHAR_MAX == SCHAR_MAX
return __lexicographical_compare_3way((const signed char*) __first1,
(const signed char*) __last1,
(const signed char*) __first2,
(const signed char*) __last2);
#else
return __lexicographical_compare_3way((const unsigned char*) __first1,
(const unsigned char*) __last1,
(const unsigned char*) __first2,
(const unsigned char*) __last2);
#endif
}
/**
* @brief @c memcmp on steroids.
* @param __first1 An input iterator.
* @param __last1 An input iterator.
* @param __first2 An input iterator.
* @param __last2 An input iterator.
* @return An int, as with @c memcmp.
*
* The return value will be less than zero if the first range is
* <em>lexigraphically less than</em> the second, greater than zero
* if the second range is <em>lexigraphically less than</em> the
* first, and zero otherwise.
* This is an SGI extension.
* @ingroup SGIextensions
*/
template<typename _InputIterator1, typename _InputIterator2>
int
lexicographical_compare_3way(_InputIterator1 __first1,
_InputIterator1 __last1,
_InputIterator2 __first2,
_InputIterator2 __last2)
{
// concept requirements
__glibcxx_function_requires(_InputIteratorConcept<_InputIterator1>)
__glibcxx_function_requires(_InputIteratorConcept<_InputIterator2>)
__glibcxx_function_requires(_LessThanComparableConcept<
typename iterator_traits<_InputIterator1>::value_type>)
__glibcxx_function_requires(_LessThanComparableConcept<
typename iterator_traits<_InputIterator2>::value_type>)
__glibcxx_requires_valid_range(__first1, __last1);
__glibcxx_requires_valid_range(__first2, __last2);
return __lexicographical_compare_3way(__first1, __last1, __first2,
__last2);
}
// count and count_if: this version, whose return type is void, was present
// in the HP STL, and is retained as an extension for backward compatibility.
template<typename _InputIterator, typename _Tp, typename _Size>
void
count(_InputIterator __first, _InputIterator __last,
const _Tp& __value,
_Size& __n)
{
// concept requirements
__glibcxx_function_requires(_InputIteratorConcept<_InputIterator>)
__glibcxx_function_requires(_EqualityComparableConcept<
typename iterator_traits<_InputIterator>::value_type >)
__glibcxx_function_requires(_EqualityComparableConcept<_Tp>)
__glibcxx_requires_valid_range(__first, __last);
for ( ; __first != __last; ++__first)
if (*__first == __value)
++__n;
}
template<typename _InputIterator, typename _Predicate, typename _Size>
void
count_if(_InputIterator __first, _InputIterator __last,
_Predicate __pred,
_Size& __n)
{
// concept requirements
__glibcxx_function_requires(_InputIteratorConcept<_InputIterator>)
__glibcxx_function_requires(_UnaryPredicateConcept<_Predicate,
typename iterator_traits<_InputIterator>::value_type>)
__glibcxx_requires_valid_range(__first, __last);
for ( ; __first != __last; ++__first)
if (__pred(*__first))
++__n;
}
// random_sample and random_sample_n (extensions, not part of the standard).
/**
* This is an SGI extension.
* @ingroup SGIextensions
* @doctodo
*/
template<typename _ForwardIterator, typename _OutputIterator,
typename _Distance>
_OutputIterator
random_sample_n(_ForwardIterator __first, _ForwardIterator __last,
_OutputIterator __out, const _Distance __n)
{
// concept requirements
__glibcxx_function_requires(_ForwardIteratorConcept<_ForwardIterator>)
__glibcxx_function_requires(_OutputIteratorConcept<_OutputIterator,
typename iterator_traits<_ForwardIterator>::value_type>)
__glibcxx_requires_valid_range(__first, __last);
_Distance __remaining = std::distance(__first, __last);
_Distance __m = min(__n, __remaining);
while (__m > 0)
{
if ((std::rand() % __remaining) < __m)
{
*__out = *__first;
++__out;
--__m;
}
--__remaining;
++__first;
}
return __out;
}
/**
* This is an SGI extension.
* @ingroup SGIextensions
* @doctodo
*/
template<typename _ForwardIterator, typename _OutputIterator,
typename _Distance, typename _RandomNumberGenerator>
_OutputIterator
random_sample_n(_ForwardIterator __first, _ForwardIterator __last,
_OutputIterator __out, const _Distance __n,
_RandomNumberGenerator& __rand)
{
// concept requirements
__glibcxx_function_requires(_ForwardIteratorConcept<_ForwardIterator>)
__glibcxx_function_requires(_OutputIteratorConcept<_OutputIterator,
typename iterator_traits<_ForwardIterator>::value_type>)
__glibcxx_function_requires(_UnaryFunctionConcept<
_RandomNumberGenerator, _Distance, _Distance>)
__glibcxx_requires_valid_range(__first, __last);
_Distance __remaining = std::distance(__first, __last);
_Distance __m = min(__n, __remaining);
while (__m > 0)
{
if (__rand(__remaining) < __m)
{
*__out = *__first;
++__out;
--__m;
}
--__remaining;
++__first;
}
return __out;
}
template<typename _InputIterator, typename _RandomAccessIterator,
typename _Distance>
_RandomAccessIterator
__random_sample(_InputIterator __first, _InputIterator __last,
_RandomAccessIterator __out,
const _Distance __n)
{
_Distance __m = 0;
_Distance __t = __n;
for ( ; __first != __last && __m < __n; ++__m, ++__first)
__out[__m] = *__first;
while (__first != __last)
{
++__t;
_Distance __M = std::rand() % (__t);
if (__M < __n)
__out[__M] = *__first;
++__first;
}
return __out + __m;
}
template<typename _InputIterator, typename _RandomAccessIterator,
typename _RandomNumberGenerator, typename _Distance>
_RandomAccessIterator
__random_sample(_InputIterator __first, _InputIterator __last,
_RandomAccessIterator __out,
_RandomNumberGenerator& __rand,
const _Distance __n)
{
// concept requirements
__glibcxx_function_requires(_UnaryFunctionConcept<
_RandomNumberGenerator, _Distance, _Distance>)
_Distance __m = 0;
_Distance __t = __n;
for ( ; __first != __last && __m < __n; ++__m, ++__first)
__out[__m] = *__first;
while (__first != __last)
{
++__t;
_Distance __M = __rand(__t);
if (__M < __n)
__out[__M] = *__first;
++__first;
}
return __out + __m;
}
/**
* This is an SGI extension.
* @ingroup SGIextensions
* @doctodo
*/
template<typename _InputIterator, typename _RandomAccessIterator>
inline _RandomAccessIterator
random_sample(_InputIterator __first, _InputIterator __last,
_RandomAccessIterator __out_first,
_RandomAccessIterator __out_last)
{
// concept requirements
__glibcxx_function_requires(_InputIteratorConcept<_InputIterator>)
__glibcxx_function_requires(_Mutable_RandomAccessIteratorConcept<
_RandomAccessIterator>)
__glibcxx_requires_valid_range(__first, __last);
__glibcxx_requires_valid_range(__out_first, __out_last);
return __random_sample(__first, __last,
__out_first, __out_last - __out_first);
}
/**
* This is an SGI extension.
* @ingroup SGIextensions
* @doctodo
*/
template<typename _InputIterator, typename _RandomAccessIterator,
typename _RandomNumberGenerator>
inline _RandomAccessIterator
random_sample(_InputIterator __first, _InputIterator __last,
_RandomAccessIterator __out_first,
_RandomAccessIterator __out_last,
_RandomNumberGenerator& __rand)
{
// concept requirements
__glibcxx_function_requires(_InputIteratorConcept<_InputIterator>)
__glibcxx_function_requires(_Mutable_RandomAccessIteratorConcept<
_RandomAccessIterator>)
__glibcxx_requires_valid_range(__first, __last);
__glibcxx_requires_valid_range(__out_first, __out_last);
return __random_sample(__first, __last,
__out_first, __rand,
__out_last - __out_first);
}
#if __cplusplus >= 201103L
using std::is_heap;
#else
/**
* This is an SGI extension.
* @ingroup SGIextensions
* @doctodo
*/
template<typename _RandomAccessIterator>
inline bool
is_heap(_RandomAccessIterator __first, _RandomAccessIterator __last)
{
// concept requirements
__glibcxx_function_requires(_RandomAccessIteratorConcept<
_RandomAccessIterator>)
__glibcxx_function_requires(_LessThanComparableConcept<
typename iterator_traits<_RandomAccessIterator>::value_type>)
__glibcxx_requires_valid_range(__first, __last);
return std::__is_heap(__first, __last - __first);
}
/**
* This is an SGI extension.
* @ingroup SGIextensions
* @doctodo
*/
template<typename _RandomAccessIterator, typename _StrictWeakOrdering>
inline bool
is_heap(_RandomAccessIterator __first, _RandomAccessIterator __last,
_StrictWeakOrdering __comp)
{
// concept requirements
__glibcxx_function_requires(_RandomAccessIteratorConcept<
_RandomAccessIterator>)
__glibcxx_function_requires(_BinaryPredicateConcept<_StrictWeakOrdering,
typename iterator_traits<_RandomAccessIterator>::value_type,
typename iterator_traits<_RandomAccessIterator>::value_type>)
__glibcxx_requires_valid_range(__first, __last);
return std::__is_heap(__first, __comp, __last - __first);
}
#endif
#if __cplusplus >= 201103L
using std::is_sorted;
#else
// is_sorted, a predicated testing whether a range is sorted in
// nondescending order. This is an extension, not part of the C++
// standard.
/**
* This is an SGI extension.
* @ingroup SGIextensions
* @doctodo
*/
template<typename _ForwardIterator>
bool
is_sorted(_ForwardIterator __first, _ForwardIterator __last)
{
// concept requirements
__glibcxx_function_requires(_ForwardIteratorConcept<_ForwardIterator>)
__glibcxx_function_requires(_LessThanComparableConcept<
typename iterator_traits<_ForwardIterator>::value_type>)
__glibcxx_requires_valid_range(__first, __last);
if (__first == __last)
return true;
_ForwardIterator __next = __first;
for (++__next; __next != __last; __first = __next, ++__next)
if (*__next < *__first)
return false;
return true;
}
/**
* This is an SGI extension.
* @ingroup SGIextensions
* @doctodo
*/
template<typename _ForwardIterator, typename _StrictWeakOrdering>
bool
is_sorted(_ForwardIterator __first, _ForwardIterator __last,
_StrictWeakOrdering __comp)
{
// concept requirements
__glibcxx_function_requires(_ForwardIteratorConcept<_ForwardIterator>)
__glibcxx_function_requires(_BinaryPredicateConcept<_StrictWeakOrdering,
typename iterator_traits<_ForwardIterator>::value_type,
typename iterator_traits<_ForwardIterator>::value_type>)
__glibcxx_requires_valid_range(__first, __last);
if (__first == __last)
return true;
_ForwardIterator __next = __first;
for (++__next; __next != __last; __first = __next, ++__next)
if (__comp(*__next, *__first))
return false;
return true;
}
#endif // C++11
/**
* @brief Find the median of three values.
* @param __a A value.
* @param __b A value.
* @param __c A value.
* @return One of @p a, @p b or @p c.
*
* If @c {l,m,n} is some convolution of @p {a,b,c} such that @c l<=m<=n
* then the value returned will be @c m.
* This is an SGI extension.
* @ingroup SGIextensions
*/
template<typename _Tp>
const _Tp&
__median(const _Tp& __a, const _Tp& __b, const _Tp& __c)
{
// concept requirements
__glibcxx_function_requires(_LessThanComparableConcept<_Tp>)
if (__a < __b)
if (__b < __c)
return __b;
else if (__a < __c)
return __c;
else
return __a;
else if (__a < __c)
return __a;
else if (__b < __c)
return __c;
else
return __b;
}
/**
* @brief Find the median of three values using a predicate for comparison.
* @param __a A value.
* @param __b A value.
* @param __c A value.
* @param __comp A binary predicate.
* @return One of @p a, @p b or @p c.
*
* If @c {l,m,n} is some convolution of @p {a,b,c} such that @p comp(l,m)
* and @p comp(m,n) are both true then the value returned will be @c m.
* This is an SGI extension.
* @ingroup SGIextensions
*/
template<typename _Tp, typename _Compare>
const _Tp&
__median(const _Tp& __a, const _Tp& __b, const _Tp& __c, _Compare __comp)
{
// concept requirements
__glibcxx_function_requires(_BinaryFunctionConcept<_Compare, bool,
_Tp, _Tp>)
if (__comp(__a, __b))
if (__comp(__b, __c))
return __b;
else if (__comp(__a, __c))
return __c;
else
return __a;
else if (__comp(__a, __c))
return __a;
else if (__comp(__b, __c))
return __c;
else
return __b;
}
_GLIBCXX_END_NAMESPACE_VERSION
} // namespace
#endif /* _EXT_ALGORITHM */
| {
"pile_set_name": "Github"
} |
// Copyright 2011 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package proxy
import (
"context"
"net"
)
type direct struct{}
// Direct implements Dialer by making network connections directly using net.Dial or net.DialContext.
var Direct = direct{}
var (
_ Dialer = Direct
_ ContextDialer = Direct
)
// Dial directly invokes net.Dial with the supplied parameters.
func (direct) Dial(network, addr string) (net.Conn, error) {
return net.Dial(network, addr)
}
// DialContext instantiates a net.Dialer and invokes its DialContext receiver with the supplied parameters.
func (direct) DialContext(ctx context.Context, network, addr string) (net.Conn, error) {
var d net.Dialer
return d.DialContext(ctx, network, addr)
}
| {
"pile_set_name": "Github"
} |
/* -*- C++ -*- */
/****************************************************************************
** Copyright (c) 2001-2014
**
** This file is part of the QuickFIX FIX Engine
**
** This file may be distributed under the terms of the quickfixengine.org
** license as defined by quickfixengine.org and appearing in the file
** LICENSE included in the packaging of this file.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.quickfixengine.org/LICENSE for licensing information.
**
** Contact ask@quickfixengine.org if any conditions of this licensing are
** not clear to you.
**
****************************************************************************/
#ifndef FIX_SESSIONID_H
#define FIX_SESSIONID_H
#include "Fields.h"
namespace FIX
{
/// Unique session id consists of BeginString, SenderCompID and TargetCompID.
class SessionID
{
public:
SessionID()
{
toString(m_frozenString);
}
SessionID( const std::string& beginString,
const std::string& senderCompID,
const std::string& targetCompID,
const std::string& sessionQualifier = "" )
: m_beginString( BeginString(beginString) ),
m_senderCompID( SenderCompID(senderCompID) ),
m_targetCompID( TargetCompID(targetCompID) ),
m_sessionQualifier( sessionQualifier ),
m_isFIXT(false)
{
toString(m_frozenString);
if( beginString.substr(0, 4) == "FIXT" )
m_isFIXT = true;
}
const BeginString& getBeginString() const
{ return m_beginString; }
const SenderCompID& getSenderCompID() const
{ return m_senderCompID; }
const TargetCompID& getTargetCompID() const
{ return m_targetCompID; }
const std::string& getSessionQualifier() const
{ return m_sessionQualifier; }
const bool isFIXT() const
{ return m_isFIXT; }
/// Get a string representation of the SessionID
std::string toString() const
{
return m_frozenString;
}
// Return a reference for a high-performance scenario
const std::string& toStringFrozen() const
{
return m_frozenString;
}
/// Build from string representation of SessionID
void fromString( const std::string& str )
{
std::string::size_type first =
str.find_first_of(':');
std::string::size_type second =
str.find("->");
std::string::size_type third =
str.find_last_of(':');
if( first == std::string::npos )
return;
if( second == std::string::npos )
return;
m_beginString = str.substr(0, first);
m_senderCompID = str.substr(first+1, second - first - 1);
if( first == third )
{
m_targetCompID = str.substr(second+2);
m_sessionQualifier = "";
}
else
{
m_targetCompID = str.substr(second+2, third - second - 2);
m_sessionQualifier = str.substr(third+1);
}
toString(m_frozenString);
}
/// Get a string representation without making a copy
std::string& toString( std::string& str ) const
{
str = getBeginString().getValue() + ":" +
getSenderCompID().getValue() + "->" +
getTargetCompID().getValue();
if( m_sessionQualifier.size() )
str += ":" + m_sessionQualifier;
return str;
}
friend bool operator<( const SessionID&, const SessionID& );
friend bool operator==( const SessionID&, const SessionID& );
friend bool operator!=( const SessionID&, const SessionID& );
friend std::ostream& operator<<( std::ostream&, const SessionID& );
friend std::ostream& operator>>( std::ostream&, const SessionID& );
SessionID operator~() const
{
return SessionID( m_beginString, SenderCompID( m_targetCompID ),
TargetCompID( m_senderCompID ), m_sessionQualifier );
}
private:
BeginString m_beginString;
SenderCompID m_senderCompID;
TargetCompID m_targetCompID;
std::string m_sessionQualifier;
bool m_isFIXT;
std::string m_frozenString;
};
/*! @} */
inline bool operator<( const SessionID& lhs, const SessionID& rhs )
{
return lhs.toStringFrozen() < rhs.toStringFrozen();
}
inline bool operator==( const SessionID& lhs, const SessionID& rhs )
{
return lhs.toStringFrozen() == rhs.toStringFrozen();
}
inline bool operator!=( const SessionID& lhs, const SessionID& rhs )
{
return !( lhs == rhs );
}
inline std::ostream& operator<<
( std::ostream& stream, const SessionID& sessionID )
{
stream << sessionID.toStringFrozen();
return stream;
}
inline std::istream& operator>>
( std::istream& stream, SessionID& sessionID )
{
std::string str;
stream >> str;
sessionID.fromString( str );
return stream;
}
}
#endif //FIX_SESSIONID_H
| {
"pile_set_name": "Github"
} |
%YAML 1.1
---
$schema: "http://stsci.edu/schemas/yaml-schema/draft-01"
id: "http://astropy.org/schemas/astropy/coordinates/longitude-1.0.0"
tag: "tag:astropy.org:astropy/coordinates/longitude-1.0.0"
title: |
Represents longitude-like angles.
description:
Longitude-like angle(s) which are wrapped within a contiguous 360 degree range.
examples:
-
- A Longitude object in Degrees
- |
!<tag:astropy.org:astropy/coordinates/longitude-1.0.0>
unit: !unit/unit-1.0.0 deg
value: 10.0
wrap_angle: !<tag:astropy.org:astropy/coordinates/angle-1.0.0>
unit: !unit/unit-1.0.0 deg
value: 180.0
type: object
properties:
value:
description: |
A vector of one or more values
anyOf:
- type: number
- $ref: "tag:stsci.edu:asdf/core/ndarray-1.0.0"
unit:
description: |
The unit corresponding to the values
$ref: "tag:stsci.edu:asdf/unit/unit-1.0.0"
wrap_angle:
description: |
Angle at which to wrap back to ``wrap_angle - 360 deg``.
$ref: "angle-1.0.0"
required: [value, unit, wrap_angle]
...
| {
"pile_set_name": "Github"
} |
#!/bin/bash
set -e
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
. ${DIR}/create-git-url.sh
runtimeEnv=$(uname)
echo "Running as $(whoami)."
if [ "$runtimeEnv" != "Linux" ]; then
echo "Do not use this script in non-dockerized environments."
echo "Detected non-Linux runtime $runtimeEnv."
echo "Use 'node bin/api' or 'npm start'.'"
exit 1
fi
# Infinite loop
while :
do
if [ ! -z "$GIT_REPO" ]; then
tmpDir=$(mktemp -d)
echo "Cloning configuration repository from $GIT_REPO into $tmpDir..."
pushd $tmpDir
if [ ! -z "$GIT_BRANCH" ] && [ ! -z "$GIT_REVISION" ]; then
echo "===================================================================================="
echo "ERROR: GIT_REVISION and GIT_BRANCH are mutually exclusive (both are defined)!"
echo "===================================================================================="
exit 1
fi
# this will create and set the GIT_URL variable
create_git_url $GIT_REPO $GIT_CREDENTIALS
if [ -z "$GIT_BRANCH" ]; then
echo "Checking out branch 'master'..."
git clone ${GIT_URL} .
else
echo "Checking out branch '$GIT_BRANCH'..."
git clone ${GIT_URL} --branch ${GIT_BRANCH} .
fi
if [ ! -z "$GIT_REVISION" ]; then
echo "Checking out specific revision with SHA ${GIT_REVISION}..."
git checkout $GIT_REVISION
fi
if [ ! -d "$tmpDir/static" ]; then
echo "===================================================================================="
echo "ERROR: Could not find directory 'static' in $tmpDir, wrong repository?"
echo "===================================================================================="
exit 1
fi
echo Adding metadata to static directory...
git log -1 > static/last_commit
git log -1 --format=%ci > static/build_date
echo "Cleaning up old configuration (if applicable)"
rm -rf /var/portal-api/static
echo "Copying configuration to /var/portal-api/static"
cp -R static /var/portal-api
echo "Done."
popd
echo "Cleanining up temp dir."
rm -rf $tmpDir
else
echo "Assuming /var/portal-api/static is prepopulated, not cloning configuration repo."
fi
echo "Setting owner of /var/portal-api to wicked:wicked"
chown wicked:wicked $(find /var/portal-api | grep -v .snapshot)
if [ ! -z "${MINIKUBE_IP}" ]; then
echo "Adding minikube IP for ${PORTAL_NETWORK_PORTALHOST} and ${PORTAL_NETWORK_APIHOST} to /etc/hosts"
echo ${MINIKUBE_IP} ${PORTAL_NETWORK_PORTALHOST} ${PORTAL_NETWORK_APIHOST} | tee -a /etc/hosts
fi
echo "Granting read/write rights to user 'wicked' for Swagger files..."
chown -R wicked:wicked /usr/src/app/routes/internal_apis
echo "Starting API, running as user 'wicked'..."
# Use gosu/su-exec to start node as the user "wicked"
gosu_command="gosu"
if [[ -z "$(which gosu)" ]]; then
gosu_command="su-exec"
fi
${gosu_command} wicked node bin/api
# Check for RELOAD_REQUESTED file; if this file is NOT present, the process has most
# probably died, and this should be a full reload of the container (triggering a rescheduling
# e.g. from Kubernetes). In case the file is present, the API process was told to trigger
# a reload of the configuration, and this can be done nicely in this loop.
if [ ! -f ./RELOAD_REQUESTED ]; then
echo "ERROR: Process terminated in an uncontrolled way. NOT restarting."
exit 1
else
echo "============================================================="
echo " Process was terminated in order to reload the configuration"
echo "============================================================="
fi
done
| {
"pile_set_name": "Github"
} |
#!/usr/bin/env bash
# -*- coding: utf-8 -*-
#
# A script to disallow syntax errors to be committed
# by running a checker (lint, pep8, pylint...) on them
#
# to install type ln -s check-stage .git/hooks/pre-commit
# Redirect output to stderr.
exec 2>&1
# set path (necessary for gitx and git-gui)
export PATH=$PATH:/opt/local/bin:/opt/local/sbin:/usr/local/sbin:/usr/local/bin
# necessary check for initial commit
if [ git rev-parse --verify HEAD >/dev/null 2>&1 ]; then
against=HEAD
else
# Initial commit: diff against an empty tree object
against=4b825dc642cb6eb9a060e54bf8d69288fbee4904
fi
# set Internal Field Separator to newline (dash does not support $'\n')
IFS='
'
# get a list of staged files
for LINE in $(git diff-index --cached --full-index $against); do
SHA=$(echo $LINE | cut -d' ' -f4)
STATUS=$(echo $LINE | cut -d' ' -f5 | cut -d' ' -f1)
FILENAME=$(echo $LINE | cut -d' ' -f5 | cut -d' ' -f2)
FILEEXT=$(echo $FILENAME | sed 's/^.*\.//')
# do not check deleted files
if [ $STATUS == "D" ]; then
continue
fi
# only check files with proper extension
if [ $FILEEXT == 'php' ]; then
PROGRAMS='php'
COMMANDS='php -l'
elif [ $FILEEXT == 'py' ]; then
PROGRAMS=$'pep8\npylint'
COMMANDS=$'pep8 --ignore=W191,E128'
else
continue
fi
for PROGRAM in $PROGRAMS; do
test $(which $PROGRAM)
if [ $? != 0 ]; then
echo "$PROGRAM binary does not exist or is not in path"
exit 1
fi
done
# check the staged content for syntax errors
for COMMAND in $COMMANDS; do
git cat-file -p $SHA > tmp.txt
RESULT=$(eval "$COMMAND tmp.txt")
if [ $? != 0 ]; then
echo "$COMMAND syntax check failed on $FILENAME"
for LINE in $RESULT; do echo $LINE; done
rm tmp.txt
exit 1
fi
done
done
unset IFS
rm tmp.txt
# If there are whitespace errors, print the offending file names and fail.
# exec git diff-index --check --cached $against --
| {
"pile_set_name": "Github"
} |
---
title: ProtectedViewWindow.Activate Method (Word)
keywords: vbawd10.chm231735396
f1_keywords:
- vbawd10.chm231735396
ms.prod: word
api_name:
- Word.ProtectedViewWindow.Activate
ms.assetid: a784fceb-38b9-2fc4-6c71-fcfb17b53dfe
ms.date: 06/08/2017
---
# ProtectedViewWindow.Activate Method (Word)
Activates the specified protected view window.
## Syntax
_expression_ . **Activate**
_expression_ An expression that returns a **[ProtectedViewWindow Object](protectedviewwindow-object-word.md)** object.
### Return Value
Nothing
## Example
The following code example activates the next protected view window in the [ProtectedViewWindows](protectedviewwindows-object-word.md) collection.
```vb
Dim pvWindow As ProtectedViewWindow
' At least one document must be open in protected view for this statement to execute.
ProtectedViewWindows(1).Activate
```
## See also
#### Concepts
[ProtectedViewWindow Object](protectedviewwindow-object-word.md)
| {
"pile_set_name": "Github"
} |
/*
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.xwiki.annotation.io.internal;
import java.io.StringReader;
import javax.inject.Inject;
import javax.inject.Named;
import javax.inject.Singleton;
import org.xwiki.annotation.io.IOServiceException;
import org.xwiki.annotation.io.IOTargetService;
import org.xwiki.annotation.reference.TypedStringEntityReferenceResolver;
import org.xwiki.bridge.DocumentAccessBridge;
import org.xwiki.component.annotation.Component;
import org.xwiki.component.manager.ComponentManager;
import org.xwiki.display.internal.DocumentDisplayer;
import org.xwiki.display.internal.DocumentDisplayerParameters;
import org.xwiki.model.EntityType;
import org.xwiki.model.reference.DocumentReference;
import org.xwiki.model.reference.EntityReference;
import org.xwiki.model.reference.ObjectPropertyReference;
import org.xwiki.rendering.block.XDOM;
import org.xwiki.rendering.parser.ParseException;
import org.xwiki.rendering.parser.Parser;
import org.xwiki.rendering.syntax.Syntax;
import org.xwiki.rendering.transformation.RenderingContext;
import org.xwiki.rendering.transformation.TransformationContext;
import org.xwiki.rendering.transformation.TransformationException;
import org.xwiki.rendering.transformation.TransformationManager;
import com.xpn.xwiki.objects.BaseObjectReference;
/**
* Default {@link IOTargetService} implementation, based on resolving XWiki documents and object properties as
* annotations targets. The references manipulated by this implementation are XWiki references, such as xwiki:Space.Page
* for documents or with an object and property reference if the target is an object property. Use the reference module
* to generate the references passed to this module, so that they can be resolved to XWiki content back by this
* implementation.
*
* @version $Id: 1f923ef0309ae507a75ef49b8c2b66f67f9a80f3 $
* @since 2.3M1
*/
@Component
@Singleton
public class DefaultIOTargetService implements IOTargetService
{
/**
* Component manager used to lookup the parsers.
*/
@Inject
private ComponentManager componentManager;
/**
* Document access bridge to manipulate xwiki documents.
*/
@Inject
private DocumentAccessBridge dab;
/**
* Document displayer.
*/
@Inject
@Named("configured")
private DocumentDisplayer documentDisplayer;
/**
* Entity reference handler to resolve the reference.
*/
@Inject
private TypedStringEntityReferenceResolver referenceResolver;
@Inject
private RenderingContext renderingContext;
@Override
public String getSource(String reference) throws IOServiceException
{
try {
EntityReference ref = referenceResolver.resolve(reference, EntityType.DOCUMENT);
if (ref.getType() == EntityType.OBJECT_PROPERTY) {
return getObjectPropertyContent(new ObjectPropertyReference(ref));
} else if (ref.getType() == EntityType.DOCUMENT) {
return dab.getTranslatedDocumentInstance(new DocumentReference(ref)).getContent();
} else {
// it was parsed as something else, just ignore the parsing and get the document content as its initial
// name was
return dab.getDocumentContent(reference);
}
} catch (Exception e) {
throw new IOServiceException("An exception has occurred while getting the source for " + reference, e);
}
}
@Override
public String getSourceSyntax(String reference) throws IOServiceException
{
try {
EntityReference ref = referenceResolver.resolve(reference, EntityType.DOCUMENT);
EntityReference docRef = ref.extractReference(EntityType.DOCUMENT);
if (docRef != null) {
// return the syntax of the document in this reference, regardless of the type of reference, obj prop or
// doc
return dab.getTranslatedDocumentInstance(new DocumentReference(docRef)).getSyntax().toIdString();
} else {
return dab.getDocumentSyntaxId(reference);
}
} catch (Exception e) {
throw new IOServiceException(
"An exception has occurred while getting the syntax of the source for " + reference, e);
}
}
@Override
public XDOM getXDOM(String reference) throws IOServiceException
{
return getXDOM(reference, null);
}
@Override
public XDOM getXDOM(String reference, String syntax) throws IOServiceException
{
String sourceSyntaxId = syntax;
// get if unspecified, get the source from the io service
if (sourceSyntaxId == null) {
sourceSyntaxId = getSourceSyntax(reference);
}
try {
EntityReference ref = referenceResolver.resolve(reference, EntityType.DOCUMENT);
if (ref.getType() == EntityType.OBJECT_PROPERTY) {
return getTransformedXDOM(getObjectPropertyContent(new ObjectPropertyReference(ref)), sourceSyntaxId);
} else if (ref.getType() == EntityType.DOCUMENT) {
return getDocumentXDOM(new DocumentReference(ref));
} else {
// it was parsed as something else, just ignore the parsing and get the document content as its initial
// name was
return getTransformedXDOM(dab.getDocumentContent(reference), sourceSyntaxId);
}
} catch (Exception e) {
throw new IOServiceException("An exception has occurred while getting the XDOM for " + reference, e);
}
}
private XDOM getDocumentXDOM(DocumentReference reference) throws Exception
{
DocumentDisplayerParameters parameters = new DocumentDisplayerParameters();
parameters.setExecutionContextIsolated(true);
parameters.setContentTranslated(true);
parameters.setTargetSyntax(renderingContext.getTargetSyntax());
return documentDisplayer.display(dab.getDocumentInstance(reference), parameters);
}
private XDOM getTransformedXDOM(String content, String sourceSyntaxId)
throws ParseException, org.xwiki.component.manager.ComponentLookupException, TransformationException
{
Parser parser = componentManager.getInstance(Parser.class, sourceSyntaxId);
XDOM xdom = parser.parse(new StringReader(content));
// run transformations
TransformationContext txContext =
new TransformationContext(xdom, Syntax.valueOf(sourceSyntaxId));
TransformationManager transformationManager = componentManager.getInstance(TransformationManager.class);
transformationManager.performTransformations(xdom, txContext);
return xdom;
}
private String getObjectPropertyContent(ObjectPropertyReference reference)
{
BaseObjectReference objRef = new BaseObjectReference(reference.getParent());
DocumentReference docRef = new DocumentReference(objRef.getParent());
if (objRef.getObjectNumber() != null) {
return dab.getProperty(docRef, objRef.getXClassReference(), objRef.getObjectNumber(), reference.getName())
.toString();
} else {
return dab.getProperty(docRef, objRef.getXClassReference(), reference.getName()).toString();
}
}
}
| {
"pile_set_name": "Github"
} |
module.exports = require("./lib/_stream_transform.js")
| {
"pile_set_name": "Github"
} |
/* Copyright (C) Microsoft 2014. All rights reserved. */
(function() {
"use strict";
var ucwa = window.site.ucwa;
function handleGetSingleContacts(data) {
if (data.results !== undefined) {
var contacts = data.results._embedded.contact;
if (contacts !== undefined && !ucwa.GeneralHelper.isEmpty(contacts)) {
if ($.isArray(contacts)) {
for (var contact in contacts) {
var contactText = contacts[contact].name ? contacts[contact].name : "Contact: " + contact;
$("#singleContactsList").append($("<option></option>", { value: contacts[contact]._links.self.href }).text(contactText));
}
} else {
var contactText = contacts[contact].name ? contacts[contact].name : "Contact: " + contact;
$("#singleContactsList").append($("<option></option>", { value: contacts._links.self.href }).text(contactText));
}
$("#singleContactsList").show();
$("#getSingleContact").removeClass("idleAnchor");
} else {
alert("No contacts found!");
}
}
$("#singleContactsList").show();
$("#getSingleContact").removeClass("idleAnchor");
}
function handleSingleContact(data) {
if (data.results !== undefined) {
var contact = data.results;
$("#singleContact").html($("#contact-template").tmpl({
name: contact.name,
email: contact.emailAddresses ? contact.emailAddresses[0] : "(None)",
image: contact._links.contactPhoto ? ucwa.Transport.getDomain() + contact._links.contactPhoto.href : null
}));
}
}
$("#getSingleContacts").click(function() {
$("#singleContactsList").html("");
ucwa.Cache.read({
id: "main"
}).done(function(cacheData) {
ucwa.Transport.clientRequest({
url: cacheData._embedded.people._links.myContacts.href,
type: "get",
callback: handleGetSingleContacts
});
});
return false;
});
$("#getSingleContact").click(function() {
if ($("#singleContactsList option:selected").length === 1 && !$("#getSingleContact").hasClass("idleAnchor")) {
ucwa.Transport.clientRequest({
url: $("#singleContactsList option:selected").val(),
type: "get",
callback: handleSingleContact
});
}
return false;
});
$("#singleContactsList").hide();
}()); | {
"pile_set_name": "Github"
} |
function sparsity=spars(x)
% sparsity = sparse(x)
%
% Returns the sparsity of the matrix/vector x. It works for sparse and dense
% storage, too.
% This file is part of SeDuMi 1.1 by Imre Polik and Oleksandr Romanko
% Copyright (C) 2005 McMaster University, Hamilton, CANADA (since 1.1)
%
% Copyright (C) 2001 Jos F. Sturm (up to 1.05R5)
% Dept. Econometrics & O.R., Tilburg University, the Netherlands.
% Supported by the Netherlands Organization for Scientific Research (NWO).
%
% Affiliation SeDuMi 1.03 and 1.04Beta (2000):
% Dept. Quantitative Economics, Maastricht University, the Netherlands.
%
% Affiliations up to SeDuMi 1.02 (AUG1998):
% CRL, McMaster University, Canada.
% Supported by the Netherlands Organization for Scientific Research (NWO).
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
% 02110-1301, USA
if ~isempty(x)
sparsity=nnz(x)/numel(x);
else
sparsity=0;
end | {
"pile_set_name": "Github"
} |
/*
Copyright 2018 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// Code generated by client-gen. DO NOT EDIT.
package fake
import (
rbac_v1 "k8s.io/api/rbac/v1"
v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
labels "k8s.io/apimachinery/pkg/labels"
schema "k8s.io/apimachinery/pkg/runtime/schema"
types "k8s.io/apimachinery/pkg/types"
watch "k8s.io/apimachinery/pkg/watch"
testing "k8s.io/client-go/testing"
)
// FakeRoles implements RoleInterface
type FakeRoles struct {
Fake *FakeRbacV1
ns string
}
var rolesResource = schema.GroupVersionResource{Group: "rbac.authorization.k8s.io", Version: "v1", Resource: "roles"}
var rolesKind = schema.GroupVersionKind{Group: "rbac.authorization.k8s.io", Version: "v1", Kind: "Role"}
// Get takes name of the role, and returns the corresponding role object, and an error if there is any.
func (c *FakeRoles) Get(name string, options v1.GetOptions) (result *rbac_v1.Role, err error) {
obj, err := c.Fake.
Invokes(testing.NewGetAction(rolesResource, c.ns, name), &rbac_v1.Role{})
if obj == nil {
return nil, err
}
return obj.(*rbac_v1.Role), err
}
// List takes label and field selectors, and returns the list of Roles that match those selectors.
func (c *FakeRoles) List(opts v1.ListOptions) (result *rbac_v1.RoleList, err error) {
obj, err := c.Fake.
Invokes(testing.NewListAction(rolesResource, rolesKind, c.ns, opts), &rbac_v1.RoleList{})
if obj == nil {
return nil, err
}
label, _, _ := testing.ExtractFromListOptions(opts)
if label == nil {
label = labels.Everything()
}
list := &rbac_v1.RoleList{}
for _, item := range obj.(*rbac_v1.RoleList).Items {
if label.Matches(labels.Set(item.Labels)) {
list.Items = append(list.Items, item)
}
}
return list, err
}
// Watch returns a watch.Interface that watches the requested roles.
func (c *FakeRoles) Watch(opts v1.ListOptions) (watch.Interface, error) {
return c.Fake.
InvokesWatch(testing.NewWatchAction(rolesResource, c.ns, opts))
}
// Create takes the representation of a role and creates it. Returns the server's representation of the role, and an error, if there is any.
func (c *FakeRoles) Create(role *rbac_v1.Role) (result *rbac_v1.Role, err error) {
obj, err := c.Fake.
Invokes(testing.NewCreateAction(rolesResource, c.ns, role), &rbac_v1.Role{})
if obj == nil {
return nil, err
}
return obj.(*rbac_v1.Role), err
}
// Update takes the representation of a role and updates it. Returns the server's representation of the role, and an error, if there is any.
func (c *FakeRoles) Update(role *rbac_v1.Role) (result *rbac_v1.Role, err error) {
obj, err := c.Fake.
Invokes(testing.NewUpdateAction(rolesResource, c.ns, role), &rbac_v1.Role{})
if obj == nil {
return nil, err
}
return obj.(*rbac_v1.Role), err
}
// Delete takes name of the role and deletes it. Returns an error if one occurs.
func (c *FakeRoles) Delete(name string, options *v1.DeleteOptions) error {
_, err := c.Fake.
Invokes(testing.NewDeleteAction(rolesResource, c.ns, name), &rbac_v1.Role{})
return err
}
// DeleteCollection deletes a collection of objects.
func (c *FakeRoles) DeleteCollection(options *v1.DeleteOptions, listOptions v1.ListOptions) error {
action := testing.NewDeleteCollectionAction(rolesResource, c.ns, listOptions)
_, err := c.Fake.Invokes(action, &rbac_v1.RoleList{})
return err
}
// Patch applies the patch and returns the patched role.
func (c *FakeRoles) Patch(name string, pt types.PatchType, data []byte, subresources ...string) (result *rbac_v1.Role, err error) {
obj, err := c.Fake.
Invokes(testing.NewPatchSubresourceAction(rolesResource, c.ns, name, data, subresources...), &rbac_v1.Role{})
if obj == nil {
return nil, err
}
return obj.(*rbac_v1.Role), err
}
| {
"pile_set_name": "Github"
} |
var LazyWrapper = require('./_LazyWrapper');
/**
* Reverses the direction of lazy iteration.
*
* @private
* @name reverse
* @memberOf LazyWrapper
* @returns {Object} Returns the new reversed `LazyWrapper` object.
*/
function lazyReverse() {
if (this.__filtered__) {
var result = new LazyWrapper(this);
result.__dir__ = -1;
result.__filtered__ = true;
} else {
result = this.clone();
result.__dir__ *= -1;
}
return result;
}
module.exports = lazyReverse;
| {
"pile_set_name": "Github"
} |
// SPDX-License-Identifier: GPL-2.0
/*
* linux/mm/compaction.c
*
* Memory compaction for the reduction of external fragmentation. Note that
* this heavily depends upon page migration to do all the real heavy
* lifting
*
* Copyright IBM Corp. 2007-2010 Mel Gorman <mel@csn.ul.ie>
*/
#include <linux/cpu.h>
#include <linux/swap.h>
#include <linux/migrate.h>
#include <linux/compaction.h>
#include <linux/mm_inline.h>
#include <linux/sched/signal.h>
#include <linux/backing-dev.h>
#include <linux/sysctl.h>
#include <linux/sysfs.h>
#include <linux/page-isolation.h>
#include <linux/kasan.h>
#include <linux/kthread.h>
#include <linux/freezer.h>
#include <linux/page_owner.h>
#include <linux/psi.h>
#include "internal.h"
#ifdef CONFIG_COMPACTION
static inline void count_compact_event(enum vm_event_item item)
{
count_vm_event(item);
}
static inline void count_compact_events(enum vm_event_item item, long delta)
{
count_vm_events(item, delta);
}
#else
#define count_compact_event(item) do { } while (0)
#define count_compact_events(item, delta) do { } while (0)
#endif
#if defined CONFIG_COMPACTION || defined CONFIG_CMA
#define CREATE_TRACE_POINTS
#include <trace/events/compaction.h>
#define block_start_pfn(pfn, order) round_down(pfn, 1UL << (order))
#define block_end_pfn(pfn, order) ALIGN((pfn) + 1, 1UL << (order))
#define pageblock_start_pfn(pfn) block_start_pfn(pfn, pageblock_order)
#define pageblock_end_pfn(pfn) block_end_pfn(pfn, pageblock_order)
/*
* Fragmentation score check interval for proactive compaction purposes.
*/
static const unsigned int HPAGE_FRAG_CHECK_INTERVAL_MSEC = 500;
/*
* Page order with-respect-to which proactive compaction
* calculates external fragmentation, which is used as
* the "fragmentation score" of a node/zone.
*/
#if defined CONFIG_TRANSPARENT_HUGEPAGE
#define COMPACTION_HPAGE_ORDER HPAGE_PMD_ORDER
#elif defined CONFIG_HUGETLBFS
#define COMPACTION_HPAGE_ORDER HUGETLB_PAGE_ORDER
#else
#define COMPACTION_HPAGE_ORDER (PMD_SHIFT - PAGE_SHIFT)
#endif
static unsigned long release_freepages(struct list_head *freelist)
{
struct page *page, *next;
unsigned long high_pfn = 0;
list_for_each_entry_safe(page, next, freelist, lru) {
unsigned long pfn = page_to_pfn(page);
list_del(&page->lru);
__free_page(page);
if (pfn > high_pfn)
high_pfn = pfn;
}
return high_pfn;
}
static void split_map_pages(struct list_head *list)
{
unsigned int i, order, nr_pages;
struct page *page, *next;
LIST_HEAD(tmp_list);
list_for_each_entry_safe(page, next, list, lru) {
list_del(&page->lru);
order = page_private(page);
nr_pages = 1 << order;
post_alloc_hook(page, order, __GFP_MOVABLE);
if (order)
split_page(page, order);
for (i = 0; i < nr_pages; i++) {
list_add(&page->lru, &tmp_list);
page++;
}
}
list_splice(&tmp_list, list);
}
#ifdef CONFIG_COMPACTION
int PageMovable(struct page *page)
{
struct address_space *mapping;
VM_BUG_ON_PAGE(!PageLocked(page), page);
if (!__PageMovable(page))
return 0;
mapping = page_mapping(page);
if (mapping && mapping->a_ops && mapping->a_ops->isolate_page)
return 1;
return 0;
}
EXPORT_SYMBOL(PageMovable);
void __SetPageMovable(struct page *page, struct address_space *mapping)
{
VM_BUG_ON_PAGE(!PageLocked(page), page);
VM_BUG_ON_PAGE((unsigned long)mapping & PAGE_MAPPING_MOVABLE, page);
page->mapping = (void *)((unsigned long)mapping | PAGE_MAPPING_MOVABLE);
}
EXPORT_SYMBOL(__SetPageMovable);
void __ClearPageMovable(struct page *page)
{
VM_BUG_ON_PAGE(!PageLocked(page), page);
VM_BUG_ON_PAGE(!PageMovable(page), page);
/*
* Clear registered address_space val with keeping PAGE_MAPPING_MOVABLE
* flag so that VM can catch up released page by driver after isolation.
* With it, VM migration doesn't try to put it back.
*/
page->mapping = (void *)((unsigned long)page->mapping &
PAGE_MAPPING_MOVABLE);
}
EXPORT_SYMBOL(__ClearPageMovable);
/* Do not skip compaction more than 64 times */
#define COMPACT_MAX_DEFER_SHIFT 6
/*
* Compaction is deferred when compaction fails to result in a page
* allocation success. 1 << compact_defer_shift, compactions are skipped up
* to a limit of 1 << COMPACT_MAX_DEFER_SHIFT
*/
void defer_compaction(struct zone *zone, int order)
{
zone->compact_considered = 0;
zone->compact_defer_shift++;
if (order < zone->compact_order_failed)
zone->compact_order_failed = order;
if (zone->compact_defer_shift > COMPACT_MAX_DEFER_SHIFT)
zone->compact_defer_shift = COMPACT_MAX_DEFER_SHIFT;
trace_mm_compaction_defer_compaction(zone, order);
}
/* Returns true if compaction should be skipped this time */
bool compaction_deferred(struct zone *zone, int order)
{
unsigned long defer_limit = 1UL << zone->compact_defer_shift;
if (order < zone->compact_order_failed)
return false;
/* Avoid possible overflow */
if (++zone->compact_considered > defer_limit)
zone->compact_considered = defer_limit;
if (zone->compact_considered >= defer_limit)
return false;
trace_mm_compaction_deferred(zone, order);
return true;
}
/*
* Update defer tracking counters after successful compaction of given order,
* which means an allocation either succeeded (alloc_success == true) or is
* expected to succeed.
*/
void compaction_defer_reset(struct zone *zone, int order,
bool alloc_success)
{
if (alloc_success) {
zone->compact_considered = 0;
zone->compact_defer_shift = 0;
}
if (order >= zone->compact_order_failed)
zone->compact_order_failed = order + 1;
trace_mm_compaction_defer_reset(zone, order);
}
/* Returns true if restarting compaction after many failures */
bool compaction_restarting(struct zone *zone, int order)
{
if (order < zone->compact_order_failed)
return false;
return zone->compact_defer_shift == COMPACT_MAX_DEFER_SHIFT &&
zone->compact_considered >= 1UL << zone->compact_defer_shift;
}
/* Returns true if the pageblock should be scanned for pages to isolate. */
static inline bool isolation_suitable(struct compact_control *cc,
struct page *page)
{
if (cc->ignore_skip_hint)
return true;
return !get_pageblock_skip(page);
}
static void reset_cached_positions(struct zone *zone)
{
zone->compact_cached_migrate_pfn[0] = zone->zone_start_pfn;
zone->compact_cached_migrate_pfn[1] = zone->zone_start_pfn;
zone->compact_cached_free_pfn =
pageblock_start_pfn(zone_end_pfn(zone) - 1);
}
/*
* Compound pages of >= pageblock_order should consistenly be skipped until
* released. It is always pointless to compact pages of such order (if they are
* migratable), and the pageblocks they occupy cannot contain any free pages.
*/
static bool pageblock_skip_persistent(struct page *page)
{
if (!PageCompound(page))
return false;
page = compound_head(page);
if (compound_order(page) >= pageblock_order)
return true;
return false;
}
static bool
__reset_isolation_pfn(struct zone *zone, unsigned long pfn, bool check_source,
bool check_target)
{
struct page *page = pfn_to_online_page(pfn);
struct page *block_page;
struct page *end_page;
unsigned long block_pfn;
if (!page)
return false;
if (zone != page_zone(page))
return false;
if (pageblock_skip_persistent(page))
return false;
/*
* If skip is already cleared do no further checking once the
* restart points have been set.
*/
if (check_source && check_target && !get_pageblock_skip(page))
return true;
/*
* If clearing skip for the target scanner, do not select a
* non-movable pageblock as the starting point.
*/
if (!check_source && check_target &&
get_pageblock_migratetype(page) != MIGRATE_MOVABLE)
return false;
/* Ensure the start of the pageblock or zone is online and valid */
block_pfn = pageblock_start_pfn(pfn);
block_pfn = max(block_pfn, zone->zone_start_pfn);
block_page = pfn_to_online_page(block_pfn);
if (block_page) {
page = block_page;
pfn = block_pfn;
}
/* Ensure the end of the pageblock or zone is online and valid */
block_pfn = pageblock_end_pfn(pfn) - 1;
block_pfn = min(block_pfn, zone_end_pfn(zone) - 1);
end_page = pfn_to_online_page(block_pfn);
if (!end_page)
return false;
/*
* Only clear the hint if a sample indicates there is either a
* free page or an LRU page in the block. One or other condition
* is necessary for the block to be a migration source/target.
*/
do {
if (pfn_valid_within(pfn)) {
if (check_source && PageLRU(page)) {
clear_pageblock_skip(page);
return true;
}
if (check_target && PageBuddy(page)) {
clear_pageblock_skip(page);
return true;
}
}
page += (1 << PAGE_ALLOC_COSTLY_ORDER);
pfn += (1 << PAGE_ALLOC_COSTLY_ORDER);
} while (page <= end_page);
return false;
}
/*
* This function is called to clear all cached information on pageblocks that
* should be skipped for page isolation when the migrate and free page scanner
* meet.
*/
static void __reset_isolation_suitable(struct zone *zone)
{
unsigned long migrate_pfn = zone->zone_start_pfn;
unsigned long free_pfn = zone_end_pfn(zone) - 1;
unsigned long reset_migrate = free_pfn;
unsigned long reset_free = migrate_pfn;
bool source_set = false;
bool free_set = false;
if (!zone->compact_blockskip_flush)
return;
zone->compact_blockskip_flush = false;
/*
* Walk the zone and update pageblock skip information. Source looks
* for PageLRU while target looks for PageBuddy. When the scanner
* is found, both PageBuddy and PageLRU are checked as the pageblock
* is suitable as both source and target.
*/
for (; migrate_pfn < free_pfn; migrate_pfn += pageblock_nr_pages,
free_pfn -= pageblock_nr_pages) {
cond_resched();
/* Update the migrate PFN */
if (__reset_isolation_pfn(zone, migrate_pfn, true, source_set) &&
migrate_pfn < reset_migrate) {
source_set = true;
reset_migrate = migrate_pfn;
zone->compact_init_migrate_pfn = reset_migrate;
zone->compact_cached_migrate_pfn[0] = reset_migrate;
zone->compact_cached_migrate_pfn[1] = reset_migrate;
}
/* Update the free PFN */
if (__reset_isolation_pfn(zone, free_pfn, free_set, true) &&
free_pfn > reset_free) {
free_set = true;
reset_free = free_pfn;
zone->compact_init_free_pfn = reset_free;
zone->compact_cached_free_pfn = reset_free;
}
}
/* Leave no distance if no suitable block was reset */
if (reset_migrate >= reset_free) {
zone->compact_cached_migrate_pfn[0] = migrate_pfn;
zone->compact_cached_migrate_pfn[1] = migrate_pfn;
zone->compact_cached_free_pfn = free_pfn;
}
}
void reset_isolation_suitable(pg_data_t *pgdat)
{
int zoneid;
for (zoneid = 0; zoneid < MAX_NR_ZONES; zoneid++) {
struct zone *zone = &pgdat->node_zones[zoneid];
if (!populated_zone(zone))
continue;
/* Only flush if a full compaction finished recently */
if (zone->compact_blockskip_flush)
__reset_isolation_suitable(zone);
}
}
/*
* Sets the pageblock skip bit if it was clear. Note that this is a hint as
* locks are not required for read/writers. Returns true if it was already set.
*/
static bool test_and_set_skip(struct compact_control *cc, struct page *page,
unsigned long pfn)
{
bool skip;
/* Do no update if skip hint is being ignored */
if (cc->ignore_skip_hint)
return false;
if (!IS_ALIGNED(pfn, pageblock_nr_pages))
return false;
skip = get_pageblock_skip(page);
if (!skip && !cc->no_set_skip_hint)
set_pageblock_skip(page);
return skip;
}
static void update_cached_migrate(struct compact_control *cc, unsigned long pfn)
{
struct zone *zone = cc->zone;
pfn = pageblock_end_pfn(pfn);
/* Set for isolation rather than compaction */
if (cc->no_set_skip_hint)
return;
if (pfn > zone->compact_cached_migrate_pfn[0])
zone->compact_cached_migrate_pfn[0] = pfn;
if (cc->mode != MIGRATE_ASYNC &&
pfn > zone->compact_cached_migrate_pfn[1])
zone->compact_cached_migrate_pfn[1] = pfn;
}
/*
* If no pages were isolated then mark this pageblock to be skipped in the
* future. The information is later cleared by __reset_isolation_suitable().
*/
static void update_pageblock_skip(struct compact_control *cc,
struct page *page, unsigned long pfn)
{
struct zone *zone = cc->zone;
if (cc->no_set_skip_hint)
return;
if (!page)
return;
set_pageblock_skip(page);
/* Update where async and sync compaction should restart */
if (pfn < zone->compact_cached_free_pfn)
zone->compact_cached_free_pfn = pfn;
}
#else
static inline bool isolation_suitable(struct compact_control *cc,
struct page *page)
{
return true;
}
static inline bool pageblock_skip_persistent(struct page *page)
{
return false;
}
static inline void update_pageblock_skip(struct compact_control *cc,
struct page *page, unsigned long pfn)
{
}
static void update_cached_migrate(struct compact_control *cc, unsigned long pfn)
{
}
static bool test_and_set_skip(struct compact_control *cc, struct page *page,
unsigned long pfn)
{
return false;
}
#endif /* CONFIG_COMPACTION */
/*
* Compaction requires the taking of some coarse locks that are potentially
* very heavily contended. For async compaction, trylock and record if the
* lock is contended. The lock will still be acquired but compaction will
* abort when the current block is finished regardless of success rate.
* Sync compaction acquires the lock.
*
* Always returns true which makes it easier to track lock state in callers.
*/
static bool compact_lock_irqsave(spinlock_t *lock, unsigned long *flags,
struct compact_control *cc)
__acquires(lock)
{
/* Track if the lock is contended in async mode */
if (cc->mode == MIGRATE_ASYNC && !cc->contended) {
if (spin_trylock_irqsave(lock, *flags))
return true;
cc->contended = true;
}
spin_lock_irqsave(lock, *flags);
return true;
}
/*
* Compaction requires the taking of some coarse locks that are potentially
* very heavily contended. The lock should be periodically unlocked to avoid
* having disabled IRQs for a long time, even when there is nobody waiting on
* the lock. It might also be that allowing the IRQs will result in
* need_resched() becoming true. If scheduling is needed, async compaction
* aborts. Sync compaction schedules.
* Either compaction type will also abort if a fatal signal is pending.
* In either case if the lock was locked, it is dropped and not regained.
*
* Returns true if compaction should abort due to fatal signal pending, or
* async compaction due to need_resched()
* Returns false when compaction can continue (sync compaction might have
* scheduled)
*/
static bool compact_unlock_should_abort(spinlock_t *lock,
unsigned long flags, bool *locked, struct compact_control *cc)
{
if (*locked) {
spin_unlock_irqrestore(lock, flags);
*locked = false;
}
if (fatal_signal_pending(current)) {
cc->contended = true;
return true;
}
cond_resched();
return false;
}
/*
* Isolate free pages onto a private freelist. If @strict is true, will abort
* returning 0 on any invalid PFNs or non-free pages inside of the pageblock
* (even though it may still end up isolating some pages).
*/
static unsigned long isolate_freepages_block(struct compact_control *cc,
unsigned long *start_pfn,
unsigned long end_pfn,
struct list_head *freelist,
unsigned int stride,
bool strict)
{
int nr_scanned = 0, total_isolated = 0;
struct page *cursor;
unsigned long flags = 0;
bool locked = false;
unsigned long blockpfn = *start_pfn;
unsigned int order;
/* Strict mode is for isolation, speed is secondary */
if (strict)
stride = 1;
cursor = pfn_to_page(blockpfn);
/* Isolate free pages. */
for (; blockpfn < end_pfn; blockpfn += stride, cursor += stride) {
int isolated;
struct page *page = cursor;
/*
* Periodically drop the lock (if held) regardless of its
* contention, to give chance to IRQs. Abort if fatal signal
* pending or async compaction detects need_resched()
*/
if (!(blockpfn % SWAP_CLUSTER_MAX)
&& compact_unlock_should_abort(&cc->zone->lock, flags,
&locked, cc))
break;
nr_scanned++;
if (!pfn_valid_within(blockpfn))
goto isolate_fail;
/*
* For compound pages such as THP and hugetlbfs, we can save
* potentially a lot of iterations if we skip them at once.
* The check is racy, but we can consider only valid values
* and the only danger is skipping too much.
*/
if (PageCompound(page)) {
const unsigned int order = compound_order(page);
if (likely(order < MAX_ORDER)) {
blockpfn += (1UL << order) - 1;
cursor += (1UL << order) - 1;
}
goto isolate_fail;
}
if (!PageBuddy(page))
goto isolate_fail;
/*
* If we already hold the lock, we can skip some rechecking.
* Note that if we hold the lock now, checked_pageblock was
* already set in some previous iteration (or strict is true),
* so it is correct to skip the suitable migration target
* recheck as well.
*/
if (!locked) {
locked = compact_lock_irqsave(&cc->zone->lock,
&flags, cc);
/* Recheck this is a buddy page under lock */
if (!PageBuddy(page))
goto isolate_fail;
}
/* Found a free page, will break it into order-0 pages */
order = page_order(page);
isolated = __isolate_free_page(page, order);
if (!isolated)
break;
set_page_private(page, order);
total_isolated += isolated;
cc->nr_freepages += isolated;
list_add_tail(&page->lru, freelist);
if (!strict && cc->nr_migratepages <= cc->nr_freepages) {
blockpfn += isolated;
break;
}
/* Advance to the end of split page */
blockpfn += isolated - 1;
cursor += isolated - 1;
continue;
isolate_fail:
if (strict)
break;
else
continue;
}
if (locked)
spin_unlock_irqrestore(&cc->zone->lock, flags);
/*
* There is a tiny chance that we have read bogus compound_order(),
* so be careful to not go outside of the pageblock.
*/
if (unlikely(blockpfn > end_pfn))
blockpfn = end_pfn;
trace_mm_compaction_isolate_freepages(*start_pfn, blockpfn,
nr_scanned, total_isolated);
/* Record how far we have got within the block */
*start_pfn = blockpfn;
/*
* If strict isolation is requested by CMA then check that all the
* pages requested were isolated. If there were any failures, 0 is
* returned and CMA will fail.
*/
if (strict && blockpfn < end_pfn)
total_isolated = 0;
cc->total_free_scanned += nr_scanned;
if (total_isolated)
count_compact_events(COMPACTISOLATED, total_isolated);
return total_isolated;
}
/**
* isolate_freepages_range() - isolate free pages.
* @cc: Compaction control structure.
* @start_pfn: The first PFN to start isolating.
* @end_pfn: The one-past-last PFN.
*
* Non-free pages, invalid PFNs, or zone boundaries within the
* [start_pfn, end_pfn) range are considered errors, cause function to
* undo its actions and return zero.
*
* Otherwise, function returns one-past-the-last PFN of isolated page
* (which may be greater then end_pfn if end fell in a middle of
* a free page).
*/
unsigned long
isolate_freepages_range(struct compact_control *cc,
unsigned long start_pfn, unsigned long end_pfn)
{
unsigned long isolated, pfn, block_start_pfn, block_end_pfn;
LIST_HEAD(freelist);
pfn = start_pfn;
block_start_pfn = pageblock_start_pfn(pfn);
if (block_start_pfn < cc->zone->zone_start_pfn)
block_start_pfn = cc->zone->zone_start_pfn;
block_end_pfn = pageblock_end_pfn(pfn);
for (; pfn < end_pfn; pfn += isolated,
block_start_pfn = block_end_pfn,
block_end_pfn += pageblock_nr_pages) {
/* Protect pfn from changing by isolate_freepages_block */
unsigned long isolate_start_pfn = pfn;
block_end_pfn = min(block_end_pfn, end_pfn);
/*
* pfn could pass the block_end_pfn if isolated freepage
* is more than pageblock order. In this case, we adjust
* scanning range to right one.
*/
if (pfn >= block_end_pfn) {
block_start_pfn = pageblock_start_pfn(pfn);
block_end_pfn = pageblock_end_pfn(pfn);
block_end_pfn = min(block_end_pfn, end_pfn);
}
if (!pageblock_pfn_to_page(block_start_pfn,
block_end_pfn, cc->zone))
break;
isolated = isolate_freepages_block(cc, &isolate_start_pfn,
block_end_pfn, &freelist, 0, true);
/*
* In strict mode, isolate_freepages_block() returns 0 if
* there are any holes in the block (ie. invalid PFNs or
* non-free pages).
*/
if (!isolated)
break;
/*
* If we managed to isolate pages, it is always (1 << n) *
* pageblock_nr_pages for some non-negative n. (Max order
* page may span two pageblocks).
*/
}
/* __isolate_free_page() does not map the pages */
split_map_pages(&freelist);
if (pfn < end_pfn) {
/* Loop terminated early, cleanup. */
release_freepages(&freelist);
return 0;
}
/* We don't use freelists for anything. */
return pfn;
}
/* Similar to reclaim, but different enough that they don't share logic */
static bool too_many_isolated(pg_data_t *pgdat)
{
unsigned long active, inactive, isolated;
inactive = node_page_state(pgdat, NR_INACTIVE_FILE) +
node_page_state(pgdat, NR_INACTIVE_ANON);
active = node_page_state(pgdat, NR_ACTIVE_FILE) +
node_page_state(pgdat, NR_ACTIVE_ANON);
isolated = node_page_state(pgdat, NR_ISOLATED_FILE) +
node_page_state(pgdat, NR_ISOLATED_ANON);
return isolated > (inactive + active) / 2;
}
/**
* isolate_migratepages_block() - isolate all migrate-able pages within
* a single pageblock
* @cc: Compaction control structure.
* @low_pfn: The first PFN to isolate
* @end_pfn: The one-past-the-last PFN to isolate, within same pageblock
* @isolate_mode: Isolation mode to be used.
*
* Isolate all pages that can be migrated from the range specified by
* [low_pfn, end_pfn). The range is expected to be within same pageblock.
* Returns zero if there is a fatal signal pending, otherwise PFN of the
* first page that was not scanned (which may be both less, equal to or more
* than end_pfn).
*
* The pages are isolated on cc->migratepages list (not required to be empty),
* and cc->nr_migratepages is updated accordingly. The cc->migrate_pfn field
* is neither read nor updated.
*/
static unsigned long
isolate_migratepages_block(struct compact_control *cc, unsigned long low_pfn,
unsigned long end_pfn, isolate_mode_t isolate_mode)
{
pg_data_t *pgdat = cc->zone->zone_pgdat;
unsigned long nr_scanned = 0, nr_isolated = 0;
struct lruvec *lruvec;
unsigned long flags = 0;
bool locked = false;
struct page *page = NULL, *valid_page = NULL;
unsigned long start_pfn = low_pfn;
bool skip_on_failure = false;
unsigned long next_skip_pfn = 0;
bool skip_updated = false;
/*
* Ensure that there are not too many pages isolated from the LRU
* list by either parallel reclaimers or compaction. If there are,
* delay for some time until fewer pages are isolated
*/
while (unlikely(too_many_isolated(pgdat))) {
/* async migration should just abort */
if (cc->mode == MIGRATE_ASYNC)
return 0;
congestion_wait(BLK_RW_ASYNC, HZ/10);
if (fatal_signal_pending(current))
return 0;
}
cond_resched();
if (cc->direct_compaction && (cc->mode == MIGRATE_ASYNC)) {
skip_on_failure = true;
next_skip_pfn = block_end_pfn(low_pfn, cc->order);
}
/* Time to isolate some pages for migration */
for (; low_pfn < end_pfn; low_pfn++) {
if (skip_on_failure && low_pfn >= next_skip_pfn) {
/*
* We have isolated all migration candidates in the
* previous order-aligned block, and did not skip it due
* to failure. We should migrate the pages now and
* hopefully succeed compaction.
*/
if (nr_isolated)
break;
/*
* We failed to isolate in the previous order-aligned
* block. Set the new boundary to the end of the
* current block. Note we can't simply increase
* next_skip_pfn by 1 << order, as low_pfn might have
* been incremented by a higher number due to skipping
* a compound or a high-order buddy page in the
* previous loop iteration.
*/
next_skip_pfn = block_end_pfn(low_pfn, cc->order);
}
/*
* Periodically drop the lock (if held) regardless of its
* contention, to give chance to IRQs. Abort completely if
* a fatal signal is pending.
*/
if (!(low_pfn % SWAP_CLUSTER_MAX)
&& compact_unlock_should_abort(&pgdat->lru_lock,
flags, &locked, cc)) {
low_pfn = 0;
goto fatal_pending;
}
if (!pfn_valid_within(low_pfn))
goto isolate_fail;
nr_scanned++;
page = pfn_to_page(low_pfn);
/*
* Check if the pageblock has already been marked skipped.
* Only the aligned PFN is checked as the caller isolates
* COMPACT_CLUSTER_MAX at a time so the second call must
* not falsely conclude that the block should be skipped.
*/
if (!valid_page && IS_ALIGNED(low_pfn, pageblock_nr_pages)) {
if (!cc->ignore_skip_hint && get_pageblock_skip(page)) {
low_pfn = end_pfn;
goto isolate_abort;
}
valid_page = page;
}
/*
* Skip if free. We read page order here without zone lock
* which is generally unsafe, but the race window is small and
* the worst thing that can happen is that we skip some
* potential isolation targets.
*/
if (PageBuddy(page)) {
unsigned long freepage_order = page_order_unsafe(page);
/*
* Without lock, we cannot be sure that what we got is
* a valid page order. Consider only values in the
* valid order range to prevent low_pfn overflow.
*/
if (freepage_order > 0 && freepage_order < MAX_ORDER)
low_pfn += (1UL << freepage_order) - 1;
continue;
}
/*
* Regardless of being on LRU, compound pages such as THP and
* hugetlbfs are not to be compacted unless we are attempting
* an allocation much larger than the huge page size (eg CMA).
* We can potentially save a lot of iterations if we skip them
* at once. The check is racy, but we can consider only valid
* values and the only danger is skipping too much.
*/
if (PageCompound(page) && !cc->alloc_contig) {
const unsigned int order = compound_order(page);
if (likely(order < MAX_ORDER))
low_pfn += (1UL << order) - 1;
goto isolate_fail;
}
/*
* Check may be lockless but that's ok as we recheck later.
* It's possible to migrate LRU and non-lru movable pages.
* Skip any other type of page
*/
if (!PageLRU(page)) {
/*
* __PageMovable can return false positive so we need
* to verify it under page_lock.
*/
if (unlikely(__PageMovable(page)) &&
!PageIsolated(page)) {
if (locked) {
spin_unlock_irqrestore(&pgdat->lru_lock,
flags);
locked = false;
}
if (!isolate_movable_page(page, isolate_mode))
goto isolate_success;
}
goto isolate_fail;
}
/*
* Migration will fail if an anonymous page is pinned in memory,
* so avoid taking lru_lock and isolating it unnecessarily in an
* admittedly racy check.
*/
if (!page_mapping(page) &&
page_count(page) > page_mapcount(page))
goto isolate_fail;
/*
* Only allow to migrate anonymous pages in GFP_NOFS context
* because those do not depend on fs locks.
*/
if (!(cc->gfp_mask & __GFP_FS) && page_mapping(page))
goto isolate_fail;
/* If we already hold the lock, we can skip some rechecking */
if (!locked) {
locked = compact_lock_irqsave(&pgdat->lru_lock,
&flags, cc);
/* Try get exclusive access under lock */
if (!skip_updated) {
skip_updated = true;
if (test_and_set_skip(cc, page, low_pfn))
goto isolate_abort;
}
/* Recheck PageLRU and PageCompound under lock */
if (!PageLRU(page))
goto isolate_fail;
/*
* Page become compound since the non-locked check,
* and it's on LRU. It can only be a THP so the order
* is safe to read and it's 0 for tail pages.
*/
if (unlikely(PageCompound(page) && !cc->alloc_contig)) {
low_pfn += compound_nr(page) - 1;
goto isolate_fail;
}
}
lruvec = mem_cgroup_page_lruvec(page, pgdat);
/* Try isolate the page */
if (__isolate_lru_page(page, isolate_mode) != 0)
goto isolate_fail;
/* The whole page is taken off the LRU; skip the tail pages. */
if (PageCompound(page))
low_pfn += compound_nr(page) - 1;
/* Successfully isolated */
del_page_from_lru_list(page, lruvec, page_lru(page));
mod_node_page_state(page_pgdat(page),
NR_ISOLATED_ANON + page_is_file_lru(page),
thp_nr_pages(page));
isolate_success:
list_add(&page->lru, &cc->migratepages);
cc->nr_migratepages++;
nr_isolated++;
/*
* Avoid isolating too much unless this block is being
* rescanned (e.g. dirty/writeback pages, parallel allocation)
* or a lock is contended. For contention, isolate quickly to
* potentially remove one source of contention.
*/
if (cc->nr_migratepages == COMPACT_CLUSTER_MAX &&
!cc->rescan && !cc->contended) {
++low_pfn;
break;
}
continue;
isolate_fail:
if (!skip_on_failure)
continue;
/*
* We have isolated some pages, but then failed. Release them
* instead of migrating, as we cannot form the cc->order buddy
* page anyway.
*/
if (nr_isolated) {
if (locked) {
spin_unlock_irqrestore(&pgdat->lru_lock, flags);
locked = false;
}
putback_movable_pages(&cc->migratepages);
cc->nr_migratepages = 0;
nr_isolated = 0;
}
if (low_pfn < next_skip_pfn) {
low_pfn = next_skip_pfn - 1;
/*
* The check near the loop beginning would have updated
* next_skip_pfn too, but this is a bit simpler.
*/
next_skip_pfn += 1UL << cc->order;
}
}
/*
* The PageBuddy() check could have potentially brought us outside
* the range to be scanned.
*/
if (unlikely(low_pfn > end_pfn))
low_pfn = end_pfn;
isolate_abort:
if (locked)
spin_unlock_irqrestore(&pgdat->lru_lock, flags);
/*
* Updated the cached scanner pfn once the pageblock has been scanned
* Pages will either be migrated in which case there is no point
* scanning in the near future or migration failed in which case the
* failure reason may persist. The block is marked for skipping if
* there were no pages isolated in the block or if the block is
* rescanned twice in a row.
*/
if (low_pfn == end_pfn && (!nr_isolated || cc->rescan)) {
if (valid_page && !skip_updated)
set_pageblock_skip(valid_page);
update_cached_migrate(cc, low_pfn);
}
trace_mm_compaction_isolate_migratepages(start_pfn, low_pfn,
nr_scanned, nr_isolated);
fatal_pending:
cc->total_migrate_scanned += nr_scanned;
if (nr_isolated)
count_compact_events(COMPACTISOLATED, nr_isolated);
return low_pfn;
}
/**
* isolate_migratepages_range() - isolate migrate-able pages in a PFN range
* @cc: Compaction control structure.
* @start_pfn: The first PFN to start isolating.
* @end_pfn: The one-past-last PFN.
*
* Returns zero if isolation fails fatally due to e.g. pending signal.
* Otherwise, function returns one-past-the-last PFN of isolated page
* (which may be greater than end_pfn if end fell in a middle of a THP page).
*/
unsigned long
isolate_migratepages_range(struct compact_control *cc, unsigned long start_pfn,
unsigned long end_pfn)
{
unsigned long pfn, block_start_pfn, block_end_pfn;
/* Scan block by block. First and last block may be incomplete */
pfn = start_pfn;
block_start_pfn = pageblock_start_pfn(pfn);
if (block_start_pfn < cc->zone->zone_start_pfn)
block_start_pfn = cc->zone->zone_start_pfn;
block_end_pfn = pageblock_end_pfn(pfn);
for (; pfn < end_pfn; pfn = block_end_pfn,
block_start_pfn = block_end_pfn,
block_end_pfn += pageblock_nr_pages) {
block_end_pfn = min(block_end_pfn, end_pfn);
if (!pageblock_pfn_to_page(block_start_pfn,
block_end_pfn, cc->zone))
continue;
pfn = isolate_migratepages_block(cc, pfn, block_end_pfn,
ISOLATE_UNEVICTABLE);
if (!pfn)
break;
if (cc->nr_migratepages == COMPACT_CLUSTER_MAX)
break;
}
return pfn;
}
#endif /* CONFIG_COMPACTION || CONFIG_CMA */
#ifdef CONFIG_COMPACTION
static bool suitable_migration_source(struct compact_control *cc,
struct page *page)
{
int block_mt;
if (pageblock_skip_persistent(page))
return false;
if ((cc->mode != MIGRATE_ASYNC) || !cc->direct_compaction)
return true;
block_mt = get_pageblock_migratetype(page);
if (cc->migratetype == MIGRATE_MOVABLE)
return is_migrate_movable(block_mt);
else
return block_mt == cc->migratetype;
}
/* Returns true if the page is within a block suitable for migration to */
static bool suitable_migration_target(struct compact_control *cc,
struct page *page)
{
/* If the page is a large free page, then disallow migration */
if (PageBuddy(page)) {
/*
* We are checking page_order without zone->lock taken. But
* the only small danger is that we skip a potentially suitable
* pageblock, so it's not worth to check order for valid range.
*/
if (page_order_unsafe(page) >= pageblock_order)
return false;
}
if (cc->ignore_block_suitable)
return true;
/* If the block is MIGRATE_MOVABLE or MIGRATE_CMA, allow migration */
if (is_migrate_movable(get_pageblock_migratetype(page)))
return true;
/* Otherwise skip the block */
return false;
}
static inline unsigned int
freelist_scan_limit(struct compact_control *cc)
{
unsigned short shift = BITS_PER_LONG - 1;
return (COMPACT_CLUSTER_MAX >> min(shift, cc->fast_search_fail)) + 1;
}
/*
* Test whether the free scanner has reached the same or lower pageblock than
* the migration scanner, and compaction should thus terminate.
*/
static inline bool compact_scanners_met(struct compact_control *cc)
{
return (cc->free_pfn >> pageblock_order)
<= (cc->migrate_pfn >> pageblock_order);
}
/*
* Used when scanning for a suitable migration target which scans freelists
* in reverse. Reorders the list such as the unscanned pages are scanned
* first on the next iteration of the free scanner
*/
static void
move_freelist_head(struct list_head *freelist, struct page *freepage)
{
LIST_HEAD(sublist);
if (!list_is_last(freelist, &freepage->lru)) {
list_cut_before(&sublist, freelist, &freepage->lru);
if (!list_empty(&sublist))
list_splice_tail(&sublist, freelist);
}
}
/*
* Similar to move_freelist_head except used by the migration scanner
* when scanning forward. It's possible for these list operations to
* move against each other if they search the free list exactly in
* lockstep.
*/
static void
move_freelist_tail(struct list_head *freelist, struct page *freepage)
{
LIST_HEAD(sublist);
if (!list_is_first(freelist, &freepage->lru)) {
list_cut_position(&sublist, freelist, &freepage->lru);
if (!list_empty(&sublist))
list_splice_tail(&sublist, freelist);
}
}
static void
fast_isolate_around(struct compact_control *cc, unsigned long pfn, unsigned long nr_isolated)
{
unsigned long start_pfn, end_pfn;
struct page *page = pfn_to_page(pfn);
/* Do not search around if there are enough pages already */
if (cc->nr_freepages >= cc->nr_migratepages)
return;
/* Minimise scanning during async compaction */
if (cc->direct_compaction && cc->mode == MIGRATE_ASYNC)
return;
/* Pageblock boundaries */
start_pfn = pageblock_start_pfn(pfn);
end_pfn = min(pageblock_end_pfn(pfn), zone_end_pfn(cc->zone)) - 1;
/* Scan before */
if (start_pfn != pfn) {
isolate_freepages_block(cc, &start_pfn, pfn, &cc->freepages, 1, false);
if (cc->nr_freepages >= cc->nr_migratepages)
return;
}
/* Scan after */
start_pfn = pfn + nr_isolated;
if (start_pfn < end_pfn)
isolate_freepages_block(cc, &start_pfn, end_pfn, &cc->freepages, 1, false);
/* Skip this pageblock in the future as it's full or nearly full */
if (cc->nr_freepages < cc->nr_migratepages)
set_pageblock_skip(page);
}
/* Search orders in round-robin fashion */
static int next_search_order(struct compact_control *cc, int order)
{
order--;
if (order < 0)
order = cc->order - 1;
/* Search wrapped around? */
if (order == cc->search_order) {
cc->search_order--;
if (cc->search_order < 0)
cc->search_order = cc->order - 1;
return -1;
}
return order;
}
static unsigned long
fast_isolate_freepages(struct compact_control *cc)
{
unsigned int limit = min(1U, freelist_scan_limit(cc) >> 1);
unsigned int nr_scanned = 0;
unsigned long low_pfn, min_pfn, high_pfn = 0, highest = 0;
unsigned long nr_isolated = 0;
unsigned long distance;
struct page *page = NULL;
bool scan_start = false;
int order;
/* Full compaction passes in a negative order */
if (cc->order <= 0)
return cc->free_pfn;
/*
* If starting the scan, use a deeper search and use the highest
* PFN found if a suitable one is not found.
*/
if (cc->free_pfn >= cc->zone->compact_init_free_pfn) {
limit = pageblock_nr_pages >> 1;
scan_start = true;
}
/*
* Preferred point is in the top quarter of the scan space but take
* a pfn from the top half if the search is problematic.
*/
distance = (cc->free_pfn - cc->migrate_pfn);
low_pfn = pageblock_start_pfn(cc->free_pfn - (distance >> 2));
min_pfn = pageblock_start_pfn(cc->free_pfn - (distance >> 1));
if (WARN_ON_ONCE(min_pfn > low_pfn))
low_pfn = min_pfn;
/*
* Search starts from the last successful isolation order or the next
* order to search after a previous failure
*/
cc->search_order = min_t(unsigned int, cc->order - 1, cc->search_order);
for (order = cc->search_order;
!page && order >= 0;
order = next_search_order(cc, order)) {
struct free_area *area = &cc->zone->free_area[order];
struct list_head *freelist;
struct page *freepage;
unsigned long flags;
unsigned int order_scanned = 0;
if (!area->nr_free)
continue;
spin_lock_irqsave(&cc->zone->lock, flags);
freelist = &area->free_list[MIGRATE_MOVABLE];
list_for_each_entry_reverse(freepage, freelist, lru) {
unsigned long pfn;
order_scanned++;
nr_scanned++;
pfn = page_to_pfn(freepage);
if (pfn >= highest)
highest = pageblock_start_pfn(pfn);
if (pfn >= low_pfn) {
cc->fast_search_fail = 0;
cc->search_order = order;
page = freepage;
break;
}
if (pfn >= min_pfn && pfn > high_pfn) {
high_pfn = pfn;
/* Shorten the scan if a candidate is found */
limit >>= 1;
}
if (order_scanned >= limit)
break;
}
/* Use a minimum pfn if a preferred one was not found */
if (!page && high_pfn) {
page = pfn_to_page(high_pfn);
/* Update freepage for the list reorder below */
freepage = page;
}
/* Reorder to so a future search skips recent pages */
move_freelist_head(freelist, freepage);
/* Isolate the page if available */
if (page) {
if (__isolate_free_page(page, order)) {
set_page_private(page, order);
nr_isolated = 1 << order;
cc->nr_freepages += nr_isolated;
list_add_tail(&page->lru, &cc->freepages);
count_compact_events(COMPACTISOLATED, nr_isolated);
} else {
/* If isolation fails, abort the search */
order = cc->search_order + 1;
page = NULL;
}
}
spin_unlock_irqrestore(&cc->zone->lock, flags);
/*
* Smaller scan on next order so the total scan ig related
* to freelist_scan_limit.
*/
if (order_scanned >= limit)
limit = min(1U, limit >> 1);
}
if (!page) {
cc->fast_search_fail++;
if (scan_start) {
/*
* Use the highest PFN found above min. If one was
* not found, be pessimistic for direct compaction
* and use the min mark.
*/
if (highest) {
page = pfn_to_page(highest);
cc->free_pfn = highest;
} else {
if (cc->direct_compaction && pfn_valid(min_pfn)) {
page = pageblock_pfn_to_page(min_pfn,
pageblock_end_pfn(min_pfn),
cc->zone);
cc->free_pfn = min_pfn;
}
}
}
}
if (highest && highest >= cc->zone->compact_cached_free_pfn) {
highest -= pageblock_nr_pages;
cc->zone->compact_cached_free_pfn = highest;
}
cc->total_free_scanned += nr_scanned;
if (!page)
return cc->free_pfn;
low_pfn = page_to_pfn(page);
fast_isolate_around(cc, low_pfn, nr_isolated);
return low_pfn;
}
/*
* Based on information in the current compact_control, find blocks
* suitable for isolating free pages from and then isolate them.
*/
static void isolate_freepages(struct compact_control *cc)
{
struct zone *zone = cc->zone;
struct page *page;
unsigned long block_start_pfn; /* start of current pageblock */
unsigned long isolate_start_pfn; /* exact pfn we start at */
unsigned long block_end_pfn; /* end of current pageblock */
unsigned long low_pfn; /* lowest pfn scanner is able to scan */
struct list_head *freelist = &cc->freepages;
unsigned int stride;
/* Try a small search of the free lists for a candidate */
isolate_start_pfn = fast_isolate_freepages(cc);
if (cc->nr_freepages)
goto splitmap;
/*
* Initialise the free scanner. The starting point is where we last
* successfully isolated from, zone-cached value, or the end of the
* zone when isolating for the first time. For looping we also need
* this pfn aligned down to the pageblock boundary, because we do
* block_start_pfn -= pageblock_nr_pages in the for loop.
* For ending point, take care when isolating in last pageblock of a
* zone which ends in the middle of a pageblock.
* The low boundary is the end of the pageblock the migration scanner
* is using.
*/
isolate_start_pfn = cc->free_pfn;
block_start_pfn = pageblock_start_pfn(isolate_start_pfn);
block_end_pfn = min(block_start_pfn + pageblock_nr_pages,
zone_end_pfn(zone));
low_pfn = pageblock_end_pfn(cc->migrate_pfn);
stride = cc->mode == MIGRATE_ASYNC ? COMPACT_CLUSTER_MAX : 1;
/*
* Isolate free pages until enough are available to migrate the
* pages on cc->migratepages. We stop searching if the migrate
* and free page scanners meet or enough free pages are isolated.
*/
for (; block_start_pfn >= low_pfn;
block_end_pfn = block_start_pfn,
block_start_pfn -= pageblock_nr_pages,
isolate_start_pfn = block_start_pfn) {
unsigned long nr_isolated;
/*
* This can iterate a massively long zone without finding any
* suitable migration targets, so periodically check resched.
*/
if (!(block_start_pfn % (SWAP_CLUSTER_MAX * pageblock_nr_pages)))
cond_resched();
page = pageblock_pfn_to_page(block_start_pfn, block_end_pfn,
zone);
if (!page)
continue;
/* Check the block is suitable for migration */
if (!suitable_migration_target(cc, page))
continue;
/* If isolation recently failed, do not retry */
if (!isolation_suitable(cc, page))
continue;
/* Found a block suitable for isolating free pages from. */
nr_isolated = isolate_freepages_block(cc, &isolate_start_pfn,
block_end_pfn, freelist, stride, false);
/* Update the skip hint if the full pageblock was scanned */
if (isolate_start_pfn == block_end_pfn)
update_pageblock_skip(cc, page, block_start_pfn);
/* Are enough freepages isolated? */
if (cc->nr_freepages >= cc->nr_migratepages) {
if (isolate_start_pfn >= block_end_pfn) {
/*
* Restart at previous pageblock if more
* freepages can be isolated next time.
*/
isolate_start_pfn =
block_start_pfn - pageblock_nr_pages;
}
break;
} else if (isolate_start_pfn < block_end_pfn) {
/*
* If isolation failed early, do not continue
* needlessly.
*/
break;
}
/* Adjust stride depending on isolation */
if (nr_isolated) {
stride = 1;
continue;
}
stride = min_t(unsigned int, COMPACT_CLUSTER_MAX, stride << 1);
}
/*
* Record where the free scanner will restart next time. Either we
* broke from the loop and set isolate_start_pfn based on the last
* call to isolate_freepages_block(), or we met the migration scanner
* and the loop terminated due to isolate_start_pfn < low_pfn
*/
cc->free_pfn = isolate_start_pfn;
splitmap:
/* __isolate_free_page() does not map the pages */
split_map_pages(freelist);
}
/*
* This is a migrate-callback that "allocates" freepages by taking pages
* from the isolated freelists in the block we are migrating to.
*/
static struct page *compaction_alloc(struct page *migratepage,
unsigned long data)
{
struct compact_control *cc = (struct compact_control *)data;
struct page *freepage;
if (list_empty(&cc->freepages)) {
isolate_freepages(cc);
if (list_empty(&cc->freepages))
return NULL;
}
freepage = list_entry(cc->freepages.next, struct page, lru);
list_del(&freepage->lru);
cc->nr_freepages--;
return freepage;
}
/*
* This is a migrate-callback that "frees" freepages back to the isolated
* freelist. All pages on the freelist are from the same zone, so there is no
* special handling needed for NUMA.
*/
static void compaction_free(struct page *page, unsigned long data)
{
struct compact_control *cc = (struct compact_control *)data;
list_add(&page->lru, &cc->freepages);
cc->nr_freepages++;
}
/* possible outcome of isolate_migratepages */
typedef enum {
ISOLATE_ABORT, /* Abort compaction now */
ISOLATE_NONE, /* No pages isolated, continue scanning */
ISOLATE_SUCCESS, /* Pages isolated, migrate */
} isolate_migrate_t;
/*
* Allow userspace to control policy on scanning the unevictable LRU for
* compactable pages.
*/
#ifdef CONFIG_PREEMPT_RT
int sysctl_compact_unevictable_allowed __read_mostly = 0;
#else
int sysctl_compact_unevictable_allowed __read_mostly = 1;
#endif
static inline void
update_fast_start_pfn(struct compact_control *cc, unsigned long pfn)
{
if (cc->fast_start_pfn == ULONG_MAX)
return;
if (!cc->fast_start_pfn)
cc->fast_start_pfn = pfn;
cc->fast_start_pfn = min(cc->fast_start_pfn, pfn);
}
static inline unsigned long
reinit_migrate_pfn(struct compact_control *cc)
{
if (!cc->fast_start_pfn || cc->fast_start_pfn == ULONG_MAX)
return cc->migrate_pfn;
cc->migrate_pfn = cc->fast_start_pfn;
cc->fast_start_pfn = ULONG_MAX;
return cc->migrate_pfn;
}
/*
* Briefly search the free lists for a migration source that already has
* some free pages to reduce the number of pages that need migration
* before a pageblock is free.
*/
static unsigned long fast_find_migrateblock(struct compact_control *cc)
{
unsigned int limit = freelist_scan_limit(cc);
unsigned int nr_scanned = 0;
unsigned long distance;
unsigned long pfn = cc->migrate_pfn;
unsigned long high_pfn;
int order;
/* Skip hints are relied on to avoid repeats on the fast search */
if (cc->ignore_skip_hint)
return pfn;
/*
* If the migrate_pfn is not at the start of a zone or the start
* of a pageblock then assume this is a continuation of a previous
* scan restarted due to COMPACT_CLUSTER_MAX.
*/
if (pfn != cc->zone->zone_start_pfn && pfn != pageblock_start_pfn(pfn))
return pfn;
/*
* For smaller orders, just linearly scan as the number of pages
* to migrate should be relatively small and does not necessarily
* justify freeing up a large block for a small allocation.
*/
if (cc->order <= PAGE_ALLOC_COSTLY_ORDER)
return pfn;
/*
* Only allow kcompactd and direct requests for movable pages to
* quickly clear out a MOVABLE pageblock for allocation. This
* reduces the risk that a large movable pageblock is freed for
* an unmovable/reclaimable small allocation.
*/
if (cc->direct_compaction && cc->migratetype != MIGRATE_MOVABLE)
return pfn;
/*
* When starting the migration scanner, pick any pageblock within the
* first half of the search space. Otherwise try and pick a pageblock
* within the first eighth to reduce the chances that a migration
* target later becomes a source.
*/
distance = (cc->free_pfn - cc->migrate_pfn) >> 1;
if (cc->migrate_pfn != cc->zone->zone_start_pfn)
distance >>= 2;
high_pfn = pageblock_start_pfn(cc->migrate_pfn + distance);
for (order = cc->order - 1;
order >= PAGE_ALLOC_COSTLY_ORDER && pfn == cc->migrate_pfn && nr_scanned < limit;
order--) {
struct free_area *area = &cc->zone->free_area[order];
struct list_head *freelist;
unsigned long flags;
struct page *freepage;
if (!area->nr_free)
continue;
spin_lock_irqsave(&cc->zone->lock, flags);
freelist = &area->free_list[MIGRATE_MOVABLE];
list_for_each_entry(freepage, freelist, lru) {
unsigned long free_pfn;
nr_scanned++;
free_pfn = page_to_pfn(freepage);
if (free_pfn < high_pfn) {
/*
* Avoid if skipped recently. Ideally it would
* move to the tail but even safe iteration of
* the list assumes an entry is deleted, not
* reordered.
*/
if (get_pageblock_skip(freepage)) {
if (list_is_last(freelist, &freepage->lru))
break;
continue;
}
/* Reorder to so a future search skips recent pages */
move_freelist_tail(freelist, freepage);
update_fast_start_pfn(cc, free_pfn);
pfn = pageblock_start_pfn(free_pfn);
cc->fast_search_fail = 0;
set_pageblock_skip(freepage);
break;
}
if (nr_scanned >= limit) {
cc->fast_search_fail++;
move_freelist_tail(freelist, freepage);
break;
}
}
spin_unlock_irqrestore(&cc->zone->lock, flags);
}
cc->total_migrate_scanned += nr_scanned;
/*
* If fast scanning failed then use a cached entry for a page block
* that had free pages as the basis for starting a linear scan.
*/
if (pfn == cc->migrate_pfn)
pfn = reinit_migrate_pfn(cc);
return pfn;
}
/*
* Isolate all pages that can be migrated from the first suitable block,
* starting at the block pointed to by the migrate scanner pfn within
* compact_control.
*/
static isolate_migrate_t isolate_migratepages(struct compact_control *cc)
{
unsigned long block_start_pfn;
unsigned long block_end_pfn;
unsigned long low_pfn;
struct page *page;
const isolate_mode_t isolate_mode =
(sysctl_compact_unevictable_allowed ? ISOLATE_UNEVICTABLE : 0) |
(cc->mode != MIGRATE_SYNC ? ISOLATE_ASYNC_MIGRATE : 0);
bool fast_find_block;
/*
* Start at where we last stopped, or beginning of the zone as
* initialized by compact_zone(). The first failure will use
* the lowest PFN as the starting point for linear scanning.
*/
low_pfn = fast_find_migrateblock(cc);
block_start_pfn = pageblock_start_pfn(low_pfn);
if (block_start_pfn < cc->zone->zone_start_pfn)
block_start_pfn = cc->zone->zone_start_pfn;
/*
* fast_find_migrateblock marks a pageblock skipped so to avoid
* the isolation_suitable check below, check whether the fast
* search was successful.
*/
fast_find_block = low_pfn != cc->migrate_pfn && !cc->fast_search_fail;
/* Only scan within a pageblock boundary */
block_end_pfn = pageblock_end_pfn(low_pfn);
/*
* Iterate over whole pageblocks until we find the first suitable.
* Do not cross the free scanner.
*/
for (; block_end_pfn <= cc->free_pfn;
fast_find_block = false,
low_pfn = block_end_pfn,
block_start_pfn = block_end_pfn,
block_end_pfn += pageblock_nr_pages) {
/*
* This can potentially iterate a massively long zone with
* many pageblocks unsuitable, so periodically check if we
* need to schedule.
*/
if (!(low_pfn % (SWAP_CLUSTER_MAX * pageblock_nr_pages)))
cond_resched();
page = pageblock_pfn_to_page(block_start_pfn,
block_end_pfn, cc->zone);
if (!page)
continue;
/*
* If isolation recently failed, do not retry. Only check the
* pageblock once. COMPACT_CLUSTER_MAX causes a pageblock
* to be visited multiple times. Assume skip was checked
* before making it "skip" so other compaction instances do
* not scan the same block.
*/
if (IS_ALIGNED(low_pfn, pageblock_nr_pages) &&
!fast_find_block && !isolation_suitable(cc, page))
continue;
/*
* For async compaction, also only scan in MOVABLE blocks
* without huge pages. Async compaction is optimistic to see
* if the minimum amount of work satisfies the allocation.
* The cached PFN is updated as it's possible that all
* remaining blocks between source and target are unsuitable
* and the compaction scanners fail to meet.
*/
if (!suitable_migration_source(cc, page)) {
update_cached_migrate(cc, block_end_pfn);
continue;
}
/* Perform the isolation */
low_pfn = isolate_migratepages_block(cc, low_pfn,
block_end_pfn, isolate_mode);
if (!low_pfn)
return ISOLATE_ABORT;
/*
* Either we isolated something and proceed with migration. Or
* we failed and compact_zone should decide if we should
* continue or not.
*/
break;
}
/* Record where migration scanner will be restarted. */
cc->migrate_pfn = low_pfn;
return cc->nr_migratepages ? ISOLATE_SUCCESS : ISOLATE_NONE;
}
/*
* order == -1 is expected when compacting via
* /proc/sys/vm/compact_memory
*/
static inline bool is_via_compact_memory(int order)
{
return order == -1;
}
static bool kswapd_is_running(pg_data_t *pgdat)
{
return pgdat->kswapd && (pgdat->kswapd->state == TASK_RUNNING);
}
/*
* A zone's fragmentation score is the external fragmentation wrt to the
* COMPACTION_HPAGE_ORDER scaled by the zone's size. It returns a value
* in the range [0, 100].
*
* The scaling factor ensures that proactive compaction focuses on larger
* zones like ZONE_NORMAL, rather than smaller, specialized zones like
* ZONE_DMA32. For smaller zones, the score value remains close to zero,
* and thus never exceeds the high threshold for proactive compaction.
*/
static unsigned int fragmentation_score_zone(struct zone *zone)
{
unsigned long score;
score = zone->present_pages *
extfrag_for_order(zone, COMPACTION_HPAGE_ORDER);
return div64_ul(score, zone->zone_pgdat->node_present_pages + 1);
}
/*
* The per-node proactive (background) compaction process is started by its
* corresponding kcompactd thread when the node's fragmentation score
* exceeds the high threshold. The compaction process remains active till
* the node's score falls below the low threshold, or one of the back-off
* conditions is met.
*/
static unsigned int fragmentation_score_node(pg_data_t *pgdat)
{
unsigned int score = 0;
int zoneid;
for (zoneid = 0; zoneid < MAX_NR_ZONES; zoneid++) {
struct zone *zone;
zone = &pgdat->node_zones[zoneid];
score += fragmentation_score_zone(zone);
}
return score;
}
static unsigned int fragmentation_score_wmark(pg_data_t *pgdat, bool low)
{
unsigned int wmark_low;
/*
* Cap the low watermak to avoid excessive compaction
* activity in case a user sets the proactivess tunable
* close to 100 (maximum).
*/
wmark_low = max(100U - sysctl_compaction_proactiveness, 5U);
return low ? wmark_low : min(wmark_low + 10, 100U);
}
static bool should_proactive_compact_node(pg_data_t *pgdat)
{
int wmark_high;
if (!sysctl_compaction_proactiveness || kswapd_is_running(pgdat))
return false;
wmark_high = fragmentation_score_wmark(pgdat, false);
return fragmentation_score_node(pgdat) > wmark_high;
}
static enum compact_result __compact_finished(struct compact_control *cc)
{
unsigned int order;
const int migratetype = cc->migratetype;
int ret;
/* Compaction run completes if the migrate and free scanner meet */
if (compact_scanners_met(cc)) {
/* Let the next compaction start anew. */
reset_cached_positions(cc->zone);
/*
* Mark that the PG_migrate_skip information should be cleared
* by kswapd when it goes to sleep. kcompactd does not set the
* flag itself as the decision to be clear should be directly
* based on an allocation request.
*/
if (cc->direct_compaction)
cc->zone->compact_blockskip_flush = true;
if (cc->whole_zone)
return COMPACT_COMPLETE;
else
return COMPACT_PARTIAL_SKIPPED;
}
if (cc->proactive_compaction) {
int score, wmark_low;
pg_data_t *pgdat;
pgdat = cc->zone->zone_pgdat;
if (kswapd_is_running(pgdat))
return COMPACT_PARTIAL_SKIPPED;
score = fragmentation_score_zone(cc->zone);
wmark_low = fragmentation_score_wmark(pgdat, true);
if (score > wmark_low)
ret = COMPACT_CONTINUE;
else
ret = COMPACT_SUCCESS;
goto out;
}
if (is_via_compact_memory(cc->order))
return COMPACT_CONTINUE;
/*
* Always finish scanning a pageblock to reduce the possibility of
* fallbacks in the future. This is particularly important when
* migration source is unmovable/reclaimable but it's not worth
* special casing.
*/
if (!IS_ALIGNED(cc->migrate_pfn, pageblock_nr_pages))
return COMPACT_CONTINUE;
/* Direct compactor: Is a suitable page free? */
ret = COMPACT_NO_SUITABLE_PAGE;
for (order = cc->order; order < MAX_ORDER; order++) {
struct free_area *area = &cc->zone->free_area[order];
bool can_steal;
/* Job done if page is free of the right migratetype */
if (!free_area_empty(area, migratetype))
return COMPACT_SUCCESS;
#ifdef CONFIG_CMA
/* MIGRATE_MOVABLE can fallback on MIGRATE_CMA */
if (migratetype == MIGRATE_MOVABLE &&
!free_area_empty(area, MIGRATE_CMA))
return COMPACT_SUCCESS;
#endif
/*
* Job done if allocation would steal freepages from
* other migratetype buddy lists.
*/
if (find_suitable_fallback(area, order, migratetype,
true, &can_steal) != -1) {
/* movable pages are OK in any pageblock */
if (migratetype == MIGRATE_MOVABLE)
return COMPACT_SUCCESS;
/*
* We are stealing for a non-movable allocation. Make
* sure we finish compacting the current pageblock
* first so it is as free as possible and we won't
* have to steal another one soon. This only applies
* to sync compaction, as async compaction operates
* on pageblocks of the same migratetype.
*/
if (cc->mode == MIGRATE_ASYNC ||
IS_ALIGNED(cc->migrate_pfn,
pageblock_nr_pages)) {
return COMPACT_SUCCESS;
}
ret = COMPACT_CONTINUE;
break;
}
}
out:
if (cc->contended || fatal_signal_pending(current))
ret = COMPACT_CONTENDED;
return ret;
}
static enum compact_result compact_finished(struct compact_control *cc)
{
int ret;
ret = __compact_finished(cc);
trace_mm_compaction_finished(cc->zone, cc->order, ret);
if (ret == COMPACT_NO_SUITABLE_PAGE)
ret = COMPACT_CONTINUE;
return ret;
}
/*
* compaction_suitable: Is this suitable to run compaction on this zone now?
* Returns
* COMPACT_SKIPPED - If there are too few free pages for compaction
* COMPACT_SUCCESS - If the allocation would succeed without compaction
* COMPACT_CONTINUE - If compaction should run now
*/
static enum compact_result __compaction_suitable(struct zone *zone, int order,
unsigned int alloc_flags,
int highest_zoneidx,
unsigned long wmark_target)
{
unsigned long watermark;
if (is_via_compact_memory(order))
return COMPACT_CONTINUE;
watermark = wmark_pages(zone, alloc_flags & ALLOC_WMARK_MASK);
/*
* If watermarks for high-order allocation are already met, there
* should be no need for compaction at all.
*/
if (zone_watermark_ok(zone, order, watermark, highest_zoneidx,
alloc_flags))
return COMPACT_SUCCESS;
/*
* Watermarks for order-0 must be met for compaction to be able to
* isolate free pages for migration targets. This means that the
* watermark and alloc_flags have to match, or be more pessimistic than
* the check in __isolate_free_page(). We don't use the direct
* compactor's alloc_flags, as they are not relevant for freepage
* isolation. We however do use the direct compactor's highest_zoneidx
* to skip over zones where lowmem reserves would prevent allocation
* even if compaction succeeds.
* For costly orders, we require low watermark instead of min for
* compaction to proceed to increase its chances.
* ALLOC_CMA is used, as pages in CMA pageblocks are considered
* suitable migration targets
*/
watermark = (order > PAGE_ALLOC_COSTLY_ORDER) ?
low_wmark_pages(zone) : min_wmark_pages(zone);
watermark += compact_gap(order);
if (!__zone_watermark_ok(zone, 0, watermark, highest_zoneidx,
ALLOC_CMA, wmark_target))
return COMPACT_SKIPPED;
return COMPACT_CONTINUE;
}
enum compact_result compaction_suitable(struct zone *zone, int order,
unsigned int alloc_flags,
int highest_zoneidx)
{
enum compact_result ret;
int fragindex;
ret = __compaction_suitable(zone, order, alloc_flags, highest_zoneidx,
zone_page_state(zone, NR_FREE_PAGES));
/*
* fragmentation index determines if allocation failures are due to
* low memory or external fragmentation
*
* index of -1000 would imply allocations might succeed depending on
* watermarks, but we already failed the high-order watermark check
* index towards 0 implies failure is due to lack of memory
* index towards 1000 implies failure is due to fragmentation
*
* Only compact if a failure would be due to fragmentation. Also
* ignore fragindex for non-costly orders where the alternative to
* a successful reclaim/compaction is OOM. Fragindex and the
* vm.extfrag_threshold sysctl is meant as a heuristic to prevent
* excessive compaction for costly orders, but it should not be at the
* expense of system stability.
*/
if (ret == COMPACT_CONTINUE && (order > PAGE_ALLOC_COSTLY_ORDER)) {
fragindex = fragmentation_index(zone, order);
if (fragindex >= 0 && fragindex <= sysctl_extfrag_threshold)
ret = COMPACT_NOT_SUITABLE_ZONE;
}
trace_mm_compaction_suitable(zone, order, ret);
if (ret == COMPACT_NOT_SUITABLE_ZONE)
ret = COMPACT_SKIPPED;
return ret;
}
bool compaction_zonelist_suitable(struct alloc_context *ac, int order,
int alloc_flags)
{
struct zone *zone;
struct zoneref *z;
/*
* Make sure at least one zone would pass __compaction_suitable if we continue
* retrying the reclaim.
*/
for_each_zone_zonelist_nodemask(zone, z, ac->zonelist,
ac->highest_zoneidx, ac->nodemask) {
unsigned long available;
enum compact_result compact_result;
/*
* Do not consider all the reclaimable memory because we do not
* want to trash just for a single high order allocation which
* is even not guaranteed to appear even if __compaction_suitable
* is happy about the watermark check.
*/
available = zone_reclaimable_pages(zone) / order;
available += zone_page_state_snapshot(zone, NR_FREE_PAGES);
compact_result = __compaction_suitable(zone, order, alloc_flags,
ac->highest_zoneidx, available);
if (compact_result != COMPACT_SKIPPED)
return true;
}
return false;
}
static enum compact_result
compact_zone(struct compact_control *cc, struct capture_control *capc)
{
enum compact_result ret;
unsigned long start_pfn = cc->zone->zone_start_pfn;
unsigned long end_pfn = zone_end_pfn(cc->zone);
unsigned long last_migrated_pfn;
const bool sync = cc->mode != MIGRATE_ASYNC;
bool update_cached;
/*
* These counters track activities during zone compaction. Initialize
* them before compacting a new zone.
*/
cc->total_migrate_scanned = 0;
cc->total_free_scanned = 0;
cc->nr_migratepages = 0;
cc->nr_freepages = 0;
INIT_LIST_HEAD(&cc->freepages);
INIT_LIST_HEAD(&cc->migratepages);
cc->migratetype = gfp_migratetype(cc->gfp_mask);
ret = compaction_suitable(cc->zone, cc->order, cc->alloc_flags,
cc->highest_zoneidx);
/* Compaction is likely to fail */
if (ret == COMPACT_SUCCESS || ret == COMPACT_SKIPPED)
return ret;
/* huh, compaction_suitable is returning something unexpected */
VM_BUG_ON(ret != COMPACT_CONTINUE);
/*
* Clear pageblock skip if there were failures recently and compaction
* is about to be retried after being deferred.
*/
if (compaction_restarting(cc->zone, cc->order))
__reset_isolation_suitable(cc->zone);
/*
* Setup to move all movable pages to the end of the zone. Used cached
* information on where the scanners should start (unless we explicitly
* want to compact the whole zone), but check that it is initialised
* by ensuring the values are within zone boundaries.
*/
cc->fast_start_pfn = 0;
if (cc->whole_zone) {
cc->migrate_pfn = start_pfn;
cc->free_pfn = pageblock_start_pfn(end_pfn - 1);
} else {
cc->migrate_pfn = cc->zone->compact_cached_migrate_pfn[sync];
cc->free_pfn = cc->zone->compact_cached_free_pfn;
if (cc->free_pfn < start_pfn || cc->free_pfn >= end_pfn) {
cc->free_pfn = pageblock_start_pfn(end_pfn - 1);
cc->zone->compact_cached_free_pfn = cc->free_pfn;
}
if (cc->migrate_pfn < start_pfn || cc->migrate_pfn >= end_pfn) {
cc->migrate_pfn = start_pfn;
cc->zone->compact_cached_migrate_pfn[0] = cc->migrate_pfn;
cc->zone->compact_cached_migrate_pfn[1] = cc->migrate_pfn;
}
if (cc->migrate_pfn <= cc->zone->compact_init_migrate_pfn)
cc->whole_zone = true;
}
last_migrated_pfn = 0;
/*
* Migrate has separate cached PFNs for ASYNC and SYNC* migration on
* the basis that some migrations will fail in ASYNC mode. However,
* if the cached PFNs match and pageblocks are skipped due to having
* no isolation candidates, then the sync state does not matter.
* Until a pageblock with isolation candidates is found, keep the
* cached PFNs in sync to avoid revisiting the same blocks.
*/
update_cached = !sync &&
cc->zone->compact_cached_migrate_pfn[0] == cc->zone->compact_cached_migrate_pfn[1];
trace_mm_compaction_begin(start_pfn, cc->migrate_pfn,
cc->free_pfn, end_pfn, sync);
migrate_prep_local();
while ((ret = compact_finished(cc)) == COMPACT_CONTINUE) {
int err;
unsigned long start_pfn = cc->migrate_pfn;
/*
* Avoid multiple rescans which can happen if a page cannot be
* isolated (dirty/writeback in async mode) or if the migrated
* pages are being allocated before the pageblock is cleared.
* The first rescan will capture the entire pageblock for
* migration. If it fails, it'll be marked skip and scanning
* will proceed as normal.
*/
cc->rescan = false;
if (pageblock_start_pfn(last_migrated_pfn) ==
pageblock_start_pfn(start_pfn)) {
cc->rescan = true;
}
switch (isolate_migratepages(cc)) {
case ISOLATE_ABORT:
ret = COMPACT_CONTENDED;
putback_movable_pages(&cc->migratepages);
cc->nr_migratepages = 0;
goto out;
case ISOLATE_NONE:
if (update_cached) {
cc->zone->compact_cached_migrate_pfn[1] =
cc->zone->compact_cached_migrate_pfn[0];
}
/*
* We haven't isolated and migrated anything, but
* there might still be unflushed migrations from
* previous cc->order aligned block.
*/
goto check_drain;
case ISOLATE_SUCCESS:
update_cached = false;
last_migrated_pfn = start_pfn;
;
}
err = migrate_pages(&cc->migratepages, compaction_alloc,
compaction_free, (unsigned long)cc, cc->mode,
MR_COMPACTION);
trace_mm_compaction_migratepages(cc->nr_migratepages, err,
&cc->migratepages);
/* All pages were either migrated or will be released */
cc->nr_migratepages = 0;
if (err) {
putback_movable_pages(&cc->migratepages);
/*
* migrate_pages() may return -ENOMEM when scanners meet
* and we want compact_finished() to detect it
*/
if (err == -ENOMEM && !compact_scanners_met(cc)) {
ret = COMPACT_CONTENDED;
goto out;
}
/*
* We failed to migrate at least one page in the current
* order-aligned block, so skip the rest of it.
*/
if (cc->direct_compaction &&
(cc->mode == MIGRATE_ASYNC)) {
cc->migrate_pfn = block_end_pfn(
cc->migrate_pfn - 1, cc->order);
/* Draining pcplists is useless in this case */
last_migrated_pfn = 0;
}
}
check_drain:
/*
* Has the migration scanner moved away from the previous
* cc->order aligned block where we migrated from? If yes,
* flush the pages that were freed, so that they can merge and
* compact_finished() can detect immediately if allocation
* would succeed.
*/
if (cc->order > 0 && last_migrated_pfn) {
unsigned long current_block_start =
block_start_pfn(cc->migrate_pfn, cc->order);
if (last_migrated_pfn < current_block_start) {
lru_add_drain_cpu_zone(cc->zone);
/* No more flushing until we migrate again */
last_migrated_pfn = 0;
}
}
/* Stop if a page has been captured */
if (capc && capc->page) {
ret = COMPACT_SUCCESS;
break;
}
}
out:
/*
* Release free pages and update where the free scanner should restart,
* so we don't leave any returned pages behind in the next attempt.
*/
if (cc->nr_freepages > 0) {
unsigned long free_pfn = release_freepages(&cc->freepages);
cc->nr_freepages = 0;
VM_BUG_ON(free_pfn == 0);
/* The cached pfn is always the first in a pageblock */
free_pfn = pageblock_start_pfn(free_pfn);
/*
* Only go back, not forward. The cached pfn might have been
* already reset to zone end in compact_finished()
*/
if (free_pfn > cc->zone->compact_cached_free_pfn)
cc->zone->compact_cached_free_pfn = free_pfn;
}
count_compact_events(COMPACTMIGRATE_SCANNED, cc->total_migrate_scanned);
count_compact_events(COMPACTFREE_SCANNED, cc->total_free_scanned);
trace_mm_compaction_end(start_pfn, cc->migrate_pfn,
cc->free_pfn, end_pfn, sync, ret);
return ret;
}
static enum compact_result compact_zone_order(struct zone *zone, int order,
gfp_t gfp_mask, enum compact_priority prio,
unsigned int alloc_flags, int highest_zoneidx,
struct page **capture)
{
enum compact_result ret;
struct compact_control cc = {
.order = order,
.search_order = order,
.gfp_mask = gfp_mask,
.zone = zone,
.mode = (prio == COMPACT_PRIO_ASYNC) ?
MIGRATE_ASYNC : MIGRATE_SYNC_LIGHT,
.alloc_flags = alloc_flags,
.highest_zoneidx = highest_zoneidx,
.direct_compaction = true,
.whole_zone = (prio == MIN_COMPACT_PRIORITY),
.ignore_skip_hint = (prio == MIN_COMPACT_PRIORITY),
.ignore_block_suitable = (prio == MIN_COMPACT_PRIORITY)
};
struct capture_control capc = {
.cc = &cc,
.page = NULL,
};
/*
* Make sure the structs are really initialized before we expose the
* capture control, in case we are interrupted and the interrupt handler
* frees a page.
*/
barrier();
WRITE_ONCE(current->capture_control, &capc);
ret = compact_zone(&cc, &capc);
VM_BUG_ON(!list_empty(&cc.freepages));
VM_BUG_ON(!list_empty(&cc.migratepages));
/*
* Make sure we hide capture control first before we read the captured
* page pointer, otherwise an interrupt could free and capture a page
* and we would leak it.
*/
WRITE_ONCE(current->capture_control, NULL);
*capture = READ_ONCE(capc.page);
return ret;
}
int sysctl_extfrag_threshold = 500;
/**
* try_to_compact_pages - Direct compact to satisfy a high-order allocation
* @gfp_mask: The GFP mask of the current allocation
* @order: The order of the current allocation
* @alloc_flags: The allocation flags of the current allocation
* @ac: The context of current allocation
* @prio: Determines how hard direct compaction should try to succeed
* @capture: Pointer to free page created by compaction will be stored here
*
* This is the main entry point for direct page compaction.
*/
enum compact_result try_to_compact_pages(gfp_t gfp_mask, unsigned int order,
unsigned int alloc_flags, const struct alloc_context *ac,
enum compact_priority prio, struct page **capture)
{
int may_perform_io = gfp_mask & __GFP_IO;
struct zoneref *z;
struct zone *zone;
enum compact_result rc = COMPACT_SKIPPED;
/*
* Check if the GFP flags allow compaction - GFP_NOIO is really
* tricky context because the migration might require IO
*/
if (!may_perform_io)
return COMPACT_SKIPPED;
trace_mm_compaction_try_to_compact_pages(order, gfp_mask, prio);
/* Compact each zone in the list */
for_each_zone_zonelist_nodemask(zone, z, ac->zonelist,
ac->highest_zoneidx, ac->nodemask) {
enum compact_result status;
if (prio > MIN_COMPACT_PRIORITY
&& compaction_deferred(zone, order)) {
rc = max_t(enum compact_result, COMPACT_DEFERRED, rc);
continue;
}
status = compact_zone_order(zone, order, gfp_mask, prio,
alloc_flags, ac->highest_zoneidx, capture);
rc = max(status, rc);
/* The allocation should succeed, stop compacting */
if (status == COMPACT_SUCCESS) {
/*
* We think the allocation will succeed in this zone,
* but it is not certain, hence the false. The caller
* will repeat this with true if allocation indeed
* succeeds in this zone.
*/
compaction_defer_reset(zone, order, false);
break;
}
if (prio != COMPACT_PRIO_ASYNC && (status == COMPACT_COMPLETE ||
status == COMPACT_PARTIAL_SKIPPED))
/*
* We think that allocation won't succeed in this zone
* so we defer compaction there. If it ends up
* succeeding after all, it will be reset.
*/
defer_compaction(zone, order);
/*
* We might have stopped compacting due to need_resched() in
* async compaction, or due to a fatal signal detected. In that
* case do not try further zones
*/
if ((prio == COMPACT_PRIO_ASYNC && need_resched())
|| fatal_signal_pending(current))
break;
}
return rc;
}
/*
* Compact all zones within a node till each zone's fragmentation score
* reaches within proactive compaction thresholds (as determined by the
* proactiveness tunable).
*
* It is possible that the function returns before reaching score targets
* due to various back-off conditions, such as, contention on per-node or
* per-zone locks.
*/
static void proactive_compact_node(pg_data_t *pgdat)
{
int zoneid;
struct zone *zone;
struct compact_control cc = {
.order = -1,
.mode = MIGRATE_SYNC_LIGHT,
.ignore_skip_hint = true,
.whole_zone = true,
.gfp_mask = GFP_KERNEL,
.proactive_compaction = true,
};
for (zoneid = 0; zoneid < MAX_NR_ZONES; zoneid++) {
zone = &pgdat->node_zones[zoneid];
if (!populated_zone(zone))
continue;
cc.zone = zone;
compact_zone(&cc, NULL);
VM_BUG_ON(!list_empty(&cc.freepages));
VM_BUG_ON(!list_empty(&cc.migratepages));
}
}
/* Compact all zones within a node */
static void compact_node(int nid)
{
pg_data_t *pgdat = NODE_DATA(nid);
int zoneid;
struct zone *zone;
struct compact_control cc = {
.order = -1,
.mode = MIGRATE_SYNC,
.ignore_skip_hint = true,
.whole_zone = true,
.gfp_mask = GFP_KERNEL,
};
for (zoneid = 0; zoneid < MAX_NR_ZONES; zoneid++) {
zone = &pgdat->node_zones[zoneid];
if (!populated_zone(zone))
continue;
cc.zone = zone;
compact_zone(&cc, NULL);
VM_BUG_ON(!list_empty(&cc.freepages));
VM_BUG_ON(!list_empty(&cc.migratepages));
}
}
/* Compact all nodes in the system */
static void compact_nodes(void)
{
int nid;
/* Flush pending updates to the LRU lists */
lru_add_drain_all();
for_each_online_node(nid)
compact_node(nid);
}
/* The written value is actually unused, all memory is compacted */
int sysctl_compact_memory;
/*
* Tunable for proactive compaction. It determines how
* aggressively the kernel should compact memory in the
* background. It takes values in the range [0, 100].
*/
unsigned int __read_mostly sysctl_compaction_proactiveness = 20;
/*
* This is the entry point for compacting all nodes via
* /proc/sys/vm/compact_memory
*/
int sysctl_compaction_handler(struct ctl_table *table, int write,
void *buffer, size_t *length, loff_t *ppos)
{
if (write)
compact_nodes();
return 0;
}
#if defined(CONFIG_SYSFS) && defined(CONFIG_NUMA)
static ssize_t sysfs_compact_node(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t count)
{
int nid = dev->id;
if (nid >= 0 && nid < nr_node_ids && node_online(nid)) {
/* Flush pending updates to the LRU lists */
lru_add_drain_all();
compact_node(nid);
}
return count;
}
static DEVICE_ATTR(compact, 0200, NULL, sysfs_compact_node);
int compaction_register_node(struct node *node)
{
return device_create_file(&node->dev, &dev_attr_compact);
}
void compaction_unregister_node(struct node *node)
{
return device_remove_file(&node->dev, &dev_attr_compact);
}
#endif /* CONFIG_SYSFS && CONFIG_NUMA */
static inline bool kcompactd_work_requested(pg_data_t *pgdat)
{
return pgdat->kcompactd_max_order > 0 || kthread_should_stop();
}
static bool kcompactd_node_suitable(pg_data_t *pgdat)
{
int zoneid;
struct zone *zone;
enum zone_type highest_zoneidx = pgdat->kcompactd_highest_zoneidx;
for (zoneid = 0; zoneid <= highest_zoneidx; zoneid++) {
zone = &pgdat->node_zones[zoneid];
if (!populated_zone(zone))
continue;
if (compaction_suitable(zone, pgdat->kcompactd_max_order, 0,
highest_zoneidx) == COMPACT_CONTINUE)
return true;
}
return false;
}
static void kcompactd_do_work(pg_data_t *pgdat)
{
/*
* With no special task, compact all zones so that a page of requested
* order is allocatable.
*/
int zoneid;
struct zone *zone;
struct compact_control cc = {
.order = pgdat->kcompactd_max_order,
.search_order = pgdat->kcompactd_max_order,
.highest_zoneidx = pgdat->kcompactd_highest_zoneidx,
.mode = MIGRATE_SYNC_LIGHT,
.ignore_skip_hint = false,
.gfp_mask = GFP_KERNEL,
};
trace_mm_compaction_kcompactd_wake(pgdat->node_id, cc.order,
cc.highest_zoneidx);
count_compact_event(KCOMPACTD_WAKE);
for (zoneid = 0; zoneid <= cc.highest_zoneidx; zoneid++) {
int status;
zone = &pgdat->node_zones[zoneid];
if (!populated_zone(zone))
continue;
if (compaction_deferred(zone, cc.order))
continue;
if (compaction_suitable(zone, cc.order, 0, zoneid) !=
COMPACT_CONTINUE)
continue;
if (kthread_should_stop())
return;
cc.zone = zone;
status = compact_zone(&cc, NULL);
if (status == COMPACT_SUCCESS) {
compaction_defer_reset(zone, cc.order, false);
} else if (status == COMPACT_PARTIAL_SKIPPED || status == COMPACT_COMPLETE) {
/*
* Buddy pages may become stranded on pcps that could
* otherwise coalesce on the zone's free area for
* order >= cc.order. This is ratelimited by the
* upcoming deferral.
*/
drain_all_pages(zone);
/*
* We use sync migration mode here, so we defer like
* sync direct compaction does.
*/
defer_compaction(zone, cc.order);
}
count_compact_events(KCOMPACTD_MIGRATE_SCANNED,
cc.total_migrate_scanned);
count_compact_events(KCOMPACTD_FREE_SCANNED,
cc.total_free_scanned);
VM_BUG_ON(!list_empty(&cc.freepages));
VM_BUG_ON(!list_empty(&cc.migratepages));
}
/*
* Regardless of success, we are done until woken up next. But remember
* the requested order/highest_zoneidx in case it was higher/tighter
* than our current ones
*/
if (pgdat->kcompactd_max_order <= cc.order)
pgdat->kcompactd_max_order = 0;
if (pgdat->kcompactd_highest_zoneidx >= cc.highest_zoneidx)
pgdat->kcompactd_highest_zoneidx = pgdat->nr_zones - 1;
}
void wakeup_kcompactd(pg_data_t *pgdat, int order, int highest_zoneidx)
{
if (!order)
return;
if (pgdat->kcompactd_max_order < order)
pgdat->kcompactd_max_order = order;
if (pgdat->kcompactd_highest_zoneidx > highest_zoneidx)
pgdat->kcompactd_highest_zoneidx = highest_zoneidx;
/*
* Pairs with implicit barrier in wait_event_freezable()
* such that wakeups are not missed.
*/
if (!wq_has_sleeper(&pgdat->kcompactd_wait))
return;
if (!kcompactd_node_suitable(pgdat))
return;
trace_mm_compaction_wakeup_kcompactd(pgdat->node_id, order,
highest_zoneidx);
wake_up_interruptible(&pgdat->kcompactd_wait);
}
/*
* The background compaction daemon, started as a kernel thread
* from the init process.
*/
static int kcompactd(void *p)
{
pg_data_t *pgdat = (pg_data_t*)p;
struct task_struct *tsk = current;
unsigned int proactive_defer = 0;
const struct cpumask *cpumask = cpumask_of_node(pgdat->node_id);
if (!cpumask_empty(cpumask))
set_cpus_allowed_ptr(tsk, cpumask);
set_freezable();
pgdat->kcompactd_max_order = 0;
pgdat->kcompactd_highest_zoneidx = pgdat->nr_zones - 1;
while (!kthread_should_stop()) {
unsigned long pflags;
trace_mm_compaction_kcompactd_sleep(pgdat->node_id);
if (wait_event_freezable_timeout(pgdat->kcompactd_wait,
kcompactd_work_requested(pgdat),
msecs_to_jiffies(HPAGE_FRAG_CHECK_INTERVAL_MSEC))) {
psi_memstall_enter(&pflags);
kcompactd_do_work(pgdat);
psi_memstall_leave(&pflags);
continue;
}
/* kcompactd wait timeout */
if (should_proactive_compact_node(pgdat)) {
unsigned int prev_score, score;
if (proactive_defer) {
proactive_defer--;
continue;
}
prev_score = fragmentation_score_node(pgdat);
proactive_compact_node(pgdat);
score = fragmentation_score_node(pgdat);
/*
* Defer proactive compaction if the fragmentation
* score did not go down i.e. no progress made.
*/
proactive_defer = score < prev_score ?
0 : 1 << COMPACT_MAX_DEFER_SHIFT;
}
}
return 0;
}
/*
* This kcompactd start function will be called by init and node-hot-add.
* On node-hot-add, kcompactd will moved to proper cpus if cpus are hot-added.
*/
int kcompactd_run(int nid)
{
pg_data_t *pgdat = NODE_DATA(nid);
int ret = 0;
if (pgdat->kcompactd)
return 0;
pgdat->kcompactd = kthread_run(kcompactd, pgdat, "kcompactd%d", nid);
if (IS_ERR(pgdat->kcompactd)) {
pr_err("Failed to start kcompactd on node %d\n", nid);
ret = PTR_ERR(pgdat->kcompactd);
pgdat->kcompactd = NULL;
}
return ret;
}
/*
* Called by memory hotplug when all memory in a node is offlined. Caller must
* hold mem_hotplug_begin/end().
*/
void kcompactd_stop(int nid)
{
struct task_struct *kcompactd = NODE_DATA(nid)->kcompactd;
if (kcompactd) {
kthread_stop(kcompactd);
NODE_DATA(nid)->kcompactd = NULL;
}
}
/*
* It's optimal to keep kcompactd on the same CPUs as their memory, but
* not required for correctness. So if the last cpu in a node goes
* away, we get changed to run anywhere: as the first one comes back,
* restore their cpu bindings.
*/
static int kcompactd_cpu_online(unsigned int cpu)
{
int nid;
for_each_node_state(nid, N_MEMORY) {
pg_data_t *pgdat = NODE_DATA(nid);
const struct cpumask *mask;
mask = cpumask_of_node(pgdat->node_id);
if (cpumask_any_and(cpu_online_mask, mask) < nr_cpu_ids)
/* One of our CPUs online: restore mask */
set_cpus_allowed_ptr(pgdat->kcompactd, mask);
}
return 0;
}
static int __init kcompactd_init(void)
{
int nid;
int ret;
ret = cpuhp_setup_state_nocalls(CPUHP_AP_ONLINE_DYN,
"mm/compaction:online",
kcompactd_cpu_online, NULL);
if (ret < 0) {
pr_err("kcompactd: failed to register hotplug callbacks.\n");
return ret;
}
for_each_node_state(nid, N_MEMORY)
kcompactd_run(nid);
return 0;
}
subsys_initcall(kcompactd_init)
#endif /* CONFIG_COMPACTION */
| {
"pile_set_name": "Github"
} |
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package mozilla.components.support.ktx.android.view
import android.view.MotionEvent
import android.view.MotionEvent.ACTION_DOWN
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.Assert.assertEquals
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.Mockito.spy
import org.mockito.Mockito.times
import org.mockito.Mockito.verify
@RunWith(AndroidJUnit4::class)
class MotionEventKtTest {
private lateinit var subject: MotionEvent
private lateinit var subjectSpy: MotionEvent
@Before
fun setUp() {
subject = MotionEvent.obtain(100, 100, ACTION_DOWN, 0f, 0f, 0)
subjectSpy = spy(subject)
}
@Test
fun `WHEN use is called without an exception THEN the object is recycled`() {
subjectSpy.use {}
verify(subjectSpy, times(1)).recycle()
}
@Test
fun `WHEN use is called with an exception THEN the object is recycled`() {
try { subjectSpy.use { throw IllegalStateException("Catch me!") } } catch (e: Exception) { /* Do nothing */ }
verify(subjectSpy, times(1)).recycle()
}
@Test
fun `WHEN use is called and its function returns a value THEN that value is returned`() {
val expected = 47
assertEquals(expected, subject.use { expected })
}
@Test(expected = IllegalStateException::class)
fun `WHEN use is called and its function throws an exception THEN that exception is thrown`() {
subject.use { throw IllegalStateException() }
}
@Test
fun `WHEN use is called THEN the use function's argument is the use receiver`() {
subject.use { assertEquals(subject, it) }
}
}
| {
"pile_set_name": "Github"
} |
{
"images" : [
{
"idiom" : "iphone",
"size" : "29x29",
"scale" : "2x"
},
{
"idiom" : "iphone",
"size" : "29x29",
"scale" : "3x"
},
{
"idiom" : "iphone",
"size" : "40x40",
"scale" : "2x"
},
{
"idiom" : "iphone",
"size" : "40x40",
"scale" : "3x"
},
{
"idiom" : "iphone",
"size" : "60x60",
"scale" : "2x"
},
{
"idiom" : "iphone",
"size" : "60x60",
"scale" : "3x"
}
],
"info" : {
"version" : 1,
"author" : "xcode"
}
} | {
"pile_set_name": "Github"
} |
From 5357e5991f09f78e945b3adcc5db0ebfa1766dc1 Mon Sep 17 00:00:00 2001
From: Dave Stevenson <dave.stevenson@raspberrypi.org>
Date: Tue, 9 Apr 2019 12:37:28 +0100
Subject: [PATCH] drm: vc4: Query the display ID for each display in
FKMS
Replace the hard coded list of display IDs for a mailbox call
that returns the display ID for each display that has been
detected.
Signed-off-by: Dave Stevenson <dave.stevenson@raspberrypi.org>
---
drivers/gpu/drm/vc4/vc4_firmware_kms.c | 16 +++++++++++++---
include/soc/bcm2835/raspberrypi-firmware.h | 1 +
2 files changed, 14 insertions(+), 3 deletions(-)
--- a/drivers/gpu/drm/vc4/vc4_firmware_kms.c
+++ b/drivers/gpu/drm/vc4/vc4_firmware_kms.c
@@ -944,7 +944,7 @@ static int vc4_fkms_bind(struct device *
struct vc4_crtc **crtc_list;
u32 num_displays, display_num;
int ret;
- const u32 display_num_lookup[] = {2, 7, 1};
+ u32 display_id;
vc4->firmware_kms = true;
@@ -983,8 +983,18 @@ static int vc4_fkms_bind(struct device *
return -ENOMEM;
for (display_num = 0; display_num < num_displays; display_num++) {
- ret = vc4_fkms_create_screen(dev, drm, display_num,
- display_num_lookup[display_num],
+ display_id = display_num;
+ ret = rpi_firmware_property(vc4->firmware,
+ RPI_FIRMWARE_FRAMEBUFFER_GET_DISPLAY_ID,
+ &display_id, sizeof(display_id));
+ /* FIXME: Determine the correct error handling here.
+ * Should we fail to create the one "screen" but keep the
+ * others, or fail the whole thing?
+ */
+ if (ret)
+ DRM_ERROR("Failed to get display id %u\n", display_num);
+
+ ret = vc4_fkms_create_screen(dev, drm, display_num, display_id,
&crtc_list[display_num]);
if (ret)
DRM_ERROR("Oh dear, failed to create display %u\n",
--- a/include/soc/bcm2835/raspberrypi-firmware.h
+++ b/include/soc/bcm2835/raspberrypi-firmware.h
@@ -114,6 +114,7 @@ enum rpi_firmware_property_tag {
RPI_FIRMWARE_FRAMEBUFFER_GET_TOUCHBUF = 0x0004000f,
RPI_FIRMWARE_FRAMEBUFFER_GET_GPIOVIRTBUF = 0x00040010,
RPI_FIRMWARE_FRAMEBUFFER_RELEASE = 0x00048001,
+ RPI_FIRMWARE_FRAMEBUFFER_GET_DISPLAY_ID = 0x00040016,
RPI_FIRMWARE_FRAMEBUFFER_SET_DISPLAY_NUM = 0x00048013,
RPI_FIRMWARE_FRAMEBUFFER_GET_NUM_DISPLAYS = 0x00040013,
RPI_FIRMWARE_FRAMEBUFFER_GET_DISPLAY_SETTINGS = 0x00040014,
| {
"pile_set_name": "Github"
} |
// SPDX-License-Identifier: ISC
/*
* Copyright (c) 2010 Broadcom Corporation
*/
#ifndef BRCMFMAC_DEBUG_H
#define BRCMFMAC_DEBUG_H
#include <linux/net.h> /* net_ratelimit() */
/* message levels */
#define BRCMF_TRACE_VAL 0x00000002
#define BRCMF_INFO_VAL 0x00000004
#define BRCMF_DATA_VAL 0x00000008
#define BRCMF_CTL_VAL 0x00000010
#define BRCMF_TIMER_VAL 0x00000020
#define BRCMF_HDRS_VAL 0x00000040
#define BRCMF_BYTES_VAL 0x00000080
#define BRCMF_INTR_VAL 0x00000100
#define BRCMF_GLOM_VAL 0x00000200
#define BRCMF_EVENT_VAL 0x00000400
#define BRCMF_BTA_VAL 0x00000800
#define BRCMF_FIL_VAL 0x00001000
#define BRCMF_USB_VAL 0x00002000
#define BRCMF_SCAN_VAL 0x00004000
#define BRCMF_CONN_VAL 0x00008000
#define BRCMF_BCDC_VAL 0x00010000
#define BRCMF_SDIO_VAL 0x00020000
#define BRCMF_MSGBUF_VAL 0x00040000
#define BRCMF_PCIE_VAL 0x00080000
#define BRCMF_FWCON_VAL 0x00100000
/* set default print format */
#undef pr_fmt
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
struct brcmf_bus;
__printf(3, 4)
void __brcmf_err(struct brcmf_bus *bus, const char *func, const char *fmt, ...);
/* Macro for error messages. When debugging / tracing the driver all error
* messages are important to us.
*/
#ifndef brcmf_err
#define brcmf_err(fmt, ...) \
do { \
if (IS_ENABLED(CONFIG_BRCMDBG) || \
IS_ENABLED(CONFIG_BRCM_TRACING) || \
net_ratelimit()) \
__brcmf_err(NULL, __func__, fmt, ##__VA_ARGS__);\
} while (0)
#endif
#define bphy_err(drvr, fmt, ...) \
do { \
if (IS_ENABLED(CONFIG_BRCMDBG) || \
IS_ENABLED(CONFIG_BRCM_TRACING) || \
net_ratelimit()) \
wiphy_err((drvr)->wiphy, "%s: " fmt, __func__, \
##__VA_ARGS__); \
} while (0)
#if defined(DEBUG) || defined(CONFIG_BRCM_TRACING)
/* For debug/tracing purposes treat info messages as errors */
#define brcmf_info brcmf_err
__printf(3, 4)
void __brcmf_dbg(u32 level, const char *func, const char *fmt, ...);
#define brcmf_dbg(level, fmt, ...) \
do { \
__brcmf_dbg(BRCMF_##level##_VAL, __func__, \
fmt, ##__VA_ARGS__); \
} while (0)
#define BRCMF_DATA_ON() (brcmf_msg_level & BRCMF_DATA_VAL)
#define BRCMF_CTL_ON() (brcmf_msg_level & BRCMF_CTL_VAL)
#define BRCMF_HDRS_ON() (brcmf_msg_level & BRCMF_HDRS_VAL)
#define BRCMF_BYTES_ON() (brcmf_msg_level & BRCMF_BYTES_VAL)
#define BRCMF_GLOM_ON() (brcmf_msg_level & BRCMF_GLOM_VAL)
#define BRCMF_EVENT_ON() (brcmf_msg_level & BRCMF_EVENT_VAL)
#define BRCMF_FIL_ON() (brcmf_msg_level & BRCMF_FIL_VAL)
#define BRCMF_FWCON_ON() (brcmf_msg_level & BRCMF_FWCON_VAL)
#define BRCMF_SCAN_ON() (brcmf_msg_level & BRCMF_SCAN_VAL)
#else /* defined(DEBUG) || defined(CONFIG_BRCM_TRACING) */
#define brcmf_info(fmt, ...) \
do { \
pr_info("%s: " fmt, __func__, ##__VA_ARGS__); \
} while (0)
#define brcmf_dbg(level, fmt, ...) no_printk(fmt, ##__VA_ARGS__)
#define BRCMF_DATA_ON() 0
#define BRCMF_CTL_ON() 0
#define BRCMF_HDRS_ON() 0
#define BRCMF_BYTES_ON() 0
#define BRCMF_GLOM_ON() 0
#define BRCMF_EVENT_ON() 0
#define BRCMF_FIL_ON() 0
#define BRCMF_FWCON_ON() 0
#define BRCMF_SCAN_ON() 0
#endif /* defined(DEBUG) || defined(CONFIG_BRCM_TRACING) */
#define brcmf_dbg_hex_dump(test, data, len, fmt, ...) \
do { \
trace_brcmf_hexdump((void *)data, len); \
if (test) \
brcmu_dbg_hex_dump(data, len, fmt, ##__VA_ARGS__); \
} while (0)
extern int brcmf_msg_level;
struct brcmf_bus;
struct brcmf_pub;
#ifdef DEBUG
struct dentry *brcmf_debugfs_get_devdir(struct brcmf_pub *drvr);
void brcmf_debugfs_add_entry(struct brcmf_pub *drvr, const char *fn,
int (*read_fn)(struct seq_file *seq, void *data));
int brcmf_debug_create_memdump(struct brcmf_bus *bus, const void *data,
size_t len);
#else
static inline struct dentry *brcmf_debugfs_get_devdir(struct brcmf_pub *drvr)
{
return ERR_PTR(-ENOENT);
}
static inline
void brcmf_debugfs_add_entry(struct brcmf_pub *drvr, const char *fn,
int (*read_fn)(struct seq_file *seq, void *data))
{ }
static inline
int brcmf_debug_create_memdump(struct brcmf_bus *bus, const void *data,
size_t len)
{
return 0;
}
#endif
#endif /* BRCMFMAC_DEBUG_H */
| {
"pile_set_name": "Github"
} |
# A generic, single database configuration.
[alembic]
# path to migration scripts
script_location = murano/db/cfapi_migration/alembic_migrations
# template used to generate migration files
# file_template = %%(rev)s_%%(slug)s
# max length of characters to apply to the
# "slug" field
#truncate_slug_length = 40
# set to 'true' to run the environment during
# the 'revision' command, regardless of autogenerate
# revision_environment = false
sqlalchemy.url =
# Logging configuration
[loggers]
keys = root,sqlalchemy,alembic
[handlers]
keys = console
[formatters]
keys = generic
[logger_root]
level = WARN
handlers = console
qualname =
[logger_sqlalchemy]
level = WARN
handlers =
qualname = sqlalchemy.engine
[logger_alembic]
level = INFO
handlers =
qualname = alembic
[handler_console]
class = StreamHandler
args = (sys.stderr,)
level = NOTSET
formatter = generic
[formatter_generic]
format = %(levelname)-5.5s [%(name)s] %(message)s
datefmt = %H:%M:%S
| {
"pile_set_name": "Github"
} |
################## BASE IMAGE ######################
FROM biocontainers/biocontainers:v1.0.0_cv4
################## METADATA ######################
LABEL base_image="biocontainers:v1.0.0_cv4"
LABEL version="3"
LABEL software="PeptideProphet"
LABEL software.version="201510131012"
LABEL about.summary="Peptide assignment statistics and validation"
LABEL about.home="http://peptideprophet.sourceforge.net/"
LABEL about.documentation="http://peptideprophet.sourceforge.net/"
LABEL about.license_file="http://peptideprophet.sourceforge.net/"
LABEL about.license="SPDX:GPL-2.0-only"
LABEL about.tags="Proteomics"
LABEL extra.identifiers.biotools="peptideprophet"
LABEL extra.binaries="PeptideProphet"
################## MAINTAINER ######################
MAINTAINER Felipe da Veiga Leprevost <felipe@leprevost.com.br>
USER biodocker
RUN ZIP=PeptideProphetParser.zip && \
wget https://github.com/BioDocker/software-archive/releases/download/PeptideProphet/$ZIP -O /tmp/$ZIP && \
unzip /tmp/$ZIP -d /home/biodocker/bin/ && \
chmod -R 755 /home/biodocker/bin/* && \
rm /tmp/$ZIP
RUN mv /home/biodocker/bin/PeptideProphetParser /home/biodocker/bin/PeptideProphet
ENV PATH /home/biodocker/bin:$PATH
WORKDIR /data/
# CMD ["PeptideProphet"]
| {
"pile_set_name": "Github"
} |
/*
* boot-common.c
*
* Common bootmode functions for omap based boards
*
* Copyright (C) 2011, Texas Instruments, Incorporated - http://www.ti.com/
*
* SPDX-License-Identifier: GPL-2.0+
*/
#include <common.h>
#include <spl.h>
#include <asm/omap_common.h>
#include <asm/arch/omap.h>
#include <asm/arch/mmc_host_def.h>
#include <asm/arch/sys_proto.h>
#include <watchdog.h>
DECLARE_GLOBAL_DATA_PTR;
void save_omap_boot_params(void)
{
u32 rom_params = *((u32 *)OMAP_SRAM_SCRATCH_BOOT_PARAMS);
u8 boot_device;
u32 dev_desc, dev_data;
if ((rom_params < NON_SECURE_SRAM_START) ||
(rom_params > NON_SECURE_SRAM_END))
return;
/*
* rom_params can be type casted to omap_boot_parameters and
* used. But it not correct to assume that romcode structure
* encoding would be same as u-boot. So use the defined offsets.
*/
gd->arch.omap_boot_params.omap_bootdevice = boot_device =
*((u8 *)(rom_params + BOOT_DEVICE_OFFSET));
gd->arch.omap_boot_params.ch_flags =
*((u8 *)(rom_params + CH_FLAGS_OFFSET));
if ((boot_device >= MMC_BOOT_DEVICES_START) &&
(boot_device <= MMC_BOOT_DEVICES_END)) {
#if !defined(CONFIG_AM33XX) && !defined(CONFIG_TI81XX) && \
!defined(CONFIG_AM43XX)
if ((omap_hw_init_context() ==
OMAP_INIT_CONTEXT_UBOOT_AFTER_SPL)) {
gd->arch.omap_boot_params.omap_bootmode =
*((u8 *)(rom_params + BOOT_MODE_OFFSET));
} else
#endif
{
dev_desc = *((u32 *)(rom_params + DEV_DESC_PTR_OFFSET));
dev_data = *((u32 *)(dev_desc + DEV_DATA_PTR_OFFSET));
gd->arch.omap_boot_params.omap_bootmode =
*((u32 *)(dev_data + BOOT_MODE_OFFSET));
}
}
#ifdef CONFIG_DRA7XX
/*
* We get different values for QSPI_1 and QSPI_4 being used, but
* don't actually care about this difference. Rather than
* mangle the later code, if we're coming in as QSPI_4 just
* change to the QSPI_1 value.
*/
if (gd->arch.omap_boot_params.omap_bootdevice == 11)
gd->arch.omap_boot_params.omap_bootdevice = BOOT_DEVICE_SPI;
#endif
}
#ifdef CONFIG_SPL_BUILD
u32 spl_boot_device(void)
{
return (u32) (gd->arch.omap_boot_params.omap_bootdevice);
}
u32 spl_boot_mode(void)
{
u32 val = gd->arch.omap_boot_params.omap_bootmode;
if (val == MMCSD_MODE_RAW)
return MMCSD_MODE_RAW;
else if (val == MMCSD_MODE_FAT)
return MMCSD_MODE_FAT;
else
#ifdef CONFIG_SUPPORT_EMMC_BOOT
return MMCSD_MODE_EMMCBOOT;
#else
return MMCSD_MODE_UNDEFINED;
#endif
}
void spl_board_init(void)
{
#ifdef CONFIG_SPL_NAND_SUPPORT
gpmc_init();
#endif
#if defined(CONFIG_AM33XX) && defined(CONFIG_SPL_MUSB_NEW_SUPPORT)
arch_misc_init();
#endif
#if defined(CONFIG_HW_WATCHDOG)
hw_watchdog_init();
#endif
#ifdef CONFIG_AM33XX
am33xx_spl_board_init();
#endif
}
int board_mmc_init(bd_t *bis)
{
switch (spl_boot_device()) {
case BOOT_DEVICE_MMC1:
omap_mmc_init(0, 0, 0, -1, -1);
break;
case BOOT_DEVICE_MMC2:
case BOOT_DEVICE_MMC2_2:
omap_mmc_init(1, 0, 0, -1, -1);
break;
}
return 0;
}
void __noreturn jump_to_image_no_args(struct spl_image_info *spl_image)
{
typedef void __noreturn (*image_entry_noargs_t)(u32 *);
image_entry_noargs_t image_entry =
(image_entry_noargs_t) spl_image->entry_point;
debug("image entry point: 0x%X\n", spl_image->entry_point);
/* Pass the saved boot_params from rom code */
image_entry((u32 *)&gd->arch.omap_boot_params);
}
#endif
| {
"pile_set_name": "Github"
} |
import React from 'react';
import PropTypes from 'prop-types';
const Degree = ({ data }) => (
<article className="degree-container">
<header>
<h4 className="degree">{data.degree}</h4>
<p className="school"><a href={data.link}>{data.school}</a>, {data.year}</p>
</header>
</article>
);
Degree.propTypes = {
data: PropTypes.shape({
degree: PropTypes.string.isRequired,
link: PropTypes.string.isRequired,
school: PropTypes.string.isRequired,
year: PropTypes.number.isRequired,
}).isRequired,
};
export default Degree;
| {
"pile_set_name": "Github"
} |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.constant.ParamConstants import *
class AlipayEbppInvoiceFinancialBlockchainBatchqueryModel(object):
def __init__(self):
self._cert_no_hash = None
self._cert_type = None
self._current_page = None
self._invoice_kind = None
self._page_size = None
@property
def cert_no_hash(self):
return self._cert_no_hash
@cert_no_hash.setter
def cert_no_hash(self, value):
self._cert_no_hash = value
@property
def cert_type(self):
return self._cert_type
@cert_type.setter
def cert_type(self, value):
self._cert_type = value
@property
def current_page(self):
return self._current_page
@current_page.setter
def current_page(self, value):
self._current_page = value
@property
def invoice_kind(self):
return self._invoice_kind
@invoice_kind.setter
def invoice_kind(self, value):
self._invoice_kind = value
@property
def page_size(self):
return self._page_size
@page_size.setter
def page_size(self, value):
self._page_size = value
def to_alipay_dict(self):
params = dict()
if self.cert_no_hash:
if hasattr(self.cert_no_hash, 'to_alipay_dict'):
params['cert_no_hash'] = self.cert_no_hash.to_alipay_dict()
else:
params['cert_no_hash'] = self.cert_no_hash
if self.cert_type:
if hasattr(self.cert_type, 'to_alipay_dict'):
params['cert_type'] = self.cert_type.to_alipay_dict()
else:
params['cert_type'] = self.cert_type
if self.current_page:
if hasattr(self.current_page, 'to_alipay_dict'):
params['current_page'] = self.current_page.to_alipay_dict()
else:
params['current_page'] = self.current_page
if self.invoice_kind:
if hasattr(self.invoice_kind, 'to_alipay_dict'):
params['invoice_kind'] = self.invoice_kind.to_alipay_dict()
else:
params['invoice_kind'] = self.invoice_kind
if self.page_size:
if hasattr(self.page_size, 'to_alipay_dict'):
params['page_size'] = self.page_size.to_alipay_dict()
else:
params['page_size'] = self.page_size
return params
@staticmethod
def from_alipay_dict(d):
if not d:
return None
o = AlipayEbppInvoiceFinancialBlockchainBatchqueryModel()
if 'cert_no_hash' in d:
o.cert_no_hash = d['cert_no_hash']
if 'cert_type' in d:
o.cert_type = d['cert_type']
if 'current_page' in d:
o.current_page = d['current_page']
if 'invoice_kind' in d:
o.invoice_kind = d['invoice_kind']
if 'page_size' in d:
o.page_size = d['page_size']
return o
| {
"pile_set_name": "Github"
} |
<!doctype html>
<html>
<head>
<title>Page with inconsistent CSS prefixes</title>
<link rel="stylesheet" href="inconsistent-prefixes.css">
</head>
<body>
</body>
</html>
| {
"pile_set_name": "Github"
} |
<?php
namespace Kunstmaan\NodeBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\HiddenType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
/**
* NodeTranslationAdminType
*/
class NodeTranslationAdminType extends AbstractType
{
/**
* @param FormBuilderInterface $builder
* @param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('id', HiddenType::class);
}
/**
* @return string
*/
public function getBlockPrefix()
{
return 'nodetranslation';
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'Kunstmaan\NodeBundle\Entity\NodeTranslation',
));
}
}
| {
"pile_set_name": "Github"
} |
//
// Copyright (c) ZeroC, Inc. All rights reserved.
//
#import <slicing/exceptions/TestI.h>
#import <TestCommon.h>
#import <objc/Ice.h>
@implementation TestSlicingExceptionsServerI
-(void) baseAsBase:(ICECurrent*)__unused current
{
@throw [TestSlicingExceptionsServerBase base:@"Base.b"];
}
-(void) unknownDerivedAsBase:(ICECurrent*)__unused current
{
@throw [TestSlicingExceptionsServerUnknownDerived unknownDerived:@"UnknownDerived.b" ud:@"UnknownDerived.ud"];
}
-(void) knownDerivedAsBase:(ICECurrent*)__unused current
{
@throw [TestSlicingExceptionsServerKnownDerived knownDerived:@"KnownDerived.b" kd:@"KnownDerived.kd"];
}
-(void) knownDerivedAsKnownDerived:(ICECurrent*)__unused current
{
@throw [TestSlicingExceptionsServerKnownDerived knownDerived:@"KnownDerived.b" kd:@"KnownDerived.kd"];
}
-(void) unknownIntermediateAsBase:(ICECurrent*)__unused current
{
@throw [TestSlicingExceptionsServerUnknownIntermediate unknownIntermediate:@"UnknownIntermediate.b" ui:@"UnknownIntermediate.ui"];
}
-(void) knownIntermediateAsBase:(ICECurrent*)__unused current
{
@throw [TestSlicingExceptionsServerKnownIntermediate knownIntermediate:@"KnownIntermediate.b" ki:@"KnownIntermediate.ki"];
}
-(void) knownMostDerivedAsBase:(ICECurrent*)__unused current
{
@throw [TestSlicingExceptionsServerKnownMostDerived knownMostDerived:@"KnownMostDerived.b" ki:@"KnownMostDerived.ki" kmd:@"KnownMostDerived.kmd"];
}
-(void) knownIntermediateAsKnownIntermediate:(ICECurrent*)__unused current
{
@throw [TestSlicingExceptionsServerKnownIntermediate knownIntermediate:@"KnownIntermediate.b" ki:@"KnownIntermediate.ki"];
}
-(void) knownMostDerivedAsKnownIntermediate:(ICECurrent*)__unused current
{
@throw [TestSlicingExceptionsServerKnownMostDerived knownMostDerived:@"KnownMostDerived.b" ki:@"KnownMostDerived.ki" kmd:@"KnownMostDerived.kmd"];
}
-(void) knownMostDerivedAsKnownMostDerived:(ICECurrent*)__unused current
{
@throw [TestSlicingExceptionsServerKnownMostDerived knownMostDerived:@"KnownMostDerived.b" ki:@"KnownMostDerived.ki" kmd:@"KnownMostDerived.kmd"];
}
-(void) unknownMostDerived1AsBase:(ICECurrent*)__unused current
{
@throw [TestSlicingExceptionsServerUnknownMostDerived1 unknownMostDerived1:@"UnknownMostDerived1.b" ki:@"UnknownMostDerived1.ki" umd1:@"UnknownMostDerived1.umd1"];
}
-(void) unknownMostDerived1AsKnownIntermediate:(ICECurrent*)__unused current
{
@throw [TestSlicingExceptionsServerUnknownMostDerived1 unknownMostDerived1:@"UnknownMostDerived1.b"
ki:@"UnknownMostDerived1.ki"
umd1:@"UnknownMostDerived1.umd1"];
}
-(void) unknownMostDerived2AsBase:(ICECurrent*)__unused current
{
@throw [TestSlicingExceptionsServerUnknownMostDerived2 unknownMostDerived2:@"UnknownMostDerived2.b"
ui:@"UnknownMostDerived2.ui"
umd2:@"UnknownMostDerived2.umd2"];
}
-(void) unknownMostDerived2AsBaseCompact:(ICECurrent*)__unused current
{
@throw [TestSlicingExceptionsServerUnknownMostDerived2 unknownMostDerived2:@"UnknownMostDerived2.b"
ui:@"UnknownMostDerived2.ui"
umd2:@"UnknownMostDerived2.umd2"];
}
-(void) knownPreservedAsBase:(ICECurrent*)__unused current
{
@throw [TestSlicingExceptionsServerKnownPreservedDerived knownPreservedDerived:@"base"
kp:@"preserved"
kpd:@"derived"];
}
-(void) knownPreservedAsKnownPreserved:(ICECurrent*)__unused current
{
@throw [TestSlicingExceptionsServerKnownPreservedDerived knownPreservedDerived:@"base"
kp:@"preserved"
kpd:@"derived"];
}
-(void) relayKnownPreservedAsBase:(TestSlicingExceptionsServerRelayPrx*)relay current:(ICECurrent*)__unused current
{
TestSlicingExceptionsServerRelayPrx* p =
[TestSlicingExceptionsServerRelayPrx uncheckedCast:[current.con createProxy:[relay ice_getIdentity]]];
[p knownPreservedAsBase];
test(NO);
}
-(void) relayKnownPreservedAsKnownPreserved:(TestSlicingExceptionsServerRelayPrx*)relay current:(ICECurrent*)__unused current
{
TestSlicingExceptionsServerRelayPrx* p =
[TestSlicingExceptionsServerRelayPrx uncheckedCast:[current.con createProxy:[relay ice_getIdentity]]];
[p knownPreservedAsKnownPreserved];
test(NO);
}
-(void) unknownPreservedAsBase:(ICECurrent*)__unused current
{
TestSlicingExceptionsServerSPreserved2* ex = [TestSlicingExceptionsServerSPreserved2 sPreserved2];
ex.b = @"base";
ex.kp = @"preserved";
ex.kpd = @"derived";
ex.p1 = [TestSlicingExceptionsServerSPreservedClass sPreservedClass:@"bc" spc:@"spc"];
ex.p2 = ex.p1;
@throw ex;
}
-(void) unknownPreservedAsKnownPreserved:(ICECurrent*)__unused current
{
TestSlicingExceptionsServerSPreserved2* ex = [TestSlicingExceptionsServerSPreserved2 sPreserved2];
ex.b = @"base";
ex.kp = @"preserved";
ex.kpd = @"derived";
ex.p1 = [TestSlicingExceptionsServerSPreservedClass sPreservedClass:@"bc" spc:@"spc"];
ex.p2 = ex.p1;
@throw ex;
}
-(void) relayUnknownPreservedAsBase:(TestSlicingExceptionsServerRelayPrx*)relay current:(ICECurrent*)__unused current
{
TestSlicingExceptionsServerRelayPrx* p =
[TestSlicingExceptionsServerRelayPrx uncheckedCast:[current.con createProxy:[relay ice_getIdentity]]];
[p unknownPreservedAsBase];
test(NO);
}
-(void) relayUnknownPreservedAsKnownPreserved:(TestSlicingExceptionsServerRelayPrx*)relay current:(ICECurrent*)__unused current
{
TestSlicingExceptionsServerRelayPrx* p =
[TestSlicingExceptionsServerRelayPrx uncheckedCast:[current.con createProxy:[relay ice_getIdentity]]];
[p unknownPreservedAsKnownPreserved];
test(NO);
}
-(void) shutdown:(ICECurrent*)current
{
[[current.adapter getCommunicator] shutdown];
}
@end
| {
"pile_set_name": "Github"
} |
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// +build darwin dragonfly freebsd netbsd openbsd
// BSD system call wrappers shared by *BSD based systems
// including OS X (Darwin) and FreeBSD. Like the other
// syscall_*.go files it is compiled as Go code but also
// used as input to mksyscall which parses the //sys
// lines and generates system call stubs.
package unix
import (
"runtime"
"syscall"
"unsafe"
)
/*
* Wrapped
*/
//sysnb getgroups(ngid int, gid *_Gid_t) (n int, err error)
//sysnb setgroups(ngid int, gid *_Gid_t) (err error)
func Getgroups() (gids []int, err error) {
n, err := getgroups(0, nil)
if err != nil {
return nil, err
}
if n == 0 {
return nil, nil
}
// Sanity check group count. Max is 16 on BSD.
if n < 0 || n > 1000 {
return nil, EINVAL
}
a := make([]_Gid_t, n)
n, err = getgroups(n, &a[0])
if err != nil {
return nil, err
}
gids = make([]int, n)
for i, v := range a[0:n] {
gids[i] = int(v)
}
return
}
func Setgroups(gids []int) (err error) {
if len(gids) == 0 {
return setgroups(0, nil)
}
a := make([]_Gid_t, len(gids))
for i, v := range gids {
a[i] = _Gid_t(v)
}
return setgroups(len(a), &a[0])
}
// Wait status is 7 bits at bottom, either 0 (exited),
// 0x7F (stopped), or a signal number that caused an exit.
// The 0x80 bit is whether there was a core dump.
// An extra number (exit code, signal causing a stop)
// is in the high bits.
type WaitStatus uint32
const (
mask = 0x7F
core = 0x80
shift = 8
exited = 0
killed = 9
stopped = 0x7F
)
func (w WaitStatus) Exited() bool { return w&mask == exited }
func (w WaitStatus) ExitStatus() int {
if w&mask != exited {
return -1
}
return int(w >> shift)
}
func (w WaitStatus) Signaled() bool { return w&mask != stopped && w&mask != 0 }
func (w WaitStatus) Signal() syscall.Signal {
sig := syscall.Signal(w & mask)
if sig == stopped || sig == 0 {
return -1
}
return sig
}
func (w WaitStatus) CoreDump() bool { return w.Signaled() && w&core != 0 }
func (w WaitStatus) Stopped() bool { return w&mask == stopped && syscall.Signal(w>>shift) != SIGSTOP }
func (w WaitStatus) Killed() bool { return w&mask == killed && syscall.Signal(w>>shift) != SIGKILL }
func (w WaitStatus) Continued() bool { return w&mask == stopped && syscall.Signal(w>>shift) == SIGSTOP }
func (w WaitStatus) StopSignal() syscall.Signal {
if !w.Stopped() {
return -1
}
return syscall.Signal(w>>shift) & 0xFF
}
func (w WaitStatus) TrapCause() int { return -1 }
//sys wait4(pid int, wstatus *_C_int, options int, rusage *Rusage) (wpid int, err error)
func Wait4(pid int, wstatus *WaitStatus, options int, rusage *Rusage) (wpid int, err error) {
var status _C_int
wpid, err = wait4(pid, &status, options, rusage)
if wstatus != nil {
*wstatus = WaitStatus(status)
}
return
}
//sys accept(s int, rsa *RawSockaddrAny, addrlen *_Socklen) (fd int, err error)
//sys bind(s int, addr unsafe.Pointer, addrlen _Socklen) (err error)
//sys connect(s int, addr unsafe.Pointer, addrlen _Socklen) (err error)
//sysnb socket(domain int, typ int, proto int) (fd int, err error)
//sys getsockopt(s int, level int, name int, val unsafe.Pointer, vallen *_Socklen) (err error)
//sys setsockopt(s int, level int, name int, val unsafe.Pointer, vallen uintptr) (err error)
//sysnb getpeername(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error)
//sysnb getsockname(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error)
//sys Shutdown(s int, how int) (err error)
func (sa *SockaddrInet4) sockaddr() (unsafe.Pointer, _Socklen, error) {
if sa.Port < 0 || sa.Port > 0xFFFF {
return nil, 0, EINVAL
}
sa.raw.Len = SizeofSockaddrInet4
sa.raw.Family = AF_INET
p := (*[2]byte)(unsafe.Pointer(&sa.raw.Port))
p[0] = byte(sa.Port >> 8)
p[1] = byte(sa.Port)
for i := 0; i < len(sa.Addr); i++ {
sa.raw.Addr[i] = sa.Addr[i]
}
return unsafe.Pointer(&sa.raw), _Socklen(sa.raw.Len), nil
}
func (sa *SockaddrInet6) sockaddr() (unsafe.Pointer, _Socklen, error) {
if sa.Port < 0 || sa.Port > 0xFFFF {
return nil, 0, EINVAL
}
sa.raw.Len = SizeofSockaddrInet6
sa.raw.Family = AF_INET6
p := (*[2]byte)(unsafe.Pointer(&sa.raw.Port))
p[0] = byte(sa.Port >> 8)
p[1] = byte(sa.Port)
sa.raw.Scope_id = sa.ZoneId
for i := 0; i < len(sa.Addr); i++ {
sa.raw.Addr[i] = sa.Addr[i]
}
return unsafe.Pointer(&sa.raw), _Socklen(sa.raw.Len), nil
}
func (sa *SockaddrUnix) sockaddr() (unsafe.Pointer, _Socklen, error) {
name := sa.Name
n := len(name)
if n >= len(sa.raw.Path) || n == 0 {
return nil, 0, EINVAL
}
sa.raw.Len = byte(3 + n) // 2 for Family, Len; 1 for NUL
sa.raw.Family = AF_UNIX
for i := 0; i < n; i++ {
sa.raw.Path[i] = int8(name[i])
}
return unsafe.Pointer(&sa.raw), _Socklen(sa.raw.Len), nil
}
func (sa *SockaddrDatalink) sockaddr() (unsafe.Pointer, _Socklen, error) {
if sa.Index == 0 {
return nil, 0, EINVAL
}
sa.raw.Len = sa.Len
sa.raw.Family = AF_LINK
sa.raw.Index = sa.Index
sa.raw.Type = sa.Type
sa.raw.Nlen = sa.Nlen
sa.raw.Alen = sa.Alen
sa.raw.Slen = sa.Slen
for i := 0; i < len(sa.raw.Data); i++ {
sa.raw.Data[i] = sa.Data[i]
}
return unsafe.Pointer(&sa.raw), SizeofSockaddrDatalink, nil
}
func anyToSockaddr(fd int, rsa *RawSockaddrAny) (Sockaddr, error) {
switch rsa.Addr.Family {
case AF_LINK:
pp := (*RawSockaddrDatalink)(unsafe.Pointer(rsa))
sa := new(SockaddrDatalink)
sa.Len = pp.Len
sa.Family = pp.Family
sa.Index = pp.Index
sa.Type = pp.Type
sa.Nlen = pp.Nlen
sa.Alen = pp.Alen
sa.Slen = pp.Slen
for i := 0; i < len(sa.Data); i++ {
sa.Data[i] = pp.Data[i]
}
return sa, nil
case AF_UNIX:
pp := (*RawSockaddrUnix)(unsafe.Pointer(rsa))
if pp.Len < 2 || pp.Len > SizeofSockaddrUnix {
return nil, EINVAL
}
sa := new(SockaddrUnix)
// Some BSDs include the trailing NUL in the length, whereas
// others do not. Work around this by subtracting the leading
// family and len. The path is then scanned to see if a NUL
// terminator still exists within the length.
n := int(pp.Len) - 2 // subtract leading Family, Len
for i := 0; i < n; i++ {
if pp.Path[i] == 0 {
// found early NUL; assume Len included the NUL
// or was overestimating.
n = i
break
}
}
bytes := (*[len(pp.Path)]byte)(unsafe.Pointer(&pp.Path[0]))[0:n]
sa.Name = string(bytes)
return sa, nil
case AF_INET:
pp := (*RawSockaddrInet4)(unsafe.Pointer(rsa))
sa := new(SockaddrInet4)
p := (*[2]byte)(unsafe.Pointer(&pp.Port))
sa.Port = int(p[0])<<8 + int(p[1])
for i := 0; i < len(sa.Addr); i++ {
sa.Addr[i] = pp.Addr[i]
}
return sa, nil
case AF_INET6:
pp := (*RawSockaddrInet6)(unsafe.Pointer(rsa))
sa := new(SockaddrInet6)
p := (*[2]byte)(unsafe.Pointer(&pp.Port))
sa.Port = int(p[0])<<8 + int(p[1])
sa.ZoneId = pp.Scope_id
for i := 0; i < len(sa.Addr); i++ {
sa.Addr[i] = pp.Addr[i]
}
return sa, nil
}
return nil, EAFNOSUPPORT
}
func Accept(fd int) (nfd int, sa Sockaddr, err error) {
var rsa RawSockaddrAny
var len _Socklen = SizeofSockaddrAny
nfd, err = accept(fd, &rsa, &len)
if err != nil {
return
}
if runtime.GOOS == "darwin" && len == 0 {
// Accepted socket has no address.
// This is likely due to a bug in xnu kernels,
// where instead of ECONNABORTED error socket
// is accepted, but has no address.
Close(nfd)
return 0, nil, ECONNABORTED
}
sa, err = anyToSockaddr(fd, &rsa)
if err != nil {
Close(nfd)
nfd = 0
}
return
}
func Getsockname(fd int) (sa Sockaddr, err error) {
var rsa RawSockaddrAny
var len _Socklen = SizeofSockaddrAny
if err = getsockname(fd, &rsa, &len); err != nil {
return
}
// TODO(jsing): DragonFly has a "bug" (see issue 3349), which should be
// reported upstream.
if runtime.GOOS == "dragonfly" && rsa.Addr.Family == AF_UNSPEC && rsa.Addr.Len == 0 {
rsa.Addr.Family = AF_UNIX
rsa.Addr.Len = SizeofSockaddrUnix
}
return anyToSockaddr(fd, &rsa)
}
//sysnb socketpair(domain int, typ int, proto int, fd *[2]int32) (err error)
// GetsockoptString returns the string value of the socket option opt for the
// socket associated with fd at the given socket level.
func GetsockoptString(fd, level, opt int) (string, error) {
buf := make([]byte, 256)
vallen := _Socklen(len(buf))
err := getsockopt(fd, level, opt, unsafe.Pointer(&buf[0]), &vallen)
if err != nil {
return "", err
}
return string(buf[:vallen-1]), nil
}
//sys recvfrom(fd int, p []byte, flags int, from *RawSockaddrAny, fromlen *_Socklen) (n int, err error)
//sys sendto(s int, buf []byte, flags int, to unsafe.Pointer, addrlen _Socklen) (err error)
//sys recvmsg(s int, msg *Msghdr, flags int) (n int, err error)
func Recvmsg(fd int, p, oob []byte, flags int) (n, oobn int, recvflags int, from Sockaddr, err error) {
var msg Msghdr
var rsa RawSockaddrAny
msg.Name = (*byte)(unsafe.Pointer(&rsa))
msg.Namelen = uint32(SizeofSockaddrAny)
var iov Iovec
if len(p) > 0 {
iov.Base = (*byte)(unsafe.Pointer(&p[0]))
iov.SetLen(len(p))
}
var dummy byte
if len(oob) > 0 {
// receive at least one normal byte
if len(p) == 0 {
iov.Base = &dummy
iov.SetLen(1)
}
msg.Control = (*byte)(unsafe.Pointer(&oob[0]))
msg.SetControllen(len(oob))
}
msg.Iov = &iov
msg.Iovlen = 1
if n, err = recvmsg(fd, &msg, flags); err != nil {
return
}
oobn = int(msg.Controllen)
recvflags = int(msg.Flags)
// source address is only specified if the socket is unconnected
if rsa.Addr.Family != AF_UNSPEC {
from, err = anyToSockaddr(fd, &rsa)
}
return
}
//sys sendmsg(s int, msg *Msghdr, flags int) (n int, err error)
func Sendmsg(fd int, p, oob []byte, to Sockaddr, flags int) (err error) {
_, err = SendmsgN(fd, p, oob, to, flags)
return
}
func SendmsgN(fd int, p, oob []byte, to Sockaddr, flags int) (n int, err error) {
var ptr unsafe.Pointer
var salen _Socklen
if to != nil {
ptr, salen, err = to.sockaddr()
if err != nil {
return 0, err
}
}
var msg Msghdr
msg.Name = (*byte)(unsafe.Pointer(ptr))
msg.Namelen = uint32(salen)
var iov Iovec
if len(p) > 0 {
iov.Base = (*byte)(unsafe.Pointer(&p[0]))
iov.SetLen(len(p))
}
var dummy byte
if len(oob) > 0 {
// send at least one normal byte
if len(p) == 0 {
iov.Base = &dummy
iov.SetLen(1)
}
msg.Control = (*byte)(unsafe.Pointer(&oob[0]))
msg.SetControllen(len(oob))
}
msg.Iov = &iov
msg.Iovlen = 1
if n, err = sendmsg(fd, &msg, flags); err != nil {
return 0, err
}
if len(oob) > 0 && len(p) == 0 {
n = 0
}
return n, nil
}
//sys kevent(kq int, change unsafe.Pointer, nchange int, event unsafe.Pointer, nevent int, timeout *Timespec) (n int, err error)
func Kevent(kq int, changes, events []Kevent_t, timeout *Timespec) (n int, err error) {
var change, event unsafe.Pointer
if len(changes) > 0 {
change = unsafe.Pointer(&changes[0])
}
if len(events) > 0 {
event = unsafe.Pointer(&events[0])
}
return kevent(kq, change, len(changes), event, len(events), timeout)
}
// sysctlmib translates name to mib number and appends any additional args.
func sysctlmib(name string, args ...int) ([]_C_int, error) {
// Translate name to mib number.
mib, err := nametomib(name)
if err != nil {
return nil, err
}
for _, a := range args {
mib = append(mib, _C_int(a))
}
return mib, nil
}
func Sysctl(name string) (string, error) {
return SysctlArgs(name)
}
func SysctlArgs(name string, args ...int) (string, error) {
buf, err := SysctlRaw(name, args...)
if err != nil {
return "", err
}
n := len(buf)
// Throw away terminating NUL.
if n > 0 && buf[n-1] == '\x00' {
n--
}
return string(buf[0:n]), nil
}
func SysctlUint32(name string) (uint32, error) {
return SysctlUint32Args(name)
}
func SysctlUint32Args(name string, args ...int) (uint32, error) {
mib, err := sysctlmib(name, args...)
if err != nil {
return 0, err
}
n := uintptr(4)
buf := make([]byte, 4)
if err := sysctl(mib, &buf[0], &n, nil, 0); err != nil {
return 0, err
}
if n != 4 {
return 0, EIO
}
return *(*uint32)(unsafe.Pointer(&buf[0])), nil
}
func SysctlUint64(name string, args ...int) (uint64, error) {
mib, err := sysctlmib(name, args...)
if err != nil {
return 0, err
}
n := uintptr(8)
buf := make([]byte, 8)
if err := sysctl(mib, &buf[0], &n, nil, 0); err != nil {
return 0, err
}
if n != 8 {
return 0, EIO
}
return *(*uint64)(unsafe.Pointer(&buf[0])), nil
}
func SysctlRaw(name string, args ...int) ([]byte, error) {
mib, err := sysctlmib(name, args...)
if err != nil {
return nil, err
}
// Find size.
n := uintptr(0)
if err := sysctl(mib, nil, &n, nil, 0); err != nil {
return nil, err
}
if n == 0 {
return nil, nil
}
// Read into buffer of that size.
buf := make([]byte, n)
if err := sysctl(mib, &buf[0], &n, nil, 0); err != nil {
return nil, err
}
// The actual call may return less than the original reported required
// size so ensure we deal with that.
return buf[:n], nil
}
//sys utimes(path string, timeval *[2]Timeval) (err error)
func Utimes(path string, tv []Timeval) error {
if tv == nil {
return utimes(path, nil)
}
if len(tv) != 2 {
return EINVAL
}
return utimes(path, (*[2]Timeval)(unsafe.Pointer(&tv[0])))
}
func UtimesNano(path string, ts []Timespec) error {
if ts == nil {
err := utimensat(AT_FDCWD, path, nil, 0)
if err != ENOSYS {
return err
}
return utimes(path, nil)
}
if len(ts) != 2 {
return EINVAL
}
// Darwin setattrlist can set nanosecond timestamps
err := setattrlistTimes(path, ts, 0)
if err != ENOSYS {
return err
}
err = utimensat(AT_FDCWD, path, (*[2]Timespec)(unsafe.Pointer(&ts[0])), 0)
if err != ENOSYS {
return err
}
// Not as efficient as it could be because Timespec and
// Timeval have different types in the different OSes
tv := [2]Timeval{
NsecToTimeval(TimespecToNsec(ts[0])),
NsecToTimeval(TimespecToNsec(ts[1])),
}
return utimes(path, (*[2]Timeval)(unsafe.Pointer(&tv[0])))
}
func UtimesNanoAt(dirfd int, path string, ts []Timespec, flags int) error {
if ts == nil {
return utimensat(dirfd, path, nil, flags)
}
if len(ts) != 2 {
return EINVAL
}
err := setattrlistTimes(path, ts, flags)
if err != ENOSYS {
return err
}
return utimensat(dirfd, path, (*[2]Timespec)(unsafe.Pointer(&ts[0])), flags)
}
//sys futimes(fd int, timeval *[2]Timeval) (err error)
func Futimes(fd int, tv []Timeval) error {
if tv == nil {
return futimes(fd, nil)
}
if len(tv) != 2 {
return EINVAL
}
return futimes(fd, (*[2]Timeval)(unsafe.Pointer(&tv[0])))
}
//sys fcntl(fd int, cmd int, arg int) (val int, err error)
//sys poll(fds *PollFd, nfds int, timeout int) (n int, err error)
func Poll(fds []PollFd, timeout int) (n int, err error) {
if len(fds) == 0 {
return poll(nil, 0, timeout)
}
return poll(&fds[0], len(fds), timeout)
}
// TODO: wrap
// Acct(name nil-string) (err error)
// Gethostuuid(uuid *byte, timeout *Timespec) (err error)
// Ptrace(req int, pid int, addr uintptr, data int) (ret uintptr, err error)
var mapper = &mmapper{
active: make(map[*byte][]byte),
mmap: mmap,
munmap: munmap,
}
func Mmap(fd int, offset int64, length int, prot int, flags int) (data []byte, err error) {
return mapper.Mmap(fd, offset, length, prot, flags)
}
func Munmap(b []byte) (err error) {
return mapper.Munmap(b)
}
//sys Madvise(b []byte, behav int) (err error)
//sys Mlock(b []byte) (err error)
//sys Mlockall(flags int) (err error)
//sys Mprotect(b []byte, prot int) (err error)
//sys Msync(b []byte, flags int) (err error)
//sys Munlock(b []byte) (err error)
//sys Munlockall() (err error)
| {
"pile_set_name": "Github"
} |
namespace Microsoft.VisualStudio.Text.AdornmentLibrary.ToolTip.Implementation
{
using Microsoft.VisualStudio.Utilities;
public interface IViewElementFactoryMetadata : IOrderable
{
string FromFullName { get; }
string ToFullName { get; }
}
}
| {
"pile_set_name": "Github"
} |
Ext.onReady(function() {
Ext.select('#modx-testconn').on('click',MODx.DB.testConnection);
Ext.select('#modx-testcoll').on('click',MODx.DB.testCollation);
Ext.select('#modx-db-info').hide();
var es = Ext.select('.modx-hidden2');
es.setVisibilityMode(Ext.Element.DISPLAY);
es.hide();
if (!MODx.showHidden) {
var ez = Ext.select('.modx-hidden');
ez.setVisibilityMode(Ext.Element.DISPLAY);
ez.hide();
}
});
MODx.DB = function() {
return {
testConnection: function() {
Ext.Ajax.request({
url: 'processors/connector.php'
,success: function(r) {
r = Ext.decode(r.responseText);
var msg = Ext.select('#modx-db-step1-msg'),
dbInfo = Ext.select('#modx-db-info'),
step2 = Ext.select('#modx-db-step2');
msg.show();
msg.removeClass('success').removeClass('warning').removeClass('error');
if (r.success) {
if (r.object.client_version) {
dbInfo.show();
var cv = Ext.select('#modx-db-client-version');
if (r.object.client_version_result != 'success') {
cv.addClass('warning');
} else {
cv.addClass('success');
}
cv.update(' '+r.object.client_version_msg);
var sv = Ext.select('#modx-db-server-version');
if (r.object.server_version_result != 'success') {
sv.addClass('warning');
} else {
sv.addClass('success');
}
sv.update(' '+r.object.server_version_msg);
}
Ext.select('#modx-db-step1-msg span.connect-msg').update(r.message);
step2.fadeIn();
var ch = Ext.get('database-connection-charset');
if (ch) {
ch.update('');
if (r.object.charsets) {
for (var i=0;i<r.object.charsets.length;i++) {
MODx.DB.optionTpl.append('database-connection-charset',r.object.charsets[i]);
}
} else {
MODx.DB.optionTpl.append('database-connection-charset',{
name: r.object.charset
,value: r.object.charset
});
}
}
var c = Ext.get('database-collation');
if (c) {
c.update('');
if (r.object.collations) {
for (var i=0;i<r.object.collations.length;i++) {
MODx.DB.optionTpl.append('database-collation',r.object.collations[i]);
}
} else {
MODx.DB.optionTpl.append('database-collation',{
name: r.object.collation
,value: r.object.collation
});
}
}
msg.addClass('success');
} else {
var errorMsg = ' <br />'+r.message+'<br />';
if (r.object) {
for (var i=0;i<r.object.length;i++) {
errorMsg = errorMsg + '<br />' + r.object[i] + '<br />';
}
}
Ext.select('#modx-db-step1-msg span.connect-msg').update(errorMsg);
msg.addClass('error');
dbInfo.hide();
step2.hide();
}
}
,scope: this
,params: {
action: 'database/connection'
,database_type: Ext.get('database-type').getValue()
,database_server: Ext.get('database-server').getValue()
,database_user: Ext.get('database-user').getValue()
,database_password: Ext.get('database-password').getValue()
,dbase: Ext.get('dbase').getValue()
,table_prefix: Ext.get('table-prefix').getValue()
}
});
}
,testCollation: function() {
var p = { action: 'database/collation' };
var co = Ext.get('database-collation');
if (co) { p.database_collation = co.getValue(); }
var ca = Ext.get('database-connection-charset');
if (ca) { p.database_connection_charset = ca.getValue(); }
Ext.Ajax.request({
url: 'processors/connector.php'
,success: function(r) {
r = Ext.decode(r.responseText);
var msg = Ext.select('#modx-db-step2-msg');
msg.show();
msg.removeClass('success').removeClass('error');
Ext.select('#modx-db-step2-msg span.result').update(r.message);
if (r.success) {
Ext.select('#modx-db-step3').fadeIn();
Ext.select('#modx-next').fadeIn();
msg.addClass('success');
} else {
msg.addClass('error');
}
}
,scope: this
,params: p
});
}
,optionTpl: new Ext.Template('<option value="{value}"{selected}>{name}</option>')
};
}();
| {
"pile_set_name": "Github"
} |
"""
.. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com>
"""
import re
from pathvalidate import validate_pathtype
from pathvalidate.error import ErrorReason, ValidationError
from ._base import _preprocess
__MAX_SHEET_NAME_LEN = 31
__INVALID_EXCEL_CHARS = "[]:*?/\\"
__RE_INVALID_EXCEL_SHEET_NAME = re.compile(
"[{:s}]".format(re.escape(__INVALID_EXCEL_CHARS)), re.UNICODE
)
def validate_excel_sheet_name(sheet_name: str) -> None:
"""
:param str sheet_name: Excel sheet name to validate.
:raises pathvalidate.ValidationError (ErrorReason.INVALID_CHARACTER):
If the ``sheet_name`` includes invalid char(s):
|invalid_excel_sheet_chars|.
:raises pathvalidate.ValidationError (ErrorReason.INVALID_LENGTH):
If the ``sheet_name`` is longer than 31 characters.
"""
validate_pathtype(sheet_name)
if len(sheet_name) > __MAX_SHEET_NAME_LEN:
raise ValidationError(
description="sheet name is too long: expected<={:d}, actual={:d}".format(
__MAX_SHEET_NAME_LEN, len(sheet_name)
),
reason=ErrorReason.INVALID_LENGTH,
)
unicode_sheet_name = _preprocess(sheet_name)
match = __RE_INVALID_EXCEL_SHEET_NAME.search(unicode_sheet_name)
if match is not None:
raise ValidationError(
description="invalid char found in the sheet name: '{:s}'".format(
re.escape(match.group())
),
reason=ErrorReason.INVALID_CHARACTER,
)
def sanitize_excel_sheet_name(sheet_name: str, replacement_text: str = "") -> str:
"""
Replace invalid characters for an Excel sheet name within
the ``sheet_name`` with the ``replacement_text``.
Invalid characters are as follows:
|invalid_excel_sheet_chars|.
The ``sheet_name`` truncate to 31 characters
(max sheet name length of Excel) from the head, if the length
of the name is exceed 31 characters.
:param str sheet_name: Excel sheet name to sanitize.
:param str replacement_text: Replacement text.
:return: A replacement string.
:rtype: str
:raises ValueError: If the ``sheet_name`` is an invalid sheet name.
"""
try:
unicode_sheet_name = _preprocess(sheet_name)
except AttributeError as e:
raise ValueError(e)
modify_sheet_name = __RE_INVALID_EXCEL_SHEET_NAME.sub(replacement_text, unicode_sheet_name)
return modify_sheet_name[:__MAX_SHEET_NAME_LEN]
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@android:color/white"
android:orientation="vertical">
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:minHeight="?attr/actionBarSize"
app:theme="@style/ToolbarTheme"
android:background="@color/color_primary"/>
<Button
android:id="@+id/push"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="16dp"
android:layout_marginRight="16dp"
android:text="Push"/>
<Button
android:id="@+id/present"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="16dp"
android:layout_marginRight="16dp"
android:text="Present"/>
<Button
android:id="@+id/push_rn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="16dp"
android:layout_marginRight="16dp"
android:text="Push React Native"/>
<Button
android:id="@+id/present_rn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="16dp"
android:layout_marginRight="16dp"
android:text="Present React Native"/>
<Button
android:id="@+id/pop"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="16dp"
android:layout_marginRight="16dp"
android:text="Pop"/>
<Button
android:id="@+id/dismiss"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="16dp"
android:layout_marginRight="16dp"
android:text="Dismiss"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Payload:"
android:layout_marginRight="4dp"/>
<EditText
android:id="@+id/payload"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Hello World"/>
</LinearLayout>
</LinearLayout> | {
"pile_set_name": "Github"
} |
var searchData=
[
['close',['close',['../class_wi_fly.html#adf4138137065fd78de83a18825f47795',1,'WiFly']]],
['createadhocnetwork',['createAdhocNetwork',['../class_wi_fly.html#ac84cdf8e1dd3c544bb935548af9d114e',1,'WiFly']]]
];
| {
"pile_set_name": "Github"
} |
/*
* Copyright (c) 2007, 2012, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.max.tele.object;
import com.sun.max.tele.*;
import com.sun.max.tele.reference.*;
import com.sun.max.tele.value.*;
import com.sun.max.vm.value.*;
/**
* Canonical surrogate for an object of type {@link ObjectReferenceValue} in the VM.
*/
public class TeleObjectReferenceValue extends TeleTupleObject {
protected TeleObjectReferenceValue(TeleVM vm, RemoteReference teleObjectReferenceValueReference) {
super(vm, teleObjectReferenceValueReference);
}
/**
* @return a local wrapper for the {@link ReferenceValue} in the VM.
*/
public TeleReferenceValue getTeleReferenceValue() {
return TeleReferenceValue.from(vm(), fields().ObjectReferenceValue_value.readRemoteReference(reference()));
}
@Override
protected Object createDeepCopy(DeepCopier context) {
// Translate into local equivalent
return getTeleReferenceValue();
}
}
| {
"pile_set_name": "Github"
} |
//============================================================================
//
// MM MM 6666 555555 0000 2222
// MMMM MMMM 66 66 55 00 00 22 22
// MM MMM MM 66 55 00 00 22
// MM M MM 66666 55555 00 00 22222 -- "A 6502 Microprocessor Emulator"
// MM MM 66 66 55 00 00 22
// MM MM 66 66 55 55 00 00 22
// MM MM 6666 5555 0000 222222
//
// Copyright (c) 1995-2007 by Bradford W. Mott and the Stella team
//
// See the file "license" for information on usage and redistribution of
// this file, and for a DISCLAIMER OF ALL WARRANTIES.
//
// $Id: NullDev.hxx,v 1.5 2007/01/01 18:04:51 stephena Exp $
//============================================================================
#ifndef NULLDEVICE_HXX
#define NULLDEVICE_HXX
class System;
class Serializer;
class Deserializer;
#include "bspf/src/bspf.hxx"
#include "Device.hxx"
/**
Class that represents a "null" device. The basic idea is that a
null device is installed in a 6502 based system anywhere there are
holes in the address space (i.e. no real device attached).
@author Bradford W. Mott
@version $Id: NullDev.hxx,v 1.5 2007/01/01 18:04:51 stephena Exp $
*/
class NullDevice : public Device
{
public:
/**
Create a new null device
*/
NullDevice();
/**
Destructor
*/
virtual ~NullDevice();
public:
/**
Get a null terminated string which is the device's name (i.e. "M6532")
@return The name of the device
*/
virtual const char* name() const;
/**
Reset device to its power-on state
*/
virtual void reset();
/**
Install device in the specified system. Invoked by the system
when the device is attached to it.
@param system The system the device should install itself in
*/
virtual void install(System& system);
/**
Saves the current state of this device to the given Serializer.
@param out The serializer device to save to.
@return The result of the save. True on success, false on failure.
*/
virtual bool save(Serializer& out);
/**
Loads the current state of this device from the given Deserializer.
@param in The deserializer device to load from.
@return The result of the load. True on success, false on failure.
*/
virtual bool load(Deserializer& in);
public:
/**
Get the byte at the specified address
@return The byte at the specified address
*/
virtual uInt8 peek(uInt16 address);
/**
Change the byte at the specified address to the given value
@param address The address where the value should be stored
@param value The value to be stored at the address
*/
virtual void poke(uInt16 address, uInt8 value);
};
#endif
| {
"pile_set_name": "Github"
} |
Title: lnx_thermal: Fix GUI warning about wrong parameter data type
Level: 1
Component: checks
Class: fix
Compatible: compat
Edition: cre
State: unknown
Version: 1.6.0b1
Date: 1544779738
This was a purely cosmetical error and did not affect the check logic
in any way.
CMK-1428
| {
"pile_set_name": "Github"
} |
#include <skypat/skypat.h>
#define _Bool bool
extern "C" {
#include <stdint.h>
#include <stdlib.h>
#include <dataTypes/Value.h>
#include <dataTypes/stack_p.h>
#include <dataTypes/vector_p.h>
#include <dataTypes/FuncType.h>
#include <structures/instrs/Memory.h>
#include <structures/WasmMemory.h>
#include <structures/WasmFunc.h>
#include <structures/WasmModule.h>
#include <Validates.h>
#include <Opcodes.h>
#include <Context.h>
}
#undef _Bool
static void test_storeN_align(stack_p opds, Context* context, stack_p ctrls, WasmMemoryInstr* instr, ValueType expect)
{
ValueType* address = (ValueType*) malloc(sizeof(ValueType));
*address = Value_i32;
stack_push(opds, address);
EXPECT_EQ(validate_Instr_storeN(instr, context, opds, ctrls), -3);
}
static void test_storeN(stack_p opds, Context* context, stack_p ctrls, WasmMemoryInstr* instr, ValueType expect)
{
ValueType* address = (ValueType*) malloc(sizeof(ValueType));
*address = Value_i32;
stack_push(opds, address);
ValueType* operand = (ValueType*) malloc(sizeof(ValueType));
*operand = expect;
stack_push(opds, operand);
EXPECT_EQ(validate_Instr_storeN(instr, context, opds, ctrls), 0);
EXPECT_EQ(stack_size(opds), 0);
}
static void test_store(stack_p opds, Context* context, stack_p ctrls, WasmMemoryInstr* instr, ValueType expect)
{
ValueType* address = (ValueType*) malloc(sizeof(ValueType));
*address = Value_i32;
stack_push(opds, address);
ValueType* operand = (ValueType*) malloc(sizeof(ValueType));
*operand = expect;
stack_push(opds, operand);
EXPECT_EQ(validate_Instr_store(instr, context, opds, ctrls), 0);
EXPECT_EQ(stack_size(opds), 0);
}
static void test_load(stack_p opds, Context* context, stack_p ctrls, WasmMemoryInstr* instr, ValueType expect)
{
ValueType* address = (ValueType*) malloc(sizeof(ValueType));
*address = Value_i32;
stack_push(opds, address);
EXPECT_EQ(validate_Instr_load(instr, context, opds, ctrls), 0);
EXPECT_EQ(stack_size(opds), 1);
ValueType* operand = stack_pop(ValueType*, opds);
EXPECT_EQ(*operand, expect);
}
static void test_loadN(stack_p opds, Context* context, stack_p ctrls, WasmMemoryInstr* instr, ValueType expect)
{
ValueType* address = (ValueType*) malloc(sizeof(ValueType));
*address = Value_i32;
stack_push(opds, address);
EXPECT_EQ(validate_Instr_loadN(instr, context, opds, ctrls), 0);
EXPECT_EQ(stack_size(opds), 1);
ValueType* operand = stack_pop(ValueType*, opds);
EXPECT_EQ(*operand, expect);
}
static void test_loadN_align(stack_p opds, Context* context, stack_p ctrls, WasmMemoryInstr* instr, ValueType expect)
{
ValueType* address = (ValueType*) malloc(sizeof(ValueType));
*address = Value_i32;
stack_push(opds, address);
EXPECT_EQ(validate_Instr_loadN(instr, context, opds, ctrls), -3);
}
static void clean(stack_p opds, stack_p ctrls)
{
free_stack_p(opds);
free_stack_p(ctrls);
}
SKYPAT_F(validate_Instr_load, valid)
{
// Prepare
WasmModule* module = new_WasmModule(NULL);
WasmFunc* func = new_WasmFunc();
func->type = 0;
FuncType type = new_FuncType();
vector_push_back(module->types, type);
WasmMemory* memory = (WasmMemory*) malloc(sizeof(WasmMemory));
memory->min = 1;
memory->max = 0;
vector_push_back(module->mems, memory);
Context* context = new_Context(module, func);
stack_p opds = new_stack_p(free);
stack_p ctrls = new_stack_p((void(*)(void*))free_ctrl_frame);
ctrl_frame* frame = new_ctrl_frame(opds);
stack_push(ctrls, frame);
WasmMemoryInstr* instr = new_WasmMemoryInstr(0, 0);
// Check
instr->parent.opcode = Op_i32_load;
test_load(opds, context, ctrls, instr, Value_i32);
instr->parent.opcode = Op_i64_load;
test_load(opds, context, ctrls, instr, Value_i64);
instr->parent.opcode = Op_f32_load;
test_load(opds, context, ctrls, instr, Value_f32);
instr->parent.opcode = Op_f64_load;
test_load(opds, context, ctrls, instr, Value_f64);
// Clean
free(instr);
clean(opds, ctrls);
free_Context(context);
free_WasmModule(module);
}
SKYPAT_F(validate_Instr_load, memory_not_exist)
{
// Prepare
WasmModule* module = new_WasmModule(NULL);
WasmFunc* func = new_WasmFunc();
func->type = 0;
FuncType type = new_FuncType();
vector_push_back(module->types, type);
Context* context = new_Context(module, func);
stack_p opds = new_stack_p(free);
stack_p ctrls = new_stack_p((void(*)(void*))free_ctrl_frame);
ctrl_frame* frame = new_ctrl_frame(opds);
stack_push(ctrls, frame);
WasmMemoryInstr* instr = new_WasmMemoryInstr(0, 0);
// Check
instr->parent.opcode = Op_i32_load;
ValueType* address = (ValueType*) malloc(sizeof(ValueType));
*address = Value_i32;
stack_push(opds, address);
EXPECT_EQ(validate_Instr_load(instr, context, opds, ctrls), -1);
// Clean
free(instr);
clean(opds, ctrls);
free_Context(context);
free_WasmModule(module);
}
SKYPAT_F(validate_Instr_load, align_too_much)
{
// Prepare
WasmModule* module = new_WasmModule(NULL);
WasmFunc* func = new_WasmFunc();
func->type = 0;
FuncType type = new_FuncType();
vector_push_back(module->types, type);
WasmMemory* memory = (WasmMemory*) malloc(sizeof(WasmMemory));
memory->min = 1;
memory->max = 0;
vector_push_back(module->mems, memory);
Context* context = new_Context(module, func);
stack_p opds = new_stack_p(free);
stack_p ctrls = new_stack_p((void(*)(void*))free_ctrl_frame);
ctrl_frame* frame = new_ctrl_frame(opds);
stack_push(ctrls, frame);
WasmMemoryInstr* instr = new_WasmMemoryInstr(4, 0);
// Check
instr->parent.opcode = Op_i32_load;
ValueType* address = (ValueType*) malloc(sizeof(ValueType));
*address = Value_i32;
stack_push(opds, address);
EXPECT_EQ(validate_Instr_load(instr, context, opds, ctrls), -3);
// Clean
free(instr);
clean(opds, ctrls);
free_Context(context);
free_WasmModule(module);
}
SKYPAT_F(validate_Instr_load, no_enough_operand)
{
// Prepare
WasmModule* module = new_WasmModule(NULL);
WasmFunc* func = new_WasmFunc();
func->type = 0;
FuncType type = new_FuncType();
vector_push_back(module->types, type);
WasmMemory* memory = (WasmMemory*) malloc(sizeof(WasmMemory));
memory->min = 1;
memory->max = 0;
vector_push_back(module->mems, memory);
Context* context = new_Context(module, func);
stack_p opds = new_stack_p(free);
stack_p ctrls = new_stack_p((void(*)(void*))free_ctrl_frame);
ctrl_frame* frame = new_ctrl_frame(opds);
stack_push(ctrls, frame);
WasmMemoryInstr* instr = new_WasmMemoryInstr(0, 0);
// Check
instr->parent.opcode = Op_i32_load;
EXPECT_EQ(validate_Instr_load(instr, context, opds, ctrls), -4);
// Clean
free(instr);
clean(opds, ctrls);
free_Context(context);
free_WasmModule(module);
}
SKYPAT_F(validate_Instr_loadN, valid)
{
// Prepare
WasmModule* module = new_WasmModule(NULL);
WasmFunc* func = new_WasmFunc();
func->type = 0;
FuncType type = new_FuncType();
vector_push_back(module->types, type);
WasmMemory* memory = (WasmMemory*) malloc(sizeof(WasmMemory));
memory->min = 1;
memory->max = 0;
vector_push_back(module->mems, memory);
Context* context = new_Context(module, func);
stack_p opds = new_stack_p(free);
stack_p ctrls = new_stack_p((void(*)(void*))free_ctrl_frame);
ctrl_frame* frame = new_ctrl_frame(opds);
stack_push(ctrls, frame);
WasmMemoryInstr* instr = new_WasmMemoryInstr(0, 0);
// Check
instr->parent.opcode = Op_i32_load8_s;
test_loadN(opds, context, ctrls, instr, Value_i32);
instr->parent.opcode = Op_i32_load8_u;
test_loadN(opds, context, ctrls, instr, Value_i32);
instr->parent.opcode = Op_i32_load16_s;
test_loadN(opds, context, ctrls, instr, Value_i32);
instr->parent.opcode = Op_i32_load16_u;
test_loadN(opds, context, ctrls, instr, Value_i32);
instr->parent.opcode = Op_i64_load8_s;
test_loadN(opds, context, ctrls, instr, Value_i64);
instr->parent.opcode = Op_i64_load8_u;
test_loadN(opds, context, ctrls, instr, Value_i64);
instr->parent.opcode = Op_i64_load16_s;
test_loadN(opds, context, ctrls, instr, Value_i64);
instr->parent.opcode = Op_i64_load16_u;
test_loadN(opds, context, ctrls, instr, Value_i64);
instr->parent.opcode = Op_i64_load32_s;
test_loadN(opds, context, ctrls, instr, Value_i64);
instr->parent.opcode = Op_i64_load32_u;
test_loadN(opds, context, ctrls, instr, Value_i64);
// Clean
free(instr);
clean(opds, ctrls);
free_Context(context);
free_WasmModule(module);
}
SKYPAT_F(validate_Instr_loadN, memory_not_exist)
{
// Prepare
WasmModule* module = new_WasmModule(NULL);
WasmFunc* func = new_WasmFunc();
func->type = 0;
FuncType type = new_FuncType();
vector_push_back(module->types, type);
Context* context = new_Context(module, func);
stack_p opds = new_stack_p(free);
stack_p ctrls = new_stack_p((void(*)(void*))free_ctrl_frame);
ctrl_frame* frame = new_ctrl_frame(opds);
stack_push(ctrls, frame);
WasmMemoryInstr* instr = new_WasmMemoryInstr(0, 0);
// Check
instr->parent.opcode = Op_i32_load8_s;
ValueType* address = (ValueType*) malloc(sizeof(ValueType));
*address = Value_i32;
stack_push(opds, address);
EXPECT_EQ(validate_Instr_loadN(instr, context, opds, ctrls), -1);
// Clean
free(instr);
clean(opds, ctrls);
free_Context(context);
free_WasmModule(module);
}
SKYPAT_F(validate_Instr_loadN, no_enough_operand)
{
// Prepare
WasmModule* module = new_WasmModule(NULL);
WasmFunc* func = new_WasmFunc();
func->type = 0;
FuncType type = new_FuncType();
vector_push_back(module->types, type);
WasmMemory* memory = (WasmMemory*) malloc(sizeof(WasmMemory));
memory->min = 1;
memory->max = 0;
vector_push_back(module->mems, memory);
Context* context = new_Context(module, func);
stack_p opds = new_stack_p(free);
stack_p ctrls = new_stack_p((void(*)(void*))free_ctrl_frame);
ctrl_frame* frame = new_ctrl_frame(opds);
stack_push(ctrls, frame);
WasmMemoryInstr* instr = new_WasmMemoryInstr(0, 0);
// Check
instr->parent.opcode = Op_i32_load8_s;
EXPECT_EQ(validate_Instr_loadN(instr, context, opds, ctrls), -4);
// Clean
free(instr);
clean(opds, ctrls);
free_Context(context);
free_WasmModule(module);
}
SKYPAT_F(validate_Instr_loadN, align_too_much)
{
// Prepare
WasmModule* module = new_WasmModule(NULL);
WasmFunc* func = new_WasmFunc();
func->type = 0;
FuncType type = new_FuncType();
vector_push_back(module->types, type);
WasmMemory* memory = (WasmMemory*) malloc(sizeof(WasmMemory));
memory->min = 1;
memory->max = 0;
vector_push_back(module->mems, memory);
Context* context = new_Context(module, func);
stack_p opds = new_stack_p(free);
stack_p ctrls = new_stack_p((void(*)(void*))free_ctrl_frame);
ctrl_frame* frame = new_ctrl_frame(opds);
stack_push(ctrls, frame);
WasmMemoryInstr* instr = new_WasmMemoryInstr(0, 0);
// Check
instr->parent.opcode = Op_i32_load8_s;
instr->align = 1;
test_loadN_align(opds, context, ctrls, instr, Value_i32);
instr->parent.opcode = Op_i32_load8_u;
instr->align = 1;
test_loadN_align(opds, context, ctrls, instr, Value_i32);
instr->parent.opcode = Op_i32_load16_s;
instr->align = 2;
test_loadN_align(opds, context, ctrls, instr, Value_i32);
instr->parent.opcode = Op_i32_load16_u;
instr->align = 2;
test_loadN_align(opds, context, ctrls, instr, Value_i32);
instr->parent.opcode = Op_i64_load8_s;
instr->align = 1;
test_loadN_align(opds, context, ctrls, instr, Value_i64);
instr->parent.opcode = Op_i64_load8_u;
instr->align = 1;
test_loadN_align(opds, context, ctrls, instr, Value_i64);
instr->parent.opcode = Op_i64_load16_s;
instr->align = 2;
test_loadN_align(opds, context, ctrls, instr, Value_i64);
instr->parent.opcode = Op_i64_load16_u;
instr->align = 2;
test_loadN_align(opds, context, ctrls, instr, Value_i64);
instr->parent.opcode = Op_i64_load32_s;
instr->align = 3;
test_loadN_align(opds, context, ctrls, instr, Value_i64);
instr->parent.opcode = Op_i64_load32_u;
instr->align = 3;
test_loadN_align(opds, context, ctrls, instr, Value_i64);
// Clean
free(instr);
clean(opds, ctrls);
free_Context(context);
free_WasmModule(module);
}
SKYPAT_F(validate_Instr_store, valid)
{
// Prepare
WasmModule* module = new_WasmModule(NULL);
WasmFunc* func = new_WasmFunc();
func->type = 0;
FuncType type = new_FuncType();
vector_push_back(module->types, type);
WasmMemory* memory = (WasmMemory*) malloc(sizeof(WasmMemory));
memory->min = 1;
memory->max = 0;
vector_push_back(module->mems, memory);
Context* context = new_Context(module, func);
stack_p opds = new_stack_p(free);
stack_p ctrls = new_stack_p((void(*)(void*))free_ctrl_frame);
ctrl_frame* frame = new_ctrl_frame(opds);
stack_push(ctrls, frame);
WasmMemoryInstr* instr = new_WasmMemoryInstr(0, 0);
// Check
instr->parent.opcode = Op_i32_store;
test_store(opds, context, ctrls, instr, Value_i32);
instr->parent.opcode = Op_i64_store;
test_store(opds, context, ctrls, instr, Value_i64);
instr->parent.opcode = Op_f32_store;
test_store(opds, context, ctrls, instr, Value_f32);
instr->parent.opcode = Op_f64_store;
test_store(opds, context, ctrls, instr, Value_f64);
// Clean
free(instr);
clean(opds, ctrls);
free_Context(context);
free_WasmModule(module);
}
SKYPAT_F(validate_Instr_store, memory_not_exist)
{
// Prepare
WasmModule* module = new_WasmModule(NULL);
WasmFunc* func = new_WasmFunc();
func->type = 0;
FuncType type = new_FuncType();
vector_push_back(module->types, type);
Context* context = new_Context(module, func);
stack_p opds = new_stack_p(free);
stack_p ctrls = new_stack_p((void(*)(void*))free_ctrl_frame);
ctrl_frame* frame = new_ctrl_frame(opds);
stack_push(ctrls, frame);
WasmMemoryInstr* instr = new_WasmMemoryInstr(0, 0);
// Check
instr->parent.opcode = Op_i32_store;
ValueType* address = (ValueType*) malloc(sizeof(ValueType));
*address = Value_i32;
stack_push(opds, address);
EXPECT_EQ(validate_Instr_store(instr, context, opds, ctrls), -1);
// Clean
free(instr);
clean(opds, ctrls);
free_Context(context);
free_WasmModule(module);
}
SKYPAT_F(validate_Instr_store, align_too_much)
{
// Prepare
WasmModule* module = new_WasmModule(NULL);
WasmFunc* func = new_WasmFunc();
func->type = 0;
FuncType type = new_FuncType();
vector_push_back(module->types, type);
WasmMemory* memory = (WasmMemory*) malloc(sizeof(WasmMemory));
memory->min = 1;
memory->max = 0;
vector_push_back(module->mems, memory);
Context* context = new_Context(module, func);
stack_p opds = new_stack_p(free);
stack_p ctrls = new_stack_p((void(*)(void*))free_ctrl_frame);
ctrl_frame* frame = new_ctrl_frame(opds);
stack_push(ctrls, frame);
WasmMemoryInstr* instr = new_WasmMemoryInstr(4, 0);
// Check
instr->parent.opcode = Op_i32_store;
ValueType* address = (ValueType*) malloc(sizeof(ValueType));
*address = Value_i32;
stack_push(opds, address);
EXPECT_EQ(validate_Instr_store(instr, context, opds, ctrls), -3);
// Clean
free(instr);
clean(opds, ctrls);
free_Context(context);
free_WasmModule(module);
}
SKYPAT_F(validate_Instr_store, no_enough_operand)
{
// Prepare
WasmModule* module = new_WasmModule(NULL);
WasmFunc* func = new_WasmFunc();
func->type = 0;
FuncType type = new_FuncType();
vector_push_back(module->types, type);
WasmMemory* memory = (WasmMemory*) malloc(sizeof(WasmMemory));
memory->min = 1;
memory->max = 0;
vector_push_back(module->mems, memory);
Context* context = new_Context(module, func);
stack_p opds = new_stack_p(free);
stack_p ctrls = new_stack_p((void(*)(void*))free_ctrl_frame);
ctrl_frame* frame = new_ctrl_frame(opds);
stack_push(ctrls, frame);
WasmMemoryInstr* instr = new_WasmMemoryInstr(0, 0);
// Check
instr->parent.opcode = Op_i32_store;
EXPECT_EQ(validate_Instr_store(instr, context, opds, ctrls), -4);
ValueType* operand = (ValueType*) malloc(sizeof(ValueType));
*operand = Value_i32;
stack_push(opds, operand);
EXPECT_EQ(validate_Instr_store(instr, context, opds, ctrls), -5);
// Clean
free(instr);
clean(opds, ctrls);
free_Context(context);
free_WasmModule(module);
}
SKYPAT_F(validate_Instr_storeN, valid)
{
// Prepare
WasmModule* module = new_WasmModule(NULL);
WasmFunc* func = new_WasmFunc();
func->type = 0;
FuncType type = new_FuncType();
vector_push_back(module->types, type);
WasmMemory* memory = (WasmMemory*) malloc(sizeof(WasmMemory));
memory->min = 1;
memory->max = 0;
vector_push_back(module->mems, memory);
Context* context = new_Context(module, func);
stack_p opds = new_stack_p(free);
stack_p ctrls = new_stack_p((void(*)(void*))free_ctrl_frame);
ctrl_frame* frame = new_ctrl_frame(opds);
stack_push(ctrls, frame);
WasmMemoryInstr* instr = new_WasmMemoryInstr(0, 0);
// Check
instr->parent.opcode = Op_i32_store8;
test_storeN(opds, context, ctrls, instr, Value_i32);
instr->parent.opcode = Op_i32_store16;
test_storeN(opds, context, ctrls, instr, Value_i32);
instr->parent.opcode = Op_i64_store8;
test_storeN(opds, context, ctrls, instr, Value_i64);
instr->parent.opcode = Op_i64_store16;
test_storeN(opds, context, ctrls, instr, Value_i64);
instr->parent.opcode = Op_i64_store32;
test_storeN(opds, context, ctrls, instr, Value_i64);
// Clean
free(instr);
clean(opds, ctrls);
free_Context(context);
free_WasmModule(module);
}
SKYPAT_F(validate_Instr_storeN, memory_not_exist)
{
// Prepare
WasmModule* module = new_WasmModule(NULL);
WasmFunc* func = new_WasmFunc();
func->type = 0;
FuncType type = new_FuncType();
vector_push_back(module->types, type);
Context* context = new_Context(module, func);
stack_p opds = new_stack_p(free);
stack_p ctrls = new_stack_p((void(*)(void*))free_ctrl_frame);
ctrl_frame* frame = new_ctrl_frame(opds);
stack_push(ctrls, frame);
WasmMemoryInstr* instr = new_WasmMemoryInstr(0, 0);
// Check
instr->parent.opcode = Op_i32_store8;
ValueType* address = (ValueType*) malloc(sizeof(ValueType));
*address = Value_i32;
stack_push(opds, address);
EXPECT_EQ(validate_Instr_storeN(instr, context, opds, ctrls), -1);
// Clean
free(instr);
clean(opds, ctrls);
free_Context(context);
free_WasmModule(module);
}
SKYPAT_F(validate_Instr_storeN, no_enough_operand)
{
// Prepare
WasmModule* module = new_WasmModule(NULL);
WasmFunc* func = new_WasmFunc();
func->type = 0;
FuncType type = new_FuncType();
vector_push_back(module->types, type);
WasmMemory* memory = (WasmMemory*) malloc(sizeof(WasmMemory));
memory->min = 1;
memory->max = 0;
vector_push_back(module->mems, memory);
Context* context = new_Context(module, func);
stack_p opds = new_stack_p(free);
stack_p ctrls = new_stack_p((void(*)(void*))free_ctrl_frame);
ctrl_frame* frame = new_ctrl_frame(opds);
stack_push(ctrls, frame);
WasmMemoryInstr* instr = new_WasmMemoryInstr(0, 0);
// Check
instr->parent.opcode = Op_i32_store8;
EXPECT_EQ(validate_Instr_storeN(instr, context, opds, ctrls), -4);
ValueType* operand = (ValueType*) malloc(sizeof(ValueType));
*operand = Value_i32;
stack_push(opds, operand);
EXPECT_EQ(validate_Instr_storeN(instr, context, opds, ctrls), -5);
// Clean
free(instr);
clean(opds, ctrls);
free_Context(context);
free_WasmModule(module);
}
SKYPAT_F(validate_Instr_storeN, align_too_much)
{
// Prepare
WasmModule* module = new_WasmModule(NULL);
WasmFunc* func = new_WasmFunc();
func->type = 0;
FuncType type = new_FuncType();
vector_push_back(module->types, type);
WasmMemory* memory = (WasmMemory*) malloc(sizeof(WasmMemory));
memory->min = 1;
memory->max = 0;
vector_push_back(module->mems, memory);
Context* context = new_Context(module, func);
stack_p opds = new_stack_p(free);
stack_p ctrls = new_stack_p((void(*)(void*))free_ctrl_frame);
ctrl_frame* frame = new_ctrl_frame(opds);
stack_push(ctrls, frame);
WasmMemoryInstr* instr = new_WasmMemoryInstr(0, 0);
// Check
instr->parent.opcode = Op_i32_store8;
instr->align = 1;
test_storeN_align(opds, context, ctrls, instr, Value_i32);
instr->parent.opcode = Op_i32_store16;
instr->align = 2;
test_storeN_align(opds, context, ctrls, instr, Value_i32);
instr->parent.opcode = Op_i64_store8;
instr->align = 1;
test_storeN_align(opds, context, ctrls, instr, Value_i64);
instr->parent.opcode = Op_i64_store16;
instr->align = 2;
test_storeN_align(opds, context, ctrls, instr, Value_i64);
instr->parent.opcode = Op_i64_store32;
instr->align = 3;
test_storeN_align(opds, context, ctrls, instr, Value_i64);
// Clean
free(instr);
clean(opds, ctrls);
free_Context(context);
free_WasmModule(module);
}
SKYPAT_F(validate_Instr_memory_size, valid)
{
// Prepare
WasmModule* module = new_WasmModule(NULL);
WasmFunc* func = new_WasmFunc();
func->type = 0;
FuncType type = new_FuncType();
vector_push_back(module->types, type);
WasmMemory* memory = (WasmMemory*) malloc(sizeof(WasmMemory));
memory->min = 1;
memory->max = 0;
vector_push_back(module->mems, memory);
Context* context = new_Context(module, func);
stack_p opds = new_stack_p(free);
stack_p ctrls = new_stack_p((void(*)(void*))free_ctrl_frame);
ctrl_frame* frame = new_ctrl_frame(opds);
stack_push(ctrls, frame);
WasmMemoryInstr* instr = new_WasmMemoryInstr(0, 0);
// Check
instr->parent.opcode = Op_memory_size;
EXPECT_EQ(validate_Instr_memory_size(instr, context, opds, ctrls), 0);
EXPECT_EQ(stack_size(opds), 1);
ValueType* operand = stack_pop(ValueType*, opds);
EXPECT_EQ(*operand, Value_i32);
// Clean
free(operand);
free(instr);
clean(opds, ctrls);
free_Context(context);
free_WasmModule(module);
}
SKYPAT_F(validate_Instr_memory_size, memory_not_exist)
{
// Prepare
WasmModule* module = new_WasmModule(NULL);
WasmFunc* func = new_WasmFunc();
func->type = 0;
FuncType type = new_FuncType();
vector_push_back(module->types, type);
Context* context = new_Context(module, func);
stack_p opds = new_stack_p(free);
stack_p ctrls = new_stack_p((void(*)(void*))free_ctrl_frame);
ctrl_frame* frame = new_ctrl_frame(opds);
stack_push(ctrls, frame);
WasmMemoryInstr* instr = new_WasmMemoryInstr(0, 0);
// Check
instr->parent.opcode = Op_memory_size;
EXPECT_EQ(validate_Instr_memory_size(instr, context, opds, ctrls), -1);
// Clean
free(instr);
clean(opds, ctrls);
free_Context(context);
free_WasmModule(module);
}
SKYPAT_F(validate_Instr_memory_grow, valid)
{
// Prepare
WasmModule* module = new_WasmModule(NULL);
WasmFunc* func = new_WasmFunc();
func->type = 0;
FuncType type = new_FuncType();
vector_push_back(module->types, type);
WasmMemory* memory = (WasmMemory*) malloc(sizeof(WasmMemory));
memory->min = 1;
memory->max = 0;
vector_push_back(module->mems, memory);
Context* context = new_Context(module, func);
stack_p opds = new_stack_p(free);
stack_p ctrls = new_stack_p((void(*)(void*))free_ctrl_frame);
ctrl_frame* frame = new_ctrl_frame(opds);
stack_push(ctrls, frame);
WasmMemoryInstr* instr = new_WasmMemoryInstr(0, 0);
// Check
instr->parent.opcode = Op_memory_grow;
ValueType* operand = (ValueType*) malloc(sizeof(ValueType));
*operand = Value_i32;
stack_push(opds, operand);
EXPECT_EQ(validate_Instr_memory_grow(instr, context, opds, ctrls), 0);
EXPECT_EQ(stack_size(opds), 1);
ValueType* result = stack_pop(ValueType*, opds);
EXPECT_EQ(*result, Value_i32);
// Clean
free(result);
free(instr);
clean(opds, ctrls);
free_Context(context);
free_WasmModule(module);
}
SKYPAT_F(validate_Instr_memory_grow, memory_not_exist)
{
// Prepare
WasmModule* module = new_WasmModule(NULL);
WasmFunc* func = new_WasmFunc();
func->type = 0;
FuncType type = new_FuncType();
vector_push_back(module->types, type);
Context* context = new_Context(module, func);
stack_p opds = new_stack_p(free);
stack_p ctrls = new_stack_p((void(*)(void*))free_ctrl_frame);
ctrl_frame* frame = new_ctrl_frame(opds);
stack_push(ctrls, frame);
WasmMemoryInstr* instr = new_WasmMemoryInstr(0, 0);
// Check
instr->parent.opcode = Op_memory_grow;
ValueType* operand = (ValueType*) malloc(sizeof(ValueType));
*operand = Value_i32;
stack_push(opds, operand);
EXPECT_EQ(validate_Instr_memory_grow(instr, context, opds, ctrls), -1);
// Clean
free(instr);
clean(opds, ctrls);
free_Context(context);
free_WasmModule(module);
}
SKYPAT_F(validate_Instr_memory_grow, no_enough_operand)
{
// Prepare
WasmModule* module = new_WasmModule(NULL);
WasmFunc* func = new_WasmFunc();
func->type = 0;
FuncType type = new_FuncType();
vector_push_back(module->types, type);
WasmMemory* memory = (WasmMemory*) malloc(sizeof(WasmMemory));
memory->min = 1;
memory->max = 0;
vector_push_back(module->mems, memory);
Context* context = new_Context(module, func);
stack_p opds = new_stack_p(free);
stack_p ctrls = new_stack_p((void(*)(void*))free_ctrl_frame);
ctrl_frame* frame = new_ctrl_frame(opds);
stack_push(ctrls, frame);
WasmMemoryInstr* instr = new_WasmMemoryInstr(0, 0);
// Check
instr->parent.opcode = Op_memory_grow;
EXPECT_EQ(validate_Instr_memory_grow(instr, context, opds, ctrls), -2);
// Clean
free(instr);
clean(opds, ctrls);
free_Context(context);
free_WasmModule(module);
} | {
"pile_set_name": "Github"
} |
# coding=utf-8
import sys
import json
from math import log
from collections import defaultdict as dict
from common import read_sequence_data
from common import plot_sequence_data
def argmax(d):
k = max(d, key = lambda x: d[x])
return k, d[k]
class HiddenMarkovModel:
def __init__(self):
self.prob_s3 = dict(float)
self.prob_xs = dict(float)
self.D = dict()
self.V = dict(set)
def train(self, X, S, smooth = 0.5):
x_count = dict(int)
xs_count = dict(int)
unigram = dict(int)
bigram = dict(int)
trigram = dict(int)
# maximum likelihood estimate
for x_list, s_list in zip(X, S):
if len(x_list) == 0 or len(x_list) != len(s_list):
print >> sys.stderr, 'ERROR: x_list =', x_list, ', s_list =', s_list
continue
bigram[('*', '*')] += 1
bigram[('*', s_list[0])] += 1
trigram[('*', '*', s_list[0])] += 1
if len(s_list) > 1:
trigram[('*', s_list[0], s_list[1])] += 1
for p in range(len(x_list)):
x, s = x_list[p], s_list[p]
self.V[x].add(s)
x_count[x] += 1
xs_count[(x, s)] += 1
unigram[s] += 1
if p < 1: continue
s_i = s_list[p - 1]
bigram[(s_i, s)] += 1
if p < 2: continue
s_i = s_list[p - 2]
s_j = s_list[p - 1]
trigram[(s_i, s_j, s)] += 1
bigram[(s_list[-1], 'STOP')] += 1
if len(s_list) < 2: continue
trigram[(s_list[-2], s_list[-1], 'STOP')] += 1
self.D = unigram
# smoothing
for s in self.D:
trigram[('*', '*', s)] += smooth
bigram[('*', '*')] += smooth * len(self.D)
for s_i in self.D:
for s_j in self.D:
trigram[('*', s_i, s_j)] += smooth
bigram[('*', s_i)] += smooth * len(self.D)
for s_i in self.D:
for s_j in self.D:
trigram[(s_i, s_j, 'STOP')] += smooth
bigram[(s_i, s_j)] += smooth
# normalize
for s_i in self.D:
for s_j in self.D:
for s_k in self.D:
trigram[(s_i, s_j, s_k)] += smooth
bigram[(s_i, s_j)] += smooth * len(self.D)
for x, s in xs_count:
self.prob_xs[(x, s)] = 1.0 * xs_count[(x, s)] / unigram[s]
for s_i, s_j, s_k in trigram:
self.prob_s3[(s_i, s_j, s_k)] = 1.0 * trigram[(s_i, s_j, s_k)] / bigram[(s_i, s_j)]
def viterbi(self, x_list):
n = len(x_list)
x_list = [''] + x_list
s_list = [''] * (n + 1)
T = dict()
T[-1] = T[0] = ['*']
for i in range(1, n + 1):
if x_list[i] in self.V:
T[i] = self.V[x_list[i]]
else:
T[i] = set(self.D)
pi = dict(float)
bp = dict(str)
pi[(0, '*', '*')] = 1.0
for k in range(1, n + 1):
for u in T[k - 1]:
for v in T[k]:
K = dict()
for w in T[k - 2]:
if (x_list[k], v) in self.prob_xs:
p = self.prob_xs[(x_list[k], v)]
else:
p = 1.0
K[w] = pi[(k - 1, w, u)] * self.prob_s3[(w, u, v)] * p
bp[(k, u, v)], pi[(k, u, v)] = argmax(K)
K = dict()
for u in T[n - 1]:
for v in T[n]:
K[(u, v)] = pi[(n, u, v)] * self.prob_s3[(u, v, 'STOP')]
(s_list[n - 1], s_list[n]), val = argmax(K)
for k in range(n - 2, 0, -1):
s_list[k] = bp[(k + 2, s_list[k + 1], s_list[k + 2])]
return s_list[1 : ]
def baseline(self, X, S):
m = n = c = 0
k, v = argmax(self.D)
for x_list, s_list in zip(X, S):
s_list_pred = [''] * len(s_list)
for i in range(len(x_list)):
x = x_list[i]
if not x in self.V:
s_list_pred[i] = k
else:
d = {(x, s) : self.prob_xs[(x, s)] for s in self.V[x] if (x, s) in self.prob_xs}
(x_max, s_max), v_max = argmax(d)
s_list_pred[i] = s_max
for p, q in zip(s_list, s_list_pred):
if p == q: m += 1
n += len(s_list)
c += 1
# print >> sys.stderr, 'Ground truth:'
# plot_sequence_data(x_list, s_list)
# print >> sys.stderr, 'Tagging result:'
# plot_sequence_data(x_list, s_list_pred)
# print >> sys.stderr, 'Baseline accuracy : %lf%% (%d/%d)' % (100.0 * m / n, m, n)
return 1.0 * m / n
def test(self, X, S):
m = n = c = 0
for x_list, s_list in zip(X, S):
s_list_pred = self.viterbi(x_list)
assert(len(s_list) == len(s_list_pred))
for p, q in zip(s_list, s_list_pred):
if p == q: m += 1
n += len(s_list)
c += 1
# print >> sys.stderr, 'Ground truth:'
# plot_sequence_data(x_list, s_list)
# print >> sys.stderr, 'Tagging result:'
# plot_sequence_data(x_list, s_list_pred)
# print >> sys.stderr, 'Accuracy for HMM POS-tagger : %lf%% (%d/%d)' % (100.0 * m / n, m, n)
return 1.0 * m / n
if __name__ == '__main__':
train_path = 'data/pos_tagging.train'
test_path = 'data/pos_tagging.test'
# train_path = 'data/pos-tagging/ictrain'
# test_path = 'data/pos-tagging/ictest'
X_train, S_train = read_sequence_data(open(train_path))
X_test, S_test = read_sequence_data(open(test_path))
tagger = HiddenMarkovModel()
tagger.train(X_train, S_train)
baseline_acc = tagger.baseline(X_test, S_test)
viterbi_acc = tagger.test(X_test, S_test)
print >> sys.stderr, 'Baseline accuracy %lf%%' % (100.0 * baseline_acc)
print >> sys.stderr, 'Accuracy for HMM POS-tagger %lf%%' % (100.0 * viterbi_acc)
| {
"pile_set_name": "Github"
} |
<html>
<head>
<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" href="report.css" type="text/css"/>
<title></title>
<script type="text/javascript" src="report.js"></script>
<script type="text/javascript" src="link_popup.js"></script>
<script type="text/javascript" src="tooltip.js"></script>
</head>
<body style="margin-left: 10px; margin-right: 10px; margin-top: 10px; margin-bottom: 10px;">
<div style="position:absolute; z-index:21; visibility:hidden" id="vplink">
<table border="1" cellpadding="0" cellspacing="0" bordercolor="#A9BFD3">
<tr>
<td>
<table border="0" cellpadding="0" width="100%" cellspacing="0">
<tr style="background:#DDDDDD">
<td style="font-size: 12px;" align="left">
<select onchange="vpLinkToggleName()" id="vplink-linkType">
<option value="Project Link">Project Link</option>
<option value="Page URL">Page URL</option>
</select>
</td>
<td style="font-size: 12px;" align="right">
<input onclick="javascript: vpLinkToggleName()" id="vplink-checkbox" type="checkbox" />
<label for="vplink-checkbox">with Name</label> </td>
</tr>
</table>
</td>
</tr>
<tr>
<td>
<textarea id="vplink-text" style="width: 348px; height: 60px; border-color: #7EADD9; outline: none;"></textarea> </td>
</tr>
</table>
</div>
<div class="HeaderText">
<span>
c-share </span>
</div>
<table border="0" cellpadding="0" width="100%" cellspacing="0">
<tr>
<td class="HeaderLine1">
</td>
</tr>
<tr>
<td class="HeaderLine2">
</td>
</tr>
<tr>
<td class="HeaderLine3">
</td>
</tr>
</table>
<p>
<a href="ProjectFormat_Q9PpVgaGAqAAegC7.html" class="PageParentTitle">ProjectFormat : ProjectFormat</a> </p>
<p class="PageTitle">
ProjectFillColorModel - <a onclick="javascript: showVpLink('c-share.vpp://modelelement/4DPpVgaGAqAAegH7', '\nc-share.vpp://modelelement/4DPpVgaGAqAAegH7', '', this); return false;" style="padding-left: 16px; font-size: 12px" href="#"><img src="../images/icons/link.png" border="0"> link</a> </p>
<p>
</p>
<table border="0" cellpadding="0" width="100%" cellspacing="0">
<tr>
<td class="Category">
Properties </td>
</tr>
<tr>
<td class="TableCellSpaceHolder5PxTall">
</td>
</tr>
</table>
<table border="0" cellpadding="0" width="100%" cellspacing="0">
<tr>
<td colSpan="4" class="TableHeaderLine">
</td>
</tr>
<tr>
<td colSpan="4" class="TableHeaderLine1">
</td>
</tr>
<tr class="TableHeader">
<td class="TableCellSpaceHolder10Px">
</td>
<td width="25%">
<span class="TableHeaderText">Name</span> </td>
<td class="TableCellSpaceHolder20Px">
</td>
<td>
<span class="TableHeaderText">Value</span> </td>
</tr>
<tr>
<td colSpan="4" class="TableHeaderLine2">
</td>
</tr>
<tr class="TableRow1">
<td>
</td>
<td>
<span class="TableContent">Base Type</span> </td>
<td>
</td>
<td>
<span class="TableContent">ArchiMatePlateau</span> </td>
</tr>
<tr class="TableRow2">
<td>
</td>
<td>
<span class="TableContent">Fill Color Type</span> </td>
<td>
</td>
<td>
<span class="TableContent">Solid</span> </td>
</tr>
<tr class="TableRow1">
<td>
</td>
<td>
<span class="TableContent">Fill Color Gradient Style</span> </td>
<td>
</td>
<td>
<span class="TableContent">S-N</span> </td>
</tr>
<tr class="TableRow2">
<td>
</td>
<td>
<span class="TableContent">Fill Color Transparency</span> </td>
<td>
</td>
<td>
<span class="TableContent">0</span> </td>
</tr>
<tr class="TableRow1">
<td>
</td>
<td>
<span class="TableContent">Fill Color Color1</span> </td>
<td>
</td>
<td>
<span class="TableContent">-2818604</span> </td>
</tr>
<tr class="TableRow2">
<td>
</td>
<td>
<span class="TableContent">Fill Color Color2</span> </td>
<td>
</td>
<td>
<span class="TableContent">0</span> </td>
</tr>
</table>
<table border="0" cellpadding="0" width="100%" cellspacing="0">
<tr>
<td class="TableCellSpaceHolder1PxTall">
</td>
</tr>
<tr>
<td class="TableFooter">
</td>
</tr>
</table>
<p>
</p>
<p>
</p>
<table border="0" cellpadding="0" width="100%" cellspacing="0">
<tr>
<td class="Category">
Appears In </td>
</tr>
<tr>
<td class="TableCellSpaceHolder5PxTall">
</td>
</tr>
</table>
<table border="0" cellpadding="0" width="100%" cellspacing="0">
<tr>
<td colSpan="4" class="TableHeaderLine">
</td>
</tr>
<tr>
<td colSpan="4" class="TableHeaderLine1">
</td>
</tr>
<tr class="TableHeader">
<td class="TableCellSpaceHolder10Px">
</td>
<td>
<span class="TableHeaderText">Diagram</span> </td>
</tr>
<tr>
<td colSpan="2" class="TableHeaderLine2">
</td>
</tr>
</table>
<table border="0" cellpadding="0" width="100%" cellspacing="0">
<tr>
<td class="TableCellSpaceHolder1PxTall">
</td>
</tr>
<tr>
<td class="TableFooter">
</td>
</tr>
</table>
<div style="height: 20px;">
</div>
<table border="0" cellpadding="0" width="100%" cellspacing="0">
<tr>
<td class="FooterLine">
</td>
</tr>
</table>
<div class="HeaderText">
c-share </div>
</body>
</html>
| {
"pile_set_name": "Github"
} |
fileFormatVersion: 2
guid: 3a38c8208cf0a405d915e5557883da1a
folderAsset: yes
timeCreated: 1532111502
licenseType: Free
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
| {
"pile_set_name": "Github"
} |
// Copyright 2014 Unknwon
//
// Licensed under the Apache License, Version 2.0 (the "License"): you may
// not use this file except in compliance with the License. You may obtain
// a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations
// under the License.
package ini_test
import (
"bytes"
"fmt"
"strings"
"testing"
"time"
. "github.com/smartystreets/goconvey/convey"
"gopkg.in/ini.v1"
)
func TestKey_AddShadow(t *testing.T) {
Convey("Add shadow to a key", t, func() {
f, err := ini.ShadowLoad([]byte(`
[notes]
-: note1`))
So(err, ShouldBeNil)
So(f, ShouldNotBeNil)
k, err := f.Section("").NewKey("NAME", "ini")
So(err, ShouldBeNil)
So(k, ShouldNotBeNil)
So(k.AddShadow("ini.v1"), ShouldBeNil)
So(k.ValueWithShadows(), ShouldResemble, []string{"ini", "ini.v1"})
Convey("Add shadow to boolean key", func() {
k, err := f.Section("").NewBooleanKey("published")
So(err, ShouldBeNil)
So(k, ShouldNotBeNil)
So(k.AddShadow("beta"), ShouldNotBeNil)
})
Convey("Add shadow to auto-increment key", func() {
So(f.Section("notes").Key("#1").AddShadow("beta"), ShouldNotBeNil)
})
})
Convey("Shadow is not allowed", t, func() {
f := ini.Empty()
So(f, ShouldNotBeNil)
k, err := f.Section("").NewKey("NAME", "ini")
So(err, ShouldBeNil)
So(k, ShouldNotBeNil)
So(k.AddShadow("ini.v1"), ShouldNotBeNil)
})
}
// Helpers for slice tests.
func float64sEqual(values []float64, expected ...float64) {
So(values, ShouldHaveLength, len(expected))
for i, v := range expected {
So(values[i], ShouldEqual, v)
}
}
func intsEqual(values []int, expected ...int) {
So(values, ShouldHaveLength, len(expected))
for i, v := range expected {
So(values[i], ShouldEqual, v)
}
}
func int64sEqual(values []int64, expected ...int64) {
So(values, ShouldHaveLength, len(expected))
for i, v := range expected {
So(values[i], ShouldEqual, v)
}
}
func uintsEqual(values []uint, expected ...uint) {
So(values, ShouldHaveLength, len(expected))
for i, v := range expected {
So(values[i], ShouldEqual, v)
}
}
func uint64sEqual(values []uint64, expected ...uint64) {
So(values, ShouldHaveLength, len(expected))
for i, v := range expected {
So(values[i], ShouldEqual, v)
}
}
func timesEqual(values []time.Time, expected ...time.Time) {
So(values, ShouldHaveLength, len(expected))
for i, v := range expected {
So(values[i].String(), ShouldEqual, v.String())
}
}
func TestKey_Helpers(t *testing.T) {
Convey("Getting and setting values", t, func() {
f, err := ini.Load(_FULL_CONF)
So(err, ShouldBeNil)
So(f, ShouldNotBeNil)
Convey("Get string representation", func() {
sec := f.Section("")
So(sec, ShouldNotBeNil)
So(sec.Key("NAME").Value(), ShouldEqual, "ini")
So(sec.Key("NAME").String(), ShouldEqual, "ini")
So(sec.Key("NAME").Validate(func(in string) string {
return in
}), ShouldEqual, "ini")
So(sec.Key("NAME").Comment, ShouldEqual, "; Package name")
So(sec.Key("IMPORT_PATH").String(), ShouldEqual, "gopkg.in/ini.v1")
Convey("With ValueMapper", func() {
f.ValueMapper = func(in string) string {
if in == "gopkg.in/%(NAME)s.%(VERSION)s" {
return "github.com/go-ini/ini"
}
return in
}
So(sec.Key("IMPORT_PATH").String(), ShouldEqual, "github.com/go-ini/ini")
})
})
Convey("Get values in non-default section", func() {
sec := f.Section("author")
So(sec, ShouldNotBeNil)
So(sec.Key("NAME").String(), ShouldEqual, "Unknwon")
So(sec.Key("GITHUB").String(), ShouldEqual, "https://github.com/Unknwon")
sec = f.Section("package")
So(sec, ShouldNotBeNil)
So(sec.Key("CLONE_URL").String(), ShouldEqual, "https://gopkg.in/ini.v1")
})
Convey("Get auto-increment key names", func() {
keys := f.Section("features").Keys()
for i, k := range keys {
So(k.Name(), ShouldEqual, fmt.Sprintf("#%d", i+1))
}
})
Convey("Get parent-keys that are available to the child section", func() {
parentKeys := f.Section("package.sub").ParentKeys()
for _, k := range parentKeys {
So(k.Name(), ShouldEqual, "CLONE_URL")
}
})
Convey("Get overwrite value", func() {
So(f.Section("author").Key("E-MAIL").String(), ShouldEqual, "u@gogs.io")
})
Convey("Get sections", func() {
sections := f.Sections()
for i, name := range []string{ini.DEFAULT_SECTION, "author", "package", "package.sub", "features", "types", "array", "note", "comments", "string escapes", "advance"} {
So(sections[i].Name(), ShouldEqual, name)
}
})
Convey("Get parent section value", func() {
So(f.Section("package.sub").Key("CLONE_URL").String(), ShouldEqual, "https://gopkg.in/ini.v1")
So(f.Section("package.fake.sub").Key("CLONE_URL").String(), ShouldEqual, "https://gopkg.in/ini.v1")
})
Convey("Get multiple line value", func() {
So(f.Section("author").Key("BIO").String(), ShouldEqual, "Gopher.\nCoding addict.\nGood man.\n")
})
Convey("Get values with type", func() {
sec := f.Section("types")
v1, err := sec.Key("BOOL").Bool()
So(err, ShouldBeNil)
So(v1, ShouldBeTrue)
v1, err = sec.Key("BOOL_FALSE").Bool()
So(err, ShouldBeNil)
So(v1, ShouldBeFalse)
v2, err := sec.Key("FLOAT64").Float64()
So(err, ShouldBeNil)
So(v2, ShouldEqual, 1.25)
v3, err := sec.Key("INT").Int()
So(err, ShouldBeNil)
So(v3, ShouldEqual, 10)
v4, err := sec.Key("INT").Int64()
So(err, ShouldBeNil)
So(v4, ShouldEqual, 10)
v5, err := sec.Key("UINT").Uint()
So(err, ShouldBeNil)
So(v5, ShouldEqual, 3)
v6, err := sec.Key("UINT").Uint64()
So(err, ShouldBeNil)
So(v6, ShouldEqual, 3)
t, err := time.Parse(time.RFC3339, "2015-01-01T20:17:05Z")
So(err, ShouldBeNil)
v7, err := sec.Key("TIME").Time()
So(err, ShouldBeNil)
So(v7.String(), ShouldEqual, t.String())
Convey("Must get values with type", func() {
So(sec.Key("STRING").MustString("404"), ShouldEqual, "str")
So(sec.Key("BOOL").MustBool(), ShouldBeTrue)
So(sec.Key("FLOAT64").MustFloat64(), ShouldEqual, 1.25)
So(sec.Key("INT").MustInt(), ShouldEqual, 10)
So(sec.Key("INT").MustInt64(), ShouldEqual, 10)
So(sec.Key("UINT").MustUint(), ShouldEqual, 3)
So(sec.Key("UINT").MustUint64(), ShouldEqual, 3)
So(sec.Key("TIME").MustTime().String(), ShouldEqual, t.String())
dur, err := time.ParseDuration("2h45m")
So(err, ShouldBeNil)
So(sec.Key("DURATION").MustDuration().Seconds(), ShouldEqual, dur.Seconds())
Convey("Must get values with default value", func() {
So(sec.Key("STRING_404").MustString("404"), ShouldEqual, "404")
So(sec.Key("BOOL_404").MustBool(true), ShouldBeTrue)
So(sec.Key("FLOAT64_404").MustFloat64(2.5), ShouldEqual, 2.5)
So(sec.Key("INT_404").MustInt(15), ShouldEqual, 15)
So(sec.Key("INT64_404").MustInt64(15), ShouldEqual, 15)
So(sec.Key("UINT_404").MustUint(6), ShouldEqual, 6)
So(sec.Key("UINT64_404").MustUint64(6), ShouldEqual, 6)
t, err := time.Parse(time.RFC3339, "2014-01-01T20:17:05Z")
So(err, ShouldBeNil)
So(sec.Key("TIME_404").MustTime(t).String(), ShouldEqual, t.String())
So(sec.Key("DURATION_404").MustDuration(dur).Seconds(), ShouldEqual, dur.Seconds())
Convey("Must should set default as key value", func() {
So(sec.Key("STRING_404").String(), ShouldEqual, "404")
So(sec.Key("BOOL_404").String(), ShouldEqual, "true")
So(sec.Key("FLOAT64_404").String(), ShouldEqual, "2.5")
So(sec.Key("INT_404").String(), ShouldEqual, "15")
So(sec.Key("INT64_404").String(), ShouldEqual, "15")
So(sec.Key("UINT_404").String(), ShouldEqual, "6")
So(sec.Key("UINT64_404").String(), ShouldEqual, "6")
So(sec.Key("TIME_404").String(), ShouldEqual, "2014-01-01T20:17:05Z")
So(sec.Key("DURATION_404").String(), ShouldEqual, "2h45m0s")
})
})
})
})
Convey("Get value with candidates", func() {
sec := f.Section("types")
So(sec.Key("STRING").In("", []string{"str", "arr", "types"}), ShouldEqual, "str")
So(sec.Key("FLOAT64").InFloat64(0, []float64{1.25, 2.5, 3.75}), ShouldEqual, 1.25)
So(sec.Key("INT").InInt(0, []int{10, 20, 30}), ShouldEqual, 10)
So(sec.Key("INT").InInt64(0, []int64{10, 20, 30}), ShouldEqual, 10)
So(sec.Key("UINT").InUint(0, []uint{3, 6, 9}), ShouldEqual, 3)
So(sec.Key("UINT").InUint64(0, []uint64{3, 6, 9}), ShouldEqual, 3)
zt, err := time.Parse(time.RFC3339, "0001-01-01T01:00:00Z")
So(err, ShouldBeNil)
t, err := time.Parse(time.RFC3339, "2015-01-01T20:17:05Z")
So(err, ShouldBeNil)
So(sec.Key("TIME").InTime(zt, []time.Time{t, time.Now(), time.Now().Add(1 * time.Second)}).String(), ShouldEqual, t.String())
Convey("Get value with candidates and default value", func() {
So(sec.Key("STRING_404").In("str", []string{"str", "arr", "types"}), ShouldEqual, "str")
So(sec.Key("FLOAT64_404").InFloat64(1.25, []float64{1.25, 2.5, 3.75}), ShouldEqual, 1.25)
So(sec.Key("INT_404").InInt(10, []int{10, 20, 30}), ShouldEqual, 10)
So(sec.Key("INT64_404").InInt64(10, []int64{10, 20, 30}), ShouldEqual, 10)
So(sec.Key("UINT_404").InUint(3, []uint{3, 6, 9}), ShouldEqual, 3)
So(sec.Key("UINT_404").InUint64(3, []uint64{3, 6, 9}), ShouldEqual, 3)
So(sec.Key("TIME_404").InTime(t, []time.Time{time.Now(), time.Now(), time.Now().Add(1 * time.Second)}).String(), ShouldEqual, t.String())
})
})
Convey("Get values in range", func() {
sec := f.Section("types")
So(sec.Key("FLOAT64").RangeFloat64(0, 1, 2), ShouldEqual, 1.25)
So(sec.Key("INT").RangeInt(0, 10, 20), ShouldEqual, 10)
So(sec.Key("INT").RangeInt64(0, 10, 20), ShouldEqual, 10)
minT, err := time.Parse(time.RFC3339, "0001-01-01T01:00:00Z")
So(err, ShouldBeNil)
midT, err := time.Parse(time.RFC3339, "2013-01-01T01:00:00Z")
So(err, ShouldBeNil)
maxT, err := time.Parse(time.RFC3339, "9999-01-01T01:00:00Z")
So(err, ShouldBeNil)
t, err := time.Parse(time.RFC3339, "2015-01-01T20:17:05Z")
So(err, ShouldBeNil)
So(sec.Key("TIME").RangeTime(t, minT, maxT).String(), ShouldEqual, t.String())
Convey("Get value in range with default value", func() {
So(sec.Key("FLOAT64").RangeFloat64(5, 0, 1), ShouldEqual, 5)
So(sec.Key("INT").RangeInt(7, 0, 5), ShouldEqual, 7)
So(sec.Key("INT").RangeInt64(7, 0, 5), ShouldEqual, 7)
So(sec.Key("TIME").RangeTime(t, minT, midT).String(), ShouldEqual, t.String())
})
})
Convey("Get values into slice", func() {
sec := f.Section("array")
So(strings.Join(sec.Key("STRINGS").Strings(","), ","), ShouldEqual, "en,zh,de")
So(len(sec.Key("STRINGS_404").Strings(",")), ShouldEqual, 0)
vals1 := sec.Key("FLOAT64S").Float64s(",")
float64sEqual(vals1, 1.1, 2.2, 3.3)
vals2 := sec.Key("INTS").Ints(",")
intsEqual(vals2, 1, 2, 3)
vals3 := sec.Key("INTS").Int64s(",")
int64sEqual(vals3, 1, 2, 3)
vals4 := sec.Key("UINTS").Uints(",")
uintsEqual(vals4, 1, 2, 3)
vals5 := sec.Key("UINTS").Uint64s(",")
uint64sEqual(vals5, 1, 2, 3)
t, err := time.Parse(time.RFC3339, "2015-01-01T20:17:05Z")
So(err, ShouldBeNil)
vals6 := sec.Key("TIMES").Times(",")
timesEqual(vals6, t, t, t)
})
Convey("Test string slice escapes", func() {
sec := f.Section("string escapes")
So(sec.Key("key1").Strings(","), ShouldResemble, []string{"value1", "value2", "value3"})
So(sec.Key("key2").Strings(","), ShouldResemble, []string{"value1, value2"})
So(sec.Key("key3").Strings(","), ShouldResemble, []string{`val\ue1`, "value2"})
So(sec.Key("key4").Strings(","), ShouldResemble, []string{`value1\`, `value\\2`})
So(sec.Key("key5").Strings(",,"), ShouldResemble, []string{"value1,, value2"})
So(sec.Key("key6").Strings(" "), ShouldResemble, []string{"aaa", "bbb and space", "ccc"})
})
Convey("Get valid values into slice", func() {
sec := f.Section("array")
vals1 := sec.Key("FLOAT64S").ValidFloat64s(",")
float64sEqual(vals1, 1.1, 2.2, 3.3)
vals2 := sec.Key("INTS").ValidInts(",")
intsEqual(vals2, 1, 2, 3)
vals3 := sec.Key("INTS").ValidInt64s(",")
int64sEqual(vals3, 1, 2, 3)
vals4 := sec.Key("UINTS").ValidUints(",")
uintsEqual(vals4, 1, 2, 3)
vals5 := sec.Key("UINTS").ValidUint64s(",")
uint64sEqual(vals5, 1, 2, 3)
t, err := time.Parse(time.RFC3339, "2015-01-01T20:17:05Z")
So(err, ShouldBeNil)
vals6 := sec.Key("TIMES").ValidTimes(",")
timesEqual(vals6, t, t, t)
})
Convey("Get values one type into slice of another type", func() {
sec := f.Section("array")
vals1 := sec.Key("STRINGS").ValidFloat64s(",")
So(vals1, ShouldBeEmpty)
vals2 := sec.Key("STRINGS").ValidInts(",")
So(vals2, ShouldBeEmpty)
vals3 := sec.Key("STRINGS").ValidInt64s(",")
So(vals3, ShouldBeEmpty)
vals4 := sec.Key("STRINGS").ValidUints(",")
So(vals4, ShouldBeEmpty)
vals5 := sec.Key("STRINGS").ValidUint64s(",")
So(vals5, ShouldBeEmpty)
vals6 := sec.Key("STRINGS").ValidTimes(",")
So(vals6, ShouldBeEmpty)
})
Convey("Get valid values into slice without errors", func() {
sec := f.Section("array")
vals1, err := sec.Key("FLOAT64S").StrictFloat64s(",")
So(err, ShouldBeNil)
float64sEqual(vals1, 1.1, 2.2, 3.3)
vals2, err := sec.Key("INTS").StrictInts(",")
So(err, ShouldBeNil)
intsEqual(vals2, 1, 2, 3)
vals3, err := sec.Key("INTS").StrictInt64s(",")
So(err, ShouldBeNil)
int64sEqual(vals3, 1, 2, 3)
vals4, err := sec.Key("UINTS").StrictUints(",")
So(err, ShouldBeNil)
uintsEqual(vals4, 1, 2, 3)
vals5, err := sec.Key("UINTS").StrictUint64s(",")
So(err, ShouldBeNil)
uint64sEqual(vals5, 1, 2, 3)
t, err := time.Parse(time.RFC3339, "2015-01-01T20:17:05Z")
So(err, ShouldBeNil)
vals6, err := sec.Key("TIMES").StrictTimes(",")
So(err, ShouldBeNil)
timesEqual(vals6, t, t, t)
})
Convey("Get invalid values into slice", func() {
sec := f.Section("array")
vals1, err := sec.Key("STRINGS").StrictFloat64s(",")
So(vals1, ShouldBeEmpty)
So(err, ShouldNotBeNil)
vals2, err := sec.Key("STRINGS").StrictInts(",")
So(vals2, ShouldBeEmpty)
So(err, ShouldNotBeNil)
vals3, err := sec.Key("STRINGS").StrictInt64s(",")
So(vals3, ShouldBeEmpty)
So(err, ShouldNotBeNil)
vals4, err := sec.Key("STRINGS").StrictUints(",")
So(vals4, ShouldBeEmpty)
So(err, ShouldNotBeNil)
vals5, err := sec.Key("STRINGS").StrictUint64s(",")
So(vals5, ShouldBeEmpty)
So(err, ShouldNotBeNil)
vals6, err := sec.Key("STRINGS").StrictTimes(",")
So(vals6, ShouldBeEmpty)
So(err, ShouldNotBeNil)
})
})
}
func TestKey_StringsWithShadows(t *testing.T) {
Convey("Get strings of shadows of a key", t, func() {
f, err := ini.ShadowLoad([]byte(""))
So(err, ShouldBeNil)
So(f, ShouldNotBeNil)
k, err := f.Section("").NewKey("NUMS", "1,2")
So(err, ShouldBeNil)
So(k, ShouldNotBeNil)
k, err = f.Section("").NewKey("NUMS", "4,5,6")
So(err, ShouldBeNil)
So(k, ShouldNotBeNil)
So(k.StringsWithShadows(","), ShouldResemble, []string{"1", "2", "4", "5", "6"})
})
}
func TestKey_SetValue(t *testing.T) {
Convey("Set value of key", t, func() {
f := ini.Empty()
So(f, ShouldNotBeNil)
k, err := f.Section("").NewKey("NAME", "ini")
So(err, ShouldBeNil)
So(k, ShouldNotBeNil)
So(k.Value(), ShouldEqual, "ini")
k.SetValue("ini.v1")
So(k.Value(), ShouldEqual, "ini.v1")
})
}
func TestKey_NestedValues(t *testing.T) {
Convey("Read and write nested values", t, func() {
f, err := ini.LoadSources(ini.LoadOptions{
AllowNestedValues: true,
}, []byte(`
aws_access_key_id = foo
aws_secret_access_key = bar
region = us-west-2
s3 =
max_concurrent_requests=10
max_queue_size=1000`))
So(err, ShouldBeNil)
So(f, ShouldNotBeNil)
So(f.Section("").Key("s3").NestedValues(), ShouldResemble, []string{"max_concurrent_requests=10", "max_queue_size=1000"})
var buf bytes.Buffer
_, err = f.WriteTo(&buf)
So(err, ShouldBeNil)
So(buf.String(), ShouldEqual, `aws_access_key_id = foo
aws_secret_access_key = bar
region = us-west-2
s3 =
max_concurrent_requests=10
max_queue_size=1000
`)
})
}
func TestRecursiveValues(t *testing.T) {
Convey("Recursive values should not reflect on same key", t, func() {
f, err := ini.Load([]byte(`
NAME = ini
[package]
NAME = %(NAME)s`))
So(err, ShouldBeNil)
So(f, ShouldNotBeNil)
So(f.Section("package").Key("NAME").String(), ShouldEqual, "ini")
})
}
| {
"pile_set_name": "Github"
} |
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.HeartbeatHandler = (client) => {
if (client) {
const nowTime = new Date().getTime();
client.setLastPing(nowTime);
}
return true;
};
| {
"pile_set_name": "Github"
} |
context("test-speedglm-speedglm")
skip_on_cran()
skip_if_not_installed("modeltests")
library(modeltests)
skip_if_not_installed("speedglm")
library(speedglm)
clotting <- data.frame(
u = c(5, 10, 15, 20, 30, 40, 60, 80, 100),
lot1 = c(118, 58, 42, 35, 27, 25, 21, 19, 18)
)
fit <- speedglm(lot1 ~ log(u), data = clotting, family = Gamma(log))
test_that("speedglm tidiers arguments", {
check_arguments(tidy.speedglm)
check_arguments(glance.speedglm)
})
test_that("tidy.speedglm", {
td <- tidy(fit, conf.int = TRUE, exponentiate = TRUE)
check_tidy_output(td)
# watch out for the bizarro factor p-values reported in #660
expect_type(td$p.value, "double")
check_dims(td, 2, 7)
})
test_that("glance.speedglm", {
gl <- glance(fit)
check_glance_outputs(gl)
})
test_that("augment.speedglm errors", {
# speedglm sub-classes speedlm, and there's an augment.speedlm()
# method we want to make sure isn't accidentally invoked
expect_error(augment(fit))
})
| {
"pile_set_name": "Github"
} |
/*******************************************************************************
* Copyright (c) 2004 Actuate Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Actuate Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.birt.report.model.elements;
import org.eclipse.birt.report.model.api.DesignElementHandle;
import org.eclipse.birt.report.model.api.ParameterGroupHandle;
import org.eclipse.birt.report.model.api.elements.ReportDesignConstants;
import org.eclipse.birt.report.model.core.ContainerSlot;
import org.eclipse.birt.report.model.core.DesignElement;
import org.eclipse.birt.report.model.core.Module;
import org.eclipse.birt.report.model.elements.interfaces.IParameterGroupModel;
/**
* This class represents a parameter group. A parameter group creates a visual
* grouping of parameters. The developer controls the order that groups appear
* in the UI, and the order in which parameters appear in the group. The
* BIRT-provided runtime UI will may choose to allow the user to expand &
* collapse parameter groups independently.
*
*/
public class ParameterGroup extends DesignElement
implements
IParameterGroupModel
{
/**
* Default constructor.
*/
public ParameterGroup( )
{
initSlots( );
}
/**
* Constructs the parameter group with an optional name.
*
* @param theName
* the optional name
*/
public ParameterGroup( String theName )
{
super( theName );
initSlots( );
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.model.core.DesignElement#getSlot(int)
*/
public ContainerSlot getSlot( int slot )
{
assert slot == PARAMETERS_SLOT;
return slots[PARAMETERS_SLOT];
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.model.core.DesignElement#apply(org.eclipse.birt.report.model.elements.ElementVisitor)
*/
public void apply( ElementVisitor visitor )
{
visitor.visitParameterGroup( this );
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.model.core.DesignElement#getElementName()
*/
public String getElementName( )
{
return ReportDesignConstants.PARAMETER_GROUP_ELEMENT;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.model.core.DesignElement#getHandle(org.eclipse.birt.report.model.elements.ReportDesign)
*/
public DesignElementHandle getHandle( Module module )
{
return handle( module );
}
/**
* Returns an API handle for this element.
*
* @param module
* the report design
* @return an API handle for this element
*/
public ParameterGroupHandle handle( Module module )
{
if ( handle == null )
{
handle = new ParameterGroupHandle( module, this );
}
return (ParameterGroupHandle) handle;
}
} | {
"pile_set_name": "Github"
} |
package com.tinkerpop.gremlin.groovy.console;
import java.util.Map;
/**
* Those wanting to extend the Gremlin Console can extend this class to provide custom imports and extension
* methods to the language itself. Gremlin Console uses ServiceLoader to install plugins. It is necessary for
* projects wishing to extend the Console to include a com.tinkerpop.gremlin.groovy.console.ConsolePlugin file in
* META-INF/services of their packaged project which includes the full class names of the implementations of this
* interface to install.
*
* @author Stephen Mallette (http://stephen.genoprime.com)
*/
public interface ConsolePlugin {
/**
* The name of the plugin. This name should be unique as naming clashes will prevent proper plugin operations.
*/
String getName();
/**
* Implementors will typically execute imports of classes within their project that they want available in the
* console. They may use groovy meta programming to introduce new extensions to the Gremlin.
*
* @param args Arbitrary arguments passed from the caller of Gremlin.use() to be used as the plugin sees fit.
*/
void pluginTo(final ConsoleGroovy groovy, final ConsoleIO io, final Map args);
}
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">Flip Demo</string>
<string name="activity_title">Flip Demo By Aphid Mobile</string>
<string name="first_page_title">[1] OpenAphid 0.2 is Available</string>
<string name="first_page_description">AphidMobile is pleased to announce the availability of OpenAphid 0.2.
\n\n
Highlights of the 0.2 release include:
\n\n
- New binding system for exposing Objective-C methods to JavaScript
\n\n
- Hide constructor when enumerating attributs of an OpenAphid JavaScript object
\n\n
- Fix incorrect value of node.onframeupdate when it’s not set; should be null instead of an invalid empty value
\n\n
- Add a new target of ObjCBindingTest in Demos
\n\n
- Support Google Analytics iOS SDK in Boilerplate-iOS
</string>
<string name="second_page_title">[2] JavaScript and Cocos2D-iPhone: A Sneak Peek of OpenAphid</string>
<string name="second_page_description">
OpenAphid is our secret OSS project to combine the power of JavaScript and Cocos2d-iPhone for native game
development on mobile devices. It allows developers to write fast and native quality games in JavaScript language.
\n\n
A set of Cocos2D-style JavaScript APIs are provided for composing scenes, applying actions on nodes, handling
events, etc. The core runtime of OpenAphid is wrote in C++, which adopts the architecture of Cocos2d-iPhone. The
JavaScript binding module bridges the C++ runtime and the JavaScript engine, which allows games to use native
features in pure JavaScript.
\n\n
A set of Cocos2D-style JavaScript APIs are provided for composing scenes, applying actions on nodes, handling
events, etc. The core runtime of OpenAphid is wrote in C++, which adopts the architecture of Cocos2d-iPhone. The
JavaScript binding module bridges the C++ runtime and the JavaScript engine, which allows games to use native
features in pure JavaScript.
</string>
<string name="item_about">about</string>
</resources>
| {
"pile_set_name": "Github"
} |
{
"browserslist": [
"chrome 78"
]
}
| {
"pile_set_name": "Github"
} |
---
title: Object doesn't support named arguments (Error 446)
keywords: vblr6.chm1011332
f1_keywords:
- vblr6.chm1011332
ms.prod: office
ms.assetid: cb7d923a-e877-6a0e-0a2a-12c81399c218
ms.date: 06/08/2017
localization_priority: Normal
---
# Object doesn't support named arguments (Error 446)
Not all objects support [named arguments](../../Glossary/vbe-glossary.md#named-argument). This error has the following cause and solution:
- You tried to access an object whose [methods](../../Glossary/vbe-glossary.md#method) don't support named arguments.
Specify [arguments](../../Glossary/vbe-glossary.md#argument) positionally when performing methods on this object. See the object's documentation for more information on argument positions and types.
For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).
[!include[Support and feedback](~/includes/feedback-boilerplate.md)] | {
"pile_set_name": "Github"
} |
/*
******************************************************************************
**
** File : LinkerScript.ld
**
**
** Abstract : Linker script for STM32H7 series
** 128Kbytes RAM_EXEC and 160Kbytes RAM
**
** Set heap size, stack size and stack location according
** to application requirements.
**
** Set memory bank area and size if external memory is used.
**
** Target : STMicroelectronics STM32
**
** Distribution: The file is distributed “as is,” without any warranty
** of any kind.
**
*****************************************************************************
** @attention
**
** Copyright (c) 2019 STMicroelectronics.
** All rights reserved.
**
** This software component is licensed by ST under BSD 3-Clause license,
** the "License"; You may not use this file except in compliance with the
** License. You may obtain a copy of the License at:
** opensource.org/licenses/BSD-3-Clause
**
****************************************************************************
*/
/* Entry Point */
ENTRY(Reset_Handler)
/* Highest address of the user mode stack */
_estack = 0x10048000; /* end of RAM */
/* Generate a link error if heap and stack don't fit into RAM */
_Min_Heap_Size = 0x200; /* required amount of heap */
_Min_Stack_Size = 0x400; /* required amount of stack */
/* Specify the memory areas */
MEMORY
{
RAM_EXEC (rx) : ORIGIN = 0x10000000, LENGTH = 128K
RAM (xrw) : ORIGIN = 0x10020000, LENGTH = 160K
}
/* Define output sections */
SECTIONS
{
/* The startup code goes first into RAM_EXEC */
.isr_vector :
{
. = ALIGN(4);
KEEP(*(.isr_vector)) /* Startup code */
. = ALIGN(4);
} >RAM_EXEC
/* The program code and other data goes into RAM_EXEC */
.text :
{
. = ALIGN(4);
*(.text) /* .text sections (code) */
*(.text*) /* .text* sections (code) */
*(.glue_7) /* glue arm to thumb code */
*(.glue_7t) /* glue thumb to arm code */
*(.eh_frame)
KEEP (*(.init))
KEEP (*(.fini))
. = ALIGN(4);
_etext = .; /* define a global symbols at end of code */
} >RAM_EXEC
/* Constant data goes into RAM_EXEC */
.rodata :
{
. = ALIGN(4);
*(.rodata) /* .rodata sections (constants, strings, etc.) */
*(.rodata*) /* .rodata* sections (constants, strings, etc.) */
. = ALIGN(4);
} >RAM_EXEC
.ARM.extab : { *(.ARM.extab* .gnu.linkonce.armextab.*) } >RAM_EXEC
.ARM : {
__exidx_start = .;
*(.ARM.exidx*)
__exidx_end = .;
} >RAM_EXEC
.preinit_array :
{
PROVIDE_HIDDEN (__preinit_array_start = .);
KEEP (*(.preinit_array*))
PROVIDE_HIDDEN (__preinit_array_end = .);
} >RAM_EXEC
.init_array :
{
PROVIDE_HIDDEN (__init_array_start = .);
KEEP (*(SORT(.init_array.*)))
KEEP (*(.init_array*))
PROVIDE_HIDDEN (__init_array_end = .);
} >RAM_EXEC
.fini_array :
{
PROVIDE_HIDDEN (__fini_array_start = .);
KEEP (*(SORT(.fini_array.*)))
KEEP (*(.fini_array*))
PROVIDE_HIDDEN (__fini_array_end = .);
} >RAM_EXEC
/* used by the startup to initialize data */
_sidata = LOADADDR(.data);
/* Initialized data sections goes into RAM, load LMA copy after code */
.data :
{
. = ALIGN(4);
_sdata = .; /* create a global symbol at data start */
*(.data) /* .data sections */
*(.data*) /* .data* sections */
. = ALIGN(4);
_edata = .; /* define a global symbol at data end */
} >RAM AT> RAM_EXEC
/* Uninitialized data section */
. = ALIGN(4);
.bss :
{
/* This is used by the startup in order to initialize the .bss secion */
_sbss = .; /* define a global symbol at bss start */
__bss_start__ = _sbss;
*(.bss)
*(.bss*)
*(COMMON)
. = ALIGN(4);
_ebss = .; /* define a global symbol at bss end */
__bss_end__ = _ebss;
} >RAM
/* User_heap_stack section, used to check that there is enough RAM left */
._user_heap_stack :
{
. = ALIGN(8);
PROVIDE ( end = . );
PROVIDE ( _end = . );
. = . + _Min_Heap_Size;
. = . + _Min_Stack_Size;
. = ALIGN(8);
} >RAM
/* Remove information from the standard libraries */
/DISCARD/ :
{
libc.a ( * )
libm.a ( * )
libgcc.a ( * )
}
.ARM.attributes 0 : { *(.ARM.attributes) }
}
| {
"pile_set_name": "Github"
} |
<?php
namespace Particle\Validator\Tests\Rule;
use Particle\Validator\Rule\Json;
use Particle\Validator\Validator;
class JsonTest extends \PHPUnit_Framework_TestCase
{
/**
* @var Validator
*/
protected $validator;
protected function setUp()
{
$this->validator = new Validator();
}
/**
* @dataProvider getValidJsonStrings
* @param string $value
*/
public function testReturnsTrueOnValidJsonString($value)
{
$this->validator->required('json')->json();
$result = $this->validator->validate(['json' => $value]);
$this->assertTrue($result->isValid());
}
/**
* @dataProvider getInvalidJsonStrings
* @param string $value
*/
public function testReturnsFalseOnInvalidJsonString($value)
{
$this->validator->required('json')->json();
$result = $this->validator->validate(['json' => $value]);
$this->assertFalse($result->isValid());
$expected = [
'json' => [
Json::INVALID_FORMAT => 'json must be a valid JSON string'
]
];
$this->assertEquals($expected, $result->getMessages());
}
/**
* Returns a list of JSON strings considered valid.
*
* @return array
*/
public function getValidJsonStrings()
{
return [
['{}'],
['[]'],
['{"a": "b", "c": "d"}'],
['{"a": null, "c": true}'],
['{"a": 9, "c": 9.99}'],
['9'],
['"json"'],
];
}
/**
* Returns a list of JSON strings considered invalid.
*
* @return array
*/
public function getInvalidJsonStrings()
{
return [
['["a": "b"'],
["{'a': 'b'}"],
['json'],
[9],
];
}
}
| {
"pile_set_name": "Github"
} |
# Description:
# Test data (Tensorflow checkpoints) for vp/pretrained tests.
licenses(["notice"]) # Apache 2.0 License
exports_files(["LICENSE"])
package(
default_visibility = ["//sonnet/python:__pkg__"],
)
filegroup(
name = "restore_initializer_test_checkpoint",
srcs = glob(["restore_initializer_test_checkpoint.*"]),
)
| {
"pile_set_name": "Github"
} |
# Datasources
Datasources are used in Renovate primarily to fetch released versions of packages.
### getReleases
The minimum exported interface for a datasource is a function called `getReleases` that takes a lookup config as input.
The config contains:
- `lookupName`: the package's full name including scope if present (e.g. `@foo/bar`)
- `registryUrls`: an array of registry Urls to try
`getReleases` should return an object containing:
- `releases`: an array of strings of matched versions. This is the only mandatory field.
- `deprecationMessage`: a string description of the package's deprecation notice, if applicable
- `sourceUrl`: a HTTP URL pointing to the source code (e.g. on GitHub)
- `homepage`: a HTTP URL for the package's homepage. Ideally should be empty if the homepage and sourceUrl are the same
- `changelogUrl`: a URL pointing to the package's Changelog (could be a markdown file, for example). If not present then Renovate will search the `sourceUrl` for a changelog file.
- `tags`: an object mapping tag -> version, e.g. `tags: { latest: '3.0.0' }`. This is only used by the `followTags` function.
### getDigest
Datasources that support the concept of digests (e.g. docker digests and git commit hashes) also can export a `getDigest` function.
The `getDigest` function has two inputs:
- `config`: the Renovate config for the package being updated, contains same fields as `getReleases`
- `newValue`: the version or value to retrieve the digest for
The `getDigest` function returns a string output representing the digest value. If none is found then a return value of `null` should be returned.
| {
"pile_set_name": "Github"
} |
// Copyright 2017 Google Inc. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// +build !js
package uuid
import "net"
var interfaces []net.Interface // cached list of interfaces
// getHardwareInterface returns the name and hardware address of interface name.
// If name is "" then the name and hardware address of one of the system's
// interfaces is returned. If no interfaces are found (name does not exist or
// there are no interfaces) then "", nil is returned.
//
// Only addresses of at least 6 bytes are returned.
func getHardwareInterface(name string) (string, []byte) {
if interfaces == nil {
var err error
interfaces, err = net.Interfaces()
if err != nil {
return "", nil
}
}
for _, ifs := range interfaces {
if len(ifs.HardwareAddr) >= 6 && (name == "" || name == ifs.Name) {
return ifs.Name, ifs.HardwareAddr
}
}
return "", nil
}
| {
"pile_set_name": "Github"
} |
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// +build 386,openbsd
package unix
func Getpagesize() int { return 4096 }
func TimespecToNsec(ts Timespec) int64 { return int64(ts.Sec)*1e9 + int64(ts.Nsec) }
func NsecToTimespec(nsec int64) (ts Timespec) {
ts.Sec = int64(nsec / 1e9)
ts.Nsec = int32(nsec % 1e9)
return
}
func TimevalToNsec(tv Timeval) int64 { return int64(tv.Sec)*1e9 + int64(tv.Usec)*1e3 }
func NsecToTimeval(nsec int64) (tv Timeval) {
nsec += 999 // round up to microsecond
tv.Usec = int32(nsec % 1e9 / 1e3)
tv.Sec = int64(nsec / 1e9)
return
}
func SetKevent(k *Kevent_t, fd, mode, flags int) {
k.Ident = uint32(fd)
k.Filter = int16(mode)
k.Flags = uint16(flags)
}
func (iov *Iovec) SetLen(length int) {
iov.Len = uint32(length)
}
func (msghdr *Msghdr) SetControllen(length int) {
msghdr.Controllen = uint32(length)
}
func (cmsg *Cmsghdr) SetLen(length int) {
cmsg.Len = uint32(length)
}
| {
"pile_set_name": "Github"
} |
{
"javascript.updateImportsOnFileMove.enabled": "always",
"javascript.preferences.importModuleSpecifier": "non-relative",
"workbench.colorCustomizations": {
"titleBar.activeForeground": "#000",
"titleBar.inactiveForeground": "#000000CC",
"titleBar.activeBackground": "#ffc600",
"titleBar.inactiveBackground": "#ffc600CC"
}
}
| {
"pile_set_name": "Github"
} |
{
"name": "@cloudbeaver/core-utils",
"sideEffects": false,
"version": "0.1.0",
"description": "",
"license": "Apache-2.0",
"main": "lib/index.js",
"module": "lib/index.js",
"types": "src/index.ts",
"scripts": {
"prebuild": "rimraf lib/*",
"build": "webpack --config ../../configs/webpack.plugin.config",
"postbuild": "tsc",
"lint": "eslint ./src/ --ext .ts,.tsx",
"lint-fix": "eslint ./src/ --ext .ts,.tsx --fix"
},
"dependencies": {
"uuid": "^7.0.3"
},
"peerDependencies": {
"mobx": "^5.x.x"
},
"devDependencies": {
"@types/uuid": "^7.0.2"
}
} | {
"pile_set_name": "Github"
} |
/*
* Copyright (C) 2014 Haruki Hasegawa
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.h6ah4i.android.media.openslmediaplayer.methodtest;
import java.io.IOException;
import junit.framework.TestSuite;
import com.h6ah4i.android.media.IBasicMediaPlayer;
import com.h6ah4i.android.media.IMediaPlayerFactory;
import com.h6ah4i.android.media.openslmediaplayer.base.BasicMediaPlayerStateTestCaseBase;
import com.h6ah4i.android.media.openslmediaplayer.base.BasicMediaPlayerTestCaseBase;
import com.h6ah4i.android.media.openslmediaplayer.utils.CompletionListenerObject;
import com.h6ah4i.android.media.openslmediaplayer.utils.ErrorListenerObject;
import com.h6ah4i.android.media.openslmediaplayer.testing.ParameterizedTestArgs;
public class BasicMediaPlayerTestCase_ReleaseMethod
extends BasicMediaPlayerStateTestCaseBase {
public static TestSuite buildTestSuite(Class<? extends IMediaPlayerFactory> factoryClazz) {
return BasicMediaPlayerTestCaseBase.buildBasicTestSuite(
BasicMediaPlayerTestCase_ReleaseMethod.class, factoryClazz);
}
public BasicMediaPlayerTestCase_ReleaseMethod(ParameterizedTestArgs args) {
super(args);
}
private void expectsNoErrors(IBasicMediaPlayer player) throws IOException {
Object sharedSyncObj = new Object();
ErrorListenerObject err = new ErrorListenerObject(sharedSyncObj, false);
CompletionListenerObject comp = new CompletionListenerObject(sharedSyncObj);
// check no errors
player.setOnErrorListener(err);
player.setOnCompletionListener(comp);
player.release();
if (comp.await(SHORT_EVENT_WAIT_DURATION)) {
fail(comp + ", " + err);
}
assertFalse(comp.occurred());
assertFalse(err.occurred());
}
// private void expectsIllegalStateException(IBasicMediaPlayer player) {
// try {
// player.release();
// } catch (IllegalStateException e) {
// // expected
// return;
// }
// fail();
// }
@Override
protected void onTestStateIdle(IBasicMediaPlayer player, Object args) throws Throwable {
expectsNoErrors(player);
}
@Override
protected void onTestStateInitialized(IBasicMediaPlayer player, Object args) throws Throwable {
expectsNoErrors(player);
}
@Override
protected void onTestStatePreparing(IBasicMediaPlayer player, Object args) throws Throwable {
expectsNoErrors(player);
}
@Override
protected void onTestStatePrepared(IBasicMediaPlayer player, Object args) throws Throwable {
expectsNoErrors(player);
}
@Override
protected void onTestStateStarted(IBasicMediaPlayer player, Object args) throws Throwable {
expectsNoErrors(player);
}
@Override
protected void onTestStatePaused(IBasicMediaPlayer player, Object args) throws Throwable {
expectsNoErrors(player);
}
@Override
protected void onTestStateStopped(IBasicMediaPlayer player, Object args) throws Throwable {
expectsNoErrors(player);
}
@Override
protected void onTestStatePlaybackCompleted(IBasicMediaPlayer player, Object args)
throws Throwable {
expectsNoErrors(player);
}
@Override
protected void onTestStateErrorBeforePrepared(IBasicMediaPlayer player, Object args)
throws Throwable {
expectsNoErrors(player);
}
@Override
protected void onTestStateErrorAfterPrepared(IBasicMediaPlayer player, Object args)
throws Throwable {
expectsNoErrors(player);
}
@Override
protected void onTestStateEnd(IBasicMediaPlayer player, Object args) throws Throwable {
// NOTE: StandardMediaPlayer will fail on this test case. It throws
// IllegalStateException.
expectsNoErrors(player);
// expectsIllegalStateException(player);
}
}
| {
"pile_set_name": "Github"
} |
golang-lru
==========
This provides the `lru` package which implements a fixed-size
thread safe LRU cache. It is based on the cache in Groupcache.
Documentation
=============
Full docs are available on [Godoc](http://godoc.org/github.com/hashicorp/golang-lru)
Example
=======
Using the LRU is very simple:
```go
l, _ := New(128)
for i := 0; i < 256; i++ {
l.Add(i, nil)
}
if l.Len() != 128 {
panic(fmt.Sprintf("bad len: %v", l.Len()))
}
```
| {
"pile_set_name": "Github"
} |
/*
YUI 3.17.2 (build 9c3c78e)
Copyright 2014 Yahoo! Inc. All rights reserved.
Licensed under the BSD License.
http://yuilibrary.com/license/
*/
.yui3-widget-stacked .yui3-widget-shim{opacity:0;filter:alpha(opacity=0);position:absolute;border:0;top:0;left:0;padding:0;margin:0;z-index:-1;width:100%;height:100%;_width:0;_height:0}#yui3-css-stamp.skin-night-widget-stack{display:none}
| {
"pile_set_name": "Github"
} |
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>CodeMirror: Vim bindings demo</title>
<link rel="stylesheet" href="../lib/codemirror.css">
<script src="../lib/codemirror.js"></script>
<script src="../addon/dialog/dialog.js"></script>
<script src="../addon/search/searchcursor.js"></script>
<script src="../mode/clike/clike.js"></script>
<script src="../keymap/vim.js"></script>
<link rel="stylesheet" href="../doc/docs.css">
<link rel="stylesheet" href="../addon/dialog/dialog.css">
<style type="text/css">
.CodeMirror {border-top: 1px solid #eee; border-bottom: 1px solid #eee;}
</style>
</head>
<body>
<h1>CodeMirror: Vim bindings demo</h1>
<form><textarea id="code" name="code">
#include "syscalls.h"
/* getchar: simple buffered version */
int getchar(void)
{
static char buf[BUFSIZ];
static char *bufp = buf;
static int n = 0;
if (n == 0) { /* buffer is empty */
n = read(0, buf, sizeof buf);
bufp = buf;
}
return (--n >= 0) ? (unsigned char) *bufp++ : EOF;
}
</textarea></form>
<form><textarea id="code2" name="code2">
I am another file! You can yank from my neighbor and paste here.
</textarea></form>
<p>The vim keybindings are enabled by
including <a href="../keymap/vim.js">keymap/vim.js</a> and setting
the <code>keyMap</code> option to <code>"vim"</code>. Because
CodeMirror's internal API is quite different from Vim, they are only
a loose approximation of actual vim bindings, though.</p>
<script>
CodeMirror.commands.save = function(){ alert("Saving"); };
var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
lineNumbers: true,
mode: "text/x-csrc",
vimMode: true,
showCursorWhenSelecting: true
});
var editor2 = CodeMirror.fromTextArea(document.getElementById("code2"), {
lineNumbers: true,
mode: "text/x-csrc",
vimMode: true,
showCursorWhenSelecting: true
});
</script>
</body>
</html>
| {
"pile_set_name": "Github"
} |
/* The contents of this file are subject to the Netscape Public
* License Version 1.1 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.mozilla.org/NPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* The Original Code is Mozilla Communicator client code, released March
* 31, 1998.
*
* The Initial Developer of the Original Code is Netscape Communications
* Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
*
*/
/**
File Name: 15.6.4-2.js
ECMA Section: 15.6.4 Properties of the Boolean Prototype Object
Description:
The Boolean prototype object is itself a Boolean object (its [[Class]] is
"Boolean") whose value is false.
The value of the internal [[Prototype]] property of the Boolean prototype object
is the Object prototype object (15.2.3.1).
Author: christine@netscape.com
Date: 30 september 1997
*/
var VERSION = "ECMA_2"
startTest();
var SECTION = "15.6.4-2";
writeHeaderToLog( SECTION + " Properties of the Boolean Prototype Object");
var testcases = getTestCases();
test();
function getTestCases() {
var array = new Array();
var item = 0;
array[item++] = new TestCase( SECTION, "Boolean.prototype.__proto__", Object.prototype, Boolean.prototype.__proto__ );
return ( array );
}
function test() {
for (tc = 0; tc < testcases.length; tc++ ) {
testcases[tc].passed = writeTestCaseResult(
testcases[tc].expect,
testcases[tc].actual,
testcases[tc].description +" = "+ testcases[tc].actual );
testcases[tc].reason += ( testcases[tc].passed ) ? "" : "wrong value "
}
stopTest();
return ( testcases );
}
| {
"pile_set_name": "Github"
} |
#import <stdio.h>
#import <mach/mach.h>
#import <mach/error.h>
#import <mach/message.h>
#import <CoreFoundation/CoreFoundation.h>
kern_return_t mach_vm_read(vm_map_t target_task,
mach_vm_address_t address,
mach_vm_size_t size,
vm_offset_t *data,
mach_msg_type_number_t *dataCnt);
kern_return_t mach_vm_write(vm_map_t target_task,
mach_vm_address_t address,
vm_offset_t data,
mach_msg_type_number_t dataCnt);
kern_return_t mach_vm_read_overwrite(vm_map_t target_task,
mach_vm_address_t address,
mach_vm_size_t size,
mach_vm_address_t data,
mach_vm_size_t *outsize);
kern_return_t mach_vm_region(vm_map_t target_task,
mach_vm_address_t *address,
mach_vm_size_t *size,
vm_region_flavor_t flavor,
vm_region_info_t info,
mach_msg_type_number_t *infoCnt,
mach_port_t *object_name);
/****** IOKit/IOKitLib.h *****/
typedef mach_port_t io_service_t;
typedef mach_port_t io_connect_t;
extern const mach_port_t kIOMasterPortDefault;
#define IO_OBJECT_NULL (0)
kern_return_t
IOConnectCallAsyncMethod(
mach_port_t connection,
uint32_t selector,
mach_port_t wakePort,
uint64_t* reference,
uint32_t referenceCnt,
const uint64_t* input,
uint32_t inputCnt,
const void* inputStruct,
size_t inputStructCnt,
uint64_t* output,
uint32_t* outputCnt,
void* outputStruct,
size_t* outputStructCntP);
kern_return_t
IOConnectCallMethod(
mach_port_t connection,
uint32_t selector,
const uint64_t* input,
uint32_t inputCnt,
const void* inputStruct,
size_t inputStructCnt,
uint64_t* output,
uint32_t* outputCnt,
void* outputStruct,
size_t* outputStructCntP);
io_service_t
IOServiceGetMatchingService(
mach_port_t _masterPort,
CFDictionaryRef matching);
CFMutableDictionaryRef
IOServiceMatching(
const char* name);
kern_return_t
IOServiceOpen(
io_service_t service,
task_port_t owningTask,
uint32_t type,
io_connect_t* connect );
kern_return_t IOConnectTrap6(io_connect_t connect, uint32_t index, uintptr_t p1, uintptr_t p2, uintptr_t p3, uintptr_t p4, uintptr_t p5, uintptr_t p6);
kern_return_t mach_vm_read_overwrite(vm_map_t target_task, mach_vm_address_t address, mach_vm_size_t size, mach_vm_address_t data, mach_vm_size_t *outsize);
kern_return_t mach_vm_write(vm_map_t target_task, mach_vm_address_t address, vm_offset_t data, mach_msg_type_number_t dataCnt);
kern_return_t mach_vm_allocate(vm_map_t target, mach_vm_address_t *address, mach_vm_size_t size, int flags);
kern_return_t mach_vm_deallocate(vm_map_t target, mach_vm_address_t address, mach_vm_size_t size);
extern mach_port_t tfp0;
extern uint64_t kernel_base;
extern uint64_t kernel_slide;
extern uint64_t offset_zonemap;
extern uint64_t offset_kernel_task;
extern uint64_t offset_vfs_context_current;
extern uint64_t offset_vnode_getfromfd;
extern uint64_t offset_vnode_getattr;
extern uint64_t offset_vnode_put;
extern uint64_t offset_csblob_ent_dict_set;
extern uint64_t offset_sha1_init;
extern uint64_t offset_sha1_update;
extern uint64_t offset_sha1_final;
extern uint64_t offset_add_x0_x0_0x40_ret;
extern uint64_t offset_osboolean_true;
extern uint64_t offset_osboolean_false;
extern uint64_t offset_osunserialize_xml;
extern uint64_t offset_cs_find_md;
uint64_t proc_find(int pid, int tries);
uint64_t find_port(mach_port_name_t port);
| {
"pile_set_name": "Github"
} |
// Generated from definition io.k8s.api.auditregistration.v1alpha1.Webhook
/// Webhook holds the configuration of the webhook
#[derive(Clone, Debug, Default, PartialEq)]
pub struct Webhook {
/// ClientConfig holds the connection parameters for the webhook required
pub client_config: crate::api::auditregistration::v1alpha1::WebhookClientConfig,
/// Throttle holds the options for throttling the webhook
pub throttle: Option<crate::api::auditregistration::v1alpha1::WebhookThrottleConfig>,
}
impl<'de> serde::Deserialize<'de> for Webhook {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: serde::Deserializer<'de> {
#[allow(non_camel_case_types)]
enum Field {
Key_client_config,
Key_throttle,
Other,
}
impl<'de> serde::Deserialize<'de> for Field {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: serde::Deserializer<'de> {
struct Visitor;
impl<'de> serde::de::Visitor<'de> for Visitor {
type Value = Field;
fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("field identifier")
}
fn visit_str<E>(self, v: &str) -> Result<Self::Value, E> where E: serde::de::Error {
Ok(match v {
"clientConfig" => Field::Key_client_config,
"throttle" => Field::Key_throttle,
_ => Field::Other,
})
}
}
deserializer.deserialize_identifier(Visitor)
}
}
struct Visitor;
impl<'de> serde::de::Visitor<'de> for Visitor {
type Value = Webhook;
fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("Webhook")
}
fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error> where A: serde::de::MapAccess<'de> {
let mut value_client_config: Option<crate::api::auditregistration::v1alpha1::WebhookClientConfig> = None;
let mut value_throttle: Option<crate::api::auditregistration::v1alpha1::WebhookThrottleConfig> = None;
while let Some(key) = serde::de::MapAccess::next_key::<Field>(&mut map)? {
match key {
Field::Key_client_config => value_client_config = Some(serde::de::MapAccess::next_value(&mut map)?),
Field::Key_throttle => value_throttle = serde::de::MapAccess::next_value(&mut map)?,
Field::Other => { let _: serde::de::IgnoredAny = serde::de::MapAccess::next_value(&mut map)?; },
}
}
Ok(Webhook {
client_config: value_client_config.ok_or_else(|| serde::de::Error::missing_field("clientConfig"))?,
throttle: value_throttle,
})
}
}
deserializer.deserialize_struct(
"Webhook",
&[
"clientConfig",
"throttle",
],
Visitor,
)
}
}
impl serde::Serialize for Webhook {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: serde::Serializer {
let mut state = serializer.serialize_struct(
"Webhook",
1 +
self.throttle.as_ref().map_or(0, |_| 1),
)?;
serde::ser::SerializeStruct::serialize_field(&mut state, "clientConfig", &self.client_config)?;
if let Some(value) = &self.throttle {
serde::ser::SerializeStruct::serialize_field(&mut state, "throttle", value)?;
}
serde::ser::SerializeStruct::end(state)
}
}
| {
"pile_set_name": "Github"
} |
from toga_dummy.utils import TestCase
from toga_winforms import window
class TestWindow(TestCase):
def setUp(self):
super().setUp()
self.window = window.Window
def test_build_filter(self):
test_filter = self.window.build_filter(None, ["txt"])
self.assertEqual(test_filter, "txt files (*.txt)|*.txt|All files (*.*)|*.*")
| {
"pile_set_name": "Github"
} |
# Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from core.config_rel import cfg
import os
import cPickle as pickle
import logging
logger = logging.getLogger(__name__)
def get_gt_val_test_proposals(split, gt_roidb):
data_name = 'vg'
proposal_file = os.path.join(
cfg.DATA_DIR, 'proposals', data_name, 'gt_proposals_' + split + '.pkl')
if os.path.exists(proposal_file):
logger.info('Loading existing proposals from {}'.format(proposal_file))
with open(proposal_file, 'rb') as fid:
gt_proposals = pickle.load(fid)
# format conversion
proposals = [dict(boxes_sbj=gt_proposals['boxes_sbj'][ind],
boxes_obj=gt_proposals['boxes_obj'][ind],
boxes_rel=gt_proposals['boxes_rel'][ind])
for ind in range(len(gt_proposals['boxes_sbj']))]
else:
logger.info('generating proposals for {}'.format(data_name + '_' + split))
num_images = len(gt_roidb)
im_list_boxes_sbj = [[]] * num_images
im_list_boxes_obj = [[]] * num_images
im_list_boxes_rel = [[]] * num_images
for im_i, _ in enumerate(gt_roidb):
boxes_sbj = gt_roidb[im_i]['sbj_boxes']
boxes_obj = gt_roidb[im_i]['obj_boxes']
boxes_rel = gt_roidb[im_i]['rel_boxes']
im_list_boxes_sbj[im_i] = boxes_sbj
im_list_boxes_obj[im_i] = boxes_obj
im_list_boxes_rel[im_i] = boxes_rel
gt_proposals = dict(boxes_sbj=im_list_boxes_sbj,
boxes_obj=im_list_boxes_obj,
boxes_rel=im_list_boxes_rel)
with open(proposal_file, 'wb') as fid:
pickle.dump(gt_proposals, fid, pickle.HIGHEST_PROTOCOL)
logger.info('wrote gt proposals to {}'.format(proposal_file))
# format conversion
proposals = [dict(boxes_sbj=gt_proposals['boxes_sbj'][ind],
boxes_obj=gt_proposals['boxes_obj'][ind],
boxes_rel=gt_proposals['boxes_rel'][ind])
for ind in range(len(gt_proposals['boxes_sbj']))]
return proposals
| {
"pile_set_name": "Github"
} |
import Spinner from './spinner';
export default Spinner;
| {
"pile_set_name": "Github"
} |
fileFormatVersion: 2
guid: ac7a7f49f26f45b29857e71b0d156fff
timeCreated: 1497030443
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
| {
"pile_set_name": "Github"
} |
package org.openintents.filemanager.search;
import android.app.SearchManager;
import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.MatrixCursor;
import android.net.Uri;
import android.os.Environment;
import android.provider.BaseColumns;
import java.util.ArrayList;
import java.util.Locale;
import androidx.annotation.NonNull;
/**
* Not that good, but it's a working implementation at least. We REALLY need asynchronous suggestion refreshing.
*
* @author George Venios
*/
public class SearchSuggestionsProvider extends ContentProvider {
public static final String SEARCH_SUGGEST_MIMETYPE = "vnd.android.cursor.item/vnd.openintents.search_suggestion";
public static final String PROVIDER_NAME = "org.openintents.filemanager.search.suggest";
public static final Uri CONTENT_URI = Uri.parse("content://" + PROVIDER_NAME);
private static final long MAX_NANOS = 2000000;
private static final int MAX_SUGGESTIONS = 7;
private ArrayList<ContentValues> mSuggestions = new ArrayList<>();
private SearchCore searcher;
@Override
/**
* Always clears all suggestions. Parameters other than uri are ignored.
*/
public int delete(@NonNull Uri uri, String selection, String[] selectionArgs) {
int count = mSuggestions.size();
mSuggestions.clear();
getContext().getContentResolver().notifyChange(uri, null);
return count;
}
@Override
public String getType(@NonNull Uri uri) {
return SEARCH_SUGGEST_MIMETYPE;
}
@Override
@NonNull
public Uri insert(@NonNull Uri uri, ContentValues values) {
long id = mSuggestions.size() + 1;
values.put(BaseColumns._ID, id);
mSuggestions.add(values);
Uri _uri = ContentUris.withAppendedId(CONTENT_URI, id);
getContext().getContentResolver().notifyChange(_uri, null);
return _uri;
}
@Override
public boolean onCreate() {
searcher = new SearchCore(getContext());
searcher.setMaxResults(MAX_SUGGESTIONS);
searcher.setURI(CONTENT_URI);
return true;
}
@Override
/**
* NOT a cheap call. Actual search happens here.
*/
public Cursor query(@NonNull Uri uri, String[] projection, String selection,
String[] selectionArgs, String sortOrder) {
searcher.setQuery(uri.getLastPathSegment().toLowerCase(Locale.ROOT));
searcher.dropPreviousResults();
searcher.startClock(MAX_NANOS);
searcher.search(Environment.getExternalStorageDirectory());
MatrixCursor cursor = new MatrixCursor(new String[]{
SearchManager.SUGGEST_COLUMN_ICON_1,
SearchManager.SUGGEST_COLUMN_TEXT_1,
SearchManager.SUGGEST_COLUMN_TEXT_2,
SearchManager.SUGGEST_COLUMN_INTENT_DATA,
BaseColumns._ID});
for (ContentValues val : mSuggestions)
cursor.newRow().add(val.get(SearchManager.SUGGEST_COLUMN_ICON_1))
.add(val.get(SearchManager.SUGGEST_COLUMN_TEXT_1))
.add(val.get(SearchManager.SUGGEST_COLUMN_TEXT_2))
.add(val.get(SearchManager.SUGGEST_COLUMN_INTENT_DATA))
.add(val.get(BaseColumns._ID));
return cursor;
}
@Override
/**
* We don't care about updating. Unimplemented.
*/
public int update(@NonNull Uri uri, ContentValues values, String selection,
String[] selectionArgs) {
return 0;
}
} | {
"pile_set_name": "Github"
} |
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
gTestfile = '11.12-1.js';
/**
File Name: 11.12.js
ECMA Section: 11.12 Conditional Operator
Description:
Logi
calORExpression ? AssignmentExpression : AssignmentExpression
Semantics
The production ConditionalExpression :
LogicalORExpression ? AssignmentExpression : AssignmentExpression
is evaluated as follows:
1. Evaluate LogicalORExpression.
2. Call GetValue(Result(1)).
3. Call ToBoolean(Result(2)).
4. If Result(3) is false, go to step 8.
5. Evaluate the first AssignmentExpression.
6. Call GetValue(Result(5)).
7. Return Result(6).
8. Evaluate the second AssignmentExpression.
9. Call GetValue(Result(8)).
10. Return Result(9).
Author: christine@netscape.com
Date: 12 november 1997
*/
var SECTION = "11.12";
var VERSION = "ECMA_1";
startTest();
writeHeaderToLog( SECTION + " Conditional operator( ? : )");
new TestCase( SECTION,
"true ? 'PASSED' : 'FAILED'",
"PASSED",
(true?"PASSED":"FAILED"));
new TestCase( SECTION,
"false ? 'FAILED' : 'PASSED'",
"PASSED",
(false?"FAILED":"PASSED"));
new TestCase( SECTION,
"1 ? 'PASSED' : 'FAILED'",
"PASSED",
(true?"PASSED":"FAILED"));
new TestCase( SECTION,
"0 ? 'FAILED' : 'PASSED'",
"PASSED",
(false?"FAILED":"PASSED"));
new TestCase( SECTION,
"-1 ? 'PASSED' : 'FAILED'",
"PASSED",
(true?"PASSED":"FAILED"));
new TestCase( SECTION,
"NaN ? 'FAILED' : 'PASSED'",
"PASSED",
(Number.NaN?"FAILED":"PASSED"));
new TestCase( SECTION,
"var VAR = true ? , : 'FAILED'",
"PASSED",
(VAR = true ? "PASSED" : "FAILED") );
test();
| {
"pile_set_name": "Github"
} |
// Copyright 2013 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// +build !nacl,!plan9,!windows
package ipv6
import (
"net"
"syscall"
)
// ReadFrom reads a payload of the received IPv6 datagram, from the
// endpoint c, copying the payload into b. It returns the number of
// bytes copied into b, the control message cm and the source address
// src of the received datagram.
func (c *payloadHandler) ReadFrom(b []byte) (n int, cm *ControlMessage, src net.Addr, err error) {
if !c.ok() {
return 0, nil, nil, syscall.EINVAL
}
oob := newControlMessage(&c.rawOpt)
var oobn int
switch c := c.PacketConn.(type) {
case *net.UDPConn:
if n, oobn, _, src, err = c.ReadMsgUDP(b, oob); err != nil {
return 0, nil, nil, err
}
case *net.IPConn:
if n, oobn, _, src, err = c.ReadMsgIP(b, oob); err != nil {
return 0, nil, nil, err
}
default:
return 0, nil, nil, errInvalidConnType
}
if cm, err = parseControlMessage(oob[:oobn]); err != nil {
return 0, nil, nil, err
}
if cm != nil {
cm.Src = netAddrToIP16(src)
}
return
}
// WriteTo writes a payload of the IPv6 datagram, to the destination
// address dst through the endpoint c, copying the payload from b. It
// returns the number of bytes written. The control message cm allows
// the IPv6 header fields and the datagram path to be specified. The
// cm may be nil if control of the outgoing datagram is not required.
func (c *payloadHandler) WriteTo(b []byte, cm *ControlMessage, dst net.Addr) (n int, err error) {
if !c.ok() {
return 0, syscall.EINVAL
}
oob := marshalControlMessage(cm)
if dst == nil {
return 0, errMissingAddress
}
switch c := c.PacketConn.(type) {
case *net.UDPConn:
n, _, err = c.WriteMsgUDP(b, oob, dst.(*net.UDPAddr))
case *net.IPConn:
n, _, err = c.WriteMsgIP(b, oob, dst.(*net.IPAddr))
default:
return 0, errInvalidConnType
}
if err != nil {
return 0, err
}
return
}
| {
"pile_set_name": "Github"
} |
/****************************************************************************
** @license
** This demo file is part of yFiles for HTML 2.3.
** Copyright (c) 2000-2020 by yWorks GmbH, Vor dem Kreuzberg 28,
** 72070 Tuebingen, Germany. All rights reserved.
**
** yFiles demo files exhibit yFiles for HTML functionalities. Any redistribution
** of demo files in source code or binary form, with or without
** modification, is not permitted.
**
** Owners of a valid software license for a yFiles for HTML version that this
** demo is shipped with are allowed to use the demo source code as basis
** for their own yFiles for HTML powered applications. Use of such programs is
** governed by the rights and conditions as set out in the yFiles for HTML
** license agreement.
**
** THIS SOFTWARE IS PROVIDED ''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 yWorks 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.
**
***************************************************************************/
import {
EdgePathLabelModel,
ExteriorLabelModel,
ExteriorLabelModelPosition,
GraphComponent,
GraphEditorInputMode,
IArrow,
ICommand,
License,
Point,
PolylineEdgeStyle,
Rect,
Size
} from 'yfiles'
import MySimpleLabelStyle from './MySimpleLabelStyle.js'
import MySimpleNodeStyle from './MySimpleNodeStyle.js'
import { bindCommand, showApp } from '../../resources/demo-app.js'
import loadJson from '../../resources/load-json.js'
/** @type {GraphComponent} */
let graphComponent = null
/**
* @param {!object} licenseData
*/
function run(licenseData) {
License.value = licenseData
// initialize the graph component
graphComponent = new GraphComponent('graphComponent')
// initialize the graph
initializeGraph()
// initialize the input mode
graphComponent.inputMode = createEditorMode()
graphComponent.fitGraphBounds()
registerCommands()
// Initialize the demo application's CSS and Javascript for the description
showApp(graphComponent)
}
/**
* Helper method that binds the various commands available in yFiles for HTML to the buttons
* in the demo's toolbar.
*/
function registerCommands() {
bindCommand("button[data-command='FitContent']", ICommand.FIT_GRAPH_BOUNDS, graphComponent)
bindCommand("button[data-command='ZoomIn']", ICommand.INCREASE_ZOOM, graphComponent)
bindCommand("button[data-command='ZoomOut']", ICommand.DECREASE_ZOOM, graphComponent)
bindCommand("button[data-command='ZoomOriginal']", ICommand.ZOOM, graphComponent, 1.0)
}
/**
* Sets a custom NodeStyle instance as a template for newly created
* nodes in the graph.
*/
function initializeGraph() {
const graph = graphComponent.graph
// Create a new style and use it as default node style
graph.nodeDefaults.style = new MySimpleNodeStyle()
// Create a new style and use it as default label style
graph.nodeDefaults.labels.style = new MySimpleLabelStyle()
// Place labels above nodes, with a small gap
const labelModel = new ExteriorLabelModel({ insets: 5 })
graph.nodeDefaults.labels.layoutParameter = labelModel.createParameter(
ExteriorLabelModelPosition.NORTH
)
graph.nodeDefaults.size = new Size(50, 50)
// Create a new style and use it as default edge style
graph.edgeDefaults.style = new PolylineEdgeStyle({
targetArrow: IArrow.DEFAULT
})
graph.edgeDefaults.labels.style = new MySimpleLabelStyle()
// For edge labels, the default is a label that is rotated to match the associated edge segment
// We'll start by creating a model that is similar to the default:
const edgeLabelModel = new EdgePathLabelModel({
autoRotation: true
})
// Finally, we can set this label model as the default for edge labels
graph.edgeDefaults.labels.layoutParameter = edgeLabelModel.createDefaultParameter()
// Create some graph elements with the above defined styles.
createSampleGraph()
}
/**
* Creates the default input mode for the GraphComponent,
* a {@link GraphEditorInputMode}.
* @returns {!GraphEditorInputMode} a new GraphEditorInputMode instance
*/
function createEditorMode() {
return new GraphEditorInputMode({
allowEditLabel: true
})
}
/**
* Creates the initial sample graph.
*/
function createSampleGraph() {
const graph = graphComponent.graph
const node0 = graph.createNode(new Rect(180, 40, 30, 30))
const node1 = graph.createNode(new Rect(260, 50, 30, 30))
const node2 = graph.createNode(new Rect(284, 200, 30, 30))
const node3 = graph.createNode(new Rect(350, 40, 30, 30))
const edge0 = graph.createEdge(node1, node2)
// Add some bends
graph.addBend(edge0, new Point(350, 130))
graph.addBend(edge0, new Point(230, 170))
graph.createEdge(node1, node0)
graph.createEdge(node1, node3)
graph.addLabel(edge0, 'Edge Label')
graph.addLabel(node1, 'Node Label')
}
// Start demo
loadJson().then(run)
| {
"pile_set_name": "Github"
} |
'use strict';
var assert = require('assert');
var config = require('../lib/config');
var helper = require('../helper');
var redis = config.redis;
describe("The 'incr' method", function () {
helper.allTests(function (ip, args) {
describe('using ' + ip, function () {
describe('when connected and a value in Redis', function () {
var client;
var key = 'ABOVE_SAFE_JAVASCRIPT_INTEGER';
var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || 9007199254740991; // Backwards compatible
afterEach(function () {
client.end(true);
});
/*
Number.MAX_SAFE_INTEGER === Math.pow(2, 53) - 1 === 9007199254740991
9007199254740992 -> 9007199254740992
9007199254740993 -> 9007199254740992
9007199254740994 -> 9007199254740994
9007199254740995 -> 9007199254740996
9007199254740996 -> 9007199254740996
9007199254740997 -> 9007199254740996
...
*/
it('count above the safe integers as numbers', function (done) {
client = redis.createClient.apply(null, args);
// Set a value to the maximum safe allowed javascript number (2^53) - 1
client.set(key, MAX_SAFE_INTEGER, helper.isNotError());
client.INCR(key, helper.isNumber(MAX_SAFE_INTEGER + 1));
client.INCR(key, helper.isNumber(MAX_SAFE_INTEGER + 2));
client.INCR(key, helper.isNumber(MAX_SAFE_INTEGER + 3));
client.INCR(key, helper.isNumber(MAX_SAFE_INTEGER + 4));
client.INCR(key, helper.isNumber(MAX_SAFE_INTEGER + 5));
client.INCR(key, function (err, res) {
helper.isNumber(MAX_SAFE_INTEGER + 6)(err, res);
assert.strictEqual(typeof res, 'number');
});
client.INCR(key, helper.isNumber(MAX_SAFE_INTEGER + 7));
client.INCR(key, helper.isNumber(MAX_SAFE_INTEGER + 8));
client.INCR(key, helper.isNumber(MAX_SAFE_INTEGER + 9));
client.INCR(key, helper.isNumber(MAX_SAFE_INTEGER + 10, done));
});
it('count above the safe integers as strings', function (done) {
args[2].string_numbers = true;
client = redis.createClient.apply(null, args);
// Set a value to the maximum safe allowed javascript number (2^53)
client.set(key, MAX_SAFE_INTEGER, helper.isNotError());
client.incr(key, helper.isString('9007199254740992'));
client.incr(key, helper.isString('9007199254740993'));
client.incr(key, helper.isString('9007199254740994'));
client.incr(key, helper.isString('9007199254740995'));
client.incr(key, helper.isString('9007199254740996'));
client.incr(key, function (err, res) {
helper.isString('9007199254740997')(err, res);
assert.strictEqual(typeof res, 'string');
});
client.incr(key, helper.isString('9007199254740998'));
client.incr(key, helper.isString('9007199254740999'));
client.incr(key, helper.isString('9007199254741000'));
client.incr(key, helper.isString('9007199254741001', done));
});
});
});
});
});
| {
"pile_set_name": "Github"
} |
/*M///////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install,
// copy or use the software.
//
//
// License Agreement
// For Open Source Computer Vision Library
//
// Copyright (C) 2000-2008, Intel Corporation, all rights reserved.
// Copyright (C) 2009, Willow Garage Inc., all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistribution's of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistribution's 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.
//
// * The name of the copyright holders may not 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 Intel Corporation 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.
//
//M*/
#ifndef OPENCV_IMGPROC_DETAIL_DISTORTION_MODEL_HPP
#define OPENCV_IMGPROC_DETAIL_DISTORTION_MODEL_HPP
//! @cond IGNORED
namespace cv { namespace detail {
/**
Computes the matrix for the projection onto a tilted image sensor
\param tauX angular parameter rotation around x-axis
\param tauY angular parameter rotation around y-axis
\param matTilt if not NULL returns the matrix
\f[
\vecthreethree{R_{33}(\tau_x, \tau_y)}{0}{-R_{13}((\tau_x, \tau_y)}
{0}{R_{33}(\tau_x, \tau_y)}{-R_{23}(\tau_x, \tau_y)}
{0}{0}{1} R(\tau_x, \tau_y)
\f]
where
\f[
R(\tau_x, \tau_y) =
\vecthreethree{\cos(\tau_y)}{0}{-\sin(\tau_y)}{0}{1}{0}{\sin(\tau_y)}{0}{\cos(\tau_y)}
\vecthreethree{1}{0}{0}{0}{\cos(\tau_x)}{\sin(\tau_x)}{0}{-\sin(\tau_x)}{\cos(\tau_x)} =
\vecthreethree{\cos(\tau_y)}{\sin(\tau_y)\sin(\tau_x)}{-\sin(\tau_y)\cos(\tau_x)}
{0}{\cos(\tau_x)}{\sin(\tau_x)}
{\sin(\tau_y)}{-\cos(\tau_y)\sin(\tau_x)}{\cos(\tau_y)\cos(\tau_x)}.
\f]
\param dMatTiltdTauX if not NULL it returns the derivative of matTilt with
respect to \f$\tau_x\f$.
\param dMatTiltdTauY if not NULL it returns the derivative of matTilt with
respect to \f$\tau_y\f$.
\param invMatTilt if not NULL it returns the inverse of matTilt
**/
template <typename FLOAT>
void computeTiltProjectionMatrix(FLOAT tauX,
FLOAT tauY,
Matx<FLOAT, 3, 3>* matTilt = 0,
Matx<FLOAT, 3, 3>* dMatTiltdTauX = 0,
Matx<FLOAT, 3, 3>* dMatTiltdTauY = 0,
Matx<FLOAT, 3, 3>* invMatTilt = 0)
{
FLOAT cTauX = cos(tauX);
FLOAT sTauX = sin(tauX);
FLOAT cTauY = cos(tauY);
FLOAT sTauY = sin(tauY);
Matx<FLOAT, 3, 3> matRotX = Matx<FLOAT, 3, 3>(1,0,0,0,cTauX,sTauX,0,-sTauX,cTauX);
Matx<FLOAT, 3, 3> matRotY = Matx<FLOAT, 3, 3>(cTauY,0,-sTauY,0,1,0,sTauY,0,cTauY);
Matx<FLOAT, 3, 3> matRotXY = matRotY * matRotX;
Matx<FLOAT, 3, 3> matProjZ = Matx<FLOAT, 3, 3>(matRotXY(2,2),0,-matRotXY(0,2),0,matRotXY(2,2),-matRotXY(1,2),0,0,1);
if (matTilt)
{
// Matrix for trapezoidal distortion of tilted image sensor
*matTilt = matProjZ * matRotXY;
}
if (dMatTiltdTauX)
{
// Derivative with respect to tauX
Matx<FLOAT, 3, 3> dMatRotXYdTauX = matRotY * Matx<FLOAT, 3, 3>(0,0,0,0,-sTauX,cTauX,0,-cTauX,-sTauX);
Matx<FLOAT, 3, 3> dMatProjZdTauX = Matx<FLOAT, 3, 3>(dMatRotXYdTauX(2,2),0,-dMatRotXYdTauX(0,2),
0,dMatRotXYdTauX(2,2),-dMatRotXYdTauX(1,2),0,0,0);
*dMatTiltdTauX = (matProjZ * dMatRotXYdTauX) + (dMatProjZdTauX * matRotXY);
}
if (dMatTiltdTauY)
{
// Derivative with respect to tauY
Matx<FLOAT, 3, 3> dMatRotXYdTauY = Matx<FLOAT, 3, 3>(-sTauY,0,-cTauY,0,0,0,cTauY,0,-sTauY) * matRotX;
Matx<FLOAT, 3, 3> dMatProjZdTauY = Matx<FLOAT, 3, 3>(dMatRotXYdTauY(2,2),0,-dMatRotXYdTauY(0,2),
0,dMatRotXYdTauY(2,2),-dMatRotXYdTauY(1,2),0,0,0);
*dMatTiltdTauY = (matProjZ * dMatRotXYdTauY) + (dMatProjZdTauY * matRotXY);
}
if (invMatTilt)
{
FLOAT inv = 1./matRotXY(2,2);
Matx<FLOAT, 3, 3> invMatProjZ = Matx<FLOAT, 3, 3>(inv,0,inv*matRotXY(0,2),0,inv,inv*matRotXY(1,2),0,0,1);
*invMatTilt = matRotXY.t()*invMatProjZ;
}
}
}} // namespace detail, cv
//! @endcond
#endif // OPENCV_IMGPROC_DETAIL_DISTORTION_MODEL_HPP
| {
"pile_set_name": "Github"
} |
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE OverloadedStrings #-}
module EnAuOckerTextSpec where
import Data.Text (Text)
import qualified Data.Text as T
import Faker hiding (defaultFakerSettings)
import qualified Faker.Address as FA
import Faker.Combinators (listOf)
import qualified Faker.Company as CO
import qualified Faker.Internet as IN
import qualified Faker.Name as NA
import qualified Faker.PhoneNumber as PH
import qualified Faker.Vehicle as VE
import Test.Hspec
import TestImport
isText :: Text -> Bool
isText x = T.length x >= 1
isTexts :: [Text] -> Bool
isTexts xs = and $ map isText xs
locale :: Text
locale = "en-au-ocker"
fakerSettings :: FakerSettings
fakerSettings = setLocale locale defaultFakerSettings
verifyDistributeFakes :: [Fake Text] -> IO [Bool]
verifyDistributeFakes funs = do
let fs :: [IO [Text]] =
map (generateWithSettings fakerSettings) $ map (listOf 100) funs
gs :: [IO Bool] = map (\f -> isTexts <$> f) fs
sequence gs
spec :: Spec
spec = do
describe "TextSpec" $ do
it "validates en-au-ocker locale" $ do
let functions :: [Fake Text] =
[
NA.lastName
, NA.firstName
, IN.domainSuffix
, CO.suffix
, PH.formats
, PH.cellPhoneFormat
, FA.postcode
, FA.city
, FA.stateAbbr
, FA.streetName
, FA.state
, FA.buildingNumber
, FA.streetSuffix
]
bools <- verifyDistributeFakes functions
(and bools) `shouldBe` True
| {
"pile_set_name": "Github"
} |
.ct-label {
fill: #676a6d;
color: #676a6d;
font-size: 1.2rem;
line-height: 1; }
.ct-chart-line .ct-label,
.ct-chart-bar .ct-label {
display: block;
display: -webkit-box;
display: -moz-box;
display: -ms-flexbox;
display: -webkit-flex;
display: flex; }
.ct-chart-pie .ct-label,
.ct-chart-donut .ct-label {
dominant-baseline: central; }
.ct-label.ct-horizontal.ct-start {
-webkit-box-align: flex-end;
-webkit-align-items: flex-end;
-ms-flex-align: flex-end;
align-items: flex-end;
-webkit-box-pack: flex-start;
-webkit-justify-content: flex-start;
-ms-flex-pack: flex-start;
justify-content: flex-start;
text-align: left;
text-anchor: start; }
.ct-label.ct-horizontal.ct-end {
-webkit-box-align: flex-start;
-webkit-align-items: flex-start;
-ms-flex-align: flex-start;
align-items: flex-start;
-webkit-box-pack: flex-start;
-webkit-justify-content: flex-start;
-ms-flex-pack: flex-start;
justify-content: flex-start;
text-align: left;
text-anchor: start; }
.ct-label.ct-vertical.ct-start {
-webkit-box-align: flex-end;
-webkit-align-items: flex-end;
-ms-flex-align: flex-end;
align-items: flex-end;
-webkit-box-pack: flex-end;
-webkit-justify-content: flex-end;
-ms-flex-pack: flex-end;
justify-content: flex-end;
text-align: right;
text-anchor: end; }
.ct-label.ct-vertical.ct-end {
-webkit-box-align: flex-end;
-webkit-align-items: flex-end;
-ms-flex-align: flex-end;
align-items: flex-end;
-webkit-box-pack: flex-start;
-webkit-justify-content: flex-start;
-ms-flex-pack: flex-start;
justify-content: flex-start;
text-align: left;
text-anchor: start; }
.ct-chart-bar .ct-label.ct-horizontal.ct-start {
-webkit-box-align: flex-end;
-webkit-align-items: flex-end;
-ms-flex-align: flex-end;
align-items: flex-end;
-webkit-box-pack: center;
-webkit-justify-content: center;
-ms-flex-pack: center;
justify-content: center;
text-align: center;
text-anchor: start; }
.ct-chart-bar .ct-label.ct-horizontal.ct-end {
-webkit-box-align: flex-start;
-webkit-align-items: flex-start;
-ms-flex-align: flex-start;
align-items: flex-start;
-webkit-box-pack: center;
-webkit-justify-content: center;
-ms-flex-pack: center;
justify-content: center;
text-align: center;
text-anchor: start; }
.ct-chart-bar.ct-horizontal-bars .ct-label.ct-horizontal.ct-start {
-webkit-box-align: flex-end;
-webkit-align-items: flex-end;
-ms-flex-align: flex-end;
align-items: flex-end;
-webkit-box-pack: flex-start;
-webkit-justify-content: flex-start;
-ms-flex-pack: flex-start;
justify-content: flex-start;
text-align: left;
text-anchor: start; }
.ct-chart-bar.ct-horizontal-bars .ct-label.ct-horizontal.ct-end {
-webkit-box-align: flex-start;
-webkit-align-items: flex-start;
-ms-flex-align: flex-start;
align-items: flex-start;
-webkit-box-pack: flex-start;
-webkit-justify-content: flex-start;
-ms-flex-pack: flex-start;
justify-content: flex-start;
text-align: left;
text-anchor: start; }
.ct-chart-bar.ct-horizontal-bars .ct-label.ct-vertical.ct-start {
-webkit-box-align: center;
-webkit-align-items: center;
-ms-flex-align: center;
align-items: center;
-webkit-box-pack: flex-end;
-webkit-justify-content: flex-end;
-ms-flex-pack: flex-end;
justify-content: flex-end;
text-align: right;
text-anchor: end; }
.ct-chart-bar.ct-horizontal-bars .ct-label.ct-vertical.ct-end {
-webkit-box-align: center;
-webkit-align-items: center;
-ms-flex-align: center;
align-items: center;
-webkit-box-pack: flex-start;
-webkit-justify-content: flex-start;
-ms-flex-pack: flex-start;
justify-content: flex-start;
text-align: left;
text-anchor: end; }
.ct-grid {
stroke: rgba(0, 0, 0, 0.2);
stroke-width: 1px;
stroke-dasharray: 2px; }
.ct-grid-background {
fill: none; }
.ct-point {
stroke-width: 8px;
stroke-linecap: round; }
.ct-line {
fill: none;
stroke-width: 3px; }
.ct-area {
stroke: none;
fill-opacity: 0.3; }
.ct-bar {
fill: none;
stroke-width: 10px; }
.ct-slice-donut {
fill: none;
stroke-width: 60px; }
.ct-series-a .ct-point, .ct-series-a .ct-line, .ct-series-a .ct-bar, .ct-series-a .ct-slice-donut {
stroke: #028fd0; }
.ct-series-a .ct-slice-pie, .ct-series-a .ct-area {
fill: #028fd0; }
.ct-series-b .ct-point, .ct-series-b .ct-line, .ct-series-b .ct-bar, .ct-series-b .ct-slice-donut {
stroke: #83c6ea; }
.ct-series-b .ct-slice-pie, .ct-series-b .ct-area {
fill: #83c6ea; }
.ct-series-c .ct-point, .ct-series-c .ct-line, .ct-series-c .ct-bar, .ct-series-c .ct-slice-donut {
stroke: #f4c63d; }
.ct-series-c .ct-slice-pie, .ct-series-c .ct-area {
fill: #f4c63d; }
.ct-series-d .ct-point, .ct-series-d .ct-line, .ct-series-d .ct-bar, .ct-series-d .ct-slice-donut {
stroke: #d17905; }
.ct-series-d .ct-slice-pie, .ct-series-d .ct-area {
fill: #d17905; }
.ct-series-e .ct-point, .ct-series-e .ct-line, .ct-series-e .ct-bar, .ct-series-e .ct-slice-donut {
stroke: #453d3f; }
.ct-series-e .ct-slice-pie, .ct-series-e .ct-area {
fill: #453d3f; }
.ct-series-f .ct-point, .ct-series-f .ct-line, .ct-series-f .ct-bar, .ct-series-f .ct-slice-donut {
stroke: #59922b; }
.ct-series-f .ct-slice-pie, .ct-series-f .ct-area {
fill: #59922b; }
.ct-series-g .ct-point, .ct-series-g .ct-line, .ct-series-g .ct-bar, .ct-series-g .ct-slice-donut {
stroke: #0544d3; }
.ct-series-g .ct-slice-pie, .ct-series-g .ct-area {
fill: #0544d3; }
.ct-series-h .ct-point, .ct-series-h .ct-line, .ct-series-h .ct-bar, .ct-series-h .ct-slice-donut {
stroke: #6b0392; }
.ct-series-h .ct-slice-pie, .ct-series-h .ct-area {
fill: #6b0392; }
.ct-series-i .ct-point, .ct-series-i .ct-line, .ct-series-i .ct-bar, .ct-series-i .ct-slice-donut {
stroke: #f05b4f; }
.ct-series-i .ct-slice-pie, .ct-series-i .ct-area {
fill: #f05b4f; }
.ct-series-j .ct-point, .ct-series-j .ct-line, .ct-series-j .ct-bar, .ct-series-j .ct-slice-donut {
stroke: #dda458; }
.ct-series-j .ct-slice-pie, .ct-series-j .ct-area {
fill: #dda458; }
.ct-series-k .ct-point, .ct-series-k .ct-line, .ct-series-k .ct-bar, .ct-series-k .ct-slice-donut {
stroke: #eacf7d; }
.ct-series-k .ct-slice-pie, .ct-series-k .ct-area {
fill: #eacf7d; }
.ct-series-l .ct-point, .ct-series-l .ct-line, .ct-series-l .ct-bar, .ct-series-l .ct-slice-donut {
stroke: #86797d; }
.ct-series-l .ct-slice-pie, .ct-series-l .ct-area {
fill: #86797d; }
.ct-series-m .ct-point, .ct-series-m .ct-line, .ct-series-m .ct-bar, .ct-series-m .ct-slice-donut {
stroke: #b2c326; }
.ct-series-m .ct-slice-pie, .ct-series-m .ct-area {
fill: #b2c326; }
.ct-series-n .ct-point, .ct-series-n .ct-line, .ct-series-n .ct-bar, .ct-series-n .ct-slice-donut {
stroke: #6188e2; }
.ct-series-n .ct-slice-pie, .ct-series-n .ct-area {
fill: #6188e2; }
.ct-series-o .ct-point, .ct-series-o .ct-line, .ct-series-o .ct-bar, .ct-series-o .ct-slice-donut {
stroke: #a748ca; }
.ct-series-o .ct-slice-pie, .ct-series-o .ct-area {
fill: #a748ca; }
.ct-square {
display: block;
position: relative;
width: 100%; }
.ct-square:before {
display: block;
float: left;
content: "";
width: 0;
height: 0;
padding-bottom: 100%; }
.ct-square:after {
content: "";
display: table;
clear: both; }
.ct-square > svg {
display: block;
position: absolute;
top: 0;
left: 0; }
.ct-minor-second {
display: block;
position: relative;
width: 100%; }
.ct-minor-second:before {
display: block;
float: left;
content: "";
width: 0;
height: 0;
padding-bottom: 93.75%; }
.ct-minor-second:after {
content: "";
display: table;
clear: both; }
.ct-minor-second > svg {
display: block;
position: absolute;
top: 0;
left: 0; }
.ct-major-second {
display: block;
position: relative;
width: 100%; }
.ct-major-second:before {
display: block;
float: left;
content: "";
width: 0;
height: 0;
padding-bottom: 88.8888888889%; }
.ct-major-second:after {
content: "";
display: table;
clear: both; }
.ct-major-second > svg {
display: block;
position: absolute;
top: 0;
left: 0; }
.ct-minor-third {
display: block;
position: relative;
width: 100%; }
.ct-minor-third:before {
display: block;
float: left;
content: "";
width: 0;
height: 0;
padding-bottom: 83.3333333333%; }
.ct-minor-third:after {
content: "";
display: table;
clear: both; }
.ct-minor-third > svg {
display: block;
position: absolute;
top: 0;
left: 0; }
.ct-major-third {
display: block;
position: relative;
width: 100%; }
.ct-major-third:before {
display: block;
float: left;
content: "";
width: 0;
height: 0;
padding-bottom: 80%; }
.ct-major-third:after {
content: "";
display: table;
clear: both; }
.ct-major-third > svg {
display: block;
position: absolute;
top: 0;
left: 0; }
.ct-perfect-fourth {
display: block;
position: relative;
width: 100%; }
.ct-perfect-fourth:before {
display: block;
float: left;
content: "";
width: 0;
height: 0;
padding-bottom: 75%; }
.ct-perfect-fourth:after {
content: "";
display: table;
clear: both; }
.ct-perfect-fourth > svg {
display: block;
position: absolute;
top: 0;
left: 0; }
.ct-perfect-fifth {
display: block;
position: relative;
width: 100%; }
.ct-perfect-fifth:before {
display: block;
float: left;
content: "";
width: 0;
height: 0;
padding-bottom: 66.6666666667%; }
.ct-perfect-fifth:after {
content: "";
display: table;
clear: both; }
.ct-perfect-fifth > svg {
display: block;
position: absolute;
top: 0;
left: 0; }
.ct-minor-sixth {
display: block;
position: relative;
width: 100%; }
.ct-minor-sixth:before {
display: block;
float: left;
content: "";
width: 0;
height: 0;
padding-bottom: 62.5%; }
.ct-minor-sixth:after {
content: "";
display: table;
clear: both; }
.ct-minor-sixth > svg {
display: block;
position: absolute;
top: 0;
left: 0; }
.ct-golden-section {
display: block;
position: relative;
width: 100%; }
.ct-golden-section:before {
display: block;
float: left;
content: "";
width: 0;
height: 0;
padding-bottom: 61.804697157%; }
.ct-golden-section:after {
content: "";
display: table;
clear: both; }
.ct-golden-section > svg {
display: block;
position: absolute;
top: 0;
left: 0; }
.ct-major-sixth {
display: block;
position: relative;
width: 100%; }
.ct-major-sixth:before {
display: block;
float: left;
content: "";
width: 0;
height: 0;
padding-bottom: 60%; }
.ct-major-sixth:after {
content: "";
display: table;
clear: both; }
.ct-major-sixth > svg {
display: block;
position: absolute;
top: 0;
left: 0; }
.ct-minor-seventh {
display: block;
position: relative;
width: 100%; }
.ct-minor-seventh:before {
display: block;
float: left;
content: "";
width: 0;
height: 0;
padding-bottom: 56.25%; }
.ct-minor-seventh:after {
content: "";
display: table;
clear: both; }
.ct-minor-seventh > svg {
display: block;
position: absolute;
top: 0;
left: 0; }
.ct-major-seventh {
display: block;
position: relative;
width: 100%; }
.ct-major-seventh:before {
display: block;
float: left;
content: "";
width: 0;
height: 0;
padding-bottom: 53.3333333333%; }
.ct-major-seventh:after {
content: "";
display: table;
clear: both; }
.ct-major-seventh > svg {
display: block;
position: absolute;
top: 0;
left: 0; }
.ct-octave {
display: block;
position: relative;
width: 100%; }
.ct-octave:before {
display: block;
float: left;
content: "";
width: 0;
height: 0;
padding-bottom: 50%; }
.ct-octave:after {
content: "";
display: table;
clear: both; }
.ct-octave > svg {
display: block;
position: absolute;
top: 0;
left: 0; }
.ct-major-tenth {
display: block;
position: relative;
width: 100%; }
.ct-major-tenth:before {
display: block;
float: left;
content: "";
width: 0;
height: 0;
padding-bottom: 40%; }
.ct-major-tenth:after {
content: "";
display: table;
clear: both; }
.ct-major-tenth > svg {
display: block;
position: absolute;
top: 0;
left: 0; }
.ct-major-eleventh {
display: block;
position: relative;
width: 100%; }
.ct-major-eleventh:before {
display: block;
float: left;
content: "";
width: 0;
height: 0;
padding-bottom: 37.5%; }
.ct-major-eleventh:after {
content: "";
display: table;
clear: both; }
.ct-major-eleventh > svg {
display: block;
position: absolute;
top: 0;
left: 0; }
.ct-major-twelfth {
display: block;
position: relative;
width: 100%; }
.ct-major-twelfth:before {
display: block;
float: left;
content: "";
width: 0;
height: 0;
padding-bottom: 33.3333333333%; }
.ct-major-twelfth:after {
content: "";
display: table;
clear: both; }
.ct-major-twelfth > svg {
display: block;
position: absolute;
top: 0;
left: 0; }
.ct-double-octave {
display: block;
position: relative;
width: 100%; }
.ct-double-octave:before {
display: block;
float: left;
content: "";
width: 0;
height: 0;
padding-bottom: 25%; }
.ct-double-octave:after {
content: "";
display: table;
clear: both; }
.ct-double-octave > svg {
display: block;
position: absolute;
top: 0;
left: 0; }
/*# sourceMappingURL=chartist-custom.css.map */ | {
"pile_set_name": "Github"
} |
package com.example.learn
import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.content.ContextWrapper
import android.graphics.drawable.Drawable
import android.net.Uri
import android.os.Handler
import android.os.Looper
import android.support.v4.app.FragmentActivity
import android.support.v4.content.ContextCompat
import android.util.DisplayMetrics
import android.util.Log
import android.view.View
import android.view.WindowManager
import android.view.animation.AnimationUtils
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import com.bumptech.glide.Glide
import com.bumptech.glide.Priority
import com.bumptech.glide.load.MultiTransformation
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions
import com.bumptech.glide.request.RequestOptions
import jp.wasabeef.glide.transformations.BitmapTransformation
import org.greenrobot.eventbus.EventBus
val dispatcher = Handler(Looper.getMainLooper())
val crossFade = DrawableTransitionOptions().crossFade(200)
val centerCrop = RequestOptions().centerCrop().placeholder(android.R.color.transparent).priority(Priority.NORMAL)
val argbEvaluator = android.animation.ArgbEvaluator()
fun ImageView?.load(res: Any?, transform: List<BitmapTransformation>? = null) {
if (this == null) return
context.activity()?.let {
val requestOptions = if (transform != null) RequestOptions.bitmapTransform(MultiTransformation(transform)) else centerCrop
Glide.with(it).load(when (res) {
is Int?, is String?, is Uri?, is Drawable? -> res
else -> throw IllegalArgumentException("imageView load un support res type")
}).apply(requestOptions).transition(crossFade).into(this)
}
}
fun TextView?.text(res: Any?) {
if (this == null) return
text = when (res) {
is Int -> resString(res)
is String -> res
else -> throw IllegalArgumentException("imageView load un support res type")
}
}
fun Context?.activity(): Activity? {
if (this == null) return null
if (this.javaClass.name.contains("com.android.internal.policy.DecorContext")) {
try {
val field = this.javaClass.getDeclaredField("mPhoneWindow")
field.isAccessible = true
val obj = field.get(this)
val m1 = obj.javaClass.getMethod("getContext")
return (m1.invoke(obj)) as Activity
} catch (e: Exception) {
e.printStackTrace()
}
}
var context = this
while (context is ContextWrapper) {
if (context is Activity) {
return context
}
context = context.baseContext
}
return null
}
fun View?.activity(): Activity? {
if (this == null) return null
return context.activity()
}
fun Activity?.v4(): FragmentActivity? {
if (this == null) return null
return this as? FragmentActivity
}
fun Any.resDrawable(drawableRes: Int, scale: Float = 1F): Drawable =
ContextCompat.getDrawable(App.get(), drawableRes)!!.apply {
setBounds(0, 0, (minimumWidth * scale).toInt(), (minimumHeight * scale).toInt())
}
fun Any.resString(stringRes: Int): String = App.get().getString(stringRes)
fun Any.resDimension(dimensionRes: Int): Int = App.get().resources.getDimensionPixelSize(dimensionRes)
fun Any.dp(dp: Int): Int {
val dm = DisplayMetrics()
(App.get().getSystemService(Context.WINDOW_SERVICE) as WindowManager)
.defaultDisplay.getMetrics(dm)
return (dp * dm.density + 0.5f).toInt()
}
fun Any.screenWidth(): Int {
val dm = DisplayMetrics()
(App.get().getSystemService(Context.WINDOW_SERVICE) as WindowManager)
.defaultDisplay.getMetrics(dm)
return dm.widthPixels
}
fun Any.screenHeight(): Int {
val dm = DisplayMetrics()
(App.get().getSystemService(Context.WINDOW_SERVICE) as WindowManager)
.defaultDisplay.getMetrics(dm)
return dm.heightPixels
}
@SuppressLint("PrivateApi")
fun Any.statusBarHeight(): Int {
var statusHeight = -1
try {
val clazz = Class.forName("com.android.internal.R\$dimen")
val `object` = clazz.newInstance()
val height = Integer.parseInt(clazz.getField("status_bar_height").get(`object`).toString())
statusHeight = App.get().resources.getDimensionPixelSize(height)
} catch (e: Exception) {
e.printStackTrace()
}
return statusHeight
}
fun Any.toast(content: String) {
Toast.makeText(App.get(), content, Toast.LENGTH_SHORT).show()
}
fun Activity.postDelayed1(r: Runnable, delayMillis: Long = 0) {
dispatcher.postDelayed({
if (isFinishing) return@postDelayed
r.run()
}, delayMillis)
}
fun View.postDelayed1(r: Runnable, delayMillis: Long = 0) {
activity()?.postDelayed1(r, delayMillis)
}
fun Any.log(content: String, lv: Int = Log.DEBUG) {
when (lv) {
Log.DEBUG -> Log.d("candy", content)
Log.ERROR -> Log.e("candy", content)
}
}
fun Any.postEvent(a: Int, o: Any? = null, o2: Any? = null, o3: Any? = null) {
when {
o != null && o2 != null && o3 != null -> EventBus.getDefault().post(BusEvent(a, o, o2, o3))
o != null && o2 != null -> EventBus.getDefault().post(BusEvent(a, o, o2))
o != null -> EventBus.getDefault().post(BusEvent(a, o))
else -> EventBus.getDefault().post(BusEvent(a))
}
}
fun View.anim(animRes: Int, visible: Int = View.VISIBLE) {
if (visibility != visible) {
visibility = visible
startAnimation(AnimationUtils.loadAnimation(App.get(), animRes))
}
} | {
"pile_set_name": "Github"
} |
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
namespace AspComet
{
/// <summary>
/// Stores clients in memory. All operations are locked and therefore thread safe when used independently.
/// </summary>
public class InMemoryClientRepository : IClientRepository
{
private static readonly KeyedClientCollection Clients = new KeyedClientCollection();
private readonly object syncRoot = new object();
public IClient GetByID(string clientID)
{
lock (syncRoot)
{
return Clients.Contains(clientID) ? Clients[clientID] : null;
}
}
public void DeleteByID(string clientID)
{
lock (syncRoot)
{
Clients.Remove(clientID);
}
}
public void Insert(IClient client)
{
lock (syncRoot)
{
Clients.Add(client);
}
}
public IEnumerable<IClient> All()
{
lock (syncRoot)
{
return Clients.ToList();
}
}
public IEnumerable<IClient> WhereSubscribedTo(string channel)
{
lock (syncRoot)
{
return Clients.Where(client => client.IsSubscribedTo(channel)).ToList(); // yield within a lock... urgh
}
}
private class KeyedClientCollection : KeyedCollection<string, IClient>
{
protected override string GetKeyForItem(IClient client)
{
return client.ID;
}
}
}
} | {
"pile_set_name": "Github"
} |
{
"CallIdentity_5_d0g0v0" : {
"blocks" : [
{
"blockHeaderPremine" : {
"difficulty" : "0x020000",
"gasLimit" : "0x05f5e100",
"timestamp" : "0x03e8",
"updatePoW" : "1"
},
"transactions" : [
{
"data" : "0x",
"gasLimit" : "0x989680",
"gasPrice" : "0x01",
"nonce" : "0x00",
"r" : "0xc8c5469bcab2d89c9083cecdf26c9d3a9e40597d1d82744bc0e5e582f9dc48a4",
"s" : "0x433eb07127e317522d4e08b89cd3824eee8bf1c75a2871db940e0c54d0dd09d2",
"to" : "0x095e7baea6a6c7c4c2dfeb977efac326af552d87",
"v" : "0x1c",
"value" : "0x0186a0"
}
],
"uncleHeaders" : [
]
}
],
"expect" : [
{
"network" : "Frontier",
"result" : {
"0x095e7baea6a6c7c4c2dfeb977efac326af552d87" : {
"storage" : {
"0x00" : "0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"
}
}
}
},
{
"network" : "Homestead",
"result" : {
"0x095e7baea6a6c7c4c2dfeb977efac326af552d87" : {
"storage" : {
"0x00" : "0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"
}
}
}
},
{
"network" : "EIP150",
"result" : {
"0x095e7baea6a6c7c4c2dfeb977efac326af552d87" : {
"storage" : {
"0x00" : "0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"
}
}
}
},
{
"network" : "EIP158",
"result" : {
"0x095e7baea6a6c7c4c2dfeb977efac326af552d87" : {
"storage" : {
"0x00" : "0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"
}
}
}
},
{
"network" : "Byzantium",
"result" : {
"0x095e7baea6a6c7c4c2dfeb977efac326af552d87" : {
"storage" : {
"0x00" : "0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"
}
}
}
},
{
"network" : "Constantinople",
"result" : {
"0x095e7baea6a6c7c4c2dfeb977efac326af552d87" : {
"storage" : {
"0x00" : "0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"
}
}
}
},
{
"network" : "ConstantinopleFix",
"result" : {
"0x095e7baea6a6c7c4c2dfeb977efac326af552d87" : {
"storage" : {
"0x00" : "0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"
}
}
}
}
],
"genesisBlockHeader" : {
"bloom" : "00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
"coinbase" : "2adc25665018aa1fe0e6bc666dac8fc2697ff9ba",
"difficulty" : "131072",
"extraData" : "0x42",
"gasLimit" : "0x05f5e100",
"gasUsed" : "0",
"mixHash" : "0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421",
"nonce" : "0x0102030405060708",
"number" : "0",
"parentHash" : "0x0000000000000000000000000000000000000000000000000000000000000000",
"receiptTrie" : "0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421",
"stateRoot" : "0xf99eb1626cfa6db435c0836235942d7ccaa935f1ae247d3f1c21e495685f903a",
"timestamp" : "0x03b6",
"transactionsTrie" : "0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421",
"uncleHash" : "0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347"
},
"pre" : {
"0x095e7baea6a6c7c4c2dfeb977efac326af552d87" : {
"balance" : "0x01312d00",
"code" : "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff60005260206000620f4240600060006004610258f1600255600051600055",
"nonce" : "0x00",
"storage" : {
}
},
"0xa94f5374fce5edbc8e2a8697c15331677e6ebf0b" : {
"balance" : "0x0de0b6b3a7640000",
"code" : "",
"nonce" : "0x00",
"storage" : {
}
}
},
"sealEngine" : "NoProof"
}
} | {
"pile_set_name": "Github"
} |
"""
Module containing all HTTP related classes
Use this module (instead of the more specific ones) when importing Headers,
Request and Response outside this module.
"""
from scrapy.http.headers import Headers
from scrapy.http.request import Request
from scrapy.http.request.form import FormRequest
from scrapy.http.request.rpc import XmlRpcRequest
from scrapy.http.request.json_request import JSONRequest
from scrapy.http.response import Response
from scrapy.http.response.html import HtmlResponse
from scrapy.http.response.xml import XmlResponse
from scrapy.http.response.text import TextResponse
| {
"pile_set_name": "Github"
} |
//
// Generated by class-dump 3.5 (64 bit) (Debug version compiled Oct 15 2018 10:31:50).
//
// class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2015 by Steve Nygard.
//
#import <objc/NSObject.h>
#import <CoreCDPUI/CDPStateUIProvider-Protocol.h>
@class CDPEnrollViewController, CDPOption, CDPRecoveryKeySheetController, NSImage, NSString, NSView, NSWindow;
@interface CDPStateBaseUIController : NSObject <CDPStateUIProvider>
{
BOOL _viewBasedUI;
NSWindow *_parentWindow;
NSImage *_displayImage;
CDPEnrollViewController *_cdpViewController;
NSView *_hostView;
NSView *_iCDPContainerView;
NSView *_iCDPContentView;
CDPRecoveryKeySheetController *_recoveryKeyController;
CDPOption *_cdpOptionViewController;
}
- (void).cxx_destruct;
@property(retain, nonatomic) CDPOption *cdpOptionViewController; // @synthesize cdpOptionViewController=_cdpOptionViewController;
@property(retain, nonatomic) CDPRecoveryKeySheetController *recoveryKeyController; // @synthesize recoveryKeyController=_recoveryKeyController;
@property(retain, nonatomic) NSView *iCDPContentView; // @synthesize iCDPContentView=_iCDPContentView;
@property(retain, nonatomic) NSView *iCDPContainerView; // @synthesize iCDPContainerView=_iCDPContainerView;
@property(retain, nonatomic) NSView *hostView; // @synthesize hostView=_hostView;
@property(nonatomic) BOOL viewBasedUI; // @synthesize viewBasedUI=_viewBasedUI;
@property(retain, nonatomic) CDPEnrollViewController *cdpViewController; // @synthesize cdpViewController=_cdpViewController;
@property(retain, nonatomic) NSImage *displayImage; // @synthesize displayImage=_displayImage;
@property(retain, nonatomic) NSWindow *parentWindow; // @synthesize parentWindow=_parentWindow;
- (void)generateNewRecoveryKey:(CDUnknownBlockType)arg1;
- (void)cdpContext:(id)arg1 promptForRecoveryKeyWithValidator:(id)arg2 completion:(CDUnknownBlockType)arg3;
- (void)cdpContext:(id)arg1 presentRecoveryKeyWithValidator:(id)arg2 completion:(CDUnknownBlockType)arg3;
- (void)cdpContext:(id)arg1 promptForInteractiveAuthenticationWithCompletion:(CDUnknownBlockType)arg2;
- (void)cdpContext:(id)arg1 showError:(id)arg2 withDefaultIndex:(long long)arg3 withCompletion:(CDUnknownBlockType)arg4;
- (void)cdpContext:(id)arg1 showError:(id)arg2 withCompletion:(CDUnknownBlockType)arg3;
- (void)cdpContext:(id)arg1 beginRemoteApprovalWithValidator:(id)arg2;
- (void)cdpContext:(id)arg1 promptForAdoptionOfMultipleICSC:(CDUnknownBlockType)arg2;
- (void)cdpContext:(id)arg1 promptForICSCWithIsNumeric:(BOOL)arg2 numericLength:(id)arg3 isRandom:(BOOL)arg4 validator:(id)arg5;
- (void)cdpContext:(id)arg1 promptForRemoteSecretWithDevices:(id)arg2 offeringRemoteApproval:(BOOL)arg3 validator:(id)arg4;
- (void)cdpContext:(id)arg1 promptForLocalSecretWithCompletion:(CDUnknownBlockType)arg2;
- (void)endCDPView;
- (void)changeView:(id)arg1;
- (id)initWithParentWindow:(id)arg1;
// Remaining properties
@property(readonly, copy) NSString *debugDescription;
@property(readonly, copy) NSString *description;
@property(readonly) unsigned long long hash;
@property(readonly) Class superclass;
@end
| {
"pile_set_name": "Github"
} |
Local File Disclosure in xxx.xxxxxxxxxxxx.xxx
Hi,
While testing the media upload thing on `xxx.xxxxxxxxxxxx.xxx`, I found a way to display the content of local file of the server.
## Description
It seems that you use the library `FFmpeg` to deal with videos on your system. FFmpeg is usually use to convert or encode videos. However, in January 2016 a researcher found an important issue in this library when HLS (HTTP Live Streaming) is enable.
Since HLS playlist can handle files as an external resource, it's possible to create a specially crafted video to include local file. After FFmpeg finish his job, the content of the file is displayed in the video.
## PoC
{}
Don't waste your time trying to play the video, it doesn't work :)
## Step to reproduce
1/ Download the attached file `gen_avi.py`
2/ Execute the following command `python3 gen_avi.py /etc/passwd lfi.avi.mp4`
3/ Create a video media in your account here:
https://xxx.xxxxxxxxxxxx.xxx
4/ Upload the video generated with the media uploader at the following url
https://xxx.xxxxxxxxxxxx.xxx
5/ Wait for a minute, the system is generating the thumbnail and probably encoding stuff
6/ Refresh your media list
The content of the local file will be displayed in the thumbnail and the bigger format of the video.
## Risk
Sensitive information leakage (usernames, package installed, service running...).
## Remediation
Update your FFmpeg package or recompile the package and disable HLS.
## See also
https://en.wikipedia.org/wiki/File_inclusion_vulnerability
http://news.softpedia.com/news/zero-day-ffmpeg-vulnerability-lets-anyone-steal-files-from-remote-machines-498880.shtml
https://docs.google.com/presentation/d/1yqWy_aE3dQNXAhW8kxMxRqtP7qMHaIfMzUDpEqFneos/edit
__Special thanks to Neex and Cdl for their public disclosure__
https://hackerone.com/reports/243470
https://hackerone.com/reports/242831
Best regards,
Gwen
| {
"pile_set_name": "Github"
} |
body {
color: #000000;
font-family: 'Segoe UI',Verdana,Arial;
font-size: 0.813em;
font-style: normal;
word-wrap: break-word;
}
/*BEGIN HEADERS*/
.h1, h1 {
color: #3A3E43;
font-family: 'Segoe UI',Verdana,Arial;
font-size: 1.4em;
font-weight: bold;
margin: 0;
}
.h2, h2 {
color: #3A3E43;
font-family: 'Segoe UI',Verdana,Arial;
font-size: 1.2em;
font-weight: bold;
}
.h3, h3 {
color: #3A3E43;
font-family: 'Segoe UI',Verdana,Arial;
font-size: 1.077em;
font-weight: bold;
}
.h4, h4 {
color: #3A3E43;
font-family: 'Segoe UI',Verdana,Arial;
font-size: 1em;
font-weight: bold;
}
h4.subHeading {
margin-bottom: 7px;
margin-top: 13px;
}
/*END HEADERS*/
/*BEGIN LINKS*/
a:link {
color: #00749E;
text-decoration: none;
}
a:hover {
text-decoration: underline;
}
a:visited {
color: #960BB4;
text-decoration: none;
}
a:focus {
outline: 1px dotted #000000;
}
a.libraryLink:link {
text-decoration:none;
border-bottom:1px dotted;
}
/*END LINKS*/
/*BEGIN IMAGES*/
img {
border: 0 none;
}
/*END IMAGES*/
/*BEGIN TABLE*/
.title table {
color: #000000;
font-family: 'Segoe UI',Verdana,Arial;
font-size: 1.077em;
font-style: normal;
}
table {
border-collapse: collapse;
}
table, table th, table td {
border:1px solid #BBBBBB;
}
/*END TABLE*/
/*BEGIN LIST*/
ul {
list-style-type: disc;
margin-left:40px;
padding-left: 0;
}
ul li {
padding-bottom: 10px;
}
ol {
margin-left:40px;
padding-left: 0;
}
ol li {
padding-bottom: 10px;
}
/*END LIST*/
.scriptcode {
position: relative;
padding: 8px 8px 8px 8px;
background: #FFFFFF;
font-size: 12px;
line-height: 125%;
font-weight:normal;
}
.scriptcode pre
{
white-space: pre-wrap !important; /* css-3 */
word-wrap: break-word !important; /* Internet Explorer 5.5+ */
margin:0 0 10px 0 !important;
padding: 10px;
border-top: solid 2px #D0D2D2;
border-bottom: solid 2px #D0D2D2;
border-left: solid 1px #D0D2D2;
border-right: solid 1px #D0D2D2;
}
.scriptcode .title {
color:#E66A38;
font-size: 12px;
font-weight:bold;
margin: 0;
min-height: 23px;
}
.scriptcode .title > span:first-child {
border-left: solid 1px #D0D2D2;
}
.scriptcode .title > span {
padding: 4px 8px 4px 8px;
display: inline-block;
border-top: 1px solid #D0D2D2;
border-right: 1px solid #D0D2D2;
border-collapse: collapse;
text-align: center;
background: white;
}
.scriptcode .title > span.otherTab {
color: #1364C4;
background: #EFF5FF;
cursor: pointer;
}
.scriptcode .hidden {
display: none !important;
visibility: hidden !important;
}
.scriptcode .copyCode {
padding: 8px 2px 0 2px !important;
margin-right: 15px;
position: absolute !important;
right: 0 !important;
top: 17px;
display:block !important;
background: #FFFFFF;
}
.scriptcode .pluginLinkHolder {
display: none;
}
.scriptcode .pluginEditHolderLink {
display: none;
}
.Opera wbr
{
display: inline-block;
}
.IE9 wbr:after
{
content: "\00200B";
}
| {
"pile_set_name": "Github"
} |
#!/bin/bash
#
# start solr in the foreground
set -e
if [[ "$VERBOSE" == "yes" ]]; then
set -x
fi
EXTRA_ARGS=()
# Allow easy setting of the OOM behaviour
# Test with: docker run -p 8983:8983 -it -e OOM=script -e SOLR_JAVA_MEM="-Xms25m -Xmx25m" solr
if [[ -z "${OOM:-}" ]]; then
OOM='none'
fi
case "$OOM" in
'script')
EXTRA_ARGS+=(-a '-XX:OnOutOfMemoryError=/opt/docker-solr/scripts/oom_solr.sh')
;;
'exit')
# recommended
EXTRA_ARGS+=(-a '-XX:+ExitOnOutOfMemoryError')
;;
'crash')
EXTRA_ARGS+=(-a '-XX:+CrashOnOutOfMemoryError')
;;
'none'|'')
;;
*)
echo "Unsupported value in OOM=$OOM"
exit 1
esac
echo "Starting Solr $SOLR_VERSION"
# determine TINI default. If it is already set, assume the user knows what they want
if [[ -z "${TINI:-}" ]]; then
if [[ "$$" == 1 ]]; then
# Default to running tini, so we can run with an OOM script and have 'kill -9' work
TINI=yes
else
# Presumably we're already running under tini through 'docker --init', in which case we
# don't need to run it twice.
# It's also possible that we're run from a wrapper script without exec,
# in which case running tini would not be ideal either.
TINI=no
fi
fi
if [[ "$TINI" == yes ]]; then
exec /usr/bin/tini -- solr -f "$@" "${EXTRA_ARGS[@]}"
elif [[ "$TINI" == no ]]; then
exec solr -f "$@" "${EXTRA_ARGS[@]}"
else
echo "invalid value TINI=$TINI"
exit 1
fi
| {
"pile_set_name": "Github"
} |
# Copyright 1999-2020 Gentoo Authors
# Distributed under the terms of the GNU General Public License v2
EAPI=6
DESCRIPTION="Asynchronous Network Library"
HOMEPAGE="http://asio.sourceforge.net/"
SRC_URI="mirror://sourceforge/${PN}/${PN}/${P}.tar.bz2"
LICENSE="Boost-1.0"
SLOT="0"
KEYWORDS="~alpha amd64 ~arm ~arm64 ~hppa ~ia64 ppc ppc64 sparc x86"
IUSE="doc examples ssl test"
RESTRICT="!test? ( test )"
RDEPEND="dev-libs/boost
ssl? ( dev-libs/openssl:0= )"
DEPEND="${RDEPEND}"
src_prepare() {
default
if ! use test; then
# Don't build nor install any examples or unittests
# since we don't have a script to run them
cat > src/Makefile.in <<-EOF || die
all:
install:
clean:
EOF
fi
}
src_install() {
use doc && local HTML_DOCS=( doc/. )
default
if use examples; then
# Get rid of the object files
emake clean
dodoc -r src/examples
docompress -x /usr/share/doc/${PF}/examples
fi
}
| {
"pile_set_name": "Github"
} |
#
# test for --maximum- my_getopt prefix
#
#
# ulong
#
SET @@session.auto_increment_increment=40960;
SELECT @@session.auto_increment_increment;
#
# ulonglong
#
SET @@session.tmp_table_size=40960;
SELECT @@session.tmp_table_size;
#
# ha_rows
#
SET @@session.max_join_size=40960;
SELECT @@session.max_join_size;
#
# enum
#
SET @@session.use_stat_tables= COMPLEMENTARY;
SELECT @@session.use_stat_tables;
SET @@session.use_stat_tables= PREFERABLY;
SELECT @@session.use_stat_tables;
SET @@session.use_stat_tables= 2;
SELECT @@session.use_stat_tables;
#
# set
#
SET @@session.sql_mode= 'REAL_AS_FLOAT';
SELECT @@session.sql_mode;
SET @@session.sql_mode= 'REAL_AS_FLOAT,ANSI_QUOTES';
SELECT @@session.sql_mode;
SET @@session.sql_mode= 'ANSI_QUOTES,IGNORE_SPACE';
SELECT @@session.sql_mode;
| {
"pile_set_name": "Github"
} |
// Copyright 2013 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package ssh
import (
"crypto"
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/subtle"
"errors"
"io"
"math/big"
"golang.org/x/crypto/curve25519"
)
const (
kexAlgoDH1SHA1 = "diffie-hellman-group1-sha1"
kexAlgoDH14SHA1 = "diffie-hellman-group14-sha1"
kexAlgoECDH256 = "ecdh-sha2-nistp256"
kexAlgoECDH384 = "ecdh-sha2-nistp384"
kexAlgoECDH521 = "ecdh-sha2-nistp521"
kexAlgoCurve25519SHA256 = "curve25519-sha256@libssh.org"
)
// kexResult captures the outcome of a key exchange.
type kexResult struct {
// Session hash. See also RFC 4253, section 8.
H []byte
// Shared secret. See also RFC 4253, section 8.
K []byte
// Host key as hashed into H.
HostKey []byte
// Signature of H.
Signature []byte
// A cryptographic hash function that matches the security
// level of the key exchange algorithm. It is used for
// calculating H, and for deriving keys from H and K.
Hash crypto.Hash
// The session ID, which is the first H computed. This is used
// to derive key material inside the transport.
SessionID []byte
}
// handshakeMagics contains data that is always included in the
// session hash.
type handshakeMagics struct {
clientVersion, serverVersion []byte
clientKexInit, serverKexInit []byte
}
func (m *handshakeMagics) write(w io.Writer) {
writeString(w, m.clientVersion)
writeString(w, m.serverVersion)
writeString(w, m.clientKexInit)
writeString(w, m.serverKexInit)
}
// kexAlgorithm abstracts different key exchange algorithms.
type kexAlgorithm interface {
// Server runs server-side key agreement, signing the result
// with a hostkey.
Server(p packetConn, rand io.Reader, magics *handshakeMagics, s Signer) (*kexResult, error)
// Client runs the client-side key agreement. Caller is
// responsible for verifying the host key signature.
Client(p packetConn, rand io.Reader, magics *handshakeMagics) (*kexResult, error)
}
// dhGroup is a multiplicative group suitable for implementing Diffie-Hellman key agreement.
type dhGroup struct {
g, p, pMinus1 *big.Int
}
func (group *dhGroup) diffieHellman(theirPublic, myPrivate *big.Int) (*big.Int, error) {
if theirPublic.Cmp(bigOne) <= 0 || theirPublic.Cmp(group.pMinus1) >= 0 {
return nil, errors.New("ssh: DH parameter out of bounds")
}
return new(big.Int).Exp(theirPublic, myPrivate, group.p), nil
}
func (group *dhGroup) Client(c packetConn, randSource io.Reader, magics *handshakeMagics) (*kexResult, error) {
hashFunc := crypto.SHA1
var x *big.Int
for {
var err error
if x, err = rand.Int(randSource, group.pMinus1); err != nil {
return nil, err
}
if x.Sign() > 0 {
break
}
}
X := new(big.Int).Exp(group.g, x, group.p)
kexDHInit := kexDHInitMsg{
X: X,
}
if err := c.writePacket(Marshal(&kexDHInit)); err != nil {
return nil, err
}
packet, err := c.readPacket()
if err != nil {
return nil, err
}
var kexDHReply kexDHReplyMsg
if err = Unmarshal(packet, &kexDHReply); err != nil {
return nil, err
}
ki, err := group.diffieHellman(kexDHReply.Y, x)
if err != nil {
return nil, err
}
h := hashFunc.New()
magics.write(h)
writeString(h, kexDHReply.HostKey)
writeInt(h, X)
writeInt(h, kexDHReply.Y)
K := make([]byte, intLength(ki))
marshalInt(K, ki)
h.Write(K)
return &kexResult{
H: h.Sum(nil),
K: K,
HostKey: kexDHReply.HostKey,
Signature: kexDHReply.Signature,
Hash: crypto.SHA1,
}, nil
}
func (group *dhGroup) Server(c packetConn, randSource io.Reader, magics *handshakeMagics, priv Signer) (result *kexResult, err error) {
hashFunc := crypto.SHA1
packet, err := c.readPacket()
if err != nil {
return
}
var kexDHInit kexDHInitMsg
if err = Unmarshal(packet, &kexDHInit); err != nil {
return
}
var y *big.Int
for {
if y, err = rand.Int(randSource, group.pMinus1); err != nil {
return
}
if y.Sign() > 0 {
break
}
}
Y := new(big.Int).Exp(group.g, y, group.p)
ki, err := group.diffieHellman(kexDHInit.X, y)
if err != nil {
return nil, err
}
hostKeyBytes := priv.PublicKey().Marshal()
h := hashFunc.New()
magics.write(h)
writeString(h, hostKeyBytes)
writeInt(h, kexDHInit.X)
writeInt(h, Y)
K := make([]byte, intLength(ki))
marshalInt(K, ki)
h.Write(K)
H := h.Sum(nil)
// H is already a hash, but the hostkey signing will apply its
// own key-specific hash algorithm.
sig, err := signAndMarshal(priv, randSource, H)
if err != nil {
return nil, err
}
kexDHReply := kexDHReplyMsg{
HostKey: hostKeyBytes,
Y: Y,
Signature: sig,
}
packet = Marshal(&kexDHReply)
err = c.writePacket(packet)
return &kexResult{
H: H,
K: K,
HostKey: hostKeyBytes,
Signature: sig,
Hash: crypto.SHA1,
}, nil
}
// ecdh performs Elliptic Curve Diffie-Hellman key exchange as
// described in RFC 5656, section 4.
type ecdh struct {
curve elliptic.Curve
}
func (kex *ecdh) Client(c packetConn, rand io.Reader, magics *handshakeMagics) (*kexResult, error) {
ephKey, err := ecdsa.GenerateKey(kex.curve, rand)
if err != nil {
return nil, err
}
kexInit := kexECDHInitMsg{
ClientPubKey: elliptic.Marshal(kex.curve, ephKey.PublicKey.X, ephKey.PublicKey.Y),
}
serialized := Marshal(&kexInit)
if err := c.writePacket(serialized); err != nil {
return nil, err
}
packet, err := c.readPacket()
if err != nil {
return nil, err
}
var reply kexECDHReplyMsg
if err = Unmarshal(packet, &reply); err != nil {
return nil, err
}
x, y, err := unmarshalECKey(kex.curve, reply.EphemeralPubKey)
if err != nil {
return nil, err
}
// generate shared secret
secret, _ := kex.curve.ScalarMult(x, y, ephKey.D.Bytes())
h := ecHash(kex.curve).New()
magics.write(h)
writeString(h, reply.HostKey)
writeString(h, kexInit.ClientPubKey)
writeString(h, reply.EphemeralPubKey)
K := make([]byte, intLength(secret))
marshalInt(K, secret)
h.Write(K)
return &kexResult{
H: h.Sum(nil),
K: K,
HostKey: reply.HostKey,
Signature: reply.Signature,
Hash: ecHash(kex.curve),
}, nil
}
// unmarshalECKey parses and checks an EC key.
func unmarshalECKey(curve elliptic.Curve, pubkey []byte) (x, y *big.Int, err error) {
x, y = elliptic.Unmarshal(curve, pubkey)
if x == nil {
return nil, nil, errors.New("ssh: elliptic.Unmarshal failure")
}
if !validateECPublicKey(curve, x, y) {
return nil, nil, errors.New("ssh: public key not on curve")
}
return x, y, nil
}
// validateECPublicKey checks that the point is a valid public key for
// the given curve. See [SEC1], 3.2.2
func validateECPublicKey(curve elliptic.Curve, x, y *big.Int) bool {
if x.Sign() == 0 && y.Sign() == 0 {
return false
}
if x.Cmp(curve.Params().P) >= 0 {
return false
}
if y.Cmp(curve.Params().P) >= 0 {
return false
}
if !curve.IsOnCurve(x, y) {
return false
}
// We don't check if N * PubKey == 0, since
//
// - the NIST curves have cofactor = 1, so this is implicit.
// (We don't foresee an implementation that supports non NIST
// curves)
//
// - for ephemeral keys, we don't need to worry about small
// subgroup attacks.
return true
}
func (kex *ecdh) Server(c packetConn, rand io.Reader, magics *handshakeMagics, priv Signer) (result *kexResult, err error) {
packet, err := c.readPacket()
if err != nil {
return nil, err
}
var kexECDHInit kexECDHInitMsg
if err = Unmarshal(packet, &kexECDHInit); err != nil {
return nil, err
}
clientX, clientY, err := unmarshalECKey(kex.curve, kexECDHInit.ClientPubKey)
if err != nil {
return nil, err
}
// We could cache this key across multiple users/multiple
// connection attempts, but the benefit is small. OpenSSH
// generates a new key for each incoming connection.
ephKey, err := ecdsa.GenerateKey(kex.curve, rand)
if err != nil {
return nil, err
}
hostKeyBytes := priv.PublicKey().Marshal()
serializedEphKey := elliptic.Marshal(kex.curve, ephKey.PublicKey.X, ephKey.PublicKey.Y)
// generate shared secret
secret, _ := kex.curve.ScalarMult(clientX, clientY, ephKey.D.Bytes())
h := ecHash(kex.curve).New()
magics.write(h)
writeString(h, hostKeyBytes)
writeString(h, kexECDHInit.ClientPubKey)
writeString(h, serializedEphKey)
K := make([]byte, intLength(secret))
marshalInt(K, secret)
h.Write(K)
H := h.Sum(nil)
// H is already a hash, but the hostkey signing will apply its
// own key-specific hash algorithm.
sig, err := signAndMarshal(priv, rand, H)
if err != nil {
return nil, err
}
reply := kexECDHReplyMsg{
EphemeralPubKey: serializedEphKey,
HostKey: hostKeyBytes,
Signature: sig,
}
serialized := Marshal(&reply)
if err := c.writePacket(serialized); err != nil {
return nil, err
}
return &kexResult{
H: H,
K: K,
HostKey: reply.HostKey,
Signature: sig,
Hash: ecHash(kex.curve),
}, nil
}
var kexAlgoMap = map[string]kexAlgorithm{}
func init() {
// This is the group called diffie-hellman-group1-sha1 in RFC
// 4253 and Oakley Group 2 in RFC 2409.
p, _ := new(big.Int).SetString("FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE649286651ECE65381FFFFFFFFFFFFFFFF", 16)
kexAlgoMap[kexAlgoDH1SHA1] = &dhGroup{
g: new(big.Int).SetInt64(2),
p: p,
pMinus1: new(big.Int).Sub(p, bigOne),
}
// This is the group called diffie-hellman-group14-sha1 in RFC
// 4253 and Oakley Group 14 in RFC 3526.
p, _ = new(big.Int).SetString("FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3DC2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F83655D23DCA3AD961C62F356208552BB9ED529077096966D670C354E4ABC9804F1746C08CA18217C32905E462E36CE3BE39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9DE2BCBF6955817183995497CEA956AE515D2261898FA051015728E5A8AACAA68FFFFFFFFFFFFFFFF", 16)
kexAlgoMap[kexAlgoDH14SHA1] = &dhGroup{
g: new(big.Int).SetInt64(2),
p: p,
pMinus1: new(big.Int).Sub(p, bigOne),
}
kexAlgoMap[kexAlgoECDH521] = &ecdh{elliptic.P521()}
kexAlgoMap[kexAlgoECDH384] = &ecdh{elliptic.P384()}
kexAlgoMap[kexAlgoECDH256] = &ecdh{elliptic.P256()}
kexAlgoMap[kexAlgoCurve25519SHA256] = &curve25519sha256{}
}
// curve25519sha256 implements the curve25519-sha256@libssh.org key
// agreement protocol, as described in
// https://git.libssh.org/projects/libssh.git/tree/doc/curve25519-sha256@libssh.org.txt
type curve25519sha256 struct{}
type curve25519KeyPair struct {
priv [32]byte
pub [32]byte
}
func (kp *curve25519KeyPair) generate(rand io.Reader) error {
if _, err := io.ReadFull(rand, kp.priv[:]); err != nil {
return err
}
curve25519.ScalarBaseMult(&kp.pub, &kp.priv)
return nil
}
// curve25519Zeros is just an array of 32 zero bytes so that we have something
// convenient to compare against in order to reject curve25519 points with the
// wrong order.
var curve25519Zeros [32]byte
func (kex *curve25519sha256) Client(c packetConn, rand io.Reader, magics *handshakeMagics) (*kexResult, error) {
var kp curve25519KeyPair
if err := kp.generate(rand); err != nil {
return nil, err
}
if err := c.writePacket(Marshal(&kexECDHInitMsg{kp.pub[:]})); err != nil {
return nil, err
}
packet, err := c.readPacket()
if err != nil {
return nil, err
}
var reply kexECDHReplyMsg
if err = Unmarshal(packet, &reply); err != nil {
return nil, err
}
if len(reply.EphemeralPubKey) != 32 {
return nil, errors.New("ssh: peer's curve25519 public value has wrong length")
}
var servPub, secret [32]byte
copy(servPub[:], reply.EphemeralPubKey)
curve25519.ScalarMult(&secret, &kp.priv, &servPub)
if subtle.ConstantTimeCompare(secret[:], curve25519Zeros[:]) == 1 {
return nil, errors.New("ssh: peer's curve25519 public value has wrong order")
}
h := crypto.SHA256.New()
magics.write(h)
writeString(h, reply.HostKey)
writeString(h, kp.pub[:])
writeString(h, reply.EphemeralPubKey)
ki := new(big.Int).SetBytes(secret[:])
K := make([]byte, intLength(ki))
marshalInt(K, ki)
h.Write(K)
return &kexResult{
H: h.Sum(nil),
K: K,
HostKey: reply.HostKey,
Signature: reply.Signature,
Hash: crypto.SHA256,
}, nil
}
func (kex *curve25519sha256) Server(c packetConn, rand io.Reader, magics *handshakeMagics, priv Signer) (result *kexResult, err error) {
packet, err := c.readPacket()
if err != nil {
return
}
var kexInit kexECDHInitMsg
if err = Unmarshal(packet, &kexInit); err != nil {
return
}
if len(kexInit.ClientPubKey) != 32 {
return nil, errors.New("ssh: peer's curve25519 public value has wrong length")
}
var kp curve25519KeyPair
if err := kp.generate(rand); err != nil {
return nil, err
}
var clientPub, secret [32]byte
copy(clientPub[:], kexInit.ClientPubKey)
curve25519.ScalarMult(&secret, &kp.priv, &clientPub)
if subtle.ConstantTimeCompare(secret[:], curve25519Zeros[:]) == 1 {
return nil, errors.New("ssh: peer's curve25519 public value has wrong order")
}
hostKeyBytes := priv.PublicKey().Marshal()
h := crypto.SHA256.New()
magics.write(h)
writeString(h, hostKeyBytes)
writeString(h, kexInit.ClientPubKey)
writeString(h, kp.pub[:])
ki := new(big.Int).SetBytes(secret[:])
K := make([]byte, intLength(ki))
marshalInt(K, ki)
h.Write(K)
H := h.Sum(nil)
sig, err := signAndMarshal(priv, rand, H)
if err != nil {
return nil, err
}
reply := kexECDHReplyMsg{
EphemeralPubKey: kp.pub[:],
HostKey: hostKeyBytes,
Signature: sig,
}
if err := c.writePacket(Marshal(&reply)); err != nil {
return nil, err
}
return &kexResult{
H: H,
K: K,
HostKey: hostKeyBytes,
Signature: sig,
Hash: crypto.SHA256,
}, nil
}
| {
"pile_set_name": "Github"
} |
{
union {
...FC
}
}
fragment FC on C {
cText
}
| {
"pile_set_name": "Github"
} |
-- in2.test
--
-- execsql {INSERT INTO a VALUES(NULL, t)}
INSERT INTO a VALUES(NULL, t)
| {
"pile_set_name": "Github"
} |
{
"type": "minecraft:crafting_shapeless",
"ingredients": [
{
"item": "quark:blue_slime_block"
},
{
"item": "minecraft:slime_block"
}
],
"result": {
"item": "quark:cyan_slime_block",
"count": 2
},
"conditions": [
{
"type": "quark:flag",
"flag": "color_slime"
}
]
} | {
"pile_set_name": "Github"
} |
/*
* Copyright (C) 2015 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.ahat;
import com.android.ahat.heapdump.AhatHeap;
import com.android.ahat.heapdump.AhatSnapshot;
import com.android.ahat.heapdump.Site;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
class SitePrinter {
public static void printSite(AhatSnapshot snapshot, Doc doc, Query query, String id, Site site) {
List<Site> path = new ArrayList<Site>();
for (Site parent = site; parent != null; parent = parent.getParent()) {
path.add(parent);
}
Collections.reverse(path);
HeapTable.TableConfig<Site> table = new HeapTable.TableConfig<Site>() {
public String getHeapsDescription() {
return "Reachable Bytes Allocated on Heap";
}
public long getSize(Site element, AhatHeap heap) {
return element.getSize(heap);
}
public List<HeapTable.ValueConfig<Site>> getValueConfigs() {
HeapTable.ValueConfig<Site> value = new HeapTable.ValueConfig<Site>() {
public String getDescription() {
return "Stack Frame";
}
public DocString render(Site element) {
DocString str = new DocString();
if (element.getParent() != null) {
str.append("→ ");
}
return str.append(Summarizer.summarize(element));
}
};
return Collections.singletonList(value);
}
};
HeapTable.render(doc, query, id, table, snapshot, path);
}
}
| {
"pile_set_name": "Github"
} |
package net.chrisrichardson.eventstore.examples.customersandorders.customersservice.web;
import net.chrisrichardson.eventstore.examples.customersandorders.customersservice.backend.CustomerBackendConfiguration;
import org.springframework.boot.autoconfigure.web.HttpMessageConverters;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
@Configuration
@ComponentScan
@Import(CustomerBackendConfiguration.class)
public class CustomerWebConfiguration {
@Bean
public HttpMessageConverters customConverters() {
HttpMessageConverter<?> additional = new MappingJackson2HttpMessageConverter();
return new HttpMessageConverters(additional);
}
}
| {
"pile_set_name": "Github"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.