repo_name stringlengths 6 101 | path stringlengths 4 300 | text stringlengths 7 1.31M |
|---|---|---|
cederberg/rapidcontext | src/plugin/system/files/js/RapidContext.Util.js | /*
* RapidContext <https://www.rapidcontext.com/>
* Copyright (c) 2007-2019 <NAME>. All rights reserved.
*
* This program is free software: you can redistribute it and/or
* modify it under the terms of the BSD license.
*
* 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 RapidContext LICENSE for more details.
*/
// Create default RapidContext object
if (typeof(RapidContext) == "undefined") {
RapidContext = {};
}
/**
* @name RapidContext.Util
* @namespace
* Provides utility functions for basic objects, arrays, DOM nodes and CSS.
* These functions are complementary to what is available in MochiKit and/or
* jQuery.
*/
if (typeof(RapidContext.Util) == "undefined") {
RapidContext.Util = {};
}
// JSON object for browsers missing it
if (typeof(JSON) == "undefined") {
var JSON = {};
}
if (!JSON.parse) {
JSON.parse = MochiKit.Base.evalJSON;
}
if (!JSON.stringify) {
JSON.stringify = MochiKit.Base.serializeJSON;
}
// General utility functions
/**
* Creates a dictionary object from a list of keys and values. Optionally a
* list of key-value pairs can be provided instead. As a third option, a single
* (non-array) value can be assigned to all the keys.
*
* If a key is specified twice, only the last value will be used. Note that
* this function is the reverse of `MochiKit.Base.items()`,
* `MochiKit.Base.keys()` and `MochiKit.Base.values()`.
*
* @param {Array} itemsOrKeys the list of keys or items
* @param {Array} [values] the list of values (optional if key-value
* pairs are specified in first argument)
*
* @return {Object} an object with properties for each key-value pair
*
* @example
* RapidContext.Util.dict(['a','b'], [1, 2])
* ==> { a: 1, b: 2 }
*
* @example
* RapidContext.Util.dict([['a', 1], ['b', 2]])
* ==> { a: 1, b: 2 }
*
* @example
* RapidContext.Util.dict(['a','b'], true)
* ==> { a: true, b: true }
*/
RapidContext.Util.dict = function (itemsOrKeys, values) {
var o = {};
if (!MochiKit.Base.isArrayLike(itemsOrKeys)) {
throw new TypeError("First argument must be array-like");
}
if (MochiKit.Base.isArrayLike(values) && itemsOrKeys.length !== values.length) {
throw new TypeError("Both arrays must be of same length");
}
for (var i = 0; i < itemsOrKeys.length; i++) {
var k = itemsOrKeys[i];
if (k === null || k === undefined) {
throw new TypeError("Key at index " + i + " is null or undefined");
} else if (MochiKit.Base.isArrayLike(k)) {
o[k[0]] = k[1];
} else if (MochiKit.Base.isArrayLike(values)) {
o[k] = values[i];
} else {
o[k] = values;
}
}
return o;
};
/**
* Filters an object by removing a list of keys. A list of key names (or an
* object whose property names will be used as keys) must be specified as an
* argument. A new object containing the source object values for the specified
* keys will be returned. The source object will be modified by removing all
* the specified keys.
*
* @param {Object} src the source object to select and modify
* @param {Array/Object} keys the list of keys to remove, or an
* object with the keys to remove
*
* @return {Object} a new object containing the matching keys and
* values found in the source object
*
* @deprecated This function will be removed in the future.
*
* @example
* var o = { a: 1, b: 2 };
* RapidContext.Util.mask(o, ['a', 'c']);
* ==> { a: 1 } and modifies o to { b: 2 }
*
* @example
* var o = { a: 1, b: 2 };
* RapidContext.Util.mask(o, { a: null, c: null });
* ==> { a: 1 } and modifies o to { b: 2 }
*/
RapidContext.Util.mask = function (src, keys) {
var res = {};
if (!MochiKit.Base.isArrayLike(keys)) {
keys = MochiKit.Base.keys(keys);
}
for (var i = 0; i < keys.length; i++) {
var k = keys[i];
if (k in src) {
res[k] = src[k];
delete src[k];
}
}
return res;
};
/**
* Converts a string to a title-cased string. All word boundaries are replaced
* with a single space and the subsequent character is capitalized.
*
* All underscore ("_"), hyphen ("-") and lower-upper character pairs are
* recognized as word boundaries. Note that this function does not change the
* capitalization of other characters in the string.
*
* @param {String} str the string to convert
*
* @return {String} the converted string
*
* @example
* RapidContext.Util.toTitleCase("a short heading")
* ==> "A Short Heading"
*
* @example
* RapidContext.Util.toTitleCase("camelCase")
* ==> "Camel Case"
*
* @example
* RapidContext.Util.toTitleCase("bounding-box")
* ==> "Bounding Box"
*
* @example
* RapidContext.Util.toTitleCase("UPPER_CASE_VALUE")
* ==> "UPPER CASE VALUE"
*/
RapidContext.Util.toTitleCase = function (str) {
str = MochiKit.Format.strip(str.replace(/[_-]+/g, " "));
str = str.replace(/[a-z][A-Z]/g, function (match) {
return match.charAt(0) + " " + match.charAt(1);
});
str = str.replace(/(^|\s)[a-z]/g, function (match) {
return match.toUpperCase();
});
return str;
};
/**
* Returns the name of a function. If the function is anonymous (i.e. the
* `name` property is `undefined` or an empty string), the value of the
* `displayName` property is returned instead.
*
* @param {Function} func the function to check
*
* @return {String} the function name, or `undefined` if not available
*
* @example
* var o = { test: function () {} };
* RapidContext.Util.registerFunctionNames(o, "o");
* RapidContext.Util.functionName(o.test)
* ==> "o.test"
*
* @see RapidContext.Util.registerFunctionNames
*/
RapidContext.Util.functionName = function (func) {
if (func == null) {
return null;
} else if (func.name != null && func.name != "") {
return func.name;
} else {
return func.displayName;
}
};
/**
* Registers function names for anonymous functions. This is useful when
* debugging code in Firebug or similar tools, as readable stack traces can be
* provided.
*
* This function will add a `displayName` property to all functions without a
* `name` property. Both the `obj` properties and `obj.prototype` properties
* are processed recursively, using the base name as a namespace (i.e.
* `[name].[property]` or `[name].prototype.[property]`).
*
* @param {Object} obj the function or object to process
* @param {String} [name] the function or object (class) name
*
* @example
* var o = { name: "MyObject", test: function () {} };
* RapidContext.Util.registerFunctionNames(o);
* o.test.displayName
* ==> "MyObject.test"
*
* @see RapidContext.Util.functionName
*/
RapidContext.Util.registerFunctionNames = function (obj, name) {
function worker(o, name, stack) {
var isObj = (o != null && typeof(o) === "object");
var isFunc = (typeof(o) === "function");
var isAnon = isFunc && (o.name == null || o.name == "");
var isProto = (o === Object.prototype || o === Function.prototype);
var isNode = isObj && (typeof(o.nodeType) === "number");
var isVisited = (MochiKit.Base.findIdentical(stack, o) >= 0);
if (isFunc && isAnon && !o.hasOwnProperty("displayName")) {
o.displayName = name;
}
if ((isObj || isFunc) && !isProto && !isNode && !isVisited) {
stack.push(o);
for (var prop in o) {
if (o.hasOwnProperty(prop)) {
worker(o[prop], name + "." + prop, stack);
}
}
worker(o.prototype, name + ".prototype", stack);
stack.pop();
}
}
worker(obj, name || obj.name || obj.displayName || obj.NAME || "", []);
};
/**
* Resolves a relative URI to an absolute URI. This function will return
* absolute URI:s directly and traverse any "../" directory paths in the
* specified URI. The base URI provided must be absolute.
*
* @param {String} uri the relative URI to resolve
* @param {String} [base] the absolute base URI, defaults to the
* the current document base URI
*
* @return {String} the resolved absolute URI
*
* @deprecated This function will be removed and/or renamed in the future.
* Better solutions for handling URL:s is to use a URL-parsing library such
* as URL.js.
*/
RapidContext.Util.resolveURI = function (uri, base) {
base = base || document.baseURI || document.getElementsByTagName("base")[0].href;
if (uri.indexOf(":") > 0) {
return uri;
} else if (uri.indexOf("#") == 0) {
var pos = base.lastIndexOf("#");
if (pos >= 0) {
base = base.substring(0, pos);
}
return base + uri;
} else if (uri.indexOf("/") == 0) {
var pos = base.indexOf("/", base.indexOf("://") + 3);
base = base.substring(0, pos);
return base + uri;
} else if (uri.indexOf("../") == 0) {
var pos = base.lastIndexOf("/");
base = base.substring(0, pos);
uri = uri.substring(3);
return RapidContext.Util.resolveURI(uri, base);
} else {
var pos = base.lastIndexOf("/");
base = base.substring(0, pos + 1);
return base + uri;
}
};
// DOM utility functions
RapidContext.Util.NS = {
XHTML: "http://www.w3.org/1999/xhtml",
XLINK: "http://www.w3.org/1999/xlink",
SVG: "http://www.w3.org/2000/svg",
XUL: "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"
};
RapidContext.Util.NS.HTML = [undefined, null, '', RapidContext.Util.NS.XHTML];
/**
* Returns `true` if the specified object looks like a DOM node. Otherwise,
* `false` will be returned. Any non-null object with a `nodeType` > 0 will be
* considered a DOM node by this function.
*
* @param {Object} obj the object to check
*
* @return {Boolean} `true` if the object looks like a DOM node, or
* `false` otherwise
*/
RapidContext.Util.isDOM = function (obj) {
return obj != null &&
typeof(obj.nodeType) === "number" &&
obj.nodeType > 0;
};
/**
* Returns `true` if the specified object looks like an HTML or XHTML DOM node.
* Otherwise, `false` will be returned. Any non-null object with a
* `nodeType` > 0 will be considered a DOM node, but only those with a matching
* `namespaceURI` will be considered HTML DOM nodes.
*
* @param {Object} obj the object to check
*
* @return {Boolean} `true` if the object looks like an HTML DOM node,
* or `false` otherwise
*/
RapidContext.Util.isHTML = function (obj) {
var ns = RapidContext.Util.NS.HTML;
return RapidContext.Util.isDOM(obj) &&
MochiKit.Base.findIdentical(ns, obj.namespaceURI) >= 0;
};
/**
* Returns an array with DOM node attribute name and value pairs. The name and
* value pairs are also stored in arrays with two elements.
*
* @param {Object} node the HTML DOM node
*
* @return {Array} an array containing attribute name and value
* pairs (as arrays)
*/
RapidContext.Util.attributeArray = function (node) {
var res = [];
node = MochiKit.DOM.getElement(node);
for (var i = 0; node != null && i < node.attributes.length; i++) {
var a = node.attributes[i];
res.push([a.name, a.value]);
}
return res;
};
/**
* Returns an immediate child node from a parent DOM node. If a numeric index
* is provided, the index will be range checked and any matching child DOM
* node will be returned. Otherwise, the DOM tree is traversed to find the
* immediate child that corresponds to the specified node.
*
* @param {Node} parent the parent HTML DOM node
* @param {Number/Node} indexOrNode the child index or a descendant node
*
* @return {Node} the child HTML DOM node, or
* `null` if no matching node was found
*
* @example
* var child = RapidContext.Util.childNode(parent, 2);
* ==> parent.childNodes[2] or null
*
* @example
* var child = RapidContext.Util.childNode(node, evt.target());
* ==> child DOM node if descendant or null otherwise
*/
RapidContext.Util.childNode = function (parent, indexOrNode) {
parent = MochiKit.DOM.getElement(parent);
if (typeof(indexOrNode) == "number") {
if (indexOrNode < 0 || indexOrNode >= parent.childNodes.length) {
return null;
} else {
return parent.childNodes[indexOrNode];
}
} else {
var node = MochiKit.DOM.getElement(indexOrNode);
while (node != null && node !== parent && node.parentNode !== parent) {
node = node.parentNode;
}
return (node == null || node === parent) ? null : node;
}
};
/**
* Creates a DOM node with a namespace.
*
* @param {String} ns the DOM namespace
* @param {String} tag the DOM tag name
* @param {Object} [attrs] the node attributes, or null for none
* @param {Object} [...] the nodes or text to add as children
*
* @return {Object} the DOM node created
*
* @example
* RapidContext.Util.createDOMExt("http://www.w3.org/2000/svg", "g");
* ==> an SVG <g> element
*/
RapidContext.Util.createDOMExt = function (ns, tag, attrs/*, ...*/) {
var doc = MochiKit.DOM.currentDocument();
var node = (ns) ? doc.createElementNS(ns, tag) : doc.createElement(tag);
MochiKit.DOM.updateNodeAttributes(node, attrs);
var children = MochiKit.Base.extend([], arguments, 3);
MochiKit.DOM.appendChildNodes(node, children);
return node;
};
/**
* Creates a DOM text node from the specified text. This is a convenience
* function for `currentDocument().createTextNode`, in order to be compatible
* with the `withDocument()` function.
*
* @param {String} text the text content
*
* @return {Object} the DOM text node created
*/
RapidContext.Util.createTextNode = function (text) {
return MochiKit.DOM.currentDocument().createTextNode(text);
};
/**
* Returns a function for creating a specific kind of DOM nodes. The returned
* function will optionally require a sequence of non-null arguments that will
* be added as attributes to the node creation. The returned function will
* otherwise work similar to the `createDOMExt()` function, taking attributes
* and child nodes.
*
* @param {String} ns the DOM namespace, or `null` for HTML
* @param {String} tag the DOM tag name
* @param {Array} [args] the array with required arguments, or `null` for no
* required arguments
* @param {Object} [attrs] the default node attributes, or `null` for none
* @param {Object} [...] the default nodes or text to add as children
*
* @return {Function} the function that creates the DOM nodes
*/
RapidContext.Util.createDOMFuncExt = function (ns, tag, args, attrs/*, ...*/) {
args = args || [];
attrs = attrs || {};
var children = MochiKit.Base.extend([], arguments, 4);
return function (/*arg1, ..., argN, attrs, ...*/) {
var myAttrs = MochiKit.Base.update({}, attrs);
for (var pos = 0; pos < args.length; pos++) {
if (arguments[pos] == null) {
throw new Error("Argument '" + args[pos] + "' cannot be null");
}
myAttrs[args[pos]] = arguments[pos];
}
MochiKit.Base.update(myAttrs, arguments[args.length]);
var myChildren = MochiKit.Base.extend([], children);
MochiKit.Base.extend(myChildren, arguments, args.length + 1);
return RapidContext.Util.createDOMExt(ns, tag, myAttrs, myChildren);
}
};
/**
* Blurs (unfocuses) a specified DOM node and all relevant child nodes. This
* function will recursively blur all `<a>`, `<button>`, `<input>`,
* `<textarea>` and `<select>` child nodes found.
*
* @param {Object} node the HTML DOM node
*/
RapidContext.Util.blurAll = function (node) {
node.blur();
var tags = ["A", "BUTTON", "INPUT", "TEXTAREA", "SELECT"];
for (var i = 0; i < tags.length; i++) {
var nodes = node.getElementsByTagName(tags[i]);
for (var j = 0; j < nodes.length; j++) {
nodes[j].blur();
}
}
};
/**
* Registers algebraic constraints for the element width, height and/or aspect
* ratio. The constraints may either be fixed numeric values, functions or
* algebraic formulas (in a string).
*
* The formulas will be converted to JavaScript functions, replacing any "%"
* character with a reference to the corresponding parent dimension value (i.e.
* the parent element width, height or aspect ratio as a percentage). It is
* also possible to directly reference the parent values as `w` or `h`.
*
* Constraint functions must take two arguments (parent width and height) and
* return a number. The returned number is set as the new element width or
* height (in pixels). Any returned value will also be bounded by the parent
* element size to avoid calculation errors.
*
* @param {Object} node the HTML DOM node
* @param {Number/Function/String} [width] the width constraint
* @param {Number/Function/String} [height] the height constraint
* @param {Number/Function/String} [aspect] the aspect ratio constraint
*
* @see RapidContext.Util.resizeElements
*
* @example
* RapidContext.Util.registerSizeConstraints(node, "50%-20", "100%");
* ==> Sets width to 50%-20 px and height to 100% of parent dimension
*
* @example
* RapidContext.Util.registerSizeConstraints(otherNode, null, null, 1.0);
* ==> Ensures a square aspect ratio
*
* @example
* RapidContext.Util.resizeElements(node, otherNode);
* ==> Evaluates the size constraints for both nodes
*/
RapidContext.Util.registerSizeConstraints = function (node, width, height, aspect) {
node = MochiKit.DOM.getElement(node);
var sc = node.sizeConstraints = { w: null, h: null, a: null };
if (typeof(width) == "number") {
sc.w = function (w, h) { return width; }
} else if (typeof(width) == "function") {
sc.w = width;
} else if (typeof(width) == "string") {
var code = "return " + width.replace(/%/g, "*0.01*w") + ";";
sc.w = new Function("w", "h", code);
}
if (typeof(height) == "number") {
sc.h = function (w, h) { return height; }
} else if (typeof(height) == "function") {
sc.h = height;
} else if (typeof(height) == "string") {
var code = "return " + height.replace(/%/g, "*0.01*h") + ";";
sc.h = new Function("w", "h", code);
}
if (typeof(aspect) == "number") {
sc.a = function (w, h) { return aspect; }
} else if (typeof(aspect) == "function") {
sc.a = aspect;
} else if (typeof(aspect) == "string") {
var code = "return " + aspect.replace(/%/g, "*0.01*w/h") + ";";
sc.a = new Function("w", "h", code);
}
};
/**
* Resizes one or more DOM nodes using their registered size constraints and
* their parent element sizes. The resize operation will only modify those
* elements that have constraints, but will perform a depth-first recursion
* over all element child nodes as well.
*
* Partial constraints are accepted, in which case only the width or the height
* is modified. Aspect ratio constraints are applied after the width and height
* constraints. The result will always be bounded by the parent element width
* or height.
*
* The recursive descent of this function can be limited by adding a
* `resizeContent` function to a DOM node. Such a function will be called to
* handle all subnode resizing, making it possible to limit or omitting the
* DOM tree traversal.
*
* @param {Object} [...] the HTML DOM nodes to resize
*
* @see RapidContext.Util.registerSizeConstraints
*
* @example
* RapidContext.Util.resizeElements(node);
* ==> Evaluates the size constraints for a node and all child nodes
*
* @example
* elem.resizeContent = MochiKit.Base.noop;
* ==> Assigns a no-op child resize handler to elem
*/
RapidContext.Util.resizeElements = function (/* ... */) {
var args = MochiKit.Base.flattenArray(arguments);
for (var i = 0; i < args.length; i++) {
var node = MochiKit.DOM.getElement(args[i]);
if (node != null && node.nodeType === 1 && // Node.ELEMENT_NODE
node.parentNode != null && node.sizeConstraints != null) {
var ref = { w: node.parentNode.w, h: node.parentNode.h };
if (ref.w == null && ref.h == null) {
ref = MochiKit.Style.getElementDimensions(node.parentNode, true);
}
var dim = RapidContext.Util._evalConstraints(node.sizeConstraints, ref);
MochiKit.Style.setElementDimensions(node, dim);
node.w = dim.w;
node.h = dim.h;
}
if (node != null && typeof(node.resizeContent) == "function") {
try {
node.resizeContent();
} catch (e) {
RapidContext.Log.error("Error in resizeContent()", node, e);
}
} else {
node = node.firstChild;
while (node != null) {
if (node.nodeType === 1) { // Node.ELEMENT_NODE
RapidContext.Util.resizeElements(node);
}
node = node.nextSibling;
}
}
}
};
/**
* Evaluates the size constraint functions with a refeence dimension
* object. This is an internal function used to encapsulate the
* function calls and provide logging on errors.
*
* @param {Object} sc the size constraints object
* @param {Object} ref the MochiKit.Style.Dimensions maximum
* reference values
*
* @return {Object} the MochiKit.Style.Dimensions with evaluated size
* constraint values (some may be null)
*/
RapidContext.Util._evalConstraints = function (sc, ref) {
var log = MochiKit.Logging.logError;
var w, h, a;
if (typeof(sc.w) == "function") {
try {
w = Math.max(0, Math.min(ref.w, sc.w(ref.w, ref.h)));
} catch (e) {
log("Error evaluating width size constraint; " +
"w: " + ref.w + ", h: " + ref.h, e);
}
}
if (typeof(sc.h) == "function") {
try {
h = Math.max(0, Math.min(ref.h, sc.h(ref.w, ref.h)));
} catch (e) {
log("Error evaluating height size constraint; " +
"w: " + ref.w + ", h: " + ref.h, e);
}
}
if (typeof(sc.a) == "function") {
try {
a = sc.a(ref.w, ref.h);
w = w || ref.w;
h = h || ref.h;
if (h * a > ref.w) {
h = ref.w / a;
}
if (w / a > ref.h) {
w = ref.h * a;
}
if (w > h * a) {
w = h * a;
} else {
h = w / a;
}
} catch (e) {
log("Error evaluating aspect size constraint; " +
"w: " + ref.w + ", h: " + ref.h, e);
}
}
if (w != null) {
w = Math.floor(w);
}
if (h != null) {
h = Math.floor(h);
}
return new MochiKit.Style.Dimensions(w, h);
};
|
abdullahemad12/Cranberry-RayTracer | src/datastructures/OctaTree/BoundingBox.java | <reponame>abdullahemad12/Cranberry-RayTracer
package datastructures.OctaTree;
import model.graphics.object.Box;
import model.graphics.object.Shape;
import java.util.List;
class BoundingBox extends Box {
private BoundingBox[] boundingBoxes;
private List<Shape> shapes; // NonNull for leaf Boxes only
/**
* Creates the tree for the OcTree with this as the head
* @param box A box representing the dimensions of this BoundingBox
* @param shapes the shapes bounded by this bounding box
*/
BoundingBox(Box box, List<Shape> shapes) {
super(box.getA(), box.getB());
this.shapes = shapes;
boundingBoxes = new BoundingBox[8];
}
void setBoundingBoxes(BoundingBox[] boundingBoxes){
this.boundingBoxes = boundingBoxes;
}
BoundingBox[] getBoundingBoxes() { return this.boundingBoxes; }
List<Shape> getShapes() {
return this.shapes;
}
}
|
tangzhankun/Narwhal | src/main/java/org/apache/hadoop/yarn/applications/narwhal/service/ContainerLauncher.java | package org.apache.hadoop.yarn.applications.narwhal.service;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.DataOutputBuffer;
import org.apache.hadoop.security.Credentials;
import org.apache.hadoop.security.UserGroupInformation;
import org.apache.hadoop.yarn.api.ApplicationConstants;
import org.apache.hadoop.yarn.api.records.*;
import org.apache.hadoop.yarn.applications.narwhal.NAppMaster;
import org.apache.hadoop.yarn.applications.narwhal.event.*;
import org.apache.hadoop.yarn.applications.narwhal.task.ExecutorID;
import org.apache.hadoop.yarn.applications.narwhal.task.TaskId;
import org.apache.hadoop.yarn.client.api.async.NMClientAsync;
import org.apache.hadoop.yarn.conf.YarnConfiguration;
import org.apache.hadoop.yarn.event.AbstractEvent;
import org.apache.hadoop.yarn.event.EventHandler;
import org.apache.hadoop.yarn.exceptions.YarnRuntimeException;
import org.apache.hadoop.yarn.util.ConverterUtils;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.*;
import java.util.Vector;
import java.util.concurrent.ConcurrentHashMap;
/**
*
*/
public class ContainerLauncher extends EventLoop implements EventHandler<ContainerLauncherEvent> {
private static final Log LOG = LogFactory.getLog(ContainerLauncher.class);
private NMClientAsync nmClientAsync;
private NMClientAsync.CallbackHandler launchListener;
private ConcurrentHashMap<ContainerId, ExecutorID> scheduledContainers =
new ConcurrentHashMap<>();
public ContainerLauncher(NAppMaster.AppContext context) {
super(context);
}
//TODO
public void stopContainers() {
}
@Override
public void stop() {
stopContainers();
nmClientAsync.stop();
}
@Override
public void handle(ContainerLauncherEvent containerLauncherEvent) {
try {
eventQueue.put(containerLauncherEvent);
} catch (InterruptedException e) {
throw new YarnRuntimeException(e);
}
}
@Override
public void processEvent(AbstractEvent event) {
ContainerLauncherEvent CLEvent = (ContainerLauncherEvent)event;
LOG.info("Processing the event " + CLEvent);
switch (CLEvent.getType()) {
case CONATAINERLAUNCHER_LAUNCH:
launchContainer(CLEvent);
break;
case CONTAINERLAUNCHER_COMPLETED:
completeContainer();
break;
case CONTAINERLAUNCHER_CLEANUP:
cleanupContainer();
break;
}
}
@Override
public void startClientAsync() {
createNMClientAsync().start();
}
protected NMClientAsync createNMClientAsync() {
launchListener = new NMCallback();
nmClientAsync = NMClientAsync.createNMClientAsync(launchListener);
nmClientAsync.init(context.getConf());
return nmClientAsync;
}
private ContainerLaunchContext buildContainerContext(String cmd, String image,
boolean useDocker, Map<String, LocalResource> localResources ) {
ContainerLaunchContext ctx = null;
try {
//env
Map<String, String> env = new HashedMap();
if (useDocker) {
env.put("YARN_CONTAINER_RUNTIME_TYPE", "docker");
env.put("YARN_CONTAINER_RUNTIME_DOCKER_IMAGE", image);
}
List<String> commands = new ArrayList<>();
//cmd
Vector<CharSequence> vargs = new Vector<>(5);
vargs.add("(" + cmd + ")");
vargs.add("1>" + ApplicationConstants.LOG_DIR_EXPANSION_VAR + "/stdout");
vargs.add("2>" + ApplicationConstants.LOG_DIR_EXPANSION_VAR + "/stderr");
StringBuilder command = new StringBuilder();
for (CharSequence str : vargs) {
command.append(str).append(" ");
}
commands.add(command.toString());
//tokens
Credentials credentials = UserGroupInformation.getCurrentUser().getCredentials();
DataOutputBuffer dob = new DataOutputBuffer();
credentials.writeTokenStorageToStream(dob);
ByteBuffer allTokens = ByteBuffer.wrap(dob.getData(), 0, dob.getLength());
//ctx
ctx = ContainerLaunchContext.newInstance(
localResources, env, commands, null, allTokens.duplicate(), null
);
} catch (IOException e) {
e.printStackTrace();
}
return ctx;
}
private void launchContainer(ContainerLauncherEvent event) {
LOG.info("start container");
String userCmd = event.getUserCmd();
ContainerLaunchContext ctx = null;
if (event.getId() instanceof TaskId) {
ctx = buildContainerContext(userCmd, event.getDockerImageName(), true, null);
} else {
Map<String, LocalResource> localResources = new HashMap<>();
String resourceFileName = event.getResourceFileName();
String resourcePath = event.getResourceFilePath();
if (resourcePath != "") {
FileSystem fs = null;
try {
fs = FileSystem.get(new YarnConfiguration());
Path dst = new Path(fs.getHomeDirectory(), resourcePath);
boolean exists = fs.exists(dst);
if(exists) {
FileStatus scFileStatus = fs.getFileStatus(dst);
LocalResource scRsrc = LocalResource.newInstance(
ConverterUtils.getYarnUrlFromURI(dst.toUri()), LocalResourceType.FILE,
LocalResourceVisibility.APPLICATION, scFileStatus.getLen(),
scFileStatus.getModificationTime());
localResources.put(resourceFileName, scRsrc);
}
} catch (IOException e) {
e.printStackTrace();
}
}
ctx = buildContainerContext(userCmd, null, false, localResources);
}
if (ctx == null) {
LOG.info("ContainerLaunchContext is null");
} else {
if (event.getContainer() == null) {
LOG.info("Container is null:" + event.getId());
}
LOG.info(event.getId() + " used container " + event.getContainer().getId());
nmClientAsync.startContainerAsync(event.getContainer(), ctx);
scheduledContainers.put(event.getId().getContainerId(), event.getId());
}
}
private void completeContainer() {
LOG.info("complete container");
}
private void cleanupContainer() {
LOG.info("stop container");
//nmClientAysnc.stopContainerAsync()
}
class NMCallback implements NMClientAsync.CallbackHandler {
private final Log LOG = LogFactory.getLog(NMCallback.class);
@Override
public void onContainerStarted(ContainerId containerId, Map<String, ByteBuffer> map) {
LOG.info("NM - Container: " + containerId + " started");
Iterator<ContainerId> it = scheduledContainers.keySet().iterator();
while (it.hasNext()) {
ContainerId scheduledContainerId = it.next();
if (scheduledContainerId.equals(containerId)) {
ExecutorID executorID = scheduledContainers.get(scheduledContainerId);
//post event to ContainerAllocator to tell it one container has started
ContainerAllocatorEvent event = new ContainerAllocatorEvent(executorID,
ContainerAllocatorEventType.CONTAINERALLOCATOR_CONTAINER_STARTED);
eventHandler.handle(event);
//remove from schedulerContainer list
it.remove();
}
}
}
@Override
public void onContainerStatusReceived(ContainerId containerId, ContainerStatus containerStatus) {
LOG.info("NM - Container: " + containerId + "status received : " + containerStatus);
}
@Override
public void onContainerStopped(ContainerId containerId) {
LOG.info("NM - Container" + containerId + " stopped");
}
@Override
public void onStartContainerError(ContainerId containerId, Throwable throwable) {
LOG.info("NM - start container" + containerId + " encountered error");
}
@Override
public void onGetContainerStatusError(ContainerId containerId, Throwable throwable) {
}
@Override
public void onStopContainerError(ContainerId containerId, Throwable throwable) {
LOG.info("NM - stop container" + containerId + " encountered error");
}
}
}
|
intellineers/django-bridger | bridger/notifications/viewsets/viewsets.py | <filename>bridger/notifications/viewsets/viewsets.py
from django.utils import timezone
from rest_framework import filters
from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework.reverse import reverse
from bridger import buttons as bt
from bridger import display as dp
from bridger import viewsets
from bridger.enums import RequestType, WBIcon
from bridger.filters import DjangoFilterBackend
from bridger.notifications.models import Notification
from bridger.notifications.serializers import NotificationModelSerializer
from .buttons import NotificationButtonConfig
from .display import NotificationDisplayConfig
from .endpoint import NotificationEndpointConfig
from .title import NotificationTitleConfig
class NotificationModelViewSet(viewsets.ModelViewSet):
queryset = Notification.objects.all()
serializer_class = NotificationModelSerializer
filter_backends = (
filters.OrderingFilter,
DjangoFilterBackend,
filters.SearchFilter,
)
ordering_fields = ("timestamp_created",)
ordering = ("-timestamp_created",)
search_fields = ("title", "message")
title_config_class = NotificationTitleConfig
display_config_class = NotificationDisplayConfig
endpoint_config_class = NotificationEndpointConfig
button_config_class = NotificationButtonConfig
def retrieve(self, request, *args, **kwargs):
obj = self.get_object()
if not obj.timestamp_read:
obj.timestamp_read = timezone.now()
obj.save()
return super().retrieve(request, *args, **kwargs)
def list(self, request, *args, **kwargs):
self.get_queryset().filter(timestamp_received__isnull=True).update(timestamp_received=timezone.now())
return super().list(request, *args, **kwargs)
def get_queryset(self):
return super().get_queryset().filter(recipient=self.request.user)
@action(methods=["POST"], detail=False)
def mark_all_as_read(self, request, pk=None):
Notification.objects.filter(timestamp_read__isnull=True).update(timestamp_read=timezone.now())
return Response({})
@action(methods=["POST"], detail=False)
def delete_all_read(self, request, pk=None):
Notification.objects.filter(timestamp_read__isnull=False).delete()
return Response({})
|
TomasHofman/galleon | core/src/main/java/org/jboss/galleon/util/formatparser/FormatErrors.java | <filename>core/src/main/java/org/jboss/galleon/util/formatparser/FormatErrors.java<gh_stars>0
/*
* Copyright 2016-2018 Red Hat, Inc. and/or its affiliates
* and other contributors as indicated by the @author tags.
*
* 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 org.jboss.galleon.util.formatparser;
/**
* @author <NAME>
*
*/
public class FormatErrors {
public static String formatExprDoesNotSupportTypeParam(String name) {
return "Format " + name + " does not support type parameters";
}
public static String parsingFailed(String str, int errorIndex, ParsingFormat format, int formatStartIndex) {
final StringBuilder buf = new StringBuilder().append("Parsing of '").append(str).append("' failed");
if(str.length() != errorIndex) {
buf.append(" at index ").append(errorIndex);
}
return buf.append(" while parsing format ").append(format).append(" started on index ").append(formatStartIndex).toString();
}
public static String formatEndedPrematurely(ParsingFormat format) {
return new StringBuilder()
.append("Format ").append(format).append(" has ended prematurely")
.toString();
}
public static String formatIncomplete(ParsingFormat format) {
return new StringBuilder()
.append("Format ").append(format).append(" is incomplete")
.toString();
}
public static String unexpectedStartingCharacter(ParsingFormat format, char expected, char actual) {
return new StringBuilder()
.append("Format ").append(format).append(" expects '").append(expected).append("' as it's starting character, not '").append(actual).append("'")
.toString();
}
public static String unexpectedChildFormat(ParsingFormat parent, ParsingFormat child) {
return "Format " + parent + " does not expect format " + child + " as a child.";
}
public static String unexpectedCompositeFormatElement(ParsingFormat format, Object elem) {
if(elem == null) {
return "Unexpected attribute for " + format;
}
return "Format " + format + " does not accept attribute " + elem;
}
}
|
isabella232/egle | server/public/js/directives/AskMobilityDirective.js | <reponame>isabella232/egle
/*
* The copyright in this software is being made available under MIT License
* MIT License, included below. This software may be subject to other third
* party and contributor rights, including patent rights, and no such rights
* are granted under this license.
*
* Copyright (c) 2014-2016, Universite catholique de Louvain (UCL), Belgium
* Copyright (c) 2014-2016, Professor <NAME>
* Copyright (c) 2014-2016, <NAME>
* All rights reserved.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
angular.module('AskMobilityDirective', []).directive('askmobility', function(gettextCatalog, $ocLazyLoad, $injector, $rootScope) {
return {
restrict: 'A',
templateUrl: 'templates/dashboard/asks/directives/ask_mobility.html',
link: function($scope, $element, $attrs) {
$scope.radio = {
buttons:[{
type: 'motor',
title: gettextCatalog.getString('Motor vehicule'),
value: undefined,
icon: 'mdi-maps-directions-car',
color: '#F06292'
},{
type: 'public',
title: gettextCatalog.getString('Public transports'),
value: undefined,
icon: 'mdi-maps-directions-subway',
color: '#E91E63'
},{
type: 'bike',
title: gettextCatalog.getString('Bike'),
value: undefined,
icon: 'mdi-maps-directions-bike',
color: '#C2185B'
},{
type: 'walk',
title: gettextCatalog.getString('Walking'),
value: undefined,
icon: 'mdi-maps-directions-walk',
color: '#880E4F'
}],
levels: [{
name: '15',
value: '0.25'
},{
name: '30',
value: '0.5'
},{
name: '45',
value: '0.75'
},{
name: '60',
value: '1'
},{
name: '90',
value: '1.5'
}]
};
//Answer
$scope.answer = function(){
var values = [];
for(i = 0; i < $scope.radio.buttons.length; i++) {
if($scope.radio.buttons[i].value !== undefined){
values.push({type:$scope.radio.buttons[i].type, value: $scope.radio.buttons[i].value});
}
}
$scope.$parent.addEntry({type: 'mobility', values: values}, function(){
$scope.$parent.buildDashboard();
});
}
// Reset radio buttons
$scope.reset = function(button){
if(button.clicked){
button.value = undefined;
button.clicked = false;
} else {
button.clicked = true;
}
}
}
}
}); |
firstake/local-barbershop | client/src/index.js | <gh_stars>0
import 'bootstrap/dist/css/bootstrap.min.css';
import React from 'react';
import ReactDOM from 'react-dom';
import {BrowserRouter} from 'react-router-dom';
import {Provider} from 'react-redux';
import {ToastContainer, toast} from 'react-toastify';
import App from './App';
import configureStore from './store';
import {restoreSession, ScrollToTop, checkWebpFeature} from './util';
import './index.scss';
import './fonts/fonts.scss';
const renderApp = (preloadedState) => {
const store = configureStore(preloadedState);
ReactDOM.render(
<Provider store={store}>
<BrowserRouter>
<>
<ToastContainer
autoClose={3000}
hideProgressBar={true}
draggable={false}
/>
<ScrollToTop />
<App />
</>
</BrowserRouter>
</Provider>,
document.getElementById('root'),
);
};
(async () => {
const supportsWebp = await checkWebpFeature('lossy');
if (!supportsWebp) {
document.body.classList.add('no-webp');
}
renderApp(await restoreSession());
})();
export const notify = (message, status = 'error') => toast[status](message);
|
nikita-uvarov/catboost | library/neh/multiclient_ut.cpp | #include "multiclient.h"
#include "rpc.h"
#include "utils.h"
#include <library/unittest/registar.h>
#include <util/generic/list.h>
#include <util/stream/str.h>
#include <util/thread/pool.h>
#include <util/system/mutex.h>
using namespace NNeh;
Y_UNIT_TEST_SUITE(TNehMultiClient) {
class TResponseDelayer: public IThreadPool::IThreadAble {
struct TTmResponse : TIntrusiveListItem<TTmResponse> {
TTmResponse(TInstant time, const IRequestRef& request, TData& data)
: Time(time)
, Request(request)
{
Data.swap(data);
}
TInstant Time;
IRequestRef Request;
TData Data;
};
public:
TResponseDelayer()
: E_(Event::rAuto)
, Shutdown_(false)
{
}
~TResponseDelayer() override {
Stop();
if (!!Thr_) {
Thr_->Join();
}
while (!R_.Empty()) {
delete R_.PopFront();
}
}
void Run() {
Thr_ = SystemThreadPool()->Run(this);
}
void Stop() {
Shutdown_ = true;
E_.Signal();
}
void SendResponseAt(TInstant& at, const IRequestRef& req, TData& data) {
{
TGuard<TMutex> g(M_);
R_.PushBack(new TTmResponse(at, req, data));
}
E_.Signal();
}
private:
void DoExecute() override {
for (;;) {
TInstant tm = TInstant::Max();
TTmResponse* resp = nullptr;
{
TGuard<TMutex> g(M_);
for (TIntrusiveList<TTmResponse>::TIterator it = R_.Begin(); it != R_.End(); ++it) {
if (it->Time < tm) {
tm = it->Time;
resp = &*it;
}
}
}
if (!E_.WaitD(tm)) {
resp->Request->SendReply(resp->Data);
TGuard<TMutex> g(M_);
delete resp;
}
if (Shutdown_) {
break;
}
}
}
private:
TAutoPtr<IThreadPool::IThread> Thr_;
TMutex M_;
TIntrusiveList<TTmResponse> R_;
Event E_;
TAtomicBool Shutdown_;
};
class TServer {
public:
TServer(const TString& response)
: R_(response)
{
D_.Run();
}
void ServeRequest(const IRequestRef& req) {
TData res(~R_, ~R_ + +R_);
if (req->Data().StartsWith("delay ")) {
TStringBuf delay = req->Data();
delay.Skip(6);
TInstant respTime = TDuration::MilliSeconds(FromString<size_t>(delay.Before('\n'))).ToDeadLine();
D_.SendResponseAt(respTime, req, res);
} else {
req->SendReply(res);
}
}
private:
TString R_;
TResponseDelayer D_;
};
class TResponsesDispatcher: public IThreadPool::IThreadAble {
public:
TResponsesDispatcher(IMultiClient& mc)
: MC_(mc)
{
}
~TResponsesDispatcher() override {
Stop();
}
void Run() {
Thr_ = SystemThreadPool()->Run(this);
}
void Stop() {
MC_.Interrupt();
if (!!Thr_) {
Thr_->Join();
}
}
private:
void DoExecute() override {
try {
size_t evNum = 0;
IMultiClient::TEvent ev;
while (MC_.Wait(ev)) {
Cdbg << "ev.Type = " << int(ev.Type) << Endl;
if (ev.Type == IMultiClient::TEvent::Response) {
TResponseRef resp = ev.Hndl->Get();
if (!!resp) {
Cdbg << "Request = " << resp->Request.Addr << ": " << resp->Request.Data << Endl;
if (resp->IsError()) {
Cdbg << "ErrorResponse = " << resp->GetErrorText() << Endl;
} else {
Cdbg << "Response = " << resp->Data << Endl;
}
}
} else {
Cdbg << "Timeout" << Endl;
}
Sleep(TDuration::MilliSeconds(5));
if (!ev.UserData) {
Error << "unexpected event";
return;
}
TStringBuf userData((const char*)ev.UserData);
if (userData.EndsWith('t')) {
if (ev.Type != IMultiClient::TEvent::Timeout) {
Error << "expect event timeout " << evNum << ", but have: " << userData;
return;
}
userData.Chop(1);
} else {
if (ev.Type != IMultiClient::TEvent::Response) {
Error << "expect event response " << evNum << ", but have: " << userData;
return;
}
}
size_t recEv = FromString<size_t>(userData);
if (recEv != evNum) {
Error << "expect event num " << evNum << ", but have: " << recEv;
return;
}
++evNum;
ev.UserData = nullptr;
}
Cdbg << "Interrupted" << Endl;
if (evNum != 5) {
Error << "receive not all events - expect next event: " << evNum;
return;
}
} catch (...) {
Error << CurrentExceptionMessage();
}
}
public:
TStringStream Error;
private:
IMultiClient& MC_;
TAutoPtr<IThreadPool::IThread> Thr_;
};
Y_UNIT_TEST(TFewRequests) {
TServer srv("test-response");
IServicesRef svs = CreateLoop();
const char* const url = "inproc://x:1/x";
const char* const badUrl = "inproc://x:2/x";
svs->Add(url, srv);
svs->ForkLoop(2);
{
TMultiClientPtr mc = CreateMultiClient();
TResponsesDispatcher disp(*mc);
disp.Run();
try {
//request to nonregistered handler
mc->Request(IMultiClient::TRequest(TMessage(badUrl, "test-data-0")));
UNIT_ASSERT_C(false, "request to not existed inptoc service MUST cause exception");
} catch (...) {
}
mc->Request(IMultiClient::TRequest(TMessage(url, "test-data-2"), TInstant::Max(), (void*)"0"));
mc->Request(IMultiClient::TRequest(TMessage(url, "delay 10000\ntest-data-1"), TDuration::MilliSeconds(30).ToDeadLine(), (void*)"1t"));
mc->Request(IMultiClient::TRequest(TMessage(url, "delay 50\ntest-data-3"), TDuration::MilliSeconds(5000).ToDeadLine(), (void*)"2"));
mc->Request(IMultiClient::TRequest(TMessage(url, "delay 1000\ntest-data-4"), TInstant::Max(), (void*)"3"));
mc->Request(IMultiClient::TRequest(TMessage(url, "delay 3000\ntest-data-5"), TDuration::MilliSeconds(2000).ToDeadLine(), (void*)"4t"));
mc->Request(IMultiClient::TRequest(TMessage(url, "delay 10000\ntest-data-6")));
Sleep(TDuration::MilliSeconds(4000));
disp.Stop();
if (!disp.Error.Empty()) {
throw yexception() << disp.Error.Str();
}
}
}
Y_UNIT_TEST(TWaitDeadline) {
TMultiClientPtr mc = CreateMultiClient();
IMultiClient::TEvent event;
UNIT_ASSERT(!mc->Wait(event, TDuration::MilliSeconds(1).ToDeadLine()));
UNIT_ASSERT(!mc->Wait(event, TDuration::MilliSeconds(1).ToDeadLine())); // the second try (check Interrupt_ flag in cycle)
}
}
|
stasinek/BHAPI | src/kits/kernel/private/arch/ppc/arch_cpu.h | /*
* Copyright 2003-2004, <NAME>, <EMAIL>.
* Distributed under the terms of the MIT License.
*/
#ifndef _KERNEL_ARCH_PPC_CPU_H
#define _KERNEL_ARCH_PPC_CPU_H
#include <arch/ppc/arch_thread_types.h>
#include <kernel.h>
#define CPU_MAX_CACHE_LEVEL 8
#define CACHE_LINE_SIZE 128
// 128 Byte lines on PPC970
struct iframe {
uint32 vector;
uint32 srr0;
uint32 srr1;
uint32 dar;
uint32 dsisr;
uint32 lr;
uint32 cr;
uint32 xer;
uint32 ctr;
uint32 fpscr;
uint32 r31;
uint32 r30;
uint32 r29;
uint32 r28;
uint32 r27;
uint32 r26;
uint32 r25;
uint32 r24;
uint32 r23;
uint32 r22;
uint32 r21;
uint32 r20;
uint32 r19;
uint32 r18;
uint32 r17;
uint32 r16;
uint32 r15;
uint32 r14;
uint32 r13;
uint32 r12;
uint32 r11;
uint32 r10;
uint32 r9;
uint32 r8;
uint32 r7;
uint32 r6;
uint32 r5;
uint32 r4;
uint32 r3;
uint32 r2;
uint32 r1;
uint32 r0;
double f31;
double f30;
double f29;
double f28;
double f27;
double f26;
double f25;
double f24;
double f23;
double f22;
double f21;
double f20;
double f19;
double f18;
double f17;
double f16;
double f15;
double f14;
double f13;
double f12;
double f11;
double f10;
double f9;
double f8;
double f7;
double f6;
double f5;
double f4;
double f3;
double f2;
double f1;
double f0;
};
enum machine_state {
MSR_EXCEPTIONS_ENABLED = 1L << 15, // EE
MSR_PRIVILEGE_LEVEL = 1L << 14, // PR
MSR_FP_AVAILABLE = 1L << 13, // FP
MSR_MACHINE_CHECK_ENABLED = 1L << 12, // ME
MSR_EXCEPTION_PREFIX = 1L << 6, // IP
MSR_INST_ADDRESS_TRANSLATION = 1L << 5, // IR
MSR_DATA_ADDRESS_TRANSLATION = 1L << 4, // DR
};
struct block_address_translation;
typedef struct arch_cpu_info {
int null;
} arch_cpu_info;
#define eieio() asm volatile("eieio")
#define isync() asm volatile("isync")
#define tlbsync() asm volatile("tlbsync")
#define ppc_sync() asm volatile("sync")
#define tlbia() asm volatile("tlbia")
#define tlbie(addr) asm volatile("tlbie %0" :: "r" (addr))
// adjust thread priority on PowerPC (Shared resource hints)
#define SRH_very_low() asm volatile("or 31,31,31")
#define SRH_low() asm volatile("or 1,1,1")
#define SRH_medium_low() asm volatile("or 6,6,6")
#define SRH_medium() asm volatile("or 2,2,2")
#define SRH_medium_high() asm volatile("or 5,5,5")
#define SRH_high() asm volatile("or 3,3,3")
#ifdef __cplusplus
extern "C" {
#endif
extern uint32 get_sdr1(void);
extern void set_sdr1(uint32 value);
extern uint32 get_sr(void *virtualAddress);
extern void set_sr(void *virtualAddress, uint32 value);
extern uint32 get_msr(void);
extern uint32 set_msr(uint32 value);
extern uint32 get_pvr(void);
extern void set_ibat0(struct block_address_translation *bat);
extern void set_ibat1(struct block_address_translation *bat);
extern void set_ibat2(struct block_address_translation *bat);
extern void set_ibat3(struct block_address_translation *bat);
extern void set_dbat0(struct block_address_translation *bat);
extern void set_dbat1(struct block_address_translation *bat);
extern void set_dbat2(struct block_address_translation *bat);
extern void set_dbat3(struct block_address_translation *bat);
extern void get_ibat0(struct block_address_translation *bat);
extern void get_ibat1(struct block_address_translation *bat);
extern void get_ibat2(struct block_address_translation *bat);
extern void get_ibat3(struct block_address_translation *bat);
extern void get_dbat0(struct block_address_translation *bat);
extern void get_dbat1(struct block_address_translation *bat);
extern void get_dbat2(struct block_address_translation *bat);
extern void get_dbat3(struct block_address_translation *bat);
extern void reset_ibats(void);
extern void reset_dbats(void);
//extern void sethid0(unsigned int val);
//extern unsigned int getl2cr(void);
//extern void setl2cr(unsigned int val);
extern long long get_time_base(void);
void __ppc_setup_system_time(vint32 *cvFactor);
// defined in libroot: os/arch/system_time.c
int64 __ppc_get_time_base(void);
// defined in libroot: os/arch/system_time_asm.S
extern void ppc_context_switch(void **_oldStackPointer, void *newStackPointer);
extern bool ppc_set_fault_handler(addr_t *handlerLocation, addr_t handler)
__attribute__((noinline));
static inline void arch_cpu_pause(void)
{
// TODO: PowerPC review logic of setting very low for pause
SRH_very_low();
}
static inline void arch_cpu_idle(void)
{
// TODO: PowerPC CPU idle call
}
#ifdef __cplusplus
}
#endif
// PowerPC processor version (the upper 16 bits of the PVR).
enum ppc_processor_version {
MPC601 = 0x0001,
MPC603 = 0x0003,
MPC604 = 0x0004,
MPC602 = 0x0005,
MPC603e = 0x0006,
MPC603ev = 0x0007,
MPC750 = 0x0008,
MPC604ev = 0x0009,
MPC7400 = 0x000c,
MPC620 = 0x0014,
IBM403 = 0x0020,
IBM401A1 = 0x0021,
IBM401B2 = 0x0022,
IBM401C2 = 0x0023,
IBM401D2 = 0x0024,
IBM401E2 = 0x0025,
IBM401F2 = 0x0026,
IBM401G2 = 0x0027,
IBMPOWER3 = 0x0041,
MPC860 = 0x0050,
MPC8240 = 0x0081,
AMCC460EX = 0x1302,
IBM405GP = 0x4011,
IBM405L = 0x4161,
AMCC440EP = 0x4222,
IBM750FX = 0x7000,
MPC7450 = 0x8000,
MPC7455 = 0x8001,
MPC7457 = 0x8002,
MPC7447A = 0x8003,
MPC7448 = 0x8004,
MPC7410 = 0x800c,
MPC8245 = 0x8081,
};
/*
Use of (some) special purpose registers.
SPRG0: per CPU physical address pointer to an ppc_cpu_exception_context
structure
SPRG1: scratch
SPRG2: current Thread*
SPRG3: TLS base pointer (only for userland threads)
*/
#endif /* _KERNEL_ARCH_PPC_CPU_H */
|
Summys/Retrospect | react-native/webpack.haul.storybook.js | module.exports = () => ({
entry: `./storybook/index.js`,
// any other haul config here.
});
|
mojojoseph/m2m-supervisor | lib/m2m-settings.js | module.exports = Object.freeze({
EventCodes: Object.freeze({
heartbeat: 0, // MO
startup: 1, // MO
config: 2, // MO/MT
status: 3, // MO/MT
restart: 4, // MT -- should result in "startup"
reboot: 5, // MT -- should result in "startup"
peripheralSchedule: 10, // MO/MT
peripheralCommand: 11, // MO/MT
peripheralConfig: 12 // MO/MT
}),
ObjectTypes: Object.freeze({
requestID: 2, // MO: sequence number of MT command
peripheralCommand: 10, // MO/MT: string to submit to peripheral
peripheralResponse: 11, // MO: string or byte array of command response
peripheralError: 12, // MO: string of command error
peripheralIndex: 13 // MO/MT: queue index of peripheral (defaults to 1)
})
}); |
jarrodmky/ShaderWriter | source/CompilerSpirV/SpirvStmtAdapter.hpp | /*
See LICENSE file in root folder
*/
#ifndef ___SDW_SpirvStmtAdapter_H___
#define ___SDW_SpirvStmtAdapter_H___
#pragma once
#include "SpirvHelpers.hpp"
#include <ShaderAST/Visitors/CloneStmt.hpp>
#include <unordered_set>
namespace spirv
{
struct AdaptationData
{
AdaptationData( PreprocContext & pcontext
, ModuleConfig pconfig )
: context{ pcontext }
, config{ std::move( pconfig ) }
{
}
PreprocContext & context;
ModuleConfig config;
};
class StmtAdapter
: public ast::StmtCloner
{
public:
static ast::stmt::ContainerPtr submit( ast::stmt::Container * container
, AdaptationData & adaptationData );
private:
StmtAdapter( ast::stmt::ContainerPtr & result
, AdaptationData & adaptationData );
ast::expr::ExprPtr doSubmit( ast::expr::Expr * expr )override;
void visitElseIfStmt( ast::stmt::ElseIf * stmt )override;
void visitElseStmt( ast::stmt::Else * stmt )override;
void visitIfStmt( ast::stmt::If * stmt )override;
void visitFunctionDeclStmt( ast::stmt::FunctionDecl * stmt )override;
void visitImageDeclStmt( ast::stmt::ImageDecl * stmt )override;
void visitInOutVariableDeclStmt( ast::stmt::InOutVariableDecl * stmt )override;
void visitPerVertexDeclStmt( ast::stmt::PerVertexDecl * stmt )override;
void visitSampledImageDeclStmt( ast::stmt::SampledImageDecl * stmt )override;
void visitShaderStructBufferDeclStmt( ast::stmt::ShaderStructBufferDecl * stmt )override;
void visitSimpleStmt( ast::stmt::Simple * stmt )override;
void visitStructureDeclStmt( ast::stmt::StructureDecl * stmt )override;
void visitVariableDeclStmt( ast::stmt::VariableDecl * stmt )override;
void visitPreprocDefine( ast::stmt::PreprocDefine * preproc )override;
void visitPreprocElif( ast::stmt::PreprocElif * preproc )override;
void visitPreprocElse( ast::stmt::PreprocElse * preproc )override;
void visitPreprocEndif( ast::stmt::PreprocEndif * preproc )override;
void visitPreprocIf( ast::stmt::PreprocIf * preproc )override;
void visitPreprocIfDef( ast::stmt::PreprocIfDef * preproc )override;
private:
void doProcess( ast::var::VariablePtr var
, ast::type::ComputeInput const & compType );
void doProcess( ast::var::VariablePtr var
, ast::type::FragmentInput const & fragType );
void doProcess( ast::var::VariablePtr var
, ast::type::GeometryOutput const & geomType );
void doProcess( ast::var::VariablePtr var
, ast::type::GeometryInput const & geomType );
void doProcess( ast::var::VariablePtr var
, ast::type::TessellationInputPatch const & patchType );
void doProcess( ast::var::VariablePtr var
, ast::type::TessellationOutputPatch const & patchType
, bool isEntryPoint );
void doProcess( ast::var::VariablePtr var
, ast::type::TessellationControlOutput const & tessType
, bool isEntryPoint );
void doProcess( ast::var::VariablePtr var
, ast::type::TessellationControlInput const & tessType
, bool isEntryPoint );
void doProcess( ast::var::VariablePtr var
, ast::type::TessellationEvaluationInput const & tessType );
void doProcessEntryPoint( ast::stmt::FunctionDecl * stmt );
void doProcessPatchRoutine( ast::stmt::FunctionDecl * stmt );
void doProcessInOut( ast::type::FunctionPtr funcType
, bool isEntryPoint );
void doDeclareStruct( ast::type::StructPtr const & structType );
private:
AdaptationData & m_adaptationData;
ast::stmt::Container * m_ioDeclarations;
std::unordered_set< ast::type::StructPtr > m_declaredStructs;
struct PendingFunction
{
ast::type::FunctionPtr funcType;
ast::stmt::ContainerPtr statements;
};
std::map< std::string, PendingFunction > m_pending;
};
}
#endif
|
openid-certification/-conformance-suite | src/main/java/net/openid/conformance/logging/TestInstanceEventLog.java | package net.openid.conformance.logging;
import java.security.SecureRandom;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import com.google.common.base.Strings;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import net.openid.conformance.testmodule.DataUtils;
/**
* A wrapper around an EventLog that supports blocks and remembers the test ID and Owner information
*/
public class TestInstanceEventLog implements DataUtils {
private String testId;
private Map<String, String> owner;
private EventLog eventLog;
// a block identifier for a log entry
private String blockId = null;
// random number generator
private Random random = new SecureRandom();
/**
* @param testId
* @param owner
* @param eventLog
*/
public TestInstanceEventLog(String testId, Map<String, String> owner, EventLog eventLog) {
this.testId = testId;
this.owner = owner;
this.eventLog = eventLog;
}
/**
* @param source
* @param msg
* @see EventLog#log(java.lang.String, java.lang.String, java.util.Map, java.lang.String)
*/
public synchronized void log(String source, String msg) {
if (blockId != null) {
eventLog.log(testId, source, owner, Map.of("blockId", blockId, "msg", msg));
} else {
eventLog.log(testId, source, owner, msg);
}
}
/**
* @param source
* @param obj
* @see EventLog#log(java.lang.String, java.lang.String, java.util.Map, com.google.gson.JsonObject)
*/
public synchronized void log(String source, JsonObject obj) {
JsonObject logObj;
if (blockId != null) {
logObj = new JsonObject();
for (Map.Entry<String, JsonElement> entry : obj.entrySet()) {
logObj.add(entry.getKey(), entry.getValue().deepCopy());
}
logObj.addProperty("blockId", blockId);
} else {
logObj = obj;
}
eventLog.log(testId, source, owner, logObj);
}
/**
* @param source
* @param map
* @see EventLog#log(java.lang.String, java.lang.String, java.util.Map, java.util.Map)
*/
public synchronized void log(String source, Map<String, Object> map) {
Map<String, Object> logMap;
if (blockId != null) {
logMap = new HashMap<>(map);
logMap.put("blockId", blockId);
} else {
logMap = map;
}
eventLog.log(testId, source, owner, logMap);
}
private String startBlock() {
// create a random six-character hex string that we can use as a CSS color code in the logs
blockId = Strings.padStart(
Integer.toHexString(
random.nextInt(256 * 256 * 256))
, 6, '0');
return blockId;
}
/**
* Start a new log block and return its ID
*
* @return
*/
public synchronized String startBlock(String message) {
String blockId = startBlock();
if (!Strings.isNullOrEmpty(message)) {
log("-START-BLOCK-", args("msg", message, "startBlock", true));
}
return blockId;
}
/**
* end a log block and return the previous block ID
*/
public synchronized String endBlock() {
String oldBlock = blockId;
blockId = null;
return oldBlock;
}
}
|
ezgikaysi/koding | go/src/github.com/canthefason/go-watcher/watch.go | // Package watcher watches all file changes via fsnotify package and sends
// update events to builder
package watcher
import (
"errors"
"fmt"
"log"
"os"
"path/filepath"
"strings"
"time"
fsnotify "gopkg.in/fsnotify.v1"
)
// Watcher watches the file change events from fsnotify and
// sends update messages. It is also used as a fsnotify.Watcher wrapper
type Watcher struct {
rootdir string
watcher *fsnotify.Watcher
// when file is changed a message is sent to update channel
update chan bool
}
// GoPath not set error
var ErrPathNotSet = errors.New("gopath not set")
// MustRegisterWatcher creates a new Watcher and starts listening
// given folders
func MustRegisterWatcher(params *Params) *Watcher {
w := &Watcher{
update: make(chan bool),
rootdir: params.Get("watch"),
}
var err error
w.watcher, err = fsnotify.NewWatcher()
if err != nil {
log.Fatalf("Could not register watcher: %s", err)
}
// add watched paths
w.watchFolders()
return w
}
// Watch listens file updates, and sends signal to
// update channel when go files are updated
func (w *Watcher) Watch() {
eventSent := false
for {
select {
case event := <-w.watcher.Events:
// discard chmod events
if event.Op&fsnotify.Chmod != fsnotify.Chmod {
ext := filepath.Ext(event.Name)
if ext == ".go" || ext == ".tmpl" {
if !eventSent {
// prevent consequent build
eventSent = true
go func() {
time.Sleep(200 * time.Millisecond)
eventSent = false
}()
w.update <- true
}
}
}
case err := <-w.watcher.Errors:
if err != nil {
log.Fatalf("Watcher error: %s", err)
}
return
}
}
}
func (w *Watcher) Wait() <-chan bool {
return w.update
}
// Close closes the fsnotify watcher channel
func (w *Watcher) Close() {
w.watcher.Close()
// close(w.update)
}
// watchFolders recursively adds folders that will be watched for changes,
// starting from the working directory
func (w *Watcher) watchFolders() {
wd, err := w.prepareRootDir()
if err != nil {
log.Fatalf("Could not get root working directory: %s", err)
}
filepath.Walk(wd, func(path string, info os.FileInfo, err error) error {
// skip files
if info == nil {
log.Fatalf("wrong watcher package: %s", path)
}
if !info.IsDir() {
return nil
}
// skip hidden folders
if len(path) > 1 && strings.HasPrefix(filepath.Base(path), ".") {
return filepath.SkipDir
}
w.addFolder(path)
return err
})
}
// addFolder adds given folder name to the watched folders, and starts
// watching it for further changes
func (w *Watcher) addFolder(name string) {
if err := w.watcher.Add(name); err != nil {
log.Fatalf("Could not watch folder: %s", err)
}
}
// prepareRootDir prepares working directory depending on root directory
func (w *Watcher) prepareRootDir() (string, error) {
if w.rootdir == "" {
return os.Getwd()
}
path := os.Getenv("GOPATH")
if path == "" {
return "", ErrPathNotSet
}
root := fmt.Sprintf("%s/src/%s", path, w.rootdir)
return root, nil
}
|
kations/contist-ui | src/lib/components/Input.js | <reponame>kations/contist-ui
import styled from "styled-components";
import propsToStyle from "../utils/propsToStyle";
let paddingVertical = "12px";
export const Input = styled.input`
width: 100%;
font-size: 1rem;
background: transparent;
background-image: none;
appearance: none;
border-radius: 0px;
vertical-align: top;
box-shadow: none;
border: none;
outline: none;
margin: 0;
${p => propsToStyle(p, p.theme)};
`;
export const Label = styled.label`
font-size: 0.8rem;
text-tranform: uppercase;
color: ${p => p.theme.colors.primary};
${p => propsToStyle(p, p.theme)};
`;
export const Fieldset = styled.fieldset`
${props => propsToStyle(props)};
`;
export const Form = styled.form`
width: 100%;
${p => propsToStyle(p, p.theme)};
`;
export const FormGroup = styled.div`
position: relative;
width: 100%;
display: flex;
flex-direction: column;
overflow: hidden;
justify-content: center;
background: rgb(245, 245, 245);
padding: 2px;
${p => p.radius && `border-radius: ${p.radius}px`};
${p => propsToStyle(p, p.theme)};
label {
position: ${p => (p.floating ? "absolute" : "relative")};
left: ${p => (p.floating ? "0px" : "auto")};
top: ${p => (p.floating ? "0px" : "auto")};
font-size: ${p => (p.floating ? "1rem" : "")};
z-index: 2;
padding: 10px ${paddingVertical} 0 ${paddingVertical};
transition: all 300ms ease-in-out;
${p => p.error && `color: ${p.theme.colors.error || "#f44336"}`};
${p =>
p.radius && `border-radius: ${p.radius - 2}px ${p.radius - 2}px 0 0`};
}
${p =>
p.floating
? `
input,
select,
textarea {
&::placeholder {
color: transparent;
}
}
label {
pointer-events: none;
width: 100%;
background: transparent;
padding: 17px ${paddingVertical}
5px ${paddingVertical};
color: rgba(0, 0, 0, 0.5);
}
&:focus-within {
label {
transform: translate3d(0, -10px, 0);
font-size: 0.8rem;
}
}
input:not(:placeholder-shown) + label {
transform: translate3d(0, -10px, 0);
font-size: 0.8rem;
}
select:not([value=""]):valid + label {
transform: translate3d(0, -10px, 0);
font-size: 0.8rem;
}`
: ""} input,
select,
textarea {
position: relative;
z-index: 1;
padding: ${p => (p.floating ? "24px" : "6px")} ${paddingVertical} 10px
${paddingVertical};
color: ${p => p.theme.colors.dark};
${p =>
p.radius && `border-radius: 0 0 ${p.radius - 2}px ${p.radius - 2}px`};
}
input:disabled,
textarea:disabled,
option:disabled {
color: rgba(0, 0, 0, 0.5);
}
input[type="checkbox"] {
display: none;
+ label {
padding: 13px ${paddingVertical};
font-size: 1.2rem;
position: relative;
color: ${p => p.theme.colors.dark};
&:before {
content: "";
position: absolute;
top: 50%;
margin-top: -15px;
right: ${paddingVertical};
background: #ccc;
width: 50px;
height: 30px;
border-radius: 25px;
transition: all 300ms ease-in-out;
}
&:after {
content: "";
position: absolute;
top: 50%;
margin-top: -15px;
right: 32px;
background: #fff;
width: 30px;
height: 30px;
border-radius: 15px;
transition: all 300ms ease-in-out;
border: 3px solid #ccc;
}
}
&:checked {
+ label {
&:before {
content: "";
background: ${p => p.theme.colors.primary};
}
&:after {
content: "";
transform: translate3d(20px, 0, 0);
border: 3px solid ${p => p.theme.colors.primary};
}
}
}
}
&:after {
${p => p.errorMessage && `content: "${p.errorMessage}"`};
position: absolute;
right: ${paddingVertical};
top: 0;
font-size: 0.8rem;
padding: 10px 0 0 0;
z-index: 3;
${p => p.error && `color: ${p.theme.colors.error || "#f44336"}`};
}
&:before {
content: "";
position: absolute;
left: 50%;
bottom: 0;
width: 0%;
height: 2px;
background: ${p => p.theme.colors.primary};
${p => p.radius && `border-radius: ${p.radius}px`};
${p => p.error && `background: ${p.theme.colors.error || "#f44336"}`};
transition: all 300ms ease-in-out;
}
&:focus-within {
&:before {
content: "";
width: 100%;
left: 0%;
}
}
`;
|
chentianming11/study | concurrent/src/main/java/com/chen/study/concurrent/concurrent2/balking/BalkingTest.java | package com.chen.study.concurrent.concurrent2.balking;
/**
* @author 陈添明
* @date 2018/9/23
*/
public class BalkingTest {
public static void main(String[] args) {
BalkingData balkingData = new BalkingData("test.txt", "---------begin----------");
new CustomerThread(balkingData).start();
new WaiterThread(balkingData).start();
}
}
|
zeusdeux/node | tools/eslint/node_modules/shelljs/src/common.js | <reponame>zeusdeux/node
var os = require('os');
var fs = require('fs');
var _ls = require('./ls');
// Module globals
var config = {
silent: false,
fatal: false
};
exports.config = config;
var state = {
error: null,
currentCmd: 'shell.js',
tempDir: null
};
exports.state = state;
var platform = os.type().match(/^Win/) ? 'win' : 'unix';
exports.platform = platform;
function log() {
if (!config.silent)
console.log.apply(this, arguments);
}
exports.log = log;
// Shows error message. Throws unless _continue or config.fatal are true
function error(msg, _continue) {
if (state.error === null)
state.error = '';
state.error += state.currentCmd + ': ' + msg + '\n';
if (msg.length > 0)
log(state.error);
if (config.fatal)
process.exit(1);
if (!_continue)
throw '';
}
exports.error = error;
// In the future, when Proxies are default, we can add methods like `.to()` to primitive strings.
// For now, this is a dummy function to bookmark places we need such strings
function ShellString(str) {
return str;
}
exports.ShellString = ShellString;
// Returns {'alice': true, 'bob': false} when passed a dictionary, e.g.:
// parseOptions('-a', {'a':'alice', 'b':'bob'});
function parseOptions(str, map) {
if (!map)
error('parseOptions() internal error: no map given');
// All options are false by default
var options = {};
for (var letter in map)
options[map[letter]] = false;
if (!str)
return options; // defaults
if (typeof str !== 'string')
error('parseOptions() internal error: wrong str');
// e.g. match[1] = 'Rf' for str = '-Rf'
var match = str.match(/^\-(.+)/);
if (!match)
return options;
// e.g. chars = ['R', 'f']
var chars = match[1].split('');
chars.forEach(function(c) {
if (c in map)
options[map[c]] = true;
else
error('option not recognized: '+c);
});
return options;
}
exports.parseOptions = parseOptions;
// Expands wildcards with matching (ie. existing) file names.
// For example:
// expand(['file*.js']) = ['file1.js', 'file2.js', ...]
// (if the files 'file1.js', 'file2.js', etc, exist in the current dir)
function expand(list) {
var expanded = [];
list.forEach(function(listEl) {
// Wildcard present on directory names ?
if(listEl.search(/\*[^\/]*\//) > -1 || listEl.search(/\*\*[^\/]*\//) > -1) {
var match = listEl.match(/^([^*]+\/|)(.*)/);
var root = match[1];
var rest = match[2];
var restRegex = rest.replace(/\*\*/g, ".*").replace(/\*/g, "[^\\/]*");
restRegex = new RegExp(restRegex);
_ls('-R', root).filter(function (e) {
return restRegex.test(e);
}).forEach(function(file) {
expanded.push(file);
});
}
// Wildcard present on file names ?
else if (listEl.search(/\*/) > -1) {
_ls('', listEl).forEach(function(file) {
expanded.push(file);
});
} else {
expanded.push(listEl);
}
});
return expanded;
}
exports.expand = expand;
// Normalizes _unlinkSync() across platforms to match Unix behavior, i.e.
// file can be unlinked even if it's read-only, see https://github.com/joyent/node/issues/3006
function unlinkSync(file) {
try {
fs.unlinkSync(file);
} catch(e) {
// Try to override file permission
if (e.code === 'EPERM') {
fs.chmodSync(file, '0666');
fs.unlinkSync(file);
} else {
throw e;
}
}
}
exports.unlinkSync = unlinkSync;
// e.g. 'shelljs_a5f185d0443ca...'
function randomFileName() {
function randomHash(count) {
if (count === 1)
return parseInt(16*Math.random(), 10).toString(16);
else {
var hash = '';
for (var i=0; i<count; i++)
hash += randomHash(1);
return hash;
}
}
return 'shelljs_'+randomHash(20);
}
exports.randomFileName = randomFileName;
// extend(target_obj, source_obj1 [, source_obj2 ...])
// Shallow extend, e.g.:
// extend({A:1}, {b:2}, {c:3}) returns {A:1, b:2, c:3}
function extend(target) {
var sources = [].slice.call(arguments, 1);
sources.forEach(function(source) {
for (var key in source)
target[key] = source[key];
});
return target;
}
exports.extend = extend;
// Common wrapper for all Unix-like commands
function wrap(cmd, fn, options) {
return function() {
var retValue = null;
state.currentCmd = cmd;
state.error = null;
try {
var args = [].slice.call(arguments, 0);
if (options && options.notUnix) {
retValue = fn.apply(this, args);
} else {
if (args.length === 0 || typeof args[0] !== 'string' || args[0][0] !== '-')
args.unshift(''); // only add dummy option if '-option' not already present
retValue = fn.apply(this, args);
}
} catch (e) {
if (!state.error) {
// If state.error hasn't been set it's an error thrown by Node, not us - probably a bug...
console.log('shell.js: internal error');
console.log(e.stack || e);
process.exit(1);
}
if (config.fatal)
throw e;
}
state.currentCmd = 'shell.js';
return retValue;
};
} // wrap
exports.wrap = wrap;
|
throne/throne-cli | src/parsers/rdap_ip_parser.py | <filename>src/parsers/rdap_ip_parser.py
# LICENSED UNDER BSD-3-CLAUSE-CLEAR LICENSE
# SEE PROVIDED LICENSE FILE IN ROOT DIRECTORY
# Import Third Party Modules
import sys
import logging
# Import Throne Modules
from src.exceptions import ThroneParsingError
# Set log variable for verbose output
log = logging.getLogger(__name__)
# RDAP & RIPESTAT URLs
BOOTSTRAP_URL = 'https://rdap-bootstrap.arin.net/bootstrap'
AFRNIC_URL = 'https://rdap.afrinic.net/rdap'
RIPESTAT_URL = 'https://stat.ripe.net/data'
# Set python check interval to 1, hopefully to improve performance
sys.setswitchinterval(1)
####################THIS LINE SEPERATES RDAP PARSERS FROM OTHER ASN PARSERS####################
class _RDAPIPCommon:
# This class is used to parse common data between AS number entities (see vars)
def __init__(self, json_result):
self.json = json_result
self.vars = {
'rir': None,
'handle': None,
'startAddress': None,
'endAddress': None,
'cidr': None,
'ipVersion': None,
'name': None,
'type': None,
}
# This function takes our JSON response key/values and ties them to the self.vars key/values
def _parse(self):
log.debug("Parsing common varibles...")
# This in particular is taking ripe from "whois.ripe.net" and making it RIPE, a value of the "rir" variable
rir = self.json['port43'].strip('whois')
rir = rir.strip('net')
rir = rir.strip('.')
rir = rir.upper()
# Assign CIDR key before assigning the rest of the json keys
if "RIPE" in rir:
if "v4" in self.json['ipVersion']:
log.debug("RIPE does not provide CIDR notation in RDAP IPv4 response!")
self.vars['cidr'] = self.json['parentHandle']
if "v6" in self.json['ipVersion']:
self.vars['cidr'] = self.json['parentHandle']
if "RIPE" not in rir:
for cidr in self.json['cidr0_cidrs']:
prefix = cidr['v4prefix']
length = cidr['length']
sum0 = '{}/{}'.format(prefix,length)
self.vars['cidr'] = sum0
# Assign the rest of the common keys to the json keys
self.vars['rir'] = rir
self.vars['startAddress'] = self.json['startAddress']
self.vars['endAddress'] = self.json['endAddress']
self.vars['ipVersion'] = self.json['ipVersion']
self.vars['name'] = self.json['name']
self.vars['type'] = self.json['type']
log.debug("Sending parsed JSON back to requesting module for user display...")
class _RDAPIPEntity(_RDAPIPCommon):
# This class is used to parse data received from AS entities into specified vars
def __init__(self, json_result):
try:
log.debug("Sending JSON to _RDAPIPCommon to prepare parsing...")
_RDAPIPCommon.__init__(self, json_result)
except ValueError:
log.debug("_RDAPIPCommon failed to parse, JSON received must not be a dict...")
raise ThroneParsingError("JSON result is not a dict!")
self.vars.update({
'entities': []
})
# This function actually doesn't do much other than parsing other received data
# from _RDAPContact into an overall JSON dictionary
def parse(self):
try:
log.debug("Setting handle from JSON response...")
self.vars['handle'] = self.json['handle'].strip()
except:
log.debug("Handle missing from RDAP entity...raising exception")
raise ThroneParsingError("Handle missing from RDAP entity")
# Parse all data vCard/Entity data in JSON response by RIR (ARIN likes to be special)
try:
log.debug("Trying to parse entity data based upon RIRs format...")
# Parse RIPE formatted data
if "ripe" in self.json['port43']:
log.debug("RIPE detected as responding RIR...")
for ent in self.json['entities']:
try:
vcard = ent['vcardArray'][1]
c = _RDAPContact(vcard)
c.parse()
c.vars['roles'] = ent['roles']
c.vars['handle'] = ent['handle']
log.debug("Appending all parsed vCardArrays to vars['entities']...")
self.vars['entities'].append(c.vars)
except:
log.debug("There might be more data for this IP...RIPE filters all contacts except abuse contacts. Filtered contacts are not displayed.")
# Parse APNIC formatted data
if "apnic" in self.json['port43']:
log.debug("APNIC detected as responding RIR...")
for ent in self.json['entities']:
try:
vcard = ent['vcardArray'][1]
c = _RDAPContact(vcard)
c.parse()
c.vars['roles'] = ent['roles']
c.vars['handle'] = ent['handle']
log.debug("Appending all parsed vCardArrays to vars['entities']...")
self.vars['entities'].append(c.vars)
except:
log.debug("Additional IP contact information found but skipping it. Please report this with all debug logs as an issue for Throne.")
# Parse ARIN formatted data
if "arin" in self.json['port43']:
log.debug("ARIN detected as responding RIR...")
for ent in self.json['entities']:
try:
vcard = ent['vcardArray'][1]
c = _RDAPContact(vcard)
c.parse()
c.vars['roles'] = ent['roles']
c.vars['handle'] = ent['handle']
log.debug("Appending all parsed vCardArrays to vars['entities']...")
self.vars['entities'].append(c.vars)
except:
log.debug("Additional IP contact information found but skipping it. Please report this with all debug logs as an issue for Throne.")
log.debug("ARIN likes to be special and nest entities, attempting to parse those...")
for ent in self.json['entities'][0]['entities']:
try:
vcard = ent['vcardArray'][1]
c = _RDAPContact(vcard)
c.parse()
c.vars['roles'] = ent['roles']
c.vars['handle'] = ent['handle']
log.debug("Appending all parsed vCardArrays to vars['entities']...")
self.vars['entities'].append(c.vars)
except:
log.debug("Additional ARIN nested contact information found but skipping it. Please report this with all debug logs as an issue for Throne.")
# Parse AFRINIC formatted data
if "afrinic" in self.json['port43']:
log.debug("AFRINIC detected as responding RIR...")
for ent in self.json['entities']:
try:
vcard = ent['vcardArray'][1]
c = _RDAPContact(vcard)
c.parse()
c.vars['roles'] = ent['roles']
c.vars['handle'] = ent['handle']
log.debug("Appending all parsed vCardArrays to vars['entities']...")
self.vars['entities'].append(c.vars)
except:
log.debug("Additional IP contact information found but skipping it. Please report this with all debug logs as an issue for Throne.")
# Placeholder for future LACNIC data
except:
log.debug("Cannot parse the vCardArry for entities, raising exception")
raise ThroneParsingError("vcardArray parsing failed!")
# If we don't get a self.vars['entities'] response just set it to None
if not self.vars['entities']:
self.vars['entities'] = None
log.debug("Asking _RDAPIPCommon to parse common variables")
self._parse()
class _RDAPContact:
# This class is used to parse the vcardArray out of each entity as specified above.
# Each key/value in the JSON response has it's own function to ultimately place it
# into custom JSON keys/values
def __init__(self, vcard):
self.vcard = vcard
self.vars = {
'handle': None,
'name': None,
'kind': None,
'address': None,
'phone': None,
'email': None,
'roles': None,
'title': None
}
def _parse_name(self, val):
"""
Parses names out of vCard
"""
self.vars['name'] = val[3].strip()
def _parse_kind(self, val):
self.vars['kind'] = val[3].strip()
def _parse_address(self, val):
answer = {
'type': None,
'value': None
}
try:
answer['type'] = val[1]['type']
except:
pass
try:
answer['value'] = val[1]['label'].replace("\n", " ")
except:
answer['value'] = '\n'.join(val[3]).strip()
try:
self.vars['address'].append(answer)
except:
self.vars['address'] = []
self.vars['address'].append(answer)
def _parse_phone(self, val):
answer = {
'type': None,
'value': None
}
try:
answer['type'] = val[1]['type']
except:
pass
answer['value'] = val[3]
try:
self.vars['phone'].append(answer)
except:
self.vars['phone'] = []
self.vars['phone'].append(answer)
def _parse_email(self, val):
answer = {
'type': None,
'value': None
}
try:
answer['type'] = val[1]['type']
except:
pass
answer['value'] = val[3].strip()
try:
self.vars['email'].append(answer)
except:
self.vars['email'] = []
self.vars['email'].append(answer)
def _parse_role(self, val):
self.vars['role'] = val[3]
def _parse_title(self, val):
self.vars['title'] = val[3]
def parse(self):
# Custom Keys
keys = {
'fn': self._parse_name,
'kind': self._parse_kind,
'adr': self._parse_address,
'tel': self._parse_phone,
'email': self._parse_email,
'role': self._parse_role,
'title': self._parse_title
}
# Take all values from the above functions and add to
# the appropriate keys
for val in self.vcard:
try:
parser = keys.get(val[0])
parser(val)
log.debug(f"Parsing {val}...")
except:
pass
class _RIPEPrefixOverview():
def __init__(self, json_result):
self.json = json_result
self.vars = {
'is_less_specific': None,
'announced': None,
'asns': [],
'related_prefixes': [],
'prefix': None,
'type': None,
'block_resource': None,
'block_desc': None,
'block_name': None
}
def parse(self):
log.debug("Parsing IP/Prefix Information...")
if self.json['data']['asns'] == []:
self.vars.update({
'asns': None
})
else:
for asn in self.json['data']['asns']:
self.vars['asns'].append(asn)
for prefixes in self.json['data']['related_prefixes']:
if self.json['data']['related_prefixes'] == []:
pass
else:
self.vars['related_prefixes'].append(prefixes)
self.vars['is_less_specific'] = self.json['data']['is_less_specific']
self.vars['announced'] = self.json['data']['announced']
self.vars['prefix'] = self.json['data']['resource']
self.vars['type'] = self.json['data']['type']
self.vars['block_resource'] = self.json['data']['block']['resource']
self.vars['block_desc'] = self.json['data']['block']['desc']
self.vars['block_name'] = self.json['data']['block']['name'] |
xionluhnis/knitsketching | src/ui/actions/seam-create.js | // <NAME> <<EMAIL>>
"use strict";
// modules
const SketchAction = require('./action.js');
const CreateSubCurve = require('./subcurve-create.js');
const { SEAM_ON } = require('../../sketch/seam.js');
class CreateSeamCurve extends CreateSubCurve {
constructor(parentSketch = null){
super(parentSketch);
}
setSeam(curve = this.curve){
if(!curve)
return;
for(let segIdx = 0; segIdx < curve.segLength; ++segIdx)
curve.setSeamMode(segIdx, SEAM_ON);
}
createCurve(curve){
this.setSeam(curve);
}
stop(...args){
const curve = this.curve;
super.stop(...args);
this.setSeam(curve);
}
}
module.exports = SketchAction.register('seam-create', CreateSeamCurve); |
kejgon/working-with-java | StringsExercise2.java | <reponame>kejgon/working-with-java
import java.util.*;
public class StringsExercise2 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);// creating an object from class Scanner
System.out.println("Enter any sentence");
String text = input.nextLine();// assigning user input to variable text
String textRepl = text.replaceAll("\\s{2,}", " ").trim();// removing any extra whitespace
char[] textChar = textRepl.toCharArray();// converting our string to sequence of characters
for (int i = 0; i < textChar.length; i++) {// populating the words array of characters
if (i % 5 == 0) {// getting the characters at the fifth position
textChar[i] = (char) (textChar[i] - 32); // converting lowerCase characters to upperCase characters
}
}
System.out.println(text);
System.out.println(textChar);
input.close();
}
} |
manasys/grouper | grouper-misc/grouper-ui-dojo/dojo/dojox/widget/MonthlyCalendar.js | <reponame>manasys/grouper
//>>built
define("dojox/widget/MonthlyCalendar",["dojo/_base/declare","./_CalendarBase","./_CalendarMonth"],function(_1,_2,_3){
return _1("dojox.widget.MonthlyCalendar",[_2,_3],{_makeDate:function(_4){
var _5=new Date();
_5.setMonth(_4);
return _5;
}});
});
|
aniskchaou/GYM-FRONTEND-ADMIN | src/modules/groupeModule/ViewGroupe/ViewGroupe.js | <filename>src/modules/groupeModule/ViewGroupe/ViewGroupe.js
import React from 'react';
import PropTypes from 'prop-types';
import './ViewGroupe.css';
const ViewGroupe = () => (
<div className="ViewGroupe">
ViewGroupe Component
</div>
);
ViewGroupe.propTypes = {};
ViewGroupe.defaultProps = {};
export default ViewGroupe;
|
LarsHagemann/OrbitEngine | inc/implementation/engine/Allocator.hpp | <filename>inc/implementation/engine/Allocator.hpp
#pragma once
#include <vector>
#include <memory>
#include <set>
#include <mutex>
#include "implementation/engine/AllocatorPage.hpp"
namespace orbit
{
class Allocator
{
protected:
using MemoryHeapPool = std::vector<std::shared_ptr<AllocatorPage>>;
// @member: the number of descriptors per heap
size_t _pagesize;
// @member: pool of descriptor heaps
MemoryHeapPool _heapPool;
// @member: indices of available pages in the DescriptorHeapPool
std::set<size_t> _availablePages;
// @member: mutex for thread safe allocations
std::mutex _allocationMutex;
protected:
// @method: creates a new descriptor heap with a certain
// number of descriptors
std::shared_ptr<AllocatorPage> CreateAllocatorPage();
public:
// @brief: creates a new descriptor allocator of a certain descriptor heap type
// @param pagesize: the number of bytes in a page
Allocator(size_t pagesize = 2_MiB);
// @destructor
virtual ~Allocator();
// @brief: allocates a number of contiguous bytes
// @param sizeInBytes: the number of bytes to allocate
Allocation CPUAllocate(size_t sizeInBytes);
// @brief: releases all the stale descriptors
// @param frameNumber:
void ReleaseStaleDescriptors();
};
}
|
alonmor1/searchblock2 | node_modules/@shopify/polaris-icons/dist/icons/SecureMajor.svg.js | <filename>node_modules/@shopify/polaris-icons/dist/icons/SecureMajor.svg.js
'use strict';
var React = require('react');
var _ref =
/*#__PURE__*/
React.createElement("path", {
fillRule: "evenodd",
d: "M9.128.233c-2.37 1.383-5.37 2.33-7.635 2.646-.821.115-1.495.79-1.493 1.62l.001.497c-.03 6.043.477 11.332 9.462 14.903a1.45 1.45 0 0 0 1.062 0c8.993-3.571 9.503-8.86 9.473-14.903v-.501c-.001-.828-.674-1.51-1.492-1.638-2.148-.337-5.281-1.274-7.65-2.628a1.733 1.733 0 0 0-1.728.004zm4.577 8.478a1 1 0 0 0-1.414-1.415L8.998 10.59 7.705 9.297A1 1 0 1 0 6.29 10.71l2 2.001a1 1 0 0 0 1.414 0l4-4.001z"
});
var SvgSecureMajor = function SvgSecureMajor(props) {
return React.createElement("svg", Object.assign({
viewBox: "0 0 20 20"
}, props), _ref);
};
exports.SvgSecureMajor = SvgSecureMajor;
|
aligoren/pyalgo | hanoi_tower_algorithm.py | <gh_stars>10-100
def hanoi_tower_algorithm(n, x, y, z):
"""
Source: http://en.wikipedia.org/wiki/Tower_of_Hanoi
Fransız matematikçi, <NAME> tarafından önerilen bir kule problemidir.
A,B ve C gibi dik konumda yerleştirilmiş üç çubuk ve n adet disk verilmektedir.
Başlangıç durumunda diskler, üstteki her diskin çapı daha küçük olmak koşuluyla A çubuğuna yerleştirilmiştir.
Her seferinde yalnız bir diskin hareketine izin verildiğinde, büyük diski küçüğünün üzerine yerleştirmeden,
disklerin C çubuğuna taşınması istenmektedir.
Hanoi problemini, problemi alt problemlere parçalayarak çözebiliriz. Problemde N sayıda disk varsa recursive şekilde
genel çözüm şöyle olabilir:
Tek disk direkt 3. çubuğa koyuluyor
N sayıda disk 3 adıma koyulmalı
A- (N-1) disk orta çubuğa taşınır.
B- En alttaki disk direkt sağa konulur.
C- (N-1) disk sağa taşınır.
Output (Number of Disc 4):
Diski A çubuğundan B çubuğuna koy
Diski A çubuğundan C çubuğuna koy
Diski B çubuğundan C çubuğuna koy
Diski A çubuğundan B çubuğuna koy
Diski C çubuğundan A çubuğuna koy
Diski C çubuğundan B çubuğuna koy
Diski A çubuğundan B çubuğuna koy
Diski A çubuğundan C çubuğuna koy
Diski B çubuğundan C çubuğuna koy
Diski B çubuğundan A çubuğuna koy
Diski C çubuğundan A çubuğuna koy
Diski B çubuğundan C çubuğuna koy
Diski A çubuğundan B çubuğuna koy
Diski A çubuğundan C çubuğuna koy
Diski B çubuğundan C çubuğuna koy
4 adet diskli bir durumda disk sayısı n = 1 olduğunda toplam 3 durum ve çözüm için K1 = 1 olmakta.
Disk sayısı n = 2 olduğunda toplam 9 durum ve minimum geçiş K2 = 3 olmakta.
Disk sayısı n = 3 olduğunda toplam 27 durum ve minimum geçiş K3 = 7 olmakta.
Disk sayısı n = 4 olduğunda toplam durum sayısı 81 ve minimum geçiş ise K4 = 15 olmakta.
Çubuk sayısı 3 olduğunda N adet disk için minimum geçişler, yinelemeli biçimde Kn = (2 Kn-1 +1) veya
n'ye bağımlı olarak Kn = 2^n - 1 şeklinde bulunmaktadır.
"""
if n == 1:
print("Diski %s çubuğundan %s çubuğuna koy" % (x,z))
else:
hanoi_tower_algorithm(n-1, x, z, y)
hanoi_tower_algorithm(1, x, y, z)
hanoi_tower_algorithm(n-1, y, x, z)
def hanoi_tower_algorithm_main(ndisc):
# ndisc = Number of Disc
hanoi_tower_algorithm(ndisc, "A", "B", "C")
hanoi_tower_algorithm_main(10)
# profiling result for 10 numbers
# profile: python -m profile hanoi_tower_algorithm.py
"""
6654 function calls (5121 primitive calls) in 0.078 seconds
Ordered by: standard name
ncalls tottime percall cumtime percall filename:lineno(function)
2046 0.000 0.000 0.000 0.000 :0(charmap_encode)
1 0.000 0.000 0.078 0.078 :0(exec)
1023 0.062 0.000 0.078 0.000 :0(print)
1 0.000 0.000 0.000 0.000 :0(setprofile)
2046 0.016 0.000 0.016 0.000 cp857.py:18(encode)
1 0.000 0.000 0.078 0.078 hanoi_tower_algorithm.py:1(<module
>)
1534/1 0.000 0.000 0.078 0.078 hanoi_tower_algorithm.py:1(hanoi_t
ower_algorithm)
1 0.000 0.000 0.078 0.078 hanoi_tower_algorithm.py:44(hanoi_
tower_algorithm_main)
1 0.000 0.000 0.078 0.078 profile:0(<code object <module> at
0x01DCC2A0, file "hanoi_tower_algorithm.py", line 1>)
0 0.000 0.000 profile:0(profiler)
""" |
hansonreal/mini-admin | mini-admin-gateway/src/main/java/com/github/mini/gateway/config/WebSecurityConfig.java | package com.github.mini.gateway.config;
import com.github.mini.common.properties.RsaKeyProperties;
import com.github.mini.gateway.security.authentication.MiniAuthenticationEntryPoint;
import com.github.mini.gateway.security.ext.SecurityExtUtil;
import com.github.mini.gateway.security.filter.JwtAuthenticationFilter;
import com.github.mini.gateway.security.handler.MiniAccessDeniedHandler;
import com.github.mini.gateway.security.service.UserDetailsServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true) //开启@PreAuthorize @PostAuthorize 等前置后置安全校验注解
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private RsaKeyProperties rsaKeyProperties;
@Autowired
private SecurityExtUtil securityExt;
/**
* 使用BCrypt强哈希函数 实现PasswordEncoder
**/
@Bean
public PasswordEncoder passwordEncoderBean() {
return new BCryptPasswordEncoder();
}
@Bean
public UserDetailsService userDetailsServiceBean() {
return new UserDetailsServiceImpl();
}
@Override
@Bean
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsServiceBean())
.passwordEncoder(passwordEncoderBean());
}
@Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
httpSecurity.csrf().disable() // 由于使用的是JWT,我们这里不需要csrf(跨站请求伪造)
.cors()// 跨越配置支持,此处代码会自动加载一个bean名称为 corsFilter的Filter
.and().exceptionHandling().authenticationEntryPoint(new MiniAuthenticationEntryPoint())// 认证失败处理方式
.accessDeniedHandler(new MiniAccessDeniedHandler())//无权限操作异常处理
.and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS) // 基于token,所以不需要session
.and().authorizeRequests().antMatchers(securityExt.getAnonymousUrls().toArray(new String[0])).permitAll()//可以匿名被访问的URL
.and().authorizeRequests().anyRequest().authenticated()// 除上面外的所有请求全部需要鉴权认证
.and().addFilterBefore(new JwtAuthenticationFilter(rsaKeyProperties), UsernamePasswordAuthenticationFilter.class) // 添加JWT 认证过滤器filter
.headers().cacheControl();// 禁用缓存
}
}
|
youyouqiu/hybrid-development | clbs/src/main/java/com/sx/platform/contorller/sxReportManagement/ShiftDataReportController.java | <filename>clbs/src/main/java/com/sx/platform/contorller/sxReportManagement/ShiftDataReportController.java
package com.sx.platform.contorller.sxReportManagement;
import com.sx.platform.service.sxReportManagement.ShiftDataReportService;
import com.zw.platform.commons.Auth;
import com.zw.platform.util.common.JsonResultBean;
import com.zw.platform.util.excel.ExportExcelUtil;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletResponse;
/**
* @author zhangsq
* @date 2018/3/12 11:02
*/
@RestController
@RequestMapping("/sx/sxReportManagement/shiftDataReport")
public class ShiftDataReportController {
private static final String LIST_PAGE = "modules/sxReportManagement/shiftDataReport";
@Autowired
private ShiftDataReportService shiftDataReportService;
private static Logger logger = LogManager.getLogger(ShiftDataReportController.class);
@Value("${sys.error.msg}")
private String sysErrorMsg;
@Auth
@RequestMapping(value = "list", method = RequestMethod.GET)
public ModelAndView listPage() {
return new ModelAndView(LIST_PAGE);
}
@RequestMapping(value = "list", method = RequestMethod.POST)
public JsonResultBean list(String band, String startTime, String endTime) {
try {
return shiftDataReportService.getListFromPaas(band, startTime, endTime);
} catch (Exception e) {
logger.error("获取漂移数据报表异常", e);
return new JsonResultBean(JsonResultBean.FAULT, sysErrorMsg);
}
}
/**
* 导出(生成excel文件)
* @param res
*/
@RequestMapping(value = "/export")
public void export2(HttpServletResponse res) {
try {
ExportExcelUtil.setResponseHead(res, "漂移数据报表");
shiftDataReportService.export(null, 1, res);
} catch (Exception e) {
logger.error(" 导出漂移数据报表异常", e);
}
}
}
|
canghai908/zabbix | src/zabbix_agent/perfstat.c | /*
** Zabbix
** Copyright (C) 2001-2015 Zabbix SIA
**
** 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.
**/
#include "common.h"
#include "stats.h"
#include "perfstat.h"
#include "alias.h"
#include "log.h"
#include "mutexs.h"
#include "sysinfo.h"
static ZBX_PERF_STAT_DATA ppsd;
static ZBX_MUTEX perfstat_access = ZBX_MUTEX_NULL;
#define LOCK_PERFCOUNTERS if (ZBX_MUTEX_NULL != perfstat_access) zbx_mutex_lock(&perfstat_access)
#define UNLOCK_PERFCOUNTERS if (ZBX_MUTEX_NULL != perfstat_access) zbx_mutex_unlock(&perfstat_access)
/******************************************************************************
* *
* Comments: counter failed or disappeared, dismiss all previous values *
* *
******************************************************************************/
static void deactivate_perf_counter(PERF_COUNTER_DATA *counter)
{
zabbix_log(LOG_LEVEL_DEBUG, "deactivate_perf_counter() counterpath:'%s'", counter->counterpath);
counter->status = PERF_COUNTER_NOTSUPPORTED;
counter->value_count = 0;
counter->value_current = -1;
counter->olderRawValue = 0;
counter->sum = 0;
}
/******************************************************************************
* *
* Comments: if the specified counter exists or a new is successfully *
* added, a pointer to that counter is returned, NULL otherwise *
* *
******************************************************************************/
PERF_COUNTER_DATA *add_perf_counter(const char *name, const char *counterpath, int interval, char **error)
{
const char *__function_name = "add_perf_counter";
PERF_COUNTER_DATA *cptr = NULL;
PDH_STATUS pdh_status;
int added = FAIL;
zabbix_log(LOG_LEVEL_DEBUG, "In %s() counter:'%s' interval:%d", __function_name, counterpath, interval);
LOCK_PERFCOUNTERS;
if (SUCCEED != perf_collector_started())
{
*error = zbx_strdup(*error, "Performance collector is not started.");
goto out;
}
for (cptr = ppsd.pPerfCounterList; ; cptr = cptr->next)
{
/* add new parameters */
if (NULL == cptr)
{
cptr = (PERF_COUNTER_DATA *)zbx_malloc(cptr, sizeof(PERF_COUNTER_DATA));
/* initialize the counter */
memset(cptr, 0, sizeof(PERF_COUNTER_DATA));
if (NULL != name)
cptr->name = zbx_strdup(NULL, name);
cptr->counterpath = zbx_strdup(NULL, counterpath);
cptr->interval = interval;
cptr->value_current = -1;
cptr->value_array = (double *)zbx_malloc(cptr->value_array, sizeof(double) * interval);
/* add the counter to the query */
pdh_status = zbx_PdhAddCounter(__function_name, cptr, ppsd.pdh_query, counterpath,
&cptr->handle);
cptr->next = ppsd.pPerfCounterList;
ppsd.pPerfCounterList = cptr;
if (ERROR_SUCCESS != pdh_status && PDH_CSTATUS_NO_INSTANCE != pdh_status)
{
*error = zbx_dsprintf(*error, "Invalid performance counter format.");
cptr = NULL; /* indicate a failure */
}
added = SUCCEED;
break;
}
if (NULL != name && 0 == strcmp(cptr->name, name))
break;
if (NULL == name && 0 == strcmp(cptr->counterpath, counterpath) && cptr->interval == interval)
break;
}
if (FAIL == added)
{
zabbix_log(LOG_LEVEL_DEBUG, "%s() counter '%s' already exists", __function_name, counterpath);
}
else if (NULL != name)
{
char *alias_name;
alias_name = zbx_dsprintf(NULL, "__UserPerfCounter[%s]", name);
add_alias(name, alias_name);
zbx_free(alias_name);
}
out:
UNLOCK_PERFCOUNTERS;
zabbix_log(LOG_LEVEL_DEBUG, "End of %s(): %s", __function_name, NULL == cptr ? "FAIL" : "SUCCEED");
return cptr;
}
/******************************************************************************
* *
* Function: extend_perf_counter_interval *
* *
* Purpose: extends the performance counter buffer to store the new data *
* interval *
* *
* Parameters: result - [IN] the performance counter *
* interval - [IN] the new data collection interval in seconds *
* *
******************************************************************************/
static void extend_perf_counter_interval(PERF_COUNTER_DATA *counter, int interval)
{
if (interval <= counter->interval)
return;
counter->value_array = (double *)zbx_realloc(counter->value_array, sizeof(double) * interval);
/* move the data to the end to keep the ring buffer intact */
if (counter->value_current < counter->value_count)
{
int i;
double *src, *dst;
src = &counter->value_array[counter->interval - 1];
dst = &counter->value_array[interval - 1];
for (i = 0; i < counter->value_count - counter->value_current; i++)
*dst-- = *src--;
}
counter->interval = interval;
}
/******************************************************************************
* *
* Comments: counter is removed from the collector and *
* the memory is freed - do not use it again *
* *
******************************************************************************/
void remove_perf_counter(PERF_COUNTER_DATA *counter)
{
PERF_COUNTER_DATA *cptr;
LOCK_PERFCOUNTERS;
if (NULL == counter || NULL == ppsd.pPerfCounterList)
goto out;
if (counter == ppsd.pPerfCounterList)
{
ppsd.pPerfCounterList = counter->next;
}
else
{
for (cptr = ppsd.pPerfCounterList; ; cptr = cptr->next)
{
if (cptr->next == counter)
{
cptr->next = counter->next;
break;
}
}
}
PdhRemoveCounter(counter->handle);
zbx_free(counter->name);
zbx_free(counter->counterpath);
zbx_free(counter->value_array);
zbx_free(counter);
out:
UNLOCK_PERFCOUNTERS;
}
static void free_perf_counter_list()
{
PERF_COUNTER_DATA *cptr;
LOCK_PERFCOUNTERS;
while (NULL != ppsd.pPerfCounterList)
{
cptr = ppsd.pPerfCounterList;
ppsd.pPerfCounterList = cptr->next;
zbx_free(cptr->name);
zbx_free(cptr->counterpath);
zbx_free(cptr->value_array);
zbx_free(cptr);
}
UNLOCK_PERFCOUNTERS;
}
/******************************************************************************
* *
* Comments: must be called only for PERF_COUNTER_ACTIVE counters, *
* interval must be less than or equal to counter->interval *
* *
******************************************************************************/
double compute_average_value(PERF_COUNTER_DATA *counter, int interval)
{
double sum = 0;
int i, j, count;
if (PERF_COUNTER_ACTIVE != counter->status || interval > counter->interval)
return 0;
if (counter->interval == interval)
return counter->sum / (double)counter->value_count;
/* compute the average manually for custom intervals */
i = counter->value_current;
count = (counter->value_count < interval ? counter->value_count : interval);
/* cycle backwards through the circular buffer of values */
for (j = 0; j < count; j++, i = (0 < i ? i - 1 : counter->interval - 1))
sum += counter->value_array[i];
return sum / (double)count;
}
int init_perf_collector(int multithreaded)
{
const char *__function_name = "init_perf_collector";
int ret = FAIL;
zabbix_log(LOG_LEVEL_DEBUG, "In %s()", __function_name);
if (0 != multithreaded)
{
if (ZBX_MUTEX_ERROR == zbx_mutex_create_force(&perfstat_access, ZBX_MUTEX_PERFSTAT))
{
zbx_error("cannot create mutex for performance counters");
exit(EXIT_FAILURE);
}
}
if (ERROR_SUCCESS != zbx_PdhOpenQuery(__function_name, &ppsd.pdh_query))
goto out;
ppsd.nextcheck = time(NULL) + UNSUPPORTED_REFRESH_PERIOD;
ret = SUCCEED;
out:
zabbix_log(LOG_LEVEL_DEBUG, "End of %s():%s", __function_name, zbx_result_string(ret));
return ret;
}
int perf_collector_started()
{
return (NULL != ppsd.pdh_query ? SUCCEED : FAIL);
}
void free_perf_collector()
{
PERF_COUNTER_DATA *cptr;
if (SUCCEED != perf_collector_started())
return;
for (cptr = ppsd.pPerfCounterList; cptr != NULL; cptr = cptr->next)
{
if (NULL != cptr->handle)
{
PdhRemoveCounter(cptr->handle);
cptr->handle = NULL;
}
}
PdhCloseQuery(ppsd.pdh_query);
ppsd.pdh_query = NULL;
free_perf_counter_list();
zbx_mutex_destroy(&perfstat_access);
}
void collect_perfstat()
{
const char *__function_name = "collect_perfstat";
PERF_COUNTER_DATA *cptr;
PDH_STATUS pdh_status;
time_t now;
PDH_FMT_COUNTERVALUE value;
zabbix_log(LOG_LEVEL_DEBUG, "In %s()", __function_name);
LOCK_PERFCOUNTERS;
if (SUCCEED != perf_collector_started())
goto out;
if (NULL == ppsd.pPerfCounterList) /* no counters */
goto out;
now = time(NULL);
/* refresh unsupported counters */
if (ppsd.nextcheck <= now)
{
for (cptr = ppsd.pPerfCounterList; NULL != cptr; cptr = cptr->next)
{
if (PERF_COUNTER_NOTSUPPORTED != cptr->status)
continue;
zbx_PdhAddCounter(__function_name, cptr, ppsd.pdh_query, cptr->counterpath, &cptr->handle);
}
ppsd.nextcheck = now + UNSUPPORTED_REFRESH_PERIOD;
}
/* query for new data */
if (ERROR_SUCCESS != (pdh_status = PdhCollectQueryData(ppsd.pdh_query)))
{
for (cptr = ppsd.pPerfCounterList; NULL != cptr; cptr = cptr->next)
{
if (PERF_COUNTER_NOTSUPPORTED != cptr->status)
deactivate_perf_counter(cptr);
}
zabbix_log(LOG_LEVEL_DEBUG, "%s() call to PdhCollectQueryData() failed: %s",
__function_name, strerror_from_module(pdh_status, L"PDH.DLL"));
goto out;
}
/* get the raw values */
for (cptr = ppsd.pPerfCounterList; NULL != cptr; cptr = cptr->next)
{
if (PERF_COUNTER_NOTSUPPORTED == cptr->status)
continue;
if (ERROR_SUCCESS != zbx_PdhGetRawCounterValue(__function_name, cptr->counterpath,
cptr->handle, &cptr->rawValues[cptr->olderRawValue]))
{
deactivate_perf_counter(cptr);
continue;
}
cptr->olderRawValue = (cptr->olderRawValue + 1) & 1;
pdh_status = PdhCalculateCounterFromRawValue(cptr->handle, PDH_FMT_DOUBLE | PDH_FMT_NOCAP100,
&cptr->rawValues[(cptr->olderRawValue + 1) & 1],
(PERF_COUNTER_INITIALIZED < cptr->status ?
&cptr->rawValues[cptr->olderRawValue] : NULL), &value);
if (ERROR_SUCCESS == pdh_status && PDH_CSTATUS_VALID_DATA != value.CStatus &&
PDH_CSTATUS_NEW_DATA != value.CStatus)
{
pdh_status = value.CStatus;
}
if (PDH_CSTATUS_INVALID_DATA == pdh_status)
{
/* some (e.g., rate) counters require two raw values, MSDN lacks documentation */
/* about what happens but tests show that PDH_CSTATUS_INVALID_DATA is returned */
cptr->status = PERF_COUNTER_GET_SECOND_VALUE;
continue;
}
/* Negative values can occur when a counter rolls over. By default, this value entry does not appear */
/* in the registry and Performance Monitor does not log data errors or notify the user that it has */
/* received bad data; More info: https://support.microsoft.com/kb/177655/EN-US */
if (PDH_CALC_NEGATIVE_DENOMINATOR == pdh_status)
{
zabbix_log(LOG_LEVEL_DEBUG, "PDH_CALC_NEGATIVE_DENOMINATOR error occurred in counterpath '%s'."
" Value ignored", cptr->counterpath);
continue;
}
if (PDH_CALC_NEGATIVE_VALUE == pdh_status)
{
zabbix_log(LOG_LEVEL_DEBUG, "PDH_CALC_NEGATIVE_VALUE error occurred in counterpath '%s'."
" Value ignored", cptr->counterpath);
continue;
}
if (ERROR_SUCCESS == pdh_status)
{
cptr->status = PERF_COUNTER_ACTIVE;
cptr->value_current = (cptr->value_current + 1) % cptr->interval
/* remove the oldest value, value_count will not increase */;
if (cptr->value_count == cptr->interval)
cptr->sum -= cptr->value_array[cptr->value_current];
cptr->value_array[cptr->value_current] = value.doubleValue;
cptr->sum += cptr->value_array[cptr->value_current];
if (cptr->value_count < cptr->interval)
cptr->value_count++;
}
else
{
zabbix_log(LOG_LEVEL_WARNING, "cannot calculate performance counter value \"%s\": %s",
cptr->counterpath, strerror_from_module(pdh_status, L"PDH.DLL"));
deactivate_perf_counter(cptr);
}
}
out:
UNLOCK_PERFCOUNTERS;
zabbix_log(LOG_LEVEL_DEBUG, "End of %s()", __function_name);
}
/******************************************************************************
* *
* Function: get_perf_counter_value_by_name *
* *
* Purpose: gets average named performance counter value *
* *
* Parameters: name - [IN] the performance counter name *
* value - [OUT] the calculated value *
* error - [OUT] the error message *
* *
* Returns: SUCCEED - the value was retrieved successfully *
* FAIL - otherwise *
* *
* Comments: The value is retrieved from collector (if it has been requested *
* before) or directly from Windows performance counters if *
* possible. *
* *
******************************************************************************/
int get_perf_counter_value_by_name(const char *name, double *value, char **error)
{
const char *__function_name = "get_perf_counter_value_by_name";
int ret = FAIL;
PERF_COUNTER_DATA *perfs = NULL;
char *counterpath = NULL;
zabbix_log(LOG_LEVEL_DEBUG, "In %s() name:%s", __function_name, name);
LOCK_PERFCOUNTERS;
if (SUCCEED != perf_collector_started())
{
*error = zbx_strdup(*error, "Performance collector is not started.");
goto out;
}
for (perfs = ppsd.pPerfCounterList; NULL != perfs; perfs = perfs->next)
{
if (NULL != perfs->name && 0 == strcmp(perfs->name, name))
{
if (PERF_COUNTER_ACTIVE != perfs->status)
break;
/* the counter data is already being collected, return it */
*value = compute_average_value(perfs, perfs->interval);
ret = SUCCEED;
goto out;
}
}
/* we can retrieve named counter data only if it has been registered before */
if (NULL == perfs)
{
*error = zbx_dsprintf(*error, "Unknown performance counter name: %s.", name);
goto out;
}
counterpath = zbx_strdup(counterpath, perfs->counterpath);
out:
UNLOCK_PERFCOUNTERS;
if (NULL != counterpath)
{
/* request counter value directly from Windows performance counters */
if (ERROR_SUCCESS == calculate_counter_value(__function_name, counterpath, value))
ret = SUCCEED;
zbx_free(counterpath);
}
zabbix_log(LOG_LEVEL_DEBUG, "End of %s():%s", __function_name, zbx_result_string(ret));
return ret;
}
/******************************************************************************
* *
* Function: get_perf_counter_value_by_path *
* *
* Purpose: gets average performance counter value *
* *
* Parameters: counterpath - [IN] the performance counter path *
* interval - [IN] the data collection interval in seconds *
* value - [OUT] the calculated value *
* error - [OUT] the error message *
* *
* Returns: SUCCEED - the value was retrieved successfully *
* FAIL - otherwise *
* *
* Comments: The value is retrieved from collector (if it has been requested *
* before) or directly from Windows performance counters if *
* possible. *
* *
******************************************************************************/
int get_perf_counter_value_by_path(const char *counterpath, int interval, double *value, char **error)
{
const char *__function_name = "get_perf_counter_value_by_path";
int ret = FAIL;
PERF_COUNTER_DATA *perfs = NULL;
zabbix_log(LOG_LEVEL_DEBUG, "In %s() path:%s interval:%d", __function_name, counterpath, interval);
LOCK_PERFCOUNTERS;
if (SUCCEED != perf_collector_started())
{
*error = zbx_strdup(*error, "Performance collector is not started.");
goto out;
}
for (perfs = ppsd.pPerfCounterList; NULL != perfs; perfs = perfs->next)
{
if (0 == strcmp(perfs->counterpath, counterpath))
{
if (perfs->interval < interval)
extend_perf_counter_interval(perfs, interval);
if (PERF_COUNTER_ACTIVE != perfs->status)
break;
/* the counter data is already being collected, return it */
*value = compute_average_value(perfs, interval);
ret = SUCCEED;
goto out;
}
}
/* if the requested counter is not already being monitored - start monitoring */
if (NULL == perfs)
perfs = add_perf_counter(NULL, counterpath, interval, error);
out:
UNLOCK_PERFCOUNTERS;
if (SUCCEED != ret && NULL != perfs)
{
/* request counter value directly from Windows performance counters */
if (ERROR_SUCCESS == calculate_counter_value(__function_name, counterpath, value))
ret = SUCCEED;
}
zabbix_log(LOG_LEVEL_DEBUG, "End of %s():%s", __function_name, zbx_result_string(ret));
return ret;
}
/******************************************************************************
* *
* Function: get_perf_counter_value *
* *
* Purpose: gets average value of the specified performance counter interval *
* *
* Parameters: counter - [IN] the performance counter *
* interval - [IN] the data collection interval in seconds *
* value - [OUT] the calculated value *
* error - [OUT] the error message *
* *
* Returns: SUCCEED - the value was retrieved successfully *
* FAIL - otherwise *
* *
******************************************************************************/
int get_perf_counter_value(PERF_COUNTER_DATA *counter, int interval, double *value, char **error)
{
const char *__function_name = "get_perf_counter_value";
int ret = FAIL;
zabbix_log(LOG_LEVEL_DEBUG, "In %s() path:%s interval:%d", __function_name, counter->counterpath, interval);
LOCK_PERFCOUNTERS;
if (SUCCEED != perf_collector_started())
{
*error = zbx_strdup(*error, "Performance collector is not started.");
goto out;
}
if (PERF_COUNTER_ACTIVE != counter->status)
{
*error = zbx_strdup(*error, "Performance counter is not ready.");
goto out;
}
*value = compute_average_value(counter, interval);
ret = SUCCEED;
out:
UNLOCK_PERFCOUNTERS;
zabbix_log(LOG_LEVEL_DEBUG, "End of %s():%s", __function_name, zbx_result_string(ret));
return ret;
}
|
Luzifer/twitch-bot | internal/actors/respond/actor.go | <filename>internal/actors/respond/actor.go
package respond
import (
"fmt"
"strings"
"github.com/go-irc/irc"
"github.com/pkg/errors"
log "github.com/sirupsen/logrus"
"github.com/Luzifer/twitch-bot/plugins"
)
const actorName = "respond"
var (
formatMessage plugins.MsgFormatter
ptrBoolFalse = func(v bool) *bool { return &v }(false)
)
func Register(args plugins.RegistrationArguments) error {
formatMessage = args.FormatMessage
args.RegisterActor(actorName, func() plugins.Actor { return &actor{} })
args.RegisterActorDocumentation(plugins.ActionDocumentation{
Description: "Respond to message with a new message",
Name: "Respond to Message",
Type: "respond",
Fields: []plugins.ActionDocumentationField{
{
Default: "",
Description: "Message text to send",
Key: "message",
Long: true,
Name: "Message",
Optional: false,
SupportTemplate: true,
Type: plugins.ActionDocumentationFieldTypeString,
},
{
Default: "",
Description: "Fallback message text to send if message cannot be generated",
Key: "fallback",
Name: "Fallback",
Optional: true,
SupportTemplate: true,
Type: plugins.ActionDocumentationFieldTypeString,
},
{
Default: "false",
Description: "Send message as a native Twitch-reply to the original message",
Key: "as_reply",
Name: "As Reply",
Optional: true,
SupportTemplate: false,
Type: plugins.ActionDocumentationFieldTypeBool,
},
{
Default: "",
Description: "Send message to a different channel than the original message",
Key: "to_channel",
Name: "To Channel",
Optional: true,
SupportTemplate: false,
Type: plugins.ActionDocumentationFieldTypeString,
},
},
})
return nil
}
type actor struct{}
func (a actor) Execute(c *irc.Client, m *irc.Message, r *plugins.Rule, eventData *plugins.FieldCollection, attrs *plugins.FieldCollection) (preventCooldown bool, err error) {
msg, err := formatMessage(attrs.MustString("message", nil), m, r, eventData)
if err != nil {
if !attrs.CanString("fallback") || attrs.MustString("fallback", nil) == "" {
return false, errors.Wrap(err, "preparing response")
}
log.WithError(err).Error("Response message processing caused error, trying fallback")
if msg, err = formatMessage(attrs.MustString("fallback", nil), m, r, eventData); err != nil {
return false, errors.Wrap(err, "preparing response fallback")
}
}
toChannel := plugins.DeriveChannel(m, eventData)
if attrs.CanString("to_channel") && attrs.MustString("to_channel", nil) != "" {
toChannel = fmt.Sprintf("#%s", strings.TrimLeft(attrs.MustString("to_channel", nil), "#"))
}
ircMessage := &irc.Message{
Command: "PRIVMSG",
Params: []string{
toChannel,
msg,
},
}
if attrs.MustBool("as_reply", ptrBoolFalse) {
id, ok := m.GetTag("id")
if ok {
if ircMessage.Tags == nil {
ircMessage.Tags = make(irc.Tags)
}
ircMessage.Tags["reply-parent-msg-id"] = irc.TagValue(id)
}
}
return false, errors.Wrap(
c.WriteMessage(ircMessage),
"sending response",
)
}
func (a actor) IsAsync() bool { return false }
func (a actor) Name() string { return actorName }
func (a actor) Validate(attrs *plugins.FieldCollection) (err error) {
if v, err := attrs.String("message"); err != nil || v == "" {
return errors.New("message must be non-empty string")
}
return nil
}
|
martiancrow/x12_engine | src/x12_engine_lib/src/x12_even_drivers.h | <filename>src/x12_engine_lib/src/x12_even_drivers.h
/*
*
*Copyright (C) 刘晓龙
*Copyright (C) 昆明黑海科技有限公司
*
*
*/
/*
*x12 engine 事件设备列表
*
*
*作者:Crow
*时间:2016-11-13
*最后修改时间:2016-11-13
*/
#ifndef _X12_EVEN_DRIVERS_H_INCLUDE_
#define _X12_EVEN_DRIVERS_H_INCLUDE_
#include "x12_pthread.h"
#define driverlist_align(d, a) (((d) + (a - 1)) & ~(a - 1)) //内存对齐
#define DRIVERLIST_DEF_BLOCK_SIZE 128 //默认数据块大小
typedef int even_drivers_size_t;
typedef struct x12_even_driver_s x12_even_driver_t;
typedef struct x12_even_driverlist_s x12_even_driverlist_t;
struct x12_even_driver_s
{
void* linkdata; //链接数据
int datalen; //链接数据长度
int driverid; //设备id
unsigned short eventype; //事件类型
};
struct x12_even_driverlist_s
{
int *nullid; //空id列表
even_drivers_size_t nullidoffset; //空id偏移量
even_drivers_size_t nullidsize; //空id指针长度
x12_even_driver_t *driverlist; //设备列表
even_drivers_size_t dataoffset; //最后位置偏移量
even_drivers_size_t drivercount; //在编设备总数
even_drivers_size_t listsize; //列表分配大小
even_drivers_size_t blocksize; //默认块大小
x12_pthread_mutex_t mutex; //设备列表互斥锁
};
/*
* Function: x12_even_drivers_init
*
* 初始化设备队列
*
* Returns:
* 成功 - 0
* 失败 - -1
*
* See Also:
*
*/
extern char x12_even_drivers_init(void);
/*
* Function: x12_even_drivers_destroy
*
* 销毁设备列表
*
* See Also:
*
*/
extern void x12_even_drivers_destroy(void);
/*
* Function: x12_even_drivers_search
*
* 查找设备
*
* Parameters:
* _id - 设备id
*
* Returns:
* 成功 - 设备数据
* 失败 - null
*
* See Also:
*
*/
extern x12_even_driver_t* x12_even_drivers_search(int _id);
/*
* Function: x12_even_drivers_add
*
* 添加设备
*
* Parameters:
* _id - 设备id
* _datalink - 链接数据
* _eventype - 事件类型
*
* Returns:
* 成功 - 0
* 失败 - -1
* 重复 - -2
*
* See Also:
*
*/
extern char x12_even_drivers_add(int *_id, void* _linkdata, int _datalen, unsigned short _eventype);
/*
* Function: x12_even_drivers_del
*
* 删除设备
*
* Parameters:
* _id - 设备id
*
* Returns:
* 成功 - 0
* 失败 - -1
*
* See Also:
*
*/
extern char x12_even_drivers_del(int _id);
#endif
|
l2silver/imp_pat | src/FollowingPanel/constants.js | <reponame>l2silver/imp_pat
// @flow
export const followingPanelId = 'followingPanelId'; |
yanzhe-chen/LeetCode | include/BinaryTreePaths.hpp | <reponame>yanzhe-chen/LeetCode
#ifndef BINARY_TREE_PATHS_HPP_
#define BINARY_TREE_PATHS_HPP_
#include <vector>
#include <string>
#include "TreeNode.hpp"
using namespace std;
class BinaryTreePaths {
public:
vector<string> binaryTreePaths(TreeNode *root);
private:
void dfs(TreeNode *root, string path, vector<string> &ret);
};
#endif // BINARY_TREE_PATHS_HPP_ |
ekaitz-zarraga/jehanne | sys/src/lib/sec/port/curve25519_dh.c | <filename>sys/src/lib/sec/port/curve25519_dh.c<gh_stars>100-1000
#include "os.h"
#include <mp.h>
#include <libsec.h>
static uint8_t nine[32] = {9};
void
curve25519_dh_new(uint8_t x[32], uint8_t y[32])
{
uint8_t b;
/* new public/private key pair */
genrandom(x, 32);
b = x[31];
x[0] &= ~7; /* clear bit 0,1,2 */
x[31] = 0x40 | (b & 0x7f); /* set bit 254, clear bit 255 */
curve25519(y, x, nine);
/* bit 255 is always 0, so make it random */
y[31] |= b & 0x80;
}
void
curve25519_dh_finish(uint8_t x[32], uint8_t y[32], uint8_t z[32])
{
/* remove the random bit */
y[31] &= 0x7f;
/* calculate dhx key */
curve25519(z, x, y);
jehanne_memset(x, 0, 32);
jehanne_memset(y, 0, 32);
}
|
ZDW6060/JZOffer | src/easy/JZ5/Solution.java | package easy.JZ5;
import java.util.Stack;
public class Solution {
Stack<Integer> stack1 = new Stack<Integer>();
Stack<Integer> stack2 = new Stack<Integer>();
public void push(int node) {
stack1.push(node);
}
public int pop() {
if(stack2.size()==0){
while(stack1.size()!=0){
stack2.push(stack1.pop());
}
}
return stack2.pop();
}
}
|
gavinband/bingwa | genfile/include/genfile/utility.hpp |
// Copyright <NAME> 2008 - 2012.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#ifndef GENFILE_UTILITY_HPP
#define GENFILE_UTILITY_HPP
#include <vector>
#include <algorithm>
#include <iterator>
namespace genfile {
namespace utility {
// function: select_entries
// Return a vector having only the entries from the given vector whose index lies in the
// second argument.
template< typename V >
std::vector< V > select_entries( std::vector< V > const& container, std::vector< std::size_t > const& indices ) {
std::vector< V > result( indices.size() ) ;
for( std::size_t i = 0; i < indices.size(); ++i ) {
assert( indices[i] < container.size() ) ;
result[i] = container[ indices[i] ] ;
}
return result ;
}
// function: select_entries
// Return a vector having only those entries of the first argument for which the corresponding entry of the
// second argument is true.
template< typename V >
std::vector< V > select_entries( std::vector< V > const& container, std::vector< bool > const& filter ) {
assert( container.size() == filter.size() ) ;
std::vector< V > result ;
result.reserve( container.size() ) ;
for( std::size_t i = 0; i < container.size(); ++i ) {
if( filter[i] ) {
result.push_back( container[i] ) ;
}
}
return result ;
}
template< typename S >
S intersect( S const& set1, S const& set2 ) {
S result ;
std::set_intersection(
set1.begin(), set1.end(),
set2.begin(), set2.end(),
std::inserter( result, result.end() )
) ;
return result ;
}
}
}
#endif
|
okertanov/Developer-Tools-for-UPnP-Technologies | Samples/EmbeddedSamples/MicroDMR/Resources/NewMicroAvServer/TypeLibs/CWMPControls.h | // CWMPControls.h : Declaration of ActiveX Control wrapper class(es) created by Microsoft Visual C++
#pragma once
/////////////////////////////////////////////////////////////////////////////
// CWMPControls
class CWMPControls : public COleDispatchDriver
{
public:
CWMPControls() {} // Calls COleDispatchDriver default constructor
CWMPControls(LPDISPATCH pDispatch) : COleDispatchDriver(pDispatch) {}
CWMPControls(const CWMPControls& dispatchSrc) : COleDispatchDriver(dispatchSrc) {}
// Attributes
public:
// Operations
public:
BOOL get_isAvailable(LPCTSTR bstrItem)
{
BOOL result;
static BYTE parms[] = VTS_BSTR ;
InvokeHelper(0x3e, DISPATCH_PROPERTYGET, VT_BOOL, (void*)&result, parms, bstrItem);
return result;
}
void play()
{
InvokeHelper(0x33, DISPATCH_METHOD, VT_EMPTY, NULL, NULL);
}
void stop()
{
InvokeHelper(0x34, DISPATCH_METHOD, VT_EMPTY, NULL, NULL);
}
void pause()
{
InvokeHelper(0x35, DISPATCH_METHOD, VT_EMPTY, NULL, NULL);
}
void fastForward()
{
InvokeHelper(0x36, DISPATCH_METHOD, VT_EMPTY, NULL, NULL);
}
void fastReverse()
{
InvokeHelper(0x37, DISPATCH_METHOD, VT_EMPTY, NULL, NULL);
}
double get_currentPosition()
{
double result;
InvokeHelper(0x38, DISPATCH_PROPERTYGET, VT_R8, (void*)&result, NULL);
return result;
}
void put_currentPosition(double newValue)
{
static BYTE parms[] = VTS_R8 ;
InvokeHelper(0x38, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, newValue);
}
CString get_currentPositionString()
{
CString result;
InvokeHelper(0x39, DISPATCH_PROPERTYGET, VT_BSTR, (void*)&result, NULL);
return result;
}
void next()
{
InvokeHelper(0x3a, DISPATCH_METHOD, VT_EMPTY, NULL, NULL);
}
void previous()
{
InvokeHelper(0x3b, DISPATCH_METHOD, VT_EMPTY, NULL, NULL);
}
LPDISPATCH get_currentItem()
{
LPDISPATCH result;
InvokeHelper(0x3c, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, NULL);
return result;
}
void put_currentItem(LPDISPATCH newValue)
{
static BYTE parms[] = VTS_DISPATCH ;
InvokeHelper(0x3c, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, newValue);
}
long get_currentMarker()
{
long result;
InvokeHelper(0x3d, DISPATCH_PROPERTYGET, VT_I4, (void*)&result, NULL);
return result;
}
void put_currentMarker(long newValue)
{
static BYTE parms[] = VTS_I4 ;
InvokeHelper(0x3d, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, newValue);
}
void playItem(LPDISPATCH pIWMPMedia)
{
static BYTE parms[] = VTS_DISPATCH ;
InvokeHelper(0x3f, DISPATCH_METHOD, VT_EMPTY, NULL, parms, pIWMPMedia);
}
};
|
exKAZUu-Research/SmartMotivator | server/app/models/prediction_model.rb | <filename>server/app/models/prediction_model.rb
# == Schema Information
#
# Table name: prediction_models
#
# id :integer not null, primary key
# dump_data :binary not null
# trained_at :datetime
#
require 'open3'
class PredictionModel < ApplicationRecord
RECOMMENDATION_DIRECTORY = "#{Rails.root}/scripts/recommendation"
def self.first_or_default
prediction_model = first_or_initialize
if prediction_model.dump_data.nil?
prediction_model.reset
prediction_model.save!
end
prediction_model
end
def train
Dir.chdir(RECOMMENDATION_DIRECTORY) do
begin
connection = ActiveRecord::Base.connection
query = "COPY users TO '#{RECOMMENDATION_DIRECTORY}/users.csv' WITH DELIMITER ',' CSV HEADER"
connection.execute(query)
query = "COPY (SELECT * FROM user_data WHERE kind IN ('logSetting', 'survey', 'quiz')) TO
'#{RECOMMENDATION_DIRECTORY}/user_data.csv' WITH DELIMITER ',' CSV HEADER"
connection.execute(query)
command = "python3 train.py ./users.csv ./user_data.csv"
res, err_text, exit_status = Open3.capture3(command, binmode: true)
if exit_status == 0
self.dump_data = res
self.trained_at = Time.now
else
raise err_text.force_encoding('UTF-8')
end
rescue => e
Rails.logger.error e
raise e
ensure
FileUtils.rm('users.csv')
FileUtils.rm('user_data.csv')
end
end
end
def reset
model_dump = File.binread("#{RECOMMENDATION_DIRECTORY}/model_default")
self.dump_data = model_dump
self.trained_at = nil
end
def recommended_setting(survey_values)
Dir.chdir(RECOMMENDATION_DIRECTORY) do
command = "python3 recommend.py '#{survey_values}'"
res_text, err_text, exit_status = Open3.capture3(command, stdin_data: dump_data, binmode: true)
if exit_status.success?
if err_text.present?
Rails.logger.warn(err_text)
end
begin
JSON.parse(res_text)
rescue => e
Rails.logger.error(e)
{}
end
else
Rails.logger.error(res_text) if res_text.present?
Rails.logger.error(err_text) if err_text.present?
{}
end
end
end
end
|
js-lib-com/js-lib | test/js/tests/dom/template/MapOperatorUnitTests.js | <gh_stars>0
$package("js.tests.template");
js.tests.template.MapOperatorUnitTests = {
testSupportedPrimitiveTypes : function () {
var html = "" + //
"<dl data-map='.'>" + //
" <dt data-text='.'></dt>" + //
" <dd data-text='.'></dd>" + //
"</dl>";
var model = {
key0 : 22,
key1 : true,
key2 : "string"
};
var doc = this.run(html, model);
var elist = doc.findByTag("dt");
assertEquals("key0", elist, 0);
assertEquals("key1", elist, 1);
assertEquals("key2", elist, 2);
elist = doc.findByTag("dd");
assertEquals("22", elist, 0);
assertEquals("true", elist, 1);
assertEquals("string", elist, 2);
},
testSupportedValueTypes : function () {
var html = "" + //
"<dl data-map='.'>" + //
" <dt data-text='.'></dt>" + //
" <dd data-text='.'></dd>" + //
"</dl>";
var model = {
key0 : "string",
key1 : 1234,
key2 : true,
key3 : new Date(1964, 2, 15, 14, 30)
};
var doc = this.run(html, model);
var elist = doc.findByTag("dt");
assertEquals(4, elist.size());
assertEquals("key0", elist, 0);
assertEquals("key1", elist, 1);
assertEquals("key2", elist, 2);
assertEquals("key3", elist, 3);
elist = doc.findByTag("dd");
assertEquals(4, elist.size());
assertEquals("string", elist, 0);
assertEquals("1234", elist, 1);
assertEquals("true", elist, 2);
assertEquals(new Date(1964, 2, 15, 14, 30).toString(), elist, 3);
},
testMapOfObjects : function () {
var html = "" + //
"<dl data-map='map'>" + //
" <dt data-text='.'></dt>" + //
" <dd data-object='.'>" + //
" <h2 data-text='title'></h2>" + //
" </dd>" + //
"</dl>";
var model = {
map : {
key0 : {
title : "title0"
},
key1 : {
title : "title1"
}
}
};
var doc = this.run(html, model);
var elist = doc.findByTag("dt");
assertEquals("key0", elist, 0);
assertEquals("key1", elist, 1);
elist = doc.findByTag("h2");
assertEquals("title0", elist, 0);
assertEquals("title1", elist, 1);
},
testAnonymousMap : function () {
var html = "" + //
"<dl data-map='.'>" + //
" <dt data-text='.'></dt>" + //
" <dd data-object='.'>" + //
" <h2 data-text='title'></h2>" + //
" </dd>" + //
"</dl>";
var model = {
key0 : {
title : "title0"
},
key1 : {
title : "title1"
}
};
var doc = this.run(html, model);
var elist = doc.findByTag("dt");
assertEquals("key0", elist, 0);
assertEquals("key1", elist, 1);
elist = doc.findByTag("h2");
assertEquals("title0", elist, 0);
assertEquals("title1", elist, 1);
},
testMapOfPrimitives : function () {
var html = "" + //
"<dl data-map='map'>" + //
" <dt data-text='.'></dt>" + //
" <dd data-text='.'></dd>" + //
"</dl>";
var model = {
map : {
key0 : 0,
key1 : 1
}
};
var doc = this.run(html, model);
var elist = doc.findByTag("dt");
assertEquals("key0", elist, 0);
assertEquals("key1", elist, 1);
elist = doc.findByTag("dd");
assertEquals("0", elist, 0);
assertEquals("1", elist, 1);
},
testMapOfLists : function () {
var html = "" + //
"<dl data-map='map'>" + //
" <dt data-text='.'></dt>" + //
" <dd data-object='.'>" + //
" <ul data-list='.'>" + //
" <li data-object='.'>" + //
" <h2 data-text='title'></h2>" + //
" </li>" + //
" </ul>" + //
" </dd>" + //
"</dl>";
var model = {
map : {
key0 : [ {
title : "title00"
}, {
title : "title01"
} ],
key1 : [ {
title : "title10"
}, {
title : "title11"
} ]
}
};
var doc = this.run(html, model);
var elist = doc.findByTag("dt");
assertEquals("key0", elist, 0);
assertEquals("key1", elist, 1);
elist = doc.findByTag("h2");
assertEquals("title00", elist, 0);
assertEquals("title01", elist, 1);
assertEquals("title10", elist, 2);
assertEquals("title11", elist, 3);
},
testNestedMaps : function () {
var html = "" + //
"<dl data-map='map'>" + //
" <dt data-text='.'></dt>" + //
" <dd data-object='.'>" + //
" <h2 data-text='title'></h2>" + //
" <div data-map='map'>" + //
" <p data-text='.'></p>" + //
" <div data-object='.'>" + //
" <h3 data-text='title'></h3>" + //
" </div>" + //
" </div>" + //
" </dd>" + //
"</dl>";
var model = {
map : {
key0 : {
title : "title0",
map : {
key00 : {
title : "title00"
},
key01 : {
title : "title01"
}
}
},
key1 : {
title : "title1",
map : {
key10 : {
title : "title10"
},
key11 : {
title : "title11"
}
}
}
}
};
var doc = this.run(html, model);
var elist = doc.findByTag("dt");
assertEquals("key0", elist, 0);
assertEquals("key1", elist, 1);
elist = doc.findByTag("h2");
assertEquals("title0", elist, 0);
assertEquals("title1", elist, 1);
elist = doc.findByTag("p");
assertEquals("key00", elist, 0);
assertEquals("key01", elist, 1);
assertEquals("key10", elist, 2);
assertEquals("key11", elist, 3);
elist = doc.findByTag("h3");
assertEquals("title00", elist, 0);
assertEquals("title01", elist, 1);
assertEquals("title10", elist, 2);
assertEquals("title11", elist, 3);
},
testMapOfDefaultPrimitives : function () {
var html = "" + //
"<dl data-map='map'>" + //
" <dt></dt>" + //
" <dd></dd>" + //
"</dl>";
var model = {
map : {
key0 : 0,
key1 : 1
}
};
var doc = this.run(html, model);
var elist = doc.findByTag("dt");
assertEquals("key0", elist, 0);
assertEquals("key1", elist, 1);
elist = doc.findByTag("dd");
assertEquals("0", elist, 0);
assertEquals("1", elist, 1);
},
testMapOfDefaultObjects : function () {
var html = "" + //
"<dl data-map='map'>" + //
" <dt></dt>" + //
" <dd>" + //
" <h2 data-text='title'></h2>" + //
" </dd>" + //
"</dl>";
var model = {
map : {
key0 : {
title : "title0"
},
key1 : {
title : "title1"
}
}
};
var doc = this.run(html, model);
var elist = doc.findByTag("dt");
assertEquals("key0", elist, 0);
assertEquals("key1", elist, 1);
elist = doc.findByTag("h2");
assertEquals("title0", elist, 0);
assertEquals("title1", elist, 1);
},
testReinjection : function () {
var html, doc, root, template, elist;
[ "map", "omap" ].forEach(function (mapType) {
html = $format("<dl data-%s='.'><dt></dt><dd></dd></dl>", mapType);
document.getElementById("scratch-area").innerHTML = html;
doc = new js.dom.Document(document);
root = doc.getById("scratch-area");
template = js.dom.template.Template.getInstance(doc);
template.inject({
key0 : 1,
key1 : 2
});
elist = root.findByTag("dd");
assertEquals(2, elist.size());
assertEquals("1", elist, 0);
assertEquals("2", elist, 1);
template.inject({});
elist = root.findByTag("dd");
assertEquals(0, elist.size());
template.inject({
key0 : 'a',
key1 : 'b'
});
elist = root.findByTag("dd");
assertEquals(2, elist.size());
assertEquals("a", elist, 0);
assertEquals("b", elist, 1);
});
},
testMapWithoutChildren : function () {
[ "map", "omap" ].forEach(function (mapType) {
assertAssertion(this, "run", $format("<dl data-%s='.'></dl>", mapType), []);
}, this);
},
testNullMapValue : function () {
var doc;
[ "map", "omap" ].forEach(function (mapType) {
doc = this.run($format("<dl data-%s='items'><dt></dt><dd></dd></dl>", mapType), {
items : null
});
assertEquals(0, doc.findByTag("dt").size());
assertEquals(0, doc.findByTag("dd").size());
}, this);
},
testBadMapValueTypes : function (context) {
context.push("js.dom.template.ContentException");
js.dom.template.ContentException = function (propertyPath, message) {
assertEquals(".", propertyPath);
assertEquals(0, message.indexOf("Invalid content type."));
};
var invalidValues = [ 123, "q", true, [], function () {
} ];
var html, i, doc;
[ "map", "omap" ].forEach(function (mapType) {
html = $format("<dl data-%s='.'><dt></dt><dd></dd></dl>", mapType);
for (i = 0; i < invalidValues.length; ++i) {
var warn = $warn;
var messageProbe;
$warn = function (sourceName, format, text, error) {
messageProbe = $format(format, text, error);
}
this.run(html, invalidValues[i]);
$warn = warn;
assertTrue(messageProbe.indexOf("Undefined or invalid property") === 0);
}
}, this);
$assert.disable();
[ "map", "omap" ].forEach(function (mapType) {
html = $format("<dl data-%s='.'><dt></dt><dd></dd></dl>", mapType);
for (i = 0; i < invalidValues.length; ++i) {
doc = this.run(html, invalidValues[i]);
assertEquals(0, doc.findByTag("dt").size());
assertEquals(0, doc.findByTag("dd").size());
}
}, this);
},
// ------------------------------------------------------
// fixture initialization and helpers
run : function (html, content) {
document.getElementById("scratch-area").innerHTML = html;
var doc = new js.dom.Document(document);
var root = doc.getById("scratch-area");
var template = js.dom.template.Template.getInstance(doc);
template.inject(content);
return root;
},
after : function () {
var n = document.getElementById("scratch-area");
while (n.firstChild) {
n.removeChild(n.firstChild);
}
}
};
TestCase.register("js.tests.template.MapOperatorUnitTests");
function assertEquals (expected, elist, index) {
// expected, elist, index
if (arguments.length === 3 && typeof arguments[2] === "number") {
assertEquals(expected, elist.item(index).getText().trim());
return;
}
// expected, concrete, message
var concrete = arguments[1];
if (expected !== concrete) {
TestCase.fail(_reason(arguments, 2, "Assert equals fails. Expected [%s] but got [%s].", expected, concrete));
}
}
|
alteholz/gomfa | ut1tai_test.go | <gh_stars>0
package gomfa
import (
"testing"
)
func BenchmarkUt1tai(b *testing.B) {
var a1, a2 float64
for i := 0; i < 10000000; i++ {
_ = Ut1tai(2453750.5, 0.892104561, -32.6659, &a1, &a2)
}
}
func TestUt1tai(t *testing.T) {
var a1, a2 float64
var j int
j = Ut1tai(2453750.5, 0.892104561, -32.6659, &a1, &a2)
if j != 0 {
t.Errorf("j != 0\n")
}
if !CheckFloat(a1, 2453750.5, 1e-6) {
t.Errorf("a1 != 2453750.5 -> %v\n", a1)
}
if !CheckFloat(a2, 0.8924826385462962963, 1e-12) {
t.Errorf("a2 != 0.8924826385462962963 -> %v\n", a2)
}
}
|
tsaurabh74/peregrine-cms | platform/base/core/src/test/java/com/peregrine/sitemap/impl/EtcMapUrlExternalizerTest.java | <gh_stars>10-100
package com.peregrine.sitemap.impl;
import com.peregrine.SlingResourcesTest;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.runners.MockitoJUnitRunner;
import static org.junit.Assert.assertEquals;
@RunWith(MockitoJUnitRunner.class)
public final class EtcMapUrlExternalizerTest extends SlingResourcesTest {
private final EtcMapUrlExternalizer model = new EtcMapUrlExternalizer();
@Test
public void map() {
final String url = "/content/page.html";
final String mappedUrl = "http://www.example.com/page.html";
repo.map(url, mappedUrl);
assertEquals(mappedUrl, model.map(resourceResolver, url));
}
} |
confine-sandbox/jsisolate-confine-runtime | index.js | <gh_stars>1-10
const { CjsIsolate, EsmIsolate } = require('./lib/isolate.js')
const { AbstractConfineRuntime} = require('abstract-confine-runtime')
const path = require('path')
module.exports = class JsIsolateConfineRuntime extends AbstractConfineRuntime {
constructor (opts) {
super(opts)
this.isolate = undefined
}
async init () {
if (this.opts.path && !path.isAbsolute(this.opts.path)) {
throw new Error('Path option must be an absolute path')
}
if (this.opts.module === 'esm') {
this.isolate = new EsmIsolate(this.source.toString('utf-8'), {
path: this.opts.path || '/tmp/script.js',
env: this.opts.env,
globals: this.opts.globals,
disableImports: this.opts.esm?.disableImports
})
} else {
this.isolate = new CjsIsolate(this.source.toString('utf-8'), {
path: this.opts.path || '/tmp/script.js',
env: this.opts.env,
globals: this.opts.globals,
requires: this.opts.cjs?.requires
})
}
this.isolate.on('closed', () => {
this.emit('closed', this.isolate.exitCode || 0)
})
await this.isolate.open()
}
async run () {
try {
await this.isolate.run()
} catch (e) {
if (e.message === 'Isolate was disposed during execution') {
// caused by process.exit(), ignore
return
}
throw e
}
}
async close () {
this.isolate.close()
}
describeAPI () {
return this.isolate.describeAPI()
}
async handleAPICall (methodName, params) {
return this.isolate.handleAPICall(methodName, params)
}
}
|
TheRakeshPurohit/CodingSpectator | plug-ins/indigo/org.eclipse.jdt.core/model/org/eclipse/jdt/core/ISourceManipulation.java | <gh_stars>1-10
/*******************************************************************************
* Copyright (c) 2000, 2009 IBM Corporation and others.
* 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:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.core;
import org.eclipse.core.runtime.IProgressMonitor;
/**
* Common protocol for Java elements that support source code manipulations such
* as copy, move, rename, and delete.
*
* @noimplement This interface is not intended to be implemented by clients.
*/
public interface ISourceManipulation {
/**
* Copies this element to the given container.
*
* @param container the container
* @param sibling the sibling element before which the copy should be inserted,
* or <code>null</code> if the copy should be inserted as the last child of
* the container
* @param rename the new name for the element, or <code>null</code> if the copy
* retains the name of this element
* @param replace <code>true</code> if any existing child in the container with
* the target name should be replaced, and <code>false</code> to throw an
* exception in the event of a name collision
* @param monitor a progress monitor
* @exception JavaModelException if this element could not be copied. Reasons include:
* <ul>
* <li> This Java element, container element, or sibling does not exist (ELEMENT_DOES_NOT_EXIST)</li>
* <li> A <code>CoreException</code> occurred while updating an underlying resource
* <li> The container is of an incompatible type (INVALID_DESTINATION)
* <li> The sibling is not a child of the given container (INVALID_SIBLING)
* <li> The new name is invalid (INVALID_NAME)
* <li> A child in the container already exists with the same name (NAME_COLLISION)
* and <code>replace</code> has been specified as <code>false</code>
* <li> The container or this element is read-only (READ_ONLY)
* </ul>
*
* @exception IllegalArgumentException if container is <code>null</code>
* @see org.eclipse.jdt.core.IJavaModelStatusConstants#INVALID_DESTINATION
*/
void copy(IJavaElement container, IJavaElement sibling, String rename, boolean replace, IProgressMonitor monitor) throws JavaModelException;
/**
* Deletes this element, forcing if specified and necessary.
*
* @param force a flag controlling whether underlying resources that are not
* in sync with the local file system will be tolerated (same as the force flag
* in IResource operations).
* @param monitor a progress monitor
* @exception JavaModelException if this element could not be deleted. Reasons include:
* <ul>
* <li> This Java element does not exist (ELEMENT_DOES_NOT_EXIST)</li>
* <li> A <code>CoreException</code> occurred while updating an underlying resource (CORE_EXCEPTION)</li>
* <li> This element is read-only (READ_ONLY)</li>
* </ul>
*/
void delete(boolean force, IProgressMonitor monitor) throws JavaModelException;
/**
* Moves this element to the given container.
*
* @param container the container
* @param sibling the sibling element before which the element should be inserted,
* or <code>null</code> if the element should be inserted as the last child of
* the container
* @param rename the new name for the element, or <code>null</code> if the
* element retains its name
* @param replace <code>true</code> if any existing child in the container with
* the target name should be replaced, and <code>false</code> to throw an
* exception in the event of a name collision
* @param monitor a progress monitor
* @exception JavaModelException if this element could not be moved. Reasons include:
* <ul>
* <li> This Java element, container element, or sibling does not exist (ELEMENT_DOES_NOT_EXIST)</li>
* <li> A <code>CoreException</code> occurred while updating an underlying resource
* <li> The container is of an incompatible type (INVALID_DESTINATION)
* <li> The sibling is not a child of the given container (INVALID_SIBLING)
* <li> The new name is invalid (INVALID_NAME)
* <li> A child in the container already exists with the same name (NAME_COLLISION)
* and <code>replace</code> has been specified as <code>false</code>
* <li> The container or this element is read-only (READ_ONLY)
* </ul>
*
* @exception IllegalArgumentException if container is <code>null</code>
* @see org.eclipse.jdt.core.IJavaModelStatusConstants#INVALID_DESTINATION
*/
void move(IJavaElement container, IJavaElement sibling, String rename, boolean replace, IProgressMonitor monitor) throws JavaModelException;
/**
* Renames this element to the given name.
*
* @param name the new name for the element
* @param replace <code>true</code> if any existing element with the target name
* should be replaced, and <code>false</code> to throw an exception in the
* event of a name collision
* @param monitor a progress monitor
* @exception JavaModelException if this element could not be renamed. Reasons include:
* <ul>
* <li> This Java element does not exist (ELEMENT_DOES_NOT_EXIST)</li>
* <li> A <code>CoreException</code> occurred while updating an underlying resource
* <li> The new name is invalid (INVALID_NAME)
* <li> A child in the container already exists with the same name (NAME_COLLISION)
* and <code>replace</code> has been specified as <code>false</code>
* <li> This element is read-only (READ_ONLY)
* </ul>
*/
void rename(String name, boolean replace, IProgressMonitor monitor) throws JavaModelException;
}
|
rlucioda/freejob | src/test/java/io/freejob/domain/EventoTest.java | package io.freejob.domain;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
import io.freejob.web.rest.TestUtil;
public class EventoTest {
@Test
public void equalsVerifier() throws Exception {
TestUtil.equalsVerifier(Evento.class);
Evento evento1 = new Evento();
evento1.setId(1L);
Evento evento2 = new Evento();
evento2.setId(evento1.getId());
assertThat(evento1).isEqualTo(evento2);
evento2.setId(2L);
assertThat(evento1).isNotEqualTo(evento2);
evento1.setId(null);
assertThat(evento1).isNotEqualTo(evento2);
}
}
|
SquaredLabs/nucore-open | app/helpers/timeline_helper.rb | # frozen_string_literal: true
module TimelineHelper
def reservation_classes(reservation, product = nil)
classes = ["unit"]
if reservation.product == product
classes << "tip" unless reservation.blackout?
else
classes << "other-product"
end
classes << "blackout" if reservation.blackout?
classes << "admin" if reservation.admin?
classes << "behalf_of" if reservation.ordered_on_behalf_of?
classes << "in_progress" if reservation.can_switch_instrument?
classes << "status_#{display_status_class(reservation.order_detail)}" if reservation.order_detail
classes.concat spans_midnight_class(reservation.reserve_start_at, reservation.reserve_end_at)
classes.join(" ")
end
MINUTE_TO_PIXEL_RATIO = 0.6
def datetime_left_position(display_date, datetime)
# don't start before midnight of the display_date
time_to_use = [datetime, display_date.beginning_of_day].max
"#{((time_to_use - display_date.beginning_of_day) / 60 * MINUTE_TO_PIXEL_RATIO).floor}px"
end
def datetime_width(display_date, datetime_start, datetime_end)
# cut off the beginning if it starts before midnight
start_datetime_to_use = [datetime_start, display_date.beginning_of_day].max
# cut it off at midnight of start day if end time goes into the next day
end_datetime_to_use = [datetime_end, display_date.end_of_day].min
# In Ruby 1.8.7, the subtraction leads to a .99999 value, so go ahead and round that off
"#{((end_datetime_to_use - start_datetime_to_use).round(4) / 60 * MINUTE_TO_PIXEL_RATIO).floor}px"
end
def reservation_width(display_date, reservation)
datetime_width(display_date, reservation.display_start_at, reservation.display_end_at)
end
def reservation_left_position(display_date, reservation)
datetime_left_position(display_date, reservation.display_start_at)
end
def spans_midnight_class(datetime_start, datetime_end)
classes = []
classes << "runs_into_tomorrow" if datetime_end > @display_datetime.end_of_day
classes << "runs_into_yesterday" if datetime_start < @display_datetime.beginning_of_day
classes
end
def reservation_user_display(reservation)
if reservation.offline?
t(".offline_reservation")
elsif reservation.admin?
t(".admin_reservation")
else
reservation.user
end
end
def reservation_date_range_display(date, reservation)
# start = date.beginning_of_day >= reservation.display_start_at ?
"#{reservation_date_in_day(date, reservation.display_start_at)} – #{reservation_date_in_day(date, reservation.display_end_at)}".html_safe
end
def reservation_date_in_day(day_date, reservation_date)
if day_date.beginning_of_day < reservation_date && reservation_date < day_date.end_of_day
human_time(reservation_date)
else
format_usa_datetime(reservation_date)
end
end
def display_status_class(order_detail)
order_detail.canceled_at ? "canceled" : order_detail.order_status.to_s.downcase
end
end
|
djthorpe/postgresql-kit | old/PostgresClientKit/FLXPostgresArray.h |
#import <Foundation/Foundation.h>
// helper function for constructing arrays
@interface FLXPostgresArray : NSObject {
FLXPostgresType type;
NSUInteger dimensions;
NSUInteger* size;
NSUInteger* lowerBound;
NSUInteger numberOfTuples;
NSMutableArray* tuples;
}
@property (retain) NSMutableArray* tuples;
@property (assign) FLXPostgresType type;
@property (assign) NSUInteger dimensions;
@property (assign) NSUInteger numberOfTuples;
@property (assign) NSUInteger* size;
@property (assign) NSUInteger* lowerBound;
+(FLXPostgresArray* )arrayWithDimensions:(NSUInteger)theDimensions type:(FLXPostgresType)theType;
// methods
-(void)setDimension:(NSUInteger)theDimension size:(NSUInteger)theSize lowerBound:(NSUInteger)theLowerBound;
-(void)addTuple:(NSObject* )theObject;
-(NSArray* )array;
@end
|
ayraz/TrainingApp | app/src/main/java/cz/nudz/www/trainingapp/dialogs/ErrorDialogFragment.java | <gh_stars>0
package cz.nudz.www.trainingapp.dialogs;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import cz.nudz.www.trainingapp.R;
import cz.nudz.www.trainingapp.TrainingApp;
/**
* Created by artem on 21-Sep-17.
*/
public class ErrorDialogFragment extends AlertDialogFragment {
public static final String TAG = ErrorDialogFragment.class.getSimpleName();
public static ErrorDialogFragment newInstance(@Nullable String title, @NonNull String message) {
Bundle args = AlertDialogFragment.bundleArguments(
title != null ? title : TrainingApp.getContext().getString(R.string.errorTitle),
message);
ErrorDialogFragment errorDialogFragment = new ErrorDialogFragment();
errorDialogFragment.setArguments(args);
return errorDialogFragment;
}
@Override
protected void init(AlertDialog.Builder builder) {
super.init(builder);
builder.setNeutralButton(R.string.ok, (dialog, which) -> {
dialog.dismiss();
ErrorDialogFragment.this.dismiss();
});
}
}
|
Tsinghua-OpenICV/OpenICV | Branch/Deprecated/ros_code/rospand/src/pandar-ros-vstyle-gps/pandar_pointcloud/src/lib/calibration.cc | /**
* \file calibration.cc
* \brief
*
* \author <NAME> (<EMAIL>)
* \author <NAME>
* Copyright (C) 2012, Austin Robot Technology,
* The University of Texas at Austin
* Copyright (c) 2017 Hesai Photonics Technology, <NAME>
*
* License: Modified BSD License
*
* $ Id: 02/14/2012 11:36:36 AM piyushk $
*/
#include <iostream>
#include <fstream>
#include <string>
#include <limits>
#include <ros/ros.h>
#include <pandar_pointcloud/calibration.h>
#include <boost/filesystem.hpp>
#include <angles/angles.h>
namespace pandar_pointcloud
{
// elevation angle of each line for HS Line 40 Lidar, Line 1 - Line 40
static const float hesai_elev_angle_map[] = {
6.96, 5.976, 4.988, 3.996,
2.999, 2.001, 1.667, 1.333,
1.001, 0.667, 0.333, 0,
-0.334, -0.667, -1.001, -1.334,
-1.667, -2.001, -2.331, -2.667,
-3, -3.327, -3.663, -3.996,
-4.321, -4.657, -4.986, -5.311,
-5.647, -5.974, -6.957, -7.934,
-8.908, -9.871, -10.826, -11.772,
-12.705, -13.63, -14.543, -15.444
};
// Line 40 Lidar azimuth Horizatal offset , Line 1 - Line 40
static const float hesai_horizatal_azimuth_offset_map[] = {
0.005, 0.006, 0.006, 0.006,
-2.479, -2.479, 2.491, -4.953,
-2.479, 2.492, -4.953, -2.479,
2.492, -4.953, 0.007, 2.491,
-4.953, 0.006, 4.961, -2.479,
0.006, 4.96, -2.478, 0.006,
4.958, -2.478, 2.488, 4.956,
-2.477, 2.487, 2.485, 2.483,
0.004, 0.004, 0.003, 0.003,
-2.466, -2.463, -2.46, -2.457
};
void Calibration::setDefaultCorrections ()
{
for (int i = 0; i < laser_count; i++)
{
laser_corrections[i].azimuthCorrection = hesai_horizatal_azimuth_offset_map[i];
laser_corrections[i].distanceCorrection = 0.0;
laser_corrections[i].horizontalOffsetCorrection = 0.0;
laser_corrections[i].verticalOffsetCorrection = 0.0;
laser_corrections[i].verticalCorrection = hesai_elev_angle_map[i];
laser_corrections[i].sinVertCorrection = std::sin (hesai_elev_angle_map[i] / 180.0 * M_PI);
laser_corrections[i].cosVertCorrection = std::cos (hesai_elev_angle_map[i] / 180.0 * M_PI);
}
}
void Calibration::read(const std::string& calibration_file)
{
initialized = true;
num_lasers = laser_count;
setDefaultCorrections ();
if (calibration_file.empty ())
return;
boost::filesystem::path file_path(calibration_file);
if (!boost::filesystem::is_regular(file_path)) {
file_path = boost::filesystem::path("pandar40.csv");
if (!boost::filesystem::is_regular(file_path))
return;
}
std::ifstream ifs(file_path.string());
if (!ifs.is_open())
return;
std::string line;
if (std::getline(ifs, line)) { // first line "Laser id,Elevation,Azimuth"
std::cout << "parsing correction file." << std::endl;
}
int line_cnt = 0;
while (std::getline(ifs, line)) {
if (line_cnt++ >= 40)
break;
int line_id = 0;
double elev, azimuth;
std::stringstream ss(line);
std::string subline;
std::getline(ss, subline, ',');
std::stringstream(subline) >> line_id;
std::getline(ss, subline, ',');
std::stringstream(subline) >> elev;
std::getline(ss, subline, ',');
std::stringstream(subline) >> azimuth;
line_id--;
laser_corrections[line_id].azimuthCorrection = azimuth;
laser_corrections[line_id].distanceCorrection = 0.0;
laser_corrections[line_id].horizontalOffsetCorrection = 0.0;
laser_corrections[line_id].verticalOffsetCorrection = 0.0;
laser_corrections[line_id].verticalCorrection = elev;
laser_corrections[line_id].sinVertCorrection = std::sin (angles::from_degrees(elev));
laser_corrections[line_id].cosVertCorrection = std::cos (angles::from_degrees(elev));
}
}
void Calibration::write(const std::string& calibration_file) {
}
} /* pandar_pointcloud */
|
viewdy/phantomjs | src/qt/qtwebkit/Source/WebCore/inspector/InspectorLayerTreeAgent.h | <gh_stars>1-10
/*
* Copyright (C) 2012 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY APPLE AND ITS 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 APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef InspectorLayerTreeAgent_h
#define InspectorLayerTreeAgent_h
#if ENABLE(INSPECTOR)
#include "InspectorBaseAgent.h"
#include "InspectorFrontend.h"
#include "InspectorTypeBuilder.h"
#include "RenderLayer.h"
#include <wtf/PassOwnPtr.h>
#include <wtf/PassRefPtr.h>
#include <wtf/Vector.h>
#include <wtf/text/WTFString.h>
namespace WebCore {
class InspectorState;
class InstrumentingAgents;
typedef String ErrorString;
class InspectorLayerTreeAgent : public InspectorBaseAgent<InspectorLayerTreeAgent>, public InspectorBackendDispatcher::LayerTreeCommandHandler {
public:
static PassOwnPtr<InspectorLayerTreeAgent> create(InstrumentingAgents* instrumentingAgents, InspectorCompositeState* state)
{
return adoptPtr(new InspectorLayerTreeAgent(instrumentingAgents, state));
}
~InspectorLayerTreeAgent();
virtual void setFrontend(InspectorFrontend*);
virtual void clearFrontend();
virtual void restore();
void reset();
void layerTreeDidChange();
void renderLayerDestroyed(const RenderLayer*);
void pseudoElementDestroyed(PseudoElement*);
// Called from the front-end.
virtual void enable(ErrorString*);
virtual void disable(ErrorString*);
virtual void layersForNode(ErrorString*, int nodeId, RefPtr<TypeBuilder::Array<TypeBuilder::LayerTree::Layer> >&);
virtual void reasonsForCompositingLayer(ErrorString*, const String& layerId, RefPtr<TypeBuilder::LayerTree::CompositingReasons>&);
private:
InspectorLayerTreeAgent(InstrumentingAgents*, InspectorCompositeState*);
// RenderLayer-related methods.
String bind(const RenderLayer*);
void unbind(const RenderLayer*);
void gatherLayersUsingRenderObjectHierarchy(ErrorString*, RenderObject*, RefPtr<TypeBuilder::Array<TypeBuilder::LayerTree::Layer> >&);
void gatherLayersUsingRenderLayerHierarchy(ErrorString*, RenderLayer*, RefPtr<TypeBuilder::Array<TypeBuilder::LayerTree::Layer> >&);
PassRefPtr<TypeBuilder::LayerTree::Layer> buildObjectForLayer(ErrorString*, RenderLayer*);
PassRefPtr<TypeBuilder::LayerTree::IntRect> buildObjectForIntRect(const IntRect&);
int idForNode(ErrorString*, Node*);
String bindPseudoElement(PseudoElement*);
void unbindPseudoElement(PseudoElement*);
InspectorFrontend::LayerTree* m_frontend;
HashMap<const RenderLayer*, String> m_documentLayerToIdMap;
HashMap<String, const RenderLayer*> m_idToLayer;
HashMap<PseudoElement*, String> m_pseudoElementToIdMap;
HashMap<String, PseudoElement*> m_idToPseudoElement;
};
} // namespace WebCore
#endif // ENABLE(INSPECTOR)
#endif // !defined(InspectorLayerTreeAgent_h)
|
arithmetic1728/google-api-java-client-services | clients/google-api-services-accesscontextmanager/v1/1.31.0/com/google/api/services/accesscontextmanager/v1/model/EgressPolicy.java | /*
* 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.
*/
/*
* This code was generated by https://github.com/googleapis/google-api-java-client-services/
* Modify at your own risk.
*/
package com.google.api.services.accesscontextmanager.v1.model;
/**
* Policy for egress from perimeter. EgressPolicies match requests based on `egress_from` and
* `egress_to` stanzas. For an EgressPolicy to match, both `egress_from` and `egress_to` stanzas
* must be matched. If an EgressPolicy matches a request, the request is allowed to span the
* ServicePerimeter boundary. For example, an EgressPolicy can be used to allow VMs on networks
* within the ServicePerimeter to access a defined set of projects outside the perimeter in certain
* contexts (e.g. to read data from a Cloud Storage bucket or query against a BigQuery dataset).
* EgressPolicies are concerned with the *resources* that a request relates as well as the API
* services and API actions being used. They do not related to the direction of data movement. More
* detailed documentation for this concept can be found in the descriptions of EgressFrom and
* EgressTo.
*
* <p> This is the Java data model class that specifies how to parse/serialize into the JSON that is
* transmitted over HTTP when working with the Access Context Manager API. For a detailed
* explanation see:
* <a href="https://developers.google.com/api-client-library/java/google-http-java-client/json">https://developers.google.com/api-client-library/java/google-http-java-client/json</a>
* </p>
*
* @author Google, Inc.
*/
@SuppressWarnings("javadoc")
public final class EgressPolicy extends com.google.api.client.json.GenericJson {
/**
* Defines conditions on the source of a request causing this EgressPolicy to apply.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private EgressFrom egressFrom;
/**
* Defines the conditions on the ApiOperation and destination resources that cause this
* EgressPolicy to apply.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private EgressTo egressTo;
/**
* Defines conditions on the source of a request causing this EgressPolicy to apply.
* @return value or {@code null} for none
*/
public EgressFrom getEgressFrom() {
return egressFrom;
}
/**
* Defines conditions on the source of a request causing this EgressPolicy to apply.
* @param egressFrom egressFrom or {@code null} for none
*/
public EgressPolicy setEgressFrom(EgressFrom egressFrom) {
this.egressFrom = egressFrom;
return this;
}
/**
* Defines the conditions on the ApiOperation and destination resources that cause this
* EgressPolicy to apply.
* @return value or {@code null} for none
*/
public EgressTo getEgressTo() {
return egressTo;
}
/**
* Defines the conditions on the ApiOperation and destination resources that cause this
* EgressPolicy to apply.
* @param egressTo egressTo or {@code null} for none
*/
public EgressPolicy setEgressTo(EgressTo egressTo) {
this.egressTo = egressTo;
return this;
}
@Override
public EgressPolicy set(String fieldName, Object value) {
return (EgressPolicy) super.set(fieldName, value);
}
@Override
public EgressPolicy clone() {
return (EgressPolicy) super.clone();
}
}
|
PiotrZdziarski/React-FsLightbox-Basic | src/constants/css-constants.js | export const ANIMATION_TIME = 250;
|
umarfarooq360/HTMLUnit | src/main/java/com/gargoylesoftware/htmlunit/HttpWebConnection.java | /*
* Copyright (c) 2002-2014 Gargoyle Software Inc.
*
* 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.gargoylesoftware.htmlunit;
import static com.gargoylesoftware.htmlunit.BrowserVersionFeatures.HEADER_CONTENT_DISPOSITION_ABSOLUTE_PATH;
import static com.gargoylesoftware.htmlunit.BrowserVersionFeatures.URL_AUTH_CREDENTIALS;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.EOFException;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLPeerUnverifiedException;
import javax.net.ssl.SSLSocketFactory;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.reflect.FieldUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.ConnectionClosedException;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpEntityEnclosingRequest;
import org.apache.http.HttpException;
import org.apache.http.HttpHost;
import org.apache.http.HttpRequest;
import org.apache.http.HttpRequestInterceptor;
import org.apache.http.HttpResponse;
import org.apache.http.ProtocolException;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.Credentials;
import org.apache.http.client.CookieStore;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpHead;
import org.apache.http.client.methods.HttpOptions;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.client.methods.HttpTrace;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.client.protocol.RequestAcceptEncoding;
import org.apache.http.client.protocol.RequestAddCookies;
import org.apache.http.client.protocol.RequestAuthCache;
import org.apache.http.client.protocol.RequestClientConnControl;
import org.apache.http.client.protocol.RequestDefaultHeaders;
import org.apache.http.client.protocol.RequestExpectContinue;
import org.apache.http.client.protocol.ResponseContentEncoding;
import org.apache.http.client.protocol.ResponseProcessCookies;
import org.apache.http.client.utils.URIUtils;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.config.ConnectionConfig;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.config.SocketConfig;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.LayeredConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContexts;
import org.apache.http.conn.ssl.X509HostnameVerifier;
import org.apache.http.cookie.Cookie;
import org.apache.http.cookie.CookieSpec;
import org.apache.http.cookie.CookieSpecProvider;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.InputStreamBody;
import org.apache.http.impl.client.DefaultRedirectStrategy;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.impl.cookie.BestMatchSpecFactory;
import org.apache.http.impl.cookie.BrowserCompatSpecFactory;
import org.apache.http.impl.cookie.IgnoreSpecFactory;
import org.apache.http.impl.cookie.NetscapeDraftSpecFactory;
import org.apache.http.impl.cookie.RFC2109SpecFactory;
import org.apache.http.impl.cookie.RFC2965SpecFactory;
import org.apache.http.protocol.HttpContext;
import org.apache.http.protocol.HttpProcessorBuilder;
import org.apache.http.protocol.RequestContent;
import org.apache.http.protocol.RequestTargetHost;
import com.gargoylesoftware.htmlunit.util.KeyDataPair;
import com.gargoylesoftware.htmlunit.util.NameValuePair;
import com.gargoylesoftware.htmlunit.util.UrlUtils;
/**
* Default implementation of {@link WebConnection}, using the HttpClient library to perform HTTP requests.
*
* @version $Revision: 9650 $
* @author <a href="mailto:<EMAIL>"><NAME></a>
* @author <NAME>
* @author <NAME>
* @author <NAME>
* @author <NAME>
* @author <NAME>
* @author <NAME>
* @author <NAME>
* @author <NAME>
* @author <NAME>
*/
public class HttpWebConnection implements WebConnection {
private static final Log LOG = LogFactory.getLog(HttpWebConnection.class);
private static final String HACKED_COOKIE_POLICY = "mine";
private HttpClientBuilder httpClientBuilder_;
private final WebClient webClient_;
/** Use single HttpContext, so there is no need to re-send authentication for each and every request. */
private final HttpContext httpContext_;
private String virtualHost_;
private final CookieSpecProvider htmlUnitCookieSpecProvider_;
private final WebClientOptions usedOptions_;
private PoolingHttpClientConnectionManager connectionManager_;
/**
* Creates a new HTTP web connection instance.
* @param webClient the WebClient that is using this connection
*/
public HttpWebConnection(final WebClient webClient) {
webClient_ = webClient;
htmlUnitCookieSpecProvider_ = new CookieSpecProvider() {
@Override
public CookieSpec create(final HttpContext context) {
return new HtmlUnitBrowserCompatCookieSpec(webClient.getBrowserVersion());
}
};
httpContext_ = new HttpClientContext();
usedOptions_ = new WebClientOptions();
}
/**
* {@inheritDoc}
*/
public WebResponse getResponse(final WebRequest request) throws IOException {
final URL url = request.getUrl();
final HttpClientBuilder builder = reconfigureHttpClientIfNeeded(getHttpClientBuilder());
if (connectionManager_ == null) {
connectionManager_ = createConnectionManager(builder);
}
builder.setConnectionManager(connectionManager_);
HttpUriRequest httpMethod = null;
try {
try {
httpMethod = makeHttpMethod(request);
}
catch (final URISyntaxException e) {
throw new IOException("Unable to create URI from URL: " + url.toExternalForm()
+ " (reason: " + e.getMessage() + ")", e);
}
final HttpHost hostConfiguration = getHostConfiguration(request);
// setProxy(httpMethod, request);
final long startTime = System.currentTimeMillis();
HttpResponse httpResponse = null;
try {
httpResponse = builder.build().execute(hostConfiguration, httpMethod, httpContext_);
}
catch (final SSLPeerUnverifiedException s) {
// Try to use only SSLv3 instead
if (webClient_.getOptions().isUseInsecureSSL()) {
HtmlUnitSSLConnectionSocketFactory.setUseSSL3Only(httpContext_, true);
httpResponse = builder.build().execute(hostConfiguration, httpMethod, httpContext_);
}
else {
throw s;
}
}
catch (final Error e) {
// in case a StackOverflowError occurs while the connection is leased, it won't get released.
// Calling code may catch the StackOverflowError, but due to the leak, the httpClient_ may
// come out of connections and throw a ConnectionPoolTimeoutException.
// => best solution, discard the HttpClient instance.
synchronized (this) {
httpClientBuilder_ = null;
}
throw e;
}
final DownloadedContent downloadedBody = downloadResponseBody(httpResponse);
final long endTime = System.currentTimeMillis();
return makeWebResponse(httpResponse, request, downloadedBody, endTime - startTime);
}
finally {
if (httpMethod != null) {
onResponseGenerated(httpMethod);
}
}
}
/**
* Called when the response has been generated. Default action is to release
* the HttpMethod's connection. Subclasses may override.
* @param httpMethod the httpMethod used (can be null)
*/
protected void onResponseGenerated(final HttpUriRequest httpMethod) {
}
/**
* Returns a new HttpClient host configuration, initialized based on the specified request.
* @param webRequest the request to use to initialize the returned host configuration
* @return a new HttpClient host configuration, initialized based on the specified request
*/
private static HttpHost getHostConfiguration(final WebRequest webRequest) {
final URL url = webRequest.getUrl();
return new HttpHost(url.getHost(), url.getPort(), url.getProtocol());
}
private void setProxy(final HttpRequestBase httpRequest, final WebRequest webRequest) {
final RequestConfig.Builder requestBuilder = createRequestConfigBuilder(getTimeout());
if (webRequest.getProxyHost() != null) {
final HttpHost proxy = new HttpHost(webRequest.getProxyHost(), webRequest.getProxyPort());
if (webRequest.isSocksProxy()) {
SocksConnectionSocketFactory.setSocksProxy(httpContext_, proxy);
}
else {
requestBuilder.setProxy(proxy);
httpRequest.setConfig(requestBuilder.build());
}
}
else {
requestBuilder.setProxy(null);
httpRequest.setConfig(requestBuilder.build());
}
}
/**
* Creates an <tt>HttpMethod</tt> instance according to the specified parameters.
* @param webRequest the request
* @return the <tt>HttpMethod</tt> instance constructed according to the specified parameters
* @throws IOException
* @throws URISyntaxException
*/
@SuppressWarnings("deprecation")
private HttpUriRequest makeHttpMethod(final WebRequest webRequest)
throws IOException, URISyntaxException {
final String charset = webRequest.getCharset();
// Make sure that the URL is fully encoded. IE actually sends some Unicode chars in request
// URLs; because of this we allow some Unicode chars in URLs. However, at this point we're
// handing things over the HttpClient, and HttpClient will blow up if we leave these Unicode
// chars in the URL.
final URL url = UrlUtils.encodeUrl(webRequest.getUrl(), false, charset);
// URIUtils.createURI is deprecated but as of httpclient-4.2.1, URIBuilder doesn't work here as it encodes path
// what shouldn't happen here
URI uri = URIUtils.createURI(url.getProtocol(), url.getHost(), url.getPort(), url.getPath(),
escapeQuery(url.getQuery()), null);
if (getVirtualHost() != null) {
uri = URI.create(getVirtualHost());
}
final HttpRequestBase httpMethod = buildHttpMethod(webRequest.getHttpMethod(), uri);
setProxy(httpMethod, webRequest);
if (!(httpMethod instanceof HttpEntityEnclosingRequest)) {
// this is the case for GET as well as TRACE, DELETE, OPTIONS and HEAD
if (!webRequest.getRequestParameters().isEmpty()) {
final List<NameValuePair> pairs = webRequest.getRequestParameters();
final org.apache.http.NameValuePair[] httpClientPairs = NameValuePair.toHttpClient(pairs);
final String query = URLEncodedUtils.format(Arrays.asList(httpClientPairs), charset);
uri = URIUtils.createURI(url.getProtocol(), url.getHost(), url.getPort(), url.getPath(), query, null);
httpMethod.setURI(uri);
}
}
else { // POST as well as PUT
final HttpEntityEnclosingRequest method = (HttpEntityEnclosingRequest) httpMethod;
if (webRequest.getEncodingType() == FormEncodingType.URL_ENCODED && method instanceof HttpPost) {
final HttpPost postMethod = (HttpPost) method;
if (webRequest.getRequestBody() == null) {
final List<NameValuePair> pairs = webRequest.getRequestParameters();
final org.apache.http.NameValuePair[] httpClientPairs = NameValuePair.toHttpClient(pairs);
final String query = URLEncodedUtils.format(Arrays.asList(httpClientPairs), charset);
final StringEntity urlEncodedEntity = new StringEntity(query, charset);
urlEncodedEntity.setContentType(URLEncodedUtils.CONTENT_TYPE);
postMethod.setEntity(urlEncodedEntity);
}
else {
final String body = StringUtils.defaultString(webRequest.getRequestBody());
final StringEntity urlEncodedEntity = new StringEntity(body, charset);
urlEncodedEntity.setContentType(URLEncodedUtils.CONTENT_TYPE);
postMethod.setEntity(urlEncodedEntity);
}
}
else if (FormEncodingType.MULTIPART == webRequest.getEncodingType()) {
final Charset c = getCharset(charset, webRequest.getRequestParameters());
final MultipartEntityBuilder builder = MultipartEntityBuilder.create().setLaxMode();
builder.setCharset(c);
for (final NameValuePair pair : webRequest.getRequestParameters()) {
if (pair instanceof KeyDataPair) {
buildFilePart((KeyDataPair) pair, builder);
}
else {
builder.addTextBody(pair.getName(), pair.getValue(),
ContentType.create("text/plain", charset));
}
}
method.setEntity(builder.build());
}
else { // for instance a PUT request
final String body = webRequest.getRequestBody();
if (body != null) {
method.setEntity(new StringEntity(body, charset));
}
}
}
final HttpClientBuilder httpClient = getHttpClientBuilder();
configureHttpProcessor(httpClient, webRequest);
// Tell the client where to get its credentials from
// (it may have changed on the webClient since last call to getHttpClientFor(...))
final CredentialsProvider credentialsProvider = webClient_.getCredentialsProvider();
// if the used url contains credentials, we have to add this
final Credentials requestUrlCredentials = webRequest.getUrlCredentials();
if (null != requestUrlCredentials
&& webClient_.getBrowserVersion().hasFeature(URL_AUTH_CREDENTIALS)) {
final URL requestUrl = webRequest.getUrl();
final AuthScope authScope = new AuthScope(requestUrl.getHost(), requestUrl.getPort());
// updating our client to keep the credentials for the next request
credentialsProvider.setCredentials(authScope, requestUrlCredentials);
httpContext_.removeAttribute(HttpClientContext.TARGET_AUTH_STATE);
}
// if someone has set credentials to this request, we have to add this
final Credentials requestCredentials = webRequest.getCredentials();
if (null != requestCredentials) {
final URL requestUrl = webRequest.getUrl();
final AuthScope authScope = new AuthScope(requestUrl.getHost(), requestUrl.getPort());
// updating our client to keep the credentials for the next request
credentialsProvider.setCredentials(authScope, requestCredentials);
httpContext_.removeAttribute(HttpClientContext.TARGET_AUTH_STATE);
}
httpClient.setDefaultCredentialsProvider(credentialsProvider);
httpContext_.removeAttribute(HttpClientContext.CREDS_PROVIDER);
return httpMethod;
}
private String escapeQuery(final String query) {
if (query == null) {
return null;
}
return query.replace("%%", "%25%25");
}
private Charset getCharset(final String charset, final List<NameValuePair> pairs) {
for (final NameValuePair pair : pairs) {
if (pair instanceof KeyDataPair) {
final KeyDataPair pairWithFile = (KeyDataPair) pair;
if (pairWithFile.getData() == null && pairWithFile.getFile() != null) {
final String fileName = pairWithFile.getFile().getName();
for (int i = 0; i < fileName.length(); i++) {
if (fileName.codePointAt(i) > 127) {
return Charset.forName(charset);
}
}
}
}
}
return null;
}
void buildFilePart(final KeyDataPair pairWithFile, final MultipartEntityBuilder builder)
throws IOException {
String mimeType = pairWithFile.getMimeType();
if (mimeType == null) {
mimeType = "application/octet-stream";
}
final ContentType contentType = ContentType.create(mimeType);
final File file = pairWithFile.getFile();
if (pairWithFile.getData() != null) {
final String filename;
if (file == null) {
filename = pairWithFile.getValue();
}
else if (webClient_.getBrowserVersion().hasFeature(HEADER_CONTENT_DISPOSITION_ABSOLUTE_PATH)) {
filename = file.getAbsolutePath();
}
else {
filename = file.getName();
}
builder.addBinaryBody(pairWithFile.getName(), new ByteArrayInputStream(pairWithFile.getData()),
contentType, filename);
return;
}
if (file == null) {
builder.addPart(pairWithFile.getName(),
// Overridden in order not to have a chunked response.
new InputStreamBody(new ByteArrayInputStream(new byte[0]), contentType, pairWithFile.getValue()) {
@Override
public long getContentLength() {
return 0;
}
});
return;
}
String filename;
if (pairWithFile.getFile() == null) {
filename = pairWithFile.getValue();
}
else if (webClient_.getBrowserVersion().hasFeature(HEADER_CONTENT_DISPOSITION_ABSOLUTE_PATH)) {
filename = pairWithFile.getFile().getAbsolutePath();
}
else {
filename = pairWithFile.getFile().getName();
}
builder.addBinaryBody(pairWithFile.getName(), pairWithFile.getFile(), contentType, filename);
}
/**
* Creates and returns a new HttpClient HTTP method based on the specified parameters.
* @param submitMethod the submit method being used
* @param uri the uri being used
* @return a new HttpClient HTTP method based on the specified parameters
*/
private static HttpRequestBase buildHttpMethod(final HttpMethod submitMethod, final URI uri) {
final HttpRequestBase method;
switch (submitMethod) {
case GET:
method = new HttpGet(uri);
break;
case POST:
method = new HttpPost(uri);
break;
case PUT:
method = new HttpPut(uri);
break;
case DELETE:
method = new HttpDelete(uri);
break;
case OPTIONS:
method = new HttpOptions(uri);
break;
case HEAD:
method = new HttpHead(uri);
break;
case TRACE:
method = new HttpTrace(uri);
break;
default:
throw new IllegalStateException("Submit method not yet supported: " + submitMethod);
}
return method;
}
/**
* Lazily initializes the internal HTTP client.
*
* @return the initialized HTTP client
*/
protected synchronized HttpClientBuilder getHttpClientBuilder() {
if (httpClientBuilder_ == null) {
httpClientBuilder_ = createHttpClient();
// this factory is required later
// to be sure this is done, we do it outside the createHttpClient() call
final RegistryBuilder<CookieSpecProvider> registeryBuilder
= RegistryBuilder.<CookieSpecProvider>create()
.register(CookieSpecs.BEST_MATCH, new BestMatchSpecFactory())
.register(CookieSpecs.STANDARD, new RFC2965SpecFactory())
.register(CookieSpecs.BROWSER_COMPATIBILITY, new BrowserCompatSpecFactory())
.register(CookieSpecs.NETSCAPE, new NetscapeDraftSpecFactory())
.register(CookieSpecs.IGNORE_COOKIES, new IgnoreSpecFactory())
.register("rfc2109", new RFC2109SpecFactory())
.register("rfc2965", new RFC2965SpecFactory());
registeryBuilder.register(HACKED_COOKIE_POLICY, htmlUnitCookieSpecProvider_);
httpClientBuilder_.setDefaultCookieSpecRegistry(registeryBuilder.build());
httpClientBuilder_.setDefaultCookieStore(new HtmlUnitCookieStore(webClient_.getCookieManager()));
}
return httpClientBuilder_;
}
/**
* Returns the timeout to use for socket and connection timeouts for HttpConnectionManager.
* Is overridden to 0 by StreamingWebConnection which keeps reading after a timeout and
* must have long running connections explicitly terminated.
* @return the WebClient's timeout
*/
protected int getTimeout() {
return webClient_.getOptions().getTimeout();
}
/**
* Creates the <tt>HttpClient</tt> that will be used by this WebClient.
* Extensions may override this method in order to create a customized
* <tt>HttpClient</tt> instance (e.g. with a custom
* {@link org.apache.http.conn.ClientConnectionManager} to perform
* some tracking; see feature request 1438216).
* @return the <tt>HttpClient</tt> that will be used by this WebConnection
*/
protected HttpClientBuilder createHttpClient() {
final HttpClientBuilder builder = HttpClientBuilder.create();
builder.setRedirectStrategy(new DefaultRedirectStrategy() {
@Override
public boolean isRedirected(final HttpRequest request, final HttpResponse response,
final HttpContext context) throws ProtocolException {
return super.isRedirected(request, response, context)
&& response.getFirstHeader("location") != null;
}
});
configureTimeout(builder, getTimeout());
configureHttpsScheme(builder);
builder.setMaxConnPerRoute(6);
return builder;
}
private void configureTimeout(final HttpClientBuilder builder, final int timeout) {
final RequestConfig.Builder requestBuilder = createRequestConfigBuilder(timeout);
builder.setDefaultRequestConfig(requestBuilder.build());
builder.setDefaultSocketConfig(createSocketConfigBuilder(timeout).build());
httpContext_.removeAttribute(HttpClientContext.REQUEST_CONFIG);
usedOptions_.setTimeout(timeout);
}
private RequestConfig.Builder createRequestConfigBuilder(final int timeout) {
final RequestConfig.Builder requestBuilder = RequestConfig.custom()
.setCookieSpec(HACKED_COOKIE_POLICY)
.setRedirectsEnabled(false)
// timeout
.setConnectTimeout(timeout)
.setConnectionRequestTimeout(timeout)
.setSocketTimeout(timeout);
return requestBuilder;
}
private SocketConfig.Builder createSocketConfigBuilder(final int timeout) {
final SocketConfig.Builder socketBuilder = SocketConfig.custom()
// timeout
.setSoTimeout(timeout);
return socketBuilder;
}
/**
* React on changes that may have occurred on the WebClient settings.
* Registering as a listener would be probably better.
*/
private HttpClientBuilder reconfigureHttpClientIfNeeded(final HttpClientBuilder httpClientBuilder) {
final WebClientOptions options = webClient_.getOptions();
// register new SSL factory only if settings have changed
if (options.isUseInsecureSSL() != usedOptions_.isUseInsecureSSL()
|| options.getSSLClientCertificateStore() != usedOptions_.getSSLClientCertificateStore()
|| options.getSSLTrustStore() != usedOptions_.getSSLTrustStore()
|| options.getSSLClientCipherSuites() != usedOptions_.getSSLClientCipherSuites()
|| options.getSSLClientProtocols() != usedOptions_.getSSLClientProtocols()
|| options.getProxyConfig() != usedOptions_.getProxyConfig()) {
configureHttpsScheme(httpClientBuilder);
if (connectionManager_ != null) {
connectionManager_.shutdown();
connectionManager_ = null;
}
}
final int timeout = getTimeout();
if (timeout != usedOptions_.getTimeout()) {
configureTimeout(httpClientBuilder, timeout);
}
return httpClientBuilder;
}
private void configureHttpsScheme(final HttpClientBuilder builder) {
final WebClientOptions options = webClient_.getOptions();
final SSLConnectionSocketFactory socketFactory =
HtmlUnitSSLConnectionSocketFactory.buildSSLSocketFactory(options);
builder.setSSLSocketFactory(socketFactory);
usedOptions_.setUseInsecureSSL(options.isUseInsecureSSL());
usedOptions_.setSSLClientCertificateStore(options.getSSLClientCertificateStore());
usedOptions_.setSSLTrustStore(options.getSSLTrustStore());
usedOptions_.setSSLClientCipherSuites(options.getSSLClientCipherSuites());
usedOptions_.setSSLClientProtocols(options.getSSLClientProtocols());
usedOptions_.setProxyConfig(options.getProxyConfig());
}
private void configureHttpProcessor(final HttpClientBuilder builder, final WebRequest webRequest)
throws IOException {
final HttpProcessorBuilder b = HttpProcessorBuilder.create();
for (final HttpRequestInterceptor i : getHttpRequestInterceptors(webRequest)) {
b.add(i);
}
// These are the headers used in HttpClientBuilder, excluding the already added ones
// (RequestClientConnControl and RequestAddCookies)
b.addAll(new RequestDefaultHeaders(null),
new RequestContent(),
new RequestTargetHost(),
new RequestExpectContinue());
b.add(new RequestAcceptEncoding());
b.add(new RequestAuthCache());
b.add(new ResponseProcessCookies());
b.add(new ResponseContentEncoding());
builder.setHttpProcessor(b.build());
}
/**
* Sets the virtual host.
* @param virtualHost the virtualHost to set
*/
public void setVirtualHost(final String virtualHost) {
virtualHost_ = virtualHost;
}
/**
* Gets the virtual host.
* @return virtualHost The current virtualHost
*/
public String getVirtualHost() {
return virtualHost_;
}
/**
* Converts an HttpMethod into a WebResponse.
*/
private WebResponse makeWebResponse(final HttpResponse httpResponse,
final WebRequest request, final DownloadedContent responseBody, final long loadTime) {
String statusMessage = httpResponse.getStatusLine().getReasonPhrase();
if (statusMessage == null) {
statusMessage = "Unknown status message";
}
final int statusCode = httpResponse.getStatusLine().getStatusCode();
final List<NameValuePair> headers = new ArrayList<NameValuePair>();
for (final Header header : httpResponse.getAllHeaders()) {
headers.add(new NameValuePair(header.getName(), header.getValue()));
}
final WebResponseData responseData = new WebResponseData(responseBody, statusCode, statusMessage, headers);
return newWebResponseInstance(responseData, loadTime, request);
}
/**
* Downloads the response body.
* @param httpResponse the web server's response
* @return a wrapper for the downloaded body.
* @throws IOException in case of problem reading/saving the body
*/
protected DownloadedContent downloadResponseBody(final HttpResponse httpResponse) throws IOException {
final HttpEntity httpEntity = httpResponse.getEntity();
if (httpEntity == null) {
return new DownloadedContent.InMemory(new byte[] {});
}
return downloadContent(httpEntity.getContent(), webClient_.getOptions().getMaxInMemory());
}
/**
* Reads the content of the stream and saves it in memory or on the file system.
* @param is the stream to read
* @return a wrapper around the downloaded content
* @throws IOException in case of read issues
* @deprecated as of 2.16, use {@link #downloadContent(InputStream, int)}
*/
@Deprecated
public static DownloadedContent downloadContent(final InputStream is) throws IOException {
return downloadContent(is, 500 * 1024);
}
/**
* Reads the content of the stream and saves it in memory or on the file system.
* @param is the stream to read
* @param maxInMemory the maximumBytes to store in memory, after which save to a local file
* @return a wrapper around the downloaded content
* @throws IOException in case of read issues
*/
public static DownloadedContent downloadContent(final InputStream is, final int maxInMemory) throws IOException {
if (is == null) {
return new DownloadedContent.InMemory(new byte[] {});
}
final ByteArrayOutputStream bos = new ByteArrayOutputStream();
final byte[] buffer = new byte[1024];
int nbRead;
try {
while ((nbRead = is.read(buffer)) != -1) {
bos.write(buffer, 0, nbRead);
if (bos.size() > maxInMemory) {
// we have exceeded the max for memory, let's write everything to a temporary file
final File file = File.createTempFile("htmlunit", ".tmp");
file.deleteOnExit();
final FileOutputStream fos = new FileOutputStream(file);
bos.writeTo(fos); // what we have already read
IOUtils.copyLarge(is, fos); // what remains from the server response
fos.close();
return new DownloadedContent.OnFile(file, true);
}
}
}
catch (final ConnectionClosedException e) {
LOG.warn("Connection was closed while reading from stream.", e);
return new DownloadedContent.InMemory(bos.toByteArray());
}
catch (final EOFException e) {
// this might happen with broken gzip content
// see com.gargoylesoftware.htmlunit.HttpWebConnection2Test.brokenGzip()
LOG.warn("EndOfFile while reading from stream.", e);
return new DownloadedContent.InMemory(bos.toByteArray());
}
finally {
IOUtils.closeQuietly(is);
}
return new DownloadedContent.InMemory(bos.toByteArray());
}
/**
* Constructs an appropriate WebResponse.
* May be overridden by subclasses to return a specialized WebResponse.
* @param responseData Data that was send back
* @param request the request used to get this response
* @param loadTime How long the response took to be sent
* @return the new WebResponse
*/
protected WebResponse newWebResponseInstance(
final WebResponseData responseData,
final long loadTime,
final WebRequest request) {
return new WebResponse(responseData, request, loadTime);
}
private List<HttpRequestInterceptor> getHttpRequestInterceptors(final WebRequest webRequest) throws IOException {
final List<HttpRequestInterceptor> list = new ArrayList<HttpRequestInterceptor>();
final Map<String, String> requestHeaders = webRequest.getAdditionalHeaders();
final int port = webRequest.getUrl().getPort();
final StringBuilder host = new StringBuilder(webRequest.getUrl().getHost());
if (port != 80 && port > 0) {
host.append(':');
host.append(Integer.toString(port));
}
final String userAgent = webClient_.getBrowserVersion().getUserAgent();
final String[] headerNames = webClient_.getBrowserVersion().getHeaderNamesOrdered();
if (headerNames != null) {
for (final String header : headerNames) {
if ("Host".equals(header)) {
list.add(new StaticHttpRequestInterceptor(header, host.toString()) { });
}
else if ("User-Agent".equals(header)) {
list.add(new StaticHttpRequestInterceptor(header, userAgent) { });
}
else if ("Accept".equals(header) && requestHeaders.get(header) != null) {
list.add(new StaticHttpRequestInterceptor(header, requestHeaders.get(header)) { });
}
else if ("Accept-Language".equals(header) && requestHeaders.get(header) != null) {
list.add(new StaticHttpRequestInterceptor(header, requestHeaders.get(header)) { });
}
else if ("Accept-Encoding".equals(header) && requestHeaders.get(header) != null) {
list.add(new StaticHttpRequestInterceptor(header, requestHeaders.get(header)) { });
}
else if ("Referer".equals(header) && requestHeaders.get(header) != null) {
list.add(new StaticHttpRequestInterceptor(header, requestHeaders.get(header)) { });
}
else if ("Connection".equals(header)) {
list.add(new RequestClientConnControl());
}
else if ("Cookie".equals(header)) {
list.add(new RequestAddCookies());
}
else if ("DNT".equals(header) && webClient_.getOptions().isDoNotTrackEnabled()) {
list.add(new StaticHttpRequestInterceptor(header, "1") { });
}
}
}
else {
list.add(new StaticHttpRequestInterceptor("User-Agent", userAgent) { });
list.add(new RequestAddCookies());
list.add(new RequestClientConnControl());
}
// not all browser versions have DNT by default as part of getHeaderNamesOrdered()
// so we add it again, in case
if (webClient_.getOptions().isDoNotTrackEnabled()) {
list.add(new StaticHttpRequestInterceptor("DNT", "1") { });
}
synchronized (requestHeaders) {
list.add(new MultiHttpRequestInterceptor(new HashMap<String, String>(requestHeaders)));
}
return list;
}
/** We must have a separate class per header, because of org.apache.http.protocol.ChainBuilder. */
private abstract static class StaticHttpRequestInterceptor implements HttpRequestInterceptor {
private String name_;
private String value_;
StaticHttpRequestInterceptor(final String name, final String value) {
this.name_ = name;
this.value_ = value;
}
@Override
public void process(final HttpRequest request, final HttpContext context)
throws HttpException, IOException {
request.setHeader(name_, value_);
}
}
private static class MultiHttpRequestInterceptor implements HttpRequestInterceptor {
private final Map<String, String> map_;
MultiHttpRequestInterceptor(final Map<String, String> map) {
this.map_ = map;
}
@Override
public void process(final HttpRequest request, final HttpContext context)
throws HttpException, IOException {
for (final String key : map_.keySet()) {
request.setHeader(key, map_.get(key));
}
}
}
/**
* Shutdown the connection.
*/
public synchronized void shutdown() {
if (httpClientBuilder_ != null) {
httpClientBuilder_ = null;
}
if (connectionManager_ != null) {
connectionManager_.shutdown();
connectionManager_ = null;
}
}
/**
* Has the exact logic in HttpClientBuilder, but with the ability to configure
* <code>socketFactory</code>.
*/
private PoolingHttpClientConnectionManager createConnectionManager(final HttpClientBuilder builder) {
final ConnectionSocketFactory socketFactory = new SocksConnectionSocketFactory();
LayeredConnectionSocketFactory sslSocketFactory;
try {
sslSocketFactory = (LayeredConnectionSocketFactory)
FieldUtils.readDeclaredField(builder, "sslSocketFactory", true);
final SocketConfig defaultSocketConfig = (SocketConfig)
FieldUtils.readDeclaredField(builder, "defaultSocketConfig", true);
final ConnectionConfig defaultConnectionConfig = (ConnectionConfig)
FieldUtils.readDeclaredField(builder, "defaultConnectionConfig", true);
final boolean systemProperties = (Boolean) FieldUtils.readDeclaredField(builder, "systemProperties", true);
final int maxConnTotal = (Integer) FieldUtils.readDeclaredField(builder, "maxConnTotal", true);
final int maxConnPerRoute = (Integer) FieldUtils.readDeclaredField(builder, "maxConnPerRoute", true);
X509HostnameVerifier hostnameVerifier = (X509HostnameVerifier)
FieldUtils.readDeclaredField(builder, "hostnameVerifier", true);
final SSLContext sslcontext = (SSLContext) FieldUtils.readDeclaredField(builder, "sslcontext", true);
if (sslSocketFactory == null) {
final String[] supportedProtocols = systemProperties
? StringUtils.split(System.getProperty("https.protocols"), ',') : null;
final String[] supportedCipherSuites = systemProperties
? StringUtils.split(System.getProperty("https.cipherSuites"), ',') : null;
if (hostnameVerifier == null) {
hostnameVerifier = SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER;
}
if (sslcontext != null) {
sslSocketFactory = new SSLConnectionSocketFactory(
sslcontext, supportedProtocols, supportedCipherSuites, hostnameVerifier);
}
else {
if (systemProperties) {
sslSocketFactory = new SSLConnectionSocketFactory(
(SSLSocketFactory) SSLSocketFactory.getDefault(),
supportedProtocols, supportedCipherSuites, hostnameVerifier);
}
else {
sslSocketFactory = new SSLConnectionSocketFactory(
SSLContexts.createDefault(),
hostnameVerifier);
}
}
}
final PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(
RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", socketFactory)
.register("https", sslSocketFactory)
.build());
if (defaultSocketConfig != null) {
connectionManager.setDefaultSocketConfig(defaultSocketConfig);
}
if (defaultConnectionConfig != null) {
connectionManager.setDefaultConnectionConfig(defaultConnectionConfig);
}
if (systemProperties) {
String s = System.getProperty("http.keepAlive", "true");
if ("true".equalsIgnoreCase(s)) {
s = System.getProperty("http.maxConnections", "5");
final int max = Integer.parseInt(s);
connectionManager.setDefaultMaxPerRoute(max);
connectionManager.setMaxTotal(2 * max);
}
}
if (maxConnTotal > 0) {
connectionManager.setMaxTotal(maxConnTotal);
}
if (maxConnPerRoute > 0) {
connectionManager.setDefaultMaxPerRoute(maxConnPerRoute);
}
return connectionManager;
}
catch (final IllegalAccessException e) {
throw new RuntimeException(e);
}
}
}
/**
* Implementation of {@link CookieStore} like {@link org.apache.http.impl.client.BasicCookieStore}
* BUT storing cookies in the order of addition.
* @author <NAME>
*/
class HtmlUnitCookieStore implements CookieStore, Serializable {
private CookieManager manager_;
HtmlUnitCookieStore(final CookieManager manager) {
manager_ = manager;
}
/**
* {@inheritDoc}
*/
public synchronized void addCookie(final Cookie cookie) {
manager_.addCookie(new com.gargoylesoftware.htmlunit.util.Cookie(cookie));
}
/**
* {@inheritDoc}
*/
public synchronized List<Cookie> getCookies() {
if (manager_.isCookiesEnabled()) {
return Arrays.asList(com.gargoylesoftware.htmlunit.util.Cookie.toHttpClient(manager_.getCookies()));
}
return Collections.<Cookie>emptyList();
}
/**
* {@inheritDoc}
*/
public synchronized boolean clearExpired(final Date date) {
return manager_.clearExpired(date);
}
/**
* {@inheritDoc}
*/
public synchronized void clear() {
manager_.clearCookies();
}
}
|
taddhopkins/experian-java | MavenWorkspace/bis-services-lib/bis-businessservices-lib/src/main/java/com/experian/bis/api/lib/businessservices/bean/response/premierprofiles/UCCFilingsDetail.java | package com.experian.bis.api.lib.businessservices.bean.response.premierprofiles;
import com.experian.bis.api.lib.businessservices.bean.response.CodeAndDefinitionResult;
public class UCCFilingsDetail {
private String dateFiled;
private String legalType;
private String legalAction;
private String documentNumber;
private String filingLocation;
private CodeAndDefinitionResult[] collateralCodes;
private String securedParty;
private String assignee;
private String owner;
private boolean customerDisputeIndicator;
private OriginalUCCFilingsInfo originalUCCFilingsInfo;
public String getDateFiled() {
return dateFiled;
}
public void setDateFiled(String dateFiled) {
this.dateFiled = dateFiled;
}
public String getLegalType() {
return legalType;
}
public void setLegalType(String legalType) {
this.legalType = legalType;
}
public String getLegalAction() {
return legalAction;
}
public void setLegalAction(String legalAction) {
this.legalAction = legalAction;
}
public String getDocumentNumber() {
return documentNumber;
}
public void setDocumentNumber(String documentNumber) {
this.documentNumber = documentNumber;
}
public String getFilingLocation() {
return filingLocation;
}
public void setFilingLocation(String filingLocation) {
this.filingLocation = filingLocation;
}
public CodeAndDefinitionResult[] getCollateralCodes() {
return collateralCodes;
}
public void setCollateralCodes(CodeAndDefinitionResult[] collateralCodes) {
this.collateralCodes = collateralCodes;
}
public String getSecuredParty() {
return securedParty;
}
public void setSecuredParty(String securedParty) {
this.securedParty = securedParty;
}
public String getAssignee() {
return assignee;
}
public void setAssignee(String assignee) {
this.assignee = assignee;
}
public String getOwner() {
return owner;
}
public void setOwner(String owner) {
this.owner = owner;
}
public boolean isCustomerDisputeIndicator() {
return customerDisputeIndicator;
}
public void setCustomerDisputeIndicator(boolean customerDisputeIndicator) {
this.customerDisputeIndicator = customerDisputeIndicator;
}
public OriginalUCCFilingsInfo getOriginalUCCFilingsInfo() {
return originalUCCFilingsInfo;
}
public void setOriginalUCCFilingsInfo(OriginalUCCFilingsInfo originalUCCFilingsInfo) {
this.originalUCCFilingsInfo = originalUCCFilingsInfo;
}
}
|
victoraranha19/Learning-Java | lista7/Atividade3/Computador.java | package lista7.atividade3;
public class Computador extends Eletrodomestico {
public Computador() {super();}
@Override
public void agir() {
System.out.println("computando...");
}
}
|
SpaceLeft/Rabbit | commands/Music/skip.js | const functions = require("../../utilities/music-function")
const config = require("../../config.json")
const Discord = require("discord.js");
module.exports = {
name: "skip",
category: "Music",
aliases: ["s"],
usage: "skip",
description: "Skips current song",
run: async (client, message, args) => {
//if not a dj, return error
if (functions.check_if_dj(message)) {
const Nopermission8 = new Discord.MessageEmbed()
.setColor(config.colors.playmode)
.setTitle("<:musicblues:888396777202520124> NO DJ-ROLE ROLE!")
.setDescription(`Opps you don't have permission for this command!\nYou need to have the ${functions.check_if_dj(message)} role`)
return message.channel.send(Nopermission8);
}
if (!message.guild.me.voice.channel){
const notPlaying = new Discord.MessageEmbed()
.setColor(config.colors.playmode)
.setTitle("<:musicblues:888396777202520124> NOTHING PLAYING!")
.setDescription(`There's currently nothing playing right now`)
return message.channel.send(notPlaying);
}
if (!message.member.voice.channel) {
const notInChannel = new Discord.MessageEmbed()
.setColor(config.colors.playmode)
.setTitle("<:musicblues:888396777202520124> NOT IN A VOICE CHANNEL!")
.setDescription(`You have to be in a voice channel to use this command!`)
return message.channel.send(notInChannel);
}
if (message.member.voice.channel.id != message.guild.me.voice.channel.id) {
const notInSameChannel = new Discord.MessageEmbed()
.setColor(config.colors.playmode)
.setTitle("<:musicblues:888396777202520124> NOT IN SAME VOICE!")
.setDescription(`You must be in the same voice channel as me - \`${message.guild.me.voice.channel.name ? message.guild.me.voice.channel.name : ""}\``)
return message.channel.send(notInSameChannel);
}
//send information message
message.react("<:musicblues:888396777202520124>");
const skip = new Discord.MessageEmbed()
.setColor(config.colors.playmode)
.setTitle("<:musicblues:888396777202520124> SKIP SUCCESS!")
.setDescription(`Successfully skipped the current song`)
message.channel.send(skip);
//skip track
client.distube.skip(message);
}
};
|
LittleNed/toontown-stride | toontown/safezone/DGSafeZoneLoader.py | <gh_stars>1-10
from toontown.safezone import DGPlayground
from toontown.safezone import SafeZoneLoader
class DGSafeZoneLoader(SafeZoneLoader.SafeZoneLoader):
def __init__(self, hood, parentFSM, doneEvent):
SafeZoneLoader.SafeZoneLoader.__init__(self, hood, parentFSM, doneEvent)
self.playgroundClass = DGPlayground.DGPlayground
self.musicFile = 'phase_8/audio/bgm/DG_nbrhood.ogg'
self.activityMusicFile = 'phase_8/audio/bgm/DG_SZ_activity.ogg'
self.dnaFile = 'phase_8/dna/daisys_garden_sz.pdna'
self.safeZoneStorageDNAFile = 'phase_8/dna/storage_DG_sz.pdna'
def load(self):
SafeZoneLoader.SafeZoneLoader.load(self)
self.birdSound = map(base.loader.loadSfx, ['phase_8/audio/sfx/SZ_DG_bird_01.ogg',
'phase_8/audio/sfx/SZ_DG_bird_02.ogg',
'phase_8/audio/sfx/SZ_DG_bird_03.ogg',
'phase_8/audio/sfx/SZ_DG_bird_04.ogg'])
def unload(self):
SafeZoneLoader.SafeZoneLoader.unload(self)
del self.birdSound |
avramtraian/CherriesX | CherriesX/src/CherriesX/Platform/OpenGL/OpenGLTexture.h | #pragma once
#include "CherriesX/Renderer/Texture.h"
namespace Cherries {
class OpenGLTexture2D : public Texture2D
{
public:
OpenGLTexture2D(const String& textureFilePath);
OpenGLTexture2D(uint32_t width, uint32_t height, const void* data);
OpenGLTexture2D(const TextureSpecification& spec);
virtual ~OpenGLTexture2D() override;
virtual void Bind(uint32_t textureUnit) override;
virtual void Bind(const String& uniformSampler, const Ref<Shader>& shader, uint32_t textureUnit) override;
virtual const RendererID& GetRendererID() const { return m_RendererID; }
private:
RendererID m_RendererID;
};
class OpenGLTexture3D : public Texture3D
{
public:
OpenGLTexture3D(const Texture3DSpecification& spec);
virtual ~OpenGLTexture3D() override;
virtual void Bind(uint32_t textureUnit) override;
virtual void Bind(const String& uniformSampler, const Ref<Shader>& shader, uint32_t textureUnit) override;
virtual const RendererID& GetRendererID() const { return m_RendererID; }
private:
RendererID m_RendererID;
Texture3DSpecification m_Specification;
};
} |
brahm16/testh | src/layouts/Admin/events/Allevents.js | import Axios from "axios";
import React, { useEffect, useState } from "react";
import { useHistory } from "react-router";
import { toast } from "react-toastify";
import DataTable from 'react-data-table-component';
import DataTableExtensions from 'react-data-table-component-extensions';
import 'react-data-table-component-extensions/dist/index.css';
import {
Button,
Card,
CardBody,
CardHeader,
CardTitle,
Col,
Form,
FormGroup,
Input,
Label,
Modal,
ModalBody,
ModalFooter,
ModalHeader,
Row,
Table,
} from "reactstrap";
export default function Allevents({ history }) {
var [events, setEvents] = useState([]);
var [modalInfo, setModalInfo] = useState([]);
const [file, setFile] = useState("");
const [img ,setImg] =useState("");
const [formData, setFormData] = useState({
name: "",
placesNembre: "",
startDate: "",
endDate: "",
desc: "",
image: "",
});
const [isToggled, setIsToggled] = React.useState(false);
const [isToggled1, setIsToggled1] = React.useState(false);
const [isUpdated, setIsUpdated] = React.useState(false);
const toggle = React.useCallback(() => setIsToggled(!isToggled));
const toggle1 = React.useCallback(() => setIsToggled1(!isToggled1));
const toggleUpdate = React.useCallback(() => setIsUpdated(!isUpdated));
const loadEvents = () => {
Axios.get(`${process.env.REACT_APP_URL}events`, {
headers: {
"Content-Type": "application/json",
},
})
.then((res) => {
setEvents(res.data);
console.log(res.data);
// console.log(images);
})
.catch((err) => {
toast.error(`Error To Your Information `);
});
};
useEffect(() => {
loadEvents();
}, []);
const handleToggle = (imag) => {
setImg(imag);
toggle1();
console.log(isToggled1);
console.log(imag);
};
const handletoggleUpdate = (prod) =>{
setModalInfo(prod);
console.log("hihi"+prod.image);
console.log(formData);
console.log(modalInfo);
toggleUpdate();
};
const columns = [
{
name: 'Name',
selector: 'name',
sortable: true,
},
{
name: 'places Nombre',
selector: 'placesNembre',
sortable: true,
},
{
name: 'Image',
selector: 'image',
sortable: true,
cell: d => <img
alt={d._id}
className="avatar" onClick={()=>handleToggle(d.image)} src={process.env.PUBLIC_URL + `/uploads/${d.image}`}
/>,
},
{
name: 'Actions',
sortable: true,
cell: d => (<><button style={{marginRight:"1rem",color:"black"}} onClick={()=>handletoggleUpdate(d)}><i className="tim-icons icon-pencil"></i></button>
<button style={{marginRight:"1rem",color:"black"}} onClick={() => handleDelete(d._id)}>
<i className="tim-icons icon-trash-simple"></i>
</button>
</>
),
},
];
const handleSubmit = (e) => {
e.preventDefault();
console.log("on submit " + formData.name);
const data = new FormData();
console.log(formData.image);
console.log("file" + file.name);
// console.log(imagefile.files[0]);
data.append("image", file);
data.append("name", formData.name);
data.append("placesNembre", formData.placesNembre);
data.append("desc", formData.desc);
data.append("startDate", formData.startDate);
data.append("endDate", formData.endDate);
toast.success("event added successfully")
Axios.post(`${process.env.REACT_APP_URL}events`, data, {
headers: {
"Content-Type": "multipart/form-data",
},
}).then((response) => {
console.log(response);
// toast.success("event added successfully")
window.location.reload();
});
};
const handleUpdate = async (id , e) => {
e.preventDefault();
console.log("on submit " + modalInfo.name);
const data = new FormData();
console.log(modalInfo.image);
//console.log("file" + file.name);
// console.log(imagefile.files[0]);
data.append("image", file);
data.append("name", modalInfo.name);
data.append("placesNembre", modalInfo.placesNembre);
data.append("desc", modalInfo.desc);
data.append("startDate", modalInfo.startDate);
data.append("endDate", modalInfo.endDate);
toast.success("product updated successfully")
//console.log("update ok "+modalInfo.name);
// return () => console.log("update ok ");
await Axios.patch(`${process.env.REACT_APP_URL}events/${id}`, data, {
headers: {
"Content-Type": "multipart/form-data",
},
}).then((response) => {
console.log(response);
// toast.success("product added successfully")
window.location.reload();
});
};
const handleChange = (text) => (e) => {
setFormData({ ...formData, [text]: e.target.value });
setModalInfo({ ...modalInfo, [text]: e.target.value });
};
const handleDelete = (id) => {
// console.log("Delete");
Axios.delete(`${process.env.REACT_APP_URL}events/${id}`, {
headers: {
"Content-Type": "multipart/form-data",
},
}).then((response) => {
console.log(response);
toast.error("product deleted");
window.location.reload();
});
};
const handleChangeFile = (text) => (e) => {
setFormData({ ...formData, [text]: e.target.value });
setModalInfo({ ...modalInfo, [text]: e.target.value });
setFile(e.target.files[0]);
};
const { name, placesNembre,startDate , endDate , desc , image } = formData;
//this methode is wrong
return (
<>
<div className="content">
<Row>
<Modal isOpen={isToggled1} toggle={isToggled1}>
<ModalHeader toggle={isToggled1}>Show Image</ModalHeader>
<ModalBody>
<img
alt={img}
className="avatar" src={process.env.PUBLIC_URL + `/uploads/${img}`}
/>
</ModalBody>
<ModalFooter>
<Button className="btn-neutral" color="info" onClick={toggle1}>
Cancel
</Button>
</ModalFooter>
</Modal>
<Modal isOpen={isUpdated} toggle={isUpdated}>
<ModalHeader toggle={isUpdated}>Update event</ModalHeader>
<ModalBody>
<Form onSubmit={(e) => handleUpdate(modalInfo._id , e)} method="Post">
<FormGroup>
<Label htmlFor="name">Name</Label>
<Input
color="info"
type="text"
style={{color: '#000'}}
id="name"
name="name"
value={modalInfo.name}
onChange={handleChange("name")}
/>
<Label htmlFor="placesNembre">places Number</Label>
<Input
color="info"
type="number"
style={{color: '#000'}}
id="placesNembre"
name="placesNembre"
value={modalInfo.placesNembre}
onChange={handleChange("placesNembre")}
/>
<Label htmlFor="startDate">Start Date</Label>
<Input
color="info"
type="Date"
style={{color: '#000'}}
id="startDate"
name="startDate"
value={modalInfo.startDate}
onChange={handleChange("startDate")}
/>
<Label htmlFor="endDate">End Date</Label>
<Input
color="info"
type="date"
style={{color: '#000'}}
id="endDate"
name="endDate"
value={modalInfo.endDate}
onChange={handleChange("endDate")}
/>
<Label htmlFor="desc">description</Label>
<Input
color="info"
type="textarea"
style={{color: '#000'}}
id="desc"
name="desc"
value={modalInfo.desc}
onChange={handleChange("desc")}
/>
</FormGroup>
<FormGroup>
<div class="upload-btn-wrapper">
<button class="btn1">Upload a file</button>
<input
color="info"
type="file"
style={{color: '#000'}}
name="image"
id="image"
value={image}
onChange={handleChangeFile("image")}
/>
</div>
</FormGroup>
<Button type="submit" value="submit" color="primary">
Update
</Button>
</Form>
</ModalBody>
<ModalFooter>
<Button className="btn-neutral" color="info" onClick={toggleUpdate}>
Cancel
</Button>
</ModalFooter>
</Modal>
<Modal isOpen={isToggled} toggle={isToggled}>
<ModalHeader toggle={isToggled}>Add Event</ModalHeader>
<ModalBody>
<Form onSubmit={handleSubmit} method="Post">
<FormGroup>
<Label htmlFor="name">Name</Label>
<Input
color="info"
type="text"
style={{color: '#000'}}
id="name"
name="name"
value={name}
onChange={handleChange("name")}
/>
<Label htmlFor="placesNembre">placesNembre</Label>
<Input
color="info"
type="number"
style={{color: '#000'}}
id="placesNembre"
style={{color: '#000'}}
name="placesNembre"
value={placesNembre}
onChange={handleChange("placesNembre")}
/>
<Label htmlFor="startDate">startDate</Label>
<Input
color="info"
type="date"
style={{color: '#000'}}
id="startDate"
name="startDate"
value={startDate}
onChange={handleChange("startDate")}
/>
<Label htmlFor="endDate">endDate</Label>
<Input
color="info"
type="date"
style={{color: '#000'}}
id="endDate"
name="endDate"
value={endDate}
onChange={handleChange("endDate")}
/>
<Label htmlFor="desc">description</Label>
<Input
color="info"
type="textarea"
style={{color: '#000'}}
id="desc"
name="desc"
value={desc}
onChange={handleChange("desc")}
/>
</FormGroup>
<FormGroup>
<div class="upload-btn-wrapper">
<button class="btn1">Upload a file</button>
<input
color="info"
type="file"
style={{color: '#000'}}
name="image"
id="image"
value={image}
onChange={handleChangeFile("image")}
/>
</div>
</FormGroup>
<Button type="submit" value="submit" color="primary">
Add
</Button>
</Form>
</ModalBody>
<ModalFooter>
<Button className="btn-neutral" color="info" onClick={toggle}>
Cancel
</Button>
</ModalFooter>
</Modal>
<Col md="12">
<Button outline onClick={toggle}>
{" "}
Add
</Button>
</Col>
<Col md="12">
<Card>
<CardHeader>
<CardTitle tag="h4">events</CardTitle>
</CardHeader>
<CardBody>
<DataTableExtensions
columns={columns}
data={events}
>
<DataTable
noHeader
defaultSortField="name"
defaultSortAsc={false}
pagination
highlightOnHover
/>
</DataTableExtensions>
</CardBody>
</Card>
</Col>
</Row>
</div>
</>
);
}
|
arpetti/LEDITA | test/server/util/HashHelperSpec.js | var expect = require('chai').expect
, HashHelper = require('../../../server/util/HashHelper');
describe('Hash Helper', function() {
var password = '<PASSWORD>';
var wrongPassword = 'passworD';
var longPassword = '<PASSWORD>';
it('Hashes a password', function(done) {
HashHelper.generateHash(password, function(err, result) {
expect(err).to.be.null;
expect(result.length).to.equal(60);
done();
});
});
it('Hashed password length is same size regardless of input size', function(done) {
HashHelper.generateHash(longPassword, function(err, result) {
expect(err).to.be.null;
expect(result.length).to.equal(60);
done();
});
});
it('Hashes and compares password success', function(done) {
HashHelper.generateHash(password, function(err, result) {
HashHelper.compareHash(password, result, function(err, compareResult) {
expect(err).to.be.null;
expect(compareResult).to.be.true;
done();
});
});
});
it('Hashes and compares password failure', function(done) {
HashHelper.generateHash(password, function(err, result) {
HashHelper.compareHash(wrongPassword, result, function(err, compareResult) {
expect(err).to.be.null;
expect(compareResult).to.be.false;
done();
});
});
});
}); |
yr0/discursus | spec/models/book_spec.rb | <filename>spec/models/book_spec.rb
# frozen_string_literal: true
describe Book do
it_behaves_like 'Sluggable'
describe '.all_categories' do
it 'returns all categories of books' do
books = create_list(:book, 2, :with_categories)
expect(Book.all_categories.pluck(:name)).to match_array(books.flat_map(&:categories).map(&:name))
end
it 'returns empty array if book has no categories' do
create_list(:book, 2)
expect(Book.all_categories).to be_empty
end
end
describe '.with_authors' do
let(:books_with_authors) { create_list(:book, 2, :with_authors, authors_amount: 2) }
it 'returns author names along with books info' do
book1, book2 = books_with_authors
expect(Book.with_authors.map(&:author_names))
.to match_array([book1.authors.order(:name).pluck(:name), book2.authors.order(:name).pluck(:name)])
end
it 'performs a single DB query to get the names' do
expect do
Book.with_authors.map(&:author_names)
end.to make_database_queries(count: 1)
end
it 'returns empty array for author names for books that have no authors' do
books_with_authors
book = create(:book)
expect(Book.with_authors.find(book.id).author_names).to eq []
end
end
describe '#author_names' do
let(:authors) { create_list(:author, 2) }
let(:book) { create(:book, authors: authors) }
let(:books_list) { create_list(:book, rand(2..4), :with_authors) }
let(:another_book) { create(:book) }
it 'falls back to #pluck if the .with_authors scope was not used' do
book
expect(Book.first.author_names).to eq authors.pluck(:name)
end
end
end
|
claudep/Geotrek | geotrek/maintenance/views.py | import logging
from django.utils.translation import gettext_lazy as _
from mapentity.views import (MapEntityLayer, MapEntityList, MapEntityJsonList, MapEntityFormat, MapEntityViewSet,
MapEntityDetail, MapEntityDocument, MapEntityCreate, MapEntityUpdate, MapEntityDelete)
from geotrek.altimetry.models import AltimetryMixin
from geotrek.common.views import FormsetMixin
from geotrek.authent.decorators import same_structure_required
from .models import Intervention, Project
from .filters import InterventionFilterSet, ProjectFilterSet
from .forms import (InterventionForm, ProjectForm,
FundingFormSet, ManDayFormSet)
from .serializers import (InterventionSerializer, ProjectSerializer,
InterventionGeojsonSerializer, ProjectGeojsonSerializer)
from rest_framework import permissions as rest_permissions
logger = logging.getLogger(__name__)
class InterventionLayer(MapEntityLayer):
queryset = Intervention.objects.existing()
filterform = InterventionFilterSet
properties = ['name']
class InterventionList(MapEntityList):
queryset = Intervention.objects.existing()
filterform = InterventionFilterSet
columns = ['id', 'name', 'date', 'type', 'target', 'status', 'stake']
class InterventionJsonList(MapEntityJsonList, InterventionList):
pass
class InterventionFormatList(MapEntityFormat, InterventionList):
columns = [
'id', 'name', 'date', 'type', 'target', 'status', 'stake',
'disorders', 'total_manday', 'project', 'subcontracting',
'width', 'height', 'length', 'area', 'structure',
'description', 'date_insert', 'date_update',
'material_cost', 'heliport_cost', 'subcontract_cost',
'total_cost_mandays', 'total_cost',
'cities', 'districts', 'areas',
] + AltimetryMixin.COLUMNS
class InterventionDetail(MapEntityDetail):
queryset = Intervention.objects.existing()
def get_context_data(self, *args, **kwargs):
context = super(InterventionDetail, self).get_context_data(*args, **kwargs)
context['can_edit'] = self.get_object().same_structure(self.request.user)
return context
class InterventionDocument(MapEntityDocument):
model = Intervention
class ManDayFormsetMixin(FormsetMixin):
context_name = 'manday_formset'
formset_class = ManDayFormSet
class InterventionCreate(ManDayFormsetMixin, MapEntityCreate):
model = Intervention
form_class = InterventionForm
def get_form_kwargs(self):
kwargs = super().get_form_kwargs()
if 'target_id' in self.request.GET and 'target_type' in self.request.GET:
# Create intervention on an existing infrastructure
kwargs['target_id'] = self.request.GET['target_id']
kwargs['target_type'] = self.request.GET['target_type']
return kwargs
class InterventionUpdate(ManDayFormsetMixin, MapEntityUpdate):
queryset = Intervention.objects.existing()
form_class = InterventionForm
@same_structure_required('maintenance:intervention_detail')
def dispatch(self, *args, **kwargs):
return super(InterventionUpdate, self).dispatch(*args, **kwargs)
class InterventionDelete(MapEntityDelete):
model = Intervention
@same_structure_required('maintenance:intervention_detail')
def dispatch(self, *args, **kwargs):
return super(InterventionDelete, self).dispatch(*args, **kwargs)
class InterventionViewSet(MapEntityViewSet):
model = Intervention
queryset = Intervention.objects.existing()
serializer_class = InterventionSerializer
geojson_serializer_class = InterventionGeojsonSerializer
permission_classes = [rest_permissions.DjangoModelPermissionsOrAnonReadOnly]
def get_queryset(self):
# Override annotation done by MapEntityViewSet.get_queryset()
return Intervention.objects.all()
class ProjectLayer(MapEntityLayer):
queryset = Project.objects.existing()
properties = ['name']
def get_queryset(self):
nonemptyqs = Intervention.objects.existing().filter(project__isnull=False).values('project')
return super(ProjectLayer, self).get_queryset().filter(pk__in=nonemptyqs)
class ProjectList(MapEntityList):
queryset = Project.objects.existing()
filterform = ProjectFilterSet
columns = ['id', 'name', 'period', 'type', 'domain']
class ProjectJsonList(MapEntityJsonList, ProjectList):
pass
class ProjectFormatList(MapEntityFormat, ProjectList):
columns = [
'id', 'structure', 'name', 'period', 'type', 'domain', 'constraint', 'global_cost',
'interventions', 'interventions_total_cost', 'comments', 'contractors',
'project_owner', 'project_manager', 'founders',
'date_insert', 'date_update',
'cities', 'districts', 'areas',
]
class ProjectDetail(MapEntityDetail):
queryset = Project.objects.existing()
def get_context_data(self, *args, **kwargs):
context = super(ProjectDetail, self).get_context_data(*args, **kwargs)
context['can_edit'] = self.get_object().same_structure(self.request.user)
context['empty_map_message'] = _("No intervention related.")
return context
class ProjectDocument(MapEntityDocument):
model = Project
class FundingFormsetMixin(FormsetMixin):
context_name = 'funding_formset'
formset_class = FundingFormSet
class ProjectCreate(FundingFormsetMixin, MapEntityCreate):
model = Project
form_class = ProjectForm
class ProjectUpdate(FundingFormsetMixin, MapEntityUpdate):
queryset = Project.objects.existing()
form_class = ProjectForm
@same_structure_required('maintenance:project_detail')
def dispatch(self, *args, **kwargs):
return super(ProjectUpdate, self).dispatch(*args, **kwargs)
class ProjectDelete(MapEntityDelete):
model = Project
@same_structure_required('maintenance:project_detail')
def dispatch(self, *args, **kwargs):
return super(ProjectDelete, self).dispatch(*args, **kwargs)
class ProjectViewSet(MapEntityViewSet):
model = Project
queryset = Project.objects.existing()
serializer_class = ProjectSerializer
geojson_serializer_class = ProjectGeojsonSerializer
permission_classes = [rest_permissions.DjangoModelPermissionsOrAnonReadOnly]
def get_queryset(self):
# Override annotation done by MapEntityViewSet.get_queryset()
return Project.objects.all()
|
Yancyyyyyy/Catnest-Project-for-Student-Accommodation-Committee | catnest/src/main/java/com/stray/cat/dao/SentenceMapper.java | package com.stray.cat.dao;
import com.stray.cat.pojo.Sentence;
import com.stray.cat.vo.CommentVo;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Repository;
import java.util.List;
@Mapper
@Repository
public interface SentenceMapper {
@Select("select * from c_sentence")
List<Sentence> queryAllSentence();
@Insert("insert into c_sentence values(#{sentenceId},#{sentenceC},#{sentenceE},#{sentenceZ})")
int addSentence(Sentence sentence);
@Delete("delete from c_sentence where sentence_id=#{sentenceId}")
int deleteSentence(int sentenceId);
}
|
hickerson/bbn | fable/fable_sources/libtbx/command_line/epydoc_run.py | <filename>fable/fable_sources/libtbx/command_line/epydoc_run.py
from __future__ import division
import epydoc
import epydoc.docwriter
import epydoc.docwriter.xlink
import epydoc.cli
help_text = """Synopsis
libtbx.epydoc [options]
Description
Generate the epydoc documentation specified by the given configuration file.
Any option understood by epydoc may be passed to this script.
If the configuration file is not specified, the file epydoc.conf in the current directory is used.
Requirements
Epydoc 3.0 and docutils.
Instructions for documentation writers
When a pure Python class A uses the Boost.Python wrapping of a C++ class B,
the docstring of A should feature a link to the doxygen-generated
documentation of B. That link shall be written as e.g.
:doxyclass:`scitbx::lbfgs::drop_convergence_test`
and will give
<a href="../c_plus_plus/classscitbx_1_1lbfgs_1_1drop__convergence__test.html">
class scitbx::lbfgs::drop_convergence_test</a>
The other magic keyword is "doxystruct" for struct instead of class.
This relies on an essential requirement on the part of the C++ documentation writers: the C++ documentation root directory and the Python documentation
root directory shall be in the same directory on the server.
"""
def help():
print help_text
exit(1)
# create our own custom external link classes
class DoxygenUrlGenerator(epydoc.docwriter.xlink.UrlGenerator):
def get_url(self, name):
url = name.replace('_', '__') \
.replace('::', '_1_1')
url = "../c_plus_plus/%s%s.html" % (self.what_is_documented, url)
return url
class DoxygenClassUrlGenerator(DoxygenUrlGenerator):
what_is_documented = 'class'
class DoxygenStructUrlGenerator(DoxygenUrlGenerator):
what_is_documented = 'struct'
def run():
# register our custom external link classes
epydoc.docwriter.xlink.register_api('doxyclass', DoxygenClassUrlGenerator())
epydoc.docwriter.xlink.create_api_role('doxyclass', problematic=False)
epydoc.docwriter.xlink.register_api('doxystruct', DoxygenClassUrlGenerator())
epydoc.docwriter.xlink.create_api_role('doxystruct', problematic=False)
# let epydoc handle the command-line arguments
import sys
if '--conf=' not in sys.argv[1:]:
sys.argv.append('--conf=epydoc.conf')
options = epydoc.cli.parse_arguments()
# run it
epydoc.cli.main(options)
if __name__ == "__main__":
run()
|
rpalcolea/genie | genie-agent/src/integTest/java/com/netflix/genie/agent/rpc/GRpcAutoConfigurationIntegrationTest.java | <reponame>rpalcolea/genie
/*
*
* Copyright 2019 Netflix, Inc.
*
* 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.netflix.genie.agent.rpc;
import com.netflix.genie.agent.cli.ArgumentDelegates;
import com.netflix.genie.agent.execution.services.impl.grpc.GRpcServicesAutoConfiguration;
import com.netflix.genie.proto.FileStreamServiceGrpc;
import com.netflix.genie.proto.HeartBeatServiceGrpc;
import com.netflix.genie.proto.JobKillServiceGrpc;
import com.netflix.genie.proto.JobServiceGrpc;
import com.netflix.genie.proto.PingServiceGrpc;
import io.grpc.ClientInterceptor;
import io.grpc.ManagedChannel;
import io.grpc.stub.AbstractStub;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
/**
* Test for {@link GRpcServicesAutoConfiguration}.
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(
classes = {
GRpcAutoConfiguration.class,
GRpcAutoConfigurationIntegrationTest.MockConfig.class
}
)
// TODO: Perhaps this should be using the context runner?
// TODO: Use mockbean instead of the whole configuration?
public class GRpcAutoConfigurationIntegrationTest {
@Autowired
private ApplicationContext applicationContext;
/**
* Check that channel is a singleton.
*/
@Test
public void channelBean() {
final ManagedChannel channel1 = applicationContext.getBean(ManagedChannel.class);
final ManagedChannel channel2 = applicationContext.getBean(ManagedChannel.class);
Assert.assertNotNull(channel1);
Assert.assertNotNull(channel2);
Assert.assertSame(channel1, channel2);
}
/**
* Check that all gRPC client stubs are available in context, that they are prototype and not singletons and that
* they all share a single channel singleton.
*/
@Test
public void clientsBeans() {
Assert.assertNotNull(applicationContext);
final Class<?>[] clientStubClasses = {
PingServiceGrpc.PingServiceFutureStub.class,
JobServiceGrpc.JobServiceFutureStub.class,
HeartBeatServiceGrpc.HeartBeatServiceStub.class,
JobKillServiceGrpc.JobKillServiceFutureStub.class,
FileStreamServiceGrpc.FileStreamServiceStub.class,
};
for (final Class<?> clientStubClass : clientStubClasses) {
final AbstractStub stub1 = (AbstractStub) applicationContext.getBean(clientStubClass);
final AbstractStub stub2 = (AbstractStub) applicationContext.getBean(clientStubClass);
Assert.assertNotNull(stub1);
Assert.assertNotNull(stub2);
Assert.assertNotSame(stub1, stub2);
Assert.assertSame(stub1.getChannel(), stub2.getChannel());
}
}
/**
* Check that interceptor beans are resolved.
*/
@Test
public void interceptorBeans() {
final Class<?>[] interceptorClasses = {
ChannelLoggingInterceptor.class,
};
for (final Class<?> interceptorClass : interceptorClasses) {
final ClientInterceptor interceptor = (ClientInterceptor) applicationContext.getBean(interceptorClass);
Assert.assertNotNull(interceptor);
}
}
@Configuration
static class MockConfig {
@Bean
ArgumentDelegates.ServerArguments serverArguments() {
final ArgumentDelegates.ServerArguments mock = Mockito.mock(ArgumentDelegates.ServerArguments.class);
Mockito.when(mock.getServerHost()).thenReturn("server.com");
Mockito.when(mock.getServerPort()).thenReturn(1234);
Mockito.when(mock.getRpcTimeout()).thenReturn(3L);
return mock;
}
}
}
|
wbingli/blox | data-service/src/main/java/com/amazonaws/blox/dataservice/api/ListClustersApi.java | <reponame>wbingli/blox
/*
* Copyright 2017 Amazon.com, Inc. or its affiliates. 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. A copy of the
* License is located at
*
* http://aws.amazon.com/apache2.0/
*
* or in the "LICENSE" file accompanying this file. This file 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.amazonaws.blox.dataservice.api;
import com.amazonaws.blox.dataservice.mapper.ApiModelMapper;
import com.amazonaws.blox.dataservice.model.Cluster;
import com.amazonaws.blox.dataservice.repository.EnvironmentRepository;
import com.amazonaws.blox.dataservicemodel.v1.exception.InternalServiceException;
import com.amazonaws.blox.dataservicemodel.v1.model.wrappers.ListClustersRequest;
import com.amazonaws.blox.dataservicemodel.v1.model.wrappers.ListClustersResponse;
import java.util.List;
import java.util.stream.Collectors;
import lombok.AllArgsConstructor;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
@Slf4j
@Component
@AllArgsConstructor
public class ListClustersApi {
@NonNull private final ApiModelMapper apiModelMapper;
@NonNull private final EnvironmentRepository environmentRepository;
public ListClustersResponse listClusters(@NonNull final ListClustersRequest request)
throws InternalServiceException {
try {
List<Cluster> clusters =
environmentRepository.listClusters(
request.getAccountId(), request.getClusterNamePrefix());
return ListClustersResponse.builder()
.clusters(clusters.stream().map(apiModelMapper::toCluster).collect(Collectors.toList()))
.build();
} catch (final Exception e) {
log.error(e.getMessage(), e);
throw new InternalServiceException(e.getMessage(), e);
}
}
}
|
FeikoJoosten/GameEngineFramework | Engine/Camera/Frustum.cpp | <reponame>FeikoJoosten/GameEngineFramework
#include "Engine/Camera/Frustum.hpp"
#include "Engine/Camera/Camera.hpp"
namespace Engine
{
Frustum::Frustum(Camera& camera, glm::vec3 right, glm::vec3 up)
{
float fov = camera.GetFoV();
float aspectRatio = camera.GetAspectRatio();
glm::vec3 cameraPosition = camera.GetPosition();
glm::vec3 cameraDirection = camera.GetRotation();
glm::vec2 clippingPlanes = camera.GetClippingPlanes();
float nearPlaneHeight = 2 * tan(fov / 2) * clippingPlanes.x;
float nearPlaneWidth = nearPlaneHeight * aspectRatio;
float farPlaneHeight = 2 * tan(fov / 2) * clippingPlanes.y;
float farPlaneWidth = farPlaneHeight * aspectRatio;
glm::vec3 farCenter = cameraPosition + cameraDirection * clippingPlanes.y;
glm::vec3 ftl = farCenter + (up * farPlaneHeight / 2.0f) - (right * farPlaneWidth / 2.0f); // far top left
glm::vec3 ftr = farCenter + (up * farPlaneHeight / 2.0f) + (right * farPlaneWidth / 2.0f); // far top right
glm::vec3 fbl = farCenter - (up * farPlaneHeight / 2.0f) - (right * farPlaneWidth / 2.0f); // far bottom left
glm::vec3 fbr = farCenter - (up * farPlaneHeight / 2.0f) + (right * farPlaneWidth / 2.0f); // far bottom right
glm::vec3 nearCenter = cameraPosition + cameraDirection * clippingPlanes.x;
glm::vec3 ntl = nearCenter + (up * nearPlaneHeight / 2.0f) - (right * nearPlaneWidth / 2.0f); // near top left
glm::vec3 ntr = nearCenter + (up * nearPlaneHeight / 2.0f) + (right * nearPlaneWidth / 2.0f); // near top right
glm::vec3 nbl = nearCenter - (up * nearPlaneHeight / 2.0f) - (right * nearPlaneWidth / 2.0f); // near bottom left
glm::vec3 nbr = nearCenter - (up * nearPlaneHeight / 2.0f) + (right * nearPlaneWidth / 2.0f); // near bottom right
topFace = Face(ntr, ntl, ftl);
bottomFace = Face(nbl, nbr, fbl);
leftFace = Face(ntl, nbl, fbl);
rightFace = Face(nbr, ntr, fbr);
frontFace = Face(ntl, ntr, nbr);
backFace = Face(ftr, ftl, fbl);
}
Frustum::Face::Face(glm::vec3 p0, glm::vec3 p1, glm::vec3 p2)
{
position0 = p0;
position1 = p1;
position2 = p2;
v = p1 - p0;
u = p2 - p0;
normal = v * u;
glm::normalize(normal);
d = glm::dot(-normal, p0);
}
Frustum::Face Frustum::GetFrontFace() const
{
return frontFace;
}
Frustum::Face Frustum::GetBackFace() const
{
return backFace;
}
Frustum::Face Frustum::GetTopFace() const
{
return topFace;
}
Frustum::Face Frustum::GetRightFace() const
{
return rightFace;
}
Frustum::Face Frustum::GetBottomFace() const
{
return bottomFace;
}
Frustum::Face Frustum::GetLeftFace() const
{
return leftFace;
}
} // namespace Engine |
1-MillionParanoidTterabytes/Blender-2.79b-blackened | source/blender/blenlib/intern/math_interp.c | /*
* ***** BEGIN GPL LICENSE BLOCK *****
*
* 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.
*
* The Original Code is Copyright (C) 2012 by Blender Foundation.
* All rights reserved.
*
* The Original Code is: all of this file.
*
* Contributor(s): <NAME>
*
* ***** END GPL LICENSE BLOCK *****
*
*/
/** \file blender/blenlib/intern/math_interp.c
* \ingroup bli
*/
#include <math.h>
#include "BLI_math.h"
#include "BLI_strict_flags.h"
/**************************************************************************
* INTERPOLATIONS
*
* Reference and docs:
* http://wiki.blender.org/index.php/User:Damiles#Interpolations_Algorithms
***************************************************************************/
/* BICUBIC Interpolation functions
* More info: http://wiki.blender.org/index.php/User:Damiles#Bicubic_pixel_interpolation
* function assumes out to be zero'ed, only does RGBA */
static float P(float k)
{
float p1, p2, p3, p4;
p1 = max_ff(k + 2.0f, 0.0f);
p2 = max_ff(k + 1.0f, 0.0f);
p3 = max_ff(k, 0.0f);
p4 = max_ff(k - 1.0f, 0.0f);
return (float)(1.0f / 6.0f) * (p1 * p1 * p1 - 4.0f * p2 * p2 * p2 + 6.0f * p3 * p3 * p3 - 4.0f * p4 * p4 * p4);
}
#if 0
/* older, slower function, works the same as above */
static float P(float k)
{
return (float)(1.0f / 6.0f) *
(pow(MAX2(k + 2.0f, 0), 3.0f) - 4.0f *
pow(MAX2(k + 1.0f, 0), 3.0f) + 6.0f *
pow(MAX2(k, 0), 3.0f) - 4.0f *
pow(MAX2(k - 1.0f, 0), 3.0f));
}
#endif
static void vector_from_float(const float *data, float vector[4], int components)
{
if (components == 1) {
vector[0] = data[0];
}
else if (components == 3) {
copy_v3_v3(vector, data);
}
else {
copy_v4_v4(vector, data);
}
}
static void vector_from_byte(const unsigned char *data, float vector[4], int components)
{
if (components == 1) {
vector[0] = data[0];
}
else if (components == 3) {
vector[0] = data[0];
vector[1] = data[1];
vector[2] = data[2];
}
else {
vector[0] = data[0];
vector[1] = data[1];
vector[2] = data[2];
vector[3] = data[3];
}
}
/* BICUBIC INTERPOLATION */
BLI_INLINE void bicubic_interpolation(const unsigned char *byte_buffer, const float *float_buffer,
unsigned char *byte_output, float *float_output, int width, int height,
int components, float u, float v)
{
int i, j, n, m, x1, y1;
float a, b, w, wx, wy[4], out[4];
/* sample area entirely outside image? */
if (ceil(u) < 0 || floor(u) > width - 1 || ceil(v) < 0 || floor(v) > height - 1) {
if (float_output) {
copy_vn_fl(float_output, components, 0.0f);
}
if (byte_output) {
copy_vn_uchar(byte_output, components, 0);
}
return;
}
i = (int)floor(u);
j = (int)floor(v);
a = u - (float)i;
b = v - (float)j;
zero_v4(out);
/* Optimized and not so easy to read */
/* avoid calling multiple times */
wy[0] = P(b - (-1));
wy[1] = P(b - 0);
wy[2] = P(b - 1);
wy[3] = P(b - 2);
for (n = -1; n <= 2; n++) {
x1 = i + n;
CLAMP(x1, 0, width - 1);
wx = P((float)n - a);
for (m = -1; m <= 2; m++) {
float data[4];
y1 = j + m;
CLAMP(y1, 0, height - 1);
/* normally we could do this */
/* w = P(n-a) * P(b-m); */
/* except that would call P() 16 times per pixel therefor pow() 64 times, better precalc these */
w = wx * wy[m + 1];
if (float_output) {
const float *float_data = float_buffer + width * y1 * components + components * x1;
vector_from_float(float_data, data, components);
}
else {
const unsigned char *byte_data = byte_buffer + width * y1 * components + components * x1;
vector_from_byte(byte_data, data, components);
}
if (components == 1) {
out[0] += data[0] * w;
}
else if (components == 3) {
out[0] += data[0] * w;
out[1] += data[1] * w;
out[2] += data[2] * w;
}
else {
out[0] += data[0] * w;
out[1] += data[1] * w;
out[2] += data[2] * w;
out[3] += data[3] * w;
}
}
}
/* Done with optimized part */
#if 0
/* older, slower function, works the same as above */
for (n = -1; n <= 2; n++) {
for (m = -1; m <= 2; m++) {
x1 = i + n;
y1 = j + m;
if (x1 > 0 && x1 < width && y1 > 0 && y1 < height) {
float data[4];
if (float_output) {
const float *float_data = float_buffer + width * y1 * components + components * x1;
vector_from_float(float_data, data, components);
}
else {
const unsigned char *byte_data = byte_buffer + width * y1 * components + components * x1;
vector_from_byte(byte_data, data, components);
}
if (components == 1) {
out[0] += data[0] * P(n - a) * P(b - m);
}
else if (components == 3) {
out[0] += data[0] * P(n - a) * P(b - m);
out[1] += data[1] * P(n - a) * P(b - m);
out[2] += data[2] * P(n - a) * P(b - m);
}
else {
out[0] += data[0] * P(n - a) * P(b - m);
out[1] += data[1] * P(n - a) * P(b - m);
out[2] += data[2] * P(n - a) * P(b - m);
out[3] += data[3] * P(n - a) * P(b - m);
}
}
}
}
#endif
if (float_output) {
if (components == 1) {
float_output[0] = out[0];
}
else if (components == 3) {
copy_v3_v3(float_output, out);
}
else {
copy_v4_v4(float_output, out);
}
}
else {
if (components == 1) {
byte_output[0] = (unsigned char)(out[0] + 0.5f);
}
else if (components == 3) {
byte_output[0] = (unsigned char)(out[0] + 0.5f);
byte_output[1] = (unsigned char)(out[1] + 0.5f);
byte_output[2] = (unsigned char)(out[2] + 0.5f);
}
else {
byte_output[0] = (unsigned char)(out[0] + 0.5f);
byte_output[1] = (unsigned char)(out[1] + 0.5f);
byte_output[2] = (unsigned char)(out[2] + 0.5f);
byte_output[3] = (unsigned char)(out[3] + 0.5f);
}
}
}
void BLI_bicubic_interpolation_fl(const float *buffer, float *output, int width, int height,
int components, float u, float v)
{
bicubic_interpolation(NULL, buffer, NULL, output, width, height, components, u, v);
}
void BLI_bicubic_interpolation_char(const unsigned char *buffer, unsigned char *output, int width, int height,
int components, float u, float v)
{
bicubic_interpolation(buffer, NULL, output, NULL, width, height, components, u, v);
}
/* BILINEAR INTERPOLATION */
BLI_INLINE void bilinear_interpolation(const unsigned char *byte_buffer, const float *float_buffer,
unsigned char *byte_output, float *float_output, int width, int height,
int components, float u, float v, bool wrap_x, bool wrap_y)
{
float a, b;
float a_b, ma_b, a_mb, ma_mb;
int y1, y2, x1, x2;
/* ImBuf in must have a valid rect or rect_float, assume this is already checked */
x1 = (int)floor(u);
x2 = (int)ceil(u);
y1 = (int)floor(v);
y2 = (int)ceil(v);
if (float_output) {
const float *row1, *row2, *row3, *row4;
float empty[4] = {0.0f, 0.0f, 0.0f, 0.0f};
/* pixel value must be already wrapped, however values at boundaries may flip */
if (wrap_x) {
if (x1 < 0) x1 = width - 1;
if (x2 >= width) x2 = 0;
}
else if (x2 < 0 || x1 >= width) {
copy_vn_fl(float_output, components, 0.0f);
return;
}
if (wrap_y) {
if (y1 < 0) y1 = height - 1;
if (y2 >= height) y2 = 0;
}
else if (y2 < 0 || y1 >= height) {
copy_vn_fl(float_output, components, 0.0f);
return;
}
/* sample including outside of edges of image */
if (x1 < 0 || y1 < 0) row1 = empty;
else row1 = float_buffer + width * y1 * components + components * x1;
if (x1 < 0 || y2 > height - 1) row2 = empty;
else row2 = float_buffer + width * y2 * components + components * x1;
if (x2 > width - 1 || y1 < 0) row3 = empty;
else row3 = float_buffer + width * y1 * components + components * x2;
if (x2 > width - 1 || y2 > height - 1) row4 = empty;
else row4 = float_buffer + width * y2 * components + components * x2;
a = u - floorf(u);
b = v - floorf(v);
a_b = a * b; ma_b = (1.0f - a) * b; a_mb = a * (1.0f - b); ma_mb = (1.0f - a) * (1.0f - b);
if (components == 1) {
float_output[0] = ma_mb * row1[0] + a_mb * row3[0] + ma_b * row2[0] + a_b * row4[0];
}
else if (components == 3) {
float_output[0] = ma_mb * row1[0] + a_mb * row3[0] + ma_b * row2[0] + a_b * row4[0];
float_output[1] = ma_mb * row1[1] + a_mb * row3[1] + ma_b * row2[1] + a_b * row4[1];
float_output[2] = ma_mb * row1[2] + a_mb * row3[2] + ma_b * row2[2] + a_b * row4[2];
}
else {
float_output[0] = ma_mb * row1[0] + a_mb * row3[0] + ma_b * row2[0] + a_b * row4[0];
float_output[1] = ma_mb * row1[1] + a_mb * row3[1] + ma_b * row2[1] + a_b * row4[1];
float_output[2] = ma_mb * row1[2] + a_mb * row3[2] + ma_b * row2[2] + a_b * row4[2];
float_output[3] = ma_mb * row1[3] + a_mb * row3[3] + ma_b * row2[3] + a_b * row4[3];
}
}
else {
const unsigned char *row1, *row2, *row3, *row4;
unsigned char empty[4] = {0, 0, 0, 0};
/* pixel value must be already wrapped, however values at boundaries may flip */
if (wrap_x) {
if (x1 < 0) x1 = width - 1;
if (x2 >= width) x2 = 0;
}
else if (x2 < 0 || x1 >= width) {
copy_vn_uchar(byte_output, components, 0);
return;
}
if (wrap_y) {
if (y1 < 0) y1 = height - 1;
if (y2 >= height) y2 = 0;
}
else if (y2 < 0 || y1 >= height) {
copy_vn_uchar(byte_output, components, 0);
return;
}
/* sample including outside of edges of image */
if (x1 < 0 || y1 < 0) row1 = empty;
else row1 = byte_buffer + width * y1 * components + components * x1;
if (x1 < 0 || y2 > height - 1) row2 = empty;
else row2 = byte_buffer + width * y2 * components + components * x1;
if (x2 > width - 1 || y1 < 0) row3 = empty;
else row3 = byte_buffer + width * y1 * components + components * x2;
if (x2 > width - 1 || y2 > height - 1) row4 = empty;
else row4 = byte_buffer + width * y2 * components + components * x2;
a = u - floorf(u);
b = v - floorf(v);
a_b = a * b; ma_b = (1.0f - a) * b; a_mb = a * (1.0f - b); ma_mb = (1.0f - a) * (1.0f - b);
if (components == 1) {
byte_output[0] = (unsigned char)(ma_mb * row1[0] + a_mb * row3[0] + ma_b * row2[0] + a_b * row4[0] + 0.5f);
}
else if (components == 3) {
byte_output[0] = (unsigned char)(ma_mb * row1[0] + a_mb * row3[0] + ma_b * row2[0] + a_b * row4[0] + 0.5f);
byte_output[1] = (unsigned char)(ma_mb * row1[1] + a_mb * row3[1] + ma_b * row2[1] + a_b * row4[1] + 0.5f);
byte_output[2] = (unsigned char)(ma_mb * row1[2] + a_mb * row3[2] + ma_b * row2[2] + a_b * row4[2] + 0.5f);
}
else {
byte_output[0] = (unsigned char)(ma_mb * row1[0] + a_mb * row3[0] + ma_b * row2[0] + a_b * row4[0] + 0.5f);
byte_output[1] = (unsigned char)(ma_mb * row1[1] + a_mb * row3[1] + ma_b * row2[1] + a_b * row4[1] + 0.5f);
byte_output[2] = (unsigned char)(ma_mb * row1[2] + a_mb * row3[2] + ma_b * row2[2] + a_b * row4[2] + 0.5f);
byte_output[3] = (unsigned char)(ma_mb * row1[3] + a_mb * row3[3] + ma_b * row2[3] + a_b * row4[3] + 0.5f);
}
}
}
void BLI_bilinear_interpolation_fl(const float *buffer, float *output, int width, int height,
int components, float u, float v)
{
bilinear_interpolation(NULL, buffer, NULL, output, width, height, components, u, v, false, false);
}
void BLI_bilinear_interpolation_char(const unsigned char *buffer, unsigned char *output, int width, int height,
int components, float u, float v)
{
bilinear_interpolation(buffer, NULL, output, NULL, width, height, components, u, v, false, false);
}
void BLI_bilinear_interpolation_wrap_fl(const float *buffer, float *output, int width, int height,
int components, float u, float v, bool wrap_x, bool wrap_y)
{
bilinear_interpolation(NULL, buffer, NULL, output, width, height, components, u, v, wrap_x, wrap_y);
}
void BLI_bilinear_interpolation_wrap_char(const unsigned char *buffer, unsigned char *output, int width, int height,
int components, float u, float v, bool wrap_x, bool wrap_y)
{
bilinear_interpolation(buffer, NULL, output, NULL, width, height, components, u, v, wrap_x, wrap_y);
}
/**************************************************************************
* Filtering method based on
* "Creating raster omnimax images from multiple perspective views using the elliptical weighted average filter"
* by <NAME> and <NAME> (1986)
***************************************************************************/
/* table of (exp(ar) - exp(a)) / (1 - exp(a)) for r in range [0, 1] and a = -2
* used instead of actual gaussian, otherwise at high texture magnifications circular artifacts are visible */
#define EWA_MAXIDX 255
const float EWA_WTS[EWA_MAXIDX + 1] = {
1.f, 0.990965f, 0.982f, 0.973105f, 0.96428f, 0.955524f, 0.946836f, 0.938216f, 0.929664f,
0.921178f, 0.912759f, 0.904405f, 0.896117f, 0.887893f, 0.879734f, 0.871638f, 0.863605f,
0.855636f, 0.847728f, 0.839883f, 0.832098f, 0.824375f, 0.816712f, 0.809108f, 0.801564f,
0.794079f, 0.786653f, 0.779284f, 0.771974f, 0.76472f, 0.757523f, 0.750382f, 0.743297f,
0.736267f, 0.729292f, 0.722372f, 0.715505f, 0.708693f, 0.701933f, 0.695227f, 0.688572f,
0.68197f, 0.67542f, 0.66892f, 0.662471f, 0.656073f, 0.649725f, 0.643426f, 0.637176f,
0.630976f, 0.624824f, 0.618719f, 0.612663f, 0.606654f, 0.600691f, 0.594776f, 0.588906f,
0.583083f, 0.577305f, 0.571572f, 0.565883f, 0.56024f, 0.55464f, 0.549084f, 0.543572f,
0.538102f, 0.532676f, 0.527291f, 0.521949f, 0.516649f, 0.511389f, 0.506171f, 0.500994f,
0.495857f, 0.490761f, 0.485704f, 0.480687f, 0.475709f, 0.470769f, 0.465869f, 0.461006f,
0.456182f, 0.451395f, 0.446646f, 0.441934f, 0.437258f, 0.432619f, 0.428017f, 0.42345f,
0.418919f, 0.414424f, 0.409963f, 0.405538f, 0.401147f, 0.39679f, 0.392467f, 0.388178f,
0.383923f, 0.379701f, 0.375511f, 0.371355f, 0.367231f, 0.363139f, 0.359079f, 0.355051f,
0.351055f, 0.347089f, 0.343155f, 0.339251f, 0.335378f, 0.331535f, 0.327722f, 0.323939f,
0.320186f, 0.316461f, 0.312766f, 0.3091f, 0.305462f, 0.301853f, 0.298272f, 0.294719f,
0.291194f, 0.287696f, 0.284226f, 0.280782f, 0.277366f, 0.273976f, 0.270613f, 0.267276f,
0.263965f, 0.26068f, 0.257421f, 0.254187f, 0.250979f, 0.247795f, 0.244636f, 0.241502f,
0.238393f, 0.235308f, 0.232246f, 0.229209f, 0.226196f, 0.223206f, 0.220239f, 0.217296f,
0.214375f, 0.211478f, 0.208603f, 0.20575f, 0.20292f, 0.200112f, 0.197326f, 0.194562f,
0.191819f, 0.189097f, 0.186397f, 0.183718f, 0.18106f, 0.178423f, 0.175806f, 0.17321f,
0.170634f, 0.168078f, 0.165542f, 0.163026f, 0.16053f, 0.158053f, 0.155595f, 0.153157f,
0.150738f, 0.148337f, 0.145955f, 0.143592f, 0.141248f, 0.138921f, 0.136613f, 0.134323f,
0.132051f, 0.129797f, 0.12756f, 0.125341f, 0.123139f, 0.120954f, 0.118786f, 0.116635f,
0.114501f, 0.112384f, 0.110283f, 0.108199f, 0.106131f, 0.104079f, 0.102043f, 0.100023f,
0.0980186f, 0.09603f, 0.094057f, 0.0920994f, 0.0901571f, 0.08823f, 0.0863179f, 0.0844208f,
0.0825384f, 0.0806708f, 0.0788178f, 0.0769792f, 0.0751551f, 0.0733451f, 0.0715493f, 0.0697676f,
0.0679997f, 0.0662457f, 0.0645054f, 0.0627786f, 0.0610654f, 0.0593655f, 0.0576789f, 0.0560055f,
0.0543452f, 0.0526979f, 0.0510634f, 0.0494416f, 0.0478326f, 0.0462361f, 0.0446521f, 0.0430805f,
0.0415211f, 0.039974f, 0.0384389f, 0.0369158f, 0.0354046f, 0.0339052f, 0.0324175f, 0.0309415f,
0.029477f, 0.0280239f, 0.0265822f, 0.0251517f, 0.0237324f, 0.0223242f, 0.020927f, 0.0195408f,
0.0181653f, 0.0168006f, 0.0154466f, 0.0141031f, 0.0127701f, 0.0114476f, 0.0101354f, 0.00883339f,
0.00754159f, 0.00625989f, 0.00498819f, 0.00372644f, 0.00247454f, 0.00123242f, 0.f
};
static void radangle2imp(float a2, float b2, float th, float *A, float *B, float *C, float *F)
{
float ct2 = cosf(th);
const float st2 = 1.0f - ct2 * ct2; /* <- sin(th)^2 */
ct2 *= ct2;
*A = a2 * st2 + b2 * ct2;
*B = (b2 - a2) * sinf(2.0f * th);
*C = a2 * ct2 + b2 * st2;
*F = a2 * b2;
}
/* all tests here are done to make sure possible overflows are hopefully minimized */
void BLI_ewa_imp2radangle(float A, float B, float C, float F, float *a, float *b, float *th, float *ecc)
{
if (F <= 1e-5f) { /* use arbitrary major radius, zero minor, infinite eccentricity */
*a = sqrtf(A > C ? A : C);
*b = 0.0f;
*ecc = 1e10f;
*th = 0.5f * (atan2f(B, A - C) + (float)M_PI);
}
else {
const float AmC = A - C, ApC = A + C, F2 = F * 2.0f;
const float r = sqrtf(AmC * AmC + B * B);
float d = ApC - r;
*a = (d <= 0.0f) ? sqrtf(A > C ? A : C) : sqrtf(F2 / d);
d = ApC + r;
if (d <= 0.0f) {
*b = 0.0f;
*ecc = 1e10f;
}
else {
*b = sqrtf(F2 / d);
*ecc = *a / *b;
}
/* incr theta by 0.5*pi (angle of major axis) */
*th = 0.5f * (atan2f(B, AmC) + (float)M_PI);
}
}
void BLI_ewa_filter(const int width, const int height,
const bool intpol,
const bool use_alpha,
const float uv[2],
const float du[2],
const float dv[2],
ewa_filter_read_pixel_cb read_pixel_cb,
void *userdata,
float result[4])
{
/* scaling dxt/dyt by full resolution can cause overflow because of huge A/B/C and esp. F values,
* scaling by aspect ratio alone does the opposite, so try something in between instead... */
const float ff2 = (float)width, ff = sqrtf(ff2), q = (float)height / ff;
const float Ux = du[0] * ff, Vx = du[1] * q, Uy = dv[0] * ff, Vy = dv[1] * q;
float A = Vx * Vx + Vy * Vy;
float B = -2.0f * (Ux * Vx + Uy * Vy);
float C = Ux * Ux + Uy * Uy;
float F = A * C - B * B * 0.25f;
float a, b, th, ecc, a2, b2, ue, ve, U0, V0, DDQ, U, ac1, ac2, BU, d;
int u, v, u1, u2, v1, v2;
/* The so-called 'high' quality ewa method simply adds a constant of 1 to both A & C,
* so the ellipse always covers at least some texels. But since the filter is now always larger,
* it also means that everywhere else it's also more blurry then ideally should be the case.
* So instead here the ellipse radii are modified instead whenever either is too low.
* Use a different radius based on interpolation switch, just enough to anti-alias when interpolation is off,
* and slightly larger to make result a bit smoother than bilinear interpolation when interpolation is on
* (minimum values: const float rmin = intpol ? 1.f : 0.5f;) */
const float rmin = (intpol ? 1.5625f : 0.765625f) / ff2;
BLI_ewa_imp2radangle(A, B, C, F, &a, &b, &th, &ecc);
if ((b2 = b * b) < rmin) {
if ((a2 = a * a) < rmin) {
B = 0.0f;
A = C = rmin;
F = A * C;
}
else {
b2 = rmin;
radangle2imp(a2, b2, th, &A, &B, &C, &F);
}
}
ue = ff * sqrtf(C);
ve = ff * sqrtf(A);
d = (float)(EWA_MAXIDX + 1) / (F * ff2);
A *= d;
B *= d;
C *= d;
U0 = uv[0] * (float)width;
V0 = uv[1] * (float)height;
u1 = (int)(floorf(U0 - ue));
u2 = (int)(ceilf(U0 + ue));
v1 = (int)(floorf(V0 - ve));
v2 = (int)(ceilf(V0 + ve));
/* sane clamping to avoid unnecessarily huge loops */
/* note: if eccentricity gets clamped (see above),
* the ue/ve limits can also be lowered accordingly
*/
if (U0 - (float)u1 > EWA_MAXIDX) u1 = (int)U0 - EWA_MAXIDX;
if ((float)u2 - U0 > EWA_MAXIDX) u2 = (int)U0 + EWA_MAXIDX;
if (V0 - (float)v1 > EWA_MAXIDX) v1 = (int)V0 - EWA_MAXIDX;
if ((float)v2 - V0 > EWA_MAXIDX) v2 = (int)V0 + EWA_MAXIDX;
/* Early output check for cases the whole region is outside of the buffer. */
if ((u2 < 0 || u1 >= width) || (v2 < 0 || v1 >= height)) {
zero_v4(result);
return;
}
U0 -= 0.5f;
V0 -= 0.5f;
DDQ = 2.0f * A;
U = (float)u1 - U0;
ac1 = A * (2.0f * U + 1.0f);
ac2 = A * U * U;
BU = B * U;
d = 0.0f;
zero_v4(result);
for (v = v1; v <= v2; ++v) {
const float V = (float)v - V0;
float DQ = ac1 + B * V;
float Q = (C * V + BU) * V + ac2;
for (u = u1; u <= u2; ++u) {
if (Q < (float)(EWA_MAXIDX + 1)) {
float tc[4];
const float wt = EWA_WTS[(Q < 0.0f) ? 0 : (unsigned int)Q];
read_pixel_cb(userdata, u, v, tc);
madd_v3_v3fl(result, tc, wt);
result[3] += use_alpha ? tc[3] * wt : 0.0f;
d += wt;
}
Q += DQ;
DQ += DDQ;
}
}
/* d should hopefully never be zero anymore */
d = 1.0f / d;
mul_v3_fl(result, d);
/* clipping can be ignored if alpha used, texr->ta already includes filtered edge */
result[3] = use_alpha ? result[3] * d : 1.0f;
}
|
akochurov/mxcache | mxcache-tests/src/test/java/com/maxifier/mxcache/test/PerformanceFTest.java | <reponame>akochurov/mxcache
/*
* Copyright (c) 2008-2014 Maxifier Ltd. All Rights Reserved.
*/
package com.maxifier.mxcache.test;
import com.maxifier.mxcache.CacheFactory;
import com.maxifier.mxcache.Cached;
import com.maxifier.mxcache.DependencyTracking;
import com.maxifier.mxcache.clean.CacheCleaner;
import com.maxifier.mxcache.resource.TrackDependency;
import org.testng.Assert;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
/**
* @author <NAME> (<EMAIL>)
*/
@Test(enabled = false)
public class PerformanceFTest {
private static final CacheCleaner CLEANER = CacheFactory.getCleaner();
private static final String[] KEYS;
private static final int MAX_TUPLE_INT_MISS_OVERHEAD = 8000;
private static final int MAX_TUPLE_INT_HIT_OVERHEAD = 3500;
private static final int MAX_INT_INT_MISS_OVERHEAD = 7000;
private static final int MAX_INT_INT_HIT_OVERHEAD = 3000;
private static final int MAX_DEPENDENCY_OVERHEAD = 3000;
private static final int MAX_CLEAR_OVERHEAD = 300000;
private static final int MAX_OBJECT_OBJECT_MISS_OVERHEAD = 10000;
private static final int MAX_OBJECT_OBJECT_HIT_OVERHEAD = 2000;
private static final int MAX_OBJECT_HIT_OVERHEAD = 1000;
private static final int N = 50000;
private static final int M = 1000;
static {
KEYS = new String[N];
for (int i = 0; i < N; i++) {
String s = Integer.toString(i);
//noinspection ResultOfMethodCallIgnored
s.hashCode();
KEYS[i] = s;
}
}
static class T {
@Cached
@TrackDependency(DependencyTracking.INSTANCE)
public static String testChainA(int x) {
return "123" + x;
}
@Cached
@TrackDependency(DependencyTracking.INSTANCE)
public String testChainB(int x) {
return testChainA(x);
}
@Cached
public String getStringToString(String src) {
return src;
}
public String missStringToString(String src) {
return src;
}
@Cached
public int getIntToInt(int src) {
return src;
}
public int missIntToInt(int src) {
return src;
}
@Cached
public int getTupleToInt(int a, int b) {
return a + b;
}
public int missInt(int a, int b) {
return a + b;
}
@Cached
public String getString() {
return "123";
}
public String missString() {
return "123";
}
}
public void testMisses() {
T t = new T();
long t1 = 0;
for (int i = 0; i < 10; i++) {
clear(t);
long start = System.nanoTime();
batchGet(t, N, 1);
long end = System.nanoTime();
t1 += end - start;
}
long start = System.nanoTime();
for (int i = 0; i < 10; i++) {
batchMiss(t, N, 1);
}
long end = System.nanoTime();
long t2 = end - start;
long overhead = (t1 - t2) / N;
checkTime("Miss overhead", overhead, MAX_OBJECT_OBJECT_MISS_OVERHEAD);
}
public void testMissesInt() {
T t = new T();
long t1 = 0;
for (int i = 0; i < 10; i++) {
clear(t);
long start = System.nanoTime();
batchGetInt(t, N, 1);
long end = System.nanoTime();
t1 += end - start;
}
long start = System.nanoTime();
for (int i = 0; i < 10; i++) {
batchMissInt(t, N, 1);
}
long end = System.nanoTime();
long t2 = end - start;
long overhead = (t1 - t2) / N;
checkTime("Miss int overhead", overhead, MAX_INT_INT_MISS_OVERHEAD);
}
public void testMissesTuple() {
T t = new T();
long t1 = 0;
for (int i = 0; i < 10; i++) {
clear(t);
long start = System.nanoTime();
batchGetTuple(t, N, 1);
long end = System.nanoTime();
t1 += end - start;
}
long start = System.nanoTime();
for (int i = 0; i < 10; i++) {
batchMissTuple(t, N, 1);
}
long end = System.nanoTime();
long t2 = end - start;
long overhead = (t1 - t2) / N;
checkTime("Miss tuple overhead", overhead, MAX_TUPLE_INT_MISS_OVERHEAD);
}
public void testHitsNoArg() {
T t = new T();
batchGet(t, N);
long t1 = 0;
for (int i = 0; i < 10; i++) {
long start = System.nanoTime();
batchGet(t, N);
long end = System.nanoTime();
t1 += end - start;
}
long overhead = t1 / N;
checkTime("Hit no arg overhead", overhead, MAX_OBJECT_HIT_OVERHEAD);
}
public void testHits() {
T t = new T();
clear(t);
batchGet(t, 5000, 1);
long start = System.nanoTime();
for (int i = 0; i < 10; i++) {
batchGet(t, N / 10, 10);
}
long end = System.nanoTime();
long overhead = (end - start) / N;
checkTime("Hit overhead", overhead, MAX_OBJECT_OBJECT_HIT_OVERHEAD);
}
public void testHitsTuple() {
T t = new T();
clear(t);
batchGetTuple(t, 5000, 1);
long start = System.nanoTime();
for (int i = 0; i < 10; i++) {
batchGetTuple(t, N / 10, 10);
}
long end = System.nanoTime();
long overhead = (end - start) / N;
checkTime("Hit tuple overhead", overhead, MAX_TUPLE_INT_HIT_OVERHEAD);
}
public void testHitsInt() {
T t = new T();
clear(t);
batchGet(t, 5000, 1);
long start = System.nanoTime();
for (int i = 0; i < 10; i++) {
batchGetInt(t, N / 10, 10);
}
long end = System.nanoTime();
long overhead = (end - start) / N;
checkTime("Hit int overhead", overhead, MAX_INT_INT_HIT_OVERHEAD);
}
public void testHitsIntWithProxy() {
T t = new T();
clear(t);
batchGet(t, 5000, 1);
long start = System.nanoTime();
for (int i = 0; i < 10; i++) {
batchGetInt(t, N / 10, 10);
}
long end = System.nanoTime();
long overhead = (end - start) / N;
checkTime("Hit int overhead", overhead, MAX_INT_INT_HIT_OVERHEAD);
}
public void testDependencyTracking() {
T t = new T();
long start = System.nanoTime();
for (int i = 0; i < 10; i++) {
clear(t);
batchChain(t, N / 10, 1);
}
long end = System.nanoTime();
long overhead = (end - start) / N;
checkTime("Chain with dependency", overhead, MAX_DEPENDENCY_OVERHEAD);
}
public void testClearByClass() {
T t = new T();
clear(t);
long start = System.nanoTime();
batchClear(M);
long end = System.nanoTime();
long overhead = (end - start) / M;
checkTime("Clear by class", overhead, MAX_CLEAR_OVERHEAD);
}
private static void batchClear(int n) {
for (int i = 0; i<n; i++) {
CLEANER.clearCacheByClass(T.class);
}
}
@SuppressWarnings({"UnusedParameters"})
private void clear(T t) {
// CLEANER.clearCacheByInstance(t);
CLEANER.clearCacheByClass(T.class);
}
private static void batchChain(T t, int width, int n) {
while (n --> 0) {
for (int i = 0; i<width; i++) {
t.testChainB(i);
}
}
}
@BeforeClass
public void makeItHot() {
T t = new T();
for (int i = 0; i < 100; i++) {
batchGet(t, 1000, 10);
batchMiss(t, 1000, 10);
batchGetTuple(t, 1000, 10);
batchGet(t, 10000);
batchMiss(t, 10000);
batchChain(t, 5000, 10);
batchClear(M);
clear(t);
}
}
private static void batchGet(T t, int width, int n) {
while (n-- > 0) {
for (int i = 0; i < width; i++) {
t.getStringToString(KEYS[i]);
}
}
}
private static void batchGetInt(T t, int width, int n) {
while (n-- > 0) {
for (int i = 0; i < width; i++) {
t.getIntToInt(i);
}
}
}
private static void batchGetTuple(T t, int width, int n) {
while (n-- > 0) {
for (int i = 0; i < width; i++) {
t.getTupleToInt(i, i / 2);
}
}
}
private static void batchGet(T t, int n) {
while (n-- > 0) {
t.getString();
}
}
private static void batchMiss(T t, int width, int n) {
while (n-- > 0) {
for (int i = 0; i < width; i++) {
t.missStringToString(KEYS[i]);
}
}
}
private static void batchMissInt(T t, int width, int n) {
while (n-- > 0) {
for (int i = 0; i < width; i++) {
t.missIntToInt(i);
}
}
}
private static void batchMissTuple(T t, int width, int n) {
while (n-- > 0) {
for (int i = 0; i < width; i++) {
t.missInt(i, i / 2);
}
}
}
private static void batchMiss(T t, int n) {
while (n-- > 0) {
t.missString();
}
}
private static void checkTime(String label, long time, int maxTime) {
System.out.println(label + " = " + time + " / " + maxTime);
System.out.flush();
Assert.assertTrue(time < maxTime, label + " (" + time + ") should be less than " + maxTime);
}
}
|
Domiii/self-asssessment-app | src/views/components/submissions/SubmissionEntry.js | import React, { PureComponent, PropTypes } from 'react';
import Moment from 'react-moment';
import {
ListGroup, ListGroupItem, Well
} from 'react-bootstrap';
import { Link } from 'react-router';
import { FAIcon } from 'src/views/components/util';
import classNames from 'classnames';
import { hrefConceptView } from 'src/views/href';
import isEqual from 'lodash/isEqual';
import SubmissionEntryTitle from './SubmissionEntryTitle';
import SubmissionEntryContent from './SubmissionEntryContent';
import SubmissionFeedbackList from './SubmissionFeedbackList';
export default class SubmissionEntry extends PureComponent {
static propTypes = {
submissionId: PropTypes.string.isRequired,
submission: PropTypes.object.isRequired,
addFeedback: PropTypes.func,
updateFeedback: PropTypes.func
};
static contextTypes = {
lookupLocalized: PropTypes.func.isRequired
};
shouldComponentUpdate(nextProps, nextState) {
return !isEqual(nextProps, this.props);
}
SubmissionContentEl() {
const {
submission: {
text,
hasSubmitted
}
} = this.props;
return !hasSubmitted ? null : (<pre className="list-group-item-text">
{ text }
</pre>);
}
render() {
let {
submissionId,
submission,
submission: {
uid,
conceptId,
text,
hasSubmitted,
updatedAt
},
addFeedback,
updateFeedback
} = this.props;
// renderCalls[submissionId] = renderCalls[submissionId] ? (renderCalls[submissionId] + 1) : 1;
// the weird names are due to `populate` not allowing aliasing the populated object's key
// see: https://github.com/prescottprue/react-redux-firebase/issues/126
const user = uid;
uid = user.uid;
const concept = conceptId;
conceptId = concept.conceptId;
const classes = classNames({
'submission-entry': true,
'submission-entry-ready': hasSubmitted,
'submission-entry-not-ready': !hasSubmitted
});
return (
<ListGroupItem className={classes}>
<SubmissionEntryTitle {...{
user,
concept,
hasSubmitted,
updatedAt
}} />
<hr />
<div className="submission-columns">
<SubmissionEntryContent {...{
text,
hasSubmitted
}} />
<SubmissionFeedbackList {...{
submissionId,
submission,
feedback: submission.feedback,
feedbackDetails: submission.feedbackDetails,
addFeedback,
updateFeedback
}} />
</div>
</ListGroupItem>
);
}
} |
joshsuson/joshsuson-frontend | src/components/AllJobs.js | <gh_stars>0
import React from "react"
import Heading from "./Heading"
import Img from "gatsby-image"
import { Link } from "gatsby"
export default function AllJobs({ data, heading, type }) {
return (
<div className="px-4 lg:px-14 pt-20 mb-20">
<Heading text={heading} align="text-center mb-20" />
<div>
{data.map(job => (
<div
key={job.name}
className="grid gap-6 lg:gap-14 xl:gap-20 mb-16 lg:mb-20 grid-cols-1 lg:grid-cols-2 xl:grid-cols-3"
>
<div>
<div className="xl:w-80 lg:h-60 bg-gradient-to-r from-customRed to-orange">
<Img
className="h-full transform translate-x-2 translate-y-2"
fluid={job.featuredImage.asset.fluid}
alt={`${job.name} screenshot`}
/>
</div>
</div>
<div className="xl:col-span-2">
<h2 className="text-xl tracking-wide mb-1">{job.name}</h2>
<h4 className="italic text-gray-700 mb-4">{job.description}</h4>
<div className="grid lg:grid-rows-4 grid-cols-3 lg:grid-cols-4 xl:grid-cols-6 lg:grid-flow-col gap-2 mb-4">
{job.technologiesUsed.map(tech => (
<p
key={tech.name}
className="rounded-sm text-center py-1 text-sm"
style={{ backgroundColor: `${tech.color}` }}
>
{tech.name}
</p>
))}
</div>
<div className="p-0.5 transition-all lg:text-left text-center mt-8">
<Link
className="bg-gradient-to-r from-customRed to-orange block bg-clip-text text-transparent uppercase text-base font-semibold tracking-wide"
to={`/${type}/${job.slug.current}`}
>
<span className="underline-hover">Read the case study</span>
</Link>
</div>
</div>
</div>
))}
</div>
</div>
)
}
|
kliegeois/ginkgo | accessor/range.hpp | <filename>accessor/range.hpp
/*******************************<GINKGO LICENSE>******************************
Copyright (c) 2017-2022, the Ginkgo authors
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
******************************<GINKGO LICENSE>*******************************/
#ifndef GKO_ACCESSOR_RANGE_HPP_
#define GKO_ACCESSOR_RANGE_HPP_
#include <utility>
#include "utils.hpp"
namespace gko {
namespace acc {
template <typename Accessor>
class range {
private:
/**
* the default check_if_same gives false.
*
* @tparam Ref the reference type
* @tparam Args the input type
*/
template <typename Ref, typename... Args>
struct check_if_same : public std::false_type {};
/**
* check_if_same gives true if the decay type of input is the same type as
* Ref.
*
* @tparam Ref the reference type
*/
template <typename Ref>
struct check_if_same<Ref, Ref> : public std::true_type {};
public:
/**
* The type of the underlying accessor.
*/
using accessor = Accessor;
/**
* The number of dimensions of the range.
*/
static constexpr size_type dimensionality = accessor::dimensionality;
/**
* Use the default destructor.
*/
~range() = default;
/**
* Creates a new range.
*
* @tparam AccessorParam types of parameters forwarded to the accessor
* constructor.
*
* @param params parameters forwarded to Accessor constructor.
*
* @note We use SFINAE to allow for a default copy and move constructor to
* be generated, so a `range` is trivially copyable if the `Accessor`
* is trivially copyable.
*/
template <typename... AccessorParams,
std::enable_if_t<
!check_if_same<range, std::decay_t<AccessorParams>...>::value,
int> = 0>
GKO_ACC_ATTRIBUTES constexpr explicit range(AccessorParams&&... args)
: accessor_{std::forward<AccessorParams>(args)...}
{}
/**
* Returns a value (or a sub-range) with the specified indexes.
*
* @tparam DimensionTypes The types of indexes. Supported types depend on
* the underlying accessor, but are usually either
* integer types or index_spans. If at least one
* index is a span, the returned value will be a
* sub-range (if that is supported by the accessor).
*
* @param dimensions the indexes of the values or index_spans for the new
* range.
*
* @return a value on position `(dimensions...)` or a sub-range with the
* given index_spans.
*/
template <typename... DimensionTypes>
GKO_ACC_ATTRIBUTES constexpr auto operator()(DimensionTypes&&... dimensions)
const -> decltype(std::declval<accessor>()(
std::forward<DimensionTypes>(dimensions)...))
{
static_assert(sizeof...(dimensions) <= dimensionality,
"Too many dimensions in range call");
return accessor_(std::forward<DimensionTypes>(dimensions)...);
}
/**
* Returns the length of the specified dimension of the range.
*
* @param dimension the dimensions whose length is returned
*
* @return the length of the `dimension`-th dimension of the range
*/
GKO_ACC_ATTRIBUTES constexpr size_type length(size_type dimension) const
{
return accessor_.length(dimension);
}
/**
* Returns a pointer to the accessor.
*
* Can be used to access data and functions of a specific accessor.
*
* @return pointer to the accessor
*/
GKO_ACC_ATTRIBUTES constexpr const accessor* operator->() const noexcept
{
return &accessor_;
}
/**
* `Returns a reference to the accessor.
*
* @return reference to the accessor
*/
GKO_ACC_ATTRIBUTES constexpr const accessor& get_accessor() const noexcept
{
return accessor_;
}
private:
accessor accessor_;
};
} // namespace acc
} // namespace gko
#endif // GKO_ACCESSOR_RANGE_HPP_
|
mcardy-ux/hotel | public/js/parameters/planCuentas/index.js | function show(event){
var ID =event.id;
let confirmacion=confirm("¿Esta seguro de eliminar? No puede reversar esta accion.");
if(confirmacion){
$.ajax({
url: $("#_url").val() + '/planCuentas/' + ID,
headers: {'X-CSRF-TOKEN': $('#_token').val()},
type: 'DELETE',
success: function (response) {
var json = $.parseJSON(response);
if(json.success){
alert('Plan de Cuentas eliminada exitosamente');
location.href=$("#_url").val()+'/planCuentas';
}else{
alert(json.data);
}
}
}).fail( function( response ) {
alert( 'Error 101-1 : No se puede Eliminar - Verifique Llaves Foraneas!' );
});
return false;
}
}
function viewCentros(event){
document.getElementById("modal_content_centros").innerHTML="";
var ID =event.id;
$("#modal_centros").modal('show');
$.ajax({
url: $("#_url").val()+"/ajax/request/getCentros/"+ID,
headers: {'X-CSRF-TOKEN': $('#_token').val()},
type: 'GET',
cache: false,
success: function (response) {
var json = $.parseJSON(response);
if(json.success){
let concat='<table class="table"><thead class="thead-light"><tr><th scope="col">#</th><th scope="col">Codigo de Cuenta</th><th scope="col">Nombre de Cuenta</th></tr></thead><tbody>';
for (let index = 0; index < json.data.length; index++) {
concat=concat+'<tr><th scope="row">'+json.data[index].id+'</th><td>'+json.data[index].value+'</td><td>'+json.data[index].secvalue+'</td></tr> ';
}
concat=concat+'</tbody></table>';
document.getElementById("modal_content_centros").innerHTML=concat;
}
}
});
return false;
} |
derberg/website-asyncapi | components/navigation/LearningPanel.js | <reponame>derberg/website-asyncapi<filename>components/navigation/LearningPanel.js
import FlyoutMenu from './FlyoutMenu'
import learningItems from './learningItems'
export default function LearningPanel () {
return (
<FlyoutMenu items={learningItems} />
)
} |
JakubKubista/-tsunami-escape | node_modules/server/src/modern/errors.js | <reponame>JakubKubista/-tsunami-escape
const error = require('../../error').defaults({
url: ({ code }) => `https://serverjs.io/documentation/errors/#${
code.toLowerCase().replace(/[^\w]+/g, '-')
}`,
status: 500
});
error['/server/modern/missingmiddleware'] = `
modern() expects a middleware to be passed but nothing was passed.
`;
// error.MissingMiddleware = () => `
// modern() expects a middleware to be passed but nothing was passed.
//`;
error['/server/modern/invalidmiddleware'] = ({ type }) => `
modern() expects the argument to be a middleware function.
"${type}" was passed instead
`;
// error.InvalidMiddleware = ({ type }) => `
// modern() expects the argument to be a middleware function.
// "${type}" was passed instead
// `;
error['/server/modern/errormiddleware'] = `
modern() cannot create a modern middleware that handles errors.
If you can handle an error in your middleware do it there.
Otherwise, use ".catch()" for truly fatal errors as "server().catch()".
`;
// error.ErrorMiddleware = () => `
// modern() cannot create a modern middleware that handles errors.
// If you can handle an error in your middleware do it there.
// Otherwise, use ".catch()" for truly fatal errors as "server().catch()".
// `;
error['/server/modern/missingcontext'] = `
There is no context being passed to the middleware.
`;
// error.MissingContext = () => `
// There is no context being passed to the middleware.
// `;
error['/server/modern/malformedcontext'] = ({ item }) => `
The argument passed as context is malformed.
Expecting it to be an object containing "${item}".
This is most likely an error from "server.modern".
Please report it: https://github.com/franciscop/server/issues
`;
// error.MalformedContext = ({ item }) => `
// The argument passed as context is malformed.
// Expecting it to be an object containing "${item}".
// This is most likely an error from "server.modern".
// Please report it: https://github.com/franciscop/server/issues
// `;
module.exports = error;
|
hugorebelo/gitlabhq | spec/frontend/helpers/dom_shims/scroll_by.js | window.scrollX = 0;
window.scrollY = 0;
window.scrollBy = (x, y) => {
window.scrollX += x;
window.scrollY += y;
};
|
Neusoft-Technology-Solutions/aws-sdk-cpp | aws-cpp-sdk-eventbridge/source/model/ListEventSourcesResult.cpp | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/eventbridge/model/ListEventSourcesResult.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <aws/core/AmazonWebServiceResult.h>
#include <aws/core/utils/StringUtils.h>
#include <aws/core/utils/UnreferencedParam.h>
#include <utility>
using namespace Aws::EventBridge::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
using namespace Aws;
ListEventSourcesResult::ListEventSourcesResult()
{
}
ListEventSourcesResult::ListEventSourcesResult(const Aws::AmazonWebServiceResult<JsonValue>& result)
{
*this = result;
}
ListEventSourcesResult& ListEventSourcesResult::operator =(const Aws::AmazonWebServiceResult<JsonValue>& result)
{
JsonView jsonValue = result.GetPayload().View();
if(jsonValue.ValueExists("EventSources"))
{
Array<JsonView> eventSourcesJsonList = jsonValue.GetArray("EventSources");
for(unsigned eventSourcesIndex = 0; eventSourcesIndex < eventSourcesJsonList.GetLength(); ++eventSourcesIndex)
{
m_eventSources.push_back(eventSourcesJsonList[eventSourcesIndex].AsObject());
}
}
if(jsonValue.ValueExists("NextToken"))
{
m_nextToken = jsonValue.GetString("NextToken");
}
return *this;
}
|
zeesh49/tutorials | libraries/src/main/java/com/baeldung/commons/io/FileMonitor.java | package com.baeldung.commons.io;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.monitor.FileAlterationListener;
import org.apache.commons.io.monitor.FileAlterationListenerAdaptor;
import org.apache.commons.io.monitor.FileAlterationMonitor;
import org.apache.commons.io.monitor.FileAlterationObserver;
import java.io.File;
public class FileMonitor {
public static void main(String[] args) throws Exception {
File folder = FileUtils.getTempDirectory();
startFileMonitor(folder);
}
/**
* @param folder
* @throws Exception
*/
public static void startFileMonitor(File folder) throws Exception {
FileAlterationObserver observer = new FileAlterationObserver(folder);
FileAlterationMonitor monitor = new FileAlterationMonitor(5000);
FileAlterationListener fal = new FileAlterationListenerAdaptor() {
@Override
public void onFileCreate(File file) {
// on create action
}
@Override
public void onFileDelete(File file) {
// on delete action
}
};
observer.addListener(fal);
monitor.addObserver(observer);
monitor.start();
}
} |
uniter/phpcore | src/Function/FunctionSpecFactory.js | /*
* PHPCore - PHP environment runtime components
* Copyright (c) <NAME> (asmblah)
* https://github.com/uniter/phpcore/
*
* Released under the MIT license
* https://github.com/uniter/phpcore/raw/master/MIT-LICENSE.txt
*/
'use strict';
var _ = require('microdash');
/**
* Creates FunctionSpec-related objects
*
* @param {class} FunctionSpec
* @param {class} FunctionContext
* @param {class} MethodContext
* @param {class} ClosureContext
* @param {CallStack} callStack
* @param {ParameterListFactory} parameterListFactory
* @param {ValueFactory} valueFactory
* @constructor
*/
function FunctionSpecFactory(
FunctionSpec,
FunctionContext,
MethodContext,
ClosureContext,
callStack,
parameterListFactory,
valueFactory
) {
/**
* @type {CallStack}
*/
this.callStack = callStack;
/**
* @type {class}
*/
this.ClosureContext = ClosureContext;
/**
* @type {class}
*/
this.FunctionContext = FunctionContext;
/**
* @type {class}
*/
this.FunctionSpec = FunctionSpec;
/**
* @type {class}
*/
this.MethodContext = MethodContext;
/**
* @type {ParameterListFactory}
*/
this.parameterListFactory = parameterListFactory;
/**
* @type {ValueFactory}
*/
this.valueFactory = valueFactory;
}
_.extend(FunctionSpecFactory.prototype, {
/**
* Creates a FunctionSpec for a function alias
*
* @param {NamespaceScope} namespaceScope
* @param {string} functionName
* @param {Parameter[]} parameters
* @param {string|null} filePath
* @param {number|null} lineNumber
* @returns {FunctionSpec}
*/
createAliasFunctionSpec: function (namespaceScope, functionName, parameters, filePath, lineNumber) {
var factory = this,
context = new factory.FunctionContext(namespaceScope, functionName);
return new factory.FunctionSpec(
factory.callStack,
factory.valueFactory,
context,
namespaceScope,
parameters,
filePath,
lineNumber
);
},
/**
* Creates a FunctionSpec from the given spec data for a closure
*
* @param {NamespaceScope} namespaceScope
* @param {Class|null} classObject
* @param {Array} parametersSpecData
* @param {string|null} filePath
* @param {number|null} lineNumber
* @returns {FunctionSpec}
*/
createClosureSpec: function (namespaceScope, classObject, parametersSpecData, filePath, lineNumber) {
var factory = this,
context = new factory.ClosureContext(namespaceScope, classObject),
parameters = factory.parameterListFactory.createParameterList(
context,
parametersSpecData,
namespaceScope,
filePath,
lineNumber
);
return new factory.FunctionSpec(
factory.callStack,
factory.valueFactory,
context,
namespaceScope,
parameters,
filePath,
lineNumber
);
},
/**
* Creates a FunctionSpec from the given spec data
*
* @param {NamespaceScope} namespaceScope
* @param {string} functionName
* @param {Array} parametersSpecData
* @param {string|null} filePath
* @param {number|null} lineNumber
* @returns {FunctionSpec}
*/
createFunctionSpec: function (namespaceScope, functionName, parametersSpecData, filePath, lineNumber) {
var factory = this,
context = new factory.FunctionContext(namespaceScope, functionName),
parameters = factory.parameterListFactory.createParameterList(
context,
parametersSpecData,
namespaceScope,
filePath,
lineNumber
);
return new factory.FunctionSpec(
factory.callStack,
factory.valueFactory,
context,
namespaceScope,
parameters,
filePath,
lineNumber
);
},
/**
* Creates a FunctionSpec from the given spec data for a method
*
* @param {NamespaceScope} namespaceScope
* @param {Class} classObject
* @param {string} methodName
* @param {Array} parametersSpecData
* @param {string|null} filePath
* @param {number|null} lineNumber
* @returns {FunctionSpec}
*/
createMethodSpec: function (namespaceScope, classObject, methodName, parametersSpecData, filePath, lineNumber) {
var factory = this,
context = new factory.MethodContext(classObject, methodName),
parameters = factory.parameterListFactory.createParameterList(
context,
parametersSpecData,
namespaceScope,
filePath,
lineNumber
);
return new factory.FunctionSpec(
factory.callStack,
factory.valueFactory,
context,
namespaceScope,
parameters,
filePath,
lineNumber
);
}
});
module.exports = FunctionSpecFactory;
|
slkim2/mastertheboss | quarkus/panache-rest-demo/src/main/java/com/mastertheboss/Ticket.java | package com.mastertheboss;
import javax.persistence.Column;
import javax.persistence.Entity;
import io.quarkus.hibernate.orm.panache.PanacheEntity;
@Entity
public class Ticket extends PanacheEntity {
@Column(length = 20, unique = true)
public String name;
@Column(length = 3, unique = true)
public String seat;
public Ticket() {
}
public Ticket(String name, String seat) {
this.name = name;
this.seat = seat;
}
} |
TheShinyBunny/HandiClient | src/main/java/com/handicraft/client/rewards/ParticleReward.java | /*
* Copyright (c) 2020. Yaniv - TheShinyBunny
*/
package com.handicraft.client.rewards;
import com.handicraft.client.client.screen.HandiPassScreen;
import com.handicraft.client.collectibles.ParticleTrail;
import com.mojang.blaze3d.systems.RenderSystem;
import net.minecraft.client.MinecraftClient;
import net.minecraft.client.util.math.MatrixStack;
import net.minecraft.client.world.ClientWorld;
import net.minecraft.util.math.MathHelper;
import net.minecraft.util.math.Quaternion;
import net.minecraft.util.math.Vec3d;
public class ParticleReward extends CollectibleReward<ParticleTrail> {
public ParticleReward(String name, int level, int textureHeight, ParticleTrail particleType) {
super(name, level, textureHeight,particleType);
}
@Override
public void onSelect(HandiPassScreen screen) {
super.onSelect(screen);
screen.player.visible = false;
if (MinecraftClient.getInstance().world == null) {
MinecraftClient.getInstance().particleManager.setWorld((ClientWorld) screen.player.world);
} else {
screen.backgroundVisible = false;
}
}
@Override
public void selectTick(HandiPassScreen screen, int ticksHovered) {
super.selectTick(screen, ticksHovered);
MinecraftClient client = MinecraftClient.getInstance();
if (client.player == null) {
screen.addRenderJob(matrices -> {
RenderSystem.pushMatrix();
float w = (screen.width / 1920f) * -1560;
float h = (screen.height / 720f) * -400;
RenderSystem.rotatef(180, 0, 0, 1f);
RenderSystem.translatef(w, h, 0);
client.particleManager.renderParticles(matrices, null, MinecraftClient.getInstance().gameRenderer.getLightmapTextureManager(), MinecraftClient.getInstance().gameRenderer.getCamera(), 1);
RenderSystem.popMatrix();
});
screen.addTickJob(() -> {
if (ticksHovered % 10 == 0) {
client.particleManager.addParticle(collectible.getEffect(), 0, 0, 0, (Math.random() - 0.5) * 4, Math.random() * 8, (Math.random() - 0.5) * 4);
}
try {
client.particleManager.tick();
} catch (Exception ignored) {
}
});
} else if (ticksHovered % 40 == 0) {
Vec3d camPos = client.gameRenderer.getCamera().getPos();
float f = client.gameRenderer.getCamera().getPitch() * 0.017453292F;
float g = -(client.gameRenderer.getCamera().getYaw() + 55) * 0.017453292F;
float h = MathHelper.cos(g);
float i = MathHelper.sin(g);
float j = MathHelper.cos(f);
float k = MathHelper.sin(f);
Vec3d rot = new Vec3d(i * j, -k, h * j);
camPos = camPos.add(rot.multiply(2));
client.player.world.addParticle(collectible.getEffect(), camPos.getX(), camPos.getY(), camPos.getZ(), (Math.random() - 0.5) * 0.05, Math.random() * 0.2, (Math.random() - 0.5) * 0.05);
}
}
@Override
public void onDeselect(HandiPassScreen screen) {
super.onDeselect(screen);
screen.player.visible = true;
if (MinecraftClient.getInstance().world != null) {
screen.backgroundVisible = true;
}
}
}
|
nhl/link-rest | agrest-engine/src/main/java/io/agrest/meta/LazyEntity.java | <filename>agrest-engine/src/main/java/io/agrest/meta/LazyEntity.java<gh_stars>10-100
package io.agrest.meta;
import io.agrest.access.CreateAuthorizer;
import io.agrest.access.DeleteAuthorizer;
import io.agrest.access.ReadFilter;
import io.agrest.access.UpdateAuthorizer;
import io.agrest.resolver.RootDataResolver;
import java.util.Collection;
import java.util.function.Supplier;
/**
* @since 5.0
*/
public class LazyEntity<T> extends BaseLazyEntity<T, AgEntity<T>> implements AgEntity<T> {
private final Class<T> type;
public LazyEntity(Class<T> type, Supplier<AgEntity<T>> delegateSupplier) {
super(delegateSupplier);
this.type = type;
}
@Override
public String getName() {
return getDelegate().getName();
}
@Override
public Class<T> getType() {
return type;
}
@Override
public Collection<AgIdPart> getIdParts() {
return getDelegate().getIdParts();
}
@Override
public AgIdPart getIdPart(String name) {
return getDelegate().getIdPart(name);
}
@Override
public Collection<AgAttribute> getAttributes() {
return getDelegate().getAttributes();
}
@Override
public AgAttribute getAttribute(String name) {
return getDelegate().getAttribute(name);
}
@Override
public Collection<AgRelationship> getRelationships() {
return getDelegate().getRelationships();
}
@Override
public AgRelationship getRelationship(String name) {
return getDelegate().getRelationship(name);
}
@Override
public RootDataResolver<T> getDataResolver() {
return getDelegate().getDataResolver();
}
@Override
public ReadFilter<T> getReadFilter() {
return getDelegate().getReadFilter();
}
@Override
public CreateAuthorizer<T> getCreateAuthorizer() {
return getDelegate().getCreateAuthorizer();
}
@Override
public UpdateAuthorizer<T> getUpdateAuthorizer() {
return getDelegate().getUpdateAuthorizer();
}
@Override
public DeleteAuthorizer<T> getDeleteAuthorizer() {
return getDelegate().getDeleteAuthorizer();
}
@Override
public String toString() {
return "LazyAgEntity[" + type.getSimpleName() + "]";
}
}
|
ORTECScientificBenchmarks/ortec-scientific-benchmarks-loadbuilding | src/ortec/scientific/benchmarks/loadbuilding/instance/read/JSONtoThreeDinstance.py | <filename>src/ortec/scientific/benchmarks/loadbuilding/instance/read/JSONtoThreeDinstance.py
from .BaseToThreeDinstance import BaseToThreeDinstance
from ...common.utils import bool_cast
import json
class JSONtoThreeDinstance(BaseToThreeDinstance):
@staticmethod
def safeFindRoot(filename="", text=""):
if filename:
with open(filename) as fd:
return json.load(fd)
if text:
return json.loads(text)
@staticmethod
def safeFindOne(json, tag):
try:
return json[tag]
except:
return None
@staticmethod
def safeFindAll(json, tag):
if json is None:
return []
return json
@staticmethod
def safeGetAttr(json, tag, cast):
try:
if json[tag] is None:
return None
if cast == bool:
return bool_cast(json[tag])
return cast(json[tag])
except:
try:
return json[tag]
except:
return None
@staticmethod
def safeGetText(json, tag, cast):
return JSONtoThreeDinstance.safeGetAttr(json, tag, cast)
def __init__(self,filename="", text=""):
super(JSONtoThreeDinstance, self).__init__(filename, text)
if __name__=="__main__":
exit("Don't run this file") |
gamekonglee/zongshuo | app/src/main/java/bc/zongshuo/com/ui/view/PullUpToLoadMore.java | <gh_stars>0
package bc.zongshuo.com.ui.view;
import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.VelocityTracker;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.widget.Scroller;
/**
* Created by baoyunlong on 16/6/8.
*/
public class PullUpToLoadMore extends ViewGroup {
public static String TAG = PullUpToLoadMore.class.getName();
MyScrollView topScrollView, bottomScrollView;
VelocityTracker velocityTracker = VelocityTracker.obtain();
Scroller scroller = new Scroller(getContext());
public static int currPosition = 0;
int position1Y;
int lastY;
public int scaledTouchSlop;//最小滑动距离
int speed = 200;
boolean isIntercept;
public boolean bottomScrollVIewIsInTop = false;
public boolean topScrollViewIsBottom = false;
private ScrollListener mListener;
public void setmListener(ScrollListener mListener) {
this.mListener = mListener;
}
public PullUpToLoadMore(Context context) {
super(context);
init();
}
public PullUpToLoadMore(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public PullUpToLoadMore(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
private void init() {
post(new Runnable() {
@Override
public void run() {
topScrollView = (MyScrollView) getChildAt(0);
bottomScrollView = (MyScrollView) getChildAt(1);
topScrollView.setScrollListener(new MyScrollView.ScrollListener() {
@Override
public void onScrollToBottom() {
topScrollViewIsBottom = true;
}
@Override
public void onScrollToTop() {
}
@Override
public void onScroll(int scrollY) {
}
@Override
public void notBottom() {
topScrollViewIsBottom = false;
}
});
bottomScrollView.setScrollListener(new MyScrollView.ScrollListener() {
@Override
public void onScrollToBottom() {
}
@Override
public void onScrollToTop() {
}
@Override
public void onScroll(int scrollY) {
if (scrollY == 0) {
bottomScrollVIewIsInTop = true;
} else {
bottomScrollVIewIsInTop = false;
}
}
@Override
public void notBottom() {
}
});
position1Y = topScrollView.getBottom();
scaledTouchSlop = ViewConfiguration.get(getContext()).getScaledTouchSlop();
}
});
}
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
//防止子View禁止父view拦截事件
this.requestDisallowInterceptTouchEvent(false);
return super.dispatchTouchEvent(ev);
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
int y = (int) ev.getY();
switch (ev.getAction()) {
case MotionEvent.ACTION_DOWN:
lastY = y;
break;
case MotionEvent.ACTION_MOVE:
//判断是否已经滚动到了底部
if (topScrollViewIsBottom) {
int dy = lastY - y;
//判断是否是向上滑动和是否在第一屏
if (dy > 0 && currPosition == 0) {
if (dy >= scaledTouchSlop) {
isIntercept = true;//拦截事件
lastY=y;
}
}
}
if (bottomScrollVIewIsInTop) {
int dy = lastY - y;
//判断是否是向下滑动和是否在第二屏
if (dy < 0 && currPosition == 1) {
if (Math.abs(dy) >= scaledTouchSlop) {
isIntercept = true;
}
}
}
break;
}
return isIntercept;
}
@Override
public boolean onTouchEvent(MotionEvent event) {
int y = (int) event.getY();
velocityTracker.addMovement(event);
switch (event.getAction()) {
case MotionEvent.ACTION_MOVE:
int dy = lastY - y;
if (getScrollY() + dy < 0) {
dy = getScrollY() + dy + Math.abs(getScrollY() + dy);
}
if (getScrollY() + dy + getHeight() > bottomScrollView.getBottom()) {
dy = dy - (getScrollY() + dy - (bottomScrollView.getBottom() - getHeight()));
}
scrollBy(0, dy);
break;
case MotionEvent.ACTION_UP:
isIntercept = false;
velocityTracker.computeCurrentVelocity(1000);
float yVelocity = velocityTracker.getYVelocity();
if (currPosition == 0) {
if (yVelocity < 0 && yVelocity < -speed) {
smoothScroll(position1Y);
currPosition = 1;
mListener.onScrollToBottom(currPosition);
} else {
smoothScroll(0);
}
} else {
if (yVelocity > 0 && yVelocity > speed) {
smoothScroll(0);
currPosition = 0;
mListener.onScrollToBottom(currPosition);
} else {
smoothScroll(position1Y);
}
}
break;
}
lastY = y;
return true;
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
measureChildren(widthMeasureSpec, heightMeasureSpec);
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
int childCount = getChildCount();
int childTop = 0;
for (int i = 0; i < childCount; i++) {
View child = getChildAt(i);
child.layout(l, childTop, r, childTop + child.getMeasuredHeight());
childTop += child.getMeasuredHeight();
}
}
//通过Scroller实现弹性滑动
private void smoothScroll(int tartY) {
int dy = tartY - getScrollY();
scroller.startScroll(getScrollX(), getScrollY(), 0, dy);
invalidate();
}
//滚动到顶部
public void scrollToTop(){
smoothScroll(0);
currPosition=0;
mListener.onScrollToBottom(currPosition);
topScrollView.smoothScrollTo(0,0);
}
@Override
public void computeScroll() {
if (scroller.computeScrollOffset()) {
scrollTo(scroller.getCurrX(), scroller.getCurrY());
postInvalidate();
}
}
public interface ScrollListener{
void onScrollToBottom(int currPosition);
}
}
|
almartin82/bayeslite | tests/test_macro.py | <reponame>almartin82/bayeslite
# -*- coding: utf-8 -*-
# Copyright (c) 2010-2016, MIT Probabilistic Computing 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.
import bayeslite.ast as ast
import bayeslite.macro as macro
def test_expand_probability_estimate():
expression = ast.ExpOp(ast.OP_LT, [
ast.ExpBQLMutInf(
['c0'],
['c1', 'c2'],
[('c3', ast.ExpLit(ast.LitInt(3)))],
None),
ast.ExpLit(ast.LitFloat(0.1)),
])
probest = ast.ExpBQLProbEst(expression)
assert macro.expand_probability_estimate(probest, 'p', 'g') == \
ast.ExpSub(
ast.Select(ast.SELQUANT_ALL,
[ast.SelColExp(
ast.ExpApp(False, 'AVG', [ast.ExpCol(None, 'x')]),
None)],
[ast.SelTab(
ast.SimulateModelsExp([ast.SelColExp(expression, 'x')],
'p', 'g'),
None)],
None, None, None, None))
def test_simulate_models_trivial():
e = ast.ExpBQLMutInf(['c0'], ['c1', 'c2'],
[('c3', ast.ExpLit(ast.LitInt(3)))],
None)
simmodels = ast.SimulateModelsExp([ast.SelColExp(e, 'x')], 'p', 'g')
assert macro.expand_simulate_models(simmodels) == \
ast.SimulateModels([ast.SelColExp(e, 'x')], 'p', 'g')
def test_simulate_models_nontrivial():
# XXX test descent into ExpLit
# XXX test descent into ExpNumpar
# XXX test descent into ExpNampar
# XXX test descent into ExpCol
# XXX test descent into ExpSub
# XXX test descent into ExpCollate
# XXX test descent into ExpIn
# XXX test descent into ExpCast
# XXX test descent into ExpExists
# XXX test descent into ExpApp
# XXX test descent into ExpAppStar
# XXX test descent into ExpCase
mutinf0 = ast.ExpBQLMutInf(['c0'], ['c1', 'c2'],
[('c3', ast.ExpLit(ast.LitInt(3)))],
None)
mutinf1 = ast.ExpBQLMutInf(['c4', 'c5'], ['c6'],
[('c7', ast.ExpLit(ast.LitString('ergodic')))],
100)
probdensity = ast.ExpBQLProbDensity(
[('x', ast.ExpLit(ast.LitFloat(1.2)))],
# No conditions for now -- that changes the weighting of the average.
[])
expression0 = ast.ExpOp(ast.OP_LT, [
mutinf0,
ast.ExpOp(ast.OP_MUL, [ast.ExpLit(ast.LitFloat(0.1)), mutinf1]),
])
expression1 = probdensity
simmodels = ast.SimulateModelsExp(
[
ast.SelColExp(expression0, 'quagga'),
ast.SelColExp(expression1, 'eland'),
], 'p', 'g')
assert macro.expand_simulate_models(simmodels) == \
ast.Select(ast.SELQUANT_ALL,
[
ast.SelColExp(
ast.ExpOp(ast.OP_LT, [
ast.ExpCol(None, 'v0'),
ast.ExpOp(ast.OP_MUL, [
ast.ExpLit(ast.LitFloat(0.1)),
ast.ExpCol(None, 'v1'),
])
]),
'quagga'),
ast.SelColExp(ast.ExpCol(None, 'v2'), 'eland'),
],
[ast.SelTab(
ast.SimulateModels(
[
ast.SelColExp(mutinf0, 'v0'),
ast.SelColExp(mutinf1, 'v1'),
ast.SelColExp(probdensity, 'v2'),
], 'p', 'g'),
None)],
None, None, None, None)
|
HostaPlantain/Floricraft2 | src/main/java/com/hosta/Floricraft2/mod/Baubles/ModuleBaubles.java | <gh_stars>1-10
package com.hosta.Floricraft2.mod.Baubles;
import com.hosta.Floricraft2.mod.Baubles.item.CharmSachet;
import com.hosta.Floricraft2.module.IModule;
import com.hosta.Floricraft2.module.IModuleRecipe;
import com.hosta.Floricraft2.module.ModuleCrops;
import com.hosta.Floricraft2.module.ModuleFragrances;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraftforge.oredict.OreDictionary;
public class ModuleBaubles implements IModule, IModuleRecipe {
// Amulet Sachet
public static final Item CHARM_SACHET_FLOWER = new CharmSachet("charm_sachet_flower");
@Override
public void registerItems()
{
register(CHARM_SACHET_FLOWER);
}
@Override
public void registerRecipes()
{
register
(
effectRecipe(null, CHARM_SACHET_FLOWER, " t ", "t t", " a ", 'a', new ItemStack(ModuleFragrances.SACHET_FLOWER, 1, OreDictionary.WILDCARD_VALUE), 't', ModuleCrops.HEMP_TWINE)
);
}
}
|
timoles/codeql | javascript/ql/test/library-tests/RegExp/CharacterRange/tst.js | <reponame>timoles/codeql<filename>javascript/ql/test/library-tests/RegExp/CharacterRange/tst.js
var reg1 = /[w-z]/; // normal range w-z, matches: wxyz
var reg2 = /[\w]/; // escape class, same as \w.
var reg3 = /[\w-z]/; // escape class \w and "-" and "z", same as [a-zA-Z0-9\-z]
var reg4 = /[\w-\w]/; // escape class \w (twice) and the char "-".
var reg5 = /[z-\w]/; // same as reg3
var reg6 = /[\n-\r]/; // from \n (code 10) to \r (code 13).
var reg7 = /[\n-z]/; // from \n (code 10) to z (code 122).
|
dmitryvinn/fatal | fatal/type/impl/cat.h | /*
* Copyright (c) 2016, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
#ifndef FATAL_INCLUDE_fatal_type_impl_cat_h
#define FATAL_INCLUDE_fatal_type_impl_cat_h
namespace fatal {
namespace impl_cat {
template <typename...> struct c;
template <typename T>
struct c<T> {
using type = T;
};
template <
typename T0, typename T1, typename T2, typename T3, typename... Args
>
struct c<T0, T1, T2, T3, Args...> {
using type = typename c<typename c<T0, T1, T2, T3>::type, Args...>::type;
};
template <
typename T0, typename T1, typename T2, typename T3, typename T4,
typename T5, typename T6, typename T7, typename... Args
>
struct c<T0, T1, T2, T3, T4, T5, T6, T7, Args...> {
using type = typename c<
typename c<T0, T1, T2, T3, T4, T5, T6, T7>::type,
Args...
>::type;
};
template <
typename T0, typename T1, typename T2, typename T3, typename T4,
typename T5, typename T6, typename T7, typename T8, typename T9,
typename T10, typename T11, typename T12, typename T13, typename T14,
typename T15, typename... Args
>
struct c<
T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, Args...
> {
using type = typename c<
typename c<
T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15
>::type,
Args...
>::type;
};
template <
template <typename...> class V0, typename... T0,
template <typename...> class V1, typename... T1
>
struct c<V0<T0...>, V1<T1...>> {
using type = V0<T0..., T1...>;
};
template <
template <typename...> class V0, typename... T0,
template <typename...> class V1, typename... T1,
template <typename...> class V2, typename... T2
>
struct c<V0<T0...>, V1<T1...>, V2<T2...>> {
using type = V0<T0..., T1..., T2...>;
};
template <
template <typename...> class V0, typename... T0,
template <typename...> class V1, typename... T1,
template <typename...> class V2, typename... T2,
template <typename...> class V3, typename... T3
>
struct c<V0<T0...>, V1<T1...>, V2<T2...>, V3<T3...>> {
using type = V0<T0..., T1..., T2..., T3...>;
};
template <
template <typename...> class V0, typename... T0,
template <typename...> class V1, typename... T1,
template <typename...> class V2, typename... T2,
template <typename...> class V3, typename... T3,
template <typename...> class V4, typename... T4,
template <typename...> class V5, typename... T5,
template <typename...> class V6, typename... T6,
template <typename...> class V7, typename... T7
>
struct c<
V0<T0...>, V1<T1...>, V2<T2...>, V3<T3...>, V4<T4...>, V5<T5...>,
V6<T6...>, V7<T7...>
> {
using type = V0<T0..., T1..., T2..., T3..., T4..., T5..., T6..., T7...>;
};
template <
template <typename...> class V0, typename... T0,
template <typename...> class V1, typename... T1,
template <typename...> class V2, typename... T2,
template <typename...> class V3, typename... T3,
template <typename...> class V4, typename... T4,
template <typename...> class V5, typename... T5,
template <typename...> class V6, typename... T6,
template <typename...> class V7, typename... T7,
template <typename...> class V8, typename... T8,
template <typename...> class V9, typename... T9,
template <typename...> class V10, typename... T10,
template <typename...> class V11, typename... T11,
template <typename...> class V12, typename... T12,
template <typename...> class V13, typename... T13,
template <typename...> class V14, typename... T14,
template <typename...> class V15, typename... T15
>
struct c<
V0<T0...>, V1<T1...>, V2<T2...>, V3<T3...>, V4<T4...>, V5<T5...>,
V6<T6...>, V7<T7...>, V8<T8...>, V9<T9...>, V10<T10...>, V11<T11...>,
V12<T12...>, V13<T13...>, V14<T14...>, V15<T15...>
> {
using type = V0<
T0..., T1..., T2..., T3..., T4..., T5...,
T6..., T7..., T8..., T9..., T10..., T11...,
T12..., T13..., T14..., T15...
>;
};
template <
typename T,
template <typename V, V...> class V0, T... T0,
template <typename V, V...> class V1, T... T1
>
struct c<V0<T, T0...>, V1<T, T1...>> {
using type = V0<T, T0..., T1...>;
};
template <
typename T,
template <typename V, V...> class V0, T... T0,
template <typename V, V...> class V1, T... T1,
template <typename V, V...> class V2, T... T2
>
struct c<V0<T, T0...>, V1<T, T1...>, V2<T, T2...>> {
using type = V0<T, T0..., T1..., T2...>;
};
template <
typename T,
template <typename V, V...> class V0, T... T0,
template <typename V, V...> class V1, T... T1,
template <typename V, V...> class V2, T... T2,
template <typename V, V...> class V3, T... T3
>
struct c<V0<T, T0...>, V1<T, T1...>, V2<T, T2...>, V3<T, T3...>> {
using type = V0<T, T0..., T1..., T2..., T3...>;
};
template <
typename T,
template <typename V, V...> class V0, T... T0,
template <typename V, V...> class V1, T... T1,
template <typename V, V...> class V2, T... T2,
template <typename V, V...> class V3, T... T3,
template <typename V, V...> class V4, T... T4,
template <typename V, V...> class V5, T... T5,
template <typename V, V...> class V6, T... T6,
template <typename V, V...> class V7, T... T7
>
struct c<
V0<T, T0...>, V1<T, T1...>, V2<T, T2...>, V3<T, T3...>, V4<T, T4...>,
V5<T, T5...>, V6<T, T6...>, V7<T, T7...>
> {
using type = V0<T, T0..., T1..., T2..., T3..., T4..., T5..., T6..., T7...>;
};
template <
typename T,
template <typename V, V...> class V0, T... T0,
template <typename V, V...> class V1, T... T1,
template <typename V, V...> class V2, T... T2,
template <typename V, V...> class V3, T... T3,
template <typename V, V...> class V4, T... T4,
template <typename V, V...> class V5, T... T5,
template <typename V, V...> class V6, T... T6,
template <typename V, V...> class V7, T... T7,
template <typename V, V...> class V8, T... T8,
template <typename V, V...> class V9, T... T9,
template <typename V, V...> class V10, T... T10,
template <typename V, V...> class V11, T... T11,
template <typename V, V...> class V12, T... T12,
template <typename V, V...> class V13, T... T13,
template <typename V, V...> class V14, T... T14,
template <typename V, V...> class V15, T... T15
>
struct c<
V0<T, T0...>, V1<T, T1...>, V2<T, T2...>, V3<T, T3...>, V4<T, T4...>,
V5<T, T5...>, V6<T, T6...>, V7<T, T7...>, V8<T, T8...>, V9<T, T9...>,
V10<T, T10...>, V11<T, T11...>, V12<T, T12...>, V13<T, T13...>,
V14<T, T14...>, V15<T, T15...>
> {
using type = V0<
T,
T0..., T1..., T2..., T3..., T4..., T5...,
T6..., T7..., T8..., T9..., T10..., T11...,
T12..., T13..., T14..., T15...
>;
};
template <typename...> struct v;
template <
template <typename...> class Variadic,
typename... LHS,
typename... RHS
>
struct v<Variadic<LHS...>, Variadic<RHS...>> {
template <typename... Args>
using apply = Variadic<LHS..., Args..., RHS...>;
};
template <
template <typename V, V...> class Variadic,
typename T,
T... LHS,
T... RHS
>
struct v<Variadic<T, LHS...>, Variadic<T, RHS...>> {
template <T... Values>
using apply = Variadic<T, LHS..., Values..., RHS...>;
};
template <typename...> struct l;
template <
template <typename...> class Variadic,
typename... LHS,
typename... RHS,
typename... Args
>
struct l<Variadic<LHS...>, Variadic<RHS...>, Args...> {
using type = Variadic<LHS..., Args..., RHS...>;
};
} // namespace impl_cat {
} // namespace fatal {
#endif // FATAL_INCLUDE_fatal_type_impl_cat_h
|
Ronsor/jangle-server | user.go | package main
import (
"fmt"
"strings"
"math/rand"
"crypto/md5"
"path"
"time"
jwt "jangled/sjwt"
"jangled/util"
"github.com/bwmarrin/snowflake"
"github.com/globalsign/mgo/bson"
"github.com/valyala/fasthttp"
)
// User flags
const (
USER_FLAG_NONE = 0
USER_FLAG_STAFF = 1 << 0
USER_FLAG_PARTNER = 1 << 1
USER_FLAG_EARLYADOPTER = 1 << 24
// The rest are unused
)
// User premium subscription type
const (
USER_PREMIUM_NONE = 0
// USER_PREMIUM_NITRO_CLASSIC = 1
USER_PREMIUM_BOLT = 2
)
// UserSettings is a Discord-compatible structure containing a user's settings
// This struct is safe to be returned by an API call
type UserSettings struct {
Locale string `json:"locale"`
AfkTimeout int `json:"afk_timeout"`
Theme string `json:"theme"`
Status string `json:"status"`
// TODO: the rest
}
// User is a Discord-compatible structure containing information on a user
// This struct is not safe to be returned by an API call
type User struct {
ID snowflake.ID `bson:"_id"`
Username string `bson:"username"`
Discriminator string `bson:"discriminator"`
Email string `bson:"email,omitempty"`
Bot bool `bson:"bot"`
Avatar string `bson:"avatar"`
MfaEnabled bool `bson:"mfa_enabled"`
Verified bool `bson:"verified"`
Flags int `bson:"flags"`
PremiumType int `bson:"premium_type"`
PremiumSince int `bson:"premium_since"`
Phone string `bson:"phone"`
LastSession int `bson:"last_session"`
PasswordHash string `bson:"password_hash"`
Settings *UserSettings `bson:"user_settings"`
Presence *gwPktDataUpdateStatus `bson:"presence"`
LastMessageIDs map[snowflake.ID]snowflake.ID `bson:"read_last_message_ids"`
JwtSecret string `bson:"jwt_secret"`
}
// CreateUser creates a user
func CreateUser(username, email, password string) (*User, error) {
c := DB.Core.C("users")
usr := &User{
ID: flake.Generate(),
Username: username,
Email: email,
PasswordHash: util.CryptPass(password),
Settings: &UserSettings{
Locale: "en-US",
},
}
dint := 1 + rand.Intn(9998)
var err error
for tries := 0; tries < 100; tries++ {
usr.Discriminator = fmt.Sprintf("%04d", dint)
err = c.Insert(usr)
if err == nil {
break
}
}
if err != nil {
return nil, err
}
return usr, nil
}
// GetUserByID returns a user by their unique ID
func GetUserByID(ID snowflake.ID) (u *User, e error) {
var u2 User
c := DB.Core.C("users")
e = c.Find(bson.M{"_id": ID}).One(&u2)
u2.ID = ID
u = &u2
return
}
func GetUserByEmail(email string) (*User, error) {
var u2 User
c := DB.Core.C("users")
err := c.Find(bson.M{"email": email}).One(&u2)
if err != nil {
return nil, err
}
return &u2, nil
}
// GetUserByToken returns a user using an authentication token
func GetUserByToken(token string) (*User, error) {
if *flgStaging {
// TODO: snowflake.ParseString
var i snowflake.ID
n, err := fmt.Sscanf(token, "%d", &i)
if n != 1 {
return nil, fmt.Errorf("Bad ID")
}
if err != nil {
return nil, err
}
return GetUserByID(i)
} else {
claims, err := jwt.Parse(token)
if err != nil {
return nil, err
}
if err := claims.Validate(); err != nil {
return nil, err
}
subj, err := claims.GetSubject()
if err != nil {
return nil, err
}
uid, err := snowflake.ParseString(subj)
if err != nil {
return nil, err
}
user, err := GetUserByID(uid)
if err != nil {
return nil, err
}
if !jwt.Verify(token, user.GetTokenSecret()) {
return nil, fmt.Errorf("Invalid token")
}
return user, nil
}
return nil, fmt.Errorf("Not implemented")
}
// GetUserByHttpRequest returns a user using a fasthttp.RequestCtx.
// Specifically, it attempts to authorize the request using a token.
func GetUserByHttpRequest(c *fasthttp.RequestCtx, ctxvar string) (*User, error) {
b := c.Request.Header.Peek("Authorization")
if b == nil {
return nil, fmt.Errorf("No authorization token supplied")
}
a := string(b)
a = strings.Replace(a, "Bot ", "", -1)
a = strings.Replace(a, "Bearer ", "", -1)
user, err := GetUserByToken(a)
if err != nil {
return nil, err
}
if ctxvar != "" {
uid2 := c.UserValue(ctxvar).(string) // You're going to pass a string, or I'll panic()
if uid2 == "" || uid2 == "@me" {
return user, nil
}
snow, err := snowflake.ParseString(uid2)
if err != nil {
return nil, err
}
user, err = GetUserByID(snow)
if err != nil {
return nil, err
}
}
return user, nil
}
func (u *User) GetTokenSecret() []byte {
return []byte(u.PasswordHash + u.JwtSecret)
}
func (u *User) IssueToken(duration time.Duration) string {
c := jwt.New()
c.SetSubject(u.ID.String())
c.Set("tag", u.Username+"#"+u.Discriminator)
c.SetIssuedAt(time.Now())
c.SetExpiresAt(time.Now().Add(duration))
c.SetTokenID()
return c.Generate(u.GetTokenSecret())
}
// ToAPI returns a version of the User struct that can be returned by API calls
func (u *User) ToAPI(safe bool) *APITypeUser {
u2 := &APITypeUser{
ID: u.ID,
Username: u.Username,
Discriminator: u.Discriminator,
AvatarHash: u.Avatar,
Bot: u.Bot,
MfaEnabled: true,
Flags: u.Flags,
PremiumType: u.PremiumType,
}
if u.Settings != nil {
u2.Locale = u.Settings.Locale
}
if u.PremiumType != USER_PREMIUM_NONE {
u2.Premium = true
}
if !safe {
if u.Phone != "" {
u2.Phone = &u.Phone
u2.Mobile = true
}
u2.Email = u.Email
u2.Verified = &u.Verified
}
return u2
}
func (u *User) StartTyping(c *Channel) error {
return StartTypingForUser(u.ID, &gwEvtDataTypingStart{
ChannelID: c.ID,
GuildID: c.GuildID,
UserID: u.ID,
Timestamp: time.Now().Unix(),
})
}
func (u *User) MarkRead(cid, mid snowflake.ID) {
if u.LastMessageIDs != nil {
u.LastMessageIDs = map[snowflake.ID]snowflake.ID{}
}
u.LastMessageIDs[cid] = mid
}
// DMChannels returns the DM channels a user is in
func (u *User) Channels() ([]*Channel, error) {
ch := []*Channel{}
err := DB.Core.C("channels").Find(bson.M{"recipient_ids": u.ID}).All(&ch)
if err != nil {
return nil, err
}
return ch, nil
}
func (u *User) Save() error {
c := DB.Core.C("users")
_, err := c.UpsertId(u.ID, u)
return err
}
func (u *User) SetTag(username, discriminator string) error {
c := DB.Core.C("users")
if discriminator == "" {
dint := 1 + rand.Intn(9998)
var err error
for tries := 0; tries < 100; tries++ {
dscm := fmt.Sprintf("%04d", dint)
err = c.UpdateId(u.ID, bson.M{"$set":bson.M{"username":username,"discriminator":dscm}})
if err == nil {
u.Discriminator = dscm
u.Username = username
return nil
}
}
return err
} else {
err := c.UpdateId(u.ID, bson.M{"$set":bson.M{"username":username,"discriminator":discriminator}})
if err == nil {
u.Username = username
u.Discriminator = discriminator
}
return err
}
}
func (u *User) SetAvatar(dataURL string) error {
c := DB.Core.C("users")
imgFp := fmt.Sprintf("%x", md5.Sum([]byte(dataURL)))
fullpath, err := ImageDataURLUpload(gFileStore, "/avatars/" + u.ID.String() + "/" + imgFp + ".png", dataURL, ImageUploadOptions{MaxWidth: 2048, MaxHeight: 2048, ForcePNG: true})
if err != nil { return err }
bp := path.Base(fullpath)
u.Avatar = strings.TrimRight(bp, path.Ext(bp))
c.UpdateId(u.ID, bson.M{"$set":bson.M{"avatar": bp}})
return nil
}
func (u *User) Guilds() ([]*Guild, error) {
return GetGuildsByUserID(u.ID)
}
/*
The following code is for testing.
It is not used in production.
*/
// Initialize dummy users in database
func InitUserStaging() {
c := DB.Core.C("users")
c.Insert(&User{
ID: 42,
Username: "test1",
Discriminator: "1234",
Email: "<EMAIL>",
PasswordHash: util.CryptPass("<PASSWORD>"),
Flags: USER_FLAG_STAFF | USER_FLAG_EARLYADOPTER,
Settings: &UserSettings{
Locale: "en-US",
},
})
c.Insert(&User{
ID: 43,
Username: "hello",
Discriminator: "4242",
Email: "<EMAIL>",
PasswordHash: util.CryptPass("<PASSWORD>"),
Flags: USER_FLAG_EARLYADOPTER,
Settings: &UserSettings{
Locale: "en-US",
},
})
}
|
Bloodknight/NeuTorsion | code/wxWidgets/include/wx/msw/ole/dropsrc.h | ///////////////////////////////////////////////////////////////////////////////
// Name: ole/dropsrc.h
// Purpose: declaration of the wxDropSource class
// Author: <NAME>
// Modified by:
// Created: 06.03.98
// RCS-ID: $Id: dropsrc.h,v 1.21 2004/08/16 12:45:40 ABX Exp $
// Copyright: (c) 1998 <NAME> <<EMAIL>>
// Licence: wxWindows licence
///////////////////////////////////////////////////////////////////////////////
#ifndef _WX_OLEDROPSRC_H
#define _WX_OLEDROPSRC_H
#if defined(__GNUG__) && !defined(NO_GCC_PRAGMA)
#pragma interface
#endif
#if wxUSE_DRAG_AND_DROP
// ----------------------------------------------------------------------------
// forward declarations
// ----------------------------------------------------------------------------
class wxIDropSource;
class WXDLLEXPORT wxDataObject;
class WXDLLEXPORT wxWindow;
// ----------------------------------------------------------------------------
// macros
// ----------------------------------------------------------------------------
// this macro may be used instead for wxDropSource ctor arguments: it will use
// the cursor 'name' from the resources under MSW, but will expand to
// something else under GTK. If you don't use it, you will have to use #ifdef
// in the application code.
#define wxDROP_ICON(name) wxCursor(_T(#name))
// ----------------------------------------------------------------------------
// wxDropSource is used to start the drag-&-drop operation on associated
// wxDataObject object. It's responsible for giving UI feedback while dragging.
// ----------------------------------------------------------------------------
class WXDLLEXPORT wxDropSource : public wxDropSourceBase
{
public:
// ctors: if you use default ctor you must call SetData() later!
//
// NB: the "wxWindow *win" parameter is unused and is here only for wxGTK
// compatibility, as well as both icon parameters
wxDropSource(wxWindow *win = NULL,
const wxCursor &cursorCopy = wxNullCursor,
const wxCursor &cursorMove = wxNullCursor,
const wxCursor &cursorStop = wxNullCursor);
wxDropSource(wxDataObject& data,
wxWindow *win = NULL,
const wxCursor &cursorCopy = wxNullCursor,
const wxCursor &cursorMove = wxNullCursor,
const wxCursor &cursorStop = wxNullCursor);
virtual ~wxDropSource();
// do it (call this in response to a mouse button press, for example)
// params: if bAllowMove is false, data can be only copied
virtual wxDragResult DoDragDrop(int flags = wxDrag_CopyOnly);
// overridable: you may give some custom UI feedback during d&d operation
// in this function (it's called on each mouse move, so it shouldn't be
// too slow). Just return false if you want default feedback.
virtual bool GiveFeedback(wxDragResult effect);
protected:
void Init();
private:
wxIDropSource *m_pIDropSource; // the pointer to COM interface
DECLARE_NO_COPY_CLASS(wxDropSource)
};
#endif //wxUSE_DRAG_AND_DROP
#endif //_WX_OLEDROPSRC_H
|
peerigon/nodeclass | lib/bundlers/index.js | "use strict"; // run code in ES5 strict mode
exports.webpack = require("./webpack.js"); |
hugolribeiro/hackerrank_exercises | problem_solving/warmup/solve_me_first/aut_tests.py | <filename>problem_solving/warmup/solve_me_first/aut_tests.py
from main import solveMeFirst
# Test 1
a1 = 2
b1 = 3
result1 = solveMeFirst(a1, b1)
answer1 = 5
if result1 == answer1:
print(f'Test number 1 \nExpected Output: {answer1}\nThe output: {result1} \n\033[0;32;1mTest OK\033[m')
else:
print(f'Test number 1 \nExpected Output: {answer1}\nThe output: {result1} \n\033[0;31;1mWRONG\033[m')
print('#' * 20)
# Test 2
a2 = 20
b2 = 31
result2 = solveMeFirst(a2, b2)
answer2 = 51
if result2 == answer2:
print(f'Test number 2 \nExpected Output: {answer2}\nThe output: {result2} \n\033[0;32;1mTest OK\033[m')
else:
print(f'Test number 2 \nExpected Output: {answer2}\nThe output: {result2} \n\033[0;31;1mWRONG\033[m')
print('#' * 20)
# Test 3
a3 = 17
b3 = 3
result3 = solveMeFirst(a3, b3)
answer3 = 20
if result3 == answer3:
print(f'Test number 1 \nExpected Output: {answer3}\nThe output: {result3} \n\033[0;32;1mTest OK\033[m')
else:
print(f'Test number 1 \nExpected Output: {answer3}\nThe output: {result3} \n\033[0;31;1mWRONG\033[m')
print('#' * 20)
# Test 4
a4 = 15
b4 = 16
result4 = solveMeFirst(a4, b4)
answer4 = 31
if result4 == answer4:
print(f'Test number 1 \nExpected Output: {answer4}\nThe output: {result4} \n\033[0;32;1mTest OK\033[m')
else:
print(f'Test number 1 \nExpected Output: {answer4}\nThe output: {result4} \n\033[0;31;1mWRONG\033[m')
|
coreywagehoft/kuma | pkg/plugins/resources/k8s/native/api/v1alpha1/mesh_insight_types.go | package v1alpha1
import (
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
// MeshInsightSpec defines the observed state of Mesh
type MeshInsightSpec = map[string]interface{}
// MeshInsight is the Schema for the Mesg Insights API
type MeshInsight struct {
metav1.TypeMeta `json:",inline"`
metav1.ObjectMeta `json:"metadata,omitempty"`
Mesh string `json:"mesh,omitempty"`
Spec MeshInsightSpec `json:"status,omitempty"`
}
// MeshInsightList contains a list of MeshInsights
type MeshInsightList struct {
metav1.TypeMeta `json:",inline"`
metav1.ListMeta `json:"metadata,omitempty"`
Items []MeshInsight `json:"items"`
}
func init() {
SchemeBuilder.Register(&MeshInsight{}, &MeshInsightList{})
}
|
egovernment/eregistrations | model/business-process-new/costs.js | // BusinessProcess costs resolution
'use strict';
var memoize = require('memoizee/plain')
, definePercentage = require('dbjs-ext/number/percentage')
, defineCurrency = require('dbjs-ext/number/currency')
, defineUInteger = require('dbjs-ext/number/integer/u-integer')
, defineMultipleProcess = require('../lib/multiple-process')
, defineCost = require('../cost')
, defineBusinessProcess = require('./registrations')
, definePaymentReceiptUploads;
module.exports = memoize(function (db/* options */) {
var options = Object(arguments[1])
, BusinessProcess = defineBusinessProcess(db, options)
, Percentage = definePercentage(db)
, UInteger = defineUInteger(db)
, MultipleProcess = defineMultipleProcess(db)
, Currency = defineCurrency(db)
, Cost = defineCost(db);
BusinessProcess.prototype.defineProperties({
costs: { type: MultipleProcess, nested: true }
});
BusinessProcess.prototype.costs.map._descriptorPrototype_.type = Cost;
BusinessProcess.prototype.costs.defineProperties({
// Applicable costs resolved out of requested registrations
applicable: { type: Cost, value: function (_observe) {
var result = [];
_observe(this.master.registrations.requested).forEach(function (registration) {
_observe(registration.costs).forEach(function (cost) { result.push(cost); });
});
return result;
} },
// Payable subset of applicable costs
// More directly: all applicable costs that are non 0
payable: { type: Cost, multiple: true, value: function (_observe) {
var result = [];
this.applicable.forEach(function (cost) {
var isPayable = Boolean(cost._get ? _observe(cost._amount) : cost.amount);
if (isPayable) result.push(cost);
});
return result;
} },
// Paid costs
paid: { type: Cost, multiple: true, value: function (_observe) {
var result = [];
this.payable.forEach(function (cost) {
if (_observe(cost._isPaid)) result.push(cost);
});
return result;
} },
// Electronic costs
electronic: { type: Cost, multiple: true, value: function (_observe) {
var result = [];
this.payable.forEach(function (cost) {
if (_observe(cost._isElectronic)) result.push(cost);
});
return result;
} },
// Global isOnlinePaymentInitialized indication
// Should be used when we use one online payment for all costs (and that's default)
// Otherwise there's a isOnlinePaymentInitialized on each cost to which we can refer
isOnlinePaymentInitialized: { type: db.Boolean, value: function () {
return this.isOnlinePaymentInProgress || this.isPaidOnline;
} },
// Global isPaidOnline indication
// Should be used when we use one online payment for all costs (and that's default)
// Otherwise there's a isPaidOnline on each cost to which we can refer
isPaidOnline: { type: db.Boolean, value: false },
// Global isOnlinePaymentInProgress indication
// Should be used when we use one online payment for all costs (and that's default)
// Otherwise there's a isOnlinePaymentInProgress on each cost to which we can refer
isOnlinePaymentInProgress: { type: db.Boolean, value: false },
// Payment progress
paymentProgress: { type: Percentage, value: function (_observe) {
var valid = 0, total = 0, paymentReceiptUploads = this.master.paymentReceiptUploads;
// Eventual online payments
if (this.electronic.size) {
++total;
if (this.electronic.every(function (cost) { return _observe(cost._isPaid); })) {
++valid;
} else if (this.electronic.some(function (cost) {
return _observe(cost._isOnlinePaymentInProgress);
})) {
valid += 0.5;
}
}
total += _observe(paymentReceiptUploads._weight);
valid += (_observe(paymentReceiptUploads._progress) * paymentReceiptUploads.weight);
if (!total) return 1;
return valid / total;
} },
// Payment weight
// Indicates number of step user needs to take to complete payment step in Part A
// e.g. one step per each payment receipt, and one step for one online payment
// If it's zero, that means we should not show payment step at all
paymentWeight: { type: UInteger, value: function (_observe) {
var weight = 0;
// We assume that there will be at most one online payment
// that will cover all electronic costs
if (this.electronic.size) ++weight;
weight += _observe(this.master.paymentReceiptUploads.applicable._size);
return weight;
} },
// Total for all payable costs
totalAmount: { type: Currency, value: function (_observe) {
var total = 0;
this.payable.forEach(function (cost) {
var amount = cost._get ? _observe(cost._amount) : cost.amount;
total += amount;
});
return total;
} }
});
if (!BusinessProcess.prototype.paymentReceiptUploads) {
definePaymentReceiptUploads(db, options);
}
return BusinessProcess;
}, { normalizer: require('memoizee/normalizers/get-1')() });
definePaymentReceiptUploads = require('./payment-receipt-uploads');
|
ssteo/webrecorder | frontend/src/components/controls/SidebarListViewerUI/renderers.js | <gh_stars>1000+
import React from 'react';
import { untitledEntry } from 'config';
import { buildDate } from 'helpers/utils';
import { Collection } from 'components/icons';
export function PageIndex({ rowIndex }) {
return <div className="row-index">{rowIndex + 1}</div>;
}
export function BookmarkRenderer({ cellData, rowData }) {
return (
<div className="bookmark-title" title={buildDate(rowData.get('timestamp'))}>
<h2>{ cellData || untitledEntry }</h2>
<span>{ rowData.get('url') }</span>
</div>
);
}
export function headerRenderer({ dataKey, label, sortBy, sortDirection, columnData: { count, activeBookmark } }) {
return (
<div
className="ReactVirtualized__Table__headerTruncatedText"
key="label"
title={label}>
<Collection />
<span dangerouslySetInnerHTML={{ __html: ` ${label} (${activeBookmark + 1} <em>of</em> ${count})` }} />
</div>
);
}
|
mgpavlov/SoftUni | Java/Java Fundamentals/02.Java OOP Basics - Jun 2018/01.02.Exercise Defining Classes/src/p08PokemonTrainer2/Main.java | <gh_stars>1-10
package p08PokemonTrainer2;
import p08PokemonTrainer2.Trainer;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.LinkedHashMap;
import java.util.Map;
public class Main {
private static final String END_OF_LINES = "Tournament";
private static final String END_OF_COMMANDS = "End";
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
Map<String, Trainer> record = new LinkedHashMap<>();
String input = reader.readLine();
while (!END_OF_LINES.equals(input)) {
String[] tokens = input.split("\\s+");
String trainerName = tokens[0];
String pokemonName = tokens[1];
String pokemonElement = tokens[2];
Integer pokemonHealth = Integer.parseInt(tokens[3]);
Pokemon cauthPokemon = new Pokemon(pokemonName, pokemonElement, pokemonHealth);
record.putIfAbsent(trainerName, new Trainer(trainerName, 0));
record.get(trainerName).addPokemon(cauthPokemon);
input = reader.readLine();
}
input = reader.readLine();
while (!END_OF_COMMANDS.equals(input)) {
for (Map.Entry<String, Trainer> kvp : record.entrySet()) {
kvp.getValue().analize(input);
}
input = reader.readLine();
}
StringBuilder sb = new StringBuilder();
record.entrySet().stream()
.sorted((t1, t2) -> Integer.compare(t2.getValue().getBadges(), t1.getValue().getBadges()))
.forEach(t -> sb.append(t.getValue()));
System.out.println(sb);
}
} |
screwjack/nemesis | wxWidgets-3.1.0/tests/testprec.h | #ifndef WX_TESTPREC_INCLUDED
#define WX_TESTPREC_INCLUDED 1
#include "wx/wxprec.h"
#include "wx/stopwatch.h"
#include "wx/evtloop.h"
#include "wx/cppunit.h"
// Custom test macro that is only defined when wxUIActionSimulator is available
// this allows the tests that do not rely on it to run on platforms that don't
// support it.
//
// FIXME: And while OS X does support it, more or less, too many tests
// currently fail under it so disable all interactive tests there. They
// should, of course, be reenabled a.s.a.p.
#if wxUSE_UIACTIONSIMULATOR && !defined(__WXOSX__)
#define WXUISIM_TEST(test) CPPUNIT_TEST(test)
#else
#define WXUISIM_TEST(test) (void)0
#endif
// define wxHAVE_U_ESCAPE if the compiler supports \uxxxx character constants
#if defined(__VISUALC__) || \
(defined(__GNUC__) && (__GNUC__ >= 3))
#define wxHAVE_U_ESCAPE
// and disable warning that using them results in with MSVC 8+
#if wxCHECK_VISUALC_VERSION(8)
// universal-character-name encountered in source
#pragma warning(disable:4428)
#endif
#endif
// Define wxUSING_VC_CRT_IO when using MSVC CRT STDIO library as its standard
// functions give different results from glibc ones in several cases (of
// course, any code relying on this is not portable and probably won't work,
// i.e. will result in tests failures, with other platforms/compilers which
// should have checks for them added as well).
//
// Notice that MinGW uses VC CRT by default but may use its own printf()
// implementation if __USE_MINGW_ANSI_STDIO is defined. And finally also notice
// that testing for __USE_MINGW_ANSI_STDIO directly results in a warning with
// -Wundef if it involves an operation with undefined __MINGW_FEATURES__ so
// test for the latter too to avoid it.
#if defined(__VISUALC__) || \
(defined(__MINGW32__) && \
(!defined(__MINGW_FEATURES__) || !__USE_MINGW_ANSI_STDIO))
#define wxUSING_VC_CRT_IO
#endif
// thrown when assert fails in debug build
class TestAssertFailure
{
public:
TestAssertFailure(const wxString& file,
int line,
const wxString& func,
const wxString& cond,
const wxString& msg)
: m_file(file),
m_line(line),
m_func(func),
m_cond(cond),
m_msg(msg)
{
}
const wxString m_file;
const int m_line;
const wxString m_func;
const wxString m_cond;
const wxString m_msg;
wxDECLARE_NO_ASSIGN_CLASS(TestAssertFailure);
};
// macro to use for the functions which are supposed to fail an assertion
#if wxDEBUG_LEVEL
// some old cppunit versions don't define CPPUNIT_ASSERT_THROW so roll our
// own
#define WX_ASSERT_FAILS_WITH_ASSERT_MESSAGE(msg, code) \
wxSTATEMENT_MACRO_BEGIN \
bool throwsAssert = false; \
try { code ; } \
catch ( const TestAssertFailure& ) { throwsAssert = true; } \
if ( !throwsAssert ) \
CPPUNIT_FAIL(msg); \
wxSTATEMENT_MACRO_END
#define WX_ASSERT_FAILS_WITH_ASSERT(code) \
WX_ASSERT_FAILS_WITH_ASSERT_MESSAGE( \
"expected assertion not generated", code)
#else
// there are no assertions in this build so we can't do anything (we used
// to check that the condition failed but this didn't work well as in
// normal build with wxDEBUG_LEVEL != 0 we can pass something not
// evaluating to a bool at all but it then would fail to compile in
// wxDEBUG_LEVEL == 0 case, so just don't do anything at all now).
#define WX_ASSERT_FAILS_WITH_ASSERT(cond)
#endif
#define WX_ASSERT_EVENT_OCCURS(eventcounter, count) \
{\
wxStopWatch sw; \
wxEventLoopBase* loop = wxEventLoopBase::GetActive(); \
while(eventcounter.GetCount() < count) \
{ \
if(sw.Time() < 100) \
loop->Dispatch(); \
else \
{ \
CPPUNIT_FAIL(wxString::Format("timeout reached with %d " \
"events received, %d expected", \
eventcounter.GetCount(), count).ToStdString()); \
break; \
} \
} \
eventcounter.Clear(); \
}
// these functions can be used to hook into wxApp event processing and are
// currently used by the events propagation test
class WXDLLIMPEXP_FWD_BASE wxEvent;
typedef int (*FilterEventFunc)(wxEvent&);
typedef bool (*ProcessEventFunc)(wxEvent&);
extern void SetFilterEventFunc(FilterEventFunc func);
extern void SetProcessEventFunc(ProcessEventFunc func);
extern bool IsNetworkAvailable();
extern bool IsAutomaticTest();
// Helper class setting the locale to the given one for its lifetime.
class LocaleSetter
{
public:
LocaleSetter(const char *loc)
: m_locOld(wxStrdupA(setlocale(LC_ALL, NULL)))
{
setlocale(LC_ALL, loc);
}
~LocaleSetter()
{
setlocale(LC_ALL, m_locOld);
free(m_locOld);
}
private:
char * const m_locOld;
wxDECLARE_NO_COPY_CLASS(LocaleSetter);
};
// An even simpler helper for setting the locale to "C" one during its lifetime.
class CLocaleSetter : private LocaleSetter
{
public:
CLocaleSetter() : LocaleSetter("C") { }
private:
wxDECLARE_NO_COPY_CLASS(CLocaleSetter);
};
// Macro that can be used to register the test with the given name in both the
// global unnamed registry so that it is ran by default and a registry with the
// same name as this test to allow running just this test individually.
//
// Notice that the name shouldn't include the "TestCase" suffix, it's added
// automatically by this macro.
//
// Implementation note: CPPUNIT_TEST_SUITE_[NAMED_]REGISTRATION macros can't be
// used here because they both declare the variable with the same name (as the
// "unique" name they generate is based on the line number which is the same
// for both calls inside the macro), so we need to do it manually.
#define wxREGISTER_UNIT_TEST(name) \
static CPPUNIT_NS::AutoRegisterSuite< name##TestCase > \
CPPUNIT_MAKE_UNIQUE_NAME( autoRegisterRegistry__ ); \
static CPPUNIT_NS::AutoRegisterSuite< name##TestCase > \
CPPUNIT_MAKE_UNIQUE_NAME( autoRegisterNamedRegistry__ )(#name "TestCase")
#endif
|
amc8391/mage | Mage.Server.Plugins/Mage.Tournament.BoosterDraft/src/mage/tournament/cubes/VintageCubeApril2020.java | package mage.tournament.cubes;
import mage.game.draft.DraftCube;
public class VintageCubeApril2020 extends DraftCube {
public VintageCubeApril2020() {
super("MTGO Vintage Cube April 2020");
cubeCards.add(new CardIdentity("Kytheon, Hero of Akros", ""));
cubeCards.add(new CardIdentity("Mother of Runes", ""));
cubeCards.add(new CardIdentity("Student of Warfare", ""));
cubeCards.add(new CardIdentity("Adanto Vanguard", ""));
cubeCards.add(new CardIdentity("Containment Priest", ""));
cubeCards.add(new CardIdentity("Leonin Relic-Warder", ""));
cubeCards.add(new CardIdentity("Porcelain Legionnaire", ""));
cubeCards.add(new CardIdentity("Selfless Spirit", ""));
cubeCards.add(new CardIdentity("Soulfire Grand Master", ""));
cubeCards.add(new CardIdentity("Stoneforge Mystic", ""));
cubeCards.add(new CardIdentity("Thalia, Guardian of Thraben", ""));
cubeCards.add(new CardIdentity("Tithe Taker", ""));
cubeCards.add(new CardIdentity("Wall of Omens", ""));
cubeCards.add(new CardIdentity("Blade Splicer", ""));
cubeCards.add(new CardIdentity("Brightling", ""));
cubeCards.add(new CardIdentity("Brimaz, King of Oreskos", ""));
cubeCards.add(new CardIdentity("Fairgrounds Warden", ""));
cubeCards.add(new CardIdentity("Flickerwisp", ""));
cubeCards.add(new CardIdentity("Monastery Mentor", ""));
cubeCards.add(new CardIdentity("Recruiter of the Guard", ""));
cubeCards.add(new CardIdentity("Silverblade Paladin", ""));
cubeCards.add(new CardIdentity("Emeria Angel", ""));
cubeCards.add(new CardIdentity("Hero of Bladehold", ""));
cubeCards.add(new CardIdentity("Linvala, Keeper of Silence", ""));
cubeCards.add(new CardIdentity("Restoration Angel", ""));
cubeCards.add(new CardIdentity("Angel of Invention", ""));
cubeCards.add(new CardIdentity("Elspeth Conquers Death", ""));
cubeCards.add(new CardIdentity("Archangel Avacyn", ""));
cubeCards.add(new CardIdentity("Baneslayer Angel", ""));
cubeCards.add(new CardIdentity("<NAME>", ""));
cubeCards.add(new CardIdentity("Reveillark", ""));
cubeCards.add(new CardIdentity("Sun Titan", ""));
cubeCards.add(new CardIdentity("Angel of Serenity", ""));
cubeCards.add(new CardIdentity("Elesh Norn, Grand Cenobite", ""));
cubeCards.add(new CardIdentity("Iona, Shield of Emeria", ""));
cubeCards.add(new CardIdentity("Gideon Blackblade", ""));
cubeCards.add(new CardIdentity("Elspeth, Sun's Nemesis", ""));
cubeCards.add(new CardIdentity("Gideon, Ally of Zendikar", ""));
cubeCards.add(new CardIdentity("Gideon Jura", ""));
cubeCards.add(new CardIdentity("Elspeth, Sun's Champion", ""));
cubeCards.add(new CardIdentity("Condemn", ""));
cubeCards.add(new CardIdentity("Enlightened Tutor", ""));
cubeCards.add(new CardIdentity("Mana Tithe", ""));
cubeCards.add(new CardIdentity("Path to Exile", ""));
cubeCards.add(new CardIdentity("Swords to Plowshares", ""));
cubeCards.add(new CardIdentity("Disenchant", ""));
cubeCards.add(new CardIdentity("Unexpectedly Absent", ""));
cubeCards.add(new CardIdentity("Balance", ""));
cubeCards.add(new CardIdentity("Council's Judgment", ""));
cubeCards.add(new CardIdentity("Spectral Procession", ""));
cubeCards.add(new CardIdentity("Armageddon", ""));
cubeCards.add(new CardIdentity("Day of Judgment", ""));
cubeCards.add(new CardIdentity("Ravages of War", ""));
cubeCards.add(new CardIdentity("Wrath of God", ""));
cubeCards.add(new CardIdentity("Terminus", ""));
cubeCards.add(new CardIdentity("Land Tax", ""));
cubeCards.add(new CardIdentity("Legion's Landing", ""));
cubeCards.add(new CardIdentity("Honor of the Pure", ""));
cubeCards.add(new CardIdentity("Banishing Light", ""));
cubeCards.add(new CardIdentity("Oblivion Ring", ""));
cubeCards.add(new CardIdentity("Faith's Fetters", ""));
cubeCards.add(new CardIdentity("Moat", ""));
cubeCards.add(new CardIdentity("Parallax Wave", ""));
cubeCards.add(new CardIdentity("Spear of Heliod", ""));
cubeCards.add(new CardIdentity("Karakas", ""));
cubeCards.add(new CardIdentity("Thassa's Oracle", ""));
cubeCards.add(new CardIdentity("Baral, Chief of Compliance", ""));
cubeCards.add(new CardIdentity("Jace, Vryn's Prodigy", ""));
cubeCards.add(new CardIdentity("Looter il-Kor", ""));
cubeCards.add(new CardIdentity("Phantasmal Image", ""));
cubeCards.add(new CardIdentity("Snapcaster Mage", ""));
cubeCards.add(new CardIdentity("Thing in the Ice", ""));
cubeCards.add(new CardIdentity("Arcane Artisan", ""));
cubeCards.add(new CardIdentity("Deceiver Exarch", ""));
cubeCards.add(new CardIdentity("Pestermite", ""));
cubeCards.add(new CardIdentity("Spellseeker", ""));
cubeCards.add(new CardIdentity("Trinket Mage", ""));
cubeCards.add(new CardIdentity("Vendilion Clique", ""));
cubeCards.add(new CardIdentity("Glen Elendra Archmage", ""));
cubeCards.add(new CardIdentity("Phyrexian Metamorph", ""));
cubeCards.add(new CardIdentity("Sower of Temptation", ""));
cubeCards.add(new CardIdentity("Venser, Shaper Savant", ""));
cubeCards.add(new CardIdentity("Mulldrifter", ""));
cubeCards.add(new CardIdentity("Riftwing Cloudskate", ""));
cubeCards.add(new CardIdentity("Consecrated Sphinx", ""));
cubeCards.add(new CardIdentity("Frost Titan", ""));
cubeCards.add(new CardIdentity("Torrential Gearhulk", ""));
cubeCards.add(new CardIdentity("Palinchron", ""));
cubeCards.add(new CardIdentity("In<NAME>", ""));
cubeCards.add(new CardIdentity("<NAME>", ""));
cubeCards.add(new CardIdentity("Jace, the Mind Sculptor", ""));
cubeCards.add(new CardIdentity("Tezzeret the Seeker", ""));
cubeCards.add(new CardIdentity("Ancestral Recall", ""));
cubeCards.add(new CardIdentity("Brainstorm", ""));
cubeCards.add(new CardIdentity("High Tide", ""));
cubeCards.add(new CardIdentity("Mystical Tutor", ""));
cubeCards.add(new CardIdentity("Spell Pierce", ""));
cubeCards.add(new CardIdentity("Brain Freeze", ""));
cubeCards.add(new CardIdentity("Counterspell", ""));
cubeCards.add(new CardIdentity("Daze", ""));
cubeCards.add(new CardIdentity("Impulse", ""));
cubeCards.add(new CardIdentity("Mana Drain", ""));
cubeCards.add(new CardIdentity("Mana Leak", ""));
cubeCards.add(new CardIdentity("Miscalculation", ""));
cubeCards.add(new CardIdentity("Remand", ""));
cubeCards.add(new CardIdentity("Frantic Search", ""));
cubeCards.add(new CardIdentity("Thirst for Knowledge", ""));
cubeCards.add(new CardIdentity("Cryptic Command", ""));
cubeCards.add(new CardIdentity("Fact or Fiction", ""));
cubeCards.add(new CardIdentity("Gifts Ungiven", ""));
cubeCards.add(new CardIdentity("Turnabout", ""));
cubeCards.add(new CardIdentity("Force of Will", ""));
cubeCards.add(new CardIdentity("Gush", ""));
cubeCards.add(new CardIdentity("Mystic Confluence", ""));
cubeCards.add(new CardIdentity("Repeal", ""));
cubeCards.add(new CardIdentity("Dig Through Time", ""));
cubeCards.add(new CardIdentity("Ancestral Vision", ""));
cubeCards.add(new CardIdentity("Gitaxian Probe", ""));
cubeCards.add(new CardIdentity("Ponder", ""));
cubeCards.add(new CardIdentity("Preordain", ""));
cubeCards.add(new CardIdentity("Chart a Course", ""));
cubeCards.add(new CardIdentity("Time Walk", ""));
cubeCards.add(new CardIdentity("Show and Tell", ""));
cubeCards.add(new CardIdentity("Timetwister", ""));
cubeCards.add(new CardIdentity("Tinker", ""));
cubeCards.add(new CardIdentity("Bribery", ""));
cubeCards.add(new CardIdentity("Time Warp", ""));
cubeCards.add(new CardIdentity("Mind's Desire", ""));
cubeCards.add(new CardIdentity("Time Spiral", ""));
cubeCards.add(new CardIdentity("Upheaval", ""));
cubeCards.add(new CardIdentity("Treasure Cruise", ""));
cubeCards.add(new CardIdentity("Search for Azcanta", ""));
cubeCards.add(new CardIdentity("Control Magic", ""));
cubeCards.add(new CardIdentity("Opposition", ""));
cubeCards.add(new CardIdentity("Treachery", ""));
cubeCards.add(new CardIdentity("Shelldock Isle", ""));
cubeCards.add(new CardIdentity("Tolarian Academy", ""));
cubeCards.add(new CardIdentity("Putrid Imp", ""));
cubeCards.add(new CardIdentity("Dark Confidant", ""));
cubeCards.add(new CardIdentity("Kitesail Freebooter", ""));
cubeCards.add(new CardIdentity("Mesmeric Fiend", ""));
cubeCards.add(new CardIdentity("Oona's Prowler", ""));
cubeCards.add(new CardIdentity("Pack Rat", ""));
cubeCards.add(new CardIdentity("Vampire Hexmage", ""));
cubeCards.add(new CardIdentity("Bone Shredder", ""));
cubeCards.add(new CardIdentity("Hypnotic Specter", ""));
cubeCards.add(new CardIdentity("Ophiomancer", ""));
cubeCards.add(new CardIdentity("Plaguecrafter", ""));
cubeCards.add(new CardIdentity("Vampire Nighthawk", ""));
cubeCards.add(new CardIdentity("Gonti, Lord of Luxury", ""));
cubeCards.add(new CardIdentity("Nekrataal", ""));
cubeCards.add(new CardIdentity("Ravenous Chupacabra", ""));
cubeCards.add(new CardIdentity("Shriekmaw", ""));
cubeCards.add(new CardIdentity("Grave Titan", ""));
cubeCards.add(new CardIdentity("Ink-Eyes, Servant of Oni", ""));
cubeCards.add(new CardIdentity("<NAME>", ""));
cubeCards.add(new CardIdentity("Tasigur, the Golden Fang", ""));
cubeCards.add(new CardIdentity("Sheoldred, Whispering One", ""));
cubeCards.add(new CardIdentity("Griselbrand", ""));
cubeCards.add(new CardIdentity("Liliana of the Veil", ""));
cubeCards.add(new CardIdentity("Liliana, Death's Majesty", ""));
cubeCards.add(new CardIdentity("Dark Ritual", ""));
cubeCards.add(new CardIdentity("Entomb", ""));
cubeCards.add(new CardIdentity("Fatal Push", ""));
cubeCards.add(new CardIdentity("Vampiric Tutor", ""));
cubeCards.add(new CardIdentity("Cabal Ritual", ""));
cubeCards.add(new CardIdentity("Go for the Throat", ""));
cubeCards.add(new CardIdentity("Liliana's Triumph", ""));
cubeCards.add(new CardIdentity("Shallow Grave", ""));
cubeCards.add(new CardIdentity("Ultimate Price", ""));
cubeCards.add(new CardIdentity("Corpse Dance", ""));
cubeCards.add(new CardIdentity("Dismember", ""));
cubeCards.add(new CardIdentity("Hero's Downfall", ""));
cubeCards.add(new CardIdentity("Makeshift Mannequin", ""));
cubeCards.add(new CardIdentity("Duress", ""));
cubeCards.add(new CardIdentity("Imperial Seal", ""));
cubeCards.add(new CardIdentity("Inquisition of Kozilek", ""));
cubeCards.add(new CardIdentity("Reanimate", ""));
cubeCards.add(new CardIdentity("Thoughtseize", ""));
cubeCards.add(new CardIdentity("Collective Brutality", ""));
cubeCards.add(new CardIdentity("Demonic Tutor", ""));
cubeCards.add(new CardIdentity("Exhume", ""));
cubeCards.add(new CardIdentity("Hymn to Tourach", ""));
cubeCards.add(new CardIdentity("Night's Whisper", ""));
cubeCards.add(new CardIdentity("Buried Alive", ""));
cubeCards.add(new CardIdentity("Toxic Deluge", ""));
cubeCards.add(new CardIdentity("Yawgmoth's Will", ""));
cubeCards.add(new CardIdentity("Damnation", ""));
cubeCards.add(new CardIdentity("Languish", ""));
cubeCards.add(new CardIdentity("Mastermind's Acquisition", ""));
cubeCards.add(new CardIdentity("Tendrils of Agony", ""));
cubeCards.add(new CardIdentity("Dark Petition", ""));
cubeCards.add(new CardIdentity("Living Death", ""));
cubeCards.add(new CardIdentity("Mind Twist", ""));
cubeCards.add(new CardIdentity("Animate Dead", ""));
cubeCards.add(new CardIdentity("Bitterblossom", ""));
cubeCards.add(new CardIdentity("Necromancy", ""));
cubeCards.add(new CardIdentity("Phyrexian Arena", ""));
cubeCards.add(new CardIdentity("Recurring Nightmare", ""));
cubeCards.add(new CardIdentity("Yawgmoth's Bargain", ""));
cubeCards.add(new CardIdentity("Goblin Guide", ""));
cubeCards.add(new CardIdentity("Goblin Welder", ""));
cubeCards.add(new CardIdentity("Grim Lavamancer", ""));
cubeCards.add(new CardIdentity("Jackal Pup", ""));
cubeCards.add(new CardIdentity("Monastery Swiftspear", ""));
cubeCards.add(new CardIdentity("Zurgo Bellstriker", ""));
cubeCards.add(new CardIdentity("Abbot of Keral Keep", ""));
cubeCards.add(new CardIdentity("Dire Fleet Daredevil", ""));
cubeCards.add(new CardIdentity("Eidolon of the Great Revel", ""));
cubeCards.add(new CardIdentity("Runaway Steam-Kin", ""));
cubeCards.add(new CardIdentity("Young Pyromancer", ""));
cubeCards.add(new CardIdentity("Goblin Rabblemaster", ""));
cubeCards.add(new CardIdentity("Imperial Recruiter", ""));
cubeCards.add(new CardIdentity("Magus of the Moon", ""));
cubeCards.add(new CardIdentity("Avalanche Riders", ""));
cubeCards.add(new CardIdentity("Flametongue Kavu", ""));
cubeCards.add(new CardIdentity("Hazoret the Fervent", ""));
cubeCards.add(new CardIdentity("Hellrider", ""));
cubeCards.add(new CardIdentity("Pia and <NAME>", ""));
cubeCards.add(new CardIdentity("Rekindling Phoenix", ""));
cubeCards.add(new CardIdentity("Glorybringer", ""));
cubeCards.add(new CardIdentity("Goblin Dark-Dwellers", ""));
cubeCards.add(new CardIdentity("Kiki-Jiki, Mirror Breaker", ""));
cubeCards.add(new CardIdentity("Siege-Gang Commander", ""));
cubeCards.add(new CardIdentity("Thundermaw Hellkite", ""));
cubeCards.add(new CardIdentity("Zealous Conscripts", ""));
cubeCards.add(new CardIdentity("Inferno Titan", ""));
cubeCards.add(new CardIdentity("Chandra, Torch of Defiance", ""));
cubeCards.add(new CardIdentity("Daretti, Scrap Savant", ""));
cubeCards.add(new CardIdentity("Koth of the Hammer", ""));
cubeCards.add(new CardIdentity("Burst Lightning", ""));
cubeCards.add(new CardIdentity("Lightning Bolt", ""));
cubeCards.add(new CardIdentity("Abrade", ""));
cubeCards.add(new CardIdentity("Ancient Grudge", ""));
cubeCards.add(new CardIdentity("Desperate Ritual", ""));
cubeCards.add(new CardIdentity("Fire // Ice", ""));
cubeCards.add(new CardIdentity("Incinerate", ""));
cubeCards.add(new CardIdentity("Lightning Strike", ""));
cubeCards.add(new CardIdentity("Pyretic Ritual", ""));
cubeCards.add(new CardIdentity("Char", ""));
cubeCards.add(new CardIdentity("Seething Song", ""));
cubeCards.add(new CardIdentity("Through the Breach", ""));
cubeCards.add(new CardIdentity("Fireblast", ""));
cubeCards.add(new CardIdentity("Chain Lightning", ""));
cubeCards.add(new CardIdentity("Faithless Looting", ""));
cubeCards.add(new CardIdentity("Firebolt", ""));
cubeCards.add(new CardIdentity("Flame Slash", ""));
cubeCards.add(new CardIdentity("Mizzium Mortars", ""));
cubeCards.add(new CardIdentity("Pyroclasm", ""));
cubeCards.add(new CardIdentity("Light Up the Stage", ""));
cubeCards.add(new CardIdentity("Underworld Breach", ""));
cubeCards.add(new CardIdentity("Wheel of Fortune", ""));
cubeCards.add(new CardIdentity("Empty the Warrens", ""));
cubeCards.add(new CardIdentity("Fiery Confluence", ""));
cubeCards.add(new CardIdentity("Past in Flames", ""));
cubeCards.add(new CardIdentity("Banefire", ""));
cubeCards.add(new CardIdentity("Burning of Xinye", ""));
cubeCards.add(new CardIdentity("Wildfire", ""));
cubeCards.add(new CardIdentity("Bonfire of the Damned", ""));
cubeCards.add(new CardIdentity("Mana Flare", ""));
cubeCards.add(new CardIdentity("Sulfuric Vortex", ""));
cubeCards.add(new CardIdentity("Sneak Attack", ""));
cubeCards.add(new CardIdentity("Splinter Twin", ""));
cubeCards.add(new CardIdentity("Arbor Elf", ""));
cubeCards.add(new CardIdentity("Avacyn's Pilgrim", ""));
cubeCards.add(new CardIdentity("Birds of Paradise", ""));
cubeCards.add(new CardIdentity("Elves of Deep Shadow", ""));
cubeCards.add(new CardIdentity("Elvish Mystic", ""));
cubeCards.add(new CardIdentity("Fyndhorn Elves", ""));
cubeCards.add(new CardIdentity("Joraga Treespeaker", ""));
cubeCards.add(new CardIdentity("Llanowar Elves", ""));
cubeCards.add(new CardIdentity("Noble Hierarch", ""));
cubeCards.add(new CardIdentity("Den Protector", ""));
cubeCards.add(new CardIdentity("Devoted Druid", ""));
cubeCards.add(new CardIdentity("Fauna Shaman", ""));
cubeCards.add(new CardIdentity("Gilded Goose", ""));
cubeCards.add(new CardIdentity("Lotus Cobra", ""));
cubeCards.add(new CardIdentity("Rofellos, Llanowar Emissary", ""));
cubeCards.add(new CardIdentity("Sakura-Tribe Elder", ""));
cubeCards.add(new CardIdentity("Scavenging Ooze", ""));
cubeCards.add(new CardIdentity("Sy<NAME>", ""));
cubeCards.add(new CardIdentity("Wall of Blossoms", ""));
cubeCards.add(new CardIdentity("Wall of Roots", ""));
cubeCards.add(new CardIdentity("Courser of Kruphix", ""));
cubeCards.add(new CardIdentity("Eternal Witness", ""));
cubeCards.add(new CardIdentity("Ramunap Excavator", ""));
cubeCards.add(new CardIdentity("Reclamation Sage", ""));
cubeCards.add(new CardIdentity("Tireless Tracker", ""));
cubeCards.add(new CardIdentity("Yavimaya Elder", ""));
cubeCards.add(new CardIdentity("Master of the Wild Hunt", ""));
cubeCards.add(new CardIdentity("Oracle of Mul Daya", ""));
cubeCards.add(new CardIdentity("Polukranos, World Eater", ""));
cubeCards.add(new CardIdentity("Acidic Slime", ""));
cubeCards.add(new CardIdentity("Biogenic Ooze", ""));
cubeCards.add(new CardIdentity("Deranged Hermit", ""));
cubeCards.add(new CardIdentity("Thragtusk", ""));
cubeCards.add(new CardIdentity("Whisperwood Elemental", ""));
cubeCards.add(new CardIdentity("Carnage Tyrant", ""));
cubeCards.add(new CardIdentity("Primeval Titan", ""));
cubeCards.add(new CardIdentity("Avenger of Zendikar", ""));
cubeCards.add(new CardIdentity("Craterhoof Behemoth", ""));
cubeCards.add(new CardIdentity("Terastodon", ""));
cubeCards.add(new CardIdentity("Woodfall Primus", ""));
cubeCards.add(new CardIdentity("Dryad of the Ilysian Grove", ""));
cubeCards.add(new CardIdentity("Garruk Relentless", ""));
cubeCards.add(new CardIdentity("Garruk Wildspeaker", ""));
cubeCards.add(new CardIdentity("Garruk, Primal Hunter", ""));
cubeCards.add(new CardIdentity("Vivien Reid", ""));
cubeCards.add(new CardIdentity("Nature's Claim", ""));
cubeCards.add(new CardIdentity("Beast Within", ""));
cubeCards.add(new CardIdentity("Channel", ""));
cubeCards.add(new CardIdentity("Regrowth", ""));
cubeCards.add(new CardIdentity("Kodama's Reach", ""));
cubeCards.add(new CardIdentity("Search for Tomorrow", ""));
cubeCards.add(new CardIdentity("Eureka", ""));
cubeCards.add(new CardIdentity("Harmonize", ""));
cubeCards.add(new CardIdentity("Natural Order", ""));
cubeCards.add(new CardIdentity("Plow Under", ""));
cubeCards.add(new CardIdentity("Primal Command", ""));
cubeCards.add(new CardIdentity("Green Sun's Zenith", ""));
cubeCards.add(new CardIdentity("Finale of Devastation", ""));
cubeCards.add(new CardIdentity("Tooth and Nail", ""));
cubeCards.add(new CardIdentity("Fastbond", ""));
cubeCards.add(new CardIdentity("Oath of Druids", ""));
cubeCards.add(new CardIdentity("Survival of the Fittest", ""));
cubeCards.add(new CardIdentity("Sylvan Library", ""));
cubeCards.add(new CardIdentity("Heartbeat of Spring", ""));
cubeCards.add(new CardIdentity("Wilderness Reclamation", ""));
cubeCards.add(new CardIdentity("Gaea's Cradle", ""));
cubeCards.add(new CardIdentity("Geist of Saint Traft", ""));
cubeCards.add(new CardIdentity("Teferi, Hero of Dominaria", ""));
cubeCards.add(new CardIdentity("Sphinx's Revelation", ""));
cubeCards.add(new CardIdentity("Fractured Identity", ""));
cubeCards.add(new CardIdentity("Celestial Colonnade", ""));
cubeCards.add(new CardIdentity("Flooded Strand", ""));
cubeCards.add(new CardIdentity("Hallowed Fountain", ""));
cubeCards.add(new CardIdentity("Seachrome Coast", ""));
cubeCards.add(new CardIdentity("Tundra", ""));
cubeCards.add(new CardIdentity("Thief of Sanity", ""));
cubeCards.add(new CardIdentity("The Scarab God", ""));
cubeCards.add(new CardIdentity("Ashiok, Nightmare Weaver", ""));
cubeCards.add(new CardIdentity("Baleful Strix", ""));
cubeCards.add(new CardIdentity("Creeping Tar Pit", ""));
cubeCards.add(new CardIdentity("Darkslick Shores", ""));
cubeCards.add(new CardIdentity("Polluted Delta", ""));
cubeCards.add(new CardIdentity("Underground Sea", ""));
cubeCards.add(new CardIdentity("Watery Grave", ""));
cubeCards.add(new CardIdentity("Daretti, Ingenious Iconoclast", ""));
cubeCards.add(new CardIdentity("Kroxa, Titan of Death's Hunger", ""));
cubeCards.add(new CardIdentity("Kolaghan's Command", ""));
cubeCards.add(new CardIdentity("Rakdos's Return", ""));
cubeCards.add(new CardIdentity("Badlands", ""));
cubeCards.add(new CardIdentity("Blackcleave Cliffs", ""));
cubeCards.add(new CardIdentity("Blood Crypt", ""));
cubeCards.add(new CardIdentity("Bloodstained Mire", ""));
cubeCards.add(new CardIdentity("Lavaclaw Reaches", ""));
cubeCards.add(new CardIdentity("Bloodbraid Elf", ""));
cubeCards.add(new CardIdentity("Huntmaster of the Fells", ""));
cubeCards.add(new CardIdentity("Dragonlord Atarka", ""));
cubeCards.add(new CardIdentity("Manamorphose", ""));
cubeCards.add(new CardIdentity("Copperline Gorge", ""));
cubeCards.add(new CardIdentity("Raging Ravine", ""));
cubeCards.add(new CardIdentity("Stomping Ground", ""));
cubeCards.add(new CardIdentity("Taiga", ""));
cubeCards.add(new CardIdentity("Wooded Foothills", ""));
cubeCards.add(new CardIdentity("Kitchen Finks", ""));
cubeCards.add(new CardIdentity("Knight of Autumn", ""));
cubeCards.add(new CardIdentity("Knight of the Reliquary", ""));
cubeCards.add(new CardIdentity("Trostani Discordant", ""));
cubeCards.add(new CardIdentity("Mirari's Wake", ""));
cubeCards.add(new CardIdentity("Razorverge Thicket", ""));
cubeCards.add(new CardIdentity("Savannah", ""));
cubeCards.add(new CardIdentity("Stirring Wildwood", ""));
cubeCards.add(new CardIdentity("Temple Garden", ""));
cubeCards.add(new CardIdentity("Windswept Heath", ""));
cubeCards.add(new CardIdentity("Ashen Rider", ""));
cubeCards.add(new CardIdentity("Kaya, Orzhov Usurper", ""));
cubeCards.add(new CardIdentity("Tidehollow Sculler", ""));
cubeCards.add(new CardIdentity("Anguished Unmaking", ""));
cubeCards.add(new CardIdentity("Lingering Souls", ""));
cubeCards.add(new CardIdentity("Vindicate", ""));
cubeCards.add(new CardIdentity("Unburial Rites", ""));
cubeCards.add(new CardIdentity("Concealed Courtyard", ""));
cubeCards.add(new CardIdentity("Godless Shrine", ""));
cubeCards.add(new CardIdentity("Marsh Flats", ""));
cubeCards.add(new CardIdentity("Scrubland", ""));
cubeCards.add(new CardIdentity("Shambling Vent", ""));
cubeCards.add(new CardIdentity("Vraska, Golgari Queen", ""));
cubeCards.add(new CardIdentity("Assassin's Trophy", ""));
cubeCards.add(new CardIdentity("Maelstrom Pulse", ""));
cubeCards.add(new CardIdentity("Pernicious Deed", ""));
cubeCards.add(new CardIdentity("Bayou", ""));
cubeCards.add(new CardIdentity("Blooming Marsh", ""));
cubeCards.add(new CardIdentity("Hissing Quagmire", ""));
cubeCards.add(new CardIdentity("Overgrown Tomb", ""));
cubeCards.add(new CardIdentity("Verdant Catacombs", ""));
cubeCards.add(new CardIdentity("Edric, Spymaster of Trest", ""));
cubeCards.add(new CardIdentity("Trygon Predator", ""));
cubeCards.add(new CardIdentity("Hydroid Krasis", ""));
cubeCards.add(new CardIdentity("Uro, Titan of Nature's Wrath", ""));
cubeCards.add(new CardIdentity("Botanical Sanctum", ""));
cubeCards.add(new CardIdentity("Breeding Pool", ""));
cubeCards.add(new CardIdentity("Lumbering Falls", ""));
cubeCards.add(new CardIdentity("Misty Rainforest", ""));
cubeCards.add(new CardIdentity("Tropical Island", ""));
cubeCards.add(new CardIdentity("Goblin Electromancer", ""));
cubeCards.add(new CardIdentity("Dack Fayden", ""));
cubeCards.add(new CardIdentity("Thousand-Year Storm", ""));
cubeCards.add(new CardIdentity("Scalding Tarn", ""));
cubeCards.add(new CardIdentity("Spirebluff Canal", ""));
cubeCards.add(new CardIdentity("Steam Vents", ""));
cubeCards.add(new CardIdentity("Volcanic Island", ""));
cubeCards.add(new CardIdentity("Wandering Fumarole", ""));
cubeCards.add(new CardIdentity("Figure of Destiny", ""));
cubeCards.add(new CardIdentity("Ajani Vengeant", ""));
cubeCards.add(new CardIdentity("Nahiri, the Harbinger", ""));
cubeCards.add(new CardIdentity("Wear // Tear", ""));
cubeCards.add(new CardIdentity("Lightning Helix", ""));
cubeCards.add(new CardIdentity("A<NAME>", ""));
cubeCards.add(new CardIdentity("Inspiring Vantage", ""));
cubeCards.add(new CardIdentity("Needle Spires", ""));
cubeCards.add(new CardIdentity("Plateau", ""));
cubeCards.add(new CardIdentity("Sacred Foundry", ""));
cubeCards.add(new CardIdentity("Sphinx of the Steel Wind", ""));
cubeCards.add(new CardIdentity("<NAME>, Dragon-God", ""));
cubeCards.add(new CardIdentity("Leovold, Emissary of Trest", ""));
cubeCards.add(new CardIdentity("Progenitus", ""));
cubeCards.add(new CardIdentity("Kozilek, Butcher of Truth", ""));
cubeCards.add(new CardIdentity("Ulamog, the Ceaseless Hunger", ""));
cubeCards.add(new CardIdentity("Ulamog, the Infinite Gyre", ""));
cubeCards.add(new CardIdentity("Emrakul, the Promised End", ""));
cubeCards.add(new CardIdentity("Emrakul, the Aeons Torn", ""));
cubeCards.add(new CardIdentity("Karn, Scion of Urza", ""));
cubeCards.add(new CardIdentity("Karn Liberated", ""));
cubeCards.add(new CardIdentity("Ugin, the Spirit Dragon", ""));
cubeCards.add(new CardIdentity("Bomat Courier", ""));
cubeCards.add(new CardIdentity("Hangarback Walker", ""));
cubeCards.add(new CardIdentity("Phyrexian Revoker", ""));
cubeCards.add(new CardIdentity("Metalworker", ""));
cubeCards.add(new CardIdentity("Lodestone Golem", ""));
cubeCards.add(new CardIdentity("Solemn Simulacrum", ""));
cubeCards.add(new CardIdentity("Kuldotha Forgemaster", ""));
cubeCards.add(new CardIdentity("Wurmcoil Engine", ""));
cubeCards.add(new CardIdentity("Myr Battlesphere", ""));
cubeCards.add(new CardIdentity("Sundering Titan", ""));
cubeCards.add(new CardIdentity("Walking Ballista", ""));
cubeCards.add(new CardIdentity("Blightsteel Colossus", ""));
cubeCards.add(new CardIdentity("Black Lotus", ""));
cubeCards.add(new CardIdentity("Chrome Mox", ""));
cubeCards.add(new CardIdentity("Everflowing Chalice", ""));
cubeCards.add(new CardIdentity("Lion's Eye Diamond", ""));
cubeCards.add(new CardIdentity("Lotus Bloom", ""));
cubeCards.add(new CardIdentity("Mana Crypt", ""));
cubeCards.add(new CardIdentity("Mox Diamond", ""));
cubeCards.add(new CardIdentity("Mox Emerald", ""));
cubeCards.add(new CardIdentity("Mox Jet", ""));
cubeCards.add(new CardIdentity("Mox Pearl", ""));
cubeCards.add(new CardIdentity("Mox Ruby", ""));
cubeCards.add(new CardIdentity("Mox Sapphire", ""));
cubeCards.add(new CardIdentity("Mana Vault", ""));
cubeCards.add(new CardIdentity("Relic of Progenitus", ""));
cubeCards.add(new CardIdentity("Sensei's Divining Top", ""));
cubeCards.add(new CardIdentity("Skullclamp", ""));
cubeCards.add(new CardIdentity("Sol Ring", ""));
cubeCards.add(new CardIdentity("Azorius Signet", ""));
cubeCards.add(new CardIdentity("Boros Signet", ""));
cubeCards.add(new CardIdentity("Dimir Signet", ""));
cubeCards.add(new CardIdentity("Golgari Signet", ""));
cubeCards.add(new CardIdentity("Grim Monolith", ""));
cubeCards.add(new CardIdentity("Gruul Signet", ""));
cubeCards.add(new CardIdentity("Izzet Signet", ""));
cubeCards.add(new CardIdentity("Lightning Greaves", ""));
cubeCards.add(new CardIdentity("Orzhov Signet", ""));
cubeCards.add(new CardIdentity("Rakdos Signet", ""));
cubeCards.add(new CardIdentity("Selesnya Signet", ""));
cubeCards.add(new CardIdentity("Shrine of Burning Rage", ""));
cubeCards.add(new CardIdentity("Simic Signet", ""));
cubeCards.add(new CardIdentity("Smuggler's Copter", ""));
cubeCards.add(new CardIdentity("Umezawa's Jitte", ""));
cubeCards.add(new CardIdentity("Winter Orb", ""));
cubeCards.add(new CardIdentity("Basalt Monolith", ""));
cubeCards.add(new CardIdentity("Coalition Relic", ""));
cubeCards.add(new CardIdentity("Crucible of Worlds", ""));
cubeCards.add(new CardIdentity("Oblivion Stone", ""));
cubeCards.add(new CardIdentity("Sword of Body and Mind", ""));
cubeCards.add(new CardIdentity("Sword of Feast and Famine", ""));
cubeCards.add(new CardIdentity("Sword of Fire and Ice", ""));
cubeCards.add(new CardIdentity("Sword of Light and Shadow", ""));
cubeCards.add(new CardIdentity("Sword of War and Peace", ""));
cubeCards.add(new CardIdentity("Tangle Wire", ""));
cubeCards.add(new CardIdentity("Worn Powerstone", ""));
cubeCards.add(new CardIdentity("Coercive Portal", ""));
cubeCards.add(new CardIdentity("Smokestack", ""));
cubeCards.add(new CardIdentity("Thran Dynamo", ""));
cubeCards.add(new CardIdentity("Batterskull", ""));
cubeCards.add(new CardIdentity("Memory Jar", ""));
cubeCards.add(new CardIdentity("Mindslaver", ""));
cubeCards.add(new CardIdentity("Academy Ruins", ""));
cubeCards.add(new CardIdentity("Ancient Tomb", ""));
cubeCards.add(new CardIdentity("Bazaar of Baghdad", ""));
cubeCards.add(new CardIdentity("Blast Zone", ""));
cubeCards.add(new CardIdentity("Field of Ruin", ""));
cubeCards.add(new CardIdentity("Library of Alexandria", ""));
cubeCards.add(new CardIdentity("Maze of Ith", ""));
cubeCards.add(new CardIdentity("Mishra's Factory", ""));
cubeCards.add(new CardIdentity("Mishra's Workshop", ""));
cubeCards.add(new CardIdentity("Mutavault", ""));
cubeCards.add(new CardIdentity("Nykthos, Shrine to Nyx", ""));
cubeCards.add(new CardIdentity("Rishadan Port", ""));
cubeCards.add(new CardIdentity("Strip Mine", ""));
cubeCards.add(new CardIdentity("Wasteland", ""));
cubeCards.add(new CardIdentity("Expansion // Explosion", ""));
cubeCards.add(new CardIdentity("Giver of Runes", ""));
cubeCards.add(new CardIdentity("Winds of Abandon", ""));
cubeCards.add(new CardIdentity("Hallowed Spiritkeeper", ""));
cubeCards.add(new CardIdentity("Thraben Inspector", ""));
cubeCards.add(new CardIdentity("Narset, Parter of Veils", ""));
cubeCards.add(new CardIdentity("Force of Negation", ""));
cubeCards.add(new CardIdentity("Urza, Lord High Artificer", ""));
cubeCards.add(new CardIdentity("Emry, Lurker of the Loch", ""));
cubeCards.add(new CardIdentity("Brazen Borrower", ""));
cubeCards.add(new CardIdentity("Bolas's Citadel", ""));
cubeCards.add(new CardIdentity("Yawgmoth, Thran Physician", ""));
cubeCards.add(new CardIdentity("Rotting Regisaur", ""));
cubeCards.add(new CardIdentity("Murderous Rider", ""));
cubeCards.add(new CardIdentity("<NAME>", ""));
cubeCards.add(new CardIdentity("Dreadhorde Arcanist", ""));
cubeCards.add(new CardIdentity("Seasoned Pyromancer", ""));
cubeCards.add(new CardIdentity("Embereth Shieldbreaker", ""));
cubeCards.add(new CardIdentity("Nissa, Who Shakes the World", ""));
cubeCards.add(new CardIdentity("Questing Beast", ""));
cubeCards.add(new CardIdentity("Teferi, Time Raveler", ""));
cubeCards.add(new CardIdentity("Angrath's Rampage", ""));
cubeCards.add(new CardIdentity("Fallen Shinobi", ""));
cubeCards.add(new CardIdentity("Wrenn and Six", ""));
cubeCards.add(new CardIdentity("Oko, Thief of Crowns", ""));
cubeCards.add(new CardIdentity("Garruk, Cursed Huntsman", ""));
cubeCards.add(new CardIdentity("Prismatic Vista", ""));
cubeCards.add(new CardIdentity("Golos, Tireless Pilgrim", ""));
cubeCards.add(new CardIdentity("Stonecoil Serpent", ""));
}
}
|
johnrobertdelinila/harmony_capstone | app/src/main/java/com/capstone/harmony/adapters/PostPhotosAdapter.java | package com.capstone.harmony.adapters;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.media.MediaPlayer;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Parcelable;
import android.util.Log;
import android.view.GestureDetector;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.DecelerateInterpolator;
import android.widget.ImageView;
import android.widget.MediaController;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.VideoView;
import androidx.annotation.NonNull;
import androidx.viewpager.widget.PagerAdapter;
import com.capstone.harmony.R;
import com.capstone.harmony.models.MultipleImage;
import com.capstone.harmony.ui.activities.notification.ImagePreview;
import com.capstone.harmony.ui.views.HifyImageView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.github.ivbaranov.mfb.MaterialFavoriteButton;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.firestore.FirebaseFirestore;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import id.zelory.compressor.Compressor;
public class PostPhotosAdapter extends PagerAdapter {
private ArrayList<MultipleImage> IMAGES;
private boolean local;
private LayoutInflater inflater;
private Context context;
private File compressedFile;
private Activity activity;
private String postId;
private static final DecelerateInterpolator DECCELERATE_INTERPOLATOR = new DecelerateInterpolator();
private static final AccelerateInterpolator ACCELERATE_INTERPOLATOR = new AccelerateInterpolator();
private MaterialFavoriteButton like_btn;
public PostPhotosAdapter(Context context, Activity activity, ArrayList<MultipleImage> IMAGES, boolean local, String postId, MaterialFavoriteButton like_btn) {
this.context = context;
this.IMAGES =IMAGES;
this.local=local;
this.activity=activity;
inflater = LayoutInflater.from(context);
this.postId=postId;
this.like_btn=like_btn;
}
@Override
public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
container.removeView((View) object);
}
@Override
public int getCount() {
return IMAGES.size();
}
private void animatePhotoLike(final View vBgLike, final ImageView ivLike) {
vBgLike.setVisibility(View.VISIBLE);
ivLike.setVisibility(View.VISIBLE);
vBgLike.setScaleY(0.1f);
vBgLike.setScaleX(0.1f);
vBgLike.setAlpha(1f);
ivLike.setScaleY(0.1f);
ivLike.setScaleX(0.1f);
AnimatorSet animatorSet = new AnimatorSet();
ObjectAnimator bgScaleYAnim = ObjectAnimator.ofFloat(vBgLike, "scaleY", 0.1f, 1f);
bgScaleYAnim.setDuration(300);
bgScaleYAnim.setInterpolator(DECCELERATE_INTERPOLATOR);
ObjectAnimator bgScaleXAnim = ObjectAnimator.ofFloat(vBgLike, "scaleX", 0.1f, 1f);
bgScaleXAnim.setDuration(300);
bgScaleXAnim.setInterpolator(DECCELERATE_INTERPOLATOR);
ObjectAnimator bgAlphaAnim = ObjectAnimator.ofFloat(vBgLike, "alpha", 1f, 0f);
bgAlphaAnim.setDuration(300);
bgAlphaAnim.setStartDelay(150);
bgAlphaAnim.setInterpolator(DECCELERATE_INTERPOLATOR);
ObjectAnimator imgScaleUpYAnim = ObjectAnimator.ofFloat(ivLike, "scaleY", 0.1f, 1f);
imgScaleUpYAnim.setDuration(300);
imgScaleUpYAnim.setInterpolator(DECCELERATE_INTERPOLATOR);
ObjectAnimator imgScaleUpXAnim = ObjectAnimator.ofFloat(ivLike, "scaleX", 0.1f, 1f);
imgScaleUpXAnim.setDuration(300);
imgScaleUpXAnim.setInterpolator(DECCELERATE_INTERPOLATOR);
ObjectAnimator imgScaleDownYAnim = ObjectAnimator.ofFloat(ivLike, "scaleY", 1f, 0f);
imgScaleDownYAnim.setDuration(300);
imgScaleDownYAnim.setInterpolator(ACCELERATE_INTERPOLATOR);
ObjectAnimator imgScaleDownXAnim = ObjectAnimator.ofFloat(ivLike, "scaleX", 1f, 0f);
imgScaleDownXAnim.setDuration(300);
imgScaleDownXAnim.setInterpolator(ACCELERATE_INTERPOLATOR);
animatorSet.playTogether(bgScaleYAnim, bgScaleXAnim, bgAlphaAnim, imgScaleUpYAnim, imgScaleUpXAnim);
animatorSet.play(imgScaleDownYAnim).with(imgScaleDownXAnim).after(imgScaleUpYAnim);
animatorSet.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
resetLikeAnimationState(vBgLike,ivLike);
like_btn.setFavorite(true,true);
}
@Override
public void onAnimationStart(Animator animation) {
super.onAnimationStart(animation);
Map<String, Object> likeMap = new HashMap<>();
likeMap.put("liked", true);
try {
FirebaseFirestore.getInstance().collection("Posts")
.document(postId)
.collection("Liked_Users")
.document(FirebaseAuth.getInstance().getCurrentUser().getUid())
.set(likeMap)
.addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
Log.i("post", "liked");
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Log.e("Error like", e.getMessage());
}
});
}catch (Exception e){
e.printStackTrace();
}
}
});
animatorSet.start();
}
private void resetLikeAnimationState(View vBgLike,ImageView ivLike) {
vBgLike.setVisibility(View.INVISIBLE);
ivLike.setVisibility(View.INVISIBLE);
}
public boolean isOnline() {
ConnectivityManager cm =
(ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
return netInfo != null && netInfo.isConnectedOrConnecting();
}
@SuppressLint("ClickableViewAccessibility")
@NonNull
@Override
public Object instantiateItem(@NonNull ViewGroup view, final int position) {
final View imageLayout = inflater.inflate(R.layout.item_viewpager_image, view, false);
assert imageLayout!=null;
HifyImageView imageView = imageLayout.findViewById(R.id.image);
VideoView videoView = imageLayout.findViewById(R.id.video);
RelativeLayout relativeLayout = imageLayout.findViewById(R.id.video_container);
ProgressBar progressBar = imageLayout.findViewById(R.id.progress);
final View vBgLike = imageLayout.findViewById(R.id.vBgLike);
final ImageView ivLike = imageLayout.findViewById(R.id.ivLike);
String tempMediaPath = IMAGES.get(position).getUrl().toLowerCase().trim();
if (tempMediaPath.contains(".png") || tempMediaPath.contains("jpg") || tempMediaPath.contains("jpeg")) {
imageView.setVisibility(View.VISIBLE);
if(!local) {
final GestureDetector detector=new GestureDetector(context, new GestureDetector.SimpleOnGestureListener(){
@Override
public boolean onDown(MotionEvent e) {
return true;
}
@Override
public void onLongPress(MotionEvent e) {
super.onLongPress(e);
Intent intent=new Intent(context, ImagePreview.class)
.putExtra("uri","")
//.putExtra("sender_name","Posts")
.putExtra("url",IMAGES.get(position).getUrl());
context.startActivity(intent);
}
@Override
public boolean onDoubleTap(MotionEvent e) {
if(isOnline()) {
animatePhotoLike(vBgLike, ivLike);
}
return true;
}
}
);
imageView.setOnTouchListener((v, event) -> detector.onTouchEvent(event));
Glide.with(context)
.setDefaultRequestOptions(new RequestOptions().placeholder(R.drawable.placeholder2))
.load(IMAGES.get(position).getUrl())
.into(imageView);
}else{
try {
compressedFile= new Compressor(context).setCompressFormat(Bitmap.CompressFormat.PNG).setQuality(75).setMaxHeight(350).compressToFile(new File(IMAGES.get(position).getLocal_path()));
imageView.setImageURI(Uri.fromFile(compressedFile));
} catch (IOException e) {
e.printStackTrace();
}
}
}else {
relativeLayout.setVisibility(View.VISIBLE);
progressBar.setVisibility(View.VISIBLE);
Uri uri = Uri.parse(IMAGES.get(position).getUrl());
videoView.setVideoURI(uri);
MediaController mediaController = new MediaController(context);
videoView.setMediaController(mediaController);
mediaController.setAnchorView(videoView);
videoView.requestFocus();
videoView.start();
// Close the progress bar and play the video
videoView.setOnPreparedListener(mp -> progressBar.setVisibility(View.GONE));
videoView.setOnCompletionListener(mp -> videoView.start());
videoView.setOnInfoListener((mp, what, extra) -> {
if (what == MediaPlayer.MEDIA_INFO_BUFFERING_START) {
progressBar.setVisibility(View.VISIBLE);
}else if (what == MediaPlayer.MEDIA_INFO_BUFFERING_END) {
progressBar.setVisibility(View.GONE);
}
return false;
});
videoView.setOnErrorListener((mp, what, extra) -> {
videoView.stopPlayback();
mediaController.hide();
progressBar.setVisibility(View.GONE);
imageLayout.findViewById(R.id.error).setVisibility(View.VISIBLE);
return false;
});
}
view.addView(imageLayout, 0);
return imageLayout;
}
@Override
public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
return view.equals(object);
}
@Override
public void restoreState(Parcelable state, ClassLoader loader) {
}
@Override
public Parcelable saveState() {
return null;
}
}
|
varunswarup0/vehica | src/views/Pages/SignUp/src/screens/Signup.js | <reponame>varunswarup0/vehica
import React, { useState, useEffect } from "react";
import Container from "../components/Container";
import PasswordConfirm from "../components/PasswordConfirm";
import EmailPhoneInput from "../components/EmailPhoneInput";
import PrimaryButton from "../components/PrimaryButton";
import SocialsContainer from "../components/SocialsContainer";
import GoogleButton from "../components/GoogleButton";
import FacebookButton from "../components/FacebookButton";
import AppleButton from "../components/AppleButton";
import FooterLink from "../components/FooterLink";
import "../index.css";
import "../assets/css/webflow.css";
import "../assets/css/normalize.css";
import "../assets/css/coot-login-auth.webflow.css";
import { CCard } from "@coreui/react";
function Signup() {
const [email, setEmail] = useState(null);
const [phone, setPhone] = useState(null);
const [pwdOne, setPwdOne] = useState(null);
const [pwdTwo, setPwdTwo] = useState(null);
const [pwdMatch, setPwdMatch] = useState(null);
useEffect(() => {
if (pwdOne === pwdTwo) {
setPwdMatch(true);
} else {
setPwdMatch(false);
}
}, [pwdOne, pwdTwo]);
return (
<div
style={{
marginTop: "5rem",
backgroundColor: "#ced2d8",
}}
>
<CCard
style={{
backgroundColor: "#ced2d8",
placeItems: "center",
}}
>
<Container label="Sign Up">
<EmailPhoneInput
setEmail={(data) => setEmail(data)}
setPhone={(data) => setPhone(data)}
/>
<PasswordConfirm
setPasswordOne={(data) => setPwdOne(data)}
setPasswordTwo={(data) => setPwdTwo(data)}
/>
<PrimaryButton text="Create An Account" />
<SocialsContainer text="Sign up using Google">
<GoogleButton />
{/* <FacebookButton />
<AppleButton /> */}
</SocialsContainer>
<FooterLink link="/login" text="Already have an account? Log in" />
</Container>
</CCard>
</div>
);
}
export default Signup;
|
ShyamNandanKumar/coding-ninja2 | 3_stl/14_unique_chars.cpp | <filename>3_stl/14_unique_chars.cpp
// Given a string, you need to remove all the duplicates. That means, the output string should contain each character only once. The respective order of characters should remain same.
#include<iostream>
#include<map>
using namespace std;
char* uniqueChar(char *str){
map<char,int> m;
for(int i=0;str[i]!='\0';i++){
m[str[i]]=1;
}
char *ans=new char[m.size()];
int x=0;
for(int i=0;str[i]!='\0';i++){
if(m[str[i]]==1){
ans[x++]=str[i];
m[str[i]]=0;
}
}
return ans;
}
int main() {
char input[1000000];
cin >> input;
cout << uniqueChar(input) << endl;
} |
ErnoW/react-nanodegree-readable | src/utils/api.js | import { schema, normalize } from 'normalizr'
const API_ROOT = 'http://localhost:3001'
const headers = { Authorization: 'RANDOM_TOKEN' }
// Define schemes by using normalizr. see: https://github.com/paularmstrong/normalizr
const postSchema = new schema.Entity(
'posts',
{},
{
idAttribute: 'id',
},
)
const commentSchema = new schema.Entity(
'comments',
{},
{
idAttribute: 'id',
},
)
export const schemas = {
post: postSchema,
postList: [postSchema],
comment: commentSchema,
commentList: [commentSchema],
}
// Generic api calls
const apiGet = (endpoint, schema) => {
return fetch(`${API_ROOT}/${endpoint}`, {
headers,
method: 'GET',
})
.then((response) => {
if (!response.ok) {
throw Error(response.statusText)
}
return response.json()
})
.then((json) => {
if (schema) {
return normalize(json, schema)
}
return json
})
}
const apiPost = (endpoint, schema, body) => {
return fetch(`${API_ROOT}/${endpoint}`, {
headers: {
...headers,
'Content-Type': 'application/json',
},
method: 'POST',
body: JSON.stringify(body),
})
.then((response) => {
if (!response.ok) {
throw Error(response.statusText)
}
return response.json()
})
.then((json) => {
if (schema) {
return normalize(json, schema)
}
return json
})
}
const apiPut = (endpoint, schema, body) => {
return fetch(`${API_ROOT}/${endpoint}`, {
headers: {
...headers,
'Content-Type': 'application/json',
},
method: 'PUT',
body: JSON.stringify(body),
})
.then((response) => {
if (!response.ok) {
throw Error(response.statusText)
}
return response.json()
})
.then((json) => {
if (schema) {
return normalize(json, schema)
}
return json
})
}
const apiDelete = (endpoint) => {
return fetch(`${API_ROOT}/${endpoint}`, {
headers: {
...headers,
'Content-Type': 'application/json',
},
method: 'DELETE',
}).then((response) => {
if (!response.ok) {
throw Error(response.statusText)
}
return response.json()
})
}
// Middleware for api calls
export const callAPIMiddleware = (store: any) => (next: any) => (
action: any,
): Promise<any> => {
const callAPI = action.callAPI
if (typeof callAPI === 'undefined') {
return next(action)
}
const { endpoint, method, schema, types, body } = callAPI
if (typeof endpoint !== 'string') {
throw new Error('Specify a string endpoint URL.')
}
if (
method !== 'GET' &&
method !== 'POST' &&
method !== 'PUT' &&
method !== 'DELETE'
) {
throw new Error('Use a valid request type.')
}
if (!Array.isArray(types) || types.length !== 3) {
throw new Error('Expected an array of three action types.')
}
if (!types.every((type) => typeof type === 'string')) {
throw new Error('Expected action types to be strings.')
}
const actionWith = (data) => {
const finalAction = Object.assign({}, action, data)
delete finalAction.callAPI
return finalAction
}
const [requestType, successType, failureType] = types
next(actionWith({ type: requestType }))
let apicall
if (method === 'GET') {
apicall = apiGet(endpoint, schema)
} else if (method === 'PUT') {
apicall = apiPut(endpoint, schema, body)
} else if (method === 'DELETE') {
apicall = apiDelete(endpoint)
} else {
apicall = apiPost(endpoint, schema, body)
}
return apicall
.then((ms) => new Promise((resolve) => setTimeout(() => resolve(ms), 1000)))
.then(
(response) =>
next(
actionWith({
payload: response,
type: successType,
}),
),
(error) =>
next(
actionWith({
type: failureType,
error: error.message || 'Something bad happened',
}),
),
)
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.