repo_name stringlengths 4 116 | path stringlengths 4 379 | size stringlengths 1 7 | content stringlengths 3 1.05M | license stringclasses 15
values |
|---|---|---|---|---|
bq/jskeleton | lib/htmlbars/dom-helper.amd.js | 46032 | define('dom-helper', ['exports', './htmlbars-runtime/morph', './morph-attr', './dom-helper/build-html-dom', './dom-helper/classes', './dom-helper/prop'], function (exports, Morph, AttrMorph, build_html_dom, classes, prop) {
'use strict';
var doc = typeof document === "undefined" ? false : document;
var deletesBlankTextNodes = doc && (function (document) {
var element = document.createElement("div");
element.appendChild(document.createTextNode(""));
var clonedElement = element.cloneNode(true);
return clonedElement.childNodes.length === 0;
})(doc);
var ignoresCheckedAttribute = doc && (function (document) {
var element = document.createElement("input");
element.setAttribute("checked", "checked");
var clonedElement = element.cloneNode(false);
return !clonedElement.checked;
})(doc);
var canRemoveSvgViewBoxAttribute = doc && (doc.createElementNS ? (function (document) {
var element = document.createElementNS(build_html_dom.svgNamespace, "svg");
element.setAttribute("viewBox", "0 0 100 100");
element.removeAttribute("viewBox");
return !element.getAttribute("viewBox");
})(doc) : true);
var canClone = doc && (function (document) {
var element = document.createElement("div");
element.appendChild(document.createTextNode(" "));
element.appendChild(document.createTextNode(" "));
var clonedElement = element.cloneNode(true);
return clonedElement.childNodes[0].nodeValue === " ";
})(doc);
// This is not the namespace of the element, but of
// the elements inside that elements.
function interiorNamespace(element) {
if (element && element.namespaceURI === build_html_dom.svgNamespace && !build_html_dom.svgHTMLIntegrationPoints[element.tagName]) {
return build_html_dom.svgNamespace;
} else {
return null;
}
}
// The HTML spec allows for "omitted start tags". These tags are optional
// when their intended child is the first thing in the parent tag. For
// example, this is a tbody start tag:
//
// <table>
// <tbody>
// <tr>
//
// The tbody may be omitted, and the browser will accept and render:
//
// <table>
// <tr>
//
// However, the omitted start tag will still be added to the DOM. Here
// we test the string and context to see if the browser is about to
// perform this cleanup.
//
// http://www.whatwg.org/specs/web-apps/current-work/multipage/syntax.html#optional-tags
// describes which tags are omittable. The spec for tbody and colgroup
// explains this behavior:
//
// http://www.whatwg.org/specs/web-apps/current-work/multipage/tables.html#the-tbody-element
// http://www.whatwg.org/specs/web-apps/current-work/multipage/tables.html#the-colgroup-element
//
var omittedStartTagChildTest = /<([\w:]+)/;
function detectOmittedStartTag(string, contextualElement) {
// Omitted start tags are only inside table tags.
if (contextualElement.tagName === "TABLE") {
var omittedStartTagChildMatch = omittedStartTagChildTest.exec(string);
if (omittedStartTagChildMatch) {
var omittedStartTagChild = omittedStartTagChildMatch[1];
// It is already asserted that the contextual element is a table
// and not the proper start tag. Just see if a tag was omitted.
return omittedStartTagChild === "tr" || omittedStartTagChild === "col";
}
}
}
function buildSVGDOM(html, dom) {
var div = dom.document.createElement("div");
div.innerHTML = "<svg>" + html + "</svg>";
return div.firstChild.childNodes;
}
function ElementMorph(element, dom, namespace) {
this.element = element;
this.dom = dom;
this.namespace = namespace;
this.state = {};
this.isDirty = true;
}
/*
* A class wrapping DOM functions to address environment compatibility,
* namespaces, contextual elements for morph un-escaped content
* insertion.
*
* When entering a template, a DOMHelper should be passed:
*
* template(context, { hooks: hooks, dom: new DOMHelper() });
*
* TODO: support foreignObject as a passed contextual element. It has
* a namespace (svg) that does not match its internal namespace
* (xhtml).
*
* @class DOMHelper
* @constructor
* @param {HTMLDocument} _document The document DOM methods are proxied to
*/
function DOMHelper(_document) {
this.document = _document || document;
if (!this.document) {
throw new Error("A document object must be passed to the DOMHelper, or available on the global scope");
}
this.canClone = canClone;
this.namespace = null;
}
var prototype = DOMHelper.prototype;
prototype.constructor = DOMHelper;
prototype.getElementById = function (id, rootNode) {
rootNode = rootNode || this.document;
return rootNode.getElementById(id);
};
prototype.insertBefore = function (element, childElement, referenceChild) {
return element.insertBefore(childElement, referenceChild);
};
prototype.appendChild = function (element, childElement) {
return element.appendChild(childElement);
};
prototype.childAt = function (element, indices) {
var child = element;
for (var i = 0; i < indices.length; i++) {
child = child.childNodes.item(indices[i]);
}
return child;
};
// Note to a Fellow Implementor:
// Ahh, accessing a child node at an index. Seems like it should be so simple,
// doesn't it? Unfortunately, this particular method has caused us a surprising
// amount of pain. As you'll note below, this method has been modified to walk
// the linked list of child nodes rather than access the child by index
// directly, even though there are two (2) APIs in the DOM that do this for us.
// If you're thinking to yourself, "What an oversight! What an opportunity to
// optimize this code!" then to you I say: stop! For I have a tale to tell.
//
// First, this code must be compatible with simple-dom for rendering on the
// server where there is no real DOM. Previously, we accessed a child node
// directly via `element.childNodes[index]`. While we *could* in theory do a
// full-fidelity simulation of a live `childNodes` array, this is slow,
// complicated and error-prone.
//
// "No problem," we thought, "we'll just use the similar
// `childNodes.item(index)` API." Then, we could just implement our own `item`
// method in simple-dom and walk the child node linked list there, allowing
// us to retain the performance advantages of the (surely optimized) `item()`
// API in the browser.
//
// Unfortunately, an enterprising soul named Samy Alzahrani discovered that in
// IE8, accessing an item out-of-bounds via `item()` causes an exception where
// other browsers return null. This necessitated a... check of
// `childNodes.length`, bringing us back around to having to support a
// full-fidelity `childNodes` array!
//
// Worst of all, Kris Selden investigated how browsers are actualy implemented
// and discovered that they're all linked lists under the hood anyway. Accessing
// `childNodes` requires them to allocate a new live collection backed by that
// linked list, which is itself a rather expensive operation. Our assumed
// optimization had backfired! That is the danger of magical thinking about
// the performance of native implementations.
//
// And this, my friends, is why the following implementation just walks the
// linked list, as surprised as that may make you. Please ensure you understand
// the above before changing this and submitting a PR.
//
// Tom Dale, January 18th, 2015, Portland OR
prototype.childAtIndex = function (element, index) {
var node = element.firstChild;
for (var idx = 0; node && idx < index; idx++) {
node = node.nextSibling;
}
return node;
};
prototype.appendText = function (element, text) {
return element.appendChild(this.document.createTextNode(text));
};
prototype.setAttribute = function (element, name, value) {
element.setAttribute(name, String(value));
};
prototype.setAttributeNS = function (element, namespace, name, value) {
element.setAttributeNS(namespace, name, String(value));
};
if (canRemoveSvgViewBoxAttribute) {
prototype.removeAttribute = function (element, name) {
element.removeAttribute(name);
};
} else {
prototype.removeAttribute = function (element, name) {
if (element.tagName === "svg" && name === "viewBox") {
element.setAttribute(name, null);
} else {
element.removeAttribute(name);
}
};
}
prototype.setPropertyStrict = function (element, name, value) {
if (value === undefined) {
value = null;
}
if (value === null && (name === "value" || name === "type" || name === "src")) {
value = "";
}
element[name] = value;
};
prototype.setProperty = function (element, name, value, namespace) {
var lowercaseName = name.toLowerCase();
if (element.namespaceURI === build_html_dom.svgNamespace || lowercaseName === "style") {
if (prop.isAttrRemovalValue(value)) {
element.removeAttribute(name);
} else {
if (namespace) {
element.setAttributeNS(namespace, name, value);
} else {
element.setAttribute(name, value);
}
}
} else {
var normalized = prop.normalizeProperty(element, name);
if (normalized) {
element[normalized] = value;
} else {
if (prop.isAttrRemovalValue(value)) {
element.removeAttribute(name);
} else {
if (namespace && element.setAttributeNS) {
element.setAttributeNS(namespace, name, value);
} else {
element.setAttribute(name, value);
}
}
}
}
};
if (doc && doc.createElementNS) {
// Only opt into namespace detection if a contextualElement
// is passed.
prototype.createElement = function (tagName, contextualElement) {
var namespace = this.namespace;
if (contextualElement) {
if (tagName === "svg") {
namespace = build_html_dom.svgNamespace;
} else {
namespace = interiorNamespace(contextualElement);
}
}
if (namespace) {
return this.document.createElementNS(namespace, tagName);
} else {
return this.document.createElement(tagName);
}
};
prototype.setAttributeNS = function (element, namespace, name, value) {
element.setAttributeNS(namespace, name, String(value));
};
} else {
prototype.createElement = function (tagName) {
return this.document.createElement(tagName);
};
prototype.setAttributeNS = function (element, namespace, name, value) {
element.setAttribute(name, String(value));
};
}
prototype.addClasses = classes.addClasses;
prototype.removeClasses = classes.removeClasses;
prototype.setNamespace = function (ns) {
this.namespace = ns;
};
prototype.detectNamespace = function (element) {
this.namespace = interiorNamespace(element);
};
prototype.createDocumentFragment = function () {
return this.document.createDocumentFragment();
};
prototype.createTextNode = function (text) {
return this.document.createTextNode(text);
};
prototype.createComment = function (text) {
return this.document.createComment(text);
};
prototype.repairClonedNode = function (element, blankChildTextNodes, isChecked) {
if (deletesBlankTextNodes && blankChildTextNodes.length > 0) {
for (var i = 0, len = blankChildTextNodes.length; i < len; i++) {
var textNode = this.document.createTextNode(""),
offset = blankChildTextNodes[i],
before = this.childAtIndex(element, offset);
if (before) {
element.insertBefore(textNode, before);
} else {
element.appendChild(textNode);
}
}
}
if (ignoresCheckedAttribute && isChecked) {
element.setAttribute("checked", "checked");
}
};
prototype.cloneNode = function (element, deep) {
var clone = element.cloneNode(!!deep);
return clone;
};
prototype.AttrMorphClass = AttrMorph['default'];
prototype.createAttrMorph = function (element, attrName, namespace) {
return new this.AttrMorphClass(element, attrName, this, namespace);
};
prototype.ElementMorphClass = ElementMorph;
prototype.createElementMorph = function (element, namespace) {
return new this.ElementMorphClass(element, this, namespace);
};
prototype.createUnsafeAttrMorph = function (element, attrName, namespace) {
var morph = this.createAttrMorph(element, attrName, namespace);
morph.escaped = false;
return morph;
};
prototype.MorphClass = Morph['default'];
prototype.createMorph = function (parent, start, end, contextualElement) {
if (contextualElement && contextualElement.nodeType === 11) {
throw new Error("Cannot pass a fragment as the contextual element to createMorph");
}
if (!contextualElement && parent && parent.nodeType === 1) {
contextualElement = parent;
}
var morph = new this.MorphClass(this, contextualElement);
morph.firstNode = start;
morph.lastNode = end;
return morph;
};
prototype.createFragmentMorph = function (contextualElement) {
if (contextualElement && contextualElement.nodeType === 11) {
throw new Error("Cannot pass a fragment as the contextual element to createMorph");
}
var fragment = this.createDocumentFragment();
return Morph['default'].create(this, contextualElement, fragment);
};
prototype.replaceContentWithMorph = function (element) {
var firstChild = element.firstChild;
if (!firstChild) {
var comment = this.createComment("");
this.appendChild(element, comment);
return Morph['default'].create(this, element, comment);
} else {
var morph = Morph['default'].attach(this, element, firstChild, element.lastChild);
morph.clear();
return morph;
}
};
prototype.createUnsafeMorph = function (parent, start, end, contextualElement) {
var morph = this.createMorph(parent, start, end, contextualElement);
morph.parseTextAsHTML = true;
return morph;
};
// This helper is just to keep the templates good looking,
// passing integers instead of element references.
prototype.createMorphAt = function (parent, startIndex, endIndex, contextualElement) {
var single = startIndex === endIndex;
var start = this.childAtIndex(parent, startIndex);
var end = single ? start : this.childAtIndex(parent, endIndex);
return this.createMorph(parent, start, end, contextualElement);
};
prototype.createUnsafeMorphAt = function (parent, startIndex, endIndex, contextualElement) {
var morph = this.createMorphAt(parent, startIndex, endIndex, contextualElement);
morph.parseTextAsHTML = true;
return morph;
};
prototype.insertMorphBefore = function (element, referenceChild, contextualElement) {
var insertion = this.document.createComment("");
element.insertBefore(insertion, referenceChild);
return this.createMorph(element, insertion, insertion, contextualElement);
};
prototype.appendMorph = function (element, contextualElement) {
var insertion = this.document.createComment("");
element.appendChild(insertion);
return this.createMorph(element, insertion, insertion, contextualElement);
};
prototype.insertBoundary = function (fragment, index) {
// this will always be null or firstChild
var child = index === null ? null : this.childAtIndex(fragment, index);
this.insertBefore(fragment, this.createTextNode(""), child);
};
prototype.parseHTML = function (html, contextualElement) {
var childNodes;
if (interiorNamespace(contextualElement) === build_html_dom.svgNamespace) {
childNodes = buildSVGDOM(html, this);
} else {
var nodes = build_html_dom.buildHTMLDOM(html, contextualElement, this);
if (detectOmittedStartTag(html, contextualElement)) {
var node = nodes[0];
while (node && node.nodeType !== 1) {
node = node.nextSibling;
}
childNodes = node.childNodes;
} else {
childNodes = nodes;
}
}
// Copy node list to a fragment.
var fragment = this.document.createDocumentFragment();
if (childNodes && childNodes.length > 0) {
var currentNode = childNodes[0];
// We prepend an <option> to <select> boxes to absorb any browser bugs
// related to auto-select behavior. Skip past it.
if (contextualElement.tagName === "SELECT") {
currentNode = currentNode.nextSibling;
}
while (currentNode) {
var tempNode = currentNode;
currentNode = currentNode.nextSibling;
fragment.appendChild(tempNode);
}
}
return fragment;
};
var parsingNode;
// Used to determine whether a URL needs to be sanitized.
prototype.protocolForURL = function (url) {
if (!parsingNode) {
parsingNode = this.document.createElement("a");
}
parsingNode.href = url;
return parsingNode.protocol;
};
exports['default'] = DOMHelper;
});
define('dom-helper/build-html-dom', ['exports'], function (exports) {
'use strict';
/* global XMLSerializer:false */
var svgHTMLIntegrationPoints = { foreignObject: 1, desc: 1, title: 1 };
var svgNamespace = 'http://www.w3.org/2000/svg';
var doc = typeof document === 'undefined' ? false : document;
// Safari does not like using innerHTML on SVG HTML integration
// points (desc/title/foreignObject).
var needsIntegrationPointFix = doc && (function (document) {
if (document.createElementNS === undefined) {
return;
}
// In FF title will not accept innerHTML.
var testEl = document.createElementNS(svgNamespace, 'title');
testEl.innerHTML = '<div></div>';
return testEl.childNodes.length === 0 || testEl.childNodes[0].nodeType !== 1;
})(doc);
// Internet Explorer prior to 9 does not allow setting innerHTML if the first element
// is a "zero-scope" element. This problem can be worked around by making
// the first node an invisible text node. We, like Modernizr, use ­
var needsShy = doc && (function (document) {
var testEl = document.createElement('div');
testEl.innerHTML = '<div></div>';
testEl.firstChild.innerHTML = '<script></script>';
return testEl.firstChild.innerHTML === '';
})(doc);
// IE 8 (and likely earlier) likes to move whitespace preceeding
// a script tag to appear after it. This means that we can
// accidentally remove whitespace when updating a morph.
var movesWhitespace = doc && (function (document) {
var testEl = document.createElement('div');
testEl.innerHTML = 'Test: <script type=\'text/x-placeholder\'></script>Value';
return testEl.childNodes[0].nodeValue === 'Test:' && testEl.childNodes[2].nodeValue === ' Value';
})(doc);
var tagNamesRequiringInnerHTMLFix = doc && (function (document) {
var tagNamesRequiringInnerHTMLFix;
// IE 9 and earlier don't allow us to set innerHTML on col, colgroup, frameset,
// html, style, table, tbody, tfoot, thead, title, tr. Detect this and add
// them to an initial list of corrected tags.
//
// Here we are only dealing with the ones which can have child nodes.
//
var tableNeedsInnerHTMLFix;
var tableInnerHTMLTestElement = document.createElement('table');
try {
tableInnerHTMLTestElement.innerHTML = '<tbody></tbody>';
} catch (e) {} finally {
tableNeedsInnerHTMLFix = tableInnerHTMLTestElement.childNodes.length === 0;
}
if (tableNeedsInnerHTMLFix) {
tagNamesRequiringInnerHTMLFix = {
colgroup: ['table'],
table: [],
tbody: ['table'],
tfoot: ['table'],
thead: ['table'],
tr: ['table', 'tbody']
};
}
// IE 8 doesn't allow setting innerHTML on a select tag. Detect this and
// add it to the list of corrected tags.
//
var selectInnerHTMLTestElement = document.createElement('select');
selectInnerHTMLTestElement.innerHTML = '<option></option>';
if (!selectInnerHTMLTestElement.childNodes[0]) {
tagNamesRequiringInnerHTMLFix = tagNamesRequiringInnerHTMLFix || {};
tagNamesRequiringInnerHTMLFix.select = [];
}
return tagNamesRequiringInnerHTMLFix;
})(doc);
function scriptSafeInnerHTML(element, html) {
// without a leading text node, IE will drop a leading script tag.
html = '­' + html;
element.innerHTML = html;
var nodes = element.childNodes;
// Look for ­ to remove it.
var shyElement = nodes[0];
while (shyElement.nodeType === 1 && !shyElement.nodeName) {
shyElement = shyElement.firstChild;
}
// At this point it's the actual unicode character.
if (shyElement.nodeType === 3 && shyElement.nodeValue.charAt(0) === '') {
var newValue = shyElement.nodeValue.slice(1);
if (newValue.length) {
shyElement.nodeValue = shyElement.nodeValue.slice(1);
} else {
shyElement.parentNode.removeChild(shyElement);
}
}
return nodes;
}
function buildDOMWithFix(html, contextualElement) {
var tagName = contextualElement.tagName;
// Firefox versions < 11 do not have support for element.outerHTML.
var outerHTML = contextualElement.outerHTML || new XMLSerializer().serializeToString(contextualElement);
if (!outerHTML) {
throw 'Can\'t set innerHTML on ' + tagName + ' in this browser';
}
html = fixSelect(html, contextualElement);
var wrappingTags = tagNamesRequiringInnerHTMLFix[tagName.toLowerCase()];
var startTag = outerHTML.match(new RegExp('<' + tagName + '([^>]*)>', 'i'))[0];
var endTag = '</' + tagName + '>';
var wrappedHTML = [startTag, html, endTag];
var i = wrappingTags.length;
var wrappedDepth = 1 + i;
while (i--) {
wrappedHTML.unshift('<' + wrappingTags[i] + '>');
wrappedHTML.push('</' + wrappingTags[i] + '>');
}
var wrapper = document.createElement('div');
scriptSafeInnerHTML(wrapper, wrappedHTML.join(''));
var element = wrapper;
while (wrappedDepth--) {
element = element.firstChild;
while (element && element.nodeType !== 1) {
element = element.nextSibling;
}
}
while (element && element.tagName !== tagName) {
element = element.nextSibling;
}
return element ? element.childNodes : [];
}
var buildDOM;
if (needsShy) {
buildDOM = function buildDOM(html, contextualElement, dom) {
html = fixSelect(html, contextualElement);
contextualElement = dom.cloneNode(contextualElement, false);
scriptSafeInnerHTML(contextualElement, html);
return contextualElement.childNodes;
};
} else {
buildDOM = function buildDOM(html, contextualElement, dom) {
html = fixSelect(html, contextualElement);
contextualElement = dom.cloneNode(contextualElement, false);
contextualElement.innerHTML = html;
return contextualElement.childNodes;
};
}
function fixSelect(html, contextualElement) {
if (contextualElement.tagName === 'SELECT') {
html = '<option></option>' + html;
}
return html;
}
var buildIESafeDOM;
if (tagNamesRequiringInnerHTMLFix || movesWhitespace) {
buildIESafeDOM = function buildIESafeDOM(html, contextualElement, dom) {
// Make a list of the leading text on script nodes. Include
// script tags without any whitespace for easier processing later.
var spacesBefore = [];
var spacesAfter = [];
if (typeof html === 'string') {
html = html.replace(/(\s*)(<script)/g, function (match, spaces, tag) {
spacesBefore.push(spaces);
return tag;
});
html = html.replace(/(<\/script>)(\s*)/g, function (match, tag, spaces) {
spacesAfter.push(spaces);
return tag;
});
}
// Fetch nodes
var nodes;
if (tagNamesRequiringInnerHTMLFix[contextualElement.tagName.toLowerCase()]) {
// buildDOMWithFix uses string wrappers for problematic innerHTML.
nodes = buildDOMWithFix(html, contextualElement);
} else {
nodes = buildDOM(html, contextualElement, dom);
}
// Build a list of script tags, the nodes themselves will be
// mutated as we add test nodes.
var i, j, node, nodeScriptNodes;
var scriptNodes = [];
for (i = 0; i < nodes.length; i++) {
node = nodes[i];
if (node.nodeType !== 1) {
continue;
}
if (node.tagName === 'SCRIPT') {
scriptNodes.push(node);
} else {
nodeScriptNodes = node.getElementsByTagName('script');
for (j = 0; j < nodeScriptNodes.length; j++) {
scriptNodes.push(nodeScriptNodes[j]);
}
}
}
// Walk the script tags and put back their leading text nodes.
var scriptNode, textNode, spaceBefore, spaceAfter;
for (i = 0; i < scriptNodes.length; i++) {
scriptNode = scriptNodes[i];
spaceBefore = spacesBefore[i];
if (spaceBefore && spaceBefore.length > 0) {
textNode = dom.document.createTextNode(spaceBefore);
scriptNode.parentNode.insertBefore(textNode, scriptNode);
}
spaceAfter = spacesAfter[i];
if (spaceAfter && spaceAfter.length > 0) {
textNode = dom.document.createTextNode(spaceAfter);
scriptNode.parentNode.insertBefore(textNode, scriptNode.nextSibling);
}
}
return nodes;
};
} else {
buildIESafeDOM = buildDOM;
}
var buildHTMLDOM;
if (needsIntegrationPointFix) {
buildHTMLDOM = function buildHTMLDOM(html, contextualElement, dom) {
if (svgHTMLIntegrationPoints[contextualElement.tagName]) {
return buildIESafeDOM(html, document.createElement('div'), dom);
} else {
return buildIESafeDOM(html, contextualElement, dom);
}
};
} else {
buildHTMLDOM = buildIESafeDOM;
}
exports.svgHTMLIntegrationPoints = svgHTMLIntegrationPoints;
exports.svgNamespace = svgNamespace;
exports.buildHTMLDOM = buildHTMLDOM;
});
define('dom-helper/classes', ['exports'], function (exports) {
'use strict';
var doc = typeof document === 'undefined' ? false : document;
// PhantomJS has a broken classList. See https://github.com/ariya/phantomjs/issues/12782
var canClassList = doc && (function () {
var d = document.createElement('div');
if (!d.classList) {
return false;
}
d.classList.add('boo');
d.classList.add('boo', 'baz');
return d.className === 'boo baz';
})();
function buildClassList(element) {
var classString = element.getAttribute('class') || '';
return classString !== '' && classString !== ' ' ? classString.split(' ') : [];
}
function intersect(containingArray, valuesArray) {
var containingIndex = 0;
var containingLength = containingArray.length;
var valuesIndex = 0;
var valuesLength = valuesArray.length;
var intersection = new Array(valuesLength);
// TODO: rewrite this loop in an optimal manner
for (; containingIndex < containingLength; containingIndex++) {
valuesIndex = 0;
for (; valuesIndex < valuesLength; valuesIndex++) {
if (valuesArray[valuesIndex] === containingArray[containingIndex]) {
intersection[valuesIndex] = containingIndex;
break;
}
}
}
return intersection;
}
function addClassesViaAttribute(element, classNames) {
var existingClasses = buildClassList(element);
var indexes = intersect(existingClasses, classNames);
var didChange = false;
for (var i = 0, l = classNames.length; i < l; i++) {
if (indexes[i] === undefined) {
didChange = true;
existingClasses.push(classNames[i]);
}
}
if (didChange) {
element.setAttribute('class', existingClasses.length > 0 ? existingClasses.join(' ') : '');
}
}
function removeClassesViaAttribute(element, classNames) {
var existingClasses = buildClassList(element);
var indexes = intersect(classNames, existingClasses);
var didChange = false;
var newClasses = [];
for (var i = 0, l = existingClasses.length; i < l; i++) {
if (indexes[i] === undefined) {
newClasses.push(existingClasses[i]);
} else {
didChange = true;
}
}
if (didChange) {
element.setAttribute('class', newClasses.length > 0 ? newClasses.join(' ') : '');
}
}
var addClasses, removeClasses;
if (canClassList) {
addClasses = function addClasses(element, classNames) {
if (element.classList) {
if (classNames.length === 1) {
element.classList.add(classNames[0]);
} else if (classNames.length === 2) {
element.classList.add(classNames[0], classNames[1]);
} else {
element.classList.add.apply(element.classList, classNames);
}
} else {
addClassesViaAttribute(element, classNames);
}
};
removeClasses = function removeClasses(element, classNames) {
if (element.classList) {
if (classNames.length === 1) {
element.classList.remove(classNames[0]);
} else if (classNames.length === 2) {
element.classList.remove(classNames[0], classNames[1]);
} else {
element.classList.remove.apply(element.classList, classNames);
}
} else {
removeClassesViaAttribute(element, classNames);
}
};
} else {
addClasses = addClassesViaAttribute;
removeClasses = removeClassesViaAttribute;
}
exports.addClasses = addClasses;
exports.removeClasses = removeClasses;
});
define('dom-helper/prop', ['exports'], function (exports) {
'use strict';
exports.isAttrRemovalValue = isAttrRemovalValue;
exports.normalizeProperty = normalizeProperty;
function isAttrRemovalValue(value) {
return value === null || value === undefined;
}
// TODO should this be an o_create kind of thing?
var propertyCaches = {};function normalizeProperty(element, attrName) {
var tagName = element.tagName;
var key;
var cache = propertyCaches[tagName];
if (!cache) {
// TODO should this be an o_create kind of thing?
cache = {};
for (key in element) {
cache[key.toLowerCase()] = key;
}
propertyCaches[tagName] = cache;
}
// presumes that the attrName has been lowercased.
return cache[attrName];
}
exports.propertyCaches = propertyCaches;
});
define('morph-attr', ['exports', './morph-attr/sanitize-attribute-value', './dom-helper/prop', './dom-helper/build-html-dom', './htmlbars-util'], function (exports, sanitize_attribute_value, prop, build_html_dom, htmlbars_util) {
'use strict';
function updateProperty(value) {
if (this._renderedInitially === true || !prop.isAttrRemovalValue(value)) {
// do not render if initial value is undefined or null
this.domHelper.setPropertyStrict(this.element, this.attrName, value);
}
this._renderedInitially = true;
}
function updateAttribute(value) {
if (prop.isAttrRemovalValue(value)) {
this.domHelper.removeAttribute(this.element, this.attrName);
} else {
this.domHelper.setAttribute(this.element, this.attrName, value);
}
}
function updateAttributeNS(value) {
if (prop.isAttrRemovalValue(value)) {
this.domHelper.removeAttribute(this.element, this.attrName);
} else {
this.domHelper.setAttributeNS(this.element, this.namespace, this.attrName, value);
}
}
function AttrMorph(element, attrName, domHelper, namespace) {
this.element = element;
this.domHelper = domHelper;
this.namespace = namespace !== undefined ? namespace : htmlbars_util.getAttrNamespace(attrName);
this.state = {};
this.isDirty = false;
this.escaped = true;
this.lastValue = null;
this.linkedParams = null;
this.rendered = false;
this._renderedInitially = false;
var normalizedAttrName = prop.normalizeProperty(this.element, attrName);
if (this.namespace) {
this._update = updateAttributeNS;
this.attrName = attrName;
} else {
if (element.namespaceURI === build_html_dom.svgNamespace || attrName === "style" || !normalizedAttrName) {
this.attrName = attrName;
this._update = updateAttribute;
} else {
this.attrName = normalizedAttrName;
this._update = updateProperty;
}
}
}
AttrMorph.prototype.setContent = function (value) {
if (this.escaped) {
var sanitized = sanitize_attribute_value.sanitizeAttributeValue(this.domHelper, this.element, this.attrName, value);
this._update(sanitized, this.namespace);
} else {
this._update(value, this.namespace);
}
};
exports['default'] = AttrMorph;
exports.sanitizeAttributeValue = sanitize_attribute_value.sanitizeAttributeValue;
});
define('morph-attr/sanitize-attribute-value', ['exports'], function (exports) {
'use strict';
exports.sanitizeAttributeValue = sanitizeAttributeValue;
var badProtocols = {
'javascript:': true,
'vbscript:': true
};
var badTags = {
'A': true,
'BODY': true,
'LINK': true,
'IMG': true,
'IFRAME': true,
'BASE': true
};
var badTagsForDataURI = {
'EMBED': true
};
var badAttributes = {
'href': true,
'src': true,
'background': true
};
var badAttributesForDataURI = {
'src': true
};
function sanitizeAttributeValue(dom, element, attribute, value) {
var tagName;
if (!element) {
tagName = null;
} else {
tagName = element.tagName.toUpperCase();
}
if (value && value.toHTML) {
return value.toHTML();
}
if ((tagName === null || badTags[tagName]) && badAttributes[attribute]) {
var protocol = dom.protocolForURL(value);
if (badProtocols[protocol] === true) {
return 'unsafe:' + value;
}
}
if (badTagsForDataURI[tagName] && badAttributesForDataURI[attribute]) {
return 'unsafe:' + value;
}
return value;
}
exports.badAttributes = badAttributes;
});
define('morph-range', ['exports', './morph-range/utils'], function (exports, utils) {
'use strict';
function Morph(domHelper, contextualElement) {
this.domHelper = domHelper;
// context if content if current content is detached
this.contextualElement = contextualElement;
// inclusive range of morph
// these should be nodeType 1, 3, or 8
this.firstNode = null;
this.lastNode = null;
// flag to force text to setContent to be treated as html
this.parseTextAsHTML = false;
// morph list graph
this.parentMorphList = null;
this.previousMorph = null;
this.nextMorph = null;
}
Morph.empty = function (domHelper, contextualElement) {
var morph = new Morph(domHelper, contextualElement);
morph.clear();
return morph;
};
Morph.create = function (domHelper, contextualElement, node) {
var morph = new Morph(domHelper, contextualElement);
morph.setNode(node);
return morph;
};
Morph.attach = function (domHelper, contextualElement, firstNode, lastNode) {
var morph = new Morph(domHelper, contextualElement);
morph.setRange(firstNode, lastNode);
return morph;
};
Morph.prototype.setContent = function Morph$setContent(content) {
if (content === null || content === undefined) {
return this.clear();
}
var type = typeof content;
switch (type) {
case 'string':
if (this.parseTextAsHTML) {
return this.setHTML(content);
}
return this.setText(content);
case 'object':
if (typeof content.nodeType === 'number') {
return this.setNode(content);
}
/* Handlebars.SafeString */
if (typeof content.string === 'string') {
return this.setHTML(content.string);
}
if (this.parseTextAsHTML) {
return this.setHTML(content.toString());
}
/* falls through */
case 'boolean':
case 'number':
return this.setText(content.toString());
default:
throw new TypeError('unsupported content');
}
};
Morph.prototype.clear = function Morph$clear() {
var node = this.setNode(this.domHelper.createComment(''));
return node;
};
Morph.prototype.setText = function Morph$setText(text) {
var firstNode = this.firstNode;
var lastNode = this.lastNode;
if (firstNode && lastNode === firstNode && firstNode.nodeType === 3) {
firstNode.nodeValue = text;
return firstNode;
}
return this.setNode(text ? this.domHelper.createTextNode(text) : this.domHelper.createComment(''));
};
Morph.prototype.setNode = function Morph$setNode(newNode) {
var firstNode, lastNode;
switch (newNode.nodeType) {
case 3:
firstNode = newNode;
lastNode = newNode;
break;
case 11:
firstNode = newNode.firstChild;
lastNode = newNode.lastChild;
if (firstNode === null) {
firstNode = this.domHelper.createComment('');
newNode.appendChild(firstNode);
lastNode = firstNode;
}
break;
default:
firstNode = newNode;
lastNode = newNode;
break;
}
this.setRange(firstNode, lastNode);
return newNode;
};
Morph.prototype.setRange = function (firstNode, lastNode) {
var previousFirstNode = this.firstNode;
if (previousFirstNode !== null) {
var parentNode = previousFirstNode.parentNode;
if (parentNode !== null) {
utils.insertBefore(parentNode, firstNode, lastNode, previousFirstNode);
utils.clear(parentNode, previousFirstNode, this.lastNode);
}
}
this.firstNode = firstNode;
this.lastNode = lastNode;
if (this.parentMorphList) {
this._syncFirstNode();
this._syncLastNode();
}
};
Morph.prototype.destroy = function Morph$destroy() {
this.unlink();
var firstNode = this.firstNode;
var lastNode = this.lastNode;
var parentNode = firstNode && firstNode.parentNode;
this.firstNode = null;
this.lastNode = null;
utils.clear(parentNode, firstNode, lastNode);
};
Morph.prototype.unlink = function Morph$unlink() {
var parentMorphList = this.parentMorphList;
var previousMorph = this.previousMorph;
var nextMorph = this.nextMorph;
if (previousMorph) {
if (nextMorph) {
previousMorph.nextMorph = nextMorph;
nextMorph.previousMorph = previousMorph;
} else {
previousMorph.nextMorph = null;
parentMorphList.lastChildMorph = previousMorph;
}
} else {
if (nextMorph) {
nextMorph.previousMorph = null;
parentMorphList.firstChildMorph = nextMorph;
} else if (parentMorphList) {
parentMorphList.lastChildMorph = parentMorphList.firstChildMorph = null;
}
}
this.parentMorphList = null;
this.nextMorph = null;
this.previousMorph = null;
if (parentMorphList && parentMorphList.mountedMorph) {
if (!parentMorphList.firstChildMorph) {
// list is empty
parentMorphList.mountedMorph.clear();
return;
} else {
parentMorphList.firstChildMorph._syncFirstNode();
parentMorphList.lastChildMorph._syncLastNode();
}
}
};
Morph.prototype.setHTML = function (text) {
var fragment = this.domHelper.parseHTML(text, this.contextualElement);
return this.setNode(fragment);
};
Morph.prototype.setMorphList = function Morph$appendMorphList(morphList) {
morphList.mountedMorph = this;
this.clear();
var originalFirstNode = this.firstNode;
if (morphList.firstChildMorph) {
this.firstNode = morphList.firstChildMorph.firstNode;
this.lastNode = morphList.lastChildMorph.lastNode;
var current = morphList.firstChildMorph;
while (current) {
var next = current.nextMorph;
current.insertBeforeNode(originalFirstNode, null);
current = next;
}
originalFirstNode.parentNode.removeChild(originalFirstNode);
}
};
Morph.prototype._syncFirstNode = function Morph$syncFirstNode() {
var morph = this;
var parentMorphList;
while (parentMorphList = morph.parentMorphList) {
if (parentMorphList.mountedMorph === null) {
break;
}
if (morph !== parentMorphList.firstChildMorph) {
break;
}
if (morph.firstNode === parentMorphList.mountedMorph.firstNode) {
break;
}
parentMorphList.mountedMorph.firstNode = morph.firstNode;
morph = parentMorphList.mountedMorph;
}
};
Morph.prototype._syncLastNode = function Morph$syncLastNode() {
var morph = this;
var parentMorphList;
while (parentMorphList = morph.parentMorphList) {
if (parentMorphList.mountedMorph === null) {
break;
}
if (morph !== parentMorphList.lastChildMorph) {
break;
}
if (morph.lastNode === parentMorphList.mountedMorph.lastNode) {
break;
}
parentMorphList.mountedMorph.lastNode = morph.lastNode;
morph = parentMorphList.mountedMorph;
}
};
Morph.prototype.insertBeforeNode = function Morph$insertBeforeNode(parent, reference) {
var current = this.firstNode;
while (current) {
var next = current.nextSibling;
parent.insertBefore(current, reference);
current = next;
}
};
Morph.prototype.appendToNode = function Morph$appendToNode(parent) {
this.insertBeforeNode(parent, null);
};
exports['default'] = Morph;
});
define('morph-range.umd', ['./morph-range'], function (Morph) {
'use strict';
(function (root, factory) {
if (typeof define === 'function' && define.amd) {
define([], factory);
} else if (typeof exports === 'object') {
module.exports = factory();
} else {
root.Morph = factory();
}
})(undefined, function () {
return Morph['default'];
});
});
define('morph-range/morph-list', ['exports', './utils'], function (exports, utils) {
'use strict';
function MorphList() {
// morph graph
this.firstChildMorph = null;
this.lastChildMorph = null;
this.mountedMorph = null;
}
var prototype = MorphList.prototype;
prototype.clear = function MorphList$clear() {
var current = this.firstChildMorph;
while (current) {
var next = current.nextMorph;
current.previousMorph = null;
current.nextMorph = null;
current.parentMorphList = null;
current = next;
}
this.firstChildMorph = this.lastChildMorph = null;
};
prototype.destroy = function MorphList$destroy() {};
prototype.appendMorph = function MorphList$appendMorph(morph) {
this.insertBeforeMorph(morph, null);
};
prototype.insertBeforeMorph = function MorphList$insertBeforeMorph(morph, referenceMorph) {
if (morph.parentMorphList !== null) {
morph.unlink();
}
if (referenceMorph && referenceMorph.parentMorphList !== this) {
throw new Error('The morph before which the new morph is to be inserted is not a child of this morph.');
}
var mountedMorph = this.mountedMorph;
if (mountedMorph) {
var parentNode = mountedMorph.firstNode.parentNode;
var referenceNode = referenceMorph ? referenceMorph.firstNode : mountedMorph.lastNode.nextSibling;
utils.insertBefore(parentNode, morph.firstNode, morph.lastNode, referenceNode);
// was not in list mode replace current content
if (!this.firstChildMorph) {
utils.clear(this.mountedMorph.firstNode.parentNode, this.mountedMorph.firstNode, this.mountedMorph.lastNode);
}
}
morph.parentMorphList = this;
var previousMorph = referenceMorph ? referenceMorph.previousMorph : this.lastChildMorph;
if (previousMorph) {
previousMorph.nextMorph = morph;
morph.previousMorph = previousMorph;
} else {
this.firstChildMorph = morph;
}
if (referenceMorph) {
referenceMorph.previousMorph = morph;
morph.nextMorph = referenceMorph;
} else {
this.lastChildMorph = morph;
}
this.firstChildMorph._syncFirstNode();
this.lastChildMorph._syncLastNode();
};
prototype.removeChildMorph = function MorphList$removeChildMorph(morph) {
if (morph.parentMorphList !== this) {
throw new Error('Cannot remove a morph from a parent it is not inside of');
}
morph.destroy();
};
exports['default'] = MorphList;
});
define('morph-range/morph-list.umd', ['./morph-list'], function (MorphList) {
'use strict';
(function (root, factory) {
if (typeof define === 'function' && define.amd) {
define([], factory);
} else if (typeof exports === 'object') {
module.exports = factory();
} else {
root.MorphList = factory();
}
})(undefined, function () {
return MorphList['default'];
});
});
define('morph-range/utils', ['exports'], function (exports) {
'use strict';
exports.clear = clear;
exports.insertBefore = insertBefore;
// inclusive of both nodes
function clear(parentNode, firstNode, lastNode) {
if (!parentNode) {
return;
}
var node = firstNode;
var nextNode;
do {
nextNode = node.nextSibling;
parentNode.removeChild(node);
if (node === lastNode) {
break;
}
node = nextNode;
} while (node);
}
function insertBefore(parentNode, firstNode, lastNode, _refNode) {
var node = lastNode;
var refNode = _refNode;
var prevNode;
do {
prevNode = node.previousSibling;
parentNode.insertBefore(node, refNode);
if (node === firstNode) {
break;
}
refNode = node;
node = prevNode;
} while (node);
}
}); | apache-2.0 |
nextreports/nextreports-server | src/ro/nextreports/server/search/SqlSearchEntry.java | 1811 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 ro.nextreports.server.search;
import org.apache.wicket.model.StringResourceModel;
public class SqlSearchEntry extends SearchEntry {
private String text;
private boolean ignoredCase;
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public boolean isIgnoredCase() {
return ignoredCase;
}
public void setIgnoredCase(boolean ignoredCase) {
this.ignoredCase = ignoredCase;
}
public String getMessage() {
StringBuilder sb = new StringBuilder();
sb.append("* sql ");
if (ignoredCase) {
sb.append("(").append(new StringResourceModel("ActionContributor.Search.entry.ignoreCase", null).getString()).append(") ");
}
sb.append(new StringResourceModel("ActionContributor.Search.entry.contains", null).getString());
sb.append(" '");
sb.append(text);
sb.append("'");
return sb.toString();
}
}
| apache-2.0 |
aulizko/soy-to-java-src-compiler-o-matic | src/test/java/com/ulizko/template/soy/javaSrc/SoyFileStockTest.java | 1208 | package com.ulizko.template.soy.javaSrc;
import com.ulizko.template.soy.utils.FileUtils;
import com.google.common.base.Joiner;
import com.google.common.base.Splitter;
import com.google.common.collect.ImmutableList;
import org.junit.Test;
import java.io.File;
import java.util.List;
import static org.junit.Assert.assertEquals;
/**
* @author Alexander <alexander@ulizko.com> Ulizko
*/
public class SoyFileStockTest {
@Test
public void testMultipleAdd() {
File soyFile = new File(getClass().getClassLoader().getResource("page.soy").getPath());
ImmutableList<String> soyFileAbsolutePathChunks =
ImmutableList.copyOf(Splitter.on(File.separatorChar).split(soyFile.getAbsolutePath()));
File resourceDirectory = new File(Joiner.on(File.separator).join(soyFileAbsolutePathChunks.subList(0,
soyFileAbsolutePathChunks.size() - 1)));
List<String> paths = FileUtils.retreiveSoyFilePathsFromDirectory(resourceDirectory);
SoyFileStock soyFileStock = new SoyFileStock(paths);
soyFileStock.checkFiles();
List<String> soyFiles = soyFileStock.getFileNames();
assertEquals(3, soyFiles.size());
}
}
| apache-2.0 |
LQJJ/demo | 126-go-common-master/app/admin/main/cache/model/tree.go | 916 | package model
import "time"
// Res res.
type Res struct {
Count int `json:"count"`
Data []*TreeNode `json:"data"`
Page int `json:"page"`
Results int `json:"results"`
}
// TreeNode TreeNode.
type TreeNode struct {
Alias string `json:"alias"`
CreatedAt string `json:"created_at"`
Name string `json:"name"`
Path string `json:"path"`
Tags interface{} `json:"tags"`
Type int `json:"type"`
}
// Node node.
type Node struct {
Name string `json:"name"`
Path string `json:"path"`
TreeID int64 `json:"tree_id"`
}
//CacheData ...
type CacheData struct {
Data map[int64]*RoleNode `json:"data"`
CTime time.Time `json:"ctime"`
}
//RoleNode roleNode .
type RoleNode struct {
ID int64 `json:"id"`
Name string `json:"name"`
Path string `json:"path"`
Type int8 `json:"type"`
Role int8 `json:"role"`
}
| apache-2.0 |
dockerian/pyapi | demo/codebase/swift.py | 5234 | """
# swift
"""
import logging
import mimetypes
import sys
from swiftclient import client as swift_client
LOGGER = logging.getLogger(__name__)
class Swift():
def __init__(self, auth_token, swift_url, container_name):
"""
Initialize a Swift instance
"""
self.auth_token = auth_token
self.swift_url = swift_url
self.container = container_name
self.connection = self.get_connection()
def get_connection(self):
"""
Get a connection to Swift
"""
try:
return swift_client.Connection(
preauthurl=self.swift_url,
preauthtoken=self.auth_token,
retries=5,
auth_version='1',
insecure=True)
except Exception as e:
err_message = "Exception raised initiating a swift connection."
LOGGER.exception(err_message)
raise
def check_container(self):
"""
Determine if default container exists in Swift
"""
try:
LOGGER.debug('Checking container {0}'.format(self.container))
headers, container_list = self.connection.get_account()
for container in container_list:
if container['name'] == self.container:
return True
return False
except Exception as e:
err_message = "Exception raised on checking container exists."
LOGGER.exception(err_message)
raise
def check_file_exists(self, file_name):
if (not self.check_container()):
return False
files = self.get_files_in_container()
for file in files:
if (file['name'] == file_name):
return True
return False
def check_package_exists(self, package_name):
file_name = '{0}.tar.gz'.format(package_name)
return self.check_file_exists(file_name)
def ensure_container_exists(self):
"""
Ensure default container exists in Swift.
"""
# Determine if necessary container missing; if so, create it
container_exists = self.check_container()
if (not container_exists):
try:
response = {}
self.connection.put_container(
self.container, response_dict=response)
LOGGER.debug(
"--- Container {0} created".format(self.container))
LOGGER.debug("--- Response {0}".format(response))
except Exception as e:
err = "Exception on creating container {0}.".format(
self.container)
LOGGER.exception(err)
raise
def get_deployment_list(self):
deployment_list = []
result = self.connection.get_files_in_container()
regex = re.compile('^deployment_(.+).json$')
for file in result:
filename = file['name']
re_match = regex.search(filename)
add_flag = \
file['content_type'] == 'application/json' and \
re_match is not None
if (add_flag):
try:
file_contents = self.get_file_contents(filename)
item = json.loads(file_contents)
deployment_list.append(item)
except Exception:
continue
return deployment_list
def get_file_contents(self, file_name):
"""
Function wrapper to perform 'get_object' call on Swift
"""
try:
response_dict = {}
# Response from Swift:
# a tuple of (response headers, the object contents)
# The response headers will be a dict and all header names
# will be lowercase.
response = self.connection.get_object(
self.container,
file_name,
response_dict=response_dict)
file_contents = response[1]
return file_contents
except Exception as e:
err = "Exception on getting {0} from Swift.".format(file_name)
LOGGER.exception(err)
raise
def get_files_in_container(self):
result = self.connection.get_container(
self.container, full_listing=True)
return result[1]
def save_file_contents(self, file_name, file_contents):
"""
Function wrapper to perform 'put_object' call Swift
"""
try:
# Ensure the container we need exists
self.ensure_container_exists()
# Push the file contents to Swift
response = {}
self.connection.put_object(
self.container,
file_name,
file_contents,
content_length=sys.getsizeof(file_contents),
content_type=mimetypes.guess_type(file_name, strict=True)[0],
response_dict=response)
return response
except Exception as e:
err = "Exception on trying to save file contents to Swift.\n"
LOGGER.exception(err)
raise
| apache-2.0 |
Hersir88/Babylon.js | src/Materials/babylon.material.ts | 43291 | module BABYLON {
/**
* Manages the defines for the Material.
*/
export class MaterialDefines {
private _keys: string[];
private _isDirty = true;
public _renderId: number;
public _areLightsDirty = true;
public _areAttributesDirty = true;
public _areTexturesDirty = true;
public _areFresnelDirty = true;
public _areMiscDirty = true;
public _areImageProcessingDirty = true;
public _normals = false;
public _uvs = false;
public _needNormals = false;
public _needUVs = false;
/**
* Specifies if the material needs to be re-calculated.
*/
public get isDirty(): boolean {
return this._isDirty;
}
/**
* Marks the material to indicate that it has been re-calculated.
*/
public markAsProcessed() {
this._isDirty = false;
this._areAttributesDirty = false;
this._areTexturesDirty = false;
this._areFresnelDirty = false;
this._areLightsDirty = false;
this._areMiscDirty = false;
this._areImageProcessingDirty = false;
}
/**
* Marks the material to indicate that it needs to be re-calculated.
*/
public markAsUnprocessed() {
this._isDirty = true;
}
/**
* Marks the material to indicate all of its defines need to be re-calculated.
*/
public markAllAsDirty() {
this._areTexturesDirty = true;
this._areAttributesDirty = true;
this._areLightsDirty = true;
this._areFresnelDirty = true;
this._areMiscDirty = true;
this._areImageProcessingDirty = true;
this._isDirty = true;
}
/**
* Marks the material to indicate that image processing needs to be re-calculated.
*/
public markAsImageProcessingDirty() {
this._areImageProcessingDirty = true;
this._isDirty = true;
}
/**
* Marks the material to indicate the lights need to be re-calculated.
*/
public markAsLightDirty() {
this._areLightsDirty = true;
this._isDirty = true;
}
/**
* Marks the attribute state as changed.
*/
public markAsAttributesDirty() {
this._areAttributesDirty = true;
this._isDirty = true;
}
/**
* Marks the texture state as changed.
*/
public markAsTexturesDirty() {
this._areTexturesDirty = true;
this._isDirty = true;
}
/**
* Marks the fresnel state as changed.
*/
public markAsFresnelDirty() {
this._areFresnelDirty = true;
this._isDirty = true;
}
/**
* Marks the misc state as changed.
*/
public markAsMiscDirty() {
this._areMiscDirty = true;
this._isDirty = true;
}
/**
* Rebuilds the material defines.
*/
public rebuild() {
if (this._keys) {
delete this._keys;
}
this._keys = [];
for (var key of Object.keys(this)) {
if (key[0] === "_") {
continue;
}
this._keys.push(key);
}
}
/**
* Specifies if two material defines are equal.
* @param other - A material define instance to compare to.
* @returns - Boolean indicating if the material defines are equal (true) or not (false).
*/
public isEqual(other: MaterialDefines): boolean {
if (this._keys.length !== other._keys.length) {
return false;
}
for (var index = 0; index < this._keys.length; index++) {
var prop = this._keys[index];
if ((<any>this)[prop] !== (<any>other)[prop]) {
return false;
}
}
return true;
}
/**
* Clones this instance's defines to another instance.
* @param other - material defines to clone values to.
*/
public cloneTo(other: MaterialDefines): void {
if (this._keys.length !== other._keys.length) {
other._keys = this._keys.slice(0);
}
for (var index = 0; index < this._keys.length; index++) {
var prop = this._keys[index];
(<any>other)[prop] = (<any>this)[prop];
}
}
/**
* Resets the material define values.
*/
public reset(): void {
for (var index = 0; index < this._keys.length; index++) {
var prop = this._keys[index];
var type = typeof (<any>this)[prop];
switch (type) {
case "number":
(<any>this)[prop] = 0;
break;
case "string":
(<any>this)[prop] = "";
break;
default:
(<any>this)[prop] = false;
break;
}
}
}
/**
* Converts the material define values to a string.
* @returns - String of material define information.
*/
public toString(): string {
var result = "";
for (var index = 0; index < this._keys.length; index++) {
var prop = this._keys[index];
var value = (<any>this)[prop];
var type = typeof value;
switch (type) {
case "number":
case "string":
result += "#define " + prop + " " + value + "\n";
break;
default:
if (value) {
result += "#define " + prop + "\n";
}
break;
}
}
return result;
}
}
/**
* This offers the main features of a material in BJS.
*/
export class Material implements IAnimatable {
// Triangle views
private static _TriangleFillMode = 0;
private static _WireFrameFillMode = 1;
private static _PointFillMode = 2;
// Draw modes
private static _PointListDrawMode = 3;
private static _LineListDrawMode = 4;
private static _LineLoopDrawMode = 5;
private static _LineStripDrawMode = 6;
private static _TriangleStripDrawMode = 7;
private static _TriangleFanDrawMode = 8;
/**
* Returns the triangle fill mode.
*/
public static get TriangleFillMode(): number {
return Material._TriangleFillMode;
}
/**
* Returns the wireframe mode.
*/
public static get WireFrameFillMode(): number {
return Material._WireFrameFillMode;
}
/**
* Returns the point fill mode.
*/
public static get PointFillMode(): number {
return Material._PointFillMode;
}
/**
* Returns the point list draw mode.
*/
public static get PointListDrawMode(): number {
return Material._PointListDrawMode;
}
/**
* Returns the line list draw mode.
*/
public static get LineListDrawMode(): number {
return Material._LineListDrawMode;
}
/**
* Returns the line loop draw mode.
*/
public static get LineLoopDrawMode(): number {
return Material._LineLoopDrawMode;
}
/**
* Returns the line strip draw mode.
*/
public static get LineStripDrawMode(): number {
return Material._LineStripDrawMode;
}
/**
* Returns the triangle strip draw mode.
*/
public static get TriangleStripDrawMode(): number {
return Material._TriangleStripDrawMode;
}
/**
* Returns the triangle fan draw mode.
*/
public static get TriangleFanDrawMode(): number {
return Material._TriangleFanDrawMode;
}
/**
* Stores the clock-wise side orientation.
*/
private static _ClockWiseSideOrientation = 0;
/**
* Stores the counter clock-wise side orientation.
*/
private static _CounterClockWiseSideOrientation = 1;
/**
* Returns the clock-wise side orientation.
*/
public static get ClockWiseSideOrientation(): number {
return Material._ClockWiseSideOrientation;
}
/**
* Returns the counter clock-wise side orientation.
*/
public static get CounterClockWiseSideOrientation(): number {
return Material._CounterClockWiseSideOrientation;
}
/**
* The dirty texture flag value.
*/
private static _TextureDirtyFlag = 1;
/**
* The dirty light flag value.
*/
private static _LightDirtyFlag = 2;
/**
* The dirty fresnel flag value.
*/
private static _FresnelDirtyFlag = 4;
/**
* The dirty attribute flag value.
*/
private static _AttributesDirtyFlag = 8;
/**
* The dirty misc flag value.
*/
private static _MiscDirtyFlag = 16;
/**
* Returns the dirty texture flag value.
*/
public static get TextureDirtyFlag(): number {
return Material._TextureDirtyFlag;
}
/**
* Returns the dirty light flag value.
*/
public static get LightDirtyFlag(): number {
return Material._LightDirtyFlag;
}
/**
* Returns the dirty fresnel flag value.
*/
public static get FresnelDirtyFlag(): number {
return Material._FresnelDirtyFlag;
}
/**
* Returns the dirty attributes flag value.
*/
public static get AttributesDirtyFlag(): number {
return Material._AttributesDirtyFlag;
}
/**
* Returns the dirty misc flag value.
*/
public static get MiscDirtyFlag(): number {
return Material._MiscDirtyFlag;
}
/**
* The ID of the material.
*/
@serialize()
public id: string;
/**
* The name of the material.
*/
@serialize()
public name: string;
/**
* Specifies if the ready state should be checked on each call.
*/
@serialize()
public checkReadyOnEveryCall = false;
/**
* Specifies if the ready state should be checked once.
*/
@serialize()
public checkReadyOnlyOnce = false;
/**
* The state of the material.
*/
@serialize()
public state = "";
/**
* The alpha value of the material.
*/
@serialize("alpha")
protected _alpha = 1.0;
/**
* Sets the alpha value of the material.
*/
public set alpha(value: number) {
if (this._alpha === value) {
return;
}
this._alpha = value;
this.markAsDirty(Material.MiscDirtyFlag);
}
/**
* Gets the alpha value of the material.
*/
public get alpha(): number {
return this._alpha;
}
/**
* Specifies if back face culling is enabled.
*/
@serialize("backFaceCulling")
protected _backFaceCulling = true;
/**
* Sets the back-face culling state.
*/
public set backFaceCulling(value: boolean) {
if (this._backFaceCulling === value) {
return;
}
this._backFaceCulling = value;
this.markAsDirty(Material.TextureDirtyFlag);
}
/**
* Gets the back-face culling state.
*/
public get backFaceCulling(): boolean {
return this._backFaceCulling;
}
/**
* Stores the value for side orientation.
*/
@serialize()
public sideOrientation: number;
/**
* Callback triggered when the material is compiled.
*/
public onCompiled: (effect: Effect) => void;
/**
* Callback triggered when an error occurs.
*/
public onError: (effect: Effect, errors: string) => void;
/**
* Callback triggered to get the render target textures.
*/
public getRenderTargetTextures: () => SmartArray<RenderTargetTexture>;
/**
* Specifies if the material should be serialized.
*/
public doNotSerialize = false;
/**
* Specifies if the effect should be stored on sub meshes.
*/
public storeEffectOnSubMeshes = false;
/**
* Stores the animations for the material.
*/
public animations: Array<Animation>;
/**
* An event triggered when the material is disposed.
*/
public onDisposeObservable = new Observable<Material>();
/**
* An observer which watches for dispose events.
*/
private _onDisposeObserver: Nullable<Observer<Material>>;
/**
* Called during a dispose event.
*/
public set onDispose(callback: () => void) {
if (this._onDisposeObserver) {
this.onDisposeObservable.remove(this._onDisposeObserver);
}
this._onDisposeObserver = this.onDisposeObservable.add(callback);
}
/**
* An event triggered when the material is bound.
*/
public onBindObservable = new Observable<AbstractMesh>();
/**
* An observer which watches for bind events.
*/
private _onBindObserver: Nullable<Observer<AbstractMesh>>;
/**
* Called during a bind event.
*/
public set onBind(callback: (Mesh: AbstractMesh) => void) {
if (this._onBindObserver) {
this.onBindObservable.remove(this._onBindObserver);
}
this._onBindObserver = this.onBindObservable.add(callback);
}
/**
* An event triggered when the material is unbound.
*/
public onUnBindObservable = new Observable<Material>();
/**
* Stores the value of the alpha mode.
*/
@serialize("alphaMode")
private _alphaMode: number = Engine.ALPHA_COMBINE;
/**
* Sets the value of the alpha mode.
*
* | Value | Type | Description |
* | --- | --- | --- |
* | 0 | ALPHA_DISABLE | |
* | 1 | ALPHA_ADD | |
* | 2 | ALPHA_COMBINE | |
* | 3 | ALPHA_SUBTRACT | |
* | 4 | ALPHA_MULTIPLY | |
* | 5 | ALPHA_MAXIMIZED | |
* | 6 | ALPHA_ONEONE | |
* | 7 | ALPHA_PREMULTIPLIED | |
* | 8 | ALPHA_PREMULTIPLIED_PORTERDUFF | |
* | 9 | ALPHA_INTERPOLATE | |
* | 10 | ALPHA_SCREENMODE | |
*
*/
public set alphaMode(value: number) {
if (this._alphaMode === value) {
return;
}
this._alphaMode = value;
this.markAsDirty(Material.TextureDirtyFlag);
}
/**
* Gets the value of the alpha mode.
*/
public get alphaMode(): number {
return this._alphaMode;
}
/**
* Stores the state of the need depth pre-pass value.
*/
@serialize()
private _needDepthPrePass = false;
/**
* Sets the need depth pre-pass value.
*/
public set needDepthPrePass(value: boolean) {
if (this._needDepthPrePass === value) {
return;
}
this._needDepthPrePass = value;
if (this._needDepthPrePass) {
this.checkReadyOnEveryCall = true;
}
}
/**
* Gets the depth pre-pass value.
*/
public get needDepthPrePass(): boolean {
return this._needDepthPrePass;
}
/**
* Specifies if depth writing should be disabled.
*/
@serialize()
public disableDepthWrite = false;
/**
* Specifies if depth writing should be forced.
*/
@serialize()
public forceDepthWrite = false;
/**
* Specifies if there should be a separate pass for culling.
*/
@serialize()
public separateCullingPass = false;
/**
* Stores the state specifing if fog should be enabled.
*/
@serialize("fogEnabled")
private _fogEnabled = true;
/**
* Sets the state for enabling fog.
*/
public set fogEnabled(value: boolean) {
if (this._fogEnabled === value) {
return;
}
this._fogEnabled = value;
this.markAsDirty(Material.MiscDirtyFlag);
}
/**
* Gets the value of the fog enabled state.
*/
public get fogEnabled(): boolean {
return this._fogEnabled;
}
/**
* Stores the size of points.
*/
@serialize()
public pointSize = 1.0;
/**
* Stores the z offset value.
*/
@serialize()
public zOffset = 0;
/**
* Gets a value specifying if wireframe mode is enabled.
*/
@serialize()
public get wireframe(): boolean {
switch (this._fillMode) {
case Material.WireFrameFillMode:
case Material.LineListDrawMode:
case Material.LineLoopDrawMode:
case Material.LineStripDrawMode:
return true;
}
return this._scene.forceWireframe;
}
/**
* Sets the state of wireframe mode.
*/
public set wireframe(value: boolean) {
this.fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
}
/**
* Gets the value specifying if point clouds are enabled.
*/
@serialize()
public get pointsCloud(): boolean {
switch (this._fillMode) {
case Material.PointFillMode:
case Material.PointListDrawMode:
return true;
}
return this._scene.forcePointsCloud;
}
/**
* Sets the state of point cloud mode.
*/
public set pointsCloud(value: boolean) {
this.fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
}
/**
* Gets the material fill mode.
*/
@serialize()
public get fillMode(): number {
return this._fillMode;
}
/**
* Sets the material fill mode.
*/
public set fillMode(value: number) {
if (this._fillMode === value) {
return;
}
this._fillMode = value;
this.markAsDirty(Material.MiscDirtyFlag);
}
/**
* Stores the effects for the material.
*/
public _effect: Nullable<Effect>;
/**
* Specifies if the material was previously ready.
*/
public _wasPreviouslyReady = false;
/**
* Specifies if uniform buffers should be used.
*/
private _useUBO: boolean;
/**
* Stores a reference to the scene.
*/
private _scene: Scene;
/**
* Stores the fill mode state.
*/
private _fillMode = Material.TriangleFillMode;
/**
* Specifies if the depth write state should be cached.
*/
private _cachedDepthWriteState: boolean;
/**
* Stores the uniform buffer.
*/
protected _uniformBuffer: UniformBuffer;
/**
* Creates a material instance.
* @param name - The name of the material.
* @param scene - The BJS scene to reference.
* @param doNotAdd - Specifies if the material should be added to the scene.
*/
constructor(name: string, scene: Scene, doNotAdd?: boolean) {
this.name = name;
this.id = name || Tools.RandomId();
this._scene = scene || Engine.LastCreatedScene;
if (this._scene.useRightHandedSystem) {
this.sideOrientation = Material.ClockWiseSideOrientation;
} else {
this.sideOrientation = Material.CounterClockWiseSideOrientation;
}
this._uniformBuffer = new UniformBuffer(this._scene.getEngine());
this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
if (!doNotAdd) {
this._scene.materials.push(this);
}
}
/**
* @param {boolean} fullDetails - support for multiple levels of logging within scene loading
* subclasses should override adding information pertainent to themselves.
* @returns - String with material information.
*/
public toString(fullDetails?: boolean): string {
var ret = "Name: " + this.name;
if (fullDetails) {
}
return ret;
}
/**
* Gets the class name of the material.
* @returns - String with the class name of the material.
*/
public getClassName(): string {
return "Material";
}
/**
* Specifies if updates for the material been locked.
*/
public get isFrozen(): boolean {
return this.checkReadyOnlyOnce;
}
/**
* Locks updates for the material.
*/
public freeze(): void {
this.checkReadyOnlyOnce = true;
}
/**
* Unlocks updates for the material.
*/
public unfreeze(): void {
this.checkReadyOnlyOnce = false;
}
/**
* Specifies if the material is ready to be used.
* @param mesh - BJS mesh.
* @param useInstances - Specifies if instances should be used.
* @returns - Boolean indicating if the material is ready to be used.
*/
public isReady(mesh?: AbstractMesh, useInstances?: boolean): boolean {
return true;
}
/**
* Specifies that the submesh is ready to be used.
* @param mesh - BJS mesh.
* @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
* @param useInstances - Specifies that instances should be used.
* @returns - boolean indicating that the submesh is ready or not.
*/
public isReadyForSubMesh(mesh: AbstractMesh, subMesh: BaseSubMesh, useInstances?: boolean): boolean {
return false;
}
/**
* Returns the material effect.
* @returns - Nullable material effect.
*/
public getEffect(): Nullable<Effect> {
return this._effect;
}
/**
* Returns the BJS scene.
* @returns - BJS Scene.
*/
public getScene(): Scene {
return this._scene;
}
/**
* Specifies if the material will require alpha blending
* @returns - Boolean specifying if alpha blending is needed.
*/
public needAlphaBlending(): boolean {
return (this.alpha < 1.0);
}
/**
* Specifies if the mesh will require alpha blending.
* @param mesh - BJS mesh.
* @returns - Boolean specifying if alpha blending is needed for the mesh.
*/
public needAlphaBlendingForMesh(mesh: AbstractMesh): boolean {
return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
}
/**
* Specifies if this material should be rendered in alpha test mode.
* @returns - Boolean specifying if an alpha test is needed.
*/
public needAlphaTesting(): boolean {
return false;
}
/**
* Gets the texture used for the alpha test.
* @returns - Nullable alpha test texture.
*/
public getAlphaTestTexture(): Nullable<BaseTexture> {
return null;
}
/**
* Marks the material to indicate that it needs to be re-calculated.
*/
public markDirty(): void {
this._wasPreviouslyReady = false;
}
public _preBind(effect?: Effect, overrideOrientation: Nullable<number> = null): boolean {
var engine = this._scene.getEngine();
var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
var reverse = orientation === Material.ClockWiseSideOrientation;
engine.enableEffect(effect ? effect : this._effect);
engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
return reverse;
}
/**
* Binds the material to the mesh.
* @param world - World transformation matrix.
* @param mesh - Mesh to bind the material to.
*/
public bind(world: Matrix, mesh?: Mesh): void {
}
/**
* Binds the submesh to the material.
* @param world - World transformation matrix.
* @param mesh - Mesh containing the submesh.
* @param subMesh - Submesh to bind the material to.
*/
public bindForSubMesh(world: Matrix, mesh: Mesh, subMesh: SubMesh): void {
}
/**
* Binds the world matrix to the material.
* @param world - World transformation matrix.
*/
public bindOnlyWorldMatrix(world: Matrix): void {
}
/**
* Binds the scene's uniform buffer to the effect.
* @param effect - Effect to bind to the scene uniform buffer.
* @param sceneUbo - Scene uniform buffer.
*/
public bindSceneUniformBuffer(effect: Effect, sceneUbo: UniformBuffer): void {
sceneUbo.bindToEffect(effect, "Scene");
}
/**
* Binds the view matrix to the effect.
* @param effect - Effect to bind the view matrix to.
*/
public bindView(effect: Effect): void {
if (!this._useUBO) {
effect.setMatrix("view", this.getScene().getViewMatrix());
} else {
this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
}
}
/**
* Binds the view projection matrix to the effect.
* @param effect - Effect to bind the view projection matrix to.
*/
public bindViewProjection(effect: Effect): void {
if (!this._useUBO) {
effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
} else {
this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
}
}
/**
* Specifies if material alpha testing should be turned on for the mesh.
* @param mesh - BJS mesh.
*/
protected _shouldTurnAlphaTestOn(mesh: AbstractMesh): boolean {
return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
}
/**
* Processes to execute after binding the material to a mesh.
* @param mesh - BJS mesh.
*/
protected _afterBind(mesh?: Mesh): void {
this._scene._cachedMaterial = this;
if (mesh) {
this._scene._cachedVisibility = mesh.visibility;
} else {
this._scene._cachedVisibility = 1;
}
if (mesh) {
this.onBindObservable.notifyObservers(mesh);
}
if (this.disableDepthWrite) {
var engine = this._scene.getEngine();
this._cachedDepthWriteState = engine.getDepthWrite();
engine.setDepthWrite(false);
}
}
/**
* Unbinds the material from the mesh.
*/
public unbind(): void {
this.onUnBindObservable.notifyObservers(this);
if (this.disableDepthWrite) {
var engine = this._scene.getEngine();
engine.setDepthWrite(this._cachedDepthWriteState);
}
}
/**
* Gets the active textures from the material.
* @returns - Array of textures.
*/
public getActiveTextures(): BaseTexture[] {
return [];
}
/**
* Specifies if the material uses a texture.
* @param texture - Texture to check against the material.
* @returns - Boolean specifying if the material uses the texture.
*/
public hasTexture(texture: BaseTexture): boolean {
return false;
}
/**
* Makes a duplicate of the material, and gives it a new name.
* @param name - Name to call the duplicated material.
* @returns - Nullable cloned material
*/
public clone(name: string): Nullable<Material> {
return null;
}
/**
* Gets the meshes bound to the material.
* @returns - Array of meshes bound to the material.
*/
public getBindedMeshes(): AbstractMesh[] {
var result = new Array<AbstractMesh>();
for (var index = 0; index < this._scene.meshes.length; index++) {
var mesh = this._scene.meshes[index];
if (mesh.material === this) {
result.push(mesh);
}
}
return result;
}
/**
* Force shader compilation
* @param mesh - BJS mesh.
* @param onCompiled - function to execute once the material is compiled.
* @param options - options to pass to this function.
*/
public forceCompilation(mesh: AbstractMesh, onCompiled?: (material: Material) => void, options?: Partial<{ clipPlane: boolean }>): void {
let localOptions = {
clipPlane: false,
...options
};
var subMesh = new BaseSubMesh();
var scene = this.getScene();
var checkReady = () => {
if (!this._scene || !this._scene.getEngine()) {
return;
}
if (subMesh._materialDefines) {
subMesh._materialDefines._renderId = -1;
}
var clipPlaneState = scene.clipPlane;
if (localOptions.clipPlane) {
scene.clipPlane = new Plane(0, 0, 0, 1);
}
if (this.storeEffectOnSubMeshes) {
if (this.isReadyForSubMesh(mesh, subMesh)) {
if (onCompiled) {
onCompiled(this);
}
}
else {
setTimeout(checkReady, 16);
}
} else {
if (this.isReady(mesh)) {
if (onCompiled) {
onCompiled(this);
}
}
else {
setTimeout(checkReady, 16);
}
}
if (localOptions.clipPlane) {
scene.clipPlane = clipPlaneState;
}
};
checkReady();
}
/**
* Force shader compilation.
* @param mesh The mesh that will use this material
* @param options Additional options for compiling the shaders
* @returns A promise that resolves when the compilation completes
*/
public forceCompilationAsync(mesh: AbstractMesh, options?: Partial<{ clipPlane: boolean }>): Promise<void> {
return new Promise(resolve => {
this.forceCompilation(mesh, () => {
resolve();
}, options);
});
}
/**
* Marks a define in the material to indicate that it needs to be re-computed.
* @param flag - Material define flag.
*/
public markAsDirty(flag: number): void {
if (flag & Material.TextureDirtyFlag) {
this._markAllSubMeshesAsTexturesDirty();
}
if (flag & Material.LightDirtyFlag) {
this._markAllSubMeshesAsLightsDirty();
}
if (flag & Material.FresnelDirtyFlag) {
this._markAllSubMeshesAsFresnelDirty();
}
if (flag & Material.AttributesDirtyFlag) {
this._markAllSubMeshesAsAttributesDirty();
}
if (flag & Material.MiscDirtyFlag) {
this._markAllSubMeshesAsMiscDirty();
}
this.getScene().resetCachedMaterial();
}
/**
* Marks all submeshes of a material to indicate that their material defines need to be re-calculated.
* @param func - function which checks material defines against the submeshes.
*/
protected _markAllSubMeshesAsDirty(func: (defines: MaterialDefines) => void) {
for (var mesh of this.getScene().meshes) {
if (!mesh.subMeshes) {
continue;
}
for (var subMesh of mesh.subMeshes) {
if (subMesh.getMaterial() !== this) {
continue;
}
if (!subMesh._materialDefines) {
continue;
}
func(subMesh._materialDefines);
}
}
}
/**
* Indicates that image processing needs to be re-calculated for all submeshes.
*/
protected _markAllSubMeshesAsImageProcessingDirty() {
this._markAllSubMeshesAsDirty(defines => defines.markAsImageProcessingDirty());
}
/**
* Indicates that textures need to be re-calculated for all submeshes.
*/
protected _markAllSubMeshesAsTexturesDirty() {
this._markAllSubMeshesAsDirty(defines => defines.markAsTexturesDirty());
}
/**
* Indicates that fresnel needs to be re-calculated for all submeshes.
*/
protected _markAllSubMeshesAsFresnelDirty() {
this._markAllSubMeshesAsDirty(defines => defines.markAsFresnelDirty());
}
/**
* Indicates that fresnel and misc need to be re-calculated for all submeshes.
*/
protected _markAllSubMeshesAsFresnelAndMiscDirty() {
this._markAllSubMeshesAsDirty(defines => {
defines.markAsFresnelDirty();
defines.markAsMiscDirty();
});
}
/**
* Indicates that lights need to be re-calculated for all submeshes.
*/
protected _markAllSubMeshesAsLightsDirty() {
this._markAllSubMeshesAsDirty(defines => defines.markAsLightDirty());
}
/**
* Indicates that attributes need to be re-calculated for all submeshes.
*/
protected _markAllSubMeshesAsAttributesDirty() {
this._markAllSubMeshesAsDirty(defines => defines.markAsAttributesDirty());
}
/**
* Indicates that misc needs to be re-calculated for all submeshes.
*/
protected _markAllSubMeshesAsMiscDirty() {
this._markAllSubMeshesAsDirty(defines => defines.markAsMiscDirty());
}
/**
* Indicates that textures and misc need to be re-calculated for all submeshes.
*/
protected _markAllSubMeshesAsTexturesAndMiscDirty() {
this._markAllSubMeshesAsDirty(defines => {
defines.markAsTexturesDirty();
defines.markAsMiscDirty();
});
}
/**
* Disposes the material.
* @param forceDisposeEffect - Specifies if effects should be force disposed.
* @param forceDisposeTextures - Specifies if textures should be force disposed.
*/
public dispose(forceDisposeEffect?: boolean, forceDisposeTextures?: boolean): void {
// Animations
this.getScene().stopAnimation(this);
this.getScene().freeProcessedMaterials();
// Remove from scene
var index = this._scene.materials.indexOf(this);
if (index >= 0) {
this._scene.materials.splice(index, 1);
}
// Remove from meshes
for (index = 0; index < this._scene.meshes.length; index++) {
var mesh = this._scene.meshes[index];
if (mesh.material === this) {
mesh.material = null;
if ((<Mesh>mesh).geometry) {
var geometry = <Geometry>((<Mesh>mesh).geometry);
if (this.storeEffectOnSubMeshes) {
for (var subMesh of mesh.subMeshes) {
geometry._releaseVertexArrayObject(subMesh._materialEffect);
if (forceDisposeEffect && subMesh._materialEffect) {
this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
}
}
} else {
geometry._releaseVertexArrayObject(this._effect)
}
}
}
}
this._uniformBuffer.dispose();
// Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
if (forceDisposeEffect && this._effect) {
if (!this.storeEffectOnSubMeshes) {
this._scene.getEngine()._releaseEffect(this._effect);
}
this._effect = null;
}
// Callback
this.onDisposeObservable.notifyObservers(this);
this.onDisposeObservable.clear();
this.onBindObservable.clear();
this.onUnBindObservable.clear();
}
/**
* Serializes this material.
* @returns - serialized material object.
*/
public serialize(): any {
return SerializationHelper.Serialize(this);
}
/**
* Creates a MultiMaterial from parse MultiMaterial data.
* @param parsedMultiMaterial - Parsed MultiMaterial data.
* @param scene - BJS scene.
* @returns - MultiMaterial.
*/
public static ParseMultiMaterial(parsedMultiMaterial: any, scene: Scene): MultiMaterial {
var multiMaterial = new MultiMaterial(parsedMultiMaterial.name, scene);
multiMaterial.id = parsedMultiMaterial.id;
if (Tags) {
Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
}
for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
var subMatId = parsedMultiMaterial.materials[matIndex];
if (subMatId) {
multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
} else {
multiMaterial.subMaterials.push(null);
}
}
return multiMaterial;
}
/**
* Creates a material from parsed material data.
* @param parsedMaterial - Parsed material data.
* @param scene - BJS scene.
* @param rootUrl - Root URL containing the material information.
* @returns - Parsed material.
*/
public static Parse(parsedMaterial: any, scene: Scene, rootUrl: string): any {
if (!parsedMaterial.customType || parsedMaterial.customType === "BABYLON.StandardMaterial" ) {
return StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
}
if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
if (!(<any>BABYLON).LegacyPBRMaterial) {
Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
return;
}
}
var materialType = Tools.Instantiate(parsedMaterial.customType);
return materialType.Parse(parsedMaterial, scene, rootUrl);;
}
}
}
| apache-2.0 |
iago-suarez/ancoweb-TFG | src/accounts/views.py | 3037 | # from django.shortcuts import render
from django.contrib.auth.forms import AuthenticationForm
from django.http import HttpResponseRedirect
from django.utils.decorators import method_decorator
from django.views import generic
from django.shortcuts import redirect
from django.core.urlresolvers import reverse_lazy, reverse
from django.contrib.auth import authenticate, REDIRECT_FIELD_NAME
from django.contrib.auth import login, logout
from django.contrib import messages
from django.views.decorators.cache import never_cache
from django.views.decorators.csrf import csrf_protect
from django.views.generic import FormView, TemplateView
from . import forms
class SignUp(generic.edit.FormMixin, generic.TemplateView):
signup_form_class = forms.SignupForm
def post(self, request):
form = self.signup_form_class(**self.get_form_kwargs())
if not form.is_valid():
messages.add_message(request,
messages.ERROR,
"Unable to register! "
"Please retype the details")
return super().get(request,
signup_form=form)
form.save()
username = form.cleaned_data["username"]
password = form.cleaned_data["password1"]
messages.add_message(request,
messages.INFO,
"{0} added sucessfully".format(
username))
# Login automatically
user = authenticate(username=username, password=password)
login(self.request, user)
return redirect("home")
class HomeView(SignUp, generic.TemplateView):
template_name = "home.html"
def get_context_data(self, **kwargs):
kwargs["signup_form"] = self.signup_form_class()
return super(HomeView, self).get_context_data(**kwargs)
class LoginView(FormView):
form_class = AuthenticationForm
redirect_field_name = REDIRECT_FIELD_NAME
template_name = 'registration/login.html'
@method_decorator(csrf_protect)
@method_decorator(never_cache)
def dispatch(self, *args, **kwargs):
# If there is a next parameter we redirect to this page,
# else we redirect to home
self.success_url = self.request.GET.get('next', reverse('home'))
return super(LoginView, self).dispatch(*args, **kwargs)
def form_valid(self, form):
"""
The user has provided valid credentials (this was checked in
AuthenticationForm.is_valid()). So now we can log him in.
"""
login(self.request, form.get_user())
return HttpResponseRedirect(self.get_success_url())
class LogoutView(generic.RedirectView):
url = reverse_lazy("home")
def get(self, request, *args, **kwargs):
logout(request)
messages.add_message(request, messages.INFO, 'Logout successful!')
return super().get(request, *args, **kwargs)
class AboutView(TemplateView):
template_name = "about.html"
| apache-2.0 |
RotatingFans/govmomi | object/storage_pod.go | 902 | /*
Copyright (c) 2015 VMware, Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package object
import (
"github.com/RotatingFans/govmomi/vim25"
"github.com/RotatingFans/govmomi/vim25/types"
)
type StoragePod struct {
*Folder
}
func NewStoragePod(c *vim25.Client, ref types.ManagedObjectReference) *StoragePod {
return &StoragePod{
Folder: &Folder{
Common: NewCommon(c, ref),
},
}
}
| apache-2.0 |
emanuelmachado/mvcphp | layouts/_menu.php | 1519 | <section class="menu">
<div class="navbar navbar_ clearfix">
<div class="navbar-inner">
<div class="container">
<div class="clearfix">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
</div>
<div class="navbar-collapse collapse nav-collapse_">
<ul class="nav navbar-nav">
<li><a href="/index.php?controller=principal&action=cadastrar">Cadastro de Pessoa</a></li>
<li><a href="/index.php?controller=principal&action=listar">Listagem de Pessoa</a></li>
</ul>
</div>
</div>
</div>
</div>
</div>
</section> | apache-2.0 |
eikek/publet | web/src/main/scala/org/eknet/publet/web/asset/Group.scala | 2971 | /*
* Copyright 2012 Eike Kettner
*
* 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.eknet.publet.web.asset
import org.eknet.publet.vfs.{Container, ContentResource}
import org.eknet.publet.Glob
/**
* @author Eike Kettner eike.kettner@gmail.com
* @since 28.09.12 20:38
*/
final case class Group(name: String,
pathPattern: Glob = Glob.all,
resources: List[AssetResource] = Nil,
befores: Set[String] = Set(),
afters: Set[String] = Set(),
uses: Set[String] = Set()) {
/**
* Creates a new group with the resource.
*
* @param r
* @return
*/
def add(r: AssetResource): Group =
Group(name, pathPattern, r.inGroup(name) :: resources, befores, afters, uses)
/**
* Creates a new group with the given resources.
* @param rs
* @return
*/
def add(rs: Iterable[AssetResource]): Group =
Group(name, pathPattern, rs.map(_.inGroup(name)).toList ::: resources, befores, afters, uses)
/**
* Creates a new group with all child resources of the container whose
* name ends in `.js`.
*
* @param c
* @return
*/
def add(c: Container): Group = {
val list = c.children.collect({ case r: ContentResource => new AssetResource(r).inGroup(name) })
add(list)
}
/**
* Specify a glob pattern such that this group is only active
* when the path is matching this glob.
*
* @param glob
* @return
*/
def forPath(glob: String) =
Group(name, Glob(glob), resources, befores, afters, uses)
/**
* Specifies the given group to be included _after_ this group or in
* other words this group comes _before_ the given one.
* @param group
* @return
*/
def before(group: String*) =
Group(name, pathPattern, resources, befores ++ group, afters, uses)
/**
* Specifies the given group to be included _before_ this group. In other
* words this group comes _after_ the given one.
* @param group
* @return
*/
def require(group: String*) =
Group(name, pathPattern, resources, befores, afters ++ group, uses)
/**
* Specifies to use the given group in this one. That means that the given
* group is just added as a child. The order how childs are finally loaded
* is determined by `before` and `after`.
*
* @param group
* @return
*/
def use(group: String*) =
Group(name, pathPattern, resources, befores, afters, uses ++ group)
} | apache-2.0 |
mbrinkmeier/abbozza | lib/js/abbozza/gui/field_lengthinput.js | 2618 | /**
* @license
* abbozza!
*
* Copyright 2015 Michael Brinkmeier ( michael.brinkmeier@uni-osnabrueck.de )
*
* 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.
*/
/**
* @fileoverview A field for the input of an array length. It checks the value if
* its value is between 0 and max-1.
*
* @author michael.brinkmeier@uni-osnabrueck.de (Michael Brinkmeier)
*/
'use strict';
goog.provide('FieldLengthInput');
goog.require('Blockly.Field');
goog.require('Blockly.FieldTextInput');
goog.require('Blockly.Msg');
goog.require('goog.asserts');
goog.require('goog.dom');
goog.require('goog.userAgent');
FieldLengthInput = function(text, max ) {
FieldNameInput.superClass_.constructor.call(this, text);
this.editing = false;
if ( max ) {
this.max = max;
} else {
max = -1;
}
};
goog.inherits(FieldLengthInput, Blockly.FieldTextInput);
FieldLengthInput.prototype.showEditor_ = function(opt_quietInput) {
this.editing = true;
Blockly.FieldTextInput.prototype.showEditor_.call(this,opt_quietInput);
};
FieldLengthInput.prototype.widgetDispose_ = function() {
var thisField = this;
return function() {
thisField.editing = false;
var htmlInput = Blockly.FieldTextInput.htmlInput_;
// Save the edit (if it validates).
var text = htmlInput.value;
text = thisField.checkValue(text);
/*
if (thisField.sourceBlock_ && thisField.changeHandler_) {
text = thisField.changeHandler_(text);
if (text === null) {
// Invalid edit.
text = htmlInput.defaultValue;
}
}*/
thisField.setText(text);
thisField.sourceBlock_.rendered && thisField.sourceBlock_.render();
Blockly.unbindEvent_(htmlInput.onKeyDownWrapper_);
Blockly.unbindEvent_(htmlInput.onKeyUpWrapper_);
Blockly.unbindEvent_(htmlInput.onKeyPressWrapper_);
Blockly.unbindEvent_(htmlInput.onWorkspaceChangeWrapper_);
Blockly.FieldTextInput.htmlInput_ = null;
// Delete the width property.
Blockly.WidgetDiv.DIV.style.width = 'auto';
}
};
FieldLengthInput.prototype.checkValue = function(text) {
return Validator.lengthValidator(text, this.max);
};
| apache-2.0 |
mrinsss/Full-Repo | AMS+WSDL/ams/application/views/web_master/index_tmp.tpl.php | 127691 | <!DOCTYPE html>
<!-- saved from url=(0054)https://almsaeedstudio.com/themes/AdminLTE/index2.html -->
<html>
<head>
<?php require_once(APPPATH.'views/'.ADMIN_DIR.'/header.tpl.php')?>
</head>
<body class="skin-blue sidebar-mini">
<div class="wrapper">
<!-- Header -->
<header class="main-header">
<!-- Logo -->
<a href="./AdminLTE 2 _ Dashboard_files/AdminLTE 2 _ Dashboard.html" class="logo">
<img src="<?php echo r_path('img/logo.png')?>" alt="###SITE_NAME_LINK###" />
</a>
<!-- Header Navbar: style can be found in header.less -->
<nav class="navbar navbar-static-top" role="navigation">
<!-- Sidebar toggle button-->
<a href="https://almsaeedstudio.com/themes/AdminLTE/index2.html#" class="sidebar-toggle" data-toggle="offcanvas" role="button">
<span class="sr-only">Toggle navigation</span>
</a>
<!-- Navbar Right Menu -->
<div class="navbar-custom-menu">
<ul class="nav navbar-nav">
<!-- Messages: style can be found in dropdown.less-->
<li class="dropdown messages-menu">
<a href="https://almsaeedstudio.com/themes/AdminLTE/index2.html#" class="dropdown-toggle" data-toggle="dropdown">
<i class="fa fa-envelope-o"></i>
<span class="label label-success">4</span>
</a>
<ul class="dropdown-menu">
<li class="header">You have 4 messages</li>
<li>
<!-- inner menu: contains the actual data -->
<div class="slimScrollDiv" style="position: relative; overflow: hidden; width: auto; height: 200px;"><ul class="menu" style="overflow: hidden; width: 100%; height: 200px;">
<li><!-- start message -->
<a href="https://almsaeedstudio.com/themes/AdminLTE/index2.html#">
<div class="pull-left">
<img src="<?php echo r_path('img/user2-160x160.jpg')?>" class="img-circle" alt="User Image">
</div>
<h4>
Support Team
<small><i class="fa fa-clock-o"></i> 5 mins</small>
</h4>
<p>Why not buy a new awesome theme?</p>
</a>
</li><!-- end message -->
<li>
<a href="https://almsaeedstudio.com/themes/AdminLTE/index2.html#">
<div class="pull-left">
<img src="<?php echo r_path('img/user3-128x128.jpg')?>" class="img-circle" alt="user image">
</div>
<h4>
AdminLTE Design Team
<small><i class="fa fa-clock-o"></i> 2 hours</small>
</h4>
<p>Why not buy a new awesome theme?</p>
</a>
</li>
<li>
<a href="https://almsaeedstudio.com/themes/AdminLTE/index2.html#">
<div class="pull-left">
<img src="<?php echo r_path('img/user4-128x128.jpg')?>" class="img-circle" alt="user image">
</div>
<h4>
Developers
<small><i class="fa fa-clock-o"></i> Today</small>
</h4>
<p>Why not buy a new awesome theme?</p>
</a>
</li>
<li>
<a href="https://almsaeedstudio.com/themes/AdminLTE/index2.html#">
<div class="pull-left">
<img src="<?php echo r_path('img/user3-128x128.jpg')?>" class="img-circle" alt="user image">
</div>
<h4>
Sales Department
<small><i class="fa fa-clock-o"></i> Yesterday</small>
</h4>
<p>Why not buy a new awesome theme?</p>
</a>
</li>
<li>
<a href="https://almsaeedstudio.com/themes/AdminLTE/index2.html#">
<div class="pull-left">
<img src="<?php echo r_path('img/user4-128x128.jpg')?>" class="img-circle" alt="user image">
</div>
<h4>
Reviewers
<small><i class="fa fa-clock-o"></i> 2 days</small>
</h4>
<p>Why not buy a new awesome theme?</p>
</a>
</li>
</ul><div class="slimScrollBar" style="width: 3px; position: absolute; top: 0px; opacity: 0.4; display: block; border-radius: 7px; z-index: 99; right: 1px; background: rgb(0, 0, 0);"></div><div class="slimScrollRail" style="width: 3px; height: 100%; position: absolute; top: 0px; display: none; border-radius: 7px; opacity: 0.2; z-index: 90; right: 1px; background: rgb(51, 51, 51);"></div></div>
</li>
<li class="footer"><a href="https://almsaeedstudio.com/themes/AdminLTE/index2.html#">See All Messages</a></li>
</ul>
</li>
<!-- Notifications: style can be found in dropdown.less -->
<li class="dropdown notifications-menu">
<a href="https://almsaeedstudio.com/themes/AdminLTE/index2.html#" class="dropdown-toggle" data-toggle="dropdown">
<i class="fa fa-bell-o"></i>
<span class="label label-warning">10</span>
</a>
<ul class="dropdown-menu">
<li class="header">You have 10 notifications</li>
<li>
<!-- inner menu: contains the actual data -->
<div class="slimScrollDiv" style="position: relative; overflow: hidden; width: auto; height: 200px;"><ul class="menu" style="overflow: hidden; width: 100%; height: 200px;">
<li>
<a href="https://almsaeedstudio.com/themes/AdminLTE/index2.html#">
<i class="fa fa-users text-aqua"></i> 5 new members joined today
</a>
</li>
<li>
<a href="https://almsaeedstudio.com/themes/AdminLTE/index2.html#">
<i class="fa fa-warning text-yellow"></i> Very long description here that may not fit into the page and may cause design problems
</a>
</li>
<li>
<a href="https://almsaeedstudio.com/themes/AdminLTE/index2.html#">
<i class="fa fa-users text-red"></i> 5 new members joined
</a>
</li>
<li>
<a href="https://almsaeedstudio.com/themes/AdminLTE/index2.html#">
<i class="fa fa-shopping-cart text-green"></i> 25 sales made
</a>
</li>
<li>
<a href="https://almsaeedstudio.com/themes/AdminLTE/index2.html#">
<i class="fa fa-user text-red"></i> You changed your username
</a>
</li>
</ul><div class="slimScrollBar" style="width: 3px; position: absolute; top: 0px; opacity: 0.4; display: block; border-radius: 7px; z-index: 99; right: 1px; background: rgb(0, 0, 0);"></div><div class="slimScrollRail" style="width: 3px; height: 100%; position: absolute; top: 0px; display: none; border-radius: 7px; opacity: 0.2; z-index: 90; right: 1px; background: rgb(51, 51, 51);"></div></div>
</li>
<li class="footer"><a href="https://almsaeedstudio.com/themes/AdminLTE/index2.html#">View all</a></li>
</ul>
</li>
<!-- Tasks: style can be found in dropdown.less -->
<li class="dropdown tasks-menu">
<a href="https://almsaeedstudio.com/themes/AdminLTE/index2.html#" class="dropdown-toggle" data-toggle="dropdown">
<i class="fa fa-flag-o"></i>
<span class="label label-danger">9</span>
</a>
<ul class="dropdown-menu">
<li class="header">You have 9 tasks</li>
<li>
<!-- inner menu: contains the actual data -->
<div class="slimScrollDiv" style="position: relative; overflow: hidden; width: auto; height: 200px;"><ul class="menu" style="overflow: hidden; width: 100%; height: 200px;">
<li><!-- Task item -->
<a href="https://almsaeedstudio.com/themes/AdminLTE/index2.html#">
<h3>
Design some buttons
<small class="pull-right">20%</small>
</h3>
<div class="progress xs">
<div class="progress-bar progress-bar-aqua" style="width: 20%" role="progressbar" aria-valuenow="20" aria-valuemin="0" aria-valuemax="100">
<span class="sr-only">20% Complete</span>
</div>
</div>
</a>
</li><!-- end task item -->
<li><!-- Task item -->
<a href="https://almsaeedstudio.com/themes/AdminLTE/index2.html#">
<h3>
Create a nice theme
<small class="pull-right">40%</small>
</h3>
<div class="progress xs">
<div class="progress-bar progress-bar-green" style="width: 40%" role="progressbar" aria-valuenow="20" aria-valuemin="0" aria-valuemax="100">
<span class="sr-only">40% Complete</span>
</div>
</div>
</a>
</li><!-- end task item -->
<li><!-- Task item -->
<a href="https://almsaeedstudio.com/themes/AdminLTE/index2.html#">
<h3>
Some task I need to do
<small class="pull-right">60%</small>
</h3>
<div class="progress xs">
<div class="progress-bar progress-bar-red" style="width: 60%" role="progressbar" aria-valuenow="20" aria-valuemin="0" aria-valuemax="100">
<span class="sr-only">60% Complete</span>
</div>
</div>
</a>
</li><!-- end task item -->
<li><!-- Task item -->
<a href="https://almsaeedstudio.com/themes/AdminLTE/index2.html#">
<h3>
Make beautiful transitions
<small class="pull-right">80%</small>
</h3>
<div class="progress xs">
<div class="progress-bar progress-bar-yellow" style="width: 80%" role="progressbar" aria-valuenow="20" aria-valuemin="0" aria-valuemax="100">
<span class="sr-only">80% Complete</span>
</div>
</div>
</a>
</li><!-- end task item -->
</ul><div class="slimScrollBar" style="width: 3px; position: absolute; top: 0px; opacity: 0.4; display: block; border-radius: 7px; z-index: 99; right: 1px; background: rgb(0, 0, 0);"></div><div class="slimScrollRail" style="width: 3px; height: 100%; position: absolute; top: 0px; display: none; border-radius: 7px; opacity: 0.2; z-index: 90; right: 1px; background: rgb(51, 51, 51);"></div></div>
</li>
<li class="footer">
<a href="https://almsaeedstudio.com/themes/AdminLTE/index2.html#">View all tasks</a>
</li>
</ul>
</li>
<!-- User Account: style can be found in dropdown.less -->
<li class="dropdown user user-menu">
<a href="https://almsaeedstudio.com/themes/AdminLTE/index2.html#" class="dropdown-toggle" data-toggle="dropdown">
<img src="<?php echo r_path('img/user2-160x160.jpg')?>" class="user-image" alt="User Image">
<span class="hidden-xs">Alexander Pierce</span>
</a>
<ul class="dropdown-menu">
<!-- User image -->
<li class="user-header">
<img src="<?php echo r_path('img/user2-160x160.jpg')?>" class="img-circle" alt="User Image">
<p>
Alexander Pierce - Web Developer
<small>Member since Nov. 2012</small>
</p>
</li>
<!-- Menu Body -->
<li class="user-body">
<div class="col-xs-4 text-center">
<a href="https://almsaeedstudio.com/themes/AdminLTE/index2.html#">Followers</a>
</div>
<div class="col-xs-4 text-center">
<a href="https://almsaeedstudio.com/themes/AdminLTE/index2.html#">Sales</a>
</div>
<div class="col-xs-4 text-center">
<a href="https://almsaeedstudio.com/themes/AdminLTE/index2.html#">Friends</a>
</div>
</li>
<!-- Menu Footer-->
<li class="user-footer">
<div class="pull-left">
<a href="https://almsaeedstudio.com/themes/AdminLTE/index2.html#" class="btn btn-default btn-flat">Profile</a>
</div>
<div class="pull-right">
<a href="https://almsaeedstudio.com/themes/AdminLTE/index2.html#" class="btn btn-default btn-flat">Sign out</a>
</div>
</li>
</ul>
</li>
<!-- Control Sidebar Toggle Button -->
<li>
<a href="https://almsaeedstudio.com/themes/AdminLTE/index2.html#" data-toggle="control-sidebar"><i class="fa fa-gears"></i></a>
</li>
</ul>
</div>
</nav>
</header>
<!-- End Header -->
<!-- Left side column. contains the logo and sidebar -->
<aside class="main-sidebar">
<!-- sidebar: style can be found in sidebar.less -->
<section class="sidebar" style="height: auto;">
<!-- Sidebar user panel -->
<div class="user-panel">
<div class="pull-left image"><img alt="User Image" class=
"img-circle" src="./img/user2-160x160.jpg"></div>
<div class="pull-left info">
<p>Alexander Pierce</p><a href=
"https://almsaeedstudio.com/themes/AdminLTE/index2.html#"><i class="fa fa-circle text-success"></i>
Online</a>
</div>
</div><!-- search form -->
<form action="https://almsaeedstudio.com/themes/AdminLTE/index2.html#"
class="sidebar-form" method="get">
<div class="input-group">
<input class="form-control" name="q" placeholder="Search..."
type="text"> <span class="input-group-btn"><button class=
"btn btn-flat" id="search-btn" name="search" type=
"submit"><span class="input-group-btn fa fa-search" style=
"font-style: italic"></span></button></span>
</div>
</form><!-- /.search form -->
<!-- sidebar menu: : style can be found in sidebar.less -->
<ul class="sidebar-menu">
<li class="header">MAIN NAVIGATION</li>
<li class="active treeview">
<a href=
"https://almsaeedstudio.com/themes/AdminLTE/index2.html#"><i class="fa fa-dashboard">
</i> <span>Dashboard</span> <i class=
"fa fa-angle-left pull-right"></i></a>
<ul class="treeview-menu">
<li>
<a href=
"https://almsaeedstudio.com/themes/AdminLTE/index.html">
<i class="fa fa-circle-o"></i> Dashboard v1</a>
</li>
<li class="active">
<a href=
"./AdminLTE%202%20_%20Dashboard_files/AdminLTE%202%20_%20Dashboard.html">
<i class="fa fa-circle-o"></i> Dashboard v2</a>
</li>
</ul>
</li>
<li class="treeview">
<a href=
"https://almsaeedstudio.com/themes/AdminLTE/index2.html#"><i class="fa fa-files-o">
</i> <span>Layout Options</span> <span class=
"label label-primary pull-right">4</span></a>
<ul class="treeview-menu">
<li>
<a href=
"https://almsaeedstudio.com/themes/AdminLTE/pages/layout/top-nav.html">
<i class="fa fa-circle-o"></i> Top Navigation</a>
</li>
<li>
<a href=
"https://almsaeedstudio.com/themes/AdminLTE/pages/layout/boxed.html">
<i class="fa fa-circle-o"></i> Boxed</a>
</li>
<li>
<a href=
"https://almsaeedstudio.com/themes/AdminLTE/pages/layout/fixed.html">
<i class="fa fa-circle-o"></i> Fixed</a>
</li>
<li>
<a href=
"https://almsaeedstudio.com/themes/AdminLTE/pages/layout/collapsed-sidebar.html">
<i class="fa fa-circle-o"></i> Collapsed Sidebar</a>
</li>
</ul>
</li>
<li>
<a href=
"https://almsaeedstudio.com/themes/AdminLTE/pages/widgets.html">
<i class="fa fa-th"></i> <span>Widgets</span> <small class=
"label pull-right bg-green">new</small></a>
</li>
<li class="treeview">
<a href=
"https://almsaeedstudio.com/themes/AdminLTE/index2.html#"><i class="fa fa-pie-chart">
</i> <span>Charts</span> <i class=
"fa fa-angle-left pull-right"></i></a>
<ul class="treeview-menu">
<li>
<a href=
"https://almsaeedstudio.com/themes/AdminLTE/pages/charts/chartjs.html">
<i class="fa fa-circle-o"></i> ChartJS</a>
</li>
<li>
<a href=
"https://almsaeedstudio.com/themes/AdminLTE/pages/charts/morris.html">
<i class="fa fa-circle-o"></i> Morris</a>
</li>
<li>
<a href=
"https://almsaeedstudio.com/themes/AdminLTE/pages/charts/flot.html">
<i class="fa fa-circle-o"></i> Flot</a>
</li>
<li>
<a href=
"https://almsaeedstudio.com/themes/AdminLTE/pages/charts/inline.html">
<i class="fa fa-circle-o"></i> Inline charts</a>
</li>
</ul>
</li>
<li class="treeview">
<a href=
"https://almsaeedstudio.com/themes/AdminLTE/index2.html#"><i class="fa fa-laptop">
</i> <span>UI Elements</span> <i class=
"fa fa-angle-left pull-right"></i></a>
<ul class="treeview-menu">
<li>
<a href=
"https://almsaeedstudio.com/themes/AdminLTE/pages/UI/general.html">
<i class="fa fa-circle-o"></i> General</a>
</li>
<li>
<a href=
"https://almsaeedstudio.com/themes/AdminLTE/pages/UI/icons.html">
<i class="fa fa-circle-o"></i> Icons</a>
</li>
<li>
<a href=
"https://almsaeedstudio.com/themes/AdminLTE/pages/UI/buttons.html">
<i class="fa fa-circle-o"></i> Buttons</a>
</li>
<li>
<a href=
"https://almsaeedstudio.com/themes/AdminLTE/pages/UI/sliders.html">
<i class="fa fa-circle-o"></i> Sliders</a>
</li>
<li>
<a href=
"https://almsaeedstudio.com/themes/AdminLTE/pages/UI/timeline.html">
<i class="fa fa-circle-o"></i> Timeline</a>
</li>
<li>
<a href=
"https://almsaeedstudio.com/themes/AdminLTE/pages/UI/modals.html">
<i class="fa fa-circle-o"></i> Modals</a>
</li>
</ul>
</li>
<li class="treeview">
<a href=
"https://almsaeedstudio.com/themes/AdminLTE/index2.html#"><i class="fa fa-edit">
</i> <span>Forms</span> <i class=
"fa fa-angle-left pull-right"></i></a>
<ul class="treeview-menu">
<li>
<a href=
"https://almsaeedstudio.com/themes/AdminLTE/pages/forms/general.html">
<i class="fa fa-circle-o"></i> General Elements</a>
</li>
<li>
<a href=
"https://almsaeedstudio.com/themes/AdminLTE/pages/forms/advanced.html">
<i class="fa fa-circle-o"></i> Advanced Elements</a>
</li>
<li>
<a href=
"https://almsaeedstudio.com/themes/AdminLTE/pages/forms/editors.html">
<i class="fa fa-circle-o"></i> Editors</a>
</li>
</ul>
</li>
<li class="treeview">
<a href=
"https://almsaeedstudio.com/themes/AdminLTE/index2.html#"><i class="fa fa-table">
</i> <span>Tables</span> <i class=
"fa fa-angle-left pull-right"></i></a>
<ul class="treeview-menu">
<li>
<a href=
"https://almsaeedstudio.com/themes/AdminLTE/pages/tables/simple.html">
<i class="fa fa-circle-o"></i> Simple tables</a>
</li>
<li>
<a href=
"https://almsaeedstudio.com/themes/AdminLTE/pages/tables/data.html">
<i class="fa fa-circle-o"></i> Data tables</a>
</li>
</ul>
</li>
<li>
<a href="./calendar.html"><i class="fa fa-calendar"></i>
<span>Calendar</span> <small class=
"label pull-right bg-red">3</small></a>
</li>
<li>
<a href=
"https://almsaeedstudio.com/themes/AdminLTE/pages/mailbox/mailbox.html">
<i class="fa fa-envelope"></i> <span>Mailbox</span>
<small class="label pull-right bg-yellow">12</small></a>
</li>
<li class="treeview">
<a href=
"https://almsaeedstudio.com/themes/AdminLTE/index2.html#"><i class="fa fa-folder">
</i> <span>Examples</span> <i class=
"fa fa-angle-left pull-right"></i></a>
<ul class="treeview-menu">
<li class="treeview">
<a href=
"https://almsaeedstudio.com/themes/AdminLTE/pages/examples/invoice.html">
<i class="fa fa-circle-o"></i> Invoice</a>
<ul class="treeview-menu">
<li>
<a href="#test1">Test1</a>
</li>
<li>
<a href="#test2">Test2</a>
</li>
<li>
<a href="#test2">Test2</a>
</li>
<li>
<a href="#test2">Test2</a>
</li>
<li>
<a href="#test2">Test2</a>
</li>
<li>
<a href="#test3">Test3</a>
</li>
</ul>
</li>
<li>
<a href=
"https://almsaeedstudio.com/themes/AdminLTE/pages/examples/login.html">
<i class="fa fa-circle-o"></i> Login</a>
</li>
<li>
<a href=
"https://almsaeedstudio.com/themes/AdminLTE/pages/examples/register.html">
<i class="fa fa-circle-o"></i> Register</a>
</li>
<li>
<a href=
"https://almsaeedstudio.com/themes/AdminLTE/pages/examples/lockscreen.html">
<i class="fa fa-circle-o"></i> Lockscreen</a>
</li>
<li>
<a href=
"https://almsaeedstudio.com/themes/AdminLTE/pages/examples/404.html">
<i class="fa fa-circle-o"></i> 404 Error</a>
</li>
<li>
<a href=
"https://almsaeedstudio.com/themes/AdminLTE/pages/examples/500.html">
<i class="fa fa-circle-o"></i> 500 Error</a>
</li>
<li>
<a href=
"https://almsaeedstudio.com/themes/AdminLTE/pages/examples/blank.html">
<i class="fa fa-circle-o"></i> Blank Page</a>
</li>
</ul>
</li>
<li class="treeview">
<a href=
"https://almsaeedstudio.com/themes/AdminLTE/index2.html#"><i class="fa fa-share">
</i> <span>Multilevel</span> <i class=
"fa fa-angle-left pull-right"></i></a>
<ul class="treeview-menu">
<li>
<a href=
"https://almsaeedstudio.com/themes/AdminLTE/index2.html#">
<i class="fa fa-circle-o"></i> Level One</a>
</li>
<li>
<a href=
"https://almsaeedstudio.com/themes/AdminLTE/index2.html#">
<i class="fa fa-circle-o"></i> Level One <i class=
"fa fa-angle-left pull-right"></i></a>
<ul class="treeview-menu">
<li>
<a href=
"https://almsaeedstudio.com/themes/AdminLTE/index2.html#">
<i class="fa fa-circle-o"></i> Level Two</a>
</li>
<li>
<a href=
"https://almsaeedstudio.com/themes/AdminLTE/index2.html#">
<i class="fa fa-circle-o"></i> Level Two
<i class="fa fa-angle-left pull-right"></i></a>
<ul class="treeview-menu">
<li>
<a href=
"https://almsaeedstudio.com/themes/AdminLTE/index2.html#">
<i class="fa fa-circle-o"></i> Level
Three</a>
</li>
<li>
<a href=
"https://almsaeedstudio.com/themes/AdminLTE/index2.html#">
<i class="fa fa-circle-o"></i> Level
Three</a>
</li>
</ul>
</li>
</ul>
</li>
<li>
<a href=
"https://almsaeedstudio.com/themes/AdminLTE/index2.html#">
<i class="fa fa-circle-o"></i> Level One</a>
</li>
</ul>
</li>
<li>
<a href=
"https://almsaeedstudio.com/themes/AdminLTE/documentation/index.html">
<i class="fa fa-book"></i> <span>Documentation</span></a>
</li>
<li class="header">LABELS</li>
<li>
<a href=
"https://almsaeedstudio.com/themes/AdminLTE/index2.html#"><i class="fa fa-circle-o text-red">
</i> <span>Important</span></a>
</li>
<li>
<a href=
"https://almsaeedstudio.com/themes/AdminLTE/index2.html#"><i class="fa fa-circle-o text-yellow">
</i> <span>Warning</span></a>
</li>
<li>
<a href=
"https://almsaeedstudio.com/themes/AdminLTE/index2.html#"><i class="fa fa-circle-o text-aqua">
</i> <span>Information</span></a>
</li>
</ul>
</section>
<!-- /.sidebar -->
</aside>
<!-- Content Wrapper. Contains page content -->
<div class="content-wrapper" style="min-height: 916px;">
<!-- Content Header (Page header) -->
<section class="content-header">
<h1>Dashboard <small>Version 2.0</small></h1>
<ol class="breadcrumb">
<li>
<a href=
"https://almsaeedstudio.com/themes/AdminLTE/index2.html#"><i class="fa fa-dashboard">
</i> Home</a>
</li>
<li class="active">Dashboard</li>
</ol>
</section><!-- Main content -->
<section class="content">
<!-- Info boxes -->
<div class="row">
<div class="col-md-3 col-sm-6 col-xs-12">
<div class="info-box">
<span class=
"info-box-icon bg-aqua ion ion-ios-gear-outline" style=
"font-style: italic"></span>
<div class="info-box-content">
<span class="info-box-text">CPU Traffic</span>
<span class=
"info-box-number">90<small>%</small></span>
</div><!-- /.info-box-content -->
</div><!-- /.info-box -->
</div><!-- /.col -->
<div class="col-md-3 col-sm-6 col-xs-12">
<div class="info-box">
<span class="info-box-icon bg-red fa fa-google-plus"
style="font-style: italic"></span>
<div class="info-box-content">
<span class="info-box-text">Likes</span>
<span class="info-box-number">41,410</span>
</div><!-- /.info-box-content -->
</div><!-- /.info-box -->
</div><!-- /.col -->
<!-- fix for small devices only -->
<div class="clearfix visible-sm-block"></div>
<div class="col-md-3 col-sm-6 col-xs-12">
<div class="info-box">
<span class=
"info-box-icon bg-green ion ion-ios-cart-outline"
style="font-style: italic"></span>
<div class="info-box-content">
<span class="info-box-text">Sales</span>
<span class="info-box-number">760</span>
</div><!-- /.info-box-content -->
</div><!-- /.info-box -->
</div><!-- /.col -->
<div class="col-md-3 col-sm-6 col-xs-12">
<div class="info-box">
<span class=
"info-box-icon bg-yellow ion ion-ios-people-outline"
style="font-style: italic"></span>
<div class="info-box-content">
<span class="info-box-text">New Members</span>
<span class="info-box-number">2,000</span>
</div><!-- /.info-box-content -->
</div><!-- /.info-box -->
</div><!-- /.col -->
</div><!-- /.row -->
<div class="row">
<div class="col-md-12">
<div class="box">
<div class="box-header with-border">
<h3 class="box-title">Monthly Recap Report</h3>
<div class="box-tools pull-right">
<button class="btn btn-box-tool fa fa-minus"
data-widget="collapse" style=
"font-style: italic"></button>
<div class="btn-group">
<button class=
"btn btn-box-tool dropdown-toggle fa fa-wrench"
data-toggle="dropdown" style=
"font-style: italic"></button>
<ul class="dropdown-menu">
<li>
<a href=
"https://almsaeedstudio.com/themes/AdminLTE/index2.html#">
Action</a>
</li>
<li>
<a href=
"https://almsaeedstudio.com/themes/AdminLTE/index2.html#">
Another action</a>
</li>
<li>
<a href=
"https://almsaeedstudio.com/themes/AdminLTE/index2.html#">
Something else here</a>
</li>
<li class="divider"></li>
<li>
<a href=
"https://almsaeedstudio.com/themes/AdminLTE/index2.html#">
Separated link</a>
</li>
</ul>
</div><button class=
"btn btn-box-tool fa fa-times" data-widget=
"remove" style="font-style: italic"></button>
</div>
</div><!-- /.box-header -->
<div class="box-body">
<div class="row">
<div class="col-md-8">
<p class="text-center"><strong>Sales: 1
Jan, 2014 - 30 Jul, 2014</strong></p>
<div class="chart">
<!-- Sales Chart Canvas -->
<canvas height="190" id="salesChart"
style="width: 475px; height: 190px;"
width="475"></canvas>
</div><!-- /.chart-responsive -->
</div><!-- /.col -->
<div class="col-md-4">
<p class="text-center"><strong>Goal
Completion</strong></p>
<div class="progress-group">
<span class="progress-text">Add
Products to Cart</span> <span class=
"progress-number"><b>160</b>/200</span>
<div class="progress sm">
<div class=
"progress-bar progress-bar-aqua"
style="width: 80%"></div>
</div>
</div><!-- /.progress-group -->
<div class="progress-group">
<span class="progress-text">Complete
Purchase</span> <span class=
"progress-number"><b>310</b>/400</span>
<div class="progress sm">
<div class=
"progress-bar progress-bar-red"
style="width: 80%"></div>
</div>
</div><!-- /.progress-group -->
<div class="progress-group">
<span class="progress-text">Visit
Premium Page</span> <span class=
"progress-number"><b>480</b>/800</span>
<div class="progress sm">
<div class=
"progress-bar progress-bar-green"
style="width: 80%"></div>
</div>
</div><!-- /.progress-group -->
<div class="progress-group">
<span class="progress-text">Send
Inquiries</span> <span class=
"progress-number"><b>250</b>/500</span>
<div class="progress sm">
<div class=
"progress-bar progress-bar-yellow"
style="width: 80%"></div>
</div>
</div><!-- /.progress-group -->
</div><!-- /.col -->
</div><!-- /.row -->
</div><!-- ./box-body -->
<div class="box-footer">
<div class="row">
<div class="col-sm-3 col-xs-6">
<div class=
"description-block border-right">
<span class=
"description-percentage text-green"><i class="fa fa-caret-up">
</i> 17%</span>
<h5 class="description-header">
$35,210.43</h5><span class=
"description-text">TOTAL REVENUE</span>
</div><!-- /.description-block -->
</div><!-- /.col -->
<div class="col-sm-3 col-xs-6">
<div class=
"description-block border-right">
<span class=
"description-percentage text-yellow"><i class="fa fa-caret-left">
</i> 0%</span>
<h5 class="description-header">
$10,390.90</h5><span class=
"description-text">TOTAL COST</span>
</div><!-- /.description-block -->
</div><!-- /.col -->
<div class="col-sm-3 col-xs-6">
<div class=
"description-block border-right">
<span class=
"description-percentage text-green"><i class="fa fa-caret-up">
</i> 20%</span>
<h5 class="description-header">
$24,813.53</h5><span class=
"description-text">TOTAL PROFIT</span>
</div><!-- /.description-block -->
</div><!-- /.col -->
<div class="col-sm-3 col-xs-6">
<div class="description-block">
<span class=
"description-percentage text-red"><i class="fa fa-caret-down">
</i> 18%</span>
<h5 class="description-header">
1200</h5><span class=
"description-text">GOAL
COMPLETIONS</span>
</div><!-- /.description-block -->
</div>
</div><!-- /.row -->
</div><!-- /.box-footer -->
</div><!-- /.box -->
</div><!-- /.col -->
</div><!-- /.row -->
<!-- Main row -->
<div class="row">
<!-- Left col -->
<div class="col-md-8">
<!-- MAP & BOX PANE -->
<div class="box box-success">
<div class="box-header with-border">
<h3 class="box-title">Visitors Report</h3>
<div class="box-tools pull-right">
<button class="btn btn-box-tool fa fa-minus"
data-widget="collapse" style=
"font-style: italic"></button> <button class=
"btn btn-box-tool fa fa-times" data-widget=
"remove" style="font-style: italic"></button>
</div>
</div><!-- /.box-header -->
</div><!-- /.box -->
<div class="row">
<div class="col-md-6">
<!-- DIRECT CHAT -->
<div class=
"box box-warning direct-chat direct-chat-warning">
<div class="box-header with-border">
<h3 class="box-title">Direct Chat</h3>
<div class="box-tools pull-right">
<span class="badge bg-yellow"
data-toggle="tooltip" title=
"3 New Messages">3</span>
<button class="btn btn-box-tool fa fa-minus"
data-widget="collapse" style=
"font-style: italic"></button>
<button class=
"btn btn-box-tool fa fa-comments"
data-toggle="tooltip" data-widget=
"chat-pane-toggle" style=
"font-style: italic" title=
"Contacts"></button> <button class=
"btn btn-box-tool fa fa-times"
data-widget="remove" style=
"font-style: italic"></button>
</div>
</div><!-- /.box-header -->
<div class="box-body">
<!-- Conversations are loaded here -->
<div class="direct-chat-messages">
<!-- Message. Default to the left -->
<div class="direct-chat-msg">
<div class=
"direct-chat-info clearfix">
<span class=
"direct-chat-name pull-left">Alexander
Pierce</span> <span class=
"direct-chat-timestamp pull-right">
23 Jan 2:00 pm</span>
</div><!-- /.direct-chat-info -->
<img alt="message user image"
class="direct-chat-img" src=
"./img/user1-128x128.jpg">
<!-- /.direct-chat-img -->
<div class="direct-chat-text">
Is this template really for
free? That's unbelievable!
</div><!-- /.direct-chat-text -->
</div><!-- /.direct-chat-msg -->
<!-- Message to the right -->
<div class="direct-chat-msg right">
<div class=
"direct-chat-info clearfix">
<span class=
"direct-chat-name pull-right">Sarah
Bullock</span> <span class=
"direct-chat-timestamp pull-left">
23 Jan 2:05 pm</span>
</div><!-- /.direct-chat-info -->
<img alt="message user image"
class="direct-chat-img" src=
"./img/user3-128x128.jpg">
<!-- /.direct-chat-img -->
<div class="direct-chat-text">
You better believe it!
</div><!-- /.direct-chat-text -->
</div><!-- /.direct-chat-msg -->
<!-- Message. Default to the left -->
<div class="direct-chat-msg">
<div class=
"direct-chat-info clearfix">
<span class=
"direct-chat-name pull-left">Alexander
Pierce</span> <span class=
"direct-chat-timestamp pull-right">
23 Jan 5:37 pm</span>
</div><!-- /.direct-chat-info -->
<img alt="message user image"
class="direct-chat-img" src=
"./img/user1-128x128.jpg">
<!-- /.direct-chat-img -->
<div class="direct-chat-text">
Working with AdminLTE on a
great new app! Wanna join?
</div><!-- /.direct-chat-text -->
</div><!-- /.direct-chat-msg -->
<!-- Message to the right -->
<div class="direct-chat-msg right">
<div class=
"direct-chat-info clearfix">
<span class=
"direct-chat-name pull-right">Sarah
Bullock</span> <span class=
"direct-chat-timestamp pull-left">
23 Jan 6:10 pm</span>
</div><!-- /.direct-chat-info -->
<img alt="message user image"
class="direct-chat-img" src=
"./img/user3-128x128.jpg">
<!-- /.direct-chat-img -->
<div class="direct-chat-text">
I would love to.
</div><!-- /.direct-chat-text -->
</div><!-- /.direct-chat-msg -->
</div><!--/.direct-chat-messages-->
<!-- Contacts are loaded here -->
<div class="direct-chat-contacts">
<ul class="contacts-list">
<li>
<a href=
"https://almsaeedstudio.com/themes/AdminLTE/index2.html#">
<img class="contacts-list-img"
src="./img/user1-128x128.jpg">
<div class=
"contacts-list-info">
<span class=
"contacts-list-name">Count
Dracula <small class=
"contacts-list-date pull-right">
2/28/2015</small></span>
<span class=
"contacts-list-msg">How
have you been? I
was...</span>
</div>
<!-- /.contacts-list-info --></a>
</li><!-- End Contact Item -->
<li>
<a href=
"https://almsaeedstudio.com/themes/AdminLTE/index2.html#">
<img class="contacts-list-img"
src="./img/user7-128x128.jpg">
<div class=
"contacts-list-info">
<span class=
"contacts-list-name">Sarah
Doe <small class=
"contacts-list-date pull-right">
2/23/2015</small></span>
<span class=
"contacts-list-msg">I will
be waiting for...</span>
</div>
<!-- /.contacts-list-info --></a>
</li><!-- End Contact Item -->
<li>
<a href=
"https://almsaeedstudio.com/themes/AdminLTE/index2.html#">
<img class="contacts-list-img"
src="./img/user3-128x128.jpg">
<div class=
"contacts-list-info">
<span class=
"contacts-list-name">Nadia
Jolie <small class=
"contacts-list-date pull-right">
2/20/2015</small></span>
<span class=
"contacts-list-msg">I'll
call you back at...</span>
</div>
<!-- /.contacts-list-info --></a>
</li><!-- End Contact Item -->
<li>
<a href=
"https://almsaeedstudio.com/themes/AdminLTE/index2.html#">
<img class="contacts-list-img"
src="./img/user5-128x128.jpg">
<div class=
"contacts-list-info">
<span class=
"contacts-list-name">Nora
S. Vans <small class=
"contacts-list-date pull-right">
2/10/2015</small></span>
<span class=
"contacts-list-msg">Where
is your new...</span>
</div>
<!-- /.contacts-list-info --></a>
</li><!-- End Contact Item -->
<li>
<a href=
"https://almsaeedstudio.com/themes/AdminLTE/index2.html#">
<img class="contacts-list-img"
src="./img/user6-128x128.jpg">
<div class=
"contacts-list-info">
<span class=
"contacts-list-name">John
K. <small class=
"contacts-list-date pull-right">
1/27/2015</small></span>
<span class=
"contacts-list-msg">Can I
take a look at...</span>
</div>
<!-- /.contacts-list-info --></a>
</li><!-- End Contact Item -->
<li>
<a href=
"https://almsaeedstudio.com/themes/AdminLTE/index2.html#">
<img class="contacts-list-img"
src="./img/user8-128x128.jpg">
<div class=
"contacts-list-info">
<span class=
"contacts-list-name">Kenneth
M. <small class=
"contacts-list-date pull-right">
1/4/2015</small></span>
<span class=
"contacts-list-msg">Never
mind I found...</span>
</div>
<!-- /.contacts-list-info --></a>
</li><!-- End Contact Item -->
</ul><!-- /.contatcts-list -->
</div><!-- /.direct-chat-pane -->
</div><!-- /.box-body -->
<div class="box-footer">
<form action=
"https://almsaeedstudio.com/themes/AdminLTE/index2.html#"
method="post">
<div class="input-group">
<input class="form-control" name=
"message" placeholder=
"Type Message ..." type="text">
<span class=
"input-group-btn"><button class=
"btn btn-warning btn-flat" type=
"button"><span class=
"input-group-btn">Send</span></button></span>
</div>
</form>
</div><!-- /.box-footer-->
</div><!--/.direct-chat -->
</div><!-- /.col -->
<div class="col-md-6">
<!-- USERS LIST -->
<div class="box box-danger">
<div class="box-header with-border">
<h3 class="box-title">Latest Members</h3>
<div class="box-tools pull-right">
<span class="label label-danger">8 New
Members</span> <button class=
"btn btn-box-tool fa fa-minus"
data-widget="collapse" style=
"font-style: italic"></button>
<button class=
"btn btn-box-tool fa fa-times"
data-widget="remove" style=
"font-style: italic"></button>
</div>
</div><!-- /.box-header -->
<div class="box-body no-padding">
<ul class="users-list clearfix">
<li>
<img alt="User Image" src=
"./img/user1-128x128.jpg">
<a class="users-list-name" href=
"https://almsaeedstudio.com/themes/AdminLTE/index2.html#">
Alexander Pierce</a> <span class=
"users-list-date">Today</span>
</li>
<li>
<img alt="User Image" src=
"./img/user8-128x128.jpg">
<a class="users-list-name" href=
"https://almsaeedstudio.com/themes/AdminLTE/index2.html#">
Norman</a> <span class=
"users-list-date">Yesterday</span>
</li>
<li>
<img alt="User Image" src=
"./img/user7-128x128.jpg">
<a class="users-list-name" href=
"https://almsaeedstudio.com/themes/AdminLTE/index2.html#">
Jane</a> <span class=
"users-list-date">12 Jan</span>
</li>
<li>
<img alt="User Image" src=
"./img/user6-128x128.jpg">
<a class="users-list-name" href=
"https://almsaeedstudio.com/themes/AdminLTE/index2.html#">
John</a> <span class=
"users-list-date">12 Jan</span>
</li>
<li>
<img alt="User Image" src=
"./img/user2-160x160.jpg">
<a class="users-list-name" href=
"https://almsaeedstudio.com/themes/AdminLTE/index2.html#">
Alexander</a> <span class=
"users-list-date">13 Jan</span>
</li>
<li>
<img alt="User Image" src=
"./img/user5-128x128.jpg">
<a class="users-list-name" href=
"https://almsaeedstudio.com/themes/AdminLTE/index2.html#">
Sarah</a> <span class=
"users-list-date">14 Jan</span>
</li>
<li>
<img alt="User Image" src=
"./img/user4-128x128.jpg">
<a class="users-list-name" href=
"https://almsaeedstudio.com/themes/AdminLTE/index2.html#">
Nora</a> <span class=
"users-list-date">15 Jan</span>
</li>
<li>
<img alt="User Image" src=
"./img/user3-128x128.jpg">
<a class="users-list-name" href=
"https://almsaeedstudio.com/themes/AdminLTE/index2.html#">
Nadia</a> <span class=
"users-list-date">15 Jan</span>
</li>
</ul><!-- /.users-list -->
</div><!-- /.box-body -->
<div class="box-footer text-center">
<a class="uppercase" href=
"javascript::">View All Users</a>
</div><!-- /.box-footer -->
</div><!--/.box -->
</div><!-- /.col -->
</div><!-- /.row -->
<!-- TABLE: LATEST ORDERS -->
<div class="box box-info">
<div class="box-header with-border">
<h3 class="box-title">Latest Orders</h3>
<div class="box-tools pull-right">
<button class="btn btn-box-tool fa fa-minus"
data-widget="collapse" style=
"font-style: italic"></button> <button class=
"btn btn-box-tool fa fa-times" data-widget=
"remove" style="font-style: italic"></button>
</div>
</div><!-- /.box-header -->
<div class="box-body">
<div class="table-responsive">
<table class="table no-margin">
<thead>
<tr>
<th>Order ID</th>
<th>Item</th>
<th>Status</th>
<th>Popularity</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<a href=
"https://almsaeedstudio.com/themes/AdminLTE/pages/examples/invoice.html">
OR9842</a>
</td>
<td>Call of Duty IV</td>
<td><span class=
"label label-success">Shipped</span></td>
<td>
<div class="sparkbar"
data-color="#00a65a"
data-height="20">
<canvas height="20" style=
"display: inline-block; width: 34px; height: 20px; vertical-align: top;"
width="34"></canvas>
</div>
</td>
</tr>
<tr>
<td>
<a href=
"https://almsaeedstudio.com/themes/AdminLTE/pages/examples/invoice.html">
OR1848</a>
</td>
<td>Samsung Smart TV</td>
<td><span class=
"label label-warning">Pending</span></td>
<td>
<div class="sparkbar"
data-color="#f39c12"
data-height="20">
<canvas height="20" style=
"display: inline-block; width: 34px; height: 20px; vertical-align: top;"
width="34"></canvas>
</div>
</td>
</tr>
<tr>
<td>
<a href=
"https://almsaeedstudio.com/themes/AdminLTE/pages/examples/invoice.html">
OR7429</a>
</td>
<td>iPhone 6 Plus</td>
<td><span class=
"label label-danger">Delivered</span></td>
<td>
<div class="sparkbar"
data-color="#f56954"
data-height="20">
<canvas height="20" style=
"display: inline-block; width: 34px; height: 20px; vertical-align: top;"
width="34"></canvas>
</div>
</td>
</tr>
<tr>
<td>
<a href=
"https://almsaeedstudio.com/themes/AdminLTE/pages/examples/invoice.html">
OR7429</a>
</td>
<td>Samsung Smart TV</td>
<td><span class=
"label label-info">Processing</span></td>
<td>
<div class="sparkbar"
data-color="#00c0ef"
data-height="20">
<canvas height="20" style=
"display: inline-block; width: 34px; height: 20px; vertical-align: top;"
width="34"></canvas>
</div>
</td>
</tr>
<tr>
<td>
<a href=
"https://almsaeedstudio.com/themes/AdminLTE/pages/examples/invoice.html">
OR1848</a>
</td>
<td>Samsung Smart TV</td>
<td><span class=
"label label-warning">Pending</span></td>
<td>
<div class="sparkbar"
data-color="#f39c12"
data-height="20">
<canvas height="20" style=
"display: inline-block; width: 34px; height: 20px; vertical-align: top;"
width="34"></canvas>
</div>
</td>
</tr>
<tr>
<td>
<a href=
"https://almsaeedstudio.com/themes/AdminLTE/pages/examples/invoice.html">
OR7429</a>
</td>
<td>iPhone 6 Plus</td>
<td><span class=
"label label-danger">Delivered</span></td>
<td>
<div class="sparkbar"
data-color="#f56954"
data-height="20">
<canvas height="20" style=
"display: inline-block; width: 34px; height: 20px; vertical-align: top;"
width="34"></canvas>
</div>
</td>
</tr>
<tr>
<td>
<a href=
"https://almsaeedstudio.com/themes/AdminLTE/pages/examples/invoice.html">
OR9842</a>
</td>
<td>Call of Duty IV</td>
<td><span class=
"label label-success">Shipped</span></td>
<td>
<div class="sparkbar"
data-color="#00a65a"
data-height="20">
<canvas height="20" style=
"display: inline-block; width: 34px; height: 20px; vertical-align: top;"
width="34"></canvas>
</div>
</td>
</tr>
</tbody>
</table>
</div><!-- /.table-responsive -->
</div><!-- /.box-body -->
<div class="box-footer clearfix">
<a class="btn btn-sm btn-info btn-flat pull-left"
href="javascript::;">Place New Order</a> <a class=
"btn btn-sm btn-default btn-flat pull-right" href=
"javascript::;">View All Orders</a>
</div><!-- /.box-footer -->
</div><!-- /.box -->
</div><!-- /.col -->
<div class="col-md-4">
<!-- Info Boxes Style 2 -->
<div class="info-box bg-yellow">
<span class=
"info-box-icon ion ion-ios-pricetag-outline" style=
"font-style: italic"></span>
<div class="info-box-content">
<span class="info-box-text">Inventory</span>
<span class="info-box-number">5,200</span>
<div class="progress">
<div class="progress-bar" style="width: 50%">
</div>
</div><span class="progress-description">50%
Increase in 30 Days</span>
</div><!-- /.info-box-content -->
</div><!-- /.info-box -->
<div class="info-box bg-green">
<span class="info-box-icon ion ion-ios-heart-outline"
style="font-style: italic"></span>
<div class="info-box-content">
<span class="info-box-text">Mentions</span>
<span class="info-box-number">92,050</span>
<div class="progress">
<div class="progress-bar" style="width: 20%">
</div>
</div><span class="progress-description">20%
Increase in 30 Days</span>
</div><!-- /.info-box-content -->
</div><!-- /.info-box -->
<div class="info-box bg-red">
<span class=
"info-box-icon ion ion-ios-cloud-download-outline"
style="font-style: italic"></span>
<div class="info-box-content">
<span class="info-box-text">Downloads</span>
<span class="info-box-number">114,381</span>
<div class="progress">
<div class="progress-bar" style="width: 70%">
</div>
</div><span class="progress-description">70%
Increase in 30 Days</span>
</div><!-- /.info-box-content -->
</div><!-- /.info-box -->
<div class="info-box bg-aqua">
<span class="info-box-icon ion-ios-chatbubble-outline"
style="font-style: italic"></span>
<div class="info-box-content">
<span class="info-box-text">Direct Messages</span>
<span class="info-box-number">163,921</span>
<div class="progress">
<div class="progress-bar" style="width: 40%">
</div>
</div><span class="progress-description">40%
Increase in 30 Days</span>
</div><!-- /.info-box-content -->
</div><!-- /.info-box -->
<div class="box box-default">
<div class="box-header with-border">
<h3 class="box-title">Browser Usage</h3>
<div class="box-tools pull-right">
<button class="btn btn-box-tool fa fa-minus"
data-widget="collapse" style=
"font-style: italic"></button> <button class=
"btn btn-box-tool fa fa-times" data-widget=
"remove" style="font-style: italic"></button>
</div>
</div><!-- /.box-header -->
<div class="box-body">
<div class="row">
<div class="col-md-8">
<div class="chart-responsive">
<canvas height="160" id="pieChart"
style="width: 129px; height: 160px;"
width="129"></canvas>
</div><!-- ./chart-responsive -->
</div><!-- /.col -->
<div class="col-md-4">
<ul class="chart-legend clearfix">
<li><i class=
"fa fa-circle-o text-red"></i>
Chrome</li>
<li><i class=
"fa fa-circle-o text-green"></i>
IE</li>
<li><i class=
"fa fa-circle-o text-yellow"></i>
FireFox</li>
<li><i class=
"fa fa-circle-o text-aqua"></i>
Safari</li>
<li><i class=
"fa fa-circle-o text-light-blue"></i>
Opera</li>
<li><i class=
"fa fa-circle-o text-gray"></i>
Navigator</li>
</ul>
</div><!-- /.col -->
</div><!-- /.row -->
</div><!-- /.box-body -->
<div class="box-footer no-padding">
<ul class="nav nav-pills nav-stacked">
<li>
<a href=
"https://almsaeedstudio.com/themes/AdminLTE/index2.html#">
United States of America <span class=
"pull-right text-red"><i class=
"fa fa-angle-down"></i> 12%</span></a>
</li>
<li>
<a href=
"https://almsaeedstudio.com/themes/AdminLTE/index2.html#">
India <span class=
"pull-right text-green"><i class=
"fa fa-angle-up"></i> 4%</span></a>
</li>
<li>
<a href=
"https://almsaeedstudio.com/themes/AdminLTE/index2.html#">
China <span class=
"pull-right text-yellow"><i class=
"fa fa-angle-left"></i> 0%</span></a>
</li>
</ul>
</div><!-- /.footer -->
</div><!-- /.box -->
<!-- PRODUCT LIST -->
<div class="box box-primary">
<div class="box-header with-border">
<h3 class="box-title">Recently Added Products</h3>
<div class="box-tools pull-right">
<button class="btn btn-box-tool fa fa-minus"
data-widget="collapse" style=
"font-style: italic"></button> <button class=
"btn btn-box-tool fa fa-times" data-widget=
"remove" style="font-style: italic"></button>
</div>
</div><!-- /.box-header -->
<div class="box-body">
<ul class="products-list product-list-in-box">
<li class="item">
<div class="product-img"><img alt=
"Product Image" src=
"./img/default-50x50.gif"></div>
<div class="product-info">
<a class="product-title" href=
"javascript::;">Samsung TV <span class=
"label label-warning pull-right">$1800</span></a>
<span class=
"product-description">Samsung 32" 1080p
60Hz LED Smart HDTV.</span>
</div>
</li><!-- /.item -->
<li class="item">
<div class="product-img"><img alt=
"Product Image" src=
"./img/default-50x50.gif"></div>
<div class="product-info">
<a class="product-title" href=
"javascript::;">Bicycle <span class=
"label label-info pull-right">$700</span></a>
<span class="product-description">26"
Mongoose Dolomite Men's 7-speed, Navy
Blue.</span>
</div>
</li><!-- /.item -->
<li class="item">
<div class="product-img"><img alt=
"Product Image" src=
"./img/default-50x50.gif"></div>
<div class="product-info">
<a class="product-title" href=
"javascript::;">Xbox One <span class=
"label label-danger pull-right">$350</span></a>
<span class="product-description">Xbox
One Console Bundle with Halo Master
Chief Collection.</span>
</div>
</li><!-- /.item -->
<li class="item">
<div class="product-img"><img alt=
"Product Image" src=
"./img/default-50x50.gif"></div>
<div class="product-info">
<a class="product-title" href=
"javascript::;">PlayStation 4
<span class=
"label label-success pull-right">$399</span></a>
<span class=
"product-description">PlayStation 4
500GB Console (PS4)</span>
</div>
</li><!-- /.item -->
</ul>
</div><!-- /.box-body -->
<div class="box-footer text-center">
<a class="uppercase" href="javascript::;">View All
Products</a>
</div><!-- /.box-footer -->
</div><!-- /.box -->
</div><!-- /.col -->
</div><!-- /.row -->
</section><!-- /.content -->
</div>
<!-- /.content-wrapper -->
<footer class="main-footer">
<div class="pull-right hidden-xs"><b>Version</b> 2.0</div>
<strong>Copyright © 2014-2015 <a href="http://almsaeedstudio.com/">Almsaeed Studio</a>.</strong> All rights reserved.
</footer>
<!-- Control Sidebar -->
<aside class="control-sidebar control-sidebar-dark">
<!-- Create the tabs -->
<ul class="nav nav-tabs nav-justified control-sidebar-tabs">
<li class="active"><a href="https://almsaeedstudio.com/themes/AdminLTE/index2.html#control-sidebar-theme-demo-options-tab" data-toggle="tab"><i class="fa fa-wrench"></i></a></li><li><a href="https://almsaeedstudio.com/themes/AdminLTE/index2.html#control-sidebar-home-tab" data-toggle="tab"><i class="fa fa-home"></i></a></li>
<li><a href="https://almsaeedstudio.com/themes/AdminLTE/index2.html#control-sidebar-settings-tab" data-toggle="tab"><i class="fa fa-gears"></i></a></li>
</ul>
<!-- Tab panes -->
<div class="tab-content">
<!-- Home tab content -->
<div class="tab-pane" id="control-sidebar-home-tab">
<h3 class="control-sidebar-heading">Recent Activity</h3>
<ul class="control-sidebar-menu">
<li>
<a href="javascript::;">
<i class="menu-icon fa fa-birthday-cake bg-red"></i>
<div class="menu-info">
<h4 class="control-sidebar-subheading">Langdon's Birthday</h4>
<p>Will be 23 on April 24th</p>
</div>
</a>
</li>
<li>
<a href="javascript::;">
<i class="menu-icon fa fa-user bg-yellow"></i>
<div class="menu-info">
<h4 class="control-sidebar-subheading">Frodo Updated His Profile</h4>
<p>New phone +1(800)555-1234</p>
</div>
</a>
</li>
<li>
<a href="javascript::;">
<i class="menu-icon fa fa-envelope-o bg-light-blue"></i>
<div class="menu-info">
<h4 class="control-sidebar-subheading">Nora Joined Mailing List</h4>
<p>nora@example.com</p>
</div>
</a>
</li>
<li>
<a href="javascript::;">
<i class="menu-icon fa fa-file-code-o bg-green"></i>
<div class="menu-info">
<h4 class="control-sidebar-subheading">Cron Job 254 Executed</h4>
<p>Execution time 5 seconds</p>
</div>
</a>
</li>
</ul><!-- /.control-sidebar-menu -->
<h3 class="control-sidebar-heading">Tasks Progress</h3>
<ul class="control-sidebar-menu">
<li>
<a href="javascript::;">
<h4 class="control-sidebar-subheading">
Custom Template Design
<span class="label label-danger pull-right">70%</span>
</h4>
<div class="progress progress-xxs">
<div class="progress-bar progress-bar-danger" style="width: 70%"></div>
</div>
</a>
</li>
<li>
<a href="javascript::;">
<h4 class="control-sidebar-subheading">
Update Resume
<span class="label label-success pull-right">95%</span>
</h4>
<div class="progress progress-xxs">
<div class="progress-bar progress-bar-success" style="width: 95%"></div>
</div>
</a>
</li>
<li>
<a href="javascript::;">
<h4 class="control-sidebar-subheading">
Laravel Integration
<span class="label label-waring pull-right">50%</span>
</h4>
<div class="progress progress-xxs">
<div class="progress-bar progress-bar-warning" style="width: 50%"></div>
</div>
</a>
</li>
<li>
<a href="javascript::;">
<h4 class="control-sidebar-subheading">
Back End Framework
<span class="label label-primary pull-right">68%</span>
</h4>
<div class="progress progress-xxs">
<div class="progress-bar progress-bar-primary" style="width: 68%"></div>
</div>
</a>
</li>
</ul><!-- /.control-sidebar-menu -->
</div>
<div id="control-sidebar-theme-demo-options-tab" class="tab-pane active">
<div>
<h4 class="control-sidebar-heading">Layout Options</h4>
<div class="form-group">
<label class="control-sidebar-subheading">
<input type="checkbox" data-layout="fixed" class="pull-right"> Fixed layout</label>
<p>Activate the fixed layout. You can't use fixed and boxed layouts together</p>
</div>
<div class="form-group">
<label class="control-sidebar-subheading">
<input type="checkbox" data-layout="layout-boxed" class="pull-right"> Boxed Layout</label>
<p>Activate the boxed layout</p>
</div>
<div class="form-group">
<label class="control-sidebar-subheading">
<input type="checkbox" data-layout="sidebar-collapse" class="pull-right"> Toggle Sidebar</label>
<p>Toggle the left sidebar's state (open or collapse)</p>
</div>
<div class="form-group">
<label class="control-sidebar-subheading">
<input type="checkbox" data-enable="expandOnHover" class="pull-right"> Sidebar Expand on Hover</label>
<p>Let the sidebar mini expand on hover</p>
</div>
<div class="form-group">
<label class="control-sidebar-subheading">
<input type="checkbox" data-controlsidebar="control-sidebar-open" class="pull-right"> Toggle Right Sidebar Slide</label>
<p>Toggle between slide over content and push content effects</p>
</div>
<div class="form-group">
<label class="control-sidebar-subheading">
<input type="checkbox" data-sidebarskin="toggle" class="pull-right"> Toggle Right Sidebar Skin</label>
<p>Toggle between dark and light skins for the right sidebar</p>
</div>
<h4 class="control-sidebar-heading">Skins</h4>
<ul class="list-unstyled clearfix">
<li style="float:left; width: 33.33333%; padding: 5px;">
<a href="javascript:void(0);" data-skin="skin-blue" style="display: block; box-shadow: 0 0 3px rgba(0,0,0,0.4)" class="clearfix full-opacity-hover">
<div><span style="display:block; width: 20%; float: left; height: 7px; background: #367fa9;"></span><span class="bg-light-blue" style="display:block; width: 80%; float: left; height: 7px;"></span>
</div>
<div><span style="display:block; width: 20%; float: left; height: 20px; background: #222d32;"></span><span style="display:block; width: 80%; float: left; height: 20px; background: #f4f5f7;"></span>
</div>
</a>
<p class="text-center no-margin">Blue</p>
</li>
<li style="float:left; width: 33.33333%; padding: 5px;">
<a href="javascript:void(0);" data-skin="skin-black" style="display: block; box-shadow: 0 0 3px rgba(0,0,0,0.4)" class="clearfix full-opacity-hover">
<div style="box-shadow: 0 0 2px rgba(0,0,0,0.1)" class="clearfix"><span style="display:block; width: 20%; float: left; height: 7px; background: #fefefe;"></span><span style="display:block; width: 80%; float: left; height: 7px; background: #fefefe;"></span>
</div>
<div><span style="display:block; width: 20%; float: left; height: 20px; background: #222;"></span><span style="display:block; width: 80%; float: left; height: 20px; background: #f4f5f7;"></span>
</div>
</a>
<p class="text-center no-margin">Black</p>
</li>
<li style="float:left; width: 33.33333%; padding: 5px;">
<a href="javascript:void(0);" data-skin="skin-purple" style="display: block; box-shadow: 0 0 3px rgba(0,0,0,0.4)" class="clearfix full-opacity-hover">
<div><span style="display:block; width: 20%; float: left; height: 7px;" class="bg-purple-active"></span><span class="bg-purple" style="display:block; width: 80%; float: left; height: 7px;"></span>
</div>
<div><span style="display:block; width: 20%; float: left; height: 20px; background: #222d32;"></span><span style="display:block; width: 80%; float: left; height: 20px; background: #f4f5f7;"></span>
</div>
</a>
<p class="text-center no-margin">Purple</p>
</li>
<li style="float:left; width: 33.33333%; padding: 5px;">
<a href="javascript:void(0);" data-skin="skin-green" style="display: block; box-shadow: 0 0 3px rgba(0,0,0,0.4)" class="clearfix full-opacity-hover">
<div><span style="display:block; width: 20%; float: left; height: 7px;" class="bg-green-active"></span><span class="bg-green" style="display:block; width: 80%; float: left; height: 7px;"></span>
</div>
<div><span style="display:block; width: 20%; float: left; height: 20px; background: #222d32;"></span><span style="display:block; width: 80%; float: left; height: 20px; background: #f4f5f7;"></span>
</div>
</a>
<p class="text-center no-margin">Green</p>
</li>
<li style="float:left; width: 33.33333%; padding: 5px;">
<a href="javascript:void(0);" data-skin="skin-red" style="display: block; box-shadow: 0 0 3px rgba(0,0,0,0.4)" class="clearfix full-opacity-hover">
<div><span style="display:block; width: 20%; float: left; height: 7px;" class="bg-red-active"></span><span class="bg-red" style="display:block; width: 80%; float: left; height: 7px;"></span>
</div>
<div><span style="display:block; width: 20%; float: left; height: 20px; background: #222d32;"></span><span style="display:block; width: 80%; float: left; height: 20px; background: #f4f5f7;"></span>
</div>
</a>
<p class="text-center no-margin">Red</p>
</li>
<li style="float:left; width: 33.33333%; padding: 5px;">
<a href="javascript:void(0);" data-skin="skin-yellow" style="display: block; box-shadow: 0 0 3px rgba(0,0,0,0.4)" class="clearfix full-opacity-hover">
<div><span style="display:block; width: 20%; float: left; height: 7px;" class="bg-yellow-active"></span><span class="bg-yellow" style="display:block; width: 80%; float: left; height: 7px;"></span>
</div>
<div><span style="display:block; width: 20%; float: left; height: 20px; background: #222d32;"></span><span style="display:block; width: 80%; float: left; height: 20px; background: #f4f5f7;"></span>
</div>
</a>
<p class="text-center no-margin">Yellow</p>
</li>
<li style="float:left; width: 33.33333%; padding: 5px;">
<a href="javascript:void(0);" data-skin="skin-blue-light" style="display: block; box-shadow: 0 0 3px rgba(0,0,0,0.4)" class="clearfix full-opacity-hover">
<div><span style="display:block; width: 20%; float: left; height: 7px; background: #367fa9;"></span><span class="bg-light-blue" style="display:block; width: 80%; float: left; height: 7px;"></span>
</div>
<div><span style="display:block; width: 20%; float: left; height: 20px; background: #f9fafc;"></span><span style="display:block; width: 80%; float: left; height: 20px; background: #f4f5f7;"></span>
</div>
</a>
<p class="text-center no-margin" style="font-size: 12px">Blue Light</p>
</li>
<li style="float:left; width: 33.33333%; padding: 5px;">
<a href="javascript:void(0);" data-skin="skin-black-light" style="display: block; box-shadow: 0 0 3px rgba(0,0,0,0.4)" class="clearfix full-opacity-hover">
<div style="box-shadow: 0 0 2px rgba(0,0,0,0.1)" class="clearfix"><span style="display:block; width: 20%; float: left; height: 7px; background: #fefefe;"></span><span style="display:block; width: 80%; float: left; height: 7px; background: #fefefe;"></span>
</div>
<div><span style="display:block; width: 20%; float: left; height: 20px; background: #f9fafc;"></span><span style="display:block; width: 80%; float: left; height: 20px; background: #f4f5f7;"></span>
</div>
</a>
<p class="text-center no-margin" style="font-size: 12px">Black Light</p>
</li>
<li style="float:left; width: 33.33333%; padding: 5px;">
<a href="javascript:void(0);" data-skin="skin-purple-light" style="display: block; box-shadow: 0 0 3px rgba(0,0,0,0.4)" class="clearfix full-opacity-hover">
<div><span style="display:block; width: 20%; float: left; height: 7px;" class="bg-purple-active"></span><span class="bg-purple" style="display:block; width: 80%; float: left; height: 7px;"></span>
</div>
<div><span style="display:block; width: 20%; float: left; height: 20px; background: #f9fafc;"></span><span style="display:block; width: 80%; float: left; height: 20px; background: #f4f5f7;"></span>
</div>
</a>
<p class="text-center no-margin" style="font-size: 12px">Purple Light</p>
</li>
<li style="float:left; width: 33.33333%; padding: 5px;">
<a href="javascript:void(0);" data-skin="skin-green-light" style="display: block; box-shadow: 0 0 3px rgba(0,0,0,0.4)" class="clearfix full-opacity-hover">
<div><span style="display:block; width: 20%; float: left; height: 7px;" class="bg-green-active"></span><span class="bg-green" style="display:block; width: 80%; float: left; height: 7px;"></span>
</div>
<div><span style="display:block; width: 20%; float: left; height: 20px; background: #f9fafc;"></span><span style="display:block; width: 80%; float: left; height: 20px; background: #f4f5f7;"></span>
</div>
</a>
<p class="text-center no-margin" style="font-size: 12px">Green Light</p>
</li>
<li style="float:left; width: 33.33333%; padding: 5px;">
<a href="javascript:void(0);" data-skin="skin-red-light" style="display: block; box-shadow: 0 0 3px rgba(0,0,0,0.4)" class="clearfix full-opacity-hover">
<div><span style="display:block; width: 20%; float: left; height: 7px;" class="bg-red-active"></span><span class="bg-red" style="display:block; width: 80%; float: left; height: 7px;"></span>
</div>
<div><span style="display:block; width: 20%; float: left; height: 20px; background: #f9fafc;"></span><span style="display:block; width: 80%; float: left; height: 20px; background: #f4f5f7;"></span>
</div>
</a>
<p class="text-center no-margin" style="font-size: 12px">Red Light</p>
</li>
<li style="float:left; width: 33.33333%; padding: 5px;">
<a href="javascript:void(0);" data-skin="skin-yellow-light" style="display: block; box-shadow: 0 0 3px rgba(0,0,0,0.4)" class="clearfix full-opacity-hover">
<div><span style="display:block; width: 20%; float: left; height: 7px;" class="bg-yellow-active"></span><span class="bg-yellow" style="display:block; width: 80%; float: left; height: 7px;"></span>
</div>
<div><span style="display:block; width: 20%; float: left; height: 20px; background: #f9fafc;"></span><span style="display:block; width: 80%; float: left; height: 20px; background: #f4f5f7;"></span>
</div>
</a>
<p class="text-center no-margin" style="font-size: 12px;">Yellow Light</p>
</li>
</ul>
</div>
</div><!-- /.tab-pane -->
<!-- Settings tab content -->
<div class="tab-pane" id="control-sidebar-settings-tab">
<form method="post">
<h3 class="control-sidebar-heading">General Settings</h3>
<div class="form-group">
<label class="control-sidebar-subheading">
Report panel usage
<input type="checkbox" class="pull-right" checked="">
</label>
<p>
Some information about this general settings option
</p>
</div><!-- /.form-group -->
<div class="form-group">
<label class="control-sidebar-subheading">
Allow mail redirect
<input type="checkbox" class="pull-right" checked="">
</label>
<p>
Other sets of options are available
</p>
</div><!-- /.form-group -->
<div class="form-group">
<label class="control-sidebar-subheading">
Expose author name in posts
<input type="checkbox" class="pull-right" checked="">
</label>
<p>
Allow the user to show his name in blog posts
</p>
</div><!-- /.form-group -->
<h3 class="control-sidebar-heading">Chat Settings</h3>
<div class="form-group">
<label class="control-sidebar-subheading">
Show me as online
<input type="checkbox" class="pull-right" checked="">
</label>
</div><!-- /.form-group -->
<div class="form-group">
<label class="control-sidebar-subheading">
Turn off notifications
<input type="checkbox" class="pull-right">
</label>
</div><!-- /.form-group -->
<div class="form-group">
<label class="control-sidebar-subheading">
Delete chat history
<a href="javascript::;" class="text-red pull-right"><i class="fa fa-trash-o"></i></a>
</label>
</div><!-- /.form-group -->
</form>
</div><!-- /.tab-pane -->
</div>
</aside>
<!-- /.control-sidebar -->
<!-- Add the sidebar's background. This div must be placed
immediately after the control sidebar -->
<div class="control-sidebar-bg" style="position: fixed; height: auto;"></div>
</div>
</body>
</html> | apache-2.0 |
lunisolar/magma | magma-asserts/src/test/java/eu/lunisolar/magma/asserts/func/function/to/LToFltFunctionAssertTest.java | 4436 | /*
* This file is part of "lunisolar-magma".
*
* (C) Copyright 2014-2019 Lunisolar (http://lunisolar.eu/).
*
* 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 eu.lunisolar.magma.asserts.func.function.to;
import eu.lunisolar.magma.func.*; // NOSONAR
import javax.annotation.Nonnull; // NOSONAR
import javax.annotation.Nullable; // NOSONAR
import java.util.Objects;// NOSONAR
import eu.lunisolar.magma.basics.meta.*; // NOSONAR
import eu.lunisolar.magma.basics.meta.functional.*; // NOSONAR
import eu.lunisolar.magma.basics.meta.functional.type.*; // NOSONAR
import eu.lunisolar.magma.basics.meta.functional.domain.*; // NOSONAR
import eu.lunisolar.magma.asserts.DefaultAttests;
import eu.lunisolar.magma.func.function.to.LToFltFunction;
import org.assertj.core.api.Assertions; //NOSONAR
import org.assertj.core.api.ObjectAssert;//NOSONAR
import org.testng.annotations.*; //NOSONAR
import java.util.regex.Pattern; //NOSONAR
import java.text.ParseException; //NOSONAR
import eu.lunisolar.magma.basics.exceptions.*; //NOSONAR
import java.util.concurrent.atomic.*; //NOSONAR
import static org.assertj.core.api.Assertions.*; //NOSONAR
import java.util.function.*; //NOSONAR
@SuppressWarnings("ALL")
public class LToFltFunctionAssertTest<T> {
private float testValue = 100f;
@SuppressWarnings("unchecked") public static final DefaultAttests<ObjectAssert> A = new DefaultAttests() {
};
private LToFltFunction<Integer> function = a ->
testValue;
private LToFltFunction<Integer> functionThrowing = a -> {
throw new UnsupportedOperationException();
};
@Test
public void testAssertPositive() throws ParseException {
A.attestToFltFunc(function)
.doesApplyAsFlt(100)
.to(a -> a.isEqualTo(testValue));
}
@Test(expectedExceptions = AssertionError.class)
public void testAssertNegative() throws ParseException {
A.attestToFltFunc(function)
.doesApplyAsFlt(100)
.to( a -> a.isEqualTo(2));
}
@Test(expectedExceptions = AssertionError.class, expectedExceptionsMessageRegExp = "Case .* should evaluate without problem.")
public void testAssertThrowsUnexpected() throws ParseException {
A.attestToFltFunc(functionThrowing)
.doesApplyAsFlt(100)
.to( a -> a.isEqualTo(1));
}
@Test
public void testAssertThrowsExpected() throws ParseException {
A.attestToFltFunc(functionThrowing)
.doesApplyAsFlt(100).withException(a -> a
.isExactlyInstanceOf(UnsupportedOperationException.class)
.hasMessage(null));
}
@Test
public void testRecurringAssertsPositive() throws ParseException {
final AtomicInteger recurringAssertsCalls = new AtomicInteger(0);
A.attestToFltFunc(function)
.inAllFollowingCases(a-> {
recurringAssertsCalls.incrementAndGet();
a.isEqualTo(testValue);
})
.doesApplyAsFlt(100)
.to(a -> a.isEqualTo(testValue))
.doesApplyAsFlt(100)
.to(a -> a.isEqualTo(testValue));
assertThat(recurringAssertsCalls.get()).isEqualTo(2);
}
@Test(expectedExceptions = AssertionError.class, expectedExceptionsMessageRegExp = "(?s).*Recurring assertion failed.*")
public void testRecurringAssertsNegative() throws ParseException {
final AtomicInteger recurringAssertsCalls = new AtomicInteger(0);
A.attestToFltFunc(function)
.inAllFollowingCases(a-> {
int i = recurringAssertsCalls.incrementAndGet();
if (i>1) {
a.isEqualTo(0);
}
})
.doesApplyAsFlt(100)
.to(a -> a.isEqualTo(testValue))
.doesApplyAsFlt(100)
.to(a -> a.isEqualTo(testValue));
assertThat(recurringAssertsCalls.get()).isEqualTo(2);
}
}
| apache-2.0 |
wmm387/wmm | app/src/main/java/com/wangyuanwmm/wmm/entity/TopData.java | 608 | package com.wangyuanwmm.wmm.entity;
public class TopData {
//标题
private String title;
//出处
private String source;
//图片的url
private String imgUrl;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getSource() {
return source;
}
public void setSource(String source) {
this.source = source;
}
public String getImgUrl() {
return imgUrl;
}
public void setImgUrl(String imgUrl) {
this.imgUrl = imgUrl;
}
}
| apache-2.0 |
ngageoint/scale | scale/scheduler/test/database/test_updater.py | 689 | from __future__ import unicode_literals
import copy
from datetime import timedelta
import django
from django.test import TestCase
from django.utils.timezone import now
from batch.definition.definition import BatchDefinition
from batch.test import utils as batch_test_utils
from batch.models import Batch
from job.models import Job, JobExecution, TaskUpdate
from job.test import utils as job_test_utils
from recipe.models import Recipe, RecipeTypeRevision
from recipe.test import utils as recipe_test_utils
from scheduler.database.updater import DatabaseUpdater
class TestDatabaseUpdater(TestCase):
fixtures = ['batch_job_types.json']
def setUp(self):
django.setup()
| apache-2.0 |
saandrews/pulsar | pulsar-connect/rabbitmq/src/main/java/org/apache/pulsar/connect/rabbitmq/RabbitMQSource.java | 3980 | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.apache.pulsar.connect.rabbitmq;
import com.rabbitmq.client.*;
import org.apache.pulsar.connect.core.Message;
import org.apache.pulsar.connect.core.PushSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.function.Function;
/**
* A simple connector to consume messages from a RabbitMQ queue
*/
public class RabbitMQSource implements PushSource<byte[]> {
private static Logger logger = LoggerFactory.getLogger(RabbitMQSource.class);
private Function<Message<byte[]>, CompletableFuture<Void>> consumer;
private Connection rabbitMQConnection;
private Channel rabbitMQChannel;
private RabbitMQConfig rabbitMQConfig;
@Override
public void setConsumer(Function<Message<byte[]>, CompletableFuture<Void>> consumeFunction) {
this.consumer = consumeFunction;
}
@Override
public void open(Map<String, String> config) throws Exception {
rabbitMQConfig = RabbitMQConfig.load(config);
if (rabbitMQConfig.getAmqUri() == null
|| rabbitMQConfig.getQueueName() == null) {
throw new IllegalArgumentException("Required property not set.");
}
ConnectionFactory connectionFactory = new ConnectionFactory();
connectionFactory.setUri(rabbitMQConfig.getAmqUri());
rabbitMQConnection = connectionFactory.newConnection(rabbitMQConfig.getConnectionName());
logger.info("A new connection to {}:{} has been opened successfully.",
rabbitMQConnection.getAddress().getCanonicalHostName(),
rabbitMQConnection.getPort()
);
rabbitMQChannel = rabbitMQConnection.createChannel();
rabbitMQChannel.queueDeclare(rabbitMQConfig.getQueueName(), false, false, false, null);
com.rabbitmq.client.Consumer consumer = new RabbitMQConsumer(this.consumer, rabbitMQChannel);
rabbitMQChannel.basicConsume(rabbitMQConfig.getQueueName(), consumer);
logger.info("A consumer for queue {} has been successfully started.", rabbitMQConfig.getQueueName());
}
@Override
public void close() throws Exception {
rabbitMQChannel.close();
rabbitMQConnection.close();
}
private class RabbitMQConsumer extends DefaultConsumer {
private Function<Message<byte[]>, CompletableFuture<Void>> consumeFunction;
public RabbitMQConsumer(Function<Message<byte[]>, CompletableFuture<Void>> consumeFunction, Channel channel) {
super(channel);
this.consumeFunction = consumeFunction;
}
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
consumeFunction.apply(new RabbitMQMessage(body));
}
}
static private class RabbitMQMessage implements Message<byte[]> {
private byte[] data;
public RabbitMQMessage(byte[] data) {
this.data = data;
}
@Override
public byte[] getData() {
return data;
}
}
} | apache-2.0 |
cloudera/crunch | crunch/src/main/java/org/apache/crunch/impl/mem/collect/MemCollection.java | 5576 | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.apache.crunch.impl.mem.collect;
import java.util.Collection;
import org.apache.crunch.DoFn;
import org.apache.crunch.FilterFn;
import org.apache.crunch.MapFn;
import org.apache.crunch.PCollection;
import org.apache.crunch.PTable;
import org.apache.crunch.Pair;
import org.apache.crunch.Pipeline;
import org.apache.crunch.Target;
import org.apache.crunch.fn.ExtractKeyFn;
import org.apache.crunch.impl.mem.MemPipeline;
import org.apache.crunch.lib.Aggregate;
import org.apache.crunch.lib.Sample;
import org.apache.crunch.lib.Sort;
import org.apache.crunch.test.InMemoryEmitter;
import org.apache.crunch.types.PTableType;
import org.apache.crunch.types.PType;
import org.apache.crunch.types.PTypeFamily;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
public class MemCollection<S> implements PCollection<S> {
private final Collection<S> collect;
private final PType<S> ptype;
private String name;
public MemCollection(Iterable<S> collect) {
this(collect, null, null);
}
public MemCollection(Iterable<S> collect, PType<S> ptype) {
this(collect, ptype, null);
}
public MemCollection(Iterable<S> collect, PType<S> ptype, String name) {
this.collect = ImmutableList.copyOf(collect);
this.ptype = ptype;
this.name = name;
}
@Override
public Pipeline getPipeline() {
return MemPipeline.getInstance();
}
@Override
public PCollection<S> union(PCollection<S>... collections) {
Collection<S> output = Lists.newArrayList();
for (PCollection<S> pcollect : collections) {
for (S s : pcollect.materialize()) {
output.add(s);
}
}
output.addAll(collect);
return new MemCollection<S>(output, collections[0].getPType());
}
@Override
public <T> PCollection<T> parallelDo(DoFn<S, T> doFn, PType<T> type) {
return parallelDo(null, doFn, type);
}
@Override
public <T> PCollection<T> parallelDo(String name, DoFn<S, T> doFn, PType<T> type) {
InMemoryEmitter<T> emitter = new InMemoryEmitter<T>();
doFn.initialize();
for (S s : collect) {
doFn.process(s, emitter);
}
doFn.cleanup(emitter);
return new MemCollection<T>(emitter.getOutput(), type, name);
}
@Override
public <K, V> PTable<K, V> parallelDo(DoFn<S, Pair<K, V>> doFn, PTableType<K, V> type) {
return parallelDo(null, doFn, type);
}
@Override
public <K, V> PTable<K, V> parallelDo(String name, DoFn<S, Pair<K, V>> doFn,
PTableType<K, V> type) {
InMemoryEmitter<Pair<K, V>> emitter = new InMemoryEmitter<Pair<K, V>>();
doFn.initialize();
for (S s : collect) {
doFn.process(s, emitter);
}
doFn.cleanup(emitter);
return new MemTable<K, V>(emitter.getOutput(), type, name);
}
@Override
public PCollection<S> write(Target target) {
getPipeline().write(this, target);
return this;
}
@Override
public Iterable<S> materialize() {
return collect;
}
public Collection<S> getCollection() {
return collect;
}
@Override
public PType<S> getPType() {
return ptype;
}
@Override
public PTypeFamily getTypeFamily() {
if (ptype != null) {
return ptype.getFamily();
}
return null;
}
@Override
public long getSize() {
return collect.size();
}
@Override
public String getName() {
return name;
}
@Override
public String toString() {
return collect.toString();
}
@Override
public PTable<S, Long> count() {
return Aggregate.count(this);
}
@Override
public PCollection<S> sample(double acceptanceProbability) {
return Sample.sample(this, acceptanceProbability);
}
@Override
public PCollection<S> sample(double acceptanceProbability, long seed) {
return Sample.sample(this, seed, acceptanceProbability);
}
@Override
public PCollection<S> max() {
return Aggregate.max(this);
}
@Override
public PCollection<S> min() {
return Aggregate.min(this);
}
@Override
public PCollection<S> sort(boolean ascending) {
return Sort.sort(this, ascending ? Sort.Order.ASCENDING : Sort.Order.DESCENDING);
}
@Override
public PCollection<S> filter(FilterFn<S> filterFn) {
return parallelDo(filterFn, getPType());
}
@Override
public PCollection<S> filter(String name, FilterFn<S> filterFn) {
return parallelDo(name, filterFn, getPType());
}
@Override
public <K> PTable<K, S> by(MapFn<S, K> mapFn, PType<K> keyType) {
return parallelDo(new ExtractKeyFn<K, S>(mapFn), getTypeFamily().tableOf(keyType, getPType()));
}
@Override
public <K> PTable<K, S> by(String name, MapFn<S, K> mapFn, PType<K> keyType) {
return parallelDo(name, new ExtractKeyFn<K, S>(mapFn), getTypeFamily().tableOf(keyType, getPType()));
}
}
| apache-2.0 |
clld/autotyp | autotyp/datatables.py | 4809 | from sqlalchemy import and_
from sqlalchemy.orm import joinedload_all, joinedload, aliased
from clld.web import datatables
from clld.db.meta import DBSession
from clld.db.models.common import (
Value, ValueSet, Parameter, DomainElement, Language, Contribution, ValueSetReference,
Value_data,
)
from clld.db.util import icontains
from clld.web.datatables.base import (
DataTable, Col, LinkCol, DetailsRowLinkCol, LinkToMapCol, IdCol,
)
from clld.web.util.helpers import linked_references, map_marker_img
from clld.web.util.htmllib import HTML, literal
from autotyp.models import Languoid, Area, Continent
class ValueNameCol(LinkCol):
def get_obj(self, item):
return item.valueset
def get_attrs(self, item):
label = item.__unicode__()
title = label
return {'label': label, 'title': title}
def order(self):
return Value.name
def search(self, qs):
return icontains(Value.name, qs)
class ValueDataCol(LinkCol):
def get_obj(self, item):
return item.valueset
def get_attrs(self, item):
label = ''
for d in item.data:
if d.ord == self.index:
label = d.value
break
return {'label': label}
def __init__(self, dt, name, index, spec, **kw):
kw['sTitle'] = spec[0]
Col.__init__(self, dt, name, **kw)
self.index = index
self.choices = spec[1]
def search(self, qs):
return icontains(self.dt.vars[self.index].value, qs)
class ValueSetCol(LinkCol):
def get_obj(self, item):
return item.valueset
def get_attrs(self, item):
return {'label': item.valueset.name}
class Values(DataTable):
__constraints__ = [Parameter, Contribution, Language]
def __init__(self, req, model, eid=None, **kw):
DataTable.__init__(self, req, model, eid=eid, **kw)
self.vars = []
if self.parameter:
self.vars = [aliased(Value_data, name='var%s' % i) for i in range(len(self.parameter.jsondata['varspec']))]
def base_query(self, query):
query = query.join(ValueSet).options(
joinedload_all(Value.valueset, ValueSet.references, ValueSetReference.source)
)
if self.language:
query = query.join(ValueSet.parameter)
return query.filter(ValueSet.language_pk == self.language.pk)
if self.parameter:
for i, var in enumerate(self.vars):
query = query.join(var, and_(var.ord == i, var.object_pk == Value.pk))
query = query.join(ValueSet.language)
query = query.outerjoin(DomainElement).options(
joinedload(Value.domainelement))
return query.filter(ValueSet.parameter_pk == self.parameter.pk)
if self.contribution:
query = query.join(ValueSet.parameter)
return query.filter(ValueSet.contribution_pk == self.contribution.pk)
return query
def col_defs(self):
if self.parameter:
res = [
LinkCol(self, 'language',
model_col=Language.name, get_object=lambda i: i.valueset.language),
LinkToMapCol(self, 'm', get_object=lambda i: i.valueset.language),
]
for i, spec in enumerate(self.parameter.jsondata['varspec']):
res.append(ValueDataCol(self, 'var%s' % i, i, spec))
return res
if self.language:
return [
ValueNameCol(self, 'value'),
LinkCol(self, 'parameter', sTitle=self.req.translate('Parameter'),
model_col=Parameter.name, get_object=lambda i: i.valueset.parameter),
]
return [
ValueNameCol(self, 'value'),
ValueSetCol(self, 'valueset', bSearchable=False, bSortable=False),
]
class Languages(datatables.Languages):
def base_query(self, query):
return query.join(Area).join(Continent).options(
joinedload_all(Languoid.area, Area.continent)).distinct()
def col_defs(self):
return [
IdCol(self, 'id'),
LinkCol(self, 'name'),
LinkToMapCol(self, 'l'),
Col(self, 'latitude'),
Col(self, 'longitude'),
Col(self, 'area',
model_col=Area.name,
get_object=lambda i: i.area,
choices=[a.name for a in DBSession.query(Area)]),
Col(self, 'continent',
model_col=Continent.name,
get_object=lambda i: i.area.continent,
choices=[a.name for a in DBSession.query(Continent)]),
]
def includeme(config):
config.register_datatable('values', Values)
config.register_datatable('languages', Languages)
| apache-2.0 |
fernandoPalaciosGit/banca-personal-DAW | access/js/accessAccount/permisos.tpl.php | 497 | <div id="permissionsHouseAccountViews">
<p>{{mensaje}}</p>
<p><small>tu cuenta esta registrada con el correo: <i class="idea">{{permisosUsuario['userMail']}}</i></small></p>
<p><h2>Estos son las cuentas a los que tienes acceso</h2></p>
<ul>
<li ng-repeat-start="permiso in permisosUsuario['userPerms']">
<a href="http://localhost:3000/appAccount?ID={{permiso['ID']}}&KEY={{permiso['Key']}}">
{{permiso['Name']}}</a>
</li>
<span ng-repeat-end></span>
</ul>
</div> | apache-2.0 |
mrsimpson/vtiger-client | dist/vtiger_consumer_swagger/src/ApiClient.js | 18300 | 'use strict';
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj; };
(function (root, factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define(['superagent'], factory);
} else if ((typeof module === 'undefined' ? 'undefined' : _typeof(module)) === 'object' && module.exports) {
// CommonJS-like environments that support module.exports, like Node.
module.exports = factory(require('superagent'));
} else {
// Browser globals (root is window)
if (!root.VTigerCrm) {
root.VTigerCrm = {};
}
root.VTigerCrm.ApiClient = factory(root.superagent);
}
})(undefined, function (superagent) {
'use strict';
/**
* @module ApiClient
* @version 0.0.2
*/
/**
* Manages low level client-server communications, parameter marshalling, etc. There should not be any need for an
* application to use this class directly - the *Api and model classes provide the public API for the service. The
* contents of this file should be regarded as internal but are documented for completeness.
* @alias module:ApiClient
* @class
*/
var exports = function exports() {
/**
* The base URL against which to resolve every API call's (relative) path.
* @type {String}
* @default http://localhost/vtigercrm_dbd/webservice.php
*/
this.basePath = 'http://localhost/vtigercrm_dbd/webservice.php'.replace(/\/+$/, '');
/**
* The authentication methods to be included for all API calls.
* @type {Array.<String>}
*/
this.authentications = {};
/**
* The default HTTP headers to be included for all API calls.
* @type {Array.<String>}
* @default {}
*/
this.defaultHeaders = {};
/**
* The default HTTP timeout for all API calls.
* @type {Number}
* @default 60000
*/
this.timeout = 60000;
};
/**
* Returns a string representation for an actual parameter.
* @param param The actual parameter.
* @returns {String} The string representation of <code>param</code>.
*/
exports.prototype.paramToString = function (param) {
if (param == undefined || param == null) {
return '';
}
if (param instanceof Date) {
return param.toJSON();
}
return param.toString();
};
/**
* Builds full URL by appending the given path to the base URL and replacing path parameter place-holders with parameter values.
* NOTE: query parameters are not handled here.
* @param {String} path The path to append to the base URL.
* @param {Object} pathParams The parameter values to append.
* @returns {String} The encoded path with parameter values substituted.
*/
exports.prototype.buildUrl = function (path, pathParams) {
if (!path.match(/^\//)) {
path = '/' + path;
}
var url = this.basePath + path;
var _this = this;
url = url.replace(/\{([\w-]+)\}/g, function (fullMatch, key) {
var value;
if (pathParams.hasOwnProperty(key)) {
value = _this.paramToString(pathParams[key]);
} else {
value = fullMatch;
}
return encodeURIComponent(value);
});
return url;
};
/**
* Checks whether the given content type represents JSON.<br>
* JSON content type examples:<br>
* <ul>
* <li>application/json</li>
* <li>application/json; charset=UTF8</li>
* <li>APPLICATION/JSON</li>
* </ul>
* @param {String} contentType The MIME content type to check.
* @returns {Boolean} <code>true</code> if <code>contentType</code> represents JSON, otherwise <code>false</code>.
*/
exports.prototype.isJsonMime = function (contentType) {
return Boolean(contentType != null && contentType.match(/^application\/json(;.*)?$/i));
};
/**
* Chooses a content type from the given array, with JSON preferred; i.e. return JSON if included, otherwise return the first.
* @param {Array.<String>} contentTypes
* @returns {String} The chosen content type, preferring JSON.
*/
exports.prototype.jsonPreferredMime = function (contentTypes) {
for (var i = 0; i < contentTypes.length; i++) {
if (this.isJsonMime(contentTypes[i])) {
return contentTypes[i];
}
}
return contentTypes[0];
};
/**
* Checks whether the given parameter value represents file-like content.
* @param param The parameter to check.
* @returns {Boolean} <code>true</code> if <code>param</code> represents a file.
*/
exports.prototype.isFileParam = function (param) {
// fs.ReadStream in Node.js (but not in runtime like browserify)
if (typeof window === 'undefined' && typeof require === 'function' && require('fs') && param instanceof require('fs').ReadStream) {
return true;
}
// Buffer in Node.js
if (typeof Buffer === 'function' && param instanceof Buffer) {
return true;
}
// Blob in browser
if (typeof Blob === 'function' && param instanceof Blob) {
return true;
}
// File in browser (it seems File object is also instance of Blob, but keep this for safe)
if (typeof File === 'function' && param instanceof File) {
return true;
}
return false;
};
/**
* Normalizes parameter values:
* <ul>
* <li>remove nils</li>
* <li>keep files and arrays</li>
* <li>format to string with `paramToString` for other cases</li>
* </ul>
* @param {Object.<String, Object>} params The parameters as object properties.
* @returns {Object.<String, Object>} normalized parameters.
*/
exports.prototype.normalizeParams = function (params) {
var newParams = {};
for (var key in params) {
if (params.hasOwnProperty(key) && params[key] != undefined && params[key] != null) {
var value = params[key];
if (this.isFileParam(value) || Array.isArray(value)) {
newParams[key] = value;
} else {
newParams[key] = this.paramToString(value);
}
}
}
return newParams;
};
/**
* Enumeration of collection format separator strategies.
* @enum {String}
* @readonly
*/
exports.CollectionFormatEnum = {
/**
* Comma-separated values. Value: <code>csv</code>
* @const
*/
CSV: ',',
/**
* Space-separated values. Value: <code>ssv</code>
* @const
*/
SSV: ' ',
/**
* Tab-separated values. Value: <code>tsv</code>
* @const
*/
TSV: '\t',
/**
* Pipe(|)-separated values. Value: <code>pipes</code>
* @const
*/
PIPES: '|',
/**
* Native array. Value: <code>multi</code>
* @const
*/
MULTI: 'multi'
};
/**
* Builds a string representation of an array-type actual parameter, according to the given collection format.
* @param {Array} param An array parameter.
* @param {module:ApiClient.CollectionFormatEnum} collectionFormat The array element separator strategy.
* @returns {String|Array} A string representation of the supplied collection, using the specified delimiter. Returns
* <code>param</code> as is if <code>collectionFormat</code> is <code>multi</code>.
*/
exports.prototype.buildCollectionParam = function buildCollectionParam(param, collectionFormat) {
if (param == null) {
return null;
}
switch (collectionFormat) {
case 'csv':
return param.map(this.paramToString).join(',');
case 'ssv':
return param.map(this.paramToString).join(' ');
case 'tsv':
return param.map(this.paramToString).join('\t');
case 'pipes':
return param.map(this.paramToString).join('|');
case 'multi':
// return the array directly as SuperAgent will handle it as expected
return param.map(this.paramToString);
default:
throw new Error('Unknown collection format: ' + collectionFormat);
}
};
/**
* Applies authentication headers to the request.
* @param {Object} request The request object created by a <code>superagent()</code> call.
* @param {Array.<String>} authNames An array of authentication method names.
*/
exports.prototype.applyAuthToRequest = function (request, authNames) {
var _this = this;
authNames.forEach(function (authName) {
var auth = _this.authentications[authName];
switch (auth.type) {
case 'basic':
if (auth.username || auth.password) {
request.auth(auth.username || '', auth.password || '');
}
break;
case 'apiKey':
if (auth.apiKey) {
var data = {};
if (auth.apiKeyPrefix) {
data[auth.name] = auth.apiKeyPrefix + ' ' + auth.apiKey;
} else {
data[auth.name] = auth.apiKey;
}
if (auth['in'] === 'header') {
request.set(data);
} else {
request.query(data);
}
}
break;
case 'oauth2':
if (auth.accessToken) {
request.set({ 'Authorization': 'Bearer ' + auth.accessToken });
}
break;
default:
throw new Error('Unknown authentication type: ' + auth.type);
}
});
};
/**
* Deserializes an HTTP response body into a value of the specified type.
* @param {Object} response A SuperAgent response object.
* @param {(String|Array.<String>|Object.<String, Object>|Function)} returnType The type to return. Pass a string for simple types
* or the constructor function for a complex type. Pass an array containing the type name to return an array of that type. To
* return an object, pass an object with one property whose name is the key type and whose value is the corresponding value type:
* all properties on <code>data<code> will be converted to this type.
* @returns A value of the specified type.
*/
exports.prototype.deserialize = function deserialize(response, returnType) {
if (response == null || returnType == null) {
return null;
}
// Rely on SuperAgent for parsing response body.
// See http://visionmedia.github.io/superagent/#parsing-response-bodies
var data = response.body;
if (data == null) {
// SuperAgent does not always produce a body; use the unparsed response as a fallback
data = response.text;
}
return exports.convertToType(data, returnType);
};
/**
* Callback function to receive the result of the operation.
* @callback module:ApiClient~callApiCallback
* @param {String} error Error message, if any.
* @param data The data returned by the service call.
* @param {String} response The complete HTTP response.
*/
/**
* Invokes the REST service using the supplied settings and parameters.
* @param {String} path The base URL to invoke.
* @param {String} httpMethod The HTTP method to use.
* @param {Object.<String, String>} pathParams A map of path parameters and their values.
* @param {Object.<String, Object>} queryParams A map of query parameters and their values.
* @param {Object.<String, Object>} headerParams A map of header parameters and their values.
* @param {Object.<String, Object>} formParams A map of form parameters and their values.
* @param {Object} bodyParam The value to pass as the request body.
* @param {Array.<String>} authNames An array of authentication type names.
* @param {Array.<String>} contentTypes An array of request MIME types.
* @param {Array.<String>} accepts An array of acceptable response MIME types.
* @param {(String|Array|ObjectFunction)} returnType The required type to return; can be a string for simple types or the
* constructor for a complex type.
* @param {module:ApiClient~callApiCallback} callback The callback function.
* @returns {Object} The SuperAgent request object.
*/
exports.prototype.callApi = function callApi(path, httpMethod, pathParams, queryParams, headerParams, formParams, bodyParam, authNames, contentTypes, accepts, returnType, callback) {
//////////////////////////////////////////// Begin of modification /////////////////////////////////////////////////
// Modification of generated code by OJ: The vTiger-Endpoints are not compatible to the general way of restfully
// addressing a resource: they are services offered by an endpoint which encodes the operation. The operation is
// the first query parameter of the endpoint. As swagger doesn't support query parameters as endpoint-components,
// the YAML definition created includes the parameter as part of the path.
// In order to properly execute the HTTP-methods, we now need to re-create this part of the path as query parameter
var effectivePath = path;
var effectiveQueryParams = queryParams;
var posQuestionMark = path.search("\\?");
if (posQuestionMark !== -1) {
var paramKeyValue = effectivePath.substring(posQuestionMark + 1).split("=");
effectiveQueryParams[paramKeyValue[0]] = paramKeyValue[1];
effectivePath = effectivePath.substring(0, posQuestionMark);
}
var _this = this;
var url = this.buildUrl(effectivePath, pathParams);
var request = superagent(httpMethod, url);
// apply authentications
this.applyAuthToRequest(request, authNames);
// set query parameters
request.query(this.normalizeParams(effectiveQueryParams));
////////////////////////////////////////////// End of modification /////////////////////////////////////////////////
// set header parameters
request.set(this.defaultHeaders).set(this.normalizeParams(headerParams));
// set request timeout
request.timeout(this.timeout);
var contentType = this.jsonPreferredMime(contentTypes);
if (contentType) {
request.type(contentType);
} else if (!request.header['Content-Type']) {
request.type('application/json');
}
if (contentType === 'application/x-www-form-urlencoded') {
request.send(this.normalizeParams(formParams));
} else if (contentType == 'multipart/form-data') {
var _formParams = this.normalizeParams(formParams);
for (var key in _formParams) {
if (_formParams.hasOwnProperty(key)) {
if (this.isFileParam(_formParams[key])) {
// file field
request.attach(key, _formParams[key]);
} else {
request.field(key, _formParams[key]);
}
}
}
} else if (bodyParam) {
request.send(bodyParam);
}
var accept = this.jsonPreferredMime(accepts);
if (accept) {
request.accept(accept);
}
request.end(function (error, response) {
if (callback) {
var data = null;
if (!error) {
data = _this.deserialize(response, returnType);
}
callback(error, data, response);
}
});
return request;
};
/**
* Parses an ISO-8601 string representation of a date value.
* @param {String} str The date value as a string.
* @returns {Date} The parsed date object.
*/
exports.parseDate = function (str) {
return new Date(str.replace(/T/i, ' '));
};
/**
* Converts a value to the specified type.
* @param {(String|Object)} data The data to convert, as a string or object.
* @param {(String|Array.<String>|Object.<String, Object>|Function)} type The type to return. Pass a string for simple types
* or the constructor function for a complex type. Pass an array containing the type name to return an array of that type. To
* return an object, pass an object with one property whose name is the key type and whose value is the corresponding value type:
* all properties on <code>data<code> will be converted to this type.
* @returns An instance of the specified type.
*/
exports.convertToType = function (data, type) {
switch (type) {
case 'Boolean':
return Boolean(data);
case 'Integer':
return parseInt(data, 10);
case 'Number':
return parseFloat(data);
case 'String':
return String(data);
case 'Date':
return this.parseDate(String(data));
default:
if (type === Object) {
// generic object, return directly
return data;
} else if (typeof type === 'function') {
// for model type like: User
return type.constructFromObject(data);
} else if (Array.isArray(type)) {
// for array type like: ['String']
var itemType = type[0];
return data.map(function (item) {
return exports.convertToType(item, itemType);
});
} else if ((typeof type === 'undefined' ? 'undefined' : _typeof(type)) === 'object') {
// for plain object type like: {'String': 'Integer'}
var keyType, valueType;
for (var k in type) {
if (type.hasOwnProperty(k)) {
keyType = k;
valueType = type[k];
break;
}
}
var result = {};
for (var k in data) {
if (data.hasOwnProperty(k)) {
var key = exports.convertToType(k, keyType);
var value = exports.convertToType(data[k], valueType);
result[key] = value;
}
}
return result;
} else {
// for unknown type, return the data directly
return data;
}
}
};
/**
* Constructs a new map or array model from REST data.
* @param data {Object|Array} The REST data.
* @param obj {Object|Array} The target object or array.
*/
exports.constructFromObject = function (data, obj, itemType) {
if (Array.isArray(data)) {
for (var i = 0; i < data.length; i++) {
if (data.hasOwnProperty(i)) obj[i] = exports.convertToType(data[i], itemType);
}
} else {
for (var k in data) {
if (data.hasOwnProperty(k)) result[k] = exports.convertToType(data[k], itemType);
}
}
};
/**
* The default API client implementation.
* @type {module:ApiClient}
*/
exports.instance = new exports();
return exports;
});
//# sourceMappingURL=ApiClient.js.map | apache-2.0 |
megastef/logsene-aws-lambda-cloudwatch | node_modules/alasql/dist/alasql-worker.js | 6199 | //! AlaSQL v0.3.4 | © 2014-2016 Andrey Gershun & Mathias Rangel Wulff | License: MIT
/*
@module alasql
@version 0.3.4
AlaSQL - JavaScript SQL database
© 2014-2016 Andrey Gershun & Mathias Rangel Wulff
@license
The MIT License (MIT)
Copyright 2014-2016 Andrey Gershun (agershun@gmail.com) & Mathias Rangel Wulff (m@rawu.dk)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
/*
//
// AlaSQL Workker
// Date: 13.04.2014
// (c) 2014-2015, Andrey Gershun
//
*/
(function (root, factory) {
if (typeof define === 'function' && define.amd) {
define([], factory);
} else if (typeof exports === 'object') {
module.exports = factory();
} else {
root.alasql = factory();
}
}(this, function () {
/**
Main procedure for worker
@function
@param {string} sql SQL statement
@param {object} params List of parameters (can be omitted)
@param {callback} cb Callback function
@return {object} Query result
*/
function alasql(sql,params,cb){
params = params||[];
// Avoid setting params if not needed even with callback
if(typeof params === 'function'){
scope = cb;
cb = params;
params = [];
}
if(typeof params !== 'object'){
params = [params];
}
// Increase last request id
var id = alasql.lastid++;
// Save callback
alasql.buffer[id] = cb;
// Send a message to worker
alasql.webworker.postMessage({id:id,sql:sql,params:params});
}
alasql.options = {};
alasql.options.progress = function(){};
isArray = function(obj){
return "[object Array]"===Object.prototype.toString.call(obj);
}
alasql.promise = function() {
throw new Error('Please include a Promise/A+ library');
}
// From src/18promise.js
if(typeof Promise !== "undefined"){
var promiseExec = function(sql, params, counterStep, counterTotal){
return new Promise(function(resolve, reject){
alasql(sql, params, function(data,err) {
if(err) {
reject(err);
} else {
if (counterStep && counterTotal && alasql.options.progress !== false) {
alasql.options.progress(counterStep, counterTotal);
}
resolve(data);
}
});
});
}
var promiseAll = function(sqlParamsArray){
if(sqlParamsArray.length<1){
return ;
}
var active, sql, params;
var execArray = [];
for (var i = 0; i < sqlParamsArray.length; i++) {
active = sqlParamsArray[i];
if(typeof active === 'string'){
active = [active];
}
if(!isArray(active) || active.length<1 || 2<active.length){
throw new Error('Error in .promise parameter');
}
sql = active[0];
params = active[1]||undefined;
execArray.push(promiseExec(sql, params, i, sqlParamsArray.length));
}
return Promise.all(execArray);
}
alasql.promise = function(sql, params) {
if(typeof Promise === "undefined"){
throw new Error('Please include a Promise/A+ library');
}
if(typeof sql === 'string'){
return promiseExec(sql, params);
}
if(!isArray(sql) || sql.length<1 || typeof params !== "undefined"){
throw new Error('Error in .promise parameters');
}
return promiseAll(sql);
};
}
alasql = alasql||false;
if(!alasql){
throw new Error('alasql was not found');
}
alasql.worker = function(){
throw new Error('Can find webworker in this enviroment');
}
if(typeof(Worker) !== "undefined") {
alasql.worker = function(path, paths, cb) {
// var path;
if(path === true){
path = undefined;
}
if (typeof path === "undefined") {
var sc = document.getElementsByTagName('script');
for(var i=0;i<sc.length;i++) {
if (sc[i].src.substr(-16).toLowerCase() === 'alasql-worker.js') {
path = sc[i].src.substr(0,sc[i].src.length-16)+'alasql.js';
break;
} else if (sc[i].src.substr(-20).toLowerCase() === 'alasql-worker.min.js') {
path = sc[i].src.substr(0,sc[i].src.length-20)+'alasql.min.js';
break;
} else if (sc[i].src.substr(-9).toLowerCase() === 'alasql.js') {
path = sc[i].src;
break;
} else if (sc[i].src.substr(-13).toLowerCase() === 'alasql.min.js') {
path = sc[i].src.substr(0,sc[i].src.length-13)+'alasql.min.js';
break;
}
}
}
if(typeof path === "undefined") {
throw new Error('Path to alasql.js is not specified');
} else if(path !== false) {
var js = "importScripts('";
js += path;
js+="');self.onmessage = function(event) {"+
"alasql(event.data.sql,event.data.params, function(data){"+
"postMessage({id:event.data.id, data:data});});}";
var blob = new Blob([js], {"type": "text\/plain"});
alasql.webworker = new Worker(URL.createObjectURL(blob));
alasql.webworker.onmessage = function(event) {
var id = event.data.id;
alasql.buffer[id](event.data.data);
delete alasql.buffer[id];
};
alasql.webworker.onerror = function(e){
throw e;
}
if(arguments.length > 1) {
var sql = 'REQUIRE ' + paths.map(function(p){
return '"'+p+'"';
}).join(",");
alasql(sql,[],cb);
}
} else if(path === false) {
delete alasql.webworker;
return;
}
};
}
/* WebWorker */
/** @type {number} */
alasql.lastid = 0;
/** @type {object} */
alasql.buffer = {};
alasql.worker();
return alasql;
}));
| apache-2.0 |
tensorflow/java | tensorflow-core/tensorflow-core-api/src/gen/java/org/tensorflow/op/nn/FixedUnigramCandidateSampler.java | 19053 | /* Copyright 2018 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
=======================================================================*/
// This class has been generated, DO NOT EDIT!
package org.tensorflow.op.nn;
import java.util.Arrays;
import java.util.List;
import org.tensorflow.GraphOperation;
import org.tensorflow.Operand;
import org.tensorflow.Operation;
import org.tensorflow.OperationBuilder;
import org.tensorflow.Output;
import org.tensorflow.op.RawOp;
import org.tensorflow.op.RawOpInputs;
import org.tensorflow.op.Scope;
import org.tensorflow.op.annotation.Endpoint;
import org.tensorflow.op.annotation.OpInputsMetadata;
import org.tensorflow.op.annotation.OpMetadata;
import org.tensorflow.op.annotation.Operator;
import org.tensorflow.types.TFloat32;
import org.tensorflow.types.TInt64;
/**
* Generates labels for candidate sampling with a learned unigram distribution.
* A unigram sampler could use a fixed unigram distribution read from a
* file or passed in as an in-memory array instead of building up the distribution
* from data on the fly. There is also an option to skew the distribution by
* applying a distortion power to the weights.
* <p>The vocabulary file should be in CSV-like format, with the last field
* being the weight associated with the word.
* <p>For each batch, this op picks a single set of sampled candidate labels.
* <p>The advantages of sampling candidates per-batch are simplicity and the
* possibility of efficient dense matrix multiplication. The disadvantage is that
* the sampled candidates must be chosen independently of the context and of the
* true labels.
*/
@OpMetadata(
opType = FixedUnigramCandidateSampler.OP_NAME,
inputsClass = FixedUnigramCandidateSampler.Inputs.class
)
@Operator(
group = "nn"
)
public final class FixedUnigramCandidateSampler extends RawOp {
/**
* The name of this op, as known by TensorFlow core engine
*/
public static final String OP_NAME = "FixedUnigramCandidateSampler";
private Output<TInt64> sampledCandidates;
private Output<TFloat32> trueExpectedCount;
private Output<TFloat32> sampledExpectedCount;
public FixedUnigramCandidateSampler(Operation operation) {
super(operation, OP_NAME);
int outputIdx = 0;
sampledCandidates = operation.output(outputIdx++);
trueExpectedCount = operation.output(outputIdx++);
sampledExpectedCount = operation.output(outputIdx++);
}
/**
* Factory method to create a class wrapping a new FixedUnigramCandidateSampler operation.
*
* @param scope current scope
* @param trueClasses A batch_size * num_true matrix, in which each row contains the
* IDs of the num_true target_classes in the corresponding original label.
* @param numTrue Number of true labels per context.
* @param numSampled Number of candidates to randomly sample.
* @param unique If unique is true, we sample with rejection, so that all sampled
* candidates in a batch are unique. This requires some approximation to
* estimate the post-rejection sampling probabilities.
* @param rangeMax The sampler will sample integers from the interval [0, range_max).
* @param options carries optional attribute values
* @return a new instance of FixedUnigramCandidateSampler
*/
@Endpoint(
describeByClass = true
)
public static FixedUnigramCandidateSampler create(Scope scope, Operand<TInt64> trueClasses,
Long numTrue, Long numSampled, Boolean unique, Long rangeMax, Options... options) {
OperationBuilder opBuilder = scope.opBuilder(OP_NAME, "FixedUnigramCandidateSampler");
opBuilder.addInput(trueClasses.asOutput());
opBuilder.setAttr("num_true", numTrue);
opBuilder.setAttr("num_sampled", numSampled);
opBuilder.setAttr("unique", unique);
opBuilder.setAttr("range_max", rangeMax);
if (options != null) {
for (Options opts : options) {
if (opts.vocabFile != null) {
opBuilder.setAttr("vocab_file", opts.vocabFile);
}
if (opts.distortion != null) {
opBuilder.setAttr("distortion", opts.distortion);
}
if (opts.numReservedIds != null) {
opBuilder.setAttr("num_reserved_ids", opts.numReservedIds);
}
if (opts.numShards != null) {
opBuilder.setAttr("num_shards", opts.numShards);
}
if (opts.shard != null) {
opBuilder.setAttr("shard", opts.shard);
}
if (opts.unigrams != null) {
float[] unigramsArray = new float[opts.unigrams.size()];
for (int i = 0 ; i < unigramsArray.length ; i++) {
unigramsArray[i] = opts.unigrams.get(i);
}
opBuilder.setAttr("unigrams", unigramsArray);
}
if (opts.seed != null) {
opBuilder.setAttr("seed", opts.seed);
}
if (opts.seed2 != null) {
opBuilder.setAttr("seed2", opts.seed2);
}
}
}
return new FixedUnigramCandidateSampler(opBuilder.build());
}
/**
* Sets the vocabFile option.
*
* @param vocabFile Each valid line in this file (which should have a CSV-like format)
* corresponds to a valid word ID. IDs are in sequential order, starting from
* num_reserved_ids. The last entry in each line is expected to be a value
* corresponding to the count or relative probability. Exactly one of vocab_file
* and unigrams needs to be passed to this op.
* @return this Options instance.
*/
public static Options vocabFile(String vocabFile) {
return new Options().vocabFile(vocabFile);
}
/**
* Sets the distortion option.
*
* @param distortion The distortion is used to skew the unigram probability distribution.
* Each weight is first raised to the distortion's power before adding to the
* internal unigram distribution. As a result, distortion = 1.0 gives regular
* unigram sampling (as defined by the vocab file), and distortion = 0.0 gives
* a uniform distribution.
* @return this Options instance.
*/
public static Options distortion(Float distortion) {
return new Options().distortion(distortion);
}
/**
* Sets the numReservedIds option.
*
* @param numReservedIds Optionally some reserved IDs can be added in the range [0,
* ..., num_reserved_ids) by the users. One use case is that a special unknown
* word token is used as ID 0. These IDs will have a sampling probability of 0.
* @return this Options instance.
*/
public static Options numReservedIds(Long numReservedIds) {
return new Options().numReservedIds(numReservedIds);
}
/**
* Sets the numShards option.
*
* @param numShards A sampler can be used to sample from a subset of the original range
* in order to speed up the whole computation through parallelism. This parameter
* (together with 'shard') indicates the number of partitions that are being
* used in the overall computation.
* @return this Options instance.
*/
public static Options numShards(Long numShards) {
return new Options().numShards(numShards);
}
/**
* Sets the shard option.
*
* @param shard A sampler can be used to sample from a subset of the original range
* in order to speed up the whole computation through parallelism. This parameter
* (together with 'num_shards') indicates the particular partition number of a
* sampler op, when partitioning is being used.
* @return this Options instance.
*/
public static Options shard(Long shard) {
return new Options().shard(shard);
}
/**
* Sets the unigrams option.
*
* @param unigrams A list of unigram counts or probabilities, one per ID in sequential
* order. Exactly one of vocab_file and unigrams should be passed to this op.
* @return this Options instance.
*/
public static Options unigrams(List<Float> unigrams) {
return new Options().unigrams(unigrams);
}
/**
* Sets the unigrams option.
*
* @param unigrams A list of unigram counts or probabilities, one per ID in sequential
* order. Exactly one of vocab_file and unigrams should be passed to this op.
* @return this Options instance.
*/
public static Options unigrams(Float... unigrams) {
return new Options().unigrams(unigrams);
}
/**
* Sets the seed option.
*
* @param seed If either seed or seed2 are set to be non-zero, the random number
* generator is seeded by the given seed. Otherwise, it is seeded by a
* random seed.
* @return this Options instance.
*/
public static Options seed(Long seed) {
return new Options().seed(seed);
}
/**
* Sets the seed2 option.
*
* @param seed2 An second seed to avoid seed collision.
* @return this Options instance.
*/
public static Options seed2(Long seed2) {
return new Options().seed2(seed2);
}
/**
* Gets sampledCandidates.
* A vector of length num_sampled, in which each element is
* the ID of a sampled candidate.
* @return sampledCandidates.
*/
public Output<TInt64> sampledCandidates() {
return sampledCandidates;
}
/**
* Gets trueExpectedCount.
* A batch_size * num_true matrix, representing
* the number of times each candidate is expected to occur in a batch
* of sampled candidates. If unique=true, then this is a probability.
* @return trueExpectedCount.
*/
public Output<TFloat32> trueExpectedCount() {
return trueExpectedCount;
}
/**
* Gets sampledExpectedCount.
* A vector of length num_sampled, for each sampled
* candidate representing the number of times the candidate is expected
* to occur in a batch of sampled candidates. If unique=true, then this is a
* probability.
* @return sampledExpectedCount.
*/
public Output<TFloat32> sampledExpectedCount() {
return sampledExpectedCount;
}
/**
* Optional attributes for {@link org.tensorflow.op.nn.FixedUnigramCandidateSampler}
*/
public static class Options {
private String vocabFile;
private Float distortion;
private Long numReservedIds;
private Long numShards;
private Long shard;
private List<Float> unigrams;
private Long seed;
private Long seed2;
private Options() {
}
/**
* Sets the vocabFile option.
*
* @param vocabFile Each valid line in this file (which should have a CSV-like format)
* corresponds to a valid word ID. IDs are in sequential order, starting from
* num_reserved_ids. The last entry in each line is expected to be a value
* corresponding to the count or relative probability. Exactly one of vocab_file
* and unigrams needs to be passed to this op.
* @return this Options instance.
*/
public Options vocabFile(String vocabFile) {
this.vocabFile = vocabFile;
return this;
}
/**
* Sets the distortion option.
*
* @param distortion The distortion is used to skew the unigram probability distribution.
* Each weight is first raised to the distortion's power before adding to the
* internal unigram distribution. As a result, distortion = 1.0 gives regular
* unigram sampling (as defined by the vocab file), and distortion = 0.0 gives
* a uniform distribution.
* @return this Options instance.
*/
public Options distortion(Float distortion) {
this.distortion = distortion;
return this;
}
/**
* Sets the numReservedIds option.
*
* @param numReservedIds Optionally some reserved IDs can be added in the range [0,
* ..., num_reserved_ids) by the users. One use case is that a special unknown
* word token is used as ID 0. These IDs will have a sampling probability of 0.
* @return this Options instance.
*/
public Options numReservedIds(Long numReservedIds) {
this.numReservedIds = numReservedIds;
return this;
}
/**
* Sets the numShards option.
*
* @param numShards A sampler can be used to sample from a subset of the original range
* in order to speed up the whole computation through parallelism. This parameter
* (together with 'shard') indicates the number of partitions that are being
* used in the overall computation.
* @return this Options instance.
*/
public Options numShards(Long numShards) {
this.numShards = numShards;
return this;
}
/**
* Sets the shard option.
*
* @param shard A sampler can be used to sample from a subset of the original range
* in order to speed up the whole computation through parallelism. This parameter
* (together with 'num_shards') indicates the particular partition number of a
* sampler op, when partitioning is being used.
* @return this Options instance.
*/
public Options shard(Long shard) {
this.shard = shard;
return this;
}
/**
* Sets the unigrams option.
*
* @param unigrams A list of unigram counts or probabilities, one per ID in sequential
* order. Exactly one of vocab_file and unigrams should be passed to this op.
* @return this Options instance.
*/
public Options unigrams(List<Float> unigrams) {
this.unigrams = unigrams;
return this;
}
/**
* Sets the unigrams option.
*
* @param unigrams A list of unigram counts or probabilities, one per ID in sequential
* order. Exactly one of vocab_file and unigrams should be passed to this op.
* @return this Options instance.
*/
public Options unigrams(Float... unigrams) {
this.unigrams = Arrays.asList(unigrams);
return this;
}
/**
* Sets the seed option.
*
* @param seed If either seed or seed2 are set to be non-zero, the random number
* generator is seeded by the given seed. Otherwise, it is seeded by a
* random seed.
* @return this Options instance.
*/
public Options seed(Long seed) {
this.seed = seed;
return this;
}
/**
* Sets the seed2 option.
*
* @param seed2 An second seed to avoid seed collision.
* @return this Options instance.
*/
public Options seed2(Long seed2) {
this.seed2 = seed2;
return this;
}
}
@OpInputsMetadata(
outputsClass = FixedUnigramCandidateSampler.class
)
public static class Inputs extends RawOpInputs<FixedUnigramCandidateSampler> {
/**
* A batch_size * num_true matrix, in which each row contains the
* IDs of the num_true target_classes in the corresponding original label.
*/
public final Operand<TInt64> trueClasses;
/**
* Number of true labels per context.
*/
public final long numTrue;
/**
* Number of candidates to randomly sample.
*/
public final long numSampled;
/**
* If unique is true, we sample with rejection, so that all sampled
* candidates in a batch are unique. This requires some approximation to
* estimate the post-rejection sampling probabilities.
*/
public final boolean unique;
/**
* The sampler will sample integers from the interval [0, range_max).
*/
public final long rangeMax;
/**
* Each valid line in this file (which should have a CSV-like format)
* corresponds to a valid word ID. IDs are in sequential order, starting from
* num_reserved_ids. The last entry in each line is expected to be a value
* corresponding to the count or relative probability. Exactly one of vocab_file
* and unigrams needs to be passed to this op.
*/
public final String vocabFile;
/**
* The distortion is used to skew the unigram probability distribution.
* Each weight is first raised to the distortion's power before adding to the
* internal unigram distribution. As a result, distortion = 1.0 gives regular
* unigram sampling (as defined by the vocab file), and distortion = 0.0 gives
* a uniform distribution.
*/
public final float distortion;
/**
* Optionally some reserved IDs can be added in the range [0,
* ..., num_reserved_ids) by the users. One use case is that a special unknown
* word token is used as ID 0. These IDs will have a sampling probability of 0.
*/
public final long numReservedIds;
/**
* A sampler can be used to sample from a subset of the original range
* in order to speed up the whole computation through parallelism. This parameter
* (together with 'shard') indicates the number of partitions that are being
* used in the overall computation.
*/
public final long numShards;
/**
* A sampler can be used to sample from a subset of the original range
* in order to speed up the whole computation through parallelism. This parameter
* (together with 'num_shards') indicates the particular partition number of a
* sampler op, when partitioning is being used.
*/
public final long shard;
/**
* A list of unigram counts or probabilities, one per ID in sequential
* order. Exactly one of vocab_file and unigrams should be passed to this op.
*/
public final float[] unigrams;
/**
* If either seed or seed2 are set to be non-zero, the random number
* generator is seeded by the given seed. Otherwise, it is seeded by a
* random seed.
*/
public final long seed;
/**
* An second seed to avoid seed collision.
*/
public final long seed2;
public Inputs(GraphOperation op) {
super(new FixedUnigramCandidateSampler(op), op, Arrays.asList("num_true", "num_sampled", "unique", "range_max", "vocab_file", "distortion", "num_reserved_ids", "num_shards", "shard", "unigrams", "seed", "seed2"));
int inputIndex = 0;
trueClasses = (Operand<TInt64>) op.input(inputIndex++);
numTrue = op.attributes().getAttrInt("num_true");
numSampled = op.attributes().getAttrInt("num_sampled");
unique = op.attributes().getAttrBool("unique");
rangeMax = op.attributes().getAttrInt("range_max");
vocabFile = op.attributes().getAttrString("vocab_file");
distortion = op.attributes().getAttrFloat("distortion");
numReservedIds = op.attributes().getAttrInt("num_reserved_ids");
numShards = op.attributes().getAttrInt("num_shards");
shard = op.attributes().getAttrInt("shard");
unigrams = op.attributes().getAttrFloatList("unigrams");
seed = op.attributes().getAttrInt("seed");
seed2 = op.attributes().getAttrInt("seed2");
}
}
}
| apache-2.0 |
googleapis/java-aiplatform | proto-google-cloud-aiplatform-v1/src/main/java/com/google/cloud/aiplatform/v1/ExportModelRequest.java | 88526 | /*
* Copyright 2020 Google LLC
*
* 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
*
* https://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.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/aiplatform/v1/model_service.proto
package com.google.cloud.aiplatform.v1;
/**
*
*
* <pre>
* Request message for [ModelService.ExportModel][google.cloud.aiplatform.v1.ModelService.ExportModel].
* </pre>
*
* Protobuf type {@code google.cloud.aiplatform.v1.ExportModelRequest}
*/
public final class ExportModelRequest extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.aiplatform.v1.ExportModelRequest)
ExportModelRequestOrBuilder {
private static final long serialVersionUID = 0L;
// Use ExportModelRequest.newBuilder() to construct.
private ExportModelRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private ExportModelRequest() {
name_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new ExportModelRequest();
}
@java.lang.Override
public final com.google.protobuf.UnknownFieldSet getUnknownFields() {
return this.unknownFields;
}
private ExportModelRequest(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
this();
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
com.google.protobuf.UnknownFieldSet.Builder unknownFields =
com.google.protobuf.UnknownFieldSet.newBuilder();
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 10:
{
java.lang.String s = input.readStringRequireUtf8();
name_ = s;
break;
}
case 18:
{
com.google.cloud.aiplatform.v1.ExportModelRequest.OutputConfig.Builder subBuilder =
null;
if (outputConfig_ != null) {
subBuilder = outputConfig_.toBuilder();
}
outputConfig_ =
input.readMessage(
com.google.cloud.aiplatform.v1.ExportModelRequest.OutputConfig.parser(),
extensionRegistry);
if (subBuilder != null) {
subBuilder.mergeFrom(outputConfig_);
outputConfig_ = subBuilder.buildPartial();
}
break;
}
default:
{
if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) {
done = true;
}
break;
}
}
}
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(this);
} catch (java.io.IOException e) {
throw new com.google.protobuf.InvalidProtocolBufferException(e).setUnfinishedMessage(this);
} finally {
this.unknownFields = unknownFields.build();
makeExtensionsImmutable();
}
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.aiplatform.v1.ModelServiceProto
.internal_static_google_cloud_aiplatform_v1_ExportModelRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.aiplatform.v1.ModelServiceProto
.internal_static_google_cloud_aiplatform_v1_ExportModelRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.aiplatform.v1.ExportModelRequest.class,
com.google.cloud.aiplatform.v1.ExportModelRequest.Builder.class);
}
public interface OutputConfigOrBuilder
extends
// @@protoc_insertion_point(interface_extends:google.cloud.aiplatform.v1.ExportModelRequest.OutputConfig)
com.google.protobuf.MessageOrBuilder {
/**
*
*
* <pre>
* The ID of the format in which the Model must be exported. Each Model
* lists the [export formats it supports][google.cloud.aiplatform.v1.Model.supported_export_formats].
* If no value is provided here, then the first from the list of the Model's
* supported formats is used by default.
* </pre>
*
* <code>string export_format_id = 1;</code>
*
* @return The exportFormatId.
*/
java.lang.String getExportFormatId();
/**
*
*
* <pre>
* The ID of the format in which the Model must be exported. Each Model
* lists the [export formats it supports][google.cloud.aiplatform.v1.Model.supported_export_formats].
* If no value is provided here, then the first from the list of the Model's
* supported formats is used by default.
* </pre>
*
* <code>string export_format_id = 1;</code>
*
* @return The bytes for exportFormatId.
*/
com.google.protobuf.ByteString getExportFormatIdBytes();
/**
*
*
* <pre>
* The Cloud Storage location where the Model artifact is to be
* written to. Under the directory given as the destination a new one with
* name "`model-export-<model-display-name>-<timestamp-of-export-call>`",
* where timestamp is in YYYY-MM-DDThh:mm:ss.sssZ ISO-8601 format,
* will be created. Inside, the Model and any of its supporting files
* will be written.
* This field should only be set when the `exportableContent` field of the
* [Model.supported_export_formats] object contains `ARTIFACT`.
* </pre>
*
* <code>.google.cloud.aiplatform.v1.GcsDestination artifact_destination = 3;</code>
*
* @return Whether the artifactDestination field is set.
*/
boolean hasArtifactDestination();
/**
*
*
* <pre>
* The Cloud Storage location where the Model artifact is to be
* written to. Under the directory given as the destination a new one with
* name "`model-export-<model-display-name>-<timestamp-of-export-call>`",
* where timestamp is in YYYY-MM-DDThh:mm:ss.sssZ ISO-8601 format,
* will be created. Inside, the Model and any of its supporting files
* will be written.
* This field should only be set when the `exportableContent` field of the
* [Model.supported_export_formats] object contains `ARTIFACT`.
* </pre>
*
* <code>.google.cloud.aiplatform.v1.GcsDestination artifact_destination = 3;</code>
*
* @return The artifactDestination.
*/
com.google.cloud.aiplatform.v1.GcsDestination getArtifactDestination();
/**
*
*
* <pre>
* The Cloud Storage location where the Model artifact is to be
* written to. Under the directory given as the destination a new one with
* name "`model-export-<model-display-name>-<timestamp-of-export-call>`",
* where timestamp is in YYYY-MM-DDThh:mm:ss.sssZ ISO-8601 format,
* will be created. Inside, the Model and any of its supporting files
* will be written.
* This field should only be set when the `exportableContent` field of the
* [Model.supported_export_formats] object contains `ARTIFACT`.
* </pre>
*
* <code>.google.cloud.aiplatform.v1.GcsDestination artifact_destination = 3;</code>
*/
com.google.cloud.aiplatform.v1.GcsDestinationOrBuilder getArtifactDestinationOrBuilder();
/**
*
*
* <pre>
* The Google Container Registry or Artifact Registry uri where the
* Model container image will be copied to.
* This field should only be set when the `exportableContent` field of the
* [Model.supported_export_formats] object contains `IMAGE`.
* </pre>
*
* <code>.google.cloud.aiplatform.v1.ContainerRegistryDestination image_destination = 4;</code>
*
* @return Whether the imageDestination field is set.
*/
boolean hasImageDestination();
/**
*
*
* <pre>
* The Google Container Registry or Artifact Registry uri where the
* Model container image will be copied to.
* This field should only be set when the `exportableContent` field of the
* [Model.supported_export_formats] object contains `IMAGE`.
* </pre>
*
* <code>.google.cloud.aiplatform.v1.ContainerRegistryDestination image_destination = 4;</code>
*
* @return The imageDestination.
*/
com.google.cloud.aiplatform.v1.ContainerRegistryDestination getImageDestination();
/**
*
*
* <pre>
* The Google Container Registry or Artifact Registry uri where the
* Model container image will be copied to.
* This field should only be set when the `exportableContent` field of the
* [Model.supported_export_formats] object contains `IMAGE`.
* </pre>
*
* <code>.google.cloud.aiplatform.v1.ContainerRegistryDestination image_destination = 4;</code>
*/
com.google.cloud.aiplatform.v1.ContainerRegistryDestinationOrBuilder
getImageDestinationOrBuilder();
}
/**
*
*
* <pre>
* Output configuration for the Model export.
* </pre>
*
* Protobuf type {@code google.cloud.aiplatform.v1.ExportModelRequest.OutputConfig}
*/
public static final class OutputConfig extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.aiplatform.v1.ExportModelRequest.OutputConfig)
OutputConfigOrBuilder {
private static final long serialVersionUID = 0L;
// Use OutputConfig.newBuilder() to construct.
private OutputConfig(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private OutputConfig() {
exportFormatId_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new OutputConfig();
}
@java.lang.Override
public final com.google.protobuf.UnknownFieldSet getUnknownFields() {
return this.unknownFields;
}
private OutputConfig(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
this();
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
com.google.protobuf.UnknownFieldSet.Builder unknownFields =
com.google.protobuf.UnknownFieldSet.newBuilder();
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 10:
{
java.lang.String s = input.readStringRequireUtf8();
exportFormatId_ = s;
break;
}
case 26:
{
com.google.cloud.aiplatform.v1.GcsDestination.Builder subBuilder = null;
if (artifactDestination_ != null) {
subBuilder = artifactDestination_.toBuilder();
}
artifactDestination_ =
input.readMessage(
com.google.cloud.aiplatform.v1.GcsDestination.parser(), extensionRegistry);
if (subBuilder != null) {
subBuilder.mergeFrom(artifactDestination_);
artifactDestination_ = subBuilder.buildPartial();
}
break;
}
case 34:
{
com.google.cloud.aiplatform.v1.ContainerRegistryDestination.Builder subBuilder =
null;
if (imageDestination_ != null) {
subBuilder = imageDestination_.toBuilder();
}
imageDestination_ =
input.readMessage(
com.google.cloud.aiplatform.v1.ContainerRegistryDestination.parser(),
extensionRegistry);
if (subBuilder != null) {
subBuilder.mergeFrom(imageDestination_);
imageDestination_ = subBuilder.buildPartial();
}
break;
}
default:
{
if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) {
done = true;
}
break;
}
}
}
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(this);
} catch (java.io.IOException e) {
throw new com.google.protobuf.InvalidProtocolBufferException(e).setUnfinishedMessage(this);
} finally {
this.unknownFields = unknownFields.build();
makeExtensionsImmutable();
}
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.aiplatform.v1.ModelServiceProto
.internal_static_google_cloud_aiplatform_v1_ExportModelRequest_OutputConfig_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.aiplatform.v1.ModelServiceProto
.internal_static_google_cloud_aiplatform_v1_ExportModelRequest_OutputConfig_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.aiplatform.v1.ExportModelRequest.OutputConfig.class,
com.google.cloud.aiplatform.v1.ExportModelRequest.OutputConfig.Builder.class);
}
public static final int EXPORT_FORMAT_ID_FIELD_NUMBER = 1;
private volatile java.lang.Object exportFormatId_;
/**
*
*
* <pre>
* The ID of the format in which the Model must be exported. Each Model
* lists the [export formats it supports][google.cloud.aiplatform.v1.Model.supported_export_formats].
* If no value is provided here, then the first from the list of the Model's
* supported formats is used by default.
* </pre>
*
* <code>string export_format_id = 1;</code>
*
* @return The exportFormatId.
*/
@java.lang.Override
public java.lang.String getExportFormatId() {
java.lang.Object ref = exportFormatId_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
exportFormatId_ = s;
return s;
}
}
/**
*
*
* <pre>
* The ID of the format in which the Model must be exported. Each Model
* lists the [export formats it supports][google.cloud.aiplatform.v1.Model.supported_export_formats].
* If no value is provided here, then the first from the list of the Model's
* supported formats is used by default.
* </pre>
*
* <code>string export_format_id = 1;</code>
*
* @return The bytes for exportFormatId.
*/
@java.lang.Override
public com.google.protobuf.ByteString getExportFormatIdBytes() {
java.lang.Object ref = exportFormatId_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
exportFormatId_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int ARTIFACT_DESTINATION_FIELD_NUMBER = 3;
private com.google.cloud.aiplatform.v1.GcsDestination artifactDestination_;
/**
*
*
* <pre>
* The Cloud Storage location where the Model artifact is to be
* written to. Under the directory given as the destination a new one with
* name "`model-export-<model-display-name>-<timestamp-of-export-call>`",
* where timestamp is in YYYY-MM-DDThh:mm:ss.sssZ ISO-8601 format,
* will be created. Inside, the Model and any of its supporting files
* will be written.
* This field should only be set when the `exportableContent` field of the
* [Model.supported_export_formats] object contains `ARTIFACT`.
* </pre>
*
* <code>.google.cloud.aiplatform.v1.GcsDestination artifact_destination = 3;</code>
*
* @return Whether the artifactDestination field is set.
*/
@java.lang.Override
public boolean hasArtifactDestination() {
return artifactDestination_ != null;
}
/**
*
*
* <pre>
* The Cloud Storage location where the Model artifact is to be
* written to. Under the directory given as the destination a new one with
* name "`model-export-<model-display-name>-<timestamp-of-export-call>`",
* where timestamp is in YYYY-MM-DDThh:mm:ss.sssZ ISO-8601 format,
* will be created. Inside, the Model and any of its supporting files
* will be written.
* This field should only be set when the `exportableContent` field of the
* [Model.supported_export_formats] object contains `ARTIFACT`.
* </pre>
*
* <code>.google.cloud.aiplatform.v1.GcsDestination artifact_destination = 3;</code>
*
* @return The artifactDestination.
*/
@java.lang.Override
public com.google.cloud.aiplatform.v1.GcsDestination getArtifactDestination() {
return artifactDestination_ == null
? com.google.cloud.aiplatform.v1.GcsDestination.getDefaultInstance()
: artifactDestination_;
}
/**
*
*
* <pre>
* The Cloud Storage location where the Model artifact is to be
* written to. Under the directory given as the destination a new one with
* name "`model-export-<model-display-name>-<timestamp-of-export-call>`",
* where timestamp is in YYYY-MM-DDThh:mm:ss.sssZ ISO-8601 format,
* will be created. Inside, the Model and any of its supporting files
* will be written.
* This field should only be set when the `exportableContent` field of the
* [Model.supported_export_formats] object contains `ARTIFACT`.
* </pre>
*
* <code>.google.cloud.aiplatform.v1.GcsDestination artifact_destination = 3;</code>
*/
@java.lang.Override
public com.google.cloud.aiplatform.v1.GcsDestinationOrBuilder
getArtifactDestinationOrBuilder() {
return getArtifactDestination();
}
public static final int IMAGE_DESTINATION_FIELD_NUMBER = 4;
private com.google.cloud.aiplatform.v1.ContainerRegistryDestination imageDestination_;
/**
*
*
* <pre>
* The Google Container Registry or Artifact Registry uri where the
* Model container image will be copied to.
* This field should only be set when the `exportableContent` field of the
* [Model.supported_export_formats] object contains `IMAGE`.
* </pre>
*
* <code>.google.cloud.aiplatform.v1.ContainerRegistryDestination image_destination = 4;</code>
*
* @return Whether the imageDestination field is set.
*/
@java.lang.Override
public boolean hasImageDestination() {
return imageDestination_ != null;
}
/**
*
*
* <pre>
* The Google Container Registry or Artifact Registry uri where the
* Model container image will be copied to.
* This field should only be set when the `exportableContent` field of the
* [Model.supported_export_formats] object contains `IMAGE`.
* </pre>
*
* <code>.google.cloud.aiplatform.v1.ContainerRegistryDestination image_destination = 4;</code>
*
* @return The imageDestination.
*/
@java.lang.Override
public com.google.cloud.aiplatform.v1.ContainerRegistryDestination getImageDestination() {
return imageDestination_ == null
? com.google.cloud.aiplatform.v1.ContainerRegistryDestination.getDefaultInstance()
: imageDestination_;
}
/**
*
*
* <pre>
* The Google Container Registry or Artifact Registry uri where the
* Model container image will be copied to.
* This field should only be set when the `exportableContent` field of the
* [Model.supported_export_formats] object contains `IMAGE`.
* </pre>
*
* <code>.google.cloud.aiplatform.v1.ContainerRegistryDestination image_destination = 4;</code>
*/
@java.lang.Override
public com.google.cloud.aiplatform.v1.ContainerRegistryDestinationOrBuilder
getImageDestinationOrBuilder() {
return getImageDestination();
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException {
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(exportFormatId_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 1, exportFormatId_);
}
if (artifactDestination_ != null) {
output.writeMessage(3, getArtifactDestination());
}
if (imageDestination_ != null) {
output.writeMessage(4, getImageDestination());
}
unknownFields.writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(exportFormatId_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, exportFormatId_);
}
if (artifactDestination_ != null) {
size +=
com.google.protobuf.CodedOutputStream.computeMessageSize(3, getArtifactDestination());
}
if (imageDestination_ != null) {
size += com.google.protobuf.CodedOutputStream.computeMessageSize(4, getImageDestination());
}
size += unknownFields.getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.cloud.aiplatform.v1.ExportModelRequest.OutputConfig)) {
return super.equals(obj);
}
com.google.cloud.aiplatform.v1.ExportModelRequest.OutputConfig other =
(com.google.cloud.aiplatform.v1.ExportModelRequest.OutputConfig) obj;
if (!getExportFormatId().equals(other.getExportFormatId())) return false;
if (hasArtifactDestination() != other.hasArtifactDestination()) return false;
if (hasArtifactDestination()) {
if (!getArtifactDestination().equals(other.getArtifactDestination())) return false;
}
if (hasImageDestination() != other.hasImageDestination()) return false;
if (hasImageDestination()) {
if (!getImageDestination().equals(other.getImageDestination())) return false;
}
if (!unknownFields.equals(other.unknownFields)) return false;
return true;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
hash = (37 * hash) + EXPORT_FORMAT_ID_FIELD_NUMBER;
hash = (53 * hash) + getExportFormatId().hashCode();
if (hasArtifactDestination()) {
hash = (37 * hash) + ARTIFACT_DESTINATION_FIELD_NUMBER;
hash = (53 * hash) + getArtifactDestination().hashCode();
}
if (hasImageDestination()) {
hash = (37 * hash) + IMAGE_DESTINATION_FIELD_NUMBER;
hash = (53 * hash) + getImageDestination().hashCode();
}
hash = (29 * hash) + unknownFields.hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.aiplatform.v1.ExportModelRequest.OutputConfig parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.aiplatform.v1.ExportModelRequest.OutputConfig parseFrom(
java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.aiplatform.v1.ExportModelRequest.OutputConfig parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.aiplatform.v1.ExportModelRequest.OutputConfig parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.aiplatform.v1.ExportModelRequest.OutputConfig parseFrom(
byte[] data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.aiplatform.v1.ExportModelRequest.OutputConfig parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.aiplatform.v1.ExportModelRequest.OutputConfig parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.aiplatform.v1.ExportModelRequest.OutputConfig parseFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.aiplatform.v1.ExportModelRequest.OutputConfig parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.aiplatform.v1.ExportModelRequest.OutputConfig parseDelimitedFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.aiplatform.v1.ExportModelRequest.OutputConfig parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.aiplatform.v1.ExportModelRequest.OutputConfig parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() {
return newBuilder();
}
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(
com.google.cloud.aiplatform.v1.ExportModelRequest.OutputConfig prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(
com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
*
*
* <pre>
* Output configuration for the Model export.
* </pre>
*
* Protobuf type {@code google.cloud.aiplatform.v1.ExportModelRequest.OutputConfig}
*/
public static final class Builder
extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.aiplatform.v1.ExportModelRequest.OutputConfig)
com.google.cloud.aiplatform.v1.ExportModelRequest.OutputConfigOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.aiplatform.v1.ModelServiceProto
.internal_static_google_cloud_aiplatform_v1_ExportModelRequest_OutputConfig_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.aiplatform.v1.ModelServiceProto
.internal_static_google_cloud_aiplatform_v1_ExportModelRequest_OutputConfig_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.aiplatform.v1.ExportModelRequest.OutputConfig.class,
com.google.cloud.aiplatform.v1.ExportModelRequest.OutputConfig.Builder.class);
}
// Construct using com.google.cloud.aiplatform.v1.ExportModelRequest.OutputConfig.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) {}
}
@java.lang.Override
public Builder clear() {
super.clear();
exportFormatId_ = "";
if (artifactDestinationBuilder_ == null) {
artifactDestination_ = null;
} else {
artifactDestination_ = null;
artifactDestinationBuilder_ = null;
}
if (imageDestinationBuilder_ == null) {
imageDestination_ = null;
} else {
imageDestination_ = null;
imageDestinationBuilder_ = null;
}
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.aiplatform.v1.ModelServiceProto
.internal_static_google_cloud_aiplatform_v1_ExportModelRequest_OutputConfig_descriptor;
}
@java.lang.Override
public com.google.cloud.aiplatform.v1.ExportModelRequest.OutputConfig
getDefaultInstanceForType() {
return com.google.cloud.aiplatform.v1.ExportModelRequest.OutputConfig.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.aiplatform.v1.ExportModelRequest.OutputConfig build() {
com.google.cloud.aiplatform.v1.ExportModelRequest.OutputConfig result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.aiplatform.v1.ExportModelRequest.OutputConfig buildPartial() {
com.google.cloud.aiplatform.v1.ExportModelRequest.OutputConfig result =
new com.google.cloud.aiplatform.v1.ExportModelRequest.OutputConfig(this);
result.exportFormatId_ = exportFormatId_;
if (artifactDestinationBuilder_ == null) {
result.artifactDestination_ = artifactDestination_;
} else {
result.artifactDestination_ = artifactDestinationBuilder_.build();
}
if (imageDestinationBuilder_ == null) {
result.imageDestination_ = imageDestination_;
} else {
result.imageDestination_ = imageDestinationBuilder_.build();
}
onBuilt();
return result;
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field,
int index,
java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.cloud.aiplatform.v1.ExportModelRequest.OutputConfig) {
return mergeFrom((com.google.cloud.aiplatform.v1.ExportModelRequest.OutputConfig) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(
com.google.cloud.aiplatform.v1.ExportModelRequest.OutputConfig other) {
if (other
== com.google.cloud.aiplatform.v1.ExportModelRequest.OutputConfig.getDefaultInstance())
return this;
if (!other.getExportFormatId().isEmpty()) {
exportFormatId_ = other.exportFormatId_;
onChanged();
}
if (other.hasArtifactDestination()) {
mergeArtifactDestination(other.getArtifactDestination());
}
if (other.hasImageDestination()) {
mergeImageDestination(other.getImageDestination());
}
this.mergeUnknownFields(other.unknownFields);
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
com.google.cloud.aiplatform.v1.ExportModelRequest.OutputConfig parsedMessage = null;
try {
parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
parsedMessage =
(com.google.cloud.aiplatform.v1.ExportModelRequest.OutputConfig)
e.getUnfinishedMessage();
throw e.unwrapIOException();
} finally {
if (parsedMessage != null) {
mergeFrom(parsedMessage);
}
}
return this;
}
private java.lang.Object exportFormatId_ = "";
/**
*
*
* <pre>
* The ID of the format in which the Model must be exported. Each Model
* lists the [export formats it supports][google.cloud.aiplatform.v1.Model.supported_export_formats].
* If no value is provided here, then the first from the list of the Model's
* supported formats is used by default.
* </pre>
*
* <code>string export_format_id = 1;</code>
*
* @return The exportFormatId.
*/
public java.lang.String getExportFormatId() {
java.lang.Object ref = exportFormatId_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
exportFormatId_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* The ID of the format in which the Model must be exported. Each Model
* lists the [export formats it supports][google.cloud.aiplatform.v1.Model.supported_export_formats].
* If no value is provided here, then the first from the list of the Model's
* supported formats is used by default.
* </pre>
*
* <code>string export_format_id = 1;</code>
*
* @return The bytes for exportFormatId.
*/
public com.google.protobuf.ByteString getExportFormatIdBytes() {
java.lang.Object ref = exportFormatId_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
exportFormatId_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* The ID of the format in which the Model must be exported. Each Model
* lists the [export formats it supports][google.cloud.aiplatform.v1.Model.supported_export_formats].
* If no value is provided here, then the first from the list of the Model's
* supported formats is used by default.
* </pre>
*
* <code>string export_format_id = 1;</code>
*
* @param value The exportFormatId to set.
* @return This builder for chaining.
*/
public Builder setExportFormatId(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
exportFormatId_ = value;
onChanged();
return this;
}
/**
*
*
* <pre>
* The ID of the format in which the Model must be exported. Each Model
* lists the [export formats it supports][google.cloud.aiplatform.v1.Model.supported_export_formats].
* If no value is provided here, then the first from the list of the Model's
* supported formats is used by default.
* </pre>
*
* <code>string export_format_id = 1;</code>
*
* @return This builder for chaining.
*/
public Builder clearExportFormatId() {
exportFormatId_ = getDefaultInstance().getExportFormatId();
onChanged();
return this;
}
/**
*
*
* <pre>
* The ID of the format in which the Model must be exported. Each Model
* lists the [export formats it supports][google.cloud.aiplatform.v1.Model.supported_export_formats].
* If no value is provided here, then the first from the list of the Model's
* supported formats is used by default.
* </pre>
*
* <code>string export_format_id = 1;</code>
*
* @param value The bytes for exportFormatId to set.
* @return This builder for chaining.
*/
public Builder setExportFormatIdBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
exportFormatId_ = value;
onChanged();
return this;
}
private com.google.cloud.aiplatform.v1.GcsDestination artifactDestination_;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.aiplatform.v1.GcsDestination,
com.google.cloud.aiplatform.v1.GcsDestination.Builder,
com.google.cloud.aiplatform.v1.GcsDestinationOrBuilder>
artifactDestinationBuilder_;
/**
*
*
* <pre>
* The Cloud Storage location where the Model artifact is to be
* written to. Under the directory given as the destination a new one with
* name "`model-export-<model-display-name>-<timestamp-of-export-call>`",
* where timestamp is in YYYY-MM-DDThh:mm:ss.sssZ ISO-8601 format,
* will be created. Inside, the Model and any of its supporting files
* will be written.
* This field should only be set when the `exportableContent` field of the
* [Model.supported_export_formats] object contains `ARTIFACT`.
* </pre>
*
* <code>.google.cloud.aiplatform.v1.GcsDestination artifact_destination = 3;</code>
*
* @return Whether the artifactDestination field is set.
*/
public boolean hasArtifactDestination() {
return artifactDestinationBuilder_ != null || artifactDestination_ != null;
}
/**
*
*
* <pre>
* The Cloud Storage location where the Model artifact is to be
* written to. Under the directory given as the destination a new one with
* name "`model-export-<model-display-name>-<timestamp-of-export-call>`",
* where timestamp is in YYYY-MM-DDThh:mm:ss.sssZ ISO-8601 format,
* will be created. Inside, the Model and any of its supporting files
* will be written.
* This field should only be set when the `exportableContent` field of the
* [Model.supported_export_formats] object contains `ARTIFACT`.
* </pre>
*
* <code>.google.cloud.aiplatform.v1.GcsDestination artifact_destination = 3;</code>
*
* @return The artifactDestination.
*/
public com.google.cloud.aiplatform.v1.GcsDestination getArtifactDestination() {
if (artifactDestinationBuilder_ == null) {
return artifactDestination_ == null
? com.google.cloud.aiplatform.v1.GcsDestination.getDefaultInstance()
: artifactDestination_;
} else {
return artifactDestinationBuilder_.getMessage();
}
}
/**
*
*
* <pre>
* The Cloud Storage location where the Model artifact is to be
* written to. Under the directory given as the destination a new one with
* name "`model-export-<model-display-name>-<timestamp-of-export-call>`",
* where timestamp is in YYYY-MM-DDThh:mm:ss.sssZ ISO-8601 format,
* will be created. Inside, the Model and any of its supporting files
* will be written.
* This field should only be set when the `exportableContent` field of the
* [Model.supported_export_formats] object contains `ARTIFACT`.
* </pre>
*
* <code>.google.cloud.aiplatform.v1.GcsDestination artifact_destination = 3;</code>
*/
public Builder setArtifactDestination(com.google.cloud.aiplatform.v1.GcsDestination value) {
if (artifactDestinationBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
artifactDestination_ = value;
onChanged();
} else {
artifactDestinationBuilder_.setMessage(value);
}
return this;
}
/**
*
*
* <pre>
* The Cloud Storage location where the Model artifact is to be
* written to. Under the directory given as the destination a new one with
* name "`model-export-<model-display-name>-<timestamp-of-export-call>`",
* where timestamp is in YYYY-MM-DDThh:mm:ss.sssZ ISO-8601 format,
* will be created. Inside, the Model and any of its supporting files
* will be written.
* This field should only be set when the `exportableContent` field of the
* [Model.supported_export_formats] object contains `ARTIFACT`.
* </pre>
*
* <code>.google.cloud.aiplatform.v1.GcsDestination artifact_destination = 3;</code>
*/
public Builder setArtifactDestination(
com.google.cloud.aiplatform.v1.GcsDestination.Builder builderForValue) {
if (artifactDestinationBuilder_ == null) {
artifactDestination_ = builderForValue.build();
onChanged();
} else {
artifactDestinationBuilder_.setMessage(builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* The Cloud Storage location where the Model artifact is to be
* written to. Under the directory given as the destination a new one with
* name "`model-export-<model-display-name>-<timestamp-of-export-call>`",
* where timestamp is in YYYY-MM-DDThh:mm:ss.sssZ ISO-8601 format,
* will be created. Inside, the Model and any of its supporting files
* will be written.
* This field should only be set when the `exportableContent` field of the
* [Model.supported_export_formats] object contains `ARTIFACT`.
* </pre>
*
* <code>.google.cloud.aiplatform.v1.GcsDestination artifact_destination = 3;</code>
*/
public Builder mergeArtifactDestination(com.google.cloud.aiplatform.v1.GcsDestination value) {
if (artifactDestinationBuilder_ == null) {
if (artifactDestination_ != null) {
artifactDestination_ =
com.google.cloud.aiplatform.v1.GcsDestination.newBuilder(artifactDestination_)
.mergeFrom(value)
.buildPartial();
} else {
artifactDestination_ = value;
}
onChanged();
} else {
artifactDestinationBuilder_.mergeFrom(value);
}
return this;
}
/**
*
*
* <pre>
* The Cloud Storage location where the Model artifact is to be
* written to. Under the directory given as the destination a new one with
* name "`model-export-<model-display-name>-<timestamp-of-export-call>`",
* where timestamp is in YYYY-MM-DDThh:mm:ss.sssZ ISO-8601 format,
* will be created. Inside, the Model and any of its supporting files
* will be written.
* This field should only be set when the `exportableContent` field of the
* [Model.supported_export_formats] object contains `ARTIFACT`.
* </pre>
*
* <code>.google.cloud.aiplatform.v1.GcsDestination artifact_destination = 3;</code>
*/
public Builder clearArtifactDestination() {
if (artifactDestinationBuilder_ == null) {
artifactDestination_ = null;
onChanged();
} else {
artifactDestination_ = null;
artifactDestinationBuilder_ = null;
}
return this;
}
/**
*
*
* <pre>
* The Cloud Storage location where the Model artifact is to be
* written to. Under the directory given as the destination a new one with
* name "`model-export-<model-display-name>-<timestamp-of-export-call>`",
* where timestamp is in YYYY-MM-DDThh:mm:ss.sssZ ISO-8601 format,
* will be created. Inside, the Model and any of its supporting files
* will be written.
* This field should only be set when the `exportableContent` field of the
* [Model.supported_export_formats] object contains `ARTIFACT`.
* </pre>
*
* <code>.google.cloud.aiplatform.v1.GcsDestination artifact_destination = 3;</code>
*/
public com.google.cloud.aiplatform.v1.GcsDestination.Builder getArtifactDestinationBuilder() {
onChanged();
return getArtifactDestinationFieldBuilder().getBuilder();
}
/**
*
*
* <pre>
* The Cloud Storage location where the Model artifact is to be
* written to. Under the directory given as the destination a new one with
* name "`model-export-<model-display-name>-<timestamp-of-export-call>`",
* where timestamp is in YYYY-MM-DDThh:mm:ss.sssZ ISO-8601 format,
* will be created. Inside, the Model and any of its supporting files
* will be written.
* This field should only be set when the `exportableContent` field of the
* [Model.supported_export_formats] object contains `ARTIFACT`.
* </pre>
*
* <code>.google.cloud.aiplatform.v1.GcsDestination artifact_destination = 3;</code>
*/
public com.google.cloud.aiplatform.v1.GcsDestinationOrBuilder
getArtifactDestinationOrBuilder() {
if (artifactDestinationBuilder_ != null) {
return artifactDestinationBuilder_.getMessageOrBuilder();
} else {
return artifactDestination_ == null
? com.google.cloud.aiplatform.v1.GcsDestination.getDefaultInstance()
: artifactDestination_;
}
}
/**
*
*
* <pre>
* The Cloud Storage location where the Model artifact is to be
* written to. Under the directory given as the destination a new one with
* name "`model-export-<model-display-name>-<timestamp-of-export-call>`",
* where timestamp is in YYYY-MM-DDThh:mm:ss.sssZ ISO-8601 format,
* will be created. Inside, the Model and any of its supporting files
* will be written.
* This field should only be set when the `exportableContent` field of the
* [Model.supported_export_formats] object contains `ARTIFACT`.
* </pre>
*
* <code>.google.cloud.aiplatform.v1.GcsDestination artifact_destination = 3;</code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.aiplatform.v1.GcsDestination,
com.google.cloud.aiplatform.v1.GcsDestination.Builder,
com.google.cloud.aiplatform.v1.GcsDestinationOrBuilder>
getArtifactDestinationFieldBuilder() {
if (artifactDestinationBuilder_ == null) {
artifactDestinationBuilder_ =
new com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.aiplatform.v1.GcsDestination,
com.google.cloud.aiplatform.v1.GcsDestination.Builder,
com.google.cloud.aiplatform.v1.GcsDestinationOrBuilder>(
getArtifactDestination(), getParentForChildren(), isClean());
artifactDestination_ = null;
}
return artifactDestinationBuilder_;
}
private com.google.cloud.aiplatform.v1.ContainerRegistryDestination imageDestination_;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.aiplatform.v1.ContainerRegistryDestination,
com.google.cloud.aiplatform.v1.ContainerRegistryDestination.Builder,
com.google.cloud.aiplatform.v1.ContainerRegistryDestinationOrBuilder>
imageDestinationBuilder_;
/**
*
*
* <pre>
* The Google Container Registry or Artifact Registry uri where the
* Model container image will be copied to.
* This field should only be set when the `exportableContent` field of the
* [Model.supported_export_formats] object contains `IMAGE`.
* </pre>
*
* <code>.google.cloud.aiplatform.v1.ContainerRegistryDestination image_destination = 4;
* </code>
*
* @return Whether the imageDestination field is set.
*/
public boolean hasImageDestination() {
return imageDestinationBuilder_ != null || imageDestination_ != null;
}
/**
*
*
* <pre>
* The Google Container Registry or Artifact Registry uri where the
* Model container image will be copied to.
* This field should only be set when the `exportableContent` field of the
* [Model.supported_export_formats] object contains `IMAGE`.
* </pre>
*
* <code>.google.cloud.aiplatform.v1.ContainerRegistryDestination image_destination = 4;
* </code>
*
* @return The imageDestination.
*/
public com.google.cloud.aiplatform.v1.ContainerRegistryDestination getImageDestination() {
if (imageDestinationBuilder_ == null) {
return imageDestination_ == null
? com.google.cloud.aiplatform.v1.ContainerRegistryDestination.getDefaultInstance()
: imageDestination_;
} else {
return imageDestinationBuilder_.getMessage();
}
}
/**
*
*
* <pre>
* The Google Container Registry or Artifact Registry uri where the
* Model container image will be copied to.
* This field should only be set when the `exportableContent` field of the
* [Model.supported_export_formats] object contains `IMAGE`.
* </pre>
*
* <code>.google.cloud.aiplatform.v1.ContainerRegistryDestination image_destination = 4;
* </code>
*/
public Builder setImageDestination(
com.google.cloud.aiplatform.v1.ContainerRegistryDestination value) {
if (imageDestinationBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
imageDestination_ = value;
onChanged();
} else {
imageDestinationBuilder_.setMessage(value);
}
return this;
}
/**
*
*
* <pre>
* The Google Container Registry or Artifact Registry uri where the
* Model container image will be copied to.
* This field should only be set when the `exportableContent` field of the
* [Model.supported_export_formats] object contains `IMAGE`.
* </pre>
*
* <code>.google.cloud.aiplatform.v1.ContainerRegistryDestination image_destination = 4;
* </code>
*/
public Builder setImageDestination(
com.google.cloud.aiplatform.v1.ContainerRegistryDestination.Builder builderForValue) {
if (imageDestinationBuilder_ == null) {
imageDestination_ = builderForValue.build();
onChanged();
} else {
imageDestinationBuilder_.setMessage(builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* The Google Container Registry or Artifact Registry uri where the
* Model container image will be copied to.
* This field should only be set when the `exportableContent` field of the
* [Model.supported_export_formats] object contains `IMAGE`.
* </pre>
*
* <code>.google.cloud.aiplatform.v1.ContainerRegistryDestination image_destination = 4;
* </code>
*/
public Builder mergeImageDestination(
com.google.cloud.aiplatform.v1.ContainerRegistryDestination value) {
if (imageDestinationBuilder_ == null) {
if (imageDestination_ != null) {
imageDestination_ =
com.google.cloud.aiplatform.v1.ContainerRegistryDestination.newBuilder(
imageDestination_)
.mergeFrom(value)
.buildPartial();
} else {
imageDestination_ = value;
}
onChanged();
} else {
imageDestinationBuilder_.mergeFrom(value);
}
return this;
}
/**
*
*
* <pre>
* The Google Container Registry or Artifact Registry uri where the
* Model container image will be copied to.
* This field should only be set when the `exportableContent` field of the
* [Model.supported_export_formats] object contains `IMAGE`.
* </pre>
*
* <code>.google.cloud.aiplatform.v1.ContainerRegistryDestination image_destination = 4;
* </code>
*/
public Builder clearImageDestination() {
if (imageDestinationBuilder_ == null) {
imageDestination_ = null;
onChanged();
} else {
imageDestination_ = null;
imageDestinationBuilder_ = null;
}
return this;
}
/**
*
*
* <pre>
* The Google Container Registry or Artifact Registry uri where the
* Model container image will be copied to.
* This field should only be set when the `exportableContent` field of the
* [Model.supported_export_formats] object contains `IMAGE`.
* </pre>
*
* <code>.google.cloud.aiplatform.v1.ContainerRegistryDestination image_destination = 4;
* </code>
*/
public com.google.cloud.aiplatform.v1.ContainerRegistryDestination.Builder
getImageDestinationBuilder() {
onChanged();
return getImageDestinationFieldBuilder().getBuilder();
}
/**
*
*
* <pre>
* The Google Container Registry or Artifact Registry uri where the
* Model container image will be copied to.
* This field should only be set when the `exportableContent` field of the
* [Model.supported_export_formats] object contains `IMAGE`.
* </pre>
*
* <code>.google.cloud.aiplatform.v1.ContainerRegistryDestination image_destination = 4;
* </code>
*/
public com.google.cloud.aiplatform.v1.ContainerRegistryDestinationOrBuilder
getImageDestinationOrBuilder() {
if (imageDestinationBuilder_ != null) {
return imageDestinationBuilder_.getMessageOrBuilder();
} else {
return imageDestination_ == null
? com.google.cloud.aiplatform.v1.ContainerRegistryDestination.getDefaultInstance()
: imageDestination_;
}
}
/**
*
*
* <pre>
* The Google Container Registry or Artifact Registry uri where the
* Model container image will be copied to.
* This field should only be set when the `exportableContent` field of the
* [Model.supported_export_formats] object contains `IMAGE`.
* </pre>
*
* <code>.google.cloud.aiplatform.v1.ContainerRegistryDestination image_destination = 4;
* </code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.aiplatform.v1.ContainerRegistryDestination,
com.google.cloud.aiplatform.v1.ContainerRegistryDestination.Builder,
com.google.cloud.aiplatform.v1.ContainerRegistryDestinationOrBuilder>
getImageDestinationFieldBuilder() {
if (imageDestinationBuilder_ == null) {
imageDestinationBuilder_ =
new com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.aiplatform.v1.ContainerRegistryDestination,
com.google.cloud.aiplatform.v1.ContainerRegistryDestination.Builder,
com.google.cloud.aiplatform.v1.ContainerRegistryDestinationOrBuilder>(
getImageDestination(), getParentForChildren(), isClean());
imageDestination_ = null;
}
return imageDestinationBuilder_;
}
@java.lang.Override
public final Builder setUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.cloud.aiplatform.v1.ExportModelRequest.OutputConfig)
}
// @@protoc_insertion_point(class_scope:google.cloud.aiplatform.v1.ExportModelRequest.OutputConfig)
private static final com.google.cloud.aiplatform.v1.ExportModelRequest.OutputConfig
DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.aiplatform.v1.ExportModelRequest.OutputConfig();
}
public static com.google.cloud.aiplatform.v1.ExportModelRequest.OutputConfig
getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<OutputConfig> PARSER =
new com.google.protobuf.AbstractParser<OutputConfig>() {
@java.lang.Override
public OutputConfig parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return new OutputConfig(input, extensionRegistry);
}
};
public static com.google.protobuf.Parser<OutputConfig> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<OutputConfig> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.aiplatform.v1.ExportModelRequest.OutputConfig
getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
public static final int NAME_FIELD_NUMBER = 1;
private volatile java.lang.Object name_;
/**
*
*
* <pre>
* Required. The resource name of the Model to export.
* </pre>
*
* <code>
* string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The name.
*/
@java.lang.Override
public java.lang.String getName() {
java.lang.Object ref = name_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
name_ = s;
return s;
}
}
/**
*
*
* <pre>
* Required. The resource name of the Model to export.
* </pre>
*
* <code>
* string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The bytes for name.
*/
@java.lang.Override
public com.google.protobuf.ByteString getNameBytes() {
java.lang.Object ref = name_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
name_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int OUTPUT_CONFIG_FIELD_NUMBER = 2;
private com.google.cloud.aiplatform.v1.ExportModelRequest.OutputConfig outputConfig_;
/**
*
*
* <pre>
* Required. The desired output location and configuration.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1.ExportModelRequest.OutputConfig output_config = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return Whether the outputConfig field is set.
*/
@java.lang.Override
public boolean hasOutputConfig() {
return outputConfig_ != null;
}
/**
*
*
* <pre>
* Required. The desired output location and configuration.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1.ExportModelRequest.OutputConfig output_config = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return The outputConfig.
*/
@java.lang.Override
public com.google.cloud.aiplatform.v1.ExportModelRequest.OutputConfig getOutputConfig() {
return outputConfig_ == null
? com.google.cloud.aiplatform.v1.ExportModelRequest.OutputConfig.getDefaultInstance()
: outputConfig_;
}
/**
*
*
* <pre>
* Required. The desired output location and configuration.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1.ExportModelRequest.OutputConfig output_config = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
@java.lang.Override
public com.google.cloud.aiplatform.v1.ExportModelRequest.OutputConfigOrBuilder
getOutputConfigOrBuilder() {
return getOutputConfig();
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException {
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(name_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 1, name_);
}
if (outputConfig_ != null) {
output.writeMessage(2, getOutputConfig());
}
unknownFields.writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(name_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, name_);
}
if (outputConfig_ != null) {
size += com.google.protobuf.CodedOutputStream.computeMessageSize(2, getOutputConfig());
}
size += unknownFields.getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.cloud.aiplatform.v1.ExportModelRequest)) {
return super.equals(obj);
}
com.google.cloud.aiplatform.v1.ExportModelRequest other =
(com.google.cloud.aiplatform.v1.ExportModelRequest) obj;
if (!getName().equals(other.getName())) return false;
if (hasOutputConfig() != other.hasOutputConfig()) return false;
if (hasOutputConfig()) {
if (!getOutputConfig().equals(other.getOutputConfig())) return false;
}
if (!unknownFields.equals(other.unknownFields)) return false;
return true;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
hash = (37 * hash) + NAME_FIELD_NUMBER;
hash = (53 * hash) + getName().hashCode();
if (hasOutputConfig()) {
hash = (37 * hash) + OUTPUT_CONFIG_FIELD_NUMBER;
hash = (53 * hash) + getOutputConfig().hashCode();
}
hash = (29 * hash) + unknownFields.hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.aiplatform.v1.ExportModelRequest parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.aiplatform.v1.ExportModelRequest parseFrom(
java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.aiplatform.v1.ExportModelRequest parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.aiplatform.v1.ExportModelRequest parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.aiplatform.v1.ExportModelRequest parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.aiplatform.v1.ExportModelRequest parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.aiplatform.v1.ExportModelRequest parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.aiplatform.v1.ExportModelRequest parseFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.aiplatform.v1.ExportModelRequest parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.aiplatform.v1.ExportModelRequest parseDelimitedFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.aiplatform.v1.ExportModelRequest parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.aiplatform.v1.ExportModelRequest parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() {
return newBuilder();
}
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(com.google.cloud.aiplatform.v1.ExportModelRequest prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
*
*
* <pre>
* Request message for [ModelService.ExportModel][google.cloud.aiplatform.v1.ModelService.ExportModel].
* </pre>
*
* Protobuf type {@code google.cloud.aiplatform.v1.ExportModelRequest}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.aiplatform.v1.ExportModelRequest)
com.google.cloud.aiplatform.v1.ExportModelRequestOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.aiplatform.v1.ModelServiceProto
.internal_static_google_cloud_aiplatform_v1_ExportModelRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.aiplatform.v1.ModelServiceProto
.internal_static_google_cloud_aiplatform_v1_ExportModelRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.aiplatform.v1.ExportModelRequest.class,
com.google.cloud.aiplatform.v1.ExportModelRequest.Builder.class);
}
// Construct using com.google.cloud.aiplatform.v1.ExportModelRequest.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) {}
}
@java.lang.Override
public Builder clear() {
super.clear();
name_ = "";
if (outputConfigBuilder_ == null) {
outputConfig_ = null;
} else {
outputConfig_ = null;
outputConfigBuilder_ = null;
}
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.aiplatform.v1.ModelServiceProto
.internal_static_google_cloud_aiplatform_v1_ExportModelRequest_descriptor;
}
@java.lang.Override
public com.google.cloud.aiplatform.v1.ExportModelRequest getDefaultInstanceForType() {
return com.google.cloud.aiplatform.v1.ExportModelRequest.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.aiplatform.v1.ExportModelRequest build() {
com.google.cloud.aiplatform.v1.ExportModelRequest result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.aiplatform.v1.ExportModelRequest buildPartial() {
com.google.cloud.aiplatform.v1.ExportModelRequest result =
new com.google.cloud.aiplatform.v1.ExportModelRequest(this);
result.name_ = name_;
if (outputConfigBuilder_ == null) {
result.outputConfig_ = outputConfig_;
} else {
result.outputConfig_ = outputConfigBuilder_.build();
}
onBuilt();
return result;
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.cloud.aiplatform.v1.ExportModelRequest) {
return mergeFrom((com.google.cloud.aiplatform.v1.ExportModelRequest) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.aiplatform.v1.ExportModelRequest other) {
if (other == com.google.cloud.aiplatform.v1.ExportModelRequest.getDefaultInstance())
return this;
if (!other.getName().isEmpty()) {
name_ = other.name_;
onChanged();
}
if (other.hasOutputConfig()) {
mergeOutputConfig(other.getOutputConfig());
}
this.mergeUnknownFields(other.unknownFields);
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
com.google.cloud.aiplatform.v1.ExportModelRequest parsedMessage = null;
try {
parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
parsedMessage =
(com.google.cloud.aiplatform.v1.ExportModelRequest) e.getUnfinishedMessage();
throw e.unwrapIOException();
} finally {
if (parsedMessage != null) {
mergeFrom(parsedMessage);
}
}
return this;
}
private java.lang.Object name_ = "";
/**
*
*
* <pre>
* Required. The resource name of the Model to export.
* </pre>
*
* <code>
* string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The name.
*/
public java.lang.String getName() {
java.lang.Object ref = name_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
name_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Required. The resource name of the Model to export.
* </pre>
*
* <code>
* string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The bytes for name.
*/
public com.google.protobuf.ByteString getNameBytes() {
java.lang.Object ref = name_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
name_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Required. The resource name of the Model to export.
* </pre>
*
* <code>
* string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @param value The name to set.
* @return This builder for chaining.
*/
public Builder setName(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
name_ = value;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The resource name of the Model to export.
* </pre>
*
* <code>
* string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return This builder for chaining.
*/
public Builder clearName() {
name_ = getDefaultInstance().getName();
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The resource name of the Model to export.
* </pre>
*
* <code>
* string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @param value The bytes for name to set.
* @return This builder for chaining.
*/
public Builder setNameBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
name_ = value;
onChanged();
return this;
}
private com.google.cloud.aiplatform.v1.ExportModelRequest.OutputConfig outputConfig_;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.aiplatform.v1.ExportModelRequest.OutputConfig,
com.google.cloud.aiplatform.v1.ExportModelRequest.OutputConfig.Builder,
com.google.cloud.aiplatform.v1.ExportModelRequest.OutputConfigOrBuilder>
outputConfigBuilder_;
/**
*
*
* <pre>
* Required. The desired output location and configuration.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1.ExportModelRequest.OutputConfig output_config = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return Whether the outputConfig field is set.
*/
public boolean hasOutputConfig() {
return outputConfigBuilder_ != null || outputConfig_ != null;
}
/**
*
*
* <pre>
* Required. The desired output location and configuration.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1.ExportModelRequest.OutputConfig output_config = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return The outputConfig.
*/
public com.google.cloud.aiplatform.v1.ExportModelRequest.OutputConfig getOutputConfig() {
if (outputConfigBuilder_ == null) {
return outputConfig_ == null
? com.google.cloud.aiplatform.v1.ExportModelRequest.OutputConfig.getDefaultInstance()
: outputConfig_;
} else {
return outputConfigBuilder_.getMessage();
}
}
/**
*
*
* <pre>
* Required. The desired output location and configuration.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1.ExportModelRequest.OutputConfig output_config = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder setOutputConfig(
com.google.cloud.aiplatform.v1.ExportModelRequest.OutputConfig value) {
if (outputConfigBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
outputConfig_ = value;
onChanged();
} else {
outputConfigBuilder_.setMessage(value);
}
return this;
}
/**
*
*
* <pre>
* Required. The desired output location and configuration.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1.ExportModelRequest.OutputConfig output_config = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder setOutputConfig(
com.google.cloud.aiplatform.v1.ExportModelRequest.OutputConfig.Builder builderForValue) {
if (outputConfigBuilder_ == null) {
outputConfig_ = builderForValue.build();
onChanged();
} else {
outputConfigBuilder_.setMessage(builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* Required. The desired output location and configuration.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1.ExportModelRequest.OutputConfig output_config = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder mergeOutputConfig(
com.google.cloud.aiplatform.v1.ExportModelRequest.OutputConfig value) {
if (outputConfigBuilder_ == null) {
if (outputConfig_ != null) {
outputConfig_ =
com.google.cloud.aiplatform.v1.ExportModelRequest.OutputConfig.newBuilder(
outputConfig_)
.mergeFrom(value)
.buildPartial();
} else {
outputConfig_ = value;
}
onChanged();
} else {
outputConfigBuilder_.mergeFrom(value);
}
return this;
}
/**
*
*
* <pre>
* Required. The desired output location and configuration.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1.ExportModelRequest.OutputConfig output_config = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder clearOutputConfig() {
if (outputConfigBuilder_ == null) {
outputConfig_ = null;
onChanged();
} else {
outputConfig_ = null;
outputConfigBuilder_ = null;
}
return this;
}
/**
*
*
* <pre>
* Required. The desired output location and configuration.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1.ExportModelRequest.OutputConfig output_config = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public com.google.cloud.aiplatform.v1.ExportModelRequest.OutputConfig.Builder
getOutputConfigBuilder() {
onChanged();
return getOutputConfigFieldBuilder().getBuilder();
}
/**
*
*
* <pre>
* Required. The desired output location and configuration.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1.ExportModelRequest.OutputConfig output_config = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public com.google.cloud.aiplatform.v1.ExportModelRequest.OutputConfigOrBuilder
getOutputConfigOrBuilder() {
if (outputConfigBuilder_ != null) {
return outputConfigBuilder_.getMessageOrBuilder();
} else {
return outputConfig_ == null
? com.google.cloud.aiplatform.v1.ExportModelRequest.OutputConfig.getDefaultInstance()
: outputConfig_;
}
}
/**
*
*
* <pre>
* Required. The desired output location and configuration.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1.ExportModelRequest.OutputConfig output_config = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.aiplatform.v1.ExportModelRequest.OutputConfig,
com.google.cloud.aiplatform.v1.ExportModelRequest.OutputConfig.Builder,
com.google.cloud.aiplatform.v1.ExportModelRequest.OutputConfigOrBuilder>
getOutputConfigFieldBuilder() {
if (outputConfigBuilder_ == null) {
outputConfigBuilder_ =
new com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.aiplatform.v1.ExportModelRequest.OutputConfig,
com.google.cloud.aiplatform.v1.ExportModelRequest.OutputConfig.Builder,
com.google.cloud.aiplatform.v1.ExportModelRequest.OutputConfigOrBuilder>(
getOutputConfig(), getParentForChildren(), isClean());
outputConfig_ = null;
}
return outputConfigBuilder_;
}
@java.lang.Override
public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.cloud.aiplatform.v1.ExportModelRequest)
}
// @@protoc_insertion_point(class_scope:google.cloud.aiplatform.v1.ExportModelRequest)
private static final com.google.cloud.aiplatform.v1.ExportModelRequest DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.aiplatform.v1.ExportModelRequest();
}
public static com.google.cloud.aiplatform.v1.ExportModelRequest getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<ExportModelRequest> PARSER =
new com.google.protobuf.AbstractParser<ExportModelRequest>() {
@java.lang.Override
public ExportModelRequest parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return new ExportModelRequest(input, extensionRegistry);
}
};
public static com.google.protobuf.Parser<ExportModelRequest> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<ExportModelRequest> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.aiplatform.v1.ExportModelRequest getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
| apache-2.0 |
synapplix/jquants | src/main/java/jquants/motion/VolumeFlowRate.java | 4545 | package jquants.motion;
import static com.googlecode.totallylazy.Sequences.sequence;
import static jquants.space.Volume.CubicFeet;
import static jquants.space.Volume.CubicMeters;
import static jquants.space.Volume.UsGallons;
import static jquants.time.Time.Seconds;
import static jquants.time.Time.SecondsPerDay;
import static jquants.time.Time.SecondsPerHour;
import static jquants.time.Time.SecondsPerMinute;
import com.googlecode.totallylazy.Option;
import jquants.Dimension;
import jquants.Quantity;
import jquants.UnitOfMeasure;
import jquants.space.Volume;
import jquants.time.Time;
import jquants.time.TimeDerivative;
/**
* @author Matahias Braeu
* @since 1.0
*
*/
public class VolumeFlowRate extends Quantity<VolumeFlowRate> implements TimeDerivative<Volume>{
public Volume change;
public Time time;
private VolumeFlowRate(Volume volume, Time time) {
this.change = volume;
this.time = time;
this.valueUnit = CubicMetersPerSecond;
this.value = to(valueUnit);
this.dimension = VolumeFlowRate;
}
private VolumeFlowRate(double value, VolumeFlowRateUnit unit){
this.value = value;
this.valueUnit = unit;
}
public static Option<VolumeFlowRate> toVolumeFlowRate(String s) {
return VolumeFlowRate.parseString(s);
}
public Volume timeIntegrated() {return CubicMeters(toCubicMetersPerSecond());}
public Time time(){ return Seconds(1);}
public double toCubicMetersPerSecond() {return to(CubicMetersPerSecond);}
public double toGallonsPerDay() {return to(GallonsPerDay);}
public double toGallonsPerHour() {return to(GallonsPerHour);}
public double toGallonsPerMinute() {return to(GallonsPerMinute);}
public double toGallonsPerSecond() {return to(GallonsPerSecond);}
public double toCubicFeetPerHour() {return to(CubicFeetPerHour);}
public static class VolumeFlowRateUnit extends UnitOfMeasure<VolumeFlowRate> {
public VolumeFlowRateUnit(String symbol, double multiplier) {
super(symbol, multiplier, true, false, false);
}
@Override
public VolumeFlowRate apply(double n) {
return new VolumeFlowRate(n, this);
}
}
public static final VolumeFlowRateUnit CubicMetersPerSecond = new VolumeFlowRateUnit("m³/s", 1);
public static final VolumeFlowRateUnit CubicFeetPerHour = new VolumeFlowRateUnit("ft³/hr", (CubicMeters.multiplier * CubicFeet.multiplier) / SecondsPerHour);
public static final VolumeFlowRateUnit GallonsPerDay = new VolumeFlowRateUnit("GPD", (CubicMeters.multiplier * UsGallons.multiplier) / SecondsPerDay);
public static final VolumeFlowRateUnit GallonsPerHour = new VolumeFlowRateUnit("GPH", (CubicMeters.multiplier * UsGallons.multiplier) / SecondsPerHour);
public static final VolumeFlowRateUnit GallonsPerMinute = new VolumeFlowRateUnit("GPM", (CubicMeters.multiplier * UsGallons.multiplier) / SecondsPerMinute);
public static final VolumeFlowRateUnit GallonsPerSecond = new VolumeFlowRateUnit("GPS", CubicMeters.multiplier * UsGallons.multiplier);
public static VolumeFlowRate cubicMeterPerSecond = CubicMetersPerSecond(1);
public static VolumeFlowRate cubicFeetPerHour = CubicFeetPerHour(1);
public static VolumeFlowRate gallonPerDay = GallonsPerDay(1);
public static VolumeFlowRate gallonPerHour = GallonsPerHour(1);
public static VolumeFlowRate gallonPerMinute = GallonsPerMinute(1);
public static VolumeFlowRate gallonPerSecond = GallonsPerSecond(1);
public static final Dimension<VolumeFlowRate> VolumeFlowRate = new Dimension<VolumeFlowRate>(
"VolumeFlowRatee",
CubicMetersPerSecond,
sequence(CubicMetersPerSecond, CubicFeetPerHour, GallonsPerHour, GallonsPerDay, GallonsPerHour, GallonsPerMinute, GallonsPerSecond));
public static VolumeFlowRate CubicMetersPerSecond(double value) {return new VolumeFlowRate(value, CubicMetersPerSecond);}
public static VolumeFlowRate CubicFeetPerHour(double value) {return new VolumeFlowRate(value, CubicFeetPerHour);}
public static VolumeFlowRate GallonsPerDay(double value) {return new VolumeFlowRate(value, GallonsPerDay);}
public static VolumeFlowRate GallonsPerHour(double value) {return new VolumeFlowRate(value, GallonsPerHour);}
public static VolumeFlowRate GallonsPerMinute(double value) {return new VolumeFlowRate(value, GallonsPerMinute);}
public static VolumeFlowRate GallonsPerSecond(double value) {return new VolumeFlowRate(value, GallonsPerSecond);}
// implicit object VolumeFlowRateNumeric extends AbstractQuantityNumeric[dimension](CubicMetersPerSecond)
}
| apache-2.0 |
DariusX/camel | core/camel-componentdsl/src/generated/java/org/apache/camel/builder/component/dsl/AwsMqComponentBuilderFactory.java | 9578 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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.apache.camel.builder.component.dsl;
import javax.annotation.Generated;
import org.apache.camel.Component;
import org.apache.camel.builder.component.AbstractComponentBuilder;
import org.apache.camel.builder.component.ComponentBuilder;
import org.apache.camel.component.aws.mq.MQComponent;
/**
* Manage AWS MQ instances.
*
* Generated by camel-package-maven-plugin - do not edit this file!
*/
@Generated("org.apache.camel.maven.packaging.ComponentDslMojo")
public interface AwsMqComponentBuilderFactory {
/**
* AWS MQ (camel-aws-mq)
* Manage AWS MQ instances.
*
* Category: cloud,messaging
* Since: 2.21
* Maven coordinates: org.apache.camel:camel-aws-mq
*/
static AwsMqComponentBuilder awsMq() {
return new AwsMqComponentBuilderImpl();
}
/**
* Builder for the AWS MQ component.
*/
interface AwsMqComponentBuilder extends ComponentBuilder<MQComponent> {
/**
* Amazon AWS Access Key.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: producer
*/
default AwsMqComponentBuilder accessKey(java.lang.String accessKey) {
doSetProperty("accessKey", accessKey);
return this;
}
/**
* To use a existing configured AmazonMQClient as client.
*
* The option is a: <code>com.amazonaws.services.mq.AmazonMQ</code>
* type.
*
* Group: producer
*/
default AwsMqComponentBuilder amazonMqClient(
com.amazonaws.services.mq.AmazonMQ amazonMqClient) {
doSetProperty("amazonMqClient", amazonMqClient);
return this;
}
/**
* The Component configuration.
*
* The option is a:
* <code>org.apache.camel.component.aws.mq.MQConfiguration</code> type.
*
* Group: producer
*/
default AwsMqComponentBuilder configuration(
org.apache.camel.component.aws.mq.MQConfiguration configuration) {
doSetProperty("configuration", configuration);
return this;
}
/**
* Whether the producer should be started lazy (on the first message).
* By starting lazy you can use this to allow CamelContext and routes to
* startup in situations where a producer may otherwise fail during
* starting and cause the route to fail being started. By deferring this
* startup to be lazy then the startup failure can be handled during
* routing messages via Camel's routing error handlers. Beware that when
* the first message is processed then creating and starting the
* producer may take a little time and prolong the total processing time
* of the processing.
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: producer
*/
default AwsMqComponentBuilder lazyStartProducer(
boolean lazyStartProducer) {
doSetProperty("lazyStartProducer", lazyStartProducer);
return this;
}
/**
* The operation to perform. It can be
* listBrokers,createBroker,deleteBroker.
*
* The option is a:
* <code>org.apache.camel.component.aws.mq.MQOperations</code> type.
*
* Group: producer
*/
default AwsMqComponentBuilder operation(
org.apache.camel.component.aws.mq.MQOperations operation) {
doSetProperty("operation", operation);
return this;
}
/**
* To define a proxy host when instantiating the MQ client.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: producer
*/
default AwsMqComponentBuilder proxyHost(java.lang.String proxyHost) {
doSetProperty("proxyHost", proxyHost);
return this;
}
/**
* To define a proxy port when instantiating the MQ client.
*
* The option is a: <code>java.lang.Integer</code> type.
*
* Group: producer
*/
default AwsMqComponentBuilder proxyPort(java.lang.Integer proxyPort) {
doSetProperty("proxyPort", proxyPort);
return this;
}
/**
* To define a proxy protocol when instantiating the MQ client.
*
* The option is a: <code>com.amazonaws.Protocol</code> type.
*
* Default: HTTPS
* Group: producer
*/
default AwsMqComponentBuilder proxyProtocol(
com.amazonaws.Protocol proxyProtocol) {
doSetProperty("proxyProtocol", proxyProtocol);
return this;
}
/**
* The region in which MQ client needs to work. When using this
* parameter, the configuration will expect the capitalized name of the
* region (for example AP_EAST_1) You'll need to use the name
* Regions.EU_WEST_1.name().
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: producer
*/
default AwsMqComponentBuilder region(java.lang.String region) {
doSetProperty("region", region);
return this;
}
/**
* Amazon AWS Secret Key.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: producer
*/
default AwsMqComponentBuilder secretKey(java.lang.String secretKey) {
doSetProperty("secretKey", secretKey);
return this;
}
/**
* Whether the component should use basic property binding (Camel 2.x)
* or the newer property binding with additional capabilities.
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: advanced
*/
default AwsMqComponentBuilder basicPropertyBinding(
boolean basicPropertyBinding) {
doSetProperty("basicPropertyBinding", basicPropertyBinding);
return this;
}
}
class AwsMqComponentBuilderImpl
extends
AbstractComponentBuilder<MQComponent>
implements
AwsMqComponentBuilder {
@Override
protected MQComponent buildConcreteComponent() {
return new MQComponent();
}
private org.apache.camel.component.aws.mq.MQConfiguration getOrCreateConfiguration(
org.apache.camel.component.aws.mq.MQComponent component) {
if (component.getConfiguration() == null) {
component.setConfiguration(new org.apache.camel.component.aws.mq.MQConfiguration());
}
return component.getConfiguration();
}
@Override
protected boolean setPropertyOnComponent(
Component component,
String name,
Object value) {
switch (name) {
case "accessKey": getOrCreateConfiguration((MQComponent) component).setAccessKey((java.lang.String) value); return true;
case "amazonMqClient": getOrCreateConfiguration((MQComponent) component).setAmazonMqClient((com.amazonaws.services.mq.AmazonMQ) value); return true;
case "configuration": ((MQComponent) component).setConfiguration((org.apache.camel.component.aws.mq.MQConfiguration) value); return true;
case "lazyStartProducer": ((MQComponent) component).setLazyStartProducer((boolean) value); return true;
case "operation": getOrCreateConfiguration((MQComponent) component).setOperation((org.apache.camel.component.aws.mq.MQOperations) value); return true;
case "proxyHost": getOrCreateConfiguration((MQComponent) component).setProxyHost((java.lang.String) value); return true;
case "proxyPort": getOrCreateConfiguration((MQComponent) component).setProxyPort((java.lang.Integer) value); return true;
case "proxyProtocol": getOrCreateConfiguration((MQComponent) component).setProxyProtocol((com.amazonaws.Protocol) value); return true;
case "region": getOrCreateConfiguration((MQComponent) component).setRegion((java.lang.String) value); return true;
case "secretKey": getOrCreateConfiguration((MQComponent) component).setSecretKey((java.lang.String) value); return true;
case "basicPropertyBinding": ((MQComponent) component).setBasicPropertyBinding((boolean) value); return true;
default: return false;
}
}
}
} | apache-2.0 |
toliaqat/xenon | xenon-ui/src/main/ui/src/client/app/modules/app/interfaces/ui/modal-context.ts | 280 | import { Notification } from './notification';
/**
* Context for rendering/controlling modals in the view.
*/
export interface ModalContext {
// isOpened: boolean;
name: string;
data: {[key: string]: any};
notifications?: Notification[];
condition?: any;
}
| apache-2.0 |
mswiderski/droolsjbpm-integration | drools-grid/drools-grid-impl/src/main/java/org/drools/grid/remote/GetQueryParametersRemoteCommand.java | 1729 | /*
* Copyright 2012 JBoss by Red Hat.
*
* 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.drools.grid.remote;
import org.drools.command.Context;
import org.drools.command.World;
import org.drools.command.impl.GenericCommand;
import org.drools.command.impl.KnowledgeCommandContext;
import org.drools.rule.Declaration;
import org.drools.runtime.impl.ExecutionResultImpl;
import org.drools.runtime.rule.impl.NativeQueryResults;
/**
*
* @author salaboy
*/
public class GetQueryParametersRemoteCommand implements GenericCommand<String[]>{
private String queryName;
private String localId;
public GetQueryParametersRemoteCommand(String queryName, String localId) {
this.queryName = queryName;
this.localId = localId;
}
public String[] execute(Context context) {
Declaration[] parameters = ((NativeQueryResults)context.getContextManager().getContext( "__TEMP__" ).get( this.localId )).getResults().getParameters();
String[] results = new String[parameters.length];
int i = 0;
for(Declaration param : parameters){
results[i]=param.getIdentifier();
i++;
}
return results;
}
}
| apache-2.0 |
deib-polimi/modaclouds-cpim-library | src/test/java/it/polimi/modaclouds/cpimlibrary/entitymng/tests/BuildersTest.java | 26763 | /**
* Copyright 2013 deib-polimi
* Contact: deib-polimi <marco.miglierina@polimi.it>
*
* 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 it.polimi.modaclouds.cpimlibrary.entitymng.tests;
import it.polimi.modaclouds.cpimlibrary.entitymng.entities.*;
import it.polimi.modaclouds.cpimlibrary.entitymng.migration.OperationType;
import it.polimi.modaclouds.cpimlibrary.entitymng.statements.DeleteStatement;
import it.polimi.modaclouds.cpimlibrary.entitymng.statements.InsertStatement;
import it.polimi.modaclouds.cpimlibrary.entitymng.statements.Statement;
import it.polimi.modaclouds.cpimlibrary.entitymng.statements.UpdateStatement;
import it.polimi.modaclouds.cpimlibrary.entitymng.statements.builders.BuildersConfiguration;
import it.polimi.modaclouds.cpimlibrary.entitymng.statements.utils.CompareOperator;
import it.polimi.modaclouds.cpimlibrary.entitymng.statements.utils.Filter;
import it.polimi.modaclouds.cpimlibrary.entitymng.statements.utils.LogicOperator;
import org.junit.Assert;
import org.junit.Test;
import javax.persistence.Query;
import javax.persistence.TypedQuery;
import java.util.Deque;
import java.util.Iterator;
/**
* @author Fabio Arcidiacono.
*/
public class BuildersTest extends TestBase {
@Test
public void joinTableTest() {
ProjectMTM project = new ProjectMTM();
project.setName("Project 1");
EmployeeMTM employee = new EmployeeMTM();
employee.setName("Fabio");
employee.setSalary(123L);
employee.addProjects(project);
Deque<Statement> statements;
print("insert project");
statements = buildStatements(project, OperationType.INSERT);
Assert.assertNotNull(statements);
Assert.assertEquals(1, statements.size());
Statement statement = statements.removeFirst();
Assert.assertTrue(statement instanceof InsertStatement);
Assert.assertEquals("ProjectMTM", statement.getTable());
Iterator<Filter> fieldsIterator = statement.getFieldsIterator();
Filter filter = fieldsIterator.next();
Assert.assertEquals("PROJECT_ID", filter.getColumn());
Object projId = filter.getValue();
filter = fieldsIterator.next();
Assert.assertEquals("NAME", filter.getColumn());
Assert.assertEquals(CompareOperator.EQUAL, filter.getOperator());
Assert.assertEquals("Project 1", filter.getValue());
// Assert.assertFalse(fieldsIterator.hasNext());
Assert.assertFalse(statement.getConditionsIterator().hasNext());
Assert.assertTrue(statements.isEmpty());
print("insert employee");
statements = buildStatements(employee, OperationType.INSERT);
Assert.assertNotNull(statements);
Assert.assertEquals(2, statements.size());
statement = statements.removeFirst();
Assert.assertTrue(statement instanceof InsertStatement);
Assert.assertEquals("EmployeeMTM", statement.getTable());
fieldsIterator = statement.getFieldsIterator();
filter = fieldsIterator.next();
Assert.assertEquals("EMPLOYEE_ID", filter.getColumn());
Object empId = filter.getValue();
filter = fieldsIterator.next();
Assert.assertEquals("NAME", filter.getColumn());
Assert.assertEquals(CompareOperator.EQUAL, filter.getOperator());
Assert.assertEquals("Fabio", filter.getValue());
filter = fieldsIterator.next();
Assert.assertEquals("SALARY", filter.getColumn());
Assert.assertEquals(CompareOperator.EQUAL, filter.getOperator());
Assert.assertEquals(123L, filter.getValue());
// Assert.assertFalse(fieldsIterator.hasNext());
Assert.assertFalse(statement.getConditionsIterator().hasNext());
statement = statements.removeFirst();
Assert.assertTrue(statement instanceof InsertStatement);
Assert.assertEquals("EMPLOYEE_PROJECT", statement.getTable());
fieldsIterator = statement.getFieldsIterator();
filter = fieldsIterator.next();
Assert.assertEquals("EMPLOYEE_ID", filter.getColumn());
Assert.assertEquals(CompareOperator.EQUAL, filter.getOperator());
Assert.assertEquals(empId, filter.getValue());
filter = fieldsIterator.next();
Assert.assertEquals("PROJECT_ID", filter.getColumn());
Assert.assertEquals(CompareOperator.EQUAL, filter.getOperator());
Assert.assertEquals(projId, filter.getValue());
Assert.assertFalse(fieldsIterator.hasNext());
Assert.assertFalse(statement.getConditionsIterator().hasNext());
Assert.assertTrue(statements.isEmpty());
print("update project");
statements = buildStatements(project, OperationType.UPDATE);
Assert.assertNotNull(statements);
Assert.assertEquals(1, statements.size());
statement = statements.removeFirst();
Assert.assertTrue(statement instanceof UpdateStatement);
Assert.assertEquals("ProjectMTM", statement.getTable());
fieldsIterator = statement.getFieldsIterator();
Assert.assertEquals("PROJECT_ID", filter.getColumn());
Assert.assertEquals(CompareOperator.EQUAL, filter.getOperator());
Assert.assertEquals(projId, filter.getValue());
filter = fieldsIterator.next();
Assert.assertEquals("NAME", filter.getColumn());
Assert.assertEquals(CompareOperator.EQUAL, filter.getOperator());
Assert.assertEquals("Project 1", filter.getValue());
// Assert.assertFalse(fieldsIterator.hasNext());
Iterator<Object> conditionsIterator = statement.getConditionsIterator();
Object condition = conditionsIterator.next();
Assert.assertTrue(condition instanceof Filter);
Assert.assertEquals("PROJECT_ID", ((Filter) condition).getColumn());
Assert.assertEquals(CompareOperator.EQUAL, filter.getOperator());
Assert.assertEquals(projId, ((Filter) condition).getValue());
Assert.assertFalse(conditionsIterator.hasNext());
Assert.assertTrue(statements.isEmpty());
print("update employee");
statements = buildStatements(employee, OperationType.UPDATE);
Assert.assertNotNull(statements);
Assert.assertEquals(1, statements.size());
statement = statements.removeFirst();
Assert.assertTrue(statement instanceof UpdateStatement);
Assert.assertEquals("EmployeeMTM", statement.getTable());
fieldsIterator = statement.getFieldsIterator();
filter = fieldsIterator.next();
Assert.assertEquals("NAME", filter.getColumn());
Assert.assertEquals(CompareOperator.EQUAL, filter.getOperator());
Assert.assertEquals("Fabio", filter.getValue());
filter = fieldsIterator.next();
Assert.assertEquals("SALARY", filter.getColumn());
Assert.assertEquals(CompareOperator.EQUAL, filter.getOperator());
Assert.assertEquals(123L, filter.getValue());
// Assert.assertFalse(fieldsIterator.hasNext());
conditionsIterator = statement.getConditionsIterator();
condition = conditionsIterator.next();
Assert.assertTrue(condition instanceof Filter);
Assert.assertEquals("EMPLOYEE_ID", ((Filter) condition).getColumn());
Assert.assertEquals(CompareOperator.EQUAL, filter.getOperator());
Assert.assertEquals(empId, ((Filter) condition).getValue());
Assert.assertFalse(conditionsIterator.hasNext());
Assert.assertTrue(statements.isEmpty());
print("delete project");
statements = buildStatements(project, OperationType.DELETE);
Assert.assertNotNull(statements);
Assert.assertEquals(2, statements.size());
statement = statements.removeFirst();
Assert.assertTrue(statement instanceof DeleteStatement);
Assert.assertEquals("EMPLOYEE_PROJECT", statement.getTable());
Assert.assertFalse(statement.getFieldsIterator().hasNext());
conditionsIterator = statement.getConditionsIterator();
condition = conditionsIterator.next();
Assert.assertTrue(condition instanceof Filter);
Assert.assertEquals("PROJECT_ID", ((Filter) condition).getColumn());
Assert.assertEquals(CompareOperator.EQUAL, filter.getOperator());
Assert.assertEquals(projId, ((Filter) condition).getValue());
Assert.assertFalse(conditionsIterator.hasNext());
statement = statements.removeFirst();
Assert.assertTrue(statement instanceof DeleteStatement);
Assert.assertEquals("ProjectMTM", statement.getTable());
Assert.assertFalse(statement.getFieldsIterator().hasNext());
conditionsIterator = statement.getConditionsIterator();
condition = conditionsIterator.next();
Assert.assertTrue(condition instanceof Filter);
Assert.assertEquals("PROJECT_ID", ((Filter) condition).getColumn());
Assert.assertEquals(CompareOperator.EQUAL, filter.getOperator());
Assert.assertEquals(projId, ((Filter) condition).getValue());
Assert.assertFalse(conditionsIterator.hasNext());
print("delete employee");
statements = buildStatements(employee, OperationType.DELETE);
Assert.assertNotNull(statements);
Assert.assertEquals(2, statements.size());
statement = statements.removeFirst();
Assert.assertTrue(statement instanceof DeleteStatement);
Assert.assertEquals("EMPLOYEE_PROJECT", statement.getTable());
Assert.assertFalse(statement.getFieldsIterator().hasNext());
conditionsIterator = statement.getConditionsIterator();
condition = conditionsIterator.next();
Assert.assertTrue(condition instanceof Filter);
Assert.assertEquals("EMPLOYEE_ID", ((Filter) condition).getColumn());
Assert.assertEquals(CompareOperator.EQUAL, filter.getOperator());
Assert.assertEquals(empId, ((Filter) condition).getValue());
Assert.assertFalse(conditionsIterator.hasNext());
statement = statements.removeFirst();
Assert.assertTrue(statement instanceof DeleteStatement);
Assert.assertEquals("EmployeeMTM", statement.getTable());
Assert.assertFalse(statement.getFieldsIterator().hasNext());
conditionsIterator = statement.getConditionsIterator();
condition = conditionsIterator.next();
Assert.assertTrue(condition instanceof Filter);
Assert.assertEquals("EMPLOYEE_ID", ((Filter) condition).getColumn());
Assert.assertEquals(CompareOperator.EQUAL, filter.getOperator());
Assert.assertEquals(empId, ((Filter) condition).getValue());
Assert.assertFalse(conditionsIterator.hasNext());
Assert.assertTrue(statements.isEmpty());
}
@Test
public void queryTest() {
Employee employee = new Employee();
employee.setName("Fabio");
employee.setSalary(123L);
Deque<Statement> statements;
print("update");
TypedQuery<Employee> typedQuery = em.createQuery("UPDATE Employee e SET e.salary = :s, e.name = :n2 WHERE e.name = :n OR e.salary <> :s2", Employee.class);
typedQuery.setParameter("s", 789L);
typedQuery.setParameter("s2", 123L);
typedQuery.setParameter("n2", "Pippo");
typedQuery.setParameter("n", "Fabio");
statements = buildStatements(typedQuery);
Assert.assertNotNull(statements);
Assert.assertEquals(1, statements.size());
Statement statement = statements.removeFirst();
Assert.assertTrue(statement instanceof UpdateStatement);
Assert.assertEquals("Employee", statement.getTable());
Iterator<Filter> fieldsIterator = statement.getFieldsIterator();
Filter filter = fieldsIterator.next();
Assert.assertEquals("SALARY", filter.getColumn());
Assert.assertEquals(CompareOperator.EQUAL, filter.getOperator());
Assert.assertEquals(789L, filter.getValue());
filter = fieldsIterator.next();
Assert.assertEquals("NAME", filter.getColumn());
Assert.assertEquals(CompareOperator.EQUAL, filter.getOperator());
Assert.assertEquals("Pippo", filter.getValue());
Assert.assertFalse(fieldsIterator.hasNext());
Iterator<Object> conditionsIterator = statement.getConditionsIterator();
Object condition = conditionsIterator.next();
Assert.assertTrue(condition instanceof Filter);
Assert.assertEquals("NAME", ((Filter) condition).getColumn());
Assert.assertEquals(CompareOperator.EQUAL, ((Filter) condition).getOperator());
Assert.assertEquals("Fabio", ((Filter) condition).getValue());
condition = conditionsIterator.next();
Assert.assertTrue(condition instanceof LogicOperator);
Assert.assertEquals(LogicOperator.OR, condition);
condition = conditionsIterator.next();
Assert.assertTrue(condition instanceof Filter);
Assert.assertEquals("SALARY", ((Filter) condition).getColumn());
Assert.assertEquals(CompareOperator.NOT_EQUAL, ((Filter) condition).getOperator());
Assert.assertEquals(123L, ((Filter) condition).getValue());
Assert.assertTrue(statements.isEmpty());
print("delete");
Query query = em.createQuery("DELETE FROM Employee e WHERE e.name = :n AND e.salary >= :s", Employee.class);
query.setParameter("n", "Pippo");
query.setParameter("s", 123L);
statements = buildStatements(query);
Assert.assertNotNull(statements);
Assert.assertEquals(1, statements.size());
statement = statements.removeFirst();
Assert.assertTrue(statement instanceof DeleteStatement);
Assert.assertEquals("Employee", statement.getTable());
Assert.assertFalse(statement.getFieldsIterator().hasNext());
conditionsIterator = statement.getConditionsIterator();
condition = conditionsIterator.next();
Assert.assertTrue(condition instanceof Filter);
Assert.assertEquals("NAME", ((Filter) condition).getColumn());
Assert.assertEquals(CompareOperator.EQUAL, filter.getOperator());
Assert.assertEquals("Pippo", ((Filter) condition).getValue());
condition = conditionsIterator.next();
Assert.assertTrue(condition instanceof LogicOperator);
Assert.assertEquals(LogicOperator.AND, condition);
condition = conditionsIterator.next();
Assert.assertTrue(condition instanceof Filter);
Assert.assertEquals("SALARY", ((Filter) condition).getColumn());
Assert.assertEquals(CompareOperator.GREATER_THAN_OR_EQUAL, ((Filter) condition).getOperator());
Assert.assertEquals(123L, ((Filter) condition).getValue());
Assert.assertFalse(conditionsIterator.hasNext());
Assert.assertTrue(statements.isEmpty());
}
@Test
public void followCascadeTest() {
Phone phone = new Phone();
phone.setNumber(123456789L);
EmployeeOTO employee = new EmployeeOTO();
employee.setName("Fabio");
employee.setSalary(123L);
employee.setPhone(phone);
Deque<Statement> statements;
BuildersConfiguration.getInstance().followCascades();
print("insert following cascade");
statements = buildStatements(employee, OperationType.INSERT);
Assert.assertNotNull(statements);
Assert.assertEquals(2, statements.size());
Statement statement = statements.removeFirst();
Assert.assertTrue(statement instanceof InsertStatement);
Assert.assertEquals("Phone", statement.getTable());
Iterator<Filter> fieldsIterator = statement.getFieldsIterator();
Assert.assertTrue(fieldsIterator.hasNext());
Filter filter = fieldsIterator.next();
Assert.assertEquals("PHONE_ID", filter.getColumn());
Object phoneId = filter.getValue();
filter = fieldsIterator.next();
Assert.assertEquals("NUMBER", filter.getColumn());
Assert.assertEquals(CompareOperator.EQUAL, filter.getOperator());
Assert.assertEquals(123456789L, filter.getValue());
// Assert.assertFalse(fieldsIterator.hasNext());
Assert.assertFalse(statement.getConditionsIterator().hasNext());
statement = statements.removeFirst();
Assert.assertTrue(statement instanceof InsertStatement);
Assert.assertEquals("EmployeeOTOne", statement.getTable());
fieldsIterator = statement.getFieldsIterator();
filter = fieldsIterator.next();
Assert.assertEquals("EMPLOYEE_ID", filter.getColumn());
Object empId = filter.getValue();
filter = fieldsIterator.next();
Assert.assertEquals("NAME", filter.getColumn());
Assert.assertEquals(CompareOperator.EQUAL, filter.getOperator());
Assert.assertEquals("Fabio", filter.getValue());
filter = fieldsIterator.next();
Assert.assertEquals("SALARY", filter.getColumn());
Assert.assertEquals(CompareOperator.EQUAL, filter.getOperator());
Assert.assertEquals(123L, filter.getValue());
filter = fieldsIterator.next();
Assert.assertEquals("PHONE_ID", filter.getColumn());
Assert.assertEquals(CompareOperator.EQUAL, filter.getOperator());
Assert.assertEquals(phoneId, filter.getValue());
// Assert.assertFalse(fieldsIterator.hasNext());
Assert.assertFalse(statement.getConditionsIterator().hasNext());
Assert.assertTrue(statements.isEmpty());
print("update following cascade");
statements = buildStatements(employee, OperationType.UPDATE);
Assert.assertNotNull(statements);
Assert.assertEquals(2, statements.size());
statement = statements.removeFirst();
Assert.assertTrue(statement instanceof UpdateStatement);
Assert.assertEquals("Phone", statement.getTable());
fieldsIterator = statement.getFieldsIterator();
filter = fieldsIterator.next();
Assert.assertEquals("NUMBER", filter.getColumn());
Assert.assertEquals(CompareOperator.EQUAL, filter.getOperator());
Assert.assertEquals(123456789L, filter.getValue());
// Assert.assertFalse(fieldsIterator.hasNext());
Iterator<Object> conditionsIterator = statement.getConditionsIterator();
Object condition = conditionsIterator.next();
Assert.assertTrue(condition instanceof Filter);
Assert.assertEquals("PHONE_ID", ((Filter) condition).getColumn());
Assert.assertEquals(CompareOperator.EQUAL, ((Filter) condition).getOperator());
Assert.assertEquals(phoneId, ((Filter) condition).getValue());
statement = statements.removeFirst();
Assert.assertTrue(statement instanceof UpdateStatement);
Assert.assertEquals("EmployeeOTOne", statement.getTable());
fieldsIterator = statement.getFieldsIterator();
filter = fieldsIterator.next();
Assert.assertEquals("NAME", filter.getColumn());
Assert.assertEquals(CompareOperator.EQUAL, filter.getOperator());
Assert.assertEquals("Fabio", filter.getValue());
filter = fieldsIterator.next();
Assert.assertEquals("SALARY", filter.getColumn());
Assert.assertEquals(CompareOperator.EQUAL, filter.getOperator());
Assert.assertEquals(123L, filter.getValue());
filter = fieldsIterator.next();
Assert.assertEquals("PHONE_ID", filter.getColumn());
Assert.assertEquals(CompareOperator.EQUAL, filter.getOperator());
Assert.assertEquals(phoneId, filter.getValue());
// Assert.assertFalse(fieldsIterator.hasNext());
conditionsIterator = statement.getConditionsIterator();
condition = conditionsIterator.next();
Assert.assertTrue(condition instanceof Filter);
Assert.assertEquals("EMPLOYEE_ID", ((Filter) condition).getColumn());
Assert.assertEquals(CompareOperator.EQUAL, ((Filter) condition).getOperator());
Assert.assertEquals(empId, ((Filter) condition).getValue());
Assert.assertFalse(conditionsIterator.hasNext());
Assert.assertTrue(statements.isEmpty());
print("delete following cascade");
statements = buildStatements(employee, OperationType.DELETE);
Assert.assertNotNull(statements);
Assert.assertEquals(2, statements.size());
statement = statements.removeFirst();
Assert.assertTrue(statement instanceof DeleteStatement);
Assert.assertEquals("Phone", statement.getTable());
Assert.assertFalse(statement.getFieldsIterator().hasNext());
conditionsIterator = statement.getConditionsIterator();
condition = conditionsIterator.next();
Assert.assertTrue(condition instanceof Filter);
Assert.assertEquals("PHONE_ID", ((Filter) condition).getColumn());
Assert.assertEquals(CompareOperator.EQUAL, ((Filter) condition).getOperator());
Assert.assertEquals(phoneId, ((Filter) condition).getValue());
Assert.assertFalse(conditionsIterator.hasNext());
statement = statements.removeFirst();
Assert.assertTrue(statement instanceof DeleteStatement);
Assert.assertEquals("EmployeeOTOne", statement.getTable());
Assert.assertFalse(statement.getFieldsIterator().hasNext());
conditionsIterator = statement.getConditionsIterator();
condition = conditionsIterator.next();
Assert.assertTrue(condition instanceof Filter);
Assert.assertEquals("EMPLOYEE_ID", ((Filter) condition).getColumn());
Assert.assertEquals(CompareOperator.EQUAL, ((Filter) condition).getOperator());
Assert.assertEquals(empId, ((Filter) condition).getValue());
Assert.assertFalse(conditionsIterator.hasNext());
Assert.assertTrue(statements.isEmpty());
}
@Test
public void noFollowCascadeTest() {
Phone phone = new Phone();
phone.setNumber(123456789L);
EmployeeOTO employee = new EmployeeOTO();
employee.setName("Fabio");
employee.setSalary(123L);
employee.setPhone(phone);
Deque<Statement> statements;
BuildersConfiguration.getInstance().doNotFollowCascades();
print("insert NO following cascade");
statements = buildStatements(employee, OperationType.INSERT);
Assert.assertNotNull(statements);
Assert.assertEquals(1, statements.size());
Statement statement = statements.removeFirst();
Assert.assertTrue(statement instanceof InsertStatement);
Assert.assertEquals("EmployeeOTOne", statement.getTable());
Iterator<Filter> fieldsIterator = statement.getFieldsIterator();
Filter filter = fieldsIterator.next();
Assert.assertEquals("EMPLOYEE_ID", filter.getColumn());
Object empId = filter.getValue();
filter = fieldsIterator.next();
Assert.assertEquals("NAME", filter.getColumn());
Assert.assertEquals(CompareOperator.EQUAL, filter.getOperator());
Assert.assertEquals("Fabio", filter.getValue());
filter = fieldsIterator.next();
Assert.assertEquals("SALARY", filter.getColumn());
Assert.assertEquals(CompareOperator.EQUAL, filter.getOperator());
Assert.assertEquals(123L, filter.getValue());
filter = fieldsIterator.next();
Assert.assertEquals("PHONE_ID", filter.getColumn());
Assert.assertEquals(CompareOperator.EQUAL, filter.getOperator());
// Assert.assertFalse(fieldsIterator.hasNext());
Assert.assertFalse(statement.getConditionsIterator().hasNext());
Assert.assertTrue(statements.isEmpty());
print("update NO following cascade");
statements = buildStatements(employee, OperationType.UPDATE);
Assert.assertNotNull(statements);
Assert.assertEquals(1, statements.size());
statement = statements.removeFirst();
Assert.assertTrue(statement instanceof UpdateStatement);
Assert.assertEquals("EmployeeOTOne", statement.getTable());
fieldsIterator = statement.getFieldsIterator();
filter = fieldsIterator.next();
Assert.assertEquals("NAME", filter.getColumn());
Assert.assertEquals(CompareOperator.EQUAL, filter.getOperator());
Assert.assertEquals("Fabio", filter.getValue());
filter = fieldsIterator.next();
Assert.assertEquals("SALARY", filter.getColumn());
Assert.assertEquals(CompareOperator.EQUAL, filter.getOperator());
Assert.assertEquals(123L, filter.getValue());
filter = fieldsIterator.next();
Assert.assertEquals("PHONE_ID", filter.getColumn());
Assert.assertEquals(CompareOperator.EQUAL, filter.getOperator());
// Assert.assertFalse(fieldsIterator.hasNext());
Iterator<Object> conditionsIterator = statement.getConditionsIterator();
Object condition = conditionsIterator.next();
Assert.assertTrue(condition instanceof Filter);
Assert.assertEquals("EMPLOYEE_ID", ((Filter) condition).getColumn());
Assert.assertEquals(CompareOperator.EQUAL, ((Filter) condition).getOperator());
Assert.assertEquals(empId, ((Filter) condition).getValue());
Assert.assertFalse(conditionsIterator.hasNext());
Assert.assertTrue(statements.isEmpty());
print("delete NO following cascade");
statements = buildStatements(employee, OperationType.DELETE);
Assert.assertNotNull(statements);
Assert.assertEquals(1, statements.size());
statement = statements.removeFirst();
Assert.assertTrue(statement instanceof DeleteStatement);
Assert.assertEquals("EmployeeOTOne", statement.getTable());
Assert.assertFalse(statement.getFieldsIterator().hasNext());
conditionsIterator = statement.getConditionsIterator();
condition = conditionsIterator.next();
Assert.assertTrue(condition instanceof Filter);
Assert.assertEquals("EMPLOYEE_ID", ((Filter) condition).getColumn());
Assert.assertEquals(CompareOperator.EQUAL, ((Filter) condition).getOperator());
Assert.assertEquals(empId, ((Filter) condition).getValue());
Assert.assertFalse(conditionsIterator.hasNext());
Assert.assertTrue(statements.isEmpty());
}
}
| apache-2.0 |
tensorflow/benchmarks | perfzero/lib/cloud_manager.py | 16087 | #!/usr/bin/python
#
# Copyright 2019 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Helper script to create, query and stop machine in GCP."""
from __future__ import print_function
import argparse
import getpass
import logging
import subprocess
import sys
import time
INSTANCE_NAME_PREFIX = 'perfzero-dev-'
def run_command(cmd, is_from_user=False):
"""Runs list of command and throw error if return code is non-zero.
Args:
cmd: Command to execute
is_from_user: If true, log the command and the command output in INFO level.
Otherwise, log these in the DEBUG level.
Returns:
a string representing the command output
Raises:
Exception: raised when the command execution has non-zero exit code
"""
_log = logging.info if is_from_user else logging.debug
_log('Executing command: {}'.format(cmd))
p = subprocess.Popen(cmd, stdout=subprocess.PIPE,
stderr=subprocess.STDOUT, shell=True)
exit_code = None
line = ''
stdout = ''
while exit_code is None or line:
exit_code = p.poll()
line = p.stdout.readline().decode('utf-8')
stdout += line
_log(line)
if exit_code and is_from_user:
sys.exit(exit_code)
elif exit_code:
raise Exception('Command:\n{}\nfailed with output:\n{}'.format(cmd, stdout))
return stdout
def get_instance_name(username):
return INSTANCE_NAME_PREFIX + username
def get_machine_type(machine_type, accelerator_count):
"""Get machine type for the instance.
- Use the user-specified machine_type if it is not None
- Otherwise, use the standard type with cpu_count = 8 x accelerator_count
if user-specified accelerator_count > 0
- Otherwise, use the standard type with 8 cpu
Args:
machine_type: machine_type specified by the user
accelerator_count: accelerator count
Returns:
the machine type used for the instance
"""
if machine_type:
return machine_type
cpu_count = max(accelerator_count, 1) * 8
return 'n1-standard-{}'.format(cpu_count)
def _ssh_prefix(project, zone, internal_ip, key_file):
if internal_ip:
ssh_prefix = 'gcloud beta compute ssh --internal-ip'
else:
ssh_prefix = 'gcloud compute ssh'
if key_file:
ssh_prefix = '{} --ssh-key-file={}'.format(ssh_prefix, key_file)
return '{} --project={} --zone={}'.format(ssh_prefix, project, zone)
def create(username, project, zone, machine_type, accelerator_count,
accelerator_type, image, nvme_count, ssh_internal_ip, ssh_key_file,
cpu_min_platform=None, boot_ssd_size=None):
"""Create gcloud computing instance.
Args:
username: the username of the current user
project: project name
zone: zone of the GCP computing instance
machine_type: the machine type used for the instance
accelerator_count: the number of pieces of the accelerator to attach to
the instance
accelerator_type: the specific type of accelerator to attach to the instance
image: the name of the image that the disk will be initialized with
nvme_count: the number of NVME local SSD devices to attach to the instance
ssh_internal_ip: internal ip to use for ssh.
ssh_key_file: ssh key file to use to connect to instance.
cpu_min_platform: minimum CPU platform to use, if None use default.
boot_ssd_size: If set boot disk is changed to SSD and this size(GB) is used.
"""
instance_name = get_instance_name(username)
machine_type = get_machine_type(machine_type, accelerator_count)
logging.debug('Creating gcloud computing instance %s', instance_name)
cmd = '''gcloud compute instances create {} \
--image={} \
--project={} \
--zone={} \
--machine-type={} \
--maintenance-policy=TERMINATE \
'''.format(instance_name, image, project, zone, machine_type)
if boot_ssd_size:
cmd += '--boot-disk-size={}GB --boot-disk-type=pd-ssd '.format(
boot_ssd_size)
if accelerator_count > 0:
cmd += '--accelerator=count={},type={} '.format(
accelerator_count, accelerator_type)
if cpu_min_platform:
cmd += '--min-cpu-platform="{}" '.format(cpu_min_platform)
for _ in range(nvme_count):
cmd += '--local-ssd=interface=NVME '
run_command(cmd, is_from_user=True)
logging.info('Successfully created gcloud computing instance %s '
'with %s accelerator.\n', instance_name, accelerator_count)
ssh_prefix = _ssh_prefix(project, zone, ssh_internal_ip, ssh_key_file)
# Wait until we can ssh to the newly created computing instance
cmd = '{} --strict-host-key-checking=no --command="exit" {}'.format(
ssh_prefix, instance_name)
ssh_remaining_retries = 12
ssh_error = None
while ssh_remaining_retries > 0:
ssh_remaining_retries -= 1
try:
run_command(cmd, is_from_user=False)
ssh_error = None
except Exception as error: # pylint: disable=broad-except
ssh_error = error
if ssh_remaining_retries:
logging.info('Cannot ssh to the computing instance. '
'Try again after 5 seconds')
time.sleep(5)
else:
logging.error('Cannot ssh to the computing instance after '
'60 seconds due to error:\n%s', str(ssh_error))
if ssh_error:
logging.info('Run the commands below manually after ssh into the computing '
'instance:\n'
'git clone https://github.com/tensorflow/benchmarks.git\n'
'sudo usermod -a -G docker $USER\n')
else:
cmd = '{} --command="git clone {}" {}'.format(
ssh_prefix, 'https://github.com/tensorflow/benchmarks.git',
instance_name)
run_command(cmd, is_from_user=True)
logging.info('Successfully checked-out PerfZero code on the '
'computing instance\n')
cmd = '{} --command="sudo usermod -a -G docker $USER" {}'.format(
ssh_prefix, instance_name)
run_command(cmd, is_from_user=True)
logging.info('Successfully added user to the docker group\n')
cmd = '{} {} -- -L 6006:127.0.0.1:6006'.format(ssh_prefix, instance_name)
logging.info('Run the command below to ssh to the instance together with '
'port forwarding for tensorboard:\n%s\n', cmd)
def status(username, project, zone, ssh_internal_ip, ssh_key_file):
"""Query the status of the computing instance.
Args:
username: the username of the current user.
project: project name.
zone: zone of the GCP computing instance.
ssh_internal_ip: internal ip of the instance.
ssh_key_file: SSH key file to use to connect to the instance.
"""
instance_name = get_instance_name(username)
logging.debug('Querying status of gcloud computing instance %s of '
'project %s in zone %s', instance_name, project, zone)
cmd = 'gcloud compute instances list --filter="name={} AND zone:{}" --project {}'.format( # pylint: disable=line-too-long
instance_name, zone, project)
stdout = run_command(cmd, is_from_user=True)
num_instances = len(stdout.splitlines()) - 1
logging.info('\nFound %s gcloud computing instance with name %s.\n',
num_instances, instance_name)
if num_instances == 1:
cmd = '{} {} -- -L 6006:127.0.0.1:6006'.format(
_ssh_prefix(project, zone, ssh_internal_ip, ssh_key_file),
instance_name)
logging.info('Run the command below to ssh to the instance together with '
'port forwarding for tensorboard:\n%s\n', cmd)
def list_all(project):
logging.debug('Finding all gcloud computing instance of project %s created '
'for PerfZero test', project)
cmd = 'gcloud compute instances list --filter="name ~ {}" --project={}'.format( # pylint: disable=line-too-long
INSTANCE_NAME_PREFIX, project)
stdout = run_command(cmd, is_from_user=True)
num_instances = len(stdout.splitlines()) - 1
logging.info('\nFound %s gcloud computing instance of project %s created '
'for PerfZero test', num_instances, project)
def start(username, project, zone):
instance_name = get_instance_name(username)
logging.debug('Starting gcloud computing instance %s of project %s '
'in zone %s', instance_name, project, zone)
cmd = 'gcloud compute instances start {} --project={} --zone={}'.format(
instance_name, project, zone)
run_command(cmd, is_from_user=True)
logging.debug('\nSuccessfully started gcloud computing instance %s of '
'project %s in zone %s', instance_name, project, zone)
def stop(username, project, zone):
instance_name = get_instance_name(username)
logging.debug('Stopping gcloud computing instance %s of project %s in '
'zone %s', instance_name, project, zone)
cmd = 'gcloud compute instances stop {} --project={} --zone={}'.format(
instance_name, project, zone)
run_command(cmd, is_from_user=True)
logging.debug('\nSuccessfully stopped gcloud computing instance %s of '
'project %s in zone %s', instance_name, project, zone)
def delete(username, project, zone):
instance_name = get_instance_name(username)
logging.debug('Deleting gcloud computing instance %s of project %s in '
'zone %s', instance_name, project, zone)
cmd = 'echo Y | gcloud compute instances delete {} --project={} --zone={}'.format( # pylint: disable=line-too-long
instance_name, project, zone)
run_command(cmd, is_from_user=True)
logging.debug('\nSuccessfully deleted gcloud computing instance %s of '
'project %s in zone %s', instance_name, project, zone)
def parse_arguments(argv, command): # pylint: disable=redefined-outer-name
"""Parse command line arguments and return parsed flags.
Args:
argv: command line arguments
command: the subcommand requested by the user
Returns:
parsed flags
"""
# pylint: disable=redefined-outer-name
parser = argparse.ArgumentParser(
usage='cloud_manager.py {} [<args>]'.format(command),
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument(
'--debug',
action='store_true',
help='If set, use debug level logging. Otherwise, use info level logging'
)
parser.add_argument(
'--project',
default='google.com:tensorflow-performance',
type=str,
help='Google Cloud Platform project name to use for this invocation'
)
if command in ['create', 'start', 'stop', 'delete', 'status']:
parser.add_argument(
'--username',
default=getpass.getuser(),
type=str,
help='''Username that uniquely identifies the name of computing instance created for PerfZero.
The default value is your ldap username.
''')
parser.add_argument(
'--zone',
default='us-west1-b',
type=str,
help='Zone of the instance to create.'
)
parser.add_argument(
'--ssh-internal-ip',
action='store_true',
help='If set, use internal IP for ssh with `gcloud beta compute ssh`.'
)
parser.add_argument(
'--ssh-key-file',
default=None,
type=str,
help='The ssh key to use with with `gcloud (beta) compute ssh`.'
)
if command == 'create':
parser.add_argument(
'--accelerator_count',
default=1,
type=int,
help='The number of pieces of the accelerator to attach to the instance'
)
parser.add_argument(
'--accelerator_type',
default='nvidia-tesla-v100',
type=str,
help='''The specific type (e.g. nvidia-tesla-v100 for nVidia Tesla V100) of
accelerator to attach to the instance. Use 'gcloud compute accelerator-types list --project=${project_name}' to
learn about all available accelerator types.
''')
parser.add_argument(
'--cpu_min_platform',
default=None,
type=str,
help='''Minimum cpu platform, only needed for CPU only instances.''')
parser.add_argument(
'--machine_type',
default=None,
type=str,
help='''The machine type used for the instance. To get a list of available machine
types, run 'gcloud compute machine-types list --project=${project_name}'
''')
parser.add_argument(
'--image',
default='tf-ubuntu-1604-20180927-410',
type=str,
help='''Specifies the name of the image that the disk will be initialized with.
A new disk will be created based on the given image. To view a list of
public images and projects, run 'gcloud compute images list --project=${project_name}'. It is best
practice to use image when a specific version of an image is needed.
''')
parser.add_argument(
'--nvme_count',
default=0,
type=int,
help='''Specifies the number of NVME local SSD devices to attach to the instance.
'''
)
parser.add_argument(
'--boot_ssd_size',
default=None,
type=int,
help='''Specifies the size (GB) of the boot disk or size is the image
size. Setting this also changes boot disk to Persistent SSD.
'''
)
flags, unparsed = parser.parse_known_args(argv) # pylint: disable=redefined-outer-name
if unparsed:
logging.error('Arguments %s are not recognized', unparsed)
sys.exit(1)
level = logging.DEBUG if flags.debug else logging.INFO
logging.basicConfig(format='%(message)s', level=level)
return flags
if __name__ == '__main__':
parser = argparse.ArgumentParser(
usage='''cloud_manager.py <command> [<args>]
The supported commands are:
create: Create a computing instance in gcloud that is unique to the specified username, which is your ldap by default
start: Start the computing instance in gcloud that is unique to the specified username, which is your ldap by default
stop: Stop the computing instance in gcloud that is unique to the specified username, which is your ldap by default
delete: Delete the computing instance in gcloud that is unique to the specified username, which is your ldap by default
status: Query the status and information of the computing instance in gcloud that is unique to the specified username, which is your ldap by default
list_all: Query the status of all computing instances that are created by this script.'''
)
parser.add_argument(
'command',
type=str
)
flags = parser.parse_args(sys.argv[1:2])
command = flags.command
if not hasattr(sys.modules[__name__], command):
print('Error: The command <{}> is not recognized\n'.format(command))
parser.print_help()
sys.exit(1)
flags = parse_arguments(sys.argv[2:], command)
if command == 'create':
create(flags.username, flags.project, flags.zone, flags.machine_type,
flags.accelerator_count, flags.accelerator_type, flags.image,
flags.nvme_count, flags.ssh_internal_ip, flags.ssh_key_file,
cpu_min_platform=flags.cpu_min_platform,
boot_ssd_size=flags.boot_ssd_size)
elif command == 'start':
start(flags.username, flags.project, flags.zone)
elif command == 'stop':
stop(flags.username, flags.project, flags.zone)
elif command == 'delete':
delete(flags.username, flags.project, flags.zone)
elif command == 'status':
status(flags.username, flags.project, flags.zone, flags.ssh_internal_ip,
flags.ssh_key_file)
elif command == 'list_all':
list_all(flags.project)
| apache-2.0 |
lmjacksoniii/hazelcast | hazelcast/src/main/java/com/hazelcast/nio/tcp/TcpIpConnection.java | 9931 | /*
* Copyright (c) 2008-2016, Hazelcast, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hazelcast.nio.tcp;
import com.hazelcast.internal.metrics.DiscardableMetricsProvider;
import com.hazelcast.internal.metrics.MetricsProvider;
import com.hazelcast.internal.metrics.MetricsRegistry;
import com.hazelcast.internal.metrics.Probe;
import com.hazelcast.internal.networking.IOThreadingModel;
import com.hazelcast.internal.networking.SocketChannelWrapper;
import com.hazelcast.internal.networking.SocketConnection;
import com.hazelcast.internal.networking.SocketReader;
import com.hazelcast.internal.networking.SocketWriter;
import com.hazelcast.logging.ILogger;
import com.hazelcast.nio.Address;
import com.hazelcast.nio.ConnectionType;
import com.hazelcast.nio.IOService;
import com.hazelcast.nio.OutboundFrame;
import java.io.EOFException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.SocketException;
import java.nio.channels.CancelledKeyException;
import java.util.concurrent.atomic.AtomicBoolean;
/**
* The Tcp/Ip implementation of the {@link com.hazelcast.nio.Connection}.
* <p>
* A {@link TcpIpConnection} is not responsible for reading or writing data to a socket, this is done through:
* <ol>
* <li>{@link SocketReader}: which care of reading from the socket and feeding it into the system/li>
* <li>{@link SocketWriter}: which care of writing data to the socket.</li>
* </ol>
*
* @see IOThreadingModel
*/
@SuppressWarnings("checkstyle:methodcount")
public final class TcpIpConnection implements SocketConnection, MetricsProvider, DiscardableMetricsProvider {
private final SocketChannelWrapper socketChannel;
private final SocketReader socketReader;
private final SocketWriter socketWriter;
private final TcpIpConnectionManager connectionManager;
private final AtomicBoolean alive = new AtomicBoolean(true);
private final ILogger logger;
private final int connectionId;
private final IOService ioService;
private Address endPoint;
private TcpIpConnectionMonitor monitor;
private volatile ConnectionType type = ConnectionType.NONE;
private volatile Throwable closeCause;
private volatile String closeReason;
public TcpIpConnection(TcpIpConnectionManager connectionManager,
int connectionId,
SocketChannelWrapper socketChannel,
IOThreadingModel ioThreadingModel) {
this.connectionId = connectionId;
this.connectionManager = connectionManager;
this.ioService = connectionManager.getIoService();
this.logger = ioService.getLoggingService().getLogger(TcpIpConnection.class);
this.socketChannel = socketChannel;
this.socketWriter = ioThreadingModel.newSocketWriter(this);
this.socketReader = ioThreadingModel.newSocketReader(this);
}
@Override
public void provideMetrics(MetricsRegistry registry) {
Socket socket = socketChannel.socket();
SocketAddress localSocketAddress = socket != null ? socket.getLocalSocketAddress() : null;
SocketAddress remoteSocketAddress = socket != null ? socket.getRemoteSocketAddress() : null;
String metricsId = localSocketAddress + "->" + remoteSocketAddress;
registry.scanAndRegister(socketWriter, "tcp.connection[" + metricsId + "].out");
registry.scanAndRegister(socketReader, "tcp.connection[" + metricsId + "].in");
}
@Override
public void discardMetrics(MetricsRegistry registry) {
registry.deregister(socketReader);
registry.deregister(socketWriter);
}
public SocketReader getSocketReader() {
return socketReader;
}
public SocketWriter getSocketWriter() {
return socketWriter;
}
@Override
public SocketChannelWrapper getSocketChannel() {
return socketChannel;
}
@Override
public ConnectionType getType() {
return type;
}
@Override
public void setType(ConnectionType type) {
if (this.type == ConnectionType.NONE) {
this.type = type;
}
}
@Probe
private int getConnectionType() {
ConnectionType t = type;
return t == null ? -1 : t.ordinal();
}
public TcpIpConnectionManager getConnectionManager() {
return connectionManager;
}
@Override
public InetAddress getInetAddress() {
return socketChannel.socket().getInetAddress();
}
@Override
public int getPort() {
return socketChannel.socket().getPort();
}
@Override
public InetSocketAddress getRemoteSocketAddress() {
return (InetSocketAddress) socketChannel.socket().getRemoteSocketAddress();
}
@Override
public boolean isAlive() {
return alive.get();
}
@Override
public long lastWriteTimeMillis() {
return socketWriter.lastWriteTimeMillis();
}
@Override
public long lastReadTimeMillis() {
return socketReader.lastReadTimeMillis();
}
@Override
public Address getEndPoint() {
return endPoint;
}
public void setEndPoint(Address endPoint) {
this.endPoint = endPoint;
}
public void setMonitor(TcpIpConnectionMonitor monitor) {
this.monitor = monitor;
}
public TcpIpConnectionMonitor getMonitor() {
return monitor;
}
public int getConnectionId() {
return connectionId;
}
public void setSendBufferSize(int size) throws SocketException {
socketChannel.socket().setSendBufferSize(size);
}
public void setReceiveBufferSize(int size) throws SocketException {
socketChannel.socket().setReceiveBufferSize(size);
}
@Override
public boolean isClient() {
ConnectionType t = type;
return (t != null) && t != ConnectionType.NONE && t.isClient();
}
/**
* Starts this connection.
* <p>
* Starting means that the connection is going to register itself to listen to incoming traffic.
*/
public void start() {
socketReader.init();
}
@Override
public boolean write(OutboundFrame frame) {
if (!alive.get()) {
if (logger.isFinestEnabled()) {
logger.finest("Connection is closed, won't write packet -> " + frame);
}
return false;
}
socketWriter.write(frame);
return true;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof TcpIpConnection)) {
return false;
}
TcpIpConnection that = (TcpIpConnection) o;
return connectionId == that.getConnectionId();
}
@Override
public int hashCode() {
return connectionId;
}
@Override
public void close(String reason, Throwable cause) {
if (!alive.compareAndSet(true, false)) {
// it is already closed.
return;
}
this.closeCause = cause;
this.closeReason = reason;
logClose();
try {
if (socketChannel != null && socketChannel.isOpen()) {
socketReader.close();
socketWriter.close();
socketChannel.close();
}
} catch (Exception e) {
logger.warning(e);
}
connectionManager.onClose(this);
ioService.onDisconnect(endPoint, cause);
if (cause != null && monitor != null) {
monitor.onError(cause);
}
}
private void logClose() {
String message = toString() + " closed. Reason: ";
if (closeReason != null) {
message += closeReason;
} else if (closeCause != null) {
message += closeCause.getClass().getName() + "[" + closeCause.getMessage() + "]";
} else {
message += "Socket explicitly closed";
}
if (ioService.isActive()) {
if (closeCause == null || closeCause instanceof EOFException || closeCause instanceof CancelledKeyException) {
logger.info(message);
} else {
logger.warning(message, closeCause);
}
} else {
if (closeCause == null) {
logger.finest(message);
} else {
logger.finest(message, closeCause);
}
}
}
@Override
public Throwable getCloseCause() {
return closeCause;
}
@Override
public String getCloseReason() {
if (closeReason == null) {
return closeCause == null ? null : closeCause.getMessage();
} else {
return closeReason;
}
}
@Override
public String toString() {
Socket socket = socketChannel.socket();
SocketAddress localSocketAddress = socket != null ? socket.getLocalSocketAddress() : null;
SocketAddress remoteSocketAddress = socket != null ? socket.getRemoteSocketAddress() : null;
return "Connection[id=" + connectionId
+ ", " + localSocketAddress + "->" + remoteSocketAddress
+ ", endpoint=" + endPoint
+ ", alive=" + alive
+ ", type=" + type
+ "]";
}
}
| apache-2.0 |
android-art-intel/Nougat | art-extension/tools/StressRunner/src/ArchiveStressor.java | 4879 | /*
* Copyright (C) 2015 Intel Corporation.
*
* 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 java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.jar.JarEntry;
import java.util.jar.JarInputStream;
import java.util.jar.JarOutputStream;
public class ArchiveStressor extends BaseStressor {
int threadCnt = processorsNmbr * 4;
boolean append = false;
public static void main(String[] args) {
ArchiveStressor as = new ArchiveStressor();
Run obj = as.new Run(1);
obj.start();
try {
Thread.sleep(200);
obj.stopIt = 1;
obj.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
/*
* Note, this method called through the Method.invoke() and should return to
* the main thread ASAP
*/
public void run(String[] args) {
if (args.length > 0) {
try {
threadCnt = Integer.parseInt(args[0]);
} catch (Exception e) {
// just use default value
}
}
if (args.length > 1) {
try {
append = Boolean.parseBoolean(args[1]);
} catch (Exception e) {
// just use default value
}
}
new DoNothing().start();
}
class DoNothing extends Thread {
public void run() {
Run[] threads = new Run[threadCnt];
for (int i = 0; i < threads.length; i++) {
threads[i] = new Run(i);
threads[i].start();
}
while (!stopStressor) {
for (int i = 1; i < threads.length; i++)
threads[i - 1].i = threads[i].i;
Thread.yield();
}
for (int i = 0; i < threads.length; i++) {
threads[i].stopIt = 1;
}
}
}
class Run extends Thread {
volatile int stopIt = 0;
volatile long i = 0;
public int id = 0;
public Run(int id) {
this.id = id;
}
public void run() {
/* Before using ArchiveStressor you should push jar file to Android device:
$ adb push /export/users/qa/tools/java-1.6.0-openjdk-1.6.0.0/jre/lib/jce.jar /data
ArchiveStressor can work with regular jar files only
Android jars like StressRunner.jar, /system/framework/core.jar cause
java.util.zip.ZipException: no Entry
jars like jsse.jar, rt.jar seem to be too large for this stressor:
java.util.zip.ZipException: CRC mismatch
at java.util.zip.ZipOutputStream.closeEntry(ZipOutputStream.java:145)
at java.util.zip.ZipOutputStream.finish(ZipOutputStream.java:234)
at java.util.zip.ZipOutputStream.close(ZipOutputStream.java:119)
at ArchiveStressor$Run.run(ArchiveStressor.java:127)
*/
String inFileName = "/data/jce.jar";
String outFileName = "/data/ArchiveStressor.jar." + id;
try {
while (stopIt != 1) {
JarInputStream in = null;
JarOutputStream out = null;
try {
in = new JarInputStream(new FileInputStream(
inFileName));
out = new JarOutputStream(new FileOutputStream(
outFileName, append));
JarEntry entry;
while (true) {
entry = in.getNextJarEntry();
if (entry == null)
break;
if (entry.getSize() != -1) {
byte[] buff = new byte[(int)entry.getSize()];
in.read(buff);
out.putNextEntry(entry);
out.write(buff);
out.flush();
}
}
} finally {
if (in != null)
in.close();
if (out != null)
out.close();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
| apache-2.0 |
jxttian/Yuna | console/src/main/java/net/myscloud/open/yuna/bean/search/PermissionSearch.java | 314 | package net.myscloud.open.yuna.bean.search;
import lombok.Data;
import net.myscloud.open.yuna.common.framework.PaginationParam;
/**
* Created by genesis on 2016/12/29.
*/
@Data
public class PermissionSearch extends PaginationParam {
private Integer sid;
private String code;
private String name;
}
| apache-2.0 |
MOON-TYPE/MTodo | MTodo Project/Assets/Moon Antonio/MTodo/Extensiones/MTodoExtensiones.cs | 5922 | // ┌∩┐(◣_◢)┌∩┐
// \\
// MTodoExtensiones.cs (08/02/2017) \\
// Autor: Antonio Mateo (Moon Antonio) \\
// Descripcion: Extensiones para el editor de MTodo \\
// Fecha Mod: 21/03/2017 \\
// Ultima Mod: Cambio en el namespace \\
//******************************************************************************\\
#region Librerias
using UnityEngine;
#if UNITY_EDITOR
using UnityEditor;
#endif
using System;
using System.IO;
#endregion
namespace MoonAntonio.MTodo.Extensiones
{
/// <summary>
/// <para>Extensiones para el editor de MTodo</para>
/// </summary>
public static class MTodoExtensiones
{
#if UNITY_EDITOR
#region Scriptable
/// <summary>
/// <para>Crea la Data de MTodo</para>
/// </summary>
/// <typeparam name="T">T</typeparam>
/// <param name="ruta">Ruta de la Data</param>
/// <returns>La data creada</returns>
public static T CrearData<T>(string ruta) where T : ScriptableObject
{
var temp = ScriptableObject.CreateInstance<T>();
AssetDatabase.CreateAsset(temp, ruta);
AssetDatabase.SaveAssets();
AssetDatabase.Refresh();
return temp;
}
/// <summary>
/// <para>Carga la data de MTodo</para>
/// </summary>
/// <typeparam name="T">T</typeparam>
/// <param name="ruta">Ruta de MTodo data</param>
/// <returns>La Data de MTodo</returns>
public static T CargarData<T>(string ruta) where T : ScriptableObject
{
return AssetDatabase.LoadAssetAtPath<T>(ruta);
}
/// <summary>
/// <para>Borra la Data de MTodo</para>
/// </summary>
/// <param name="ruta">Ruta de la data</param>
/// <returns>True si se ha borrado, false si no se ha borrado</returns>
public static bool BorrarData(string ruta)
{
var archivo = new FileInfo(ruta);
if (archivo.Exists)
{
archivo.Delete();
return true;
}
else
{
return false;
}
}
/// <summary>
/// <para>Carga o en su defecto crea una Data de MTodo</para>
/// </summary>
/// <typeparam name="T">T</typeparam>
/// <param name="ruta">Ruta de MTodo</param>
/// <returns>La carga</returns>
public static T CrearDataPersistente<T>(string ruta) where T : ScriptableObject
{
var temp = CargarData<T>(ruta);
return temp ?? CrearData<T>(ruta);
}
#endregion
#region Path
/// <summary>
/// <para>Convertir ruta global a relativa</para>
/// </summary>
/// <param name="path">Ruta</param>
/// <returns></returns>
public static string GlobalPathARelativa(string path)
{
if (path.StartsWith(Application.dataPath))
return "Assets" + path.Substring(Application.dataPath.Length);
else
throw new ArgumentException("Ruta incorrecta. La ruta no contiene Application.datapath");
}
/// <summary>
/// <para>Convertir ruta relativa a global</para>
/// </summary>
/// <param name="path">Ruta</param>
/// <returns></returns>
public static string RelativaPathAGlobal(string path)
{
return Path.Combine(Application.dataPath, path);
}
/// <summary>
/// <para>Convertir ruta de unix a Windows</para>
/// </summary>
/// <param name="path">Ruta</param>
/// <returns></returns>
public static string UnixAWindowsPath(string path)
{
return path.Replace("/", "\\");
}
/// <summary>
/// <para>Convertir ruta de windows a unix</para>
/// </summary>
/// <param name="path">Ruta</param>
/// <returns></returns>
public static string WindowsAUnixPath(string path)
{
return path.Replace("\\", "/");
}
#endregion
#region Layout
public class VerticalBlock : IDisposable
{
public VerticalBlock(params GUILayoutOption[] opciones)
{
GUILayout.BeginVertical(opciones);
}
public VerticalBlock(GUIStyle style, params GUILayoutOption[] opciones)
{
GUILayout.BeginVertical(style, opciones);
}
public void Dispose()
{
GUILayout.EndVertical();
}
}
public class ScrollviewBlock : IDisposable
{
public ScrollviewBlock(ref Vector2 scrollPos, params GUILayoutOption[] opciones)
{
scrollPos = GUILayout.BeginScrollView(scrollPos, opciones);
}
public void Dispose()
{
GUILayout.EndScrollView();
}
}
public class HorizontalBlock : IDisposable
{
public HorizontalBlock(params GUILayoutOption[] opciones)
{
GUILayout.BeginHorizontal(opciones);
}
public HorizontalBlock(GUIStyle style, params GUILayoutOption[] opciones)
{
GUILayout.BeginHorizontal(style, opciones);
}
public void Dispose()
{
GUILayout.EndHorizontal();
}
}
public class ColoredBlock : System.IDisposable
{
public ColoredBlock(Color color)
{
GUI.color = color;
}
public void Dispose()
{
GUI.color = Color.white;
}
}
#endregion
#endif
}
} | apache-2.0 |
xiaomak/XRepair | BackEnd/app/service/model/RepairOrderModel.php | 5870 | <?php
/**
* Created by PhpStorm.
* User: Mak
* Email:xiaomak@qq.com
* Date: 2017/8/15
* Time: 23:00
*/
namespace app\service\model;
use think\Db;
use think\Model;
class RepairOrderModel extends Model {
protected $autoWriteTimestamp = true;
/**
* 添加通用报修单
*
* @param $data array 报修信息
*
* @return bool|mixed
*/
public function addGeneralOrder($data) {
self::startTrans();
try {
$this->allowField(true)->save($data);
$data['oid'] = $this->id;
$generalOrderModel = new GeneralOrderModel();
$generalOrderModel->allowField(true)->save($data);
self::commit();
return $data['oid'];
} catch (\Exception $e) {
self::rollback();
return false;
}
}
/**
* 查询报修
*
* @param $user_id int 用户id
* @param $page int 页码
*
* @return array
*/
public function getRepairList($user_id, $page) {
$repairLists = $this->field('id,type,create_time,update_time,order_time,complete_time,status,feedback')->where('user_id', '=', $user_id)->page($page, 10)->order(['create_time' => 'desc',
'id' => 'desc'])->select()->toArray();
foreach ($repairLists as $key => $val) {
switch ($val['type']) {
case 'general':
$repairLists[$key]['data'] = Db::view('GeneralOrder', 'name,mobile,region,desc')->view('RepairRegion', ['GROUP_CONCAT(distinct RepairRegion.name)' => 'address'], 'FIND_IN_SET(RepairRegion.id,GeneralOrder.region)', 'LEFT')->view('GeneralCategory', ['GROUP_CONCAT(distinct GeneralCategory.name)' => 'cate'], 'FIND_IN_SET(GeneralCategory.id,GeneralOrder.category)', 'LEFT')->where('oid', '=', $val['id'])->group('GeneralOrder.id')->find();
break;
case 'net':
$repairLists[$key]['data'] = Db::view('NetOrder', 'name,account,mobile,desc')->view('RepairRegion', ['GROUP_CONCAT(distinct RepairRegion.name)' => 'address'], 'FIND_IN_SET(RepairRegion.id,NetOrder.region)', 'LEFT')->view('NetOperator', ['name' => 'operator'], 'NetOperator.id=NetOrder.operator_id', 'LEFT')->where('oid', '=', $val['id'])->group('NetOrder.id')->find();
break;
}
}
return $repairLists;
}
public function getMyOrderList($repairer_id, $page) {
$repairLists = $this->field('id,type,create_time,update_time,order_time,complete_time,status,feedback')->where('repairer_id', '=', $repairer_id)->page($page, 10)->order(['create_time' => 'desc',
'id' => 'desc'])->select()->toArray();
foreach ($repairLists as $key => $val) {
switch ($val['type']) {
case 'general':
$repairLists[$key]['data'] = Db::view('GeneralOrder', 'name,mobile,region,desc')->view('RepairRegion', ['GROUP_CONCAT(distinct RepairRegion.name)' => 'address'], 'FIND_IN_SET(RepairRegion.id,GeneralOrder.region)', 'LEFT')->view('GeneralCategory', ['GROUP_CONCAT(distinct GeneralCategory.name)' => 'cate'], 'FIND_IN_SET(GeneralCategory.id,GeneralOrder.category)', 'LEFT')->where('oid', '=', $val['id'])->group('GeneralOrder.id')->find();
break;
case 'net':
$repairLists[$key]['data'] = Db::view('NetOrder', 'name,account,mobile,desc')->view('RepairRegion', ['GROUP_CONCAT(distinct RepairRegion.name)' => 'address'], 'FIND_IN_SET(RepairRegion.id,NetOrder.region)', 'LEFT')->view('NetOperator', ['name' => 'operator'], 'NetOperator.id=NetOrder.operator_id', 'LEFT')->where('oid', '=', $val['id'])->group('NetOrder.id')->find();
break;
}
}
return $repairLists;
}
/**
* 统计报修次数
*
* @param $user_id int 用户id
*
* @return int|string
*/
public function getRepairCount($user_id) {
return $this->where('user_id', '=', $user_id)->count();
}
/**
* 获取报修详情
* @param $oid int 报修id
* @param $user_id int 用户id
*
* @return array|false|\PDOStatement|string|Model
*/
public function getRepairDetails($oid, $user_id) {
// $result = $this->field('id,type,create_time,update_time,order_time,complete_time,status,feedback')->where(['id' => $oid,
// 'user_id' => $user_id])->find();
$result = Db::view('RepairOrder','id,type,create_time,update_time,order_time,complete_time,status,feedback')
->view('User',['user_nickname'=>'repairer_name','mobile'=>'repairer_mobile'],'RepairOrder.repairer_id=User.id','LEFT')
->where(['id' => $oid, 'user_id' => $user_id])
->find();
switch ($result['type']) {
case 'general':
$general = Db::view('GeneralOrder', 'name,mobile,region,desc')->view('RepairRegion', ['GROUP_CONCAT(distinct RepairRegion.name)' => 'address'], 'FIND_IN_SET(RepairRegion.id,GeneralOrder.region)', 'LEFT')->view('GeneralCategory', ['GROUP_CONCAT(distinct GeneralCategory.name)' => 'cate'], 'FIND_IN_SET(GeneralCategory.id,GeneralOrder.category)', 'LEFT')->where('oid', '=', $result['id'])->group('GeneralOrder.id')->find();
$result=array_merge($result,$general);
break;
case 'net':
$net = Db::view('NetOrder', 'name,account,mobile,desc')->view('RepairRegion', ['GROUP_CONCAT(distinct RepairRegion.name)' => 'address'], 'FIND_IN_SET(RepairRegion.id,NetOrder.region)', 'LEFT')->view('NetOperator', ['name' => 'operator'], 'NetOperator.id=NetOrder.operator_id', 'LEFT')->where('oid', '=', $result['id'])->group('NetOrder.id')->find();
$result=array_merge($result,$net);
break;
}
return $result;
}
} | apache-2.0 |
trasa/aws-sdk-java | aws-java-sdk-waf/src/main/java/com/amazonaws/services/waf/model/WafAction.java | 11379 | /*
* Copyright 2010-2016 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.services.waf.model;
import java.io.Serializable;
/**
* <p>
* For the action that is associated with a rule in a <code>WebACL</code>,
* specifies the action that you want AWS WAF to perform when a web request
* matches all of the conditions in a rule. For the default action in a
* <code>WebACL</code>, specifies the action that you want AWS WAF to take when
* a web request doesn't match all of the conditions in any of the rules in a
* <code>WebACL</code>.
* </p>
*/
public class WafAction implements Serializable, Cloneable {
/**
* <p>
* Specifies how you want AWS WAF to respond to requests that match the
* settings in a <code>Rule</code>. Valid settings include the following:
* </p>
* <ul>
* <li><code>ALLOW</code>: AWS WAF allows requests</li>
* <li><code>BLOCK</code>: AWS WAF blocks requests</li>
* <li><code>COUNT</code>: AWS WAF increments a counter of the requests that
* match all of the conditions in the rule. AWS WAF then continues to
* inspect the web request based on the remaining rules in the web ACL. You
* can't specify <code>COUNT</code> for the default action for a
* <code>WebACL</code>.</li>
* </ul>
*/
private String type;
/**
* <p>
* Specifies how you want AWS WAF to respond to requests that match the
* settings in a <code>Rule</code>. Valid settings include the following:
* </p>
* <ul>
* <li><code>ALLOW</code>: AWS WAF allows requests</li>
* <li><code>BLOCK</code>: AWS WAF blocks requests</li>
* <li><code>COUNT</code>: AWS WAF increments a counter of the requests that
* match all of the conditions in the rule. AWS WAF then continues to
* inspect the web request based on the remaining rules in the web ACL. You
* can't specify <code>COUNT</code> for the default action for a
* <code>WebACL</code>.</li>
* </ul>
*
* @param type
* Specifies how you want AWS WAF to respond to requests that match
* the settings in a <code>Rule</code>. Valid settings include the
* following:</p>
* <ul>
* <li><code>ALLOW</code>: AWS WAF allows requests</li>
* <li><code>BLOCK</code>: AWS WAF blocks requests</li>
* <li><code>COUNT</code>: AWS WAF increments a counter of the
* requests that match all of the conditions in the rule. AWS WAF
* then continues to inspect the web request based on the remaining
* rules in the web ACL. You can't specify <code>COUNT</code> for the
* default action for a <code>WebACL</code>.</li>
* @see WafActionType
*/
public void setType(String type) {
this.type = type;
}
/**
* <p>
* Specifies how you want AWS WAF to respond to requests that match the
* settings in a <code>Rule</code>. Valid settings include the following:
* </p>
* <ul>
* <li><code>ALLOW</code>: AWS WAF allows requests</li>
* <li><code>BLOCK</code>: AWS WAF blocks requests</li>
* <li><code>COUNT</code>: AWS WAF increments a counter of the requests that
* match all of the conditions in the rule. AWS WAF then continues to
* inspect the web request based on the remaining rules in the web ACL. You
* can't specify <code>COUNT</code> for the default action for a
* <code>WebACL</code>.</li>
* </ul>
*
* @return Specifies how you want AWS WAF to respond to requests that match
* the settings in a <code>Rule</code>. Valid settings include the
* following:</p>
* <ul>
* <li><code>ALLOW</code>: AWS WAF allows requests</li>
* <li><code>BLOCK</code>: AWS WAF blocks requests</li>
* <li><code>COUNT</code>: AWS WAF increments a counter of the
* requests that match all of the conditions in the rule. AWS WAF
* then continues to inspect the web request based on the remaining
* rules in the web ACL. You can't specify <code>COUNT</code> for
* the default action for a <code>WebACL</code>.</li>
* @see WafActionType
*/
public String getType() {
return this.type;
}
/**
* <p>
* Specifies how you want AWS WAF to respond to requests that match the
* settings in a <code>Rule</code>. Valid settings include the following:
* </p>
* <ul>
* <li><code>ALLOW</code>: AWS WAF allows requests</li>
* <li><code>BLOCK</code>: AWS WAF blocks requests</li>
* <li><code>COUNT</code>: AWS WAF increments a counter of the requests that
* match all of the conditions in the rule. AWS WAF then continues to
* inspect the web request based on the remaining rules in the web ACL. You
* can't specify <code>COUNT</code> for the default action for a
* <code>WebACL</code>.</li>
* </ul>
*
* @param type
* Specifies how you want AWS WAF to respond to requests that match
* the settings in a <code>Rule</code>. Valid settings include the
* following:</p>
* <ul>
* <li><code>ALLOW</code>: AWS WAF allows requests</li>
* <li><code>BLOCK</code>: AWS WAF blocks requests</li>
* <li><code>COUNT</code>: AWS WAF increments a counter of the
* requests that match all of the conditions in the rule. AWS WAF
* then continues to inspect the web request based on the remaining
* rules in the web ACL. You can't specify <code>COUNT</code> for the
* default action for a <code>WebACL</code>.</li>
* @return Returns a reference to this object so that method calls can be
* chained together.
* @see WafActionType
*/
public WafAction withType(String type) {
setType(type);
return this;
}
/**
* <p>
* Specifies how you want AWS WAF to respond to requests that match the
* settings in a <code>Rule</code>. Valid settings include the following:
* </p>
* <ul>
* <li><code>ALLOW</code>: AWS WAF allows requests</li>
* <li><code>BLOCK</code>: AWS WAF blocks requests</li>
* <li><code>COUNT</code>: AWS WAF increments a counter of the requests that
* match all of the conditions in the rule. AWS WAF then continues to
* inspect the web request based on the remaining rules in the web ACL. You
* can't specify <code>COUNT</code> for the default action for a
* <code>WebACL</code>.</li>
* </ul>
*
* @param type
* Specifies how you want AWS WAF to respond to requests that match
* the settings in a <code>Rule</code>. Valid settings include the
* following:</p>
* <ul>
* <li><code>ALLOW</code>: AWS WAF allows requests</li>
* <li><code>BLOCK</code>: AWS WAF blocks requests</li>
* <li><code>COUNT</code>: AWS WAF increments a counter of the
* requests that match all of the conditions in the rule. AWS WAF
* then continues to inspect the web request based on the remaining
* rules in the web ACL. You can't specify <code>COUNT</code> for the
* default action for a <code>WebACL</code>.</li>
* @return Returns a reference to this object so that method calls can be
* chained together.
* @see WafActionType
*/
public void setType(WafActionType type) {
this.type = type.toString();
}
/**
* <p>
* Specifies how you want AWS WAF to respond to requests that match the
* settings in a <code>Rule</code>. Valid settings include the following:
* </p>
* <ul>
* <li><code>ALLOW</code>: AWS WAF allows requests</li>
* <li><code>BLOCK</code>: AWS WAF blocks requests</li>
* <li><code>COUNT</code>: AWS WAF increments a counter of the requests that
* match all of the conditions in the rule. AWS WAF then continues to
* inspect the web request based on the remaining rules in the web ACL. You
* can't specify <code>COUNT</code> for the default action for a
* <code>WebACL</code>.</li>
* </ul>
*
* @param type
* Specifies how you want AWS WAF to respond to requests that match
* the settings in a <code>Rule</code>. Valid settings include the
* following:</p>
* <ul>
* <li><code>ALLOW</code>: AWS WAF allows requests</li>
* <li><code>BLOCK</code>: AWS WAF blocks requests</li>
* <li><code>COUNT</code>: AWS WAF increments a counter of the
* requests that match all of the conditions in the rule. AWS WAF
* then continues to inspect the web request based on the remaining
* rules in the web ACL. You can't specify <code>COUNT</code> for the
* default action for a <code>WebACL</code>.</li>
* @return Returns a reference to this object so that method calls can be
* chained together.
* @see WafActionType
*/
public WafAction withType(WafActionType type) {
setType(type);
return this;
}
/**
* Returns a string representation of this object; useful for testing and
* debugging.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getType() != null)
sb.append("Type: " + getType());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof WafAction == false)
return false;
WafAction other = (WafAction) obj;
if (other.getType() == null ^ this.getType() == null)
return false;
if (other.getType() != null
&& other.getType().equals(this.getType()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode
+ ((getType() == null) ? 0 : getType().hashCode());
return hashCode;
}
@Override
public WafAction clone() {
try {
return (WafAction) super.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException(
"Got a CloneNotSupportedException from Object.clone() "
+ "even though we're Cloneable!", e);
}
}
} | apache-2.0 |
SergeyZhernovoy/Java-education | PartXI/lesson3/src/main/java/ru/szhernovoy/jpa/carstore/service/impl/OrderServiceImpl.java | 1154 | package ru.szhernovoy.jpa.carstore.service.impl;/**
* Created by Admin on 05.02.2017.
*/
import com.google.common.collect.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import ru.szhernovoy.jpa.carstore.repositories.OrderCrud;
import ru.szhernovoy.jpa.carstore.domain.Order;
import ru.szhernovoy.jpa.carstore.service.OrderService;
import java.util.List;
@Component
public class OrderServiceImpl implements OrderService {
private OrderCrud orderCrud;
@Autowired
public OrderServiceImpl(OrderCrud orderCrud) {
this.orderCrud = orderCrud;
}
@Override
public Order create(Order order) {
return this.orderCrud.save(order);
}
@Override
public Order update(Order order) {
return this.orderCrud.save(order);
}
@Override
public void delete(Order order) {
this.orderCrud.delete(order);
}
@Override
public Order get(int id) {
return this.orderCrud.findOne(id);
}
@Override
public List<Order> get() {
return Lists.newArrayList(this.orderCrud.findAll());
}
}
| apache-2.0 |
sghill/gocd | server/webapp/WEB-INF/rails.new/spec/controllers/admin/materials/hg_controller_spec.rb | 1907 | ##########################GO-LICENSE-START################################
# Copyright 2014 ThoughtWorks, 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.
##########################GO-LICENSE-END##################################
require 'spec_helper'
load File.join(File.dirname(__FILE__), 'material_controller_examples.rb')
describe Admin::Materials::HgController do
before do
@material = MaterialConfigsMother.hgMaterialConfig("hg://foo.com")
@short_material_type = 'hg'
end
it_should_behave_like :material_controller
def new_material
HgMaterialConfig.new("", nil)
end
def assert_successful_create
hg_material_config = HgMaterialConfig.new("new-url", nil)
hg_material_config.setName(CaseInsensitiveString.new('new-some-kinda-material'))
hg_material_config.setConfigAttributes({HgMaterialConfig::FOLDER => "folder"})
expect(@pipeline.materialConfigs().get(1)).to eq(hg_material_config)
end
def update_payload
{:materialName => "new-some-kinda-material", :url => "new-url", :folder => "folder"}
end
def assert_successful_update
expect(@pipeline.materialConfigs().get(0).getUrl()).to eq("new-url")
expect(@pipeline.materialConfigs().get(0).getName()).to eq(CaseInsensitiveString.new("new-some-kinda-material"))
end
def setup_other_form_objects
#nothing to load
end
def setup_for_new_material
#nothing to load
end
end
| apache-2.0 |
google/site-kit-wp | assets/js/modules/adsense/index.js | 5042 | /**
* AdSense module initialization.
*
* Site Kit by Google, Copyright 2021 Google LLC
*
* 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
*
* https://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.
*/
/**
* WordPress dependencies
*/
import { __ } from '@wordpress/i18n';
/**
* Internal dependencies
*/
import {
AREA_DASHBOARD_EARNINGS,
AREA_MAIN_DASHBOARD_MONETIZATION_PRIMARY,
} from '../../googlesitekit/widgets/default-areas';
import { SetupMain } from './components/setup';
import {
SettingsEdit,
SettingsSetupIncomplete,
SettingsView,
} from './components/settings';
import {
DashboardSummaryWidget,
DashboardTopEarningPagesWidget,
AdBlockerWarningWidget,
AdSenseConnectCTAWidget,
} from './components/dashboard';
import ModuleTopEarningPagesWidget from './components/module/ModuleTopEarningPagesWidget';
import { ModuleOverviewWidget } from './components/module';
import AdSenseIcon from '../../../svg/graphics/adsense.svg';
import { MODULES_ADSENSE } from './datastore/constants';
import {
AREA_MODULE_ADSENSE_MAIN,
CONTEXT_MODULE_ADSENSE,
ERROR_CODE_ADBLOCKER_ACTIVE,
} from './constants';
import { WIDGET_AREA_STYLES } from '../../googlesitekit/widgets/datastore/constants';
import { isFeatureEnabled } from '../../features';
export { registerStore } from './datastore';
export const registerModule = ( modules ) => {
modules.registerModule( 'adsense', {
storeName: MODULES_ADSENSE,
SettingsEditComponent: SettingsEdit,
SettingsViewComponent: SettingsView,
SettingsSetupIncompleteComponent: SettingsSetupIncomplete,
SetupComponent: SetupMain,
Icon: AdSenseIcon,
features: [
__( 'Intelligent, automatic ad placement', 'google-site-kit' ),
__( 'Revenue from ads placed on your site', 'google-site-kit' ),
__( 'AdSense insights through Site Kit', 'google-site-kit' ),
],
checkRequirements: async ( registry ) => {
const adBlockerActive = await registry
.__experimentalResolveSelect( MODULES_ADSENSE )
.isAdBlockerActive();
if ( ! adBlockerActive ) {
return;
}
const message = registry
.select( MODULES_ADSENSE )
.getAdBlockerWarningMessage();
throw {
code: ERROR_CODE_ADBLOCKER_ACTIVE,
message,
data: null,
};
},
screenWidgetContext: CONTEXT_MODULE_ADSENSE,
} );
};
export const registerWidgets = ( widgets ) => {
widgets.registerWidget(
'adBlockerWarning',
{
Component: AdBlockerWarningWidget,
width: widgets.WIDGET_WIDTHS.FULL,
priority: 1,
wrapWidget: false,
},
[ AREA_MAIN_DASHBOARD_MONETIZATION_PRIMARY, AREA_MODULE_ADSENSE_MAIN ]
);
if ( isFeatureEnabled( 'unifiedDashboard' ) ) {
widgets.registerWidget(
'adsenseModuleOverview',
{
Component: ModuleOverviewWidget,
width: widgets.WIDGET_WIDTHS.FULL,
priority: 2,
wrapWidget: false,
},
[ AREA_MAIN_DASHBOARD_MONETIZATION_PRIMARY ]
);
widgets.registerWidget(
'adsenseConnectCTA',
{
Component: AdSenseConnectCTAWidget,
width: [ widgets.WIDGET_WIDTHS.FULL ],
priority: 2,
wrapWidget: false,
},
[ AREA_MAIN_DASHBOARD_MONETIZATION_PRIMARY ]
);
widgets.registerWidget(
'adsenseTopEarningPages',
{
Component: DashboardTopEarningPagesWidget,
width: [
widgets.WIDGET_WIDTHS.HALF,
widgets.WIDGET_WIDTHS.FULL,
],
priority: 3,
wrapWidget: false,
},
[ AREA_MAIN_DASHBOARD_MONETIZATION_PRIMARY ]
);
}
if ( ! isFeatureEnabled( 'unifiedDashboard' ) ) {
widgets.registerWidgetArea(
AREA_MODULE_ADSENSE_MAIN,
{
priority: 1,
style: WIDGET_AREA_STYLES.BOXES,
title: __( 'Overview', 'google-site-kit' ),
},
CONTEXT_MODULE_ADSENSE
);
widgets.registerWidget(
'adsenseSummary',
{
Component: DashboardSummaryWidget,
width: widgets.WIDGET_WIDTHS.HALF,
priority: 1,
wrapWidget: false,
},
[ AREA_DASHBOARD_EARNINGS ]
);
widgets.registerWidget(
'adsenseTopEarningPages',
{
Component: DashboardTopEarningPagesWidget,
width: [
widgets.WIDGET_WIDTHS.HALF,
widgets.WIDGET_WIDTHS.FULL,
],
priority: 2,
wrapWidget: false,
},
[ AREA_DASHBOARD_EARNINGS ]
);
widgets.registerWidget(
'adsenseModuleOverview',
{
Component: ModuleOverviewWidget,
width: widgets.WIDGET_WIDTHS.FULL,
priority: 2,
wrapWidget: false,
},
[ AREA_MODULE_ADSENSE_MAIN ]
);
widgets.registerWidget(
'adsenseModuleTopEarningPages',
{
Component: ModuleTopEarningPagesWidget,
width: widgets.WIDGET_WIDTHS.FULL,
priority: 2,
wrapWidget: false,
},
[ AREA_MODULE_ADSENSE_MAIN ]
);
}
};
| apache-2.0 |
lvjk/excrawler | src/main/java/six/com/crawler/work/store/impl/HttpStore.java | 693 | package six.com.crawler.work.store.impl;
import java.util.List;
import java.util.Map;
import six.com.crawler.work.AbstractWorker;
import six.com.crawler.work.store.AbstarctStore;
import six.com.crawler.work.store.exception.StoreException;
/**
* @author 作者
* @E-mail: 359852326@qq.com
* @date 创建时间:2017年3月27日 上午11:37:37
*/
public class HttpStore extends AbstarctStore{
public HttpStore(AbstractWorker<?> worker) {
super(worker);
}
@Override
protected int insideStore(List<Map<String, String>> results) throws StoreException {
return 0;
}
@Override
public void close() {
// TODO Auto-generated method stub
}
}
| apache-2.0 |
sundrio/sundrio | model/utils/src/main/java/io/sundr/model/utils/Optionals.java | 4872 | /*
* Copyright 2016 The original authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.sundr.model.utils;
import java.util.Optional;
import java.util.OptionalDouble;
import java.util.OptionalInt;
import java.util.OptionalLong;
import java.util.function.Function;
import javax.lang.model.element.Modifier;
import io.sundr.FunctionFactory;
import io.sundr.model.TypeDef;
import io.sundr.model.TypeDefBuilder;
import io.sundr.model.TypeParamDef;
import io.sundr.model.TypeParamDefBuilder;
import io.sundr.model.TypeRef;
public class Optionals {
public static TypeParamDef E = new TypeParamDefBuilder().withName("E").build();
public static final TypeDef OPTIONAL = new TypeDefBuilder(TypeDef.forName(Optional.class.getName()))
.withParameters(E)
.addNewMethod()
.withModifiers(Types.modifiersToInt(Modifier.PUBLIC, Modifier.STATIC))
.withName("of")
.addNewArgument()
.withName("value")
.withTypeRef(E.toReference())
.endArgument()
.endMethod()
.build();
public static final TypeDef OPTIONAL_INT = new TypeDefBuilder(TypeDef.forName(OptionalInt.class.getName()))
.addNewMethod()
.withModifiers(Types.modifiersToInt(Modifier.PUBLIC, Modifier.STATIC))
.withName("of")
.addNewArgument()
.withName("value")
.withTypeRef(Types.PRIMITIVE_INT_REF)
.endArgument()
.endMethod()
.build();
public static final TypeDef OPTIONAL_DOUBLE = new TypeDefBuilder(TypeDef.forName(OptionalDouble.class.getName()))
.addNewMethod()
.withModifiers(Types.modifiersToInt(Modifier.PUBLIC, Modifier.STATIC))
.withName("of")
.addNewArgument()
.withName("value")
.withTypeRef(Types.PRIMITIVE_DOUBLE_REF)
.endArgument()
.endMethod()
.build();
public static final TypeDef OPTIONAL_LONG = new TypeDefBuilder(TypeDef.forName(OptionalLong.class.getName()))
.addNewMethod()
.withModifiers(Types.modifiersToInt(Modifier.PUBLIC, Modifier.STATIC))
.withName("of")
.addNewArgument()
.withName("value")
.withTypeRef(Types.PRIMITIVE_LONG_REF)
.endArgument()
.endMethod()
.build();
public static final Function<TypeRef, Boolean> IS_OPTIONAL = FunctionFactory.cache(new Function<TypeRef, Boolean>() {
public Boolean apply(TypeRef type) {
return Types.isInstanceOf(type, OPTIONAL, IS_OPTIONAL);
}
});
public static final Function<TypeRef, Boolean> IS_OPTIONAL_INT = FunctionFactory.cache(new Function<TypeRef, Boolean>() {
public Boolean apply(TypeRef type) {
return Types.isInstanceOf(type, OPTIONAL_INT, IS_OPTIONAL_INT);
}
});
public static final Function<TypeRef, Boolean> IS_OPTIONAL_DOUBLE = FunctionFactory.cache(new Function<TypeRef, Boolean>() {
public Boolean apply(TypeRef type) {
return Types.isInstanceOf(type, OPTIONAL_DOUBLE, IS_OPTIONAL_DOUBLE);
}
});
public static final Function<TypeRef, Boolean> IS_OPTIONAL_LONG = FunctionFactory.cache(new Function<TypeRef, Boolean>() {
public Boolean apply(TypeRef type) {
return Types.isInstanceOf(type, OPTIONAL_LONG, IS_OPTIONAL_LONG);
}
});
/**
* Checks if a {@link TypeRef} is a {@link java.util.Optional}.
*
* @param type The type to check.
* @return True if its a {@link java.util.Optional}.
*/
public static boolean isOptional(TypeRef type) {
return IS_OPTIONAL.apply(type);
}
/**
* Checks if a {@link TypeRef} is a {@link java.util.OptionalInt}.
*
* @param type The type to check.
* @return True if its a {@link java.util.OptionalInt}.
*/
public static boolean isOptionalInt(TypeRef type) {
return IS_OPTIONAL_INT.apply(type);
}
/**
* Checks if a {@link TypeRef} is a {@link java.util.OptionalDouble}.
*
* @param type The type to check.
* @return True if its a {@link java.util.OptionalDouble}.
*/
public static boolean isOptionalDouble(TypeRef type) {
return IS_OPTIONAL_DOUBLE.apply(type);
}
/**
* Checks if a {@link TypeRef} is a {@link java.util.OptionalLong}.
*
* @param type The type to check.
* @return True if its a {@link java.util.OptionalLong}.
*/
public static boolean isOptionalLong(TypeRef type) {
return IS_OPTIONAL_LONG.apply(type);
}
}
| apache-2.0 |
vam-google/google-cloud-java | google-cloud-clients/google-cloud-iot/synth.py | 1599 | # Copyright 2018 Google LLC
#
# 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 script is used to synthesize generated parts of this library."""
import synthtool as s
import synthtool.gcp as gcp
import synthtool.languages.java as java
gapic = gcp.GAPICGenerator()
service = 'iot'
versions = ['v1']
config_pattern = '/google/cloud/iot/artman_cloudiot.yaml'
for version in versions:
library = gapic.java_library(
service=service,
version=version,
config_path=config_pattern.format(version=version),
artman_output_name='')
s.copy(library / f'gapic-google-cloud-{service}-{version}/src', 'src')
s.copy(library / f'grpc-google-cloud-{service}-{version}/src', f'../../google-api-grpc/grpc-google-cloud-{service}-{version}/src')
s.copy(library / f'proto-google-cloud-{service}-{version}/src', f'../../google-api-grpc/proto-google-cloud-{service}-{version}/src')
java.format_code('./src')
java.format_code(f'../../google-api-grpc/grpc-google-cloud-{service}-{version}/src')
java.format_code(f'../../google-api-grpc/proto-google-cloud-{service}-{version}/src')
| apache-2.0 |
scheuchzer/outbound-connector | examples/urlbased/echo/echo-connector/src/main/java/com/ja/rsc/echo/InMemoryEchoConnection.java | 1748 | /*
Copyright 2013 Thomas Scheuchzer, java-adventures.com
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.ja.rsc.echo;
import java.io.Closeable;
import com.ja.rsc.UrlBasedConnection;
import com.ja.rsc.UrlConnectionConfiguration;
import com.ja.rsc.echo.api.EchoConnection;
import com.ja.rsc.echo.api.EchoResponse;
/**
* Example implementation that works fully in-memory without any remote
* invocation. Just for the sake of demonstration the {@link EchoResponse} gets
* populated with url, username and password configured with the connection.
* Real connection implementation would use this information to open a
* connection to a remote system.
*
* @author Thomas Scheuchzer, java-adventures.com
*
*/
public class InMemoryEchoConnection extends
UrlBasedConnection<UrlConnectionConfiguration> implements
EchoConnection {
public InMemoryEchoConnection(
UrlConnectionConfiguration connectionConfiguration,
Closeable closeable) {
super(connectionConfiguration, closeable);
}
@Override
public EchoResponse echo(String text) {
EchoResponse response = new EchoResponse();
response.setText(text);
response.setUrl(getUrl());
response.setUsername(getUsername());
response.setPassword(getPassword());
return response;
}
}
| apache-2.0 |
regestaexe/bygle-ldp | src/main/java/org/bygle/xml/XMLReader.java | 8210 | package org.bygle.xml;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import org.apache.commons.lang3.StringEscapeUtils;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.Namespace;
import org.dom4j.Node;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
/**
* @author Sandro De Leo sdeleo@regesta.com
*/
public class XMLReader {
private Element root = null;
private String defaultEncoding;
public XMLReader(FileInputStream fileInputStream) throws DocumentException {
SAXReader saxReader = new SAXReader();
Document document = saxReader.read(fileInputStream);
defaultEncoding = document.getXMLEncoding();
root = document.getRootElement();
}
public XMLReader(InputStreamReader inputStreamReader) throws DocumentException {
SAXReader saxReader = new SAXReader();
Document document = saxReader.read(inputStreamReader);
defaultEncoding = document.getXMLEncoding();
root = document.getRootElement();
}
public XMLReader(File file) throws DocumentException {
SAXReader saxReader = new SAXReader();
Document document = saxReader.read(file);
defaultEncoding = document.getXMLEncoding();
root = document.getRootElement();
}
public XMLReader(String strDocXml) throws DocumentException {
Document document = DocumentHelper.parseText(strDocXml);
defaultEncoding = document.getXMLEncoding();
root = document.getRootElement();
}
public XMLReader(byte[] bytes) throws DocumentException {
SAXReader saxReader = new SAXReader();
Document document = saxReader.read(new ByteArrayInputStream(bytes));
defaultEncoding = document.getXMLEncoding();
root = document.getRootElement();
}
public void analyzeNodes(HashMap<String, ArrayList<String>> xpaths){
analyzeNodes(root,xpaths);
}
@SuppressWarnings("unchecked")
public List<Namespace> getNamespaces(){
return (List<Namespace>)root.declaredNamespaces();
}
@SuppressWarnings("unchecked")
public void analyzeNodes(Element node,HashMap<String, ArrayList<String>> xpaths){
if(node!=null){
if(node.getText()!=null && !node.getText().trim().equals("")){
if(xpaths.get(node.getPath())==null){
ArrayList<String> arrayList = new ArrayList<String>();
arrayList.add(node.getText().trim());
xpaths.put(node.getPath(),arrayList);
}else{
ArrayList<String> arrayList = xpaths.get(node.getPath());
arrayList.add(node.getText().trim());
xpaths.put(node.getPath(),arrayList);
}
}
if(node.attributes()!=null){
List<?> list =node.attributes();
for (Iterator<Attribute> iterator = (Iterator<Attribute>)list.iterator(); iterator.hasNext();) {
Attribute attribute = iterator.next();
if(attribute.getText()!=null && !attribute.getText().trim().equals("")){
if(xpaths.get(attribute.getPath())==null){
ArrayList<String> arrayList = new ArrayList<String>();
arrayList.add(attribute.getText().trim());
xpaths.put(attribute.getPath(),arrayList);
}else{
ArrayList<String> arrayList = xpaths.get(attribute.getPath());
arrayList.add(attribute.getText().trim());
xpaths.put(attribute.getPath(),arrayList);
}
}
}
}
if(node.elements()!=null){
List<?> list =node.elements();
for (Iterator<Element> iterator = (Iterator<Element>)list.iterator(); iterator.hasNext();) {
Element element = iterator.next();
analyzeNodes(element,xpaths);
}
}
}
}
private String getValue(String xPath,String separator){
String value = "";
if (xPath.endsWith("/text()")) {
List<?> nodeList = root.selectNodes(xPath);
for (int i = 0; i < nodeList.size(); i++) {
try {
if(((Node)nodeList.get(i)).getText().indexOf("\\n")!=-1)
value += ((Node)nodeList.get(i)).getText() + "\n";
else
value += ((Node)nodeList.get(i)).getText();
} catch (NullPointerException exc) {
}
if(separator!=null && i<nodeList.size()-1)
value+=separator;
}
} else {
Node node = root.selectSingleNode(xPath);
if (node != null) {
value = node.getText();
} else {
value = "";
}
}
if (value.equals(null)) {
value = "";
}
//value = StringEscapeUtils.unescapeXml(value);
OutputFormat outputFormat = new OutputFormat();
outputFormat.setEncoding(defaultEncoding);
StringWriter stringWriter = new StringWriter();
XMLWriter xmlWriter = null;
outputFormat.setNewlines(true);
xmlWriter = new XMLWriter(stringWriter, outputFormat);
xmlWriter.setMaximumAllowedCharacter(255);
try {
xmlWriter.write(value);
xmlWriter.flush();
xmlWriter.close();
stringWriter.close();
} catch (IOException e) {
return "";
}
return StringEscapeUtils.unescapeXml(stringWriter.toString());
}
public String getNodeAsXML(String xPath){
try {
Node node = root.selectSingleNode(xPath);
OutputFormat outputFormat = new OutputFormat();
outputFormat.setEncoding(defaultEncoding);
StringWriter stringWriter = new StringWriter();
XMLWriter xmlWriter = null;
outputFormat.setNewlines(true);
xmlWriter = new XMLWriter(stringWriter, outputFormat);
xmlWriter.setMaximumAllowedCharacter(255);
try {
xmlWriter.write(node.asXML());
xmlWriter.flush();
xmlWriter.close();
stringWriter.close();
} catch (IOException e) {
return null;
}
return stringWriter.toString();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public String getNodeListAsXML(String xPath){
try {
List<?> nodeList = root.selectNodes(xPath);
OutputFormat outputFormat = new OutputFormat();
outputFormat.setEncoding(defaultEncoding);
StringWriter stringWriter = new StringWriter();
XMLWriter xmlWriter = null;
outputFormat.setNewlines(true);
xmlWriter = new XMLWriter(stringWriter, outputFormat);
xmlWriter.setMaximumAllowedCharacter(255);
try {
for (int i = 0; i < nodeList.size(); i++) {
xmlWriter.write(((Node)nodeList.get(i)).asXML());
if(i< nodeList.size()-1)
xmlWriter.write("\r\n");
}
xmlWriter.flush();
xmlWriter.close();
stringWriter.close();
} catch (IOException e) {
return null;
}
return stringWriter.toString();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public int getNodeCount(String xPath){
try {
return root.selectNodes(xPath).size();
} catch (Exception e) {
return 0;
}
}
private ArrayList<String> getValues(String xPath){
ArrayList<String> result = new ArrayList<String>();
List<?> nodeList = root.selectNodes(xPath);
for (int i = 0; i < nodeList.size(); i++) {
if(((Node)nodeList.get(i)).getNodeType()== Node.ATTRIBUTE_NODE){
result.add(((Attribute)nodeList.get(i)).getStringValue());
}else{
try {
if(((Node)nodeList.get(i)).getText().indexOf("\\n")!=-1)
result.add(((Node)nodeList.get(i)).getText());
else
result.add(((Node)nodeList.get(i)).getText());
} catch (NullPointerException exc) {
}
}
}
return result;
}
public List<?> getNodeList(String xPath){
return root.selectNodes(xPath);
}
public String getNodeValue(String xPath,String separator){
return getValue(xPath,separator);
}
public String getNodeValue(String xPath){
return getValue(xPath,null);
}
public String getTrimmedNodeValue(String xPath,String separator){
return getValue(xPath,separator).trim();
}
public String getTrimmedNodeValue(String xPath){
return getValue(xPath,null).trim();
}
public String getValueOf(String xPath){
return root.valueOf(xPath);
}
public ArrayList<String> getNodesValues(String xPath){
return getValues(xPath);
}
public String getDefaultEncoding() {
return defaultEncoding;
}
public void setDefaultEncoding(String defaultEncoding) {
this.defaultEncoding = defaultEncoding;
}
public String getRootNode(){
return root.getName();
}
}
| apache-2.0 |
istio/bots | policybot/pkg/config/duration.go | 1288 | // Copyright 2019 Istio Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package config
import (
"encoding/json"
"errors"
"time"
)
// Work around the fact time.Duration doesn't support JSON serialization for some reason
type Duration time.Duration
func (d Duration) MarshalJSON() ([]byte, error) {
return json.Marshal(time.Duration(d).String())
}
func (d *Duration) UnmarshalJSON(b []byte) error {
var v interface{}
if err := json.Unmarshal(b, &v); err != nil {
return err
}
switch value := v.(type) {
case float64:
*d = Duration(time.Duration(value))
return nil
case string:
tmp, err := time.ParseDuration(value)
if err != nil {
return err
}
*d = Duration(tmp)
return nil
default:
return errors.New("invalid duration value %s")
}
}
| apache-2.0 |
freedot/tstolua | tests/cases/conformance/expressions/typeGuards/typeGuardsInRightOperandOfAndAndOperator.ts | 2393 | // In the right operand of a && operation,
// the type of a variable or parameter is narrowed by any type guard in the left operand when true,
// provided the right operand contains no assignments to the variable or parameter.
function foo(x: number | string) {
return typeof x === "string" && x.length === 10; // string
}
function foo2(x: number | string) {
// modify x in right hand operand
return typeof x === "string" && ((x = 10) && x); // string | number
}
function foo3(x: number | string) {
// modify x in right hand operand with string type itself
return typeof x === "string" && ((x = "hello") && x); // string | number
}
function foo4(x: number | string | boolean) {
return typeof x !== "string" // string | number | boolean
&& typeof x !== "number" // number | boolean
&& x; // boolean
}
function foo5(x: number | string | boolean) {
// usage of x or assignment to separate variable shouldn't cause narrowing of type to stop
var b: number | boolean;
return typeof x !== "string" // string | number | boolean
&& ((b = x) && (typeof x !== "number" // number | boolean
&& x)); // boolean
}
function foo6(x: number | string | boolean) {
// Mixing typeguard narrowing in if statement with conditional expression typeguard
return typeof x !== "string" // string | number | boolean
&& (typeof x !== "number" // number | boolean
? x // boolean
: x === 10) // number
}
function foo7(x: number | string | boolean) {
var y: number| boolean | string;
var z: number| boolean | string;
// Mixing typeguard narrowing
// Assigning value to x deep inside another guard stops narrowing of type too
return typeof x !== "string"
&& ((z = x) // string | number | boolean - x changed deeper in conditional expression
&& (typeof x === "number"
// change value of x
? (x = 10 && x.toString()) // number | boolean | string
// do not change value
: (y = x && x.toString()))); // number | boolean | string
}
function foo8(x: number | string) {
// Mixing typeguard
// Assigning value to x in outer guard shouldn't stop narrowing in the inner expression
return typeof x !== "string"
&& (x = 10) // change x - number| string
&& (typeof x === "number"
? x // number
: x.length); // string
} | apache-2.0 |
Coderec/market | src/com/online/market/model/PwdMsg.java | 1194 | package com.online.market.model;
// Generated 2014-3-30 13:25:23 by Hibernate Tools 3.3.0.GA
import java.util.Date;
/**
* PwdMsg generated by hbm2java
*/
public class PwdMsg implements java.io.Serializable {
private static final long serialVersionUID = -2048330260846404770L;
private String pid;
private Admin admin;
private String uname;
private Date ptime;
private Boolean pisNew;
public PwdMsg() {
}
public String getPid() {
return pid;
}
public void setPid(String pid) {
this.pid = pid;
}
public Admin getAdmin() {
return admin;
}
public void setAdmin(Admin admin) {
this.admin = admin;
}
public PwdMsg(String pid, Admin admin, String uname, Date ptime,
Boolean pisNew) {
super();
this.pid = pid;
this.admin = admin;
this.uname = uname;
this.ptime = ptime;
this.pisNew = pisNew;
}
public String getUname() {
return uname;
}
public void setUname(String uname) {
this.uname = uname;
}
public Date getPtime() {
return ptime;
}
public void setPtime(Date ptime) {
this.ptime = ptime;
}
public Boolean getPisNew() {
return pisNew;
}
public void setPisNew(Boolean pisNew) {
this.pisNew = pisNew;
}
}
| apache-2.0 |
cictourgune/MDP-Crawler | src/org/tourgune/mdp/amazon/bean/Review.java | 2389 | package org.tourgune.mdp.amazon.bean;
import java.util.Date;
public class Review {
private int idAccommodation;
private Date scrapingDate;
private int idSegment;
private String typeTrip;
private String segment;
private String typeRoom;
private int stayNights;
private String withPet;
// private String subSegment;
private String from;
private Date date;
private String lang;
private String reviewGood;
private String reviewBad;
private float score;
public int getIdAccommodation() {
return idAccommodation;
}
public void setIdAccommodation(int idAccommodation) {
this.idAccommodation = idAccommodation;
}
public Date getScrapingDate() {
return scrapingDate;
}
public void setScrapingDate(Date scrapingDate) {
this.scrapingDate = scrapingDate;
}
public int getIdSegment() {
return idSegment;
}
public void setIdSegment(int idSegment) {
this.idSegment = idSegment;
}
public String getTypeTrip() {
return typeTrip;
}
public void setTypeTrip(String typeTrip) {
this.typeTrip = typeTrip;
}
public String getSegment() {
return segment;
}
public void setSegment(String segment) {
this.segment = segment;
}
public String getTypeRoom() {
return typeRoom;
}
public void setTypeRoom(String typeRoom) {
this.typeRoom = typeRoom;
}
public int getStayNights() {
return stayNights;
}
public void setStayNights(int stayNights) {
this.stayNights = stayNights;
}
public String getWithPet() {
return withPet;
}
public void setWithPet(String withPet) {
this.withPet = withPet;
}
// public String getSubSegment() {
// return subSegment;
// }
// public void setSubSegment(String subSegment) {
// this.subSegment = subSegment;
// }
public String getFrom() {
return from;
}
public void setFrom(String from) {
this.from = from;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public String getLang() {
return lang;
}
public void setLang(String lang) {
this.lang = lang;
}
public String getReviewGood() {
return reviewGood;
}
public void setReviewGood(String reviewGood) {
this.reviewGood = reviewGood;
}
public String getReviewBad() {
return reviewBad;
}
public void setReviewBad(String reviewBad) {
this.reviewBad = reviewBad;
}
public float getScore() {
return score;
}
public void setScore(float score) {
this.score = score;
}
}
| apache-2.0 |
AntonGavr92/agavrikov | chapter_007/src/main/java/ru/job4j/task/Hero.java | 990 | package ru.job4j.task;
/**
* Класс описывающий героя игры bomberman.
* @author agavrikov
* @since 27.07.2017
* @version 1
*/
public class Hero {
/**
* Текущая позиция героя в строке.
*/
final int row;
/**
* Текущая позиция героя в колонке.
*/
final int col;
/**
* Инициализация полей.
* @param row строка
* @param col колонка
*/
public Hero(int row, int col) {
this.row = row;
this.col = col;
}
/**
* Изменение позиции героя, по факту создание нового экземпляра с новыми координатами.
* @param row строка
* @param col колонка
* @return новый экземпляр класса.
*/
public Hero changeField(int row, int col) {
return new Hero(row, col);
}
}
| apache-2.0 |
ettoremaiorana/ReconcilerServer | src/main/java/com/fourcasters/forec/reconciler/server/EventHandler.java | 142 | package com.fourcasters.forec.reconciler.server;
/**
* Created by ivan on 08/09/17.
*/
public interface EventHandler {
int handle();
}
| apache-2.0 |
iRobotCorporation/djinni | test-suite/generated-src/jni/NativeInterfaceEncapsulator.cpp | 4916 | // AUTOGENERATED FILE - DO NOT MODIFY!
// This file generated by Djinni from interface_inheritance.djinni
#include "NativeInterfaceEncapsulator.hpp" // my header
#include "NativeBaseCppInterfaceInheritance.hpp"
#include "NativeBaseObjcJavaInterfaceInheritance.hpp"
#include "NativeSubObjcJavaInterfaceInheritance.hpp"
namespace djinni_generated {
NativeInterfaceEncapsulator::NativeInterfaceEncapsulator() : ::djinni::JniInterface<::testsuite::InterfaceEncapsulator, NativeInterfaceEncapsulator>("com/dropbox/djinni/test/InterfaceEncapsulator$CppProxy") {}
NativeInterfaceEncapsulator::~NativeInterfaceEncapsulator() = default;
CJNIEXPORT void JNICALL Java_com_dropbox_djinni_test_InterfaceEncapsulator_00024CppProxy_nativeDestroy(JNIEnv* jniEnv, jobject /*this*/, jlong nativeRef)
{
try {
DJINNI_FUNCTION_PROLOGUE1(jniEnv, nativeRef);
delete reinterpret_cast<::djinni::CppProxyHandle<::testsuite::InterfaceEncapsulator>*>(nativeRef);
} JNI_TRANSLATE_EXCEPTIONS_RETURN(jniEnv, )
}
CJNIEXPORT void JNICALL Java_com_dropbox_djinni_test_InterfaceEncapsulator_00024CppProxy_native_1setCppObject(JNIEnv* jniEnv, jobject /*this*/, jlong nativeRef, jobject j_object)
{
try {
DJINNI_FUNCTION_PROLOGUE1(jniEnv, nativeRef);
const auto& ref = ::djinni::objectFromHandleAddress<::testsuite::InterfaceEncapsulator>(nativeRef);
ref->set_cpp_object(::djinni_generated::NativeBaseCppInterfaceInheritance::toCpp(jniEnv, j_object));
} JNI_TRANSLATE_EXCEPTIONS_RETURN(jniEnv, )
}
CJNIEXPORT jobject JNICALL Java_com_dropbox_djinni_test_InterfaceEncapsulator_00024CppProxy_native_1getCppObject(JNIEnv* jniEnv, jobject /*this*/, jlong nativeRef)
{
try {
DJINNI_FUNCTION_PROLOGUE1(jniEnv, nativeRef);
const auto& ref = ::djinni::objectFromHandleAddress<::testsuite::InterfaceEncapsulator>(nativeRef);
auto r = ref->get_cpp_object();
return ::djinni::release(::djinni_generated::NativeBaseCppInterfaceInheritance::fromCpp(jniEnv, r));
} JNI_TRANSLATE_EXCEPTIONS_RETURN(jniEnv, 0 /* value doesn't matter */)
}
CJNIEXPORT jobject JNICALL Java_com_dropbox_djinni_test_InterfaceEncapsulator_00024CppProxy_native_1subCppAsBaseCpp(JNIEnv* jniEnv, jobject /*this*/, jlong nativeRef)
{
try {
DJINNI_FUNCTION_PROLOGUE1(jniEnv, nativeRef);
const auto& ref = ::djinni::objectFromHandleAddress<::testsuite::InterfaceEncapsulator>(nativeRef);
auto r = ref->sub_cpp_as_base_cpp();
return ::djinni::release(::djinni_generated::NativeBaseCppInterfaceInheritance::fromCpp(jniEnv, r));
} JNI_TRANSLATE_EXCEPTIONS_RETURN(jniEnv, 0 /* value doesn't matter */)
}
CJNIEXPORT void JNICALL Java_com_dropbox_djinni_test_InterfaceEncapsulator_00024CppProxy_native_1setObjcJavaObject(JNIEnv* jniEnv, jobject /*this*/, jlong nativeRef, jobject j_object)
{
try {
DJINNI_FUNCTION_PROLOGUE1(jniEnv, nativeRef);
const auto& ref = ::djinni::objectFromHandleAddress<::testsuite::InterfaceEncapsulator>(nativeRef);
ref->set_objc_java_object(::djinni_generated::NativeBaseObjcJavaInterfaceInheritance::toCpp(jniEnv, j_object));
} JNI_TRANSLATE_EXCEPTIONS_RETURN(jniEnv, )
}
CJNIEXPORT jobject JNICALL Java_com_dropbox_djinni_test_InterfaceEncapsulator_00024CppProxy_native_1getObjcJavaObject(JNIEnv* jniEnv, jobject /*this*/, jlong nativeRef)
{
try {
DJINNI_FUNCTION_PROLOGUE1(jniEnv, nativeRef);
const auto& ref = ::djinni::objectFromHandleAddress<::testsuite::InterfaceEncapsulator>(nativeRef);
auto r = ref->get_objc_java_object();
return ::djinni::release(::djinni_generated::NativeBaseObjcJavaInterfaceInheritance::fromCpp(jniEnv, r));
} JNI_TRANSLATE_EXCEPTIONS_RETURN(jniEnv, 0 /* value doesn't matter */)
}
CJNIEXPORT jobject JNICALL Java_com_dropbox_djinni_test_InterfaceEncapsulator_00024CppProxy_native_1castBaseArgToSub(JNIEnv* jniEnv, jobject /*this*/, jlong nativeRef, jobject j_subAsBase)
{
try {
DJINNI_FUNCTION_PROLOGUE1(jniEnv, nativeRef);
const auto& ref = ::djinni::objectFromHandleAddress<::testsuite::InterfaceEncapsulator>(nativeRef);
auto r = ref->cast_base_arg_to_sub(::djinni_generated::NativeBaseObjcJavaInterfaceInheritance::toCpp(jniEnv, j_subAsBase));
return ::djinni::release(::djinni_generated::NativeSubObjcJavaInterfaceInheritance::fromCpp(jniEnv, r));
} JNI_TRANSLATE_EXCEPTIONS_RETURN(jniEnv, 0 /* value doesn't matter */)
}
CJNIEXPORT jobject JNICALL Java_com_dropbox_djinni_test_InterfaceEncapsulator_create(JNIEnv* jniEnv, jobject /*this*/)
{
try {
DJINNI_FUNCTION_PROLOGUE0(jniEnv);
auto r = ::testsuite::InterfaceEncapsulator::create();
return ::djinni::release(::djinni_generated::NativeInterfaceEncapsulator::fromCpp(jniEnv, r));
} JNI_TRANSLATE_EXCEPTIONS_RETURN(jniEnv, 0 /* value doesn't matter */)
}
} // namespace djinni_generated
| apache-2.0 |
Aloomaio/googleads-python-lib | examples/ad_manager/v201811/proposal_service/submit_proposals_for_approval.py | 2333 | #!/usr/bin/env python
#
# Copyright 2015 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""This code example approves a single proposal.
To determine which proposals exist, run get_all_proposals.py.
"""
# Import appropriate modules from the client library.
from googleads import ad_manager
PROPOSAL_ID = 'INSERT_PROPOSAL_ID_HERE'
def main(client, proposal_id):
# Initialize appropriate service.
proposal_service = client.GetService('ProposalService', version='v201811')
# Create query.
statement = (ad_manager.StatementBuilder(version='v201811')
.Where('id = :proposalId')
.WithBindVariable('proposalId', proposal_id))
proposals_approved = 0
# Get proposals by statement.
while True:
response = proposal_service.getProposalsByStatement(statement.ToStatement())
if 'results' in response and len(response['results']):
# Display results.
for proposal in response['results']:
print ('Proposal with id "%s", name "%s", and status "%s" will be'
' approved.' % (proposal['id'], proposal['name'],
proposal['status']))
# Perform action.
result = proposal_service.performProposalAction(
{'xsi_type': 'SubmitProposalsForApproval'}, statement.ToStatement())
if result and int(result['numChanges']) > 0:
proposals_approved += int(result['numChanges'])
statement.offset += statement.limit
else:
break
# Display results.
if proposals_approved > 0:
print '\nNumber of proposals approved: %s' % proposals_approved
else:
print '\nNo proposals were approved.'
if __name__ == '__main__':
# Initialize client object.
ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
main(ad_manager_client, PROPOSAL_ID)
| apache-2.0 |
DavidS/pdk | spec/acceptance/support/contain_valid_junit_xml.rb | 570 | require 'rspec/xsd'
class RSpec::XSD::Matcher
attr_reader :errors
end
RSpec::Matchers.define :contain_valid_junit_xml do
match do |text|
xsd = File.join(RSpec.configuration.fixtures_path, 'JUnit.xsd')
@matcher = RSpec::XSD::Matcher.new(xsd, nil)
@matcher.matches?(text)
end
description do
'contain valid JUnit XML'
end
failure_message do
"expected that it would contain valid JUnit XML\r\n\r\n#{@matcher.errors.join("\r\n")}"
end
failure_message_when_negated do
'expected that it would not contain valid JUnit XML'
end
end
| apache-2.0 |
tangxin983/easy-mybatis | src/test/java/com/github/tx/mybatis/test/AbstractMybatisTest.java | 1303 | package com.github.tx.mybatis.test;
import java.io.Reader;
import java.sql.Connection;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.jdbc.ScriptRunner;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.After;
import org.junit.Before;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
*
* @author tangx
* @since 2014年10月22日
*/
public abstract class AbstractMybatisTest {
protected Logger logger = LoggerFactory.getLogger(this.getClass());
protected SqlSessionFactory sqlSessionFactory;
@Before
public void setUp() throws Exception {
Reader reader = Resources.getResourceAsReader("mybatis-config.xml");
sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
// 创建表
SqlSession session = null;
try {
session = sqlSessionFactory.openSession();
Connection conn = session.getConnection();
reader = Resources.getResourceAsReader("mysql.sql");
ScriptRunner runner = new ScriptRunner(conn);
runner.setLogWriter(null);
runner.runScript(reader);
reader.close();
} finally {
if (session != null) {
session.close();
}
}
}
@After
public void tearDown() throws Exception {
}
}
| apache-2.0 |
Ariah-Group/Finance | af_webapp/src/main/java/org/kuali/kfs/module/purap/document/service/impl/B2BPurchaseOrderSciquestServiceImpl.java | 34989 | /*
* Copyright 2006-2008 The Kuali Foundation
*
* Licensed under the Educational Community 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.opensource.org/licenses/ecl2.php
*
* 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.kuali.kfs.module.purap.document.service.impl;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import org.apache.commons.lang.StringUtils;
import org.kuali.kfs.module.purap.PurapConstants;
import org.kuali.kfs.module.purap.businessobject.PurchaseOrderItem;
import org.kuali.kfs.module.purap.dataaccess.B2BDao;
import org.kuali.kfs.module.purap.document.PurchaseOrderDocument;
import org.kuali.kfs.module.purap.document.RequisitionDocument;
import org.kuali.kfs.module.purap.document.service.B2BPurchaseOrderService;
import org.kuali.kfs.module.purap.document.service.RequisitionService;
import org.kuali.kfs.module.purap.exception.B2BConnectionException;
import org.kuali.kfs.module.purap.exception.CxmlParseError;
import org.kuali.kfs.module.purap.util.PurApDateFormatUtils;
import org.kuali.kfs.module.purap.util.cxml.B2BParserHelper;
import org.kuali.kfs.module.purap.util.cxml.PurchaseOrderResponse;
import org.kuali.kfs.sys.context.SpringContext;
import org.kuali.kfs.vnd.businessobject.ContractManager;
import org.kuali.rice.core.api.datetime.DateTimeService;
import org.kuali.rice.coreservice.framework.parameter.ParameterService;
import org.kuali.rice.kew.api.WorkflowDocument;
import org.kuali.rice.kim.api.identity.Person;
import org.kuali.rice.kim.api.identity.PersonService;
import org.kuali.rice.krad.util.ObjectUtils;
import org.springframework.transaction.annotation.Transactional;
@Transactional
public class B2BPurchaseOrderSciquestServiceImpl implements B2BPurchaseOrderService {
private static org.apache.log4j.Logger LOG = org.apache.log4j.Logger.getLogger(B2BPurchaseOrderSciquestServiceImpl.class);
private B2BDao b2bDao;
private RequisitionService requisitionService;
private ParameterService parameterService;
private PersonService personService;
// injected values
private String b2bEnvironment;
private String b2bUserAgent;
private String b2bPurchaseOrderURL;
private String b2bPurchaseOrderIdentity;
private String b2bPurchaseOrderPassword;
/**
* @see org.kuali.kfs.module.purap.document.service.B2BPurchaseOrderService#sendPurchaseOrder(org.kuali.kfs.module.purap.document.PurchaseOrderDocument)
*/
public String sendPurchaseOrder(PurchaseOrderDocument purchaseOrder) {
/*
* IMPORTANT DESIGN NOTE: We need the contract manager's name, phone number, and e-mail address. B2B orders that don't
* qualify to become APO's will have contract managers on the PO, and the ones that DO become APO's will not. We decided to
* always get the contract manager from the B2B contract associated with the order, and for B2B orders to ignore the
* contract manager field on the PO. We pull the name and phone number from the contract manager table and get the e-mail
* address from the user data.
*/
ContractManager contractManager = purchaseOrder.getVendorContract().getContractManager();
String contractManagerEmail = getContractManagerEmail(contractManager);
String vendorDuns = purchaseOrder.getVendorDetail().getVendorDunsNumber();
RequisitionDocument r = requisitionService.getRequisitionById(purchaseOrder.getRequisitionIdentifier());
WorkflowDocument reqWorkflowDoc = r.getDocumentHeader().getWorkflowDocument();
String requisitionInitiatorPrincipalId = getRequisitionInitiatorPrincipal(reqWorkflowDoc.getInitiatorPrincipalId());
if (LOG.isDebugEnabled()) {
LOG.debug("sendPurchaseOrder(): b2bPurchaseOrderURL is " + b2bPurchaseOrderURL);
}
String validateErrors = verifyCxmlPOData(purchaseOrder, requisitionInitiatorPrincipalId, b2bPurchaseOrderPassword, contractManager, contractManagerEmail, vendorDuns);
if (!StringUtils.isEmpty(validateErrors)) {
return validateErrors;
}
StringBuffer transmitErrors = new StringBuffer();
try {
LOG.debug("sendPurchaseOrder() Generating cxml");
String cxml = getCxml(purchaseOrder, requisitionInitiatorPrincipalId, b2bPurchaseOrderPassword, contractManager, contractManagerEmail, vendorDuns);
LOG.info("sendPurchaseOrder() Sending cxml\n" + cxml);
String responseCxml = b2bDao.sendPunchOutRequest(cxml, b2bPurchaseOrderURL);
LOG.info("sendPurchaseOrder(): Response cXML for po #" + purchaseOrder.getPurapDocumentIdentifier() + ":\n" + responseCxml);
PurchaseOrderResponse poResponse = B2BParserHelper.getInstance().parsePurchaseOrderResponse(responseCxml);
String statusText = poResponse.getStatusText();
if (LOG.isDebugEnabled()) {
LOG.debug("sendPurchaseOrder(): statusText is " + statusText);
}
if (ObjectUtils.isNull(statusText) || (!"success".equalsIgnoreCase(statusText.trim()))) {
LOG.error("sendPurchaseOrder(): PO cXML for po number " + purchaseOrder.getPurapDocumentIdentifier() + " failed sending to SciQuest:\n" + statusText);
transmitErrors.append("Unable to send Purchase Order: " + statusText);
// find any additional error messages that might have been sent
List errorMessages = poResponse.getPOResponseErrorMessages();
if (ObjectUtils.isNotNull(errorMessages) && !errorMessages.isEmpty()) {
for (Iterator iter = errorMessages.iterator(); iter.hasNext();) {
String errorMessage = (String) iter.next();
if (ObjectUtils.isNotNull(errorMessage)) {
LOG.error("sendPurchaseOrder(): SciQuest error message for po number " + purchaseOrder.getPurapDocumentIdentifier() + ": " + errorMessage);
transmitErrors.append("Error sending Purchase Order: " + errorMessage);
}
}
}
}
}
catch (B2BConnectionException e) {
LOG.error("sendPurchaseOrder() Error connecting to b2b", e);
transmitErrors.append("Connection to Sciquest failed.");
}
catch (CxmlParseError e) {
LOG.error("sendPurchaseOrder() Error Parsing", e);
transmitErrors.append("Unable to read cxml returned from Sciquest.");
}
catch (Throwable e) {
LOG.error("sendPurchaseOrder() Unknown Error", e);
transmitErrors.append("Unexpected error occurred while attempting to transmit Purchase Order.");
}
return transmitErrors.toString();
}
/**
* @see org.kuali.kfs.module.purap.document.service.B2BPurchaseOrderService#getCxml(org.kuali.kfs.module.purap.document.PurchaseOrderDocument,
* org.kuali.rice.kim.api.identity.Person, java.lang.String, org.kuali.kfs.vnd.businessobject.ContractManager,
* java.lang.String, java.lang.String)
*/
public String getCxml(PurchaseOrderDocument purchaseOrder, String requisitionInitiatorPrincipalId, String password, ContractManager contractManager, String contractManagerEmail, String vendorDuns) {
StringBuffer cxml = new StringBuffer();
cxml.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
cxml.append("<!DOCTYPE PurchaseOrderMessage SYSTEM \"PO.dtd\">\n");
cxml.append("<PurchaseOrderMessage version=\"2.0\">\n");
cxml.append(" <Header>\n");
// MessageId - can be whatever you would like it to be. Just make it unique.
cxml.append(" <MessageId>KFS_cXML_PO</MessageId>\n");
// Timestamp - it doesn't matter what's in the timezone, just that it's there (need "T" space between date/time)
Date d = SpringContext.getBean(DateTimeService.class).getCurrentDate();
SimpleDateFormat date = PurApDateFormatUtils.getSimpleDateFormat(PurapConstants.NamedDateFormats.CXML_SIMPLE_DATE_FORMAT);
SimpleDateFormat time = PurApDateFormatUtils.getSimpleDateFormat(PurapConstants.NamedDateFormats.CXML_SIMPLE_TIME_FORMAT);
cxml.append(" <Timestamp>").append(date.format(d)).append("T").append(time.format(d)).append("+05:30").append("</Timestamp>\n");
cxml.append(" <Authentication>\n");
cxml.append(" <Identity>").append(b2bPurchaseOrderIdentity).append("</Identity>\n");
cxml.append(" <SharedSecret>").append(password).append("</SharedSecret>\n");
cxml.append(" </Authentication>\n");
cxml.append(" </Header>\n");
cxml.append(" <PurchaseOrder>\n");
cxml.append(" <POHeader>\n");
cxml.append(" <PONumber>").append(purchaseOrder.getPurapDocumentIdentifier()).append("</PONumber>\n");
cxml.append(" <Requestor>\n");
cxml.append(" <UserProfile username=\"").append(requisitionInitiatorPrincipalId.toUpperCase()).append("\">\n");
cxml.append(" </UserProfile>\n");
cxml.append(" </Requestor>\n");
cxml.append(" <Priority>High</Priority>\n");
cxml.append(" <AccountingDate>").append(purchaseOrder.getPurchaseOrderCreateTimestamp()).append("</AccountingDate>\n");
/** *** SUPPLIER SECTION **** */
cxml.append(" <Supplier id=\"").append(purchaseOrder.getExternalOrganizationB2bSupplierIdentifier()).append("\">\n");
cxml.append(" <DUNS>").append(vendorDuns).append("</DUNS>\n");
cxml.append(" <SupplierNumber>").append(purchaseOrder.getVendorNumber()).append("</SupplierNumber>\n");
// Type attribute is required. Valid values: main and technical. Only main will be considered for POImport.
cxml.append(" <ContactInfo type=\"main\">\n");
// TelephoneNumber is required. With all fields, only numeric digits will be stored. Non-numeric characters are allowed, but
// will be stripped before storing.
cxml.append(" <Phone>\n");
cxml.append(" <TelephoneNumber>\n");
cxml.append(" <CountryCode>1</CountryCode>\n");
if (contractManager.getContractManagerPhoneNumber().length() > 4) {
cxml.append(" <AreaCode>").append(contractManager.getContractManagerPhoneNumber().substring(0, 3)).append("</AreaCode>\n");
cxml.append(" <Number>").append(contractManager.getContractManagerPhoneNumber().substring(3)).append("</Number>\n");
}
else {
LOG.error("getCxml() The phone number is invalid for this contract manager: " + contractManager.getContractManagerUserIdentifier() + " " + contractManager.getContractManagerName());
cxml.append(" <AreaCode>555</AreaCode>\n");
cxml.append(" <Number>").append(contractManager.getContractManagerPhoneNumber()).append("</Number>\n");
}
cxml.append(" </TelephoneNumber>\n");
cxml.append(" </Phone>\n");
cxml.append(" </ContactInfo>\n");
cxml.append(" </Supplier>\n");
/** *** BILL TO SECTION **** */
cxml.append(" <BillTo>\n");
cxml.append(" <Address>\n");
cxml.append(" <TemplateName>Bill To</TemplateName>\n");
cxml.append(" <AddressCode>").append(purchaseOrder.getDeliveryCampusCode()).append("</AddressCode>\n");
// Contact - There can be 0-5 Contact elements. The label attribute is optional.
cxml.append(" <Contact label=\"FirstName\" linenumber=\"1\"><![CDATA[Accounts]]></Contact>\n");
cxml.append(" <Contact label=\"LastName\" linenumber=\"2\"><![CDATA[Payable]]></Contact>\n");
cxml.append(" <Contact label=\"Company\" linenumber=\"3\"><![CDATA[").append(purchaseOrder.getBillingName().trim()).append("]]></Contact>\n");
// since email address is not required, we need to check whether its empty; if yes, don't add it
if (!StringUtils.isEmpty(purchaseOrder.getBillingEmailAddress())) {
cxml.append(" <Contact label=\"Email\" linenumber=\"4\"><![CDATA[").append(purchaseOrder.getBillingEmailAddress().trim()).append("]]></Contact>\n");
}
// since phone number is not required, we need to check whether its empty; if yes, don't add it
if (!StringUtils.isEmpty(purchaseOrder.getBillingPhoneNumber())) {
cxml.append(" <Contact label=\"Phone\" linenumber=\"5\"><![CDATA[").append(purchaseOrder.getBillingPhoneNumber().trim()).append("]]></Contact>\n");
}
// There must be 1-5 AddressLine elements. The label attribute is optional.
cxml.append(" <AddressLine label=\"Street1\" linenumber=\"1\"><![CDATA[").append(purchaseOrder.getBillingLine1Address()).append("]]></AddressLine>\n");
cxml.append(" <AddressLine label=\"Street2\" linenumber=\"2\"><![CDATA[").append(purchaseOrder.getBillingLine2Address()).append("]]></AddressLine>\n");
cxml.append(" <City><![CDATA[").append(purchaseOrder.getBillingCityName()).append("]]></City>\n"); // Required.
cxml.append(" <State>").append(purchaseOrder.getBillingStateCode()).append("</State>\n");
cxml.append(" <PostalCode>").append(purchaseOrder.getBillingPostalCode()).append("</PostalCode>\n"); // Required.
cxml.append(" <Country isocountrycode=\"").append(purchaseOrder.getBillingCountryCode()).append("\">").append(purchaseOrder.getBillingCountryCode()).append("</Country>\n");
cxml.append(" </Address>\n");
cxml.append(" </BillTo>\n");
/** *** SHIP TO SECTION **** */
cxml.append(" <ShipTo>\n");
cxml.append(" <Address>\n");
cxml.append(" <TemplateName>Ship To</TemplateName>\n");
// AddressCode. A code to identify the address, that is sent to the supplier.
cxml.append(" <AddressCode>").append(purchaseOrder.getDeliveryCampusCode()).append(purchaseOrder.getOrganizationCode()).append("</AddressCode>\n");
cxml.append(" <Contact label=\"Name\" linenumber=\"1\"><![CDATA[").append(purchaseOrder.getDeliveryToName().trim()).append("]]></Contact>\n");
cxml.append(" <Contact label=\"PurchasingEmail\" linenumber=\"2\"><![CDATA[").append(contractManagerEmail).append("]]></Contact>\n");
if (ObjectUtils.isNotNull(purchaseOrder.getInstitutionContactEmailAddress())) {
cxml.append(" <Contact label=\"ContactEmail\" linenumber=\"3\"><![CDATA[").append(purchaseOrder.getInstitutionContactEmailAddress()).append("]]></Contact>\n");
}
else {
cxml.append(" <Contact label=\"ContactEmail\" linenumber=\"3\"><![CDATA[").append(purchaseOrder.getRequestorPersonEmailAddress()).append("]]></Contact>\n");
}
if (ObjectUtils.isNotNull(purchaseOrder.getInstitutionContactPhoneNumber())) {
cxml.append(" <Contact label=\"Phone\" linenumber=\"4\"><![CDATA[").append(purchaseOrder.getInstitutionContactPhoneNumber().trim()).append("]]></Contact>\n");
}
else {
cxml.append(" <Contact label=\"Phone\" linenumber=\"4\"><![CDATA[").append(purchaseOrder.getRequestorPersonPhoneNumber()).append("]]></Contact>\n");
}
//check indicator to decide if receiving or delivery address should be sent to the vendor
if (purchaseOrder.getAddressToVendorIndicator()) { //use receiving address
cxml.append(" <AddressLine label=\"Street1\" linenumber=\"1\"><![CDATA[").append(purchaseOrder.getReceivingName().trim()).append("]]></AddressLine>\n");
cxml.append(" <AddressLine label=\"Street2\" linenumber=\"2\"><![CDATA[").append(purchaseOrder.getReceivingLine1Address().trim()).append("]]></AddressLine>\n");
if (ObjectUtils.isNull(purchaseOrder.getReceivingLine2Address())) {
cxml.append(" <AddressLine label=\"Street3\" linenumber=\"3\"><![CDATA[").append(" ").append("]]></AddressLine>\n");
}
else {
cxml.append(" <AddressLine label=\"Street3\" linenumber=\"3\"><![CDATA[").append(purchaseOrder.getReceivingLine2Address()).append("]]></AddressLine>\n");
}
cxml.append(" <City><![CDATA[").append(purchaseOrder.getReceivingCityName().trim()).append("]]></City>\n");
cxml.append(" <State>").append(purchaseOrder.getReceivingStateCode()).append("</State>\n");
cxml.append(" <PostalCode>").append(purchaseOrder.getReceivingPostalCode()).append("</PostalCode>\n");
cxml.append(" <Country isocountrycode=\"").append(purchaseOrder.getReceivingCountryCode()).append("\">").append(purchaseOrder.getReceivingCountryCode()).append("</Country>\n");
}
else { //use final delivery address
if (StringUtils.isNotEmpty(purchaseOrder.getDeliveryBuildingName())) {
cxml.append(" <Contact label=\"Building\" linenumber=\"5\"><![CDATA[").append(purchaseOrder.getDeliveryBuildingName()).append(" (").append(purchaseOrder.getDeliveryBuildingCode()).append(")]]></Contact>\n");
}
cxml.append(" <AddressLine label=\"Street1\" linenumber=\"1\"><![CDATA[").append(purchaseOrder.getDeliveryBuildingLine1Address().trim()).append("]]></AddressLine>\n");
cxml.append(" <AddressLine label=\"Street2\" linenumber=\"2\"><![CDATA[Room #").append(purchaseOrder.getDeliveryBuildingRoomNumber().trim()).append("]]></AddressLine>\n");
cxml.append(" <AddressLine label=\"Company\" linenumber=\"4\"><![CDATA[").append(purchaseOrder.getBillingName().trim()).append("]]></AddressLine>\n");
if (ObjectUtils.isNull(purchaseOrder.getDeliveryBuildingLine2Address())) {
cxml.append(" <AddressLine label=\"Street3\" linenumber=\"3\"><![CDATA[").append(" ").append("]]></AddressLine>\n");
}
else {
cxml.append(" <AddressLine label=\"Street3\" linenumber=\"3\"><![CDATA[").append(purchaseOrder.getDeliveryBuildingLine2Address()).append("]]></AddressLine>\n");
}
cxml.append(" <City><![CDATA[").append(purchaseOrder.getDeliveryCityName().trim()).append("]]></City>\n");
cxml.append(" <State>").append(purchaseOrder.getDeliveryStateCode()).append("</State>\n");
cxml.append(" <PostalCode>").append(purchaseOrder.getDeliveryPostalCode()).append("</PostalCode>\n");
cxml.append(" <Country isocountrycode=\"").append(purchaseOrder.getDeliveryCountryCode()).append("\">").append(purchaseOrder.getDeliveryCountryCode()).append("</Country>\n");
}
cxml.append(" </Address>\n");
cxml.append(" </ShipTo>\n");
cxml.append(" </POHeader>\n");
/** *** Items Section **** */
List detailList = purchaseOrder.getItems();
for (Iterator iter = detailList.iterator(); iter.hasNext();) {
PurchaseOrderItem poi = (PurchaseOrderItem) iter.next();
if ((ObjectUtils.isNotNull(poi.getItemType())) && poi.getItemType().isLineItemIndicator()) {
cxml.append(" <POLine linenumber=\"").append(poi.getItemLineNumber()).append("\">\n");
cxml.append(" <Item>\n");
// CatalogNumber - This is a string that the supplier uses to identify the item (i.e., SKU). Optional.
cxml.append(" <CatalogNumber><![CDATA[").append(poi.getItemCatalogNumber()).append("]]></CatalogNumber>\n");
if (ObjectUtils.isNotNull(poi.getItemAuxiliaryPartIdentifier())) {
cxml.append(" <AuxiliaryCatalogNumber><![CDATA[").append(poi.getItemAuxiliaryPartIdentifier()).append("]]></AuxiliaryCatalogNumber>\n");
}
cxml.append(" <Description><![CDATA[").append(poi.getItemDescription()).append("]]></Description>\n"); // Required.
cxml.append(" <ProductUnitOfMeasure type=\"supplier\"><Measurement><MeasurementValue><![CDATA[").append(poi.getItemUnitOfMeasureCode()).append("]]></MeasurementValue></Measurement></ProductUnitOfMeasure>\n");
cxml.append(" <ProductUnitOfMeasure type=\"system\"><Measurement><MeasurementValue><![CDATA[").append(poi.getItemUnitOfMeasureCode()).append("]]></MeasurementValue></Measurement></ProductUnitOfMeasure>\n");
// ProductReferenceNumber - Unique id for hosted products in SelectSite
if (poi.getExternalOrganizationB2bProductTypeName().equals("Punchout")) {
cxml.append(" <ProductReferenceNumber>null</ProductReferenceNumber>\n");
}
else {
cxml.append(" <ProductReferenceNumber>").append(poi.getExternalOrganizationB2bProductReferenceNumber()).append("</ProductReferenceNumber>\n");
}
// ProductType - Describes the type of the product or service. Valid values: Catalog, Form, Punchout. Mandatory.
cxml.append(" <ProductType>").append(poi.getExternalOrganizationB2bProductTypeName()).append("</ProductType>\n");
cxml.append(" </Item>\n");
cxml.append(" <Quantity>").append(poi.getItemQuantity()).append("</Quantity>\n");
// LineCharges - All the monetary charges for this line, including the price, tax, shipping, and handling.
// Required.
cxml.append(" <LineCharges>\n");
cxml.append(" <UnitPrice>\n");
cxml.append(" <Money currency=\"USD\">").append(poi.getItemUnitPrice()).append("</Money>\n");
cxml.append(" </UnitPrice>\n");
cxml.append(" </LineCharges>\n");
cxml.append(" </POLine>\n");
}
}
cxml.append(" </PurchaseOrder>\n");
cxml.append("</PurchaseOrderMessage>");
if (LOG.isDebugEnabled()) {
LOG.debug("getCxml(): cXML for po number " + purchaseOrder.getPurapDocumentIdentifier() + ":\n" + cxml.toString());
}
return cxml.toString();
}
/**
* @see org.kuali.kfs.module.purap.document.service.B2BPurchaseOrderService#verifyCxmlPOData(org.kuali.kfs.module.purap.document.PurchaseOrderDocument,
* org.kuali.rice.kim.api.identity.Person, java.lang.String, org.kuali.kfs.vnd.businessobject.ContractManager,
* java.lang.String, java.lang.String)
*/
public String verifyCxmlPOData(PurchaseOrderDocument purchaseOrder, String requisitionInitiatorPrincipalName, String password, ContractManager contractManager, String contractManagerEmail, String vendorDuns) {
StringBuffer errors = new StringBuffer();
if (ObjectUtils.isNull(purchaseOrder)) {
LOG.error("verifyCxmlPOData() The Purchase Order is null.");
errors.append("Error occurred retrieving Purchase Order\n");
return errors.toString();
}
if (ObjectUtils.isNull(contractManager)) {
LOG.error("verifyCxmlPOData() The contractManager is null.");
errors.append("Error occurred retrieving Contract Manager\n");
return errors.toString();
}
if (StringUtils.isEmpty(password)) {
LOG.error("verifyCxmlPOData() The B2B PO password is required for the cXML PO but is missing.");
errors.append("Missing Data: B2B PO password\n");
}
if (ObjectUtils.isNull(purchaseOrder.getPurapDocumentIdentifier())) {
LOG.error("verifyCxmlPOData() The purchase order Id is required for the cXML PO but is missing.");
errors.append("Missing Data: Purchase Order ID\n");
}
if (StringUtils.isEmpty(requisitionInitiatorPrincipalName)) {
LOG.error("verifyCxmlPOData() The requisition initiator principal name is required for the cXML PO but is missing.");
errors.append("Missing Data: Requisition Initiator Principal Name\n");
}
if (ObjectUtils.isNull(purchaseOrder.getPurchaseOrderCreateTimestamp())) {
LOG.error("verifyCxmlPOData() The PO create date is required for the cXML PO but is null.");
errors.append("Create Date\n");
}
if (StringUtils.isEmpty(contractManager.getContractManagerPhoneNumber())) {
LOG.error("verifyCxmlPOData() The contract manager phone number is required for the cXML PO but is missing.");
errors.append("Missing Data: Contract Manager Phone Number\n");
}
if (StringUtils.isEmpty(contractManager.getContractManagerName())) {
LOG.error("verifyCxmlPOData() The contract manager name is required for the cXML PO but is missing.");
errors.append("Missing Data: Contract Manager Name\n");
}
if (StringUtils.isEmpty(purchaseOrder.getDeliveryCampusCode())) {
LOG.error("verifyCxmlPOData() The Delivery Campus Code is required for the cXML PO but is missing.");
errors.append("Missing Data: Delivery Campus Code\n");
}
if (StringUtils.isEmpty(purchaseOrder.getBillingName())) {
LOG.error("verifyCxmlPOData() The Delivery Billing Name is required for the cXML PO but is missing.");
errors.append("Missing Data: Delivery Billing Name\n");
}
if (StringUtils.isEmpty(purchaseOrder.getBillingLine1Address())) {
LOG.error("verifyCxmlPOData() The Billing Line 1 Address is required for the cXML PO but is missing.");
errors.append("Missing Data: Billing Line 1 Address\n");
}
if (StringUtils.isEmpty(purchaseOrder.getBillingLine2Address())) {
LOG.error("verifyCxmlPOData() The Billing Line 2 Address is required for the cXML PO but is missing.");
errors.append("Missing Data: Billing Line 2 Address\n");
}
if (StringUtils.isEmpty(purchaseOrder.getBillingCityName())) {
LOG.error("verifyCxmlPOData() The Billing Address City Name is required for the cXML PO but is missing.");
errors.append("Missing Data: Billing Address City Name\n");
}
if (StringUtils.isEmpty(purchaseOrder.getBillingStateCode())) {
LOG.error("verifyCxmlPOData() The Billing Address State Code is required for the cXML PO but is missing.");
errors.append("Missing Data: Billing Address State Code\n");
}
if (StringUtils.isEmpty(purchaseOrder.getBillingPostalCode())) {
LOG.error("verifyCxmlPOData() The Billing Address Postal Code is required for the cXML PO but is missing.");
errors.append("Missing Data: Billing Address Postal Code\n");
}
if (StringUtils.isEmpty(purchaseOrder.getDeliveryToName())) {
LOG.error("verifyCxmlPOData() The Delivery To Name is required for the cXML PO but is missing.");
errors.append("Missing Data: Delivery To Name\n");
}
if (StringUtils.isEmpty(contractManagerEmail)) {
LOG.error("verifyCxmlPOData() The Contract Manager Email is required for the cXML PO but is missing.");
errors.append("Missing Data: Contract Manager Email\n");
}
if (StringUtils.isEmpty(purchaseOrder.getRequestorPersonEmailAddress())) {
LOG.error("verifyCxmlPOData() The Requesting Person Email Address is required for the cXML PO but is missing.");
errors.append("Missing Data: Requesting Person Email Address\n");
}
if (StringUtils.isEmpty(purchaseOrder.getRequestorPersonPhoneNumber())) {
LOG.error("verifyCxmlPOData() The Requesting Person Phone Number is required for the cXML PO but is missing.");
errors.append("Missing Data: Requesting Person Phone Number\n");
}
if (StringUtils.isEmpty(purchaseOrder.getDeliveryBuildingLine1Address())) {
LOG.error("verifyCxmlPOData() The Delivery Line 1 Address is required for the cXML PO but is missing.");
errors.append("Missing Data: Delivery Line 1 Address\n");
}
if (StringUtils.isEmpty(purchaseOrder.getDeliveryToName())) {
LOG.error("verifyCxmlPOData() The Delivery To Name is required for the cXML PO but is missing.");
errors.append("Missing Data: Delivery To Name\n");
}
if (StringUtils.isEmpty(purchaseOrder.getDeliveryCityName())) {
LOG.error("verifyCxmlPOData() The Delivery City Name is required for the cXML PO but is missing.");
errors.append("Missing Data: Delivery City Name\n");
}
if (StringUtils.isEmpty(purchaseOrder.getDeliveryStateCode())) {
LOG.error("verifyCxmlPOData() The Delivery State is required for the cXML PO but is missing.");
errors.append("Missing Data: Delivery State\n");
}
if (StringUtils.isEmpty(purchaseOrder.getDeliveryPostalCode())) {
LOG.error("verifyCxmlPOData() The Delivery Postal Code is required for the cXML PO but is missing.");
errors.append("Missing Data: Delivery Postal Code\n");
}
// verify item data
List detailList = purchaseOrder.getItems();
for (Iterator iter = detailList.iterator(); iter.hasNext();) {
PurchaseOrderItem poi = (PurchaseOrderItem) iter.next();
if (ObjectUtils.isNotNull(poi.getItemType()) && poi.getItemType().isLineItemIndicator()) {
if (ObjectUtils.isNull(poi.getItemLineNumber())) {
LOG.error("verifyCxmlPOData() The Item Line Number is required for the cXML PO but is missing.");
errors.append("Missing Data: Item Line Number\n");
}
if (StringUtils.isEmpty(poi.getItemCatalogNumber())) {
LOG.error("verifyCxmlPOData() The Catalog Number for item number " + poi.getItemLineNumber() + " is required for the cXML PO but is missing.");
errors.append("Missing Data: Item#" + poi.getItemLineNumber() + " - Catalog Number\n");
}
if (StringUtils.isEmpty(poi.getItemDescription())) {
LOG.error("verifyCxmlPOData() The Description for item number " + poi.getItemLineNumber() + " is required for the cXML PO but is missing.");
errors.append("Missing Data: Item#" + poi.getItemLineNumber() + " - Description\n");
}
if (StringUtils.isEmpty(poi.getItemUnitOfMeasureCode())) {
LOG.error("verifyCxmlPOData() The Unit Of Measure Code for item number " + poi.getItemLineNumber() + " is required for the cXML PO but is missing.");
errors.append("Missing Data: Item#" + poi.getItemLineNumber() + " - Unit Of Measure\n");
}
if (StringUtils.isEmpty(poi.getExternalOrganizationB2bProductTypeName())) {
LOG.error("verifyCxmlPOData() The External Org B2B Product Type Name for item number " + poi.getItemLineNumber() + " is required for the cXML PO but is missing.");
errors.append("Missing Data: Item#" + poi.getItemLineNumber() + " - External Org B2B Product Type Name\n");
}
if (poi.getItemQuantity() == null) {
LOG.error("verifyCxmlPOData() The Order Quantity for item number " + poi.getItemLineNumber() + " is required for the cXML PO but is missing.");
errors.append("Missing Data: Item#" + poi.getItemLineNumber() + " - Order Quantity\n");
}
if (poi.getItemUnitPrice() == null) {
LOG.error("verifyCxmlPOData() The Unit Price for item number " + poi.getItemLineNumber() + " is required for the cXML PO but is missing.");
errors.append("Missing Data: Item#" + poi.getItemLineNumber() + " - Unit Price\n");
}
}
} // end item looping
return errors.toString();
}
/**
* Retrieve the Contract Manager's email
*/
protected String getContractManagerEmail(ContractManager cm) {
Person contractManager = getPersonService().getPerson(cm.getContractManagerUserIdentifier());
if (ObjectUtils.isNotNull(contractManager)) {
return contractManager.getEmailAddressUnmasked();
}
return "";
}
/**
* Retrieve the Requisition Initiator Principal Name
*/
protected String getRequisitionInitiatorPrincipal(String requisitionInitiatorPrincipalId) {
Person requisitionInitiator = getPersonService().getPerson(requisitionInitiatorPrincipalId);
if (ObjectUtils.isNotNull(requisitionInitiator)) {
return requisitionInitiator.getPrincipalName();
}
return "";
}
public void setRequisitionService(RequisitionService requisitionService) {
this.requisitionService = requisitionService;
}
public void setParameterService(ParameterService parameterService) {
this.parameterService = parameterService;
}
public void setB2bDao(B2BDao b2bDao) {
this.b2bDao = b2bDao;
}
/**
* @return Returns the personService.
*/
protected PersonService getPersonService() {
if(personService==null)
personService = SpringContext.getBean(PersonService.class);
return personService;
}
public void setB2bEnvironment(String environment) {
b2bEnvironment = environment;
}
public void setB2bUserAgent(String userAgent) {
b2bUserAgent = userAgent;
}
public void setB2bPurchaseOrderURL(String purchaseOrderURL) {
b2bPurchaseOrderURL = purchaseOrderURL;
}
public void setB2bPurchaseOrderIdentity(String b2bPurchaseOrderIdentity) {
this.b2bPurchaseOrderIdentity = b2bPurchaseOrderIdentity;
}
public void setB2bPurchaseOrderPassword(String purchaseOrderPassword) {
b2bPurchaseOrderPassword = purchaseOrderPassword;
}
}
| apache-2.0 |
bremond/siconos | mechanics/src/joints/JointFrictionR.cpp | 3286 | /* Siconos is a program dedicated to modeling, simulation and control
* of non smooth dynamical systems.
*
* Copyright 2016 INRIA.
*
* 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.
*/
/*! \file JointFrictionR.cpp
*/
#include "JointFrictionR.hpp"
#include <NewtonEulerDS.hpp>
#include <Interaction.hpp>
#include <boost/math/quaternion.hpp>
#include <BlockVector.hpp>
#include <cfloat>
#include <iostream>
// #define DEBUG_BEGIN_END_ONLY
// #define DEBUG_STDOUT
// #define DEBUG_MESSAGES
#include "debug.h"
/** Initialize a joint friction for a common case: a single axis with a
* single friction, either positive or negative. For use with
* NewtonImpactNSL. */
JointFrictionR::JointFrictionR(SP::NewtonEulerJointR joint, unsigned int axis)
: NewtonEulerR()
, _joint(joint)
, _axis(std11::make_shared< std::vector<unsigned int> >())
{
_axis->push_back(axis);
_axisMin = axis;
_axisMax = axis;
assert( (_axisMax - _axisMin + 1) <= _joint->numberOfDoF() );
}
/** Initialize a multidimensional joint friction, e.g. the cone friction on
* a ball joint. For use with NewtonImpactFrictionNSL size 2 or 3. */
JointFrictionR::JointFrictionR(SP::NewtonEulerJointR joint, SP::UnsignedIntVector axes)
: NewtonEulerR()
, _joint(joint)
, _axis(axes)
{
if (axes)
{
_axisMin = 100;
_axisMax = 0;
for (unsigned int i=0; i < _axis->size(); i++)
{
if ((*_axis)[i] > _axisMax) _axisMax = (*_axis)[i];
if ((*_axis)[i] < _axisMin) _axisMin = (*_axis)[i];
}
}
else
{
_axisMin = _axisMax = 0;
_axis = std11::make_shared< std::vector<unsigned int> >();
_axis->push_back(0);
}
assert( (_axisMax - _axisMin + 1) <= _joint->numberOfDoF() );
}
void JointFrictionR::computeh(double time, BlockVector& q0, SiconosVector& y)
{
// Velocity-level constraint, no position-level h
y.zero();
}
void JointFrictionR::computeJachq(double time, Interaction& inter, SP::BlockVector q0)
{
unsigned int n = _axisMax - _axisMin + 1;
assert(n==1); // For now, multi-axis support TODO
if (!_jachqTmp || !(_jachqTmp->size(1) == q0->size() &&
_jachqTmp->size(0) == n))
{
_jachqTmp = std11::make_shared<SimpleMatrix>(n, q0->size());
}
// Compute the jacobian for the required range of axes
_joint->computeJachqDoF(time, inter, q0, *_jachqTmp, _axisMin);
// Copy indicated axes into the friction jacobian, negative and positive sides
// NOTE trying ==1 using Relay, maybe don't need LCP formulation
assert(_jachq->size(0)==1);
for (unsigned int i=0; i<1; i++)
for (unsigned int j=0; j<_jachq->size(1); j++) {
_jachq->setValue(i,j,_jachqTmp->getValue((*_axis)[i]-_axisMin,j) * (i==1?1:-1));
}
}
unsigned int JointFrictionR::numberOfConstraints()
{
return _axis->size();
}
| apache-2.0 |
googleapis/google-api-java-client-services | clients/google-api-services-dialogflow/v3/1.31.0/com/google/api/services/dialogflow/v3/model/GoogleCloudDialogflowV2beta1IntentMessageBrowseCarouselCard.java | 3654 | /*
* 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.dialogflow.v3.model;
/**
* Browse Carousel Card for Actions on Google.
* https://developers.google.com/actions/assistant/responses#browsing_carousel
*
* <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 Dialogflow 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 GoogleCloudDialogflowV2beta1IntentMessageBrowseCarouselCard extends com.google.api.client.json.GenericJson {
/**
* Optional. Settings for displaying the image. Applies to every image in items.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String imageDisplayOptions;
/**
* Required. List of items in the Browse Carousel Card. Minimum of two items, maximum of ten.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<GoogleCloudDialogflowV2beta1IntentMessageBrowseCarouselCardBrowseCarouselCardItem> items;
/**
* Optional. Settings for displaying the image. Applies to every image in items.
* @return value or {@code null} for none
*/
public java.lang.String getImageDisplayOptions() {
return imageDisplayOptions;
}
/**
* Optional. Settings for displaying the image. Applies to every image in items.
* @param imageDisplayOptions imageDisplayOptions or {@code null} for none
*/
public GoogleCloudDialogflowV2beta1IntentMessageBrowseCarouselCard setImageDisplayOptions(java.lang.String imageDisplayOptions) {
this.imageDisplayOptions = imageDisplayOptions;
return this;
}
/**
* Required. List of items in the Browse Carousel Card. Minimum of two items, maximum of ten.
* @return value or {@code null} for none
*/
public java.util.List<GoogleCloudDialogflowV2beta1IntentMessageBrowseCarouselCardBrowseCarouselCardItem> getItems() {
return items;
}
/**
* Required. List of items in the Browse Carousel Card. Minimum of two items, maximum of ten.
* @param items items or {@code null} for none
*/
public GoogleCloudDialogflowV2beta1IntentMessageBrowseCarouselCard setItems(java.util.List<GoogleCloudDialogflowV2beta1IntentMessageBrowseCarouselCardBrowseCarouselCardItem> items) {
this.items = items;
return this;
}
@Override
public GoogleCloudDialogflowV2beta1IntentMessageBrowseCarouselCard set(String fieldName, Object value) {
return (GoogleCloudDialogflowV2beta1IntentMessageBrowseCarouselCard) super.set(fieldName, value);
}
@Override
public GoogleCloudDialogflowV2beta1IntentMessageBrowseCarouselCard clone() {
return (GoogleCloudDialogflowV2beta1IntentMessageBrowseCarouselCard) super.clone();
}
}
| apache-2.0 |
MobileManAG/KURAVIS | src/main/java/com/mobileman/kuravis/core/util/JsonUtil.java | 974 | /*******************************************************************************
* Copyright 2015 MobileMan GmbH
* www.mobileman.com
*
* 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.mobileman.kuravis.core.util;
/**
* @author MobileMan GmbH
*
*/
public class JsonUtil {
/**
*
*/
public static final String MEDIA_TYPE_APPLICATION_JSON = "application/json";
}
| apache-2.0 |
googleads/google-ads-php | src/Google/Ads/GoogleAds/V8/Errors/UrlFieldErrorEnum.php | 851 | <?php
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: google/ads/googleads/v8/errors/url_field_error.proto
namespace Google\Ads\GoogleAds\V8\Errors;
use Google\Protobuf\Internal\GPBType;
use Google\Protobuf\Internal\RepeatedField;
use Google\Protobuf\Internal\GPBUtil;
/**
* Container for enum describing possible url field errors.
*
* Generated from protobuf message <code>google.ads.googleads.v8.errors.UrlFieldErrorEnum</code>
*/
class UrlFieldErrorEnum extends \Google\Protobuf\Internal\Message
{
/**
* Constructor.
*
* @param array $data {
* Optional. Data for populating the Message object.
*
* }
*/
public function __construct($data = NULL) {
\GPBMetadata\Google\Ads\GoogleAds\V8\Errors\UrlFieldError::initOnce();
parent::__construct($data);
}
}
| apache-2.0 |
TKnudsen/ComplexDataObject | src/main/java/com/github/TKnudsen/ComplexDataObject/model/scoring/functions/BooleanAttributeScoringFunction.java | 4405 | package com.github.TKnudsen.ComplexDataObject.model.scoring.functions;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Function;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.github.TKnudsen.ComplexDataObject.data.complexDataObject.ComplexDataContainer;
import com.github.TKnudsen.ComplexDataObject.data.complexDataObject.ComplexDataObject;
import com.github.TKnudsen.ComplexDataObject.model.io.parsers.objects.BooleanParser;
import com.github.TKnudsen.ComplexDataObject.model.io.parsers.objects.IObjectParser;
import com.github.TKnudsen.ComplexDataObject.model.tools.StatisticsSupport;
import com.github.TKnudsen.ComplexDataObject.model.transformations.normalization.LinearNormalizationFunction;
import com.github.TKnudsen.ComplexDataObject.model.transformations.normalization.NormalizationFunction;
import com.github.TKnudsen.ComplexDataObject.model.transformations.normalization.QuantileNormalizationFunction;
public class BooleanAttributeScoringFunction extends AttributeScoringFunction<Boolean> {
@JsonIgnore
private StatisticsSupport statisticsSupport;
private NormalizationFunction normalizationFunction;
private QuantileNormalizationFunction quantileNormalizationFunction;
/**
* for serialization purposes
*/
@SuppressWarnings("unused")
private BooleanAttributeScoringFunction() {
super();
}
public BooleanAttributeScoringFunction(ComplexDataContainer container, String attribute) {
this(container, new BooleanParser(), attribute, null, false, true, 1.0, null);
}
public BooleanAttributeScoringFunction(ComplexDataContainer container, IObjectParser<Boolean> parser,
String attribute, String abbreviation, boolean quantileBased, boolean highIsGood, double weight) {
this(container, parser, attribute, abbreviation, quantileBased, highIsGood, weight, null);
}
public BooleanAttributeScoringFunction(ComplexDataContainer container, IObjectParser<Boolean> parser,
String attribute, String abbreviation, boolean quantileBased, boolean highIsGood, double weight,
Function<ComplexDataObject, Double> uncertaintyFunction) {
super(container, parser, attribute, abbreviation, quantileBased, highIsGood, weight, uncertaintyFunction);
refreshScoringFunction();
}
@Override
protected void refreshScoringFunction() {
Map<Long, Object> attributeValues = getContainer().getAttributeValues(getAttribute());
Collection<Object> values = attributeValues.values();
List<Double> doubleValues = new ArrayList<>();
for (Object o : values) {
Boolean b = getParser().apply(o);
if (b == null)
continue;
doubleValues.add(toDouble(b));
}
statisticsSupport = new StatisticsSupport(doubleValues);
if (getQuantileNormalizationRate() > 0)
quantileNormalizationFunction = new QuantileNormalizationFunction(statisticsSupport, true);
normalizationFunction = new LinearNormalizationFunction(0.0, 1.0, true);
scoreAverageWithoutMissingValues = AttributeScoringFunctions.calculateAverageScoreWithoutMissingValues(this,
false);
// clear scoresBuffer as it contains old missing value data now
scoresBuffer.clear();
if (Double.isNaN(scoreAverageWithoutMissingValues))
System.err.println(
this.getClass().getSimpleName() + ": NaN value detected for the scoreAverageWithoutMissingValues!");
Double missingValueAvgScoreRatio = getMissingValueAvgScoreRatio();
if (missingValueAvgScoreRatio == null || Double.isNaN(missingValueAvgScoreRatio))
scoreForMissingObjects = scoreAverageWithoutMissingValues * 0.5;
else
scoreForMissingObjects = scoreAverageWithoutMissingValues * missingValueAvgScoreRatio;
}
@Override
protected Double toDouble(Boolean t) {
Objects.requireNonNull(t);
if (t)
return 1.0;
return 0.0;
}
@Override
protected double invertScore(double output) {
return output = 1 - output;
}
@Override
protected double normalizeLinear(double value) {
return normalizationFunction.apply(value).doubleValue();
}
@Override
protected double normalizeQuantiles(double value) {
return quantileNormalizationFunction.apply(value).doubleValue();
}
@Override
public StatisticsSupport getStatisticsSupport() {
return statisticsSupport;
}
}
| apache-2.0 |
hmcfletch/cache-money | lib/cache_money.rb | 1216 | $LOAD_PATH.unshift(File.dirname(__FILE__))
require 'rubygems'
require 'active_support'
require 'active_record'
require 'cash/lock'
require 'cash/transactional'
require 'cash/write_through'
require 'cash/finders'
require 'cash/buffered'
require 'cash/index'
require 'cash/config'
require 'cash/accessor'
require 'cash/request'
require 'cash/mock'
require 'cash/local'
require 'cash/query/abstract'
require 'cash/query/select'
require 'cash/query/primary_key'
require 'cash/query/calculation'
require 'cash/util/array'
class ActiveRecord::Base
def self.is_cached(options = {})
options.assert_valid_keys(:ttl, :repository, :version)
include Cash
Config.create(self, options)
end
end
module Cash
def self.included(active_record_class)
active_record_class.class_eval do
include Config, Accessor, WriteThrough, Finders
extend ClassMethods
end
end
module ClassMethods
def self.extended(active_record_class)
class << active_record_class
alias_method_chain :transaction, :cache_transaction
end
end
def transaction_with_cache_transaction(&block)
repository.transaction { transaction_without_cache_transaction(&block) }
end
end
end
| apache-2.0 |
ArcherCraftStore/ArcherVMPeridot | apps/owncloud/htdocs/lib/private/user.php | 16044 | <?php
/**
* ownCloud
*
* @author Frank Karlitschek
* @copyright 2012 Frank Karlitschek frank@owncloud.org
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
* License as published by the Free Software Foundation; either
* version 3 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU AFFERO GENERAL PUBLIC LICENSE for more details.
*
* You should have received a copy of the GNU Affero General Public
* License along with this library. If not, see <http://www.gnu.org/licenses/>.
*
*/
/**
* This class provides wrapper methods for user management. Multiple backends are
* supported. User management operations are delegated to the configured backend for
* execution.
*
* Hooks provided:
* pre_createUser(&run, uid, password)
* post_createUser(uid, password)
* pre_deleteUser(&run, uid)
* post_deleteUser(uid)
* pre_setPassword(&run, uid, password, recoveryPassword)
* post_setPassword(uid, password, recoveryPassword)
* pre_login(&run, uid, password)
* post_login(uid)
* logout()
*/
class OC_User {
public static function getUserSession() {
return OC::$server->getUserSession();
}
/**
* @return \OC\User\Manager
*/
public static function getManager() {
return OC::$server->getUserManager();
}
private static $_backends = array();
private static $_usedBackends = array();
private static $_setupedBackends = array();
// bool, stores if a user want to access a resource anonymously, e.g if he opens a public link
private static $incognitoMode = false;
/**
* @brief registers backend
* @param string $backend name of the backend
* @deprecated Add classes by calling useBackend with a class instance instead
* @return bool
*
* Makes a list of backends that can be used by other modules
*/
public static function registerBackend($backend) {
self::$_backends[] = $backend;
return true;
}
/**
* @brief gets available backends
* @deprecated
* @returns array of backends
*
* Returns the names of all backends.
*/
public static function getBackends() {
return self::$_backends;
}
/**
* @brief gets used backends
* @deprecated
* @returns array of backends
*
* Returns the names of all used backends.
*/
public static function getUsedBackends() {
return array_keys(self::$_usedBackends);
}
/**
* @brief Adds the backend to the list of used backends
* @param string | OC_User_Backend $backend default: database The backend to use for user management
* @return bool
*
* Set the User Authentication Module
*/
public static function useBackend($backend = 'database') {
if ($backend instanceof OC_User_Interface) {
self::$_usedBackends[get_class($backend)] = $backend;
self::getManager()->registerBackend($backend);
} else {
// You'll never know what happens
if (null === $backend OR !is_string($backend)) {
$backend = 'database';
}
// Load backend
switch ($backend) {
case 'database':
case 'mysql':
case 'sqlite':
OC_Log::write('core', 'Adding user backend ' . $backend . '.', OC_Log::DEBUG);
self::$_usedBackends[$backend] = new OC_User_Database();
self::getManager()->registerBackend(self::$_usedBackends[$backend]);
break;
default:
OC_Log::write('core', 'Adding default user backend ' . $backend . '.', OC_Log::DEBUG);
$className = 'OC_USER_' . strToUpper($backend);
self::$_usedBackends[$backend] = new $className();
self::getManager()->registerBackend(self::$_usedBackends[$backend]);
break;
}
}
return true;
}
/**
* remove all used backends
*/
public static function clearBackends() {
self::$_usedBackends = array();
self::getManager()->clearBackends();
}
/**
* setup the configured backends in config.php
*/
public static function setupBackends() {
OC_App::loadApps(array('prelogin'));
$backends = OC_Config::getValue('user_backends', array());
foreach ($backends as $i => $config) {
$class = $config['class'];
$arguments = $config['arguments'];
if (class_exists($class)) {
if (array_search($i, self::$_setupedBackends) === false) {
// make a reflection object
$reflectionObj = new ReflectionClass($class);
// use Reflection to create a new instance, using the $args
$backend = $reflectionObj->newInstanceArgs($arguments);
self::useBackend($backend);
self::$_setupedBackends[] = $i;
} else {
OC_Log::write('core', 'User backend ' . $class . ' already initialized.', OC_Log::DEBUG);
}
} else {
OC_Log::write('core', 'User backend ' . $class . ' not found.', OC_Log::ERROR);
}
}
}
/**
* @brief Create a new user
* @param string $uid The username of the user to create
* @param string $password The password of the new user
* @throws Exception
* @return bool true/false
*
* Creates a new user. Basic checking of username is done in OC_User
* itself, not in its subclasses.
*
* Allowed characters in the username are: "a-z", "A-Z", "0-9" and "_.@-"
*/
public static function createUser($uid, $password) {
return self::getManager()->createUser($uid, $password);
}
/**
* @brief delete a user
* @param string $uid The username of the user to delete
* @return bool
*
* Deletes a user
*/
public static function deleteUser($uid) {
$user = self::getManager()->get($uid);
if ($user) {
$result = $user->delete();
// if delete was successful we clean-up the rest
if ($result) {
// We have to delete the user from all groups
foreach (OC_Group::getUserGroups($uid) as $i) {
OC_Group::removeFromGroup($uid, $i);
}
// Delete the user's keys in preferences
OC_Preferences::deleteUser($uid);
// Delete user files in /data/
$home = \OC_User::getHome($uid);
OC_Helper::rmdirr($home);
// Delete the users entry in the storage table
\OC\Files\Cache\Storage::remove('home::' . $uid);
\OC\Files\Cache\Storage::remove('local::' . $home . '/');
// Remove it from the Cache
self::getManager()->delete($uid);
}
return true;
} else {
return false;
}
}
/**
* @brief Try to login a user
* @param $uid The username of the user to log in
* @param $password The password of the user
* @return bool
*
* Log in a user and regenerate a new session - if the password is ok
*/
public static function login($uid, $password) {
session_regenerate_id(true);
return self::getUserSession()->login($uid, $password);
}
/**
* @brief Try to login a user, assuming authentication
* has already happened (e.g. via Single Sign On).
*
* Log in a user and regenerate a new session.
*
* @param \OCP\Authentication\IApacheBackend $backend
* @return bool
*/
public static function loginWithApache(\OCP\Authentication\IApacheBackend $backend) {
$uid = $backend->getCurrentUserId();
$run = true;
OC_Hook::emit( "OC_User", "pre_login", array( "run" => &$run, "uid" => $uid ));
if($uid) {
self::setUserId($uid);
self::setDisplayName($uid);
self::getUserSession()->setLoginName($uid);
OC_Hook::emit( "OC_User", "post_login", array( "uid" => $uid, 'password'=>'' ));
return true;
}
return false;
}
/**
* @brief Verify with Apache whether user is authenticated.
*
* @return boolean|null
* true: authenticated
* false: not authenticated
* null: not handled / no backend available
*/
public static function handleApacheAuth() {
$backend = self::findFirstActiveUsedBackend();
if ($backend) {
OC_App::loadApps();
//setup extra user backends
self::setupBackends();
self::unsetMagicInCookie();
return self::loginWithApache($backend);
}
return null;
}
/**
* @brief Sets user id for session and triggers emit
*/
public static function setUserId($uid) {
OC::$session->set('user_id', $uid);
}
/**
* @brief Sets user display name for session
*/
public static function setDisplayName($uid, $displayName = null) {
if (is_null($displayName)) {
$displayName = $uid;
}
$user = self::getManager()->get($uid);
if ($user) {
return $user->setDisplayName($displayName);
} else {
return false;
}
}
/**
* @brief Logs the current user out and kills all the session data
*
* Logout, destroys session
*/
public static function logout() {
self::getUserSession()->logout();
}
/**
* @brief Check if the user is logged in
* @returns bool
*
* Checks if the user is logged in
*/
public static function isLoggedIn() {
if (\OC::$session->get('user_id') && self::$incognitoMode === false) {
OC_App::loadApps(array('authentication'));
self::setupBackends();
return self::userExists(\OC::$session->get('user_id'));
}
return false;
}
/**
* @brief set incognito mode, e.g. if a user wants to open a public link
* @param bool $status
*/
public static function setIncognitoMode($status) {
self::$incognitoMode = $status;
}
/**
* Supplies an attribute to the logout hyperlink. The default behaviour
* is to return an href with '?logout=true' appended. However, it can
* supply any attribute(s) which are valid for <a>.
*
* @return string with one or more HTML attributes.
*/
public static function getLogoutAttribute() {
$backend = self::findFirstActiveUsedBackend();
if ($backend) {
return $backend->getLogoutAttribute();
}
return 'href="' . link_to('', 'index.php') . '?logout=true"';
}
/**
* @brief Check if the user is an admin user
* @param string $uid uid of the admin
* @return bool
*/
public static function isAdminUser($uid) {
if (OC_Group::inGroup($uid, 'admin') && self::$incognitoMode === false) {
return true;
}
return false;
}
/**
* @brief get the user id of the user currently logged in.
* @return string uid or false
*/
public static function getUser() {
$uid = OC::$session ? OC::$session->get('user_id') : null;
if (!is_null($uid) && self::$incognitoMode === false) {
return $uid;
} else {
return false;
}
}
/**
* @brief get the display name of the user currently logged in.
* @param string $uid
* @return string uid or false
*/
public static function getDisplayName($uid = null) {
if ($uid) {
$user = self::getManager()->get($uid);
if ($user) {
return $user->getDisplayName();
} else {
return $uid;
}
} else {
$user = self::getUserSession()->getUser();
if ($user) {
return $user->getDisplayName();
} else {
return false;
}
}
}
/**
* @brief Autogenerate a password
* @return string
*
* generates a password
*/
public static function generatePassword() {
return OC_Util::generateRandomBytes(30);
}
/**
* @brief Set password
* @param string $uid The username
* @param string $password The new password
* @param string $recoveryPassword for the encryption app to reset encryption keys
* @return bool
*
* Change the password of a user
*/
public static function setPassword($uid, $password, $recoveryPassword = null) {
$user = self::getManager()->get($uid);
if ($user) {
return $user->setPassword($password, $recoveryPassword);
} else {
return false;
}
}
/**
* @brief Check whether user can change his avatar
* @param string $uid The username
* @return bool
*
* Check whether a specified user can change his avatar
*/
public static function canUserChangeAvatar($uid) {
$user = self::getManager()->get($uid);
if ($user) {
return $user->canChangeAvatar();
} else {
return false;
}
}
/**
* @brief Check whether user can change his password
* @param string $uid The username
* @return bool
*
* Check whether a specified user can change his password
*/
public static function canUserChangePassword($uid) {
$user = self::getManager()->get($uid);
if ($user) {
return $user->canChangePassword();
} else {
return false;
}
}
/**
* @brief Check whether user can change his display name
* @param string $uid The username
* @return bool
*
* Check whether a specified user can change his display name
*/
public static function canUserChangeDisplayName($uid) {
$user = self::getManager()->get($uid);
if ($user) {
return $user->canChangeDisplayName();
} else {
return false;
}
}
/**
* @brief Check if the password is correct
* @param string $uid The username
* @param string $password The password
* @return mixed user id a string on success, false otherwise
*
* Check if the password is correct without logging in the user
* returns the user id or false
*/
public static function checkPassword($uid, $password) {
$manager = self::getManager();
$username = $manager->checkPassword($uid, $password);
if ($username !== false) {
return $username->getUID();
}
return false;
}
/**
* @param string $uid The username
* @return string
*
* returns the path to the users home directory
*/
public static function getHome($uid) {
$user = self::getManager()->get($uid);
if ($user) {
return $user->getHome();
} else {
return OC_Config::getValue('datadirectory', OC::$SERVERROOT . '/data') . '/' . $uid;
}
}
/**
* @brief Get a list of all users
* @returns array with all uids
*
* Get a list of all users.
*/
public static function getUsers($search = '', $limit = null, $offset = null) {
$users = self::getManager()->search($search, $limit, $offset);
$uids = array();
foreach ($users as $user) {
$uids[] = $user->getUID();
}
return $uids;
}
/**
* @brief Get a list of all users display name
* @param string $search
* @param int $limit
* @param int $offset
* @return array associative array with all display names (value) and corresponding uids (key)
*
* Get a list of all display names and user ids.
*/
public static function getDisplayNames($search = '', $limit = null, $offset = null) {
$displayNames = array();
$users = self::getManager()->searchDisplayName($search, $limit, $offset);
foreach ($users as $user) {
$displayNames[$user->getUID()] = $user->getDisplayName();
}
return $displayNames;
}
/**
* @brief check if a user exists
* @param string $uid the username
* @return boolean
*/
public static function userExists($uid) {
return self::getManager()->userExists($uid);
}
/**
* disables a user
*
* @param string $uid the user to disable
*/
public static function disableUser($uid) {
$user = self::getManager()->get($uid);
if ($user) {
$user->setEnabled(false);
}
}
/**
* enable a user
*
* @param string $uid
*/
public static function enableUser($uid) {
$user = self::getManager()->get($uid);
if ($user) {
$user->setEnabled(true);
}
}
/**
* checks if a user is enabled
*
* @param string $uid
* @return bool
*/
public static function isEnabled($uid) {
$user = self::getManager()->get($uid);
if ($user) {
return $user->isEnabled();
} else {
return false;
}
}
/**
* @brief Set cookie value to use in next page load
* @param string $username username to be set
* @param string $token
*/
public static function setMagicInCookie($username, $token) {
self::getUserSession()->setMagicInCookie($username, $token);
}
/**
* @brief Remove cookie for "remember username"
*/
public static function unsetMagicInCookie() {
self::getUserSession()->unsetMagicInCookie();
}
/**
* @brief Returns the first active backend from self::$_usedBackends.
* @return null if no backend active, otherwise OCP\Authentication\IApacheBackend
*/
private static function findFirstActiveUsedBackend() {
foreach (self::$_usedBackends as $backend) {
if ($backend instanceof OCP\Authentication\IApacheBackend) {
if ($backend->isSessionActive()) {
return $backend;
}
}
}
return null;
}
}
| apache-2.0 |
caiiiyua/UnifiedApp | src/org/caiiiyua/unifiedapp/utils/ContentProviderTask.java | 4944 | /*
* Copyright (C) 2012 Google Inc.
* Licensed to The Android Open Source Project.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.caiiiyua.unifiedapp.utils;
import android.content.ContentProvider;
import android.content.ContentProviderOperation;
import android.content.ContentProviderResult;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.net.Uri;
import android.os.AsyncTask;
//import com.google.common.collect.Lists;
import java.util.ArrayList;
/**
* Simple utility class to make an asynchronous {@link ContentProvider} request expressed as
* a list of {@link ContentProviderOperation}s. As with all {@link AsyncTask}s, subclasses should
* override {@link #onPostExecute(Object)} to handle success/failure.
*
* @see InsertTask
* @see UpdateTask
* @see DeleteTask
*
*/
public class ContentProviderTask extends AsyncTask<Void, Void, ContentProviderTask.Result> {
private ContentResolver mResolver;
private String mAuthority;
private ArrayList<ContentProviderOperation> mOps;
private static final String LOG_TAG = LogTag.getLogTag();
public static class Result {
public final Exception exception;
public final ContentProviderResult[] results;
/**
* Create a new result.
* @param exception
* @param results
*/
private Result(Exception exception, ContentProviderResult[] results) {
this.exception = exception;
this.results = results;
}
/**
* Create a new success result.
* @param success
* @return
*/
private static Result newSuccess(ContentProviderResult[] success) {
return new Result(null, success);
}
/**
* Create a new failure result.
* @param failure
*/
private static Result newFailure(Exception failure) {
return new Result(failure, null);
}
}
@Override
protected Result doInBackground(Void... params) {
Result result;
try {
result = Result.newSuccess(mResolver.applyBatch(mAuthority, mOps));
} catch (Exception e) {
LogUtils.w(LOG_TAG, e, "exception executing ContentProviderOperationsTask");
result = Result.newFailure(e);
}
return result;
}
public void run(ContentResolver resolver, String authority,
ArrayList<ContentProviderOperation> ops) {
mResolver = resolver;
mAuthority = authority;
mOps = ops;
executeOnExecutor(THREAD_POOL_EXECUTOR, (Void) null);
}
public static class InsertTask extends ContentProviderTask {
public void run(ContentResolver resolver, Uri uri, ContentValues values) {
final ContentProviderOperation op = ContentProviderOperation
.newInsert(uri)
.withValues(values)
.build();
ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
ops.add(op);
super.run(resolver, uri.getAuthority(), ops);
}
}
public static class UpdateTask extends ContentProviderTask {
public void run(ContentResolver resolver, Uri uri, ContentValues values,
String selection, String[] selectionArgs) {
final ContentProviderOperation op = ContentProviderOperation
.newUpdate(uri)
.withValues(values)
.withSelection(selection, selectionArgs)
.build();
ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
ops.add(op);
super.run(resolver, uri.getAuthority(), ops);
}
}
public static class DeleteTask extends ContentProviderTask {
public void run(ContentResolver resolver, Uri uri, String selection,
String[] selectionArgs) {
final ContentProviderOperation op = ContentProviderOperation
.newDelete(uri)
.withSelection(selection, selectionArgs)
.build();
ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
ops.add(op);
super.run(resolver, uri.getAuthority(), ops);
}
}
}
| apache-2.0 |
ygorshenin/omim | routing/cross_mwm_connector.cpp | 448 | #include "routing/cross_mwm_connector.hpp"
namespace routing
{
namespace connector
{
std::string DebugPrint(WeightsLoadState state)
{
switch (state)
{
case WeightsLoadState::Unknown: return "Unknown";
case WeightsLoadState::ReadyToLoad: return "ReadyToLoad";
case WeightsLoadState::NotExists: return "NotExists";
case WeightsLoadState::Loaded: return "Loaded";
}
CHECK_SWITCH();
}
} // namespace connector
} // namespace routing
| apache-2.0 |
RotatingFans/govmomi | govc/flags/virtual_machine.go | 2625 | /*
Copyright (c) 2014-2015 VMware, Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package flags
import (
"flag"
"fmt"
"os"
"github.com/RotatingFans/govmomi/object"
"golang.org/x/net/context"
)
type VirtualMachineFlag struct {
common
*ClientFlag
*DatacenterFlag
*SearchFlag
name string
vm *object.VirtualMachine
}
var virtualMachineFlagKey = flagKey("virtualMachine")
func NewVirtualMachineFlag(ctx context.Context) (*VirtualMachineFlag, context.Context) {
if v := ctx.Value(virtualMachineFlagKey); v != nil {
return v.(*VirtualMachineFlag), ctx
}
v := &VirtualMachineFlag{}
v.ClientFlag, ctx = NewClientFlag(ctx)
v.DatacenterFlag, ctx = NewDatacenterFlag(ctx)
v.SearchFlag, ctx = NewSearchFlag(ctx, SearchVirtualMachines)
ctx = context.WithValue(ctx, virtualMachineFlagKey, v)
return v, ctx
}
func (flag *VirtualMachineFlag) Register(ctx context.Context, f *flag.FlagSet) {
flag.RegisterOnce(func() {
flag.ClientFlag.Register(ctx, f)
flag.DatacenterFlag.Register(ctx, f)
flag.SearchFlag.Register(ctx, f)
env := "GOVC_VM"
value := os.Getenv(env)
usage := fmt.Sprintf("Virtual machine [%s]", env)
f.StringVar(&flag.name, "vm", value, usage)
})
}
func (flag *VirtualMachineFlag) Process(ctx context.Context) error {
return flag.ProcessOnce(func() error {
if err := flag.ClientFlag.Process(ctx); err != nil {
return err
}
if err := flag.DatacenterFlag.Process(ctx); err != nil {
return err
}
if err := flag.SearchFlag.Process(ctx); err != nil {
return err
}
return nil
})
}
func (flag *VirtualMachineFlag) VirtualMachine() (*object.VirtualMachine, error) {
if flag.vm != nil {
return flag.vm, nil
}
// Use search flags if specified.
if flag.SearchFlag.IsSet() {
vm, err := flag.SearchFlag.VirtualMachine()
if err != nil {
return nil, err
}
flag.vm = vm
return flag.vm, nil
}
// Never look for a default virtual machine.
if flag.name == "" {
return nil, nil
}
finder, err := flag.Finder()
if err != nil {
return nil, err
}
flag.vm, err = finder.VirtualMachine(context.TODO(), flag.name)
return flag.vm, err
}
| apache-2.0 |
alien4cloud/alien4cloud | alien4cloud-rest-it/src/test/java/alien4cloud/it/topology/TopologyStepDefinitions.java | 39592 | package alien4cloud.it.topology;
import static alien4cloud.it.utils.TestUtils.getFullId;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.alien4cloud.tosca.catalog.CatalogVersionResult;
import org.alien4cloud.tosca.model.CSARDependency;
import org.alien4cloud.tosca.model.definitions.DeploymentArtifact;
import org.alien4cloud.tosca.model.templates.NodeGroup;
import org.alien4cloud.tosca.model.templates.NodeTemplate;
import org.alien4cloud.tosca.model.templates.RelationshipTemplate;
import org.alien4cloud.tosca.model.templates.ScalingPolicy;
import org.alien4cloud.tosca.model.types.AbstractInheritableToscaType;
import org.alien4cloud.tosca.model.types.AbstractToscaType;
import org.alien4cloud.tosca.model.types.CapabilityType;
import org.alien4cloud.tosca.model.types.NodeType;
import org.alien4cloud.tosca.model.types.RelationshipType;
import org.alien4cloud.tosca.utils.TopologyUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.elasticsearch.action.support.WriteRequest.RefreshPolicy;
import org.elasticsearch.client.Client;
import org.elasticsearch.common.xcontent.XContentType;
import com.google.common.collect.Maps;
import org.elasticsearch.mapping.FieldsMappingBuilder;
import org.elasticsearch.mapping.MappingBuilder;
import org.junit.Assert;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Sets;
import alien4cloud.dao.ElasticSearchDAO;
import alien4cloud.it.Context;
import alien4cloud.it.common.CommonStepDefinitions;
import alien4cloud.rest.model.RestResponse;
import alien4cloud.rest.utils.JsonUtil;
import alien4cloud.topology.TopologyDTO;
import alien4cloud.topology.TopologyValidationResult;
import alien4cloud.topology.task.AbstractTask;
import alien4cloud.topology.task.ArtifactTask;
import alien4cloud.topology.task.RequirementToSatisfy;
import alien4cloud.topology.task.TaskCode;
import alien4cloud.topology.task.TaskLevel;
import alien4cloud.tosca.properties.constraints.ConstraintUtil.ConstraintInformation;
import alien4cloud.utils.AlienConstants;
import alien4cloud.utils.MapUtil;
import alien4cloud.utils.PropertyUtil;
import cucumber.api.DataTable;
import cucumber.api.PendingException;
import cucumber.api.java.en.And;
import cucumber.api.java.en.Given;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class TopologyStepDefinitions {
private final static Map<String, Class<? extends AbstractToscaType>> WORDS_TO_CLASSES;
private final ObjectMapper jsonMapper = new ObjectMapper();
private final Client esClient = Context.getEsClientInstance();
private CommonStepDefinitions commonStepDefinitions = new CommonStepDefinitions();
static {
WORDS_TO_CLASSES = Maps.newHashMap();
WORDS_TO_CLASSES.put("node type", NodeType.class);
WORDS_TO_CLASSES.put("relationship type", RelationshipType.class);
WORDS_TO_CLASSES.put("node types", NodeType.class);
}
@When("^I retrieve the newly created topology$")
public void I_retrieve_the_newly_created_topology() throws Throwable {
// Topology from context
String topologyId = Context.getInstance().getTopologyId();
Context.getInstance().registerRestResponse(Context.getRestClientInstance().get("/rest/v1/topologies/" + topologyId));
}
@Then("^The RestResponse should contain a topology id$")
public void The_RestResponse_should_contain_an_id_string() throws Throwable {
String response = Context.getInstance().getRestResponse();
assertNotNull(response);
RestResponse<String> restResponse = JsonUtil.read(response, String.class);
assertNotNull(restResponse.getData());
assertFalse(restResponse.getData().isEmpty());
}
@When("^I try to retrieve it$")
public void I_try_to_retrieve_it() throws Throwable {
String topologyId = Context.getInstance().getTopologyId();
Context.getInstance().registerRestResponse(Context.getRestClientInstance().get("/rest/v1/topologies/" + topologyId));
}
@Then("^I get a topology by id \"([^\"]*)\"$")
public void I_get_a_topology_by_id(String topologyId) throws Throwable {
Context.getInstance().registerRestResponse(Context.getRestClientInstance().get("/rest/v1/topologies/" + topologyId));
}
@Then("^The RestResponse should contain a topology$")
public void The_RestResponse_should_contain_a_topology() throws Throwable {
String topologyResponseText = Context.getInstance().getRestResponse();
RestResponse<TopologyDTO> topologyResponse = JsonUtil.read(topologyResponseText, TopologyDTO.class, Context.getJsonMapper());
assertNotNull(topologyResponse.getData());
assertNotNull(topologyResponse.getData().getTopology().getId());
}
@Given("^There is a \"([^\"]*)\" with element name \"([^\"]*)\" and archive version \"([^\"]*)\"$")
public void There_is_a_with_element_name_and_archive_version(String elementType, String elementId, String archiveVersion) throws Throwable {
String componentId = getFullId(elementId, archiveVersion);
Context.getInstance().registerRestResponse(Context.getRestClientInstance().get("/rest/v1/components/" + componentId));
AbstractToscaType idnt = JsonUtil.read(Context.getInstance().takeRestResponse(), WORDS_TO_CLASSES.get(elementType), Context.getJsonMapper()).getData();
assertNotNull(idnt);
assertEquals(componentId, idnt.getId());
}
@Given("^There are properties for \"([^\"]*)\" element \"([^\"]*)\" and archive version \"([^\"]*)\"$")
public void There_are_properties_for_element_and_archive_version(String elementType, String elementId, String archiveVersion, DataTable properties)
throws Throwable {
String componentId = getFullId(elementId, archiveVersion);
Context.getInstance().registerRestResponse(Context.getRestClientInstance().get("/rest/v1/components/" + componentId));
AbstractToscaType idnt = JsonUtil.read(Context.getInstance().takeRestResponse(), WORDS_TO_CLASSES.get(elementType), Context.getJsonMapper()).getData();
assertNotNull(idnt);
assertEquals(componentId, idnt.getId());
}
private String getRelationShipName(String type, String target) {
String[] splitted = type.split("\\.");
String last = splitted[splitted.length - 1];
return last.trim() + "_" + target.trim();
}
@Then("^The RestResponse should not contain a nodetemplate named \"([^\"]*)\"")
public void The_RestResponse_should_not_contain_a_nodetemplate_named(String key) throws Throwable {
TopologyDTO topologyDTO = JsonUtil.read(Context.getInstance().getRestResponse(), TopologyDTO.class, Context.getJsonMapper()).getData();
assertNotNull(topologyDTO);
assertNotNull(topologyDTO.getTopology());
assertTrue(topologyDTO.getTopology().getNodeTemplates() == null || topologyDTO.getTopology().getNodeTemplates().get(key) == null);
}
@Then("The RestResponse should not contain a relationship of type \"([^\"]*)\" with source \"([^\"]*)\" and target \"([^\"]*)\"")
public void The_RestResponse_should_not_contain_a_relationship_of_type_with_source_and_target(String type, String source, String target) throws Throwable {
TopologyDTO topologyDTO = JsonUtil.read(Context.getInstance().getRestResponse(), TopologyDTO.class, Context.getJsonMapper()).getData();
assertNotNull(topologyDTO);
assertNotNull(topologyDTO.getTopology());
assertNotNull(topologyDTO.getTopology().getNodeTemplates());
assertNotNull(topologyDTO.getTopology().getNodeTemplates().get(source));
assertNotNull(topologyDTO.getTopology().getNodeTemplates().get(source).getRelationships() == null
|| topologyDTO.getTopology().getNodeTemplates().get(source).getRelationships().get(getRelationShipName(type, target)) == null);
}
@Then("^The RestResponse should contain a nodetemplate named \"([^\"]*)\" and type \"([^\"]*)\"")
public void The_RestResponse_should_contain_a_nodetemplate_named_and_type(String key, String type) throws Throwable {
TopologyDTO topologyDTO = JsonUtil.read(Context.getInstance().getRestResponse(), TopologyDTO.class, Context.getJsonMapper()).getData();
assertNotNull(topologyDTO);
assertNotNull(topologyDTO.getTopology());
assertNotNull(topologyDTO.getTopology().getNodeTemplates());
assertEquals(type, topologyDTO.getTopology().getNodeTemplates().get(key).getType());
}
@Then("^The RestResponse should contain a node type with \"([^\"]*)\" id$")
public void The_RestResponse_should_contain_a_node_type_with_id(String expectedId) throws Throwable {
TopologyDTO topologyDTO = JsonUtil.read(Context.getInstance().getRestResponse(), TopologyDTO.class, Context.getJsonMapper()).getData();
assertNotNull(topologyDTO);
assertNotNull(topologyDTO.getNodeTypes());
assertNotNull(topologyDTO.getNodeTypes().get(expectedId.split(":")[0]));
assertEquals(expectedId, topologyDTO.getNodeTypes().get(expectedId.split(":")[0]).getId());
}
@When("^I try to retrieve the created topology$")
public void I_try_to_retrieve_the_created_topology() throws Throwable {
Context.getInstance().registerRestResponse(Context.getRestClientInstance().get("/rest/v1/topologies/" + Context.getInstance().getTopologyId()));
}
@Then("^The topology should contain a nodetemplate named \"([^\"]*)\"$")
public void The_topology_should_contain_a_nodetemplate_named(String name) throws Throwable {
String topologyResponseText = Context.getInstance().getRestResponse();
RestResponse<TopologyDTO> topologyResponse = JsonUtil.read(topologyResponseText, TopologyDTO.class, Context.getJsonMapper());
assertNotNull(topologyResponse.getData());
Map<String, NodeTemplate> nodeTemplates = topologyResponse.getData().getTopology().getNodeTemplates();
assertNotNull(nodeTemplates);
assertNotNull(nodeTemplates.get(name));
}
@Then("^The topology should contain a nodetemplate named \"([^\"]*)\" with property \"([^\"]*)\" set to \"([^\"]*)\"$")
public void The_topology_should_contain_a_nodetemplate_named_with_property_set_to(String nodeTemplateName, String propertyName, String propertyValue)
throws Throwable {
The_topology_should_contain_a_nodetemplate_named(nodeTemplateName);
String topologyResponseText = Context.getInstance().getRestResponse();
NodeTemplate nodeTemp = JsonUtil.read(topologyResponseText, TopologyDTO.class, Context.getJsonMapper()).getData().getTopology().getNodeTemplates()
.get(nodeTemplateName);
assertNotNull(nodeTemp.getProperties());
if (propertyValue != null) {
assertNotNull(nodeTemp.getProperties().get(propertyName));
}
assertEquals(propertyValue, PropertyUtil.getScalarValue(nodeTemp.getProperties().get(propertyName)));
}
@Then("^The topology should contain a nodetemplate named \"([^\"]*)\" with property \"([^\"]*)\" set to null$")
public void The_topology_should_contain_a_nodetemplate_named_with_property_set_to_null(String nodeTemplateName, String propertyName) throws Throwable {
The_topology_should_contain_a_nodetemplate_named_with_property_set_to(nodeTemplateName, propertyName, null);
}
@And("^The topology should contain a nodetemplate named \"([^\"]*)\" with property \"([^\"]*)\" of capability \"([^\"]*)\" set to \"([^\"]*)\"$")
public void theTopologyShouldContainANodetemplateNamedWithPropertyOfCapabilitySetToNull(String nodeTemplateName, String propertyName, String capabilityName, String propertyValue) throws Throwable {
The_topology_should_contain_a_nodetemplate_named(nodeTemplateName);
String topologyResponseText = Context.getInstance().getRestResponse();
NodeTemplate nodeTemp = JsonUtil.read(topologyResponseText, TopologyDTO.class, Context.getJsonMapper()).getData().getTopology().getNodeTemplates()
.get(nodeTemplateName);
assertNotNull(nodeTemp.getCapabilities().get(capabilityName).getProperties());
if (propertyValue != null) {
assertNotNull(nodeTemp.getCapabilities().get(capabilityName).getProperties().get(propertyName));
}
assertEquals(propertyValue, PropertyUtil.getScalarValue(nodeTemp.getCapabilities().get(capabilityName).getProperties().get(propertyName)));
}
@And("^The topology should contain a nodetemplate named \"([^\"]*)\" with property \"([^\"]*)\" of capability \"([^\"]*)\" set to null$")
public void theTopologyShouldContainANodetemplateNamedWithPropertyOfCapabilitySetToNull(String nodeTemplateName, String propertyName, String capabilityName) throws Throwable {
theTopologyShouldContainANodetemplateNamedWithPropertyOfCapabilitySetToNull(nodeTemplateName, propertyName, capabilityName, null);
}
@Then("^I should have a relationship with type \"([^\"]*)\" from \"([^\"]*)\" to \"([^\"]*)\" in ALIEN$")
public void I_should_have_a_relationship_with_type_from_to_in_ALIEN(String relType, String source, String target) throws Throwable {
I_should_have_a_relationship_with_type_from_to_in_ALIEN(null, relType, source, target);
}
@Then("^I should have a relationship \"([^\"]*)\" with type \"([^\"]*)\" from \"([^\"]*)\" to \"([^\"]*)\" in ALIEN$")
public void I_should_have_a_relationship_with_type_from_to_in_ALIEN(String relName, String relType, String source, String target) throws Throwable {
// I should have a relationship with type
String topologyJson = Context.getRestClientInstance().get("/rest/v1/topologies/" + Context.getInstance().getTopologyId());
RestResponse<TopologyDTO> topologyResponse = JsonUtil.read(topologyJson, TopologyDTO.class, Context.getJsonMapper());
NodeTemplate sourceNode = topologyResponse.getData().getTopology().getNodeTemplates().get(source);
relName = relName == null || relName.isEmpty() ? getRelationShipName(relType, target) : relName;
RelationshipTemplate rel = sourceNode.getRelationships().get(relName);
assertNotNull(rel);
assertEquals(relType, rel.getType());
assertEquals(target, rel.getTarget());
assertNotNull(rel.getRequirementName());
assertNotNull(rel.getRequirementType());
}
@Then("^I should have (\\d+) relationship with source \"([^\"]*)\" and target \"([^\"]*)\" for type \"([^\"]*)\" with requirement \"([^\"]*)\" of type \"([^\"]*)\"$")
public void I_should_have_relationship_with_source_for_requirement_of_type(int relationshipCount, String source, String target, String relType,
String requirementName, String requirementType) throws Throwable {
String topologyJson = Context.getRestClientInstance().get("/rest/v1/topologies/" + Context.getInstance().getTopologyId());
RestResponse<TopologyDTO> topologyResponse = JsonUtil.read(topologyJson, TopologyDTO.class, Context.getJsonMapper());
NodeTemplate sourceNode = topologyResponse.getData().getTopology().getNodeTemplates().get(source);
RelationshipTemplate rel = sourceNode.getRelationships().get(getRelationShipName(relType, target));
assertNotNull(rel);
// Only one relationship of this type for the moment : cardinality check soon
assertEquals(rel.getRequirementName(), requirementName);
assertEquals(rel.getRequirementType(), requirementType);
}
@Then("^I should receive a RestResponse with constraint data name \"([^\"]*)\" and reference \"([^\"]*)\"$")
public void I_should_receive_a_RestResponse_with_constraint_data_name_and_reference(String name, String reference) throws Throwable {
RestResponse<?> restResponse = JsonUtil.read(Context.getInstance().getRestResponse(), Context.getJsonMapper());
Assert.assertNotNull(restResponse.getData());
ConstraintInformation constraint = JsonUtil.readObject(JsonUtil.toString(restResponse.getData()), ConstraintInformation.class);
assertEquals(constraint.getName().toString(), name);
assertEquals(constraint.getReference().toString(), reference);
}
@Given("^there are these types with element names and archive version$")
public void there_are_these_types_with_element_names_and_archive_version(DataTable elements) throws Throwable {
for (List<String> element : elements.raw()) {
There_is_a_with_element_name_and_archive_version(element.get(0), element.get(1), element.get(2));
}
}
@When("^I check for the valid status of the topology$")
public void I_check_for_the_valid_status_of_the_topology() throws Throwable {
String topologyId = Context.getInstance().getTopologyId();
Context.getInstance().registerRestResponse(Context.getRestClientInstance().get("/rest/v1/topologies/" + topologyId + "/isvalid?environmentId="
+ Context.getInstance().getDefaultApplicationEnvironmentId(Context.getInstance().getApplication().getName())));
}
@When("^I check for the valid status of the topology on the default environment$")
public void I_check_for_the_valid_status_of_the_topology_on_the_default_environment() throws Throwable {
String topologyId = Context.getInstance().getTopologyId();
Context.getInstance().registerRestResponse(Context.getRestClientInstance().get("/rest/v1/topologies/" + topologyId + "/isvalid?environmentId="
+ Context.getInstance().getDefaultApplicationEnvironmentId(Context.getInstance().getApplication().getName())));
}
@Then("^the topology should be valid$")
public void the_topology_should_be_valid() throws Throwable {
RestResponse<?> restResponse = JsonUtil.read(Context.getInstance().getRestResponse(), Context.getJsonMapper());
assertNotNull(restResponse.getData());
Map<String, Object> dataMap = JsonUtil.toMap(JsonUtil.toString(restResponse.getData()));
assertTrue(Boolean.valueOf(dataMap.get("valid").toString()));
}
@Then("^the topology should not be valid$")
public void the_topology_should_not_be_valid() throws Throwable {
RestResponse<?> restResponse = JsonUtil.read(Context.getInstance().getRestResponse(), Context.getJsonMapper());
assertNotNull(restResponse.getData());
Map<String, Object> dataMap = JsonUtil.toMap(JsonUtil.toString(restResponse.getData()));
assertFalse(Boolean.valueOf(dataMap.get("valid").toString()));
}
@Given("^i create a nodetype \"([^\"]*)\" in an archive name \"([^\"]*)\" version \"([^\"]*)\" with properties$")
public void i_create_a_nodetype_in_an_archive_name_version_with_properties(String elementId, String arhiveName, String archiveVersion, DataTable properties)
throws Throwable {
throw new PendingException();
}
@Given("^i create a relationshiptype \"([^\"]*)\" in an archive name \"([^\"]*)\" version \"([^\"]*)\" with properties$")
public void i_create_a_relationshiptype_in_an_archive_name_version_with_properties(String elementId, String archiveName, String archiveVersion,
DataTable properties) throws Throwable {
RelationshipType relationship = new RelationshipType();
relationship.setArchiveName(archiveName);
relationship.setArchiveVersion(archiveVersion);
relationship.setElementId(elementId);
relationship.setWorkspace(AlienConstants.GLOBAL_WORKSPACE_ID);
for (List<String> propertyObject : properties.raw()) {
if (propertyObject.get(0).equals("validSource")) {
relationship.setValidSources(propertyObject.get(1).split(","));
} else if (propertyObject.get(0).equals("validTarget")) {
relationship.setValidTargets(propertyObject.get(1).split(","));
} else if (propertyObject.get(0).equals("abstract")) {
relationship.setAbstract(Boolean.valueOf(propertyObject.get(1)));
}
}
String idValue = null;
try {
idValue = (new FieldsMappingBuilder()).getIdValue(relationship);
} catch (Exception e) {}
//esClient.prepareIndex(ElasticSearchDAO.TOSCA_ELEMENT_INDEX, MappingBuilder.indexTypeFromClass(RelationshipType.class), idValue)
esClient.prepareIndex(MappingBuilder.indexTypeFromClass(RelationshipType.class), "_doc", idValue)
.setSource(JsonUtil.toString(relationship), XContentType.JSON).setRefreshPolicy(RefreshPolicy.IMMEDIATE).execute().actionGet();
}
@Given("^I create a \"([^\"]*)\" \"([^\"]*)\" in an archive name \"([^\"]*)\" version \"([^\"]*)\"$")
public void I_create_a_in_an_archive_name_version(String componentType, String elementId, String archiveName, String archiveVersion) throws Throwable {
AbstractInheritableToscaType element = new AbstractInheritableToscaType();
element.setAbstract(false);
element.setElementId(elementId);
element.setArchiveName(archiveName);
element.setArchiveVersion(archiveVersion);
element.setWorkspace(AlienConstants.GLOBAL_WORKSPACE_ID);
Class<?> clazz = null;
if (componentType.equals("capability") || componentType.equals("capabilities")) {
clazz = CapabilityType.class;
} else {
throw new PendingException("creation of Type " + componentType + "not supported!");
}
String idValue = null;
try {
idValue = (new FieldsMappingBuilder()).getIdValue(element);
} catch (Exception e) {}
//esClient.prepareIndex(ElasticSearchDAO.TOSCA_ELEMENT_INDEX, MappingBuilder.indexTypeFromClass(clazz), idValue)
esClient.prepareIndex(MappingBuilder.indexTypeFromClass(clazz), "_doc", idValue)
.setSource(JsonUtil.toString(element), XContentType.JSON)
.setRefreshPolicy(RefreshPolicy.IMMEDIATE).execute().actionGet();
}
@Given("^I create \"([^\"]*)\" in an archive name \"([^\"]*)\" version \"([^\"]*)\"$")
public void I_create_in_an_archive_name_version(String componentType, String archiveName, String archiveVersion, List<String> elementIds) throws Throwable {
for (String elementId : elementIds) {
I_create_a_in_an_archive_name_version(componentType, elementId, archiveName, archiveVersion);
}
}
@Then("^there should not be suggested nodetypes for the \"([^\"]*)\" node template$")
public void there_should_not_be_suggested_nodetypes_for_the_node_template(String nodeTemplateName) throws Throwable {
RestResponse<Map> restResponse = JsonUtil.read(Context.getInstance().getRestResponse(), Map.class, Context.getJsonMapper());
assertNotNull(restResponse.getData());
String dataString = JsonUtil.toString(restResponse.getData());
Map<String, Object> validationDTOMap = JsonUtil.toMap(dataString);
Object tasklist = MapUtil.get(validationDTOMap, "taskList");
assertNotNull(tasklist);
assertNull(getSuggestedNodesFor(nodeTemplateName, tasklist));
}
private NodeType[] getSuggestedNodesFor(String nodeTemplateName, Object taskList) throws IOException {
for (Map<String, Object> task : (List<Map<String, Object>>) taskList) {
String nodeTemp = (String) MapUtil.get(task, "nodeTemplateName");
List<Object> suggestedNodeTypes = (List<Object>) MapUtil.get(task, "suggestedNodeTypes");
if (nodeTemp.equals(nodeTemplateName) && suggestedNodeTypes != null) {
return JsonUtil.toArray(Context.getInstance().getJsonMapper().writeValueAsString(suggestedNodeTypes), NodeType.class, Context.getJsonMapper());
}
}
return null;
}
@Then("^the suggested nodes types for the abstracts nodes templates should be:$")
public void the_suggested_nodes_types_for_the_abstracts_nodes_templates_should_be(DataTable expectedSuggestedElemntIds) throws Throwable {
RestResponse<Map> restResponse = JsonUtil.read(Context.getInstance().getRestResponse(), Map.class, Context.getJsonMapper());
assertNotNull(restResponse.getData());
String dataString = JsonUtil.toString(restResponse.getData());
Map<String, Object> validationDTOMap = JsonUtil.toMap(dataString);
Object tasklist = MapUtil.get(validationDTOMap, "taskList");
assertNotNull(tasklist);
for (List<String> expected : expectedSuggestedElemntIds.raw()) {
String[] expectedElementIds = expected.get(1).split(",");
NodeType[] indexedNodeTypes = getSuggestedNodesFor(expected.get(0), tasklist);
assertNotNull(indexedNodeTypes);
String[] suggestedElementIds = getElementsId(indexedNodeTypes);
assertNotNull(suggestedElementIds);
assertEquals(expectedElementIds.length, suggestedElementIds.length);
Arrays.sort(expectedElementIds);
Arrays.sort(suggestedElementIds);
assertArrayEquals(expectedElementIds, suggestedElementIds);
}
}
private static final String ARTIFACT_PATH = "./src/test/resources/data/artifacts/";
@When("^I update the application's input artifact \"([^\"]*)\" with \"([^\"]*)\"$")
public void I_update_the_application_s_input_artifact_with(String artifactId, String artifactName) throws Throwable {
String topologyId = Context.getInstance().getTopologyId();
String url = "/rest/v1/topologies/" + topologyId + "/inputArtifacts/" + artifactId + "/upload";
InputStream artifactStream = Files.newInputStream(Paths.get(ARTIFACT_PATH, artifactName));
Context.getInstance().registerRestResponse(Context.getRestClientInstance().postMultipart(url, artifactName, artifactStream));
}
@Then("^The topology should contain a nodetemplate named \"([^\"]*)\" with an artifact \"([^\"]*)\" with the specified UID and name \"([^\"]*)\"$")
public void The_topology_should_contain_a_nodetemplate_named_with_an_artifact_with_the_specified_UID(String nodeTemplateName, String artifactId,
String artifactName) throws Throwable {
The_topology_should_contain_a_nodetemplate_named(nodeTemplateName);
String topologyResponseText = Context.getInstance().getRestResponse();
NodeTemplate nodeTemp = JsonUtil.read(topologyResponseText, TopologyDTO.class, Context.getJsonMapper()).getData().getTopology().getNodeTemplates()
.get(nodeTemplateName);
Assert.assertNotNull(nodeTemp.getArtifacts());
Assert.assertFalse(nodeTemp.getArtifacts().isEmpty());
DeploymentArtifact deploymentArtifact = nodeTemp.getArtifacts().get(artifactId);
Assert.assertNotNull(deploymentArtifact);
Assert.assertNotNull(deploymentArtifact.getArtifactType());
Assert.assertEquals(artifactName, deploymentArtifact.getArtifactName());
}
@Then("^the node with requirements lowerbound not satisfied should be$")
public void the_node_with_requirements_lowerbound_not_satisfied_should_be(DataTable expectedRequirementsNames) throws Throwable {
RestResponse<Map> restResponse = JsonUtil.read(Context.getInstance().getRestResponse(), Map.class, Context.getJsonMapper());
assertNotNull(restResponse.getData());
String dataString = JsonUtil.toString(restResponse.getData());
Map<String, Object> validationDTOMap = JsonUtil.toMap(dataString);
Object tasklist = MapUtil.get(validationDTOMap, "taskList");
assertNotNull(tasklist);
for (List<String> expected : expectedRequirementsNames.raw()) {
String[] expectedNames = expected.get(1).split(",");
List<RequirementToSatisfy> requirementsToSatify = getRequirementsToSatisfy(expected.get(0), tasklist);
String[] requirementsNames = getRequirementsNames(requirementsToSatify.toArray(new RequirementToSatisfy[requirementsToSatify.size()]));
assertNotNull(requirementsNames);
assertEquals(expectedNames.length, requirementsNames.length);
Arrays.sort(expectedNames);
Arrays.sort(requirementsNames);
assertArrayEquals(expectedNames, requirementsNames);
}
}
private List<RequirementToSatisfy> getRequirementsToSatisfy(String nodeTemplateName, Object taskList) throws IOException {
for (Map<String, Object> task : (List<Map<String, Object>>) taskList) {
String nodeTemp = (String) MapUtil.get(task, "nodeTemplateName");
List<Object> resToImp = (List<Object>) MapUtil.get(task, "requirementsToImplement");
if (nodeTemp.equals(nodeTemplateName) && resToImp != null) {
return JsonUtil.toList(JsonUtil.toString(resToImp), RequirementToSatisfy.class, Context.getJsonMapper());
}
}
return null;
}
public String[] getElementsId(NodeType... indexedNodeTypes) {
String[] toReturn = null;
for (NodeType indexedNodeType : indexedNodeTypes) {
toReturn = ArrayUtils.add(toReturn, indexedNodeType.getElementId());
}
return toReturn;
}
public String[] getRequirementsNames(RequirementToSatisfy... requirementsToSatisfy) {
String[] toReturn = null;
for (RequirementToSatisfy requirementToSatisfy : requirementsToSatisfy) {
toReturn = ArrayUtils.add(toReturn, requirementToSatisfy.getName());
}
return toReturn;
}
@SuppressWarnings("unchecked")
private List<String> getRequiredPropertiesNotSet(String nodeTemplateName, Object taskList) throws IOException {
for (Map<String, Object> task : (List<Map<String, Object>>) taskList) {
String nodeTemp = (String) MapUtil.get(task, "nodeTemplateName");
Map<TaskLevel, List<String>> resToImp = (Map<TaskLevel, List<String>>) MapUtil.get(task, "properties");
if (nodeTemp.equals(nodeTemplateName) && resToImp != null) {
return JsonUtil.toList(JsonUtil.toString(resToImp.get(TaskLevel.REQUIRED.toString())), String.class);
}
}
return null;
}
@Then("^the scaling policy of the node \"([^\"]*)\" should match max instances equals to (\\d+), initial instances equals to (\\d+) and min instances equals to (\\d+)$")
public void the_scaling_policy_of_the_node_should_match_max_instances_equals_to_initial_instances_equals_to_and_min_instances_equals_to(String nodeName,
int maxInstances, int initialInstances, int minInstances) throws Throwable {
I_try_to_retrieve_the_created_topology();
String topologyResponseText = Context.getInstance().getRestResponse();
RestResponse<TopologyDTO> topologyResponse = JsonUtil.read(topologyResponseText, TopologyDTO.class, Context.getJsonMapper());
assertNotNull(topologyResponse.getData());
ScalingPolicy computePolicy = TopologyUtils
.getScalingPolicy(TopologyUtils.getScalableCapability(topologyResponse.getData().getTopology(), nodeName, true));
assertNotNull(computePolicy);
assertEquals(maxInstances, computePolicy.getMaxInstances());
assertEquals(minInstances, computePolicy.getMinInstances());
assertEquals(initialInstances, computePolicy.getInitialInstances());
}
@Then("^There's no defined scaling policy for the node \"([^\"]*)\"$")
public void There_s_no_defined_scaling_policy(String nodeName) throws Throwable {
I_try_to_retrieve_the_created_topology();
String topologyResponseText = Context.getInstance().getRestResponse();
RestResponse<TopologyDTO> topologyResponse = JsonUtil.read(topologyResponseText, TopologyDTO.class, Context.getJsonMapper());
assertNotNull(topologyResponse.getData());
ScalingPolicy computePolicy = TopologyUtils
.getScalingPolicy(TopologyUtils.getScalableCapability(topologyResponse.getData().getTopology(), nodeName, true));
assertEquals(ScalingPolicy.NOT_SCALABLE_POLICY, computePolicy);
}
@Then("^the node with required properties not set should be$")
public void the_node_with_required_properties_not_set_should_be(DataTable expectedRequiredProperties) throws Throwable {
RestResponse<Map> restResponse = JsonUtil.read(Context.getInstance().getRestResponse(), Map.class, Context.getJsonMapper());
assertNotNull(restResponse.getData());
String dataString = JsonUtil.toString(restResponse.getData());
Map<String, Object> validationDTOMap = JsonUtil.toMap(dataString);
Object tasklist = MapUtil.get(validationDTOMap, "taskList");
assertNotNull(tasklist);
for (List<String> expected : expectedRequiredProperties.raw()) {
String[] expectedProperties = expected.get(1).split(",");
List<String> requiredPropertiesNotSet = getRequiredPropertiesNotSet(expected.get(0), tasklist);
assertNotNull(requiredPropertiesNotSet);
String[] requiredProperties = requiredPropertiesNotSet.toArray(new String[requiredPropertiesNotSet.size()]);
assertNotNull(requiredProperties);
assertEquals(expectedProperties.length, requiredProperties.length);
Arrays.sort(expectedProperties);
Arrays.sort(requiredProperties);
assertArrayEquals(expectedProperties, requiredProperties);
}
}
@And("^The topology should have as dependencies$")
public void The_topology_should_have_as_dependencies(DataTable dependencies) throws Throwable {
Set<CSARDependency> expectedDependencies = Sets.newHashSet();
for (List<String> row : dependencies.raw()) {
expectedDependencies.add(new CSARDependency(row.get(0), row.get(1)));
}
String topologyResponseText = Context.getInstance().getRestResponse();
Set<CSARDependency> actualDependencies = JsonUtil.read(topologyResponseText, TopologyDTO.class, Context.getJsonMapper()).getData().getTopology()
.getDependencies();
Assert.assertEquals(expectedDependencies, actualDependencies);
}
@And("^The RestResponse should contain a group named \"([^\"]*)\" whose members are \"([^\"]*)\" and policy is \"([^\"]*)\"$")
public void The_RestResponse_should_contain_a_group_named_whose_members_are_and_policy_is(String groupName, String members, String policy)
throws Throwable {
String topologyResponseText = Context.getInstance().getRestResponse();
RestResponse<TopologyDTO> topologyResponse = JsonUtil.read(topologyResponseText, TopologyDTO.class, Context.getJsonMapper());
Assert.assertNotNull(topologyResponse.getData().getTopology().getGroups());
NodeGroup nodeGroup = topologyResponse.getData().getTopology().getGroups().get(groupName);
Set<String> expectedMembers = Sets.newHashSet(members.split(","));
Assert.assertNotNull(nodeGroup);
Assert.assertEquals(nodeGroup.getMembers(), expectedMembers);
Assert.assertEquals(nodeGroup.getPolicies().iterator().next().getType(), policy);
for (String expectedMember : expectedMembers) {
NodeTemplate nodeTemplate = topologyResponse.getData().getTopology().getNodeTemplates().get(expectedMember);
Assert.assertNotNull(nodeTemplate);
Assert.assertTrue(nodeTemplate.getGroups().contains(groupName));
}
}
@Then("^The RestResponse should not contain any group$")
public void The_RestResponse_should_not_contain_any_group() throws Throwable {
String topologyResponseText = Context.getInstance().getRestResponse();
RestResponse<TopologyDTO> topologyResponse = JsonUtil.read(topologyResponseText, TopologyDTO.class, Context.getJsonMapper());
Map<String, NodeGroup> groups = topologyResponse.getData().getTopology().getGroups();
Assert.assertTrue(groups == null || groups.isEmpty());
}
@And("^The topology should have scalability policy error concerning \"([^\"]*)\"$")
public void The_topology_should_have_scalability_policy_error_concerning(String scalabilityProperty) throws Throwable {
RestResponse<Map> restResponse = JsonUtil.read(Context.getInstance().getRestResponse(), Map.class, Context.getJsonMapper());
assertNotNull(restResponse.getData());
List<Map<String, Object>> taskList = (List<Map<String, Object>>) restResponse.getData().get("taskList");
assertNotNull(taskList);
assertFalse(taskList.isEmpty());
for (Map<String, Object> task : taskList) {
if (task.get("code").equals(TaskCode.SCALABLE_CAPABILITY_INVALID.toString())) {
((List<String>) ((Map<String, Object>) task.get("properties")).get(TaskLevel.ERROR.toString())).contains(scalabilityProperty);
}
}
}
private boolean missingArtifactsContain(List<AbstractTask> taskList, String nodeName, String artifactName) {
for (AbstractTask task : taskList) {
if (task instanceof ArtifactTask) {
ArtifactTask artifactTask = (ArtifactTask) task;
if (artifactTask.getArtifactName().equals(artifactName) && artifactTask.getNodeTemplateName().equals(nodeName)) {
return true;
}
}
}
return false;
}
@And("^the nodes with missing artifacts should be$")
public void theNodesWithMissingArtifactsShouldBe(DataTable expectedMissingArtifacts) throws Throwable {
RestResponse<TopologyValidationResult> restResponse = JsonUtil.read(Context.getInstance().getRestResponse(), TopologyValidationResult.class,
Context.getJsonMapper());
assertNotNull(restResponse.getData());
List<AbstractTask> taskList = restResponse.getData().getTaskList();
for (List<String> expected : expectedMissingArtifacts.raw()) {
assertTrue("Task list does not contain [" + expected.get(0) + " , " + expected.get(1) + "]",
missingArtifactsContain(taskList, expected.get(0), expected.get(1)));
}
}
@And("^The registered topology should not exist$")
public void theRegisteredTopologyShouldNotExist() throws Throwable {
Context.getInstance().registerRestResponse(Context.getRestClientInstance().get("/rest/v1/catalog/topologies/" + Context.getInstance().getTopologyId()));
commonStepDefinitions.I_should_receive_a_RestResponse_with_an_error_code(504);
}
@Then("^the topology named \"([^\"]*)\" should have (\\d+) versions$")
public void theTopologyNamedShouldHaveVersions(String name, int expectedVersionCount) throws Throwable {
String responseString = Context.getRestClientInstance().get("/rest/v1/catalog/topologies/" + name + "/versions");
RestResponse<?> response = JsonUtil.read(responseString);
List<CatalogVersionResult> versionResults = JsonUtil.toList(JsonUtil.toString(response.getData()), CatalogVersionResult.class);
assertEquals(expectedVersionCount, versionResults.size());
}
}
| apache-2.0 |
java110/MicroCommunity | java110-bean/src/main/java/com/java110/dto/msg/SmsDto.java | 997 | package com.java110.dto.msg;
import com.java110.dto.PageDto;
import java.io.Serializable;
import java.util.Date;
/**
* @ClassName FloorDto
* @Description 消息数据层封装
* @Author wuxw
* @Date 2019/4/24 8:52
* @Version 1.0
* add by wuxw 2019/4/24
**/
public class SmsDto extends PageDto implements Serializable {
private String tel;
private String code;
private boolean success; //true 成功 false 失败
private String msg; //原因
public String getTel() {
return tel;
}
public void setTel(String tel) {
this.tel = tel;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public boolean isSuccess() {
return success;
}
public void setSuccess(boolean success) {
this.success = success;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
}
| apache-2.0 |
mogoweb/365browser | app/src/main/java/org/chromium/device/mojom/NfcRecordTypeFilter.java | 3567 |
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// This file is autogenerated by:
// mojo/public/tools/bindings/mojom_bindings_generator.py
// For:
// services/device/public/interfaces/nfc.mojom
//
package org.chromium.device.mojom;
import org.chromium.base.annotations.SuppressFBWarnings;
import org.chromium.mojo.bindings.DeserializationException;
public final class NfcRecordTypeFilter extends org.chromium.mojo.bindings.Struct {
private static final int STRUCT_SIZE = 16;
private static final org.chromium.mojo.bindings.DataHeader[] VERSION_ARRAY = new org.chromium.mojo.bindings.DataHeader[] {new org.chromium.mojo.bindings.DataHeader(16, 0)};
private static final org.chromium.mojo.bindings.DataHeader DEFAULT_STRUCT_INFO = VERSION_ARRAY[0];
public int recordType;
private NfcRecordTypeFilter(int version) {
super(STRUCT_SIZE, version);
}
public NfcRecordTypeFilter() {
this(0);
}
public static NfcRecordTypeFilter deserialize(org.chromium.mojo.bindings.Message message) {
return decode(new org.chromium.mojo.bindings.Decoder(message));
}
/**
* Similar to the method above, but deserializes from a |ByteBuffer| instance.
*
* @throws org.chromium.mojo.bindings.DeserializationException on deserialization failure.
*/
public static NfcRecordTypeFilter deserialize(java.nio.ByteBuffer data) {
if (data == null)
return null;
return deserialize(new org.chromium.mojo.bindings.Message(
data, new java.util.ArrayList<org.chromium.mojo.system.Handle>()));
}
@SuppressWarnings("unchecked")
public static NfcRecordTypeFilter decode(org.chromium.mojo.bindings.Decoder decoder0) {
if (decoder0 == null) {
return null;
}
decoder0.increaseStackDepth();
NfcRecordTypeFilter result;
try {
org.chromium.mojo.bindings.DataHeader mainDataHeader = decoder0.readAndValidateDataHeader(VERSION_ARRAY);
result = new NfcRecordTypeFilter(mainDataHeader.elementsOrVersion);
if (mainDataHeader.elementsOrVersion >= 0) {
result.recordType = decoder0.readInt(8);
NfcRecordType.validate(result.recordType);
}
} finally {
decoder0.decreaseStackDepth();
}
return result;
}
@SuppressWarnings("unchecked")
@Override
protected final void encode(org.chromium.mojo.bindings.Encoder encoder) {
org.chromium.mojo.bindings.Encoder encoder0 = encoder.getEncoderAtDataOffset(DEFAULT_STRUCT_INFO);
encoder0.encode(recordType, 8);
}
/**
* @see Object#equals(Object)
*/
@Override
public boolean equals(Object object) {
if (object == this)
return true;
if (object == null)
return false;
if (getClass() != object.getClass())
return false;
NfcRecordTypeFilter other = (NfcRecordTypeFilter) object;
if (this.recordType!= other.recordType)
return false;
return true;
}
/**
* @see Object#hashCode()
*/
@Override
public int hashCode() {
final int prime = 31;
int result = prime + getClass().hashCode();
result = prime * result + org.chromium.mojo.bindings.BindingsHelper.hashCode(recordType);
return result;
}
} | apache-2.0 |
shalinmangar/solr-jmh-tests | src/main/java/DataGen.java | 2241 | import org.noggit.CharArr;
import org.noggit.JSONWriter;
import java.io.*;
import java.net.URL;
import java.nio.charset.Charset;
public class DataGen {
public static void main(String[] args) throws IOException {
if (args.length < 1) {
System.err.println("Usage: java -cp ./target/benchmarks.jar DataGen </path/to/write/json/file> [size_of_document_mb=10MB]");
System.exit(1);
}
File path = new File(args[0]);
if (!path.getParentFile().exists()) {
System.err.println("Parent directory of path: " + args[0] + " does not exist.");
System.exit(1);
}
if (!path.getParentFile().canWrite()) {
System.err.println("Specified path: " + args[0] + " is not writable.");
System.exit(1);
}
long targetSize = 10 * 1024L * 1024L; // 10 MB
if (args.length > 1) {
targetSize = Long.parseLong(args[1]) * 1024L * 1024L;
}
URL url = new URL("http://www.gutenberg.org/ebooks/1322.txt.utf-8");
System.out.println("Making request to: " + url.toString());
try (InputStream in = url.openStream()) {
BufferedReader reader = new BufferedReader(new InputStreamReader(in, Charset.forName("UTF-8")));
CharArr out = new CharArr();
JSONWriter jsonWriter = new JSONWriter(out);
jsonWriter.startArray();
jsonWriter.startObject();
jsonWriter.writeString("content");
jsonWriter.writeNameSeparator();
char[] scratch = new char[1 << 15];
int len = 0, count = 0;
CharArr tmp = new CharArr(1 << 15);
while ((len = reader.read(scratch)) != -1) {
tmp.write(scratch, 0, len);
count += len;
}
jsonWriter.writeStringStart();
for (int i = 0; i < targetSize / count; i++) {
jsonWriter.writeStringChars(tmp);
}
jsonWriter.writeStringEnd();
jsonWriter.endObject();
jsonWriter.endArray();
try (FileWriter writer = new FileWriter(args[0])) {
writer.append(out);
}
}
}
}
| apache-2.0 |
jboilesen/openbel-webtools | app/controllers/belfiles_controller.rb | 9015 | require 'open-uri'
require 'json'
require 'bel'
class BelfilesController < ApplicationController
respond_to :html, :json
BELFILES_FOLDER = "public/belfiles/"
def build_graph(graph, statement)
if graph.is_a?(Graph) && statement.is_a?(Statement)
## 1. identify statement type
## 2. find nodes and, if they don't exist, create them
## 3. create edges following each case rules
if statement.simple?
# Statement subject
@source_node = Node.find_by label: "#{statement.subject}", graph_id: graph.id
if @source_node.blank?
@source_node = Node.new
@source_node.label = "#{statement.subject}"
@source_node.fx = "#{statement.subject.fx}"
@source_node.graph = graph
@source_node.save
end
# Statement object
@target_node = Node.find_by label: "#{statement.object}", graph_id: graph.id
if @target_node.blank?
@target_node = Node.new
@target_node.label = "#{statement.object}"
@target_node.fx = "#{statement.object.fx}"
@target_node.graph = graph
@target_node.save
end
## In a simple statement, edges simply connect subject to object
@edge = Edge.new
@edge.relation = "#{statement.relationship}"
@edge.source = @source_node
@edge.target = @target_node
@edge.graph = graph
@edge.save
elsif statement.nested?
# Statement subject node
@statement_subject_node = Node.find_by label: "#{statement.subject}", graph_id: graph.id
if @statement_subject_node.blank?
@statement_subject_node = Node.new
@statement_subject_node.label = "#{statement.subject}"
@statement_subject_node.fx = "#{statement.subject.fx}"
@statement_subject_node.graph = graph
@statement_subject_node.save
end
# Statement object subject node
@statement_object_subject_node = Node.find_by label: "#{statement.object.subject}", graph_id: graph.id
if @statement_object_subject_node.blank?
@statement_object_subject_node = Node.new
@statement_object_subject_node.label = "#{statement.object.subject}"
@statement_object_subject_node.fx = "#{statement.object.subject.fx}"
@statement_object_subject_node.graph = graph
@statement_object_subject_node.save
end
# Statement object object node
@statement_object_object_node = Node.find_by label: "#{statement.object.object}", graph_id: graph.id
if @statement_object_object_node.blank?
@statement_object_object_node = Node.new
@statement_object_object_node.label = "#{statement.object.object}"
@statement_object_object_node.fx = "#{statement.object.object.fx}"
@statement_object_object_node.graph = graph
@statement_object_object_node.save
end
## In nested statements, edges connect inner object subject to its object
@object_subject_to_object_edge = Edge.new
@object_subject_to_object_edge.relation = "#{statement.object.relationship}"
@object_subject_to_object_edge.source = @statement_object_subject_node
@object_subject_to_object_edge.target = @statement_object_object_node
@object_subject_to_object_edge.graph = graph
@object_subject_to_object_edge.save
## And then edges connect statement subject to inner object subject...
@statement_subject_to_subject_edge = Edge.new
@statement_subject_to_subject_edge.relation = "#{statement.relationship}"
@statement_subject_to_subject_edge.source = @statement_subject_node
@statement_subject_to_subject_edge.target = @statement_object_subject_node
@statement_subject_to_subject_edge.graph = graph
@statement_subject_to_subject_edge.save
## ...and to inner object object
@statement_subject_to_object_edge = Edge.new
@statement_subject_to_object_edge.relation = "#{statement.relationship}"
@statement_subject_to_object_edge.source = @statement_subject_node
@statement_subject_to_object_edge.target = @statement_object_object_node
@statement_subject_to_object_edge.graph = graph
@statement_subject_to_object_edge.save
elsif statement.subject_only?
## Statement subject
@subject_statement_node = Node.find_by label: "#{statement.subject}", graph_id: graph.id
if @subject_statement_node.blank?
@subject_statement_node = Node.new
@subject_statement_node.label = "#{statement.subject}"
@subject_statement_node.fx = "#{statement.subject.fx}"
@subject_statement_node.graph = graph
@subject_statement_node.save
end
## Edges connect statement subject to its arguments
statement.subject.arguments.each do |argument|
@subject_statement_argument_node = Node.find_by label: "#{argument}", graph_id: graph.id
if @subject_statement_argument_node.blank?
@subject_statement_argument_node = Node.new
@subject_statement_argument_node.label = "#{argument}"
@subject_statement_argument_node.graph = graph
@subject_statement_argument_node.save
end
@subject_statement_edge = Edge.new
@subject_statement_edge.relation = "hasComponent"
@subject_statement_edge.source = @subject_statement_node
@subject_statement_edge.target = @subject_statement_argument_node
@subject_statement_edge.graph = graph
@subject_statement_edge.save
end
end
end
end
def new
end
def index
@belfiles = Belfile.all
end
def show
@belfile = Belfile.find(params[:id])
if (params.has_key?(:node))
@json_graph_cystoscape_url = '"' + graph_url(params[:id], type: JSON_GRAPH_CYTOSCAPE, node: params[:node], format: :json) + '"'
else
@json_graph_cystoscape_url = '"' + graph_url(params[:id], type: JSON_GRAPH_CYTOSCAPE, format: :json) + '"'
end
end
def graph
@belfile = Belfile.find(params[:id])
if (params.has_key?(:node))
@nodes = Node.find_by_sql ['SELECT distinct n.* FROM nodes n INNER JOIN (SELECT * from edges WHERE (source_id = ? OR target_id = ?) AND graph_id = ?) e ON n.id = e.source_id OR n.id = e.target_id', params[:node], params[:node], @belfile.graph.id]
@edges = Edge.find_by_sql ['SELECT distinct e.* FROM nodes n INNER JOIN (SELECT * from edges WHERE (source_id = ? OR target_id = ?) AND graph_id = ?) e ON n.id = e.source_id OR n.id = e.target_id', params[:node], params[:node], @belfile.graph.id]
else
@nodes = @belfile.graph.nodes
@edges = @belfile.graph.edges
end
end
def create
@belfile = Belfile.new
@belfile.title = belfile_params[:title]
@belfile.description = belfile_params[:description]
@graph = Graph.new
@graph.label = @belfile.title
@graph.directed = true
@graph.belfile = @belfile
## Treating file upload (:belfile) or download from URL (:url)
if !belfile_params[:belfile].nil?
filename = belfile_params[:belfile].original_filename
belfile_path = BELFILES_FOLDER + filename
if !File.exist?(belfile_path)
@belfile.belfile_path = belfile_path
path = File.join(BELFILES_FOLDER, filename)
File.open(path, "wb") { |f| f.write(belfile_params[:belfile].read) }
@belfile.save
@graph.save
else
## TODO: file already exists error message
redirect_to new_belfile_path
end
elsif !belfile_params[:url].nil?
@belfile.title = belfile_params[:title]
@belfile.description = belfile_params[:description]
## Filename will be based on title
filename = @belfile.title
## So, we sanitize it
filename.gsub!(/^.*(\\|\/)/, '')
filename.gsub!(/[^0-9A-Za-z.\-]/, '_')
filename = filename + '.bel'
belfile_path = BELFILES_FOLDER + filename
## If it not exists, create it
if !File.exist?(belfile_path)
@belfile.belfile_path = belfile_path
path = File.join(BELFILES_FOLDER, filename)
url = URI.parse(belfile_params[:url])
open(path, 'wb') do |file|
file << url.open.read
end
@belfile.save
@graph.save
else
## TODO: file already exists error message
redirect_to new_belfile_path
end
else
## TODO: fill in form correctly error message
redirect_to new_belfile_path
end
bel_content = File.open(@belfile.belfile_path, 'r:UTF-8').read
BEL::Script.parse(bel_content) do |parsed_object|
## here we get bel expressions parsed from belfile
if parsed_object.is_a?(Statement)
build_graph(@graph, parsed_object)
end
end
redirect_to @belfile
end
private
def belfile_params
params.require(:belfile).permit(:title, :description, :belfile, :url)
end
end
| apache-2.0 |
SalmanTKhan/MyAnimeViewer | app/src/main/java/com/taskdesignsinc/android/myanimeviewer/fragment/LibraryMaterialFragment.java | 60204 | package com.taskdesignsinc.android.myanimeviewer.fragment;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.DrawableContainer.DrawableContainerState;
import android.graphics.drawable.GradientDrawable;
import android.graphics.drawable.ShapeDrawable;
import android.graphics.drawable.StateListDrawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Parcelable;
import android.preference.PreferenceManager;
import android.support.annotation.NonNull;
import android.support.design.widget.CoordinatorLayout;
import android.support.design.widget.Snackbar;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.LoaderManager;
import android.support.v4.app.SharedElementCallback;
import android.support.v4.content.AsyncTaskLoader;
import android.support.v4.content.Loader;
import android.support.v4.view.MenuItemCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.view.ActionMode;
import android.support.v7.widget.AppCompatImageButton;
import android.support.v7.widget.SearchView;
import android.support.v7.widget.SearchView.OnCloseListener;
import android.support.v7.widget.SearchView.OnQueryTextListener;
import android.support.v7.widget.Toolbar;
import android.text.InputType;
import android.text.TextUtils;
import android.util.Log;
import android.util.SparseBooleanArray;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.karumi.dexter.PermissionToken;
import com.karumi.dexter.listener.PermissionDeniedResponse;
import com.karumi.dexter.listener.PermissionGrantedResponse;
import com.karumi.dexter.listener.PermissionRequest;
import com.karumi.dexter.listener.single.PermissionListener;
import com.taskdesignsinc.android.myanimeviewer.MAVApplication;
import com.taskdesignsinc.android.myanimeviewer.R;
import com.taskdesignsinc.android.myanimeviewer.adapter.EpisodeListAdapter;
import com.taskdesignsinc.android.myanimeviewer.fragment.base.HeaderGridCompatFragment;
import com.taskdesignsinc.android.myanimeviewer.model.Anime;
import com.taskdesignsinc.android.myanimeviewer.model.Episode;
import com.taskdesignsinc.android.myanimeviewer.model.helper.EpisodeUtils;
import com.taskdesignsinc.android.myanimeviewer.util.BuildUtils;
import com.taskdesignsinc.android.myanimeviewer.util.Constants;
import com.taskdesignsinc.android.myanimeviewer.util.FileUtils;
import com.taskdesignsinc.android.myanimeviewer.util.ImageLoaderManager;
import com.taskdesignsinc.android.myanimeviewer.util.StorageUtils;
import com.taskdesignsinc.android.myanimeviewer.util.WriteLog;
import com.taskdesignsinc.android.myanimeviewer.view.HeaderGridView;
import com.taskdesignsinc.android.thememanager.ThemeManager;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileFilter;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
public class LibraryMaterialFragment extends HeaderGridCompatFragment
implements OnQueryTextListener, OnCloseListener, SwipeRefreshLayout.OnRefreshListener,
LoaderManager.LoaderCallbacks<Anime> {
/**
* Create a new instance of LibraryMaterialFragment, initialized to show the text at
* 'index'.
*/
public static LibraryMaterialFragment newInstance(String pPath) {
LibraryMaterialFragment f = new LibraryMaterialFragment();
// Supply index input as an argument.
Bundle args = new Bundle();
args.putString(Constants.EPISODE_VIDEO_URL, pPath);
f.setArguments(args);
return f;
}
/**
* Create a new instance of LibraryMaterialFragment, initialized to show the text at
* 'index'.
*/
public static LibraryMaterialFragment newInstance(Bundle args) {
LibraryMaterialFragment f = new LibraryMaterialFragment();
f.setArguments(args);
return f;
}
final String mTAG = LibraryMaterialFragment.class.getSimpleName();
// This is the Adapter being used to display the list's data.
EpisodeListAdapter mAdapter;
// The SearchView for doing filtering.
SearchView mSearchView;
CoordinatorLayout mCoordinatorLayout;
private AppCompatImageButton mFloatingActionButton;
private View mHeaderInfoView;
private ImageView mHeaderImageView;
private TextView mTitleAuthorTextView;
private TextView mTitleAliasTextView;
private TextView mTitleGenreTextView;
private TextView mTitleStatusTextView;
private TextView mTitleSummaryTextView;
private TextView mNameTextView;
private TextView mSummaryTextView;
private TextView mAuthorTextView;
private TextView mAliasTextView;
private TextView mGenreTextView;
private TextView mStatusTextView;
private RelativeLayout mHeaderEpisodeView;
// If non-null, this is the current filter the user has provided.
String mCurFilter;
private boolean mLoadImageCalled = false;
private boolean mIsTablet = false;
int mSortType = 0;
private SharedPreferences mPrefs;
private String mPath;
private String mAnimeUrl;
private int mAnimeID;
Handler mHandler;
public ActionMode mMode;
Anime mAnime;
HashMap<String, Episode> mEpisodes = null;
private int mSelectionMode = Constants.SELECT_SINGLE;
private int mSelectedLowerBound = -1;
private int mSelectedUpperBound = -1;
private boolean mEpisodeHistory = true;
private boolean mHideViewedEpisodes = false;
public String mLastEpisodeDownloaded = "";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
mAnimeID = getArguments() != null ? getArguments().getInt(Constants.ANIME_ID) : -1;
mAnimeUrl = getArguments() != null ? getArguments().getString(Constants.ANIME_URL) : "";
mPath = getArguments() != null ? getArguments().getString(Constants.EPISODE_VIDEO_URL) : "";
if (!TextUtils.isEmpty(mAnimeUrl))
if (mAnimeUrl.contains("batoto.net"))
mAnimeUrl = mAnimeUrl.replace("batoto.net", "bato.to");
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View layout = super.onCreateView(inflater, container,
savedInstanceState);
HeaderGridView lv = layout.findViewById(android.R.id.list);
ViewGroup parent = (ViewGroup) lv.getParent();
// Remove ListView and add CustomView in its place
int lvIndex = parent.indexOfChild(lv);
parent.removeViewAt(lvIndex);
FrameLayout mLinearLayout = (FrameLayout) inflater.inflate(
R.layout.anime_details_layout, container, false);
parent.addView(mLinearLayout, lvIndex, lv.getLayoutParams());
View parentView = null;
if (mIsTablet) {
parentView = mLinearLayout;
} else
parentView = mHeaderInfoView = inflater.inflate(R.layout.header_anime_info, null);
mHeaderImageView = parentView.findViewById(R.id.headerImageView);
//mMaskImageView = parentView.findViewById(R.id.maskImageView);
mTitleAuthorTextView = parentView.findViewById(R.id.authorTitleTextView);
mTitleAliasTextView = parentView.findViewById(R.id.aliasTitleTextView);
mTitleGenreTextView = parentView.findViewById(R.id.genreTitleTextView);
mTitleStatusTextView = parentView.findViewById(R.id.statusTitleTextView);
mTitleSummaryTextView = parentView.findViewById(R.id.descriptionTitleTextView);
if (mTitleAuthorTextView != null)
mTitleAuthorTextView.setTextColor(ThemeManager.getInstance().getPrimaryTextColor(parentView.getContext()));
if (mTitleAliasTextView != null)
mTitleAliasTextView.setTextColor(ThemeManager.getInstance().getPrimaryTextColor(parentView.getContext()));
if (mTitleGenreTextView != null)
mTitleGenreTextView.setTextColor(ThemeManager.getInstance().getPrimaryTextColor(parentView.getContext()));
if (mTitleStatusTextView != null)
mTitleStatusTextView.setTextColor(ThemeManager.getInstance().getPrimaryTextColor(parentView.getContext()));
if (mTitleSummaryTextView != null)
mTitleSummaryTextView.setTextColor(ThemeManager.getInstance().getPrimaryTextColor(parentView.getContext()));
mSummaryTextView = parentView.findViewById(R.id.descriptionTextView);
mAuthorTextView = parentView.findViewById(R.id.authorTextView);
mAliasTextView = parentView.findViewById(R.id.aliasTextView);
mGenreTextView = parentView.findViewById(R.id.genreTextView);
mStatusTextView = parentView.findViewById(R.id.statusTextView);
mNameTextView = parentView.findViewById(R.id.nameTextView);
mNameTextView.setTextColor(ThemeManager.getInstance().getPrimaryTextColor(parentView.getContext()));
// Fab Button
mFloatingActionButton = parentView.findViewById(R.id.fab_button);
if (mFloatingActionButton != null) {
Drawable fabBackground = mFloatingActionButton.getBackground();
if (fabBackground instanceof ShapeDrawable) {
((ShapeDrawable) fabBackground).getPaint().setColor(
getResources().getColor(ThemeManager.getInstance().getPrimaryDarkColorResId()));
} else if (fabBackground instanceof StateListDrawable) {
StateListDrawable tempDrawableList = (StateListDrawable) fabBackground;
DrawableContainerState drawableContainerState = (DrawableContainerState) tempDrawableList.getConstantState();
Drawable[] children = drawableContainerState.getChildren();
GradientDrawable selectedItem = (GradientDrawable) children[0];
GradientDrawable pressedItem = (GradientDrawable) children[1];
GradientDrawable unselectedItem = (GradientDrawable) children[2];
selectedItem.setStroke(100, ThemeManager.getInstance().getAccentColor(parent.getContext()));
pressedItem.setStroke(100, ThemeManager.getInstance().getAccentColor(parent.getContext()));
unselectedItem.setStroke(100, ThemeManager.getInstance().getPrimaryDarkColor(parent.getContext()));
}
mFloatingActionButton.setImageResource(R.drawable.ic_file_download_white_24dp);
mFloatingActionButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View pV) {
MaterialDialog downloadAllorSelect = new MaterialDialog
.Builder(getActivity())
.title(R.string.download)
.content("Download episodes, either all or select which one.")
.positiveText(R.string.all)
.neutralText(R.string.select)
.negativeText(R.string.cancel)
.onPositive(new MaterialDialog.SingleButtonCallback() {
@Override
public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
dialog.dismiss();
if (StorageUtils.isStorageAllowed()) {
for (int i = 0; i < getGridAdapter().getCount(); i++) {
LibraryMaterialFragment.this.directDownloadEpisode((Episode) getGridAdapter().getItem(i));
}
} else {
if (BuildUtils.isMarshmallowOrLater()) {
StorageUtils.requestStoragePermissions(new PermissionListener() {
@Override
public void onPermissionGranted(PermissionGrantedResponse response) {
for (int i = 0; i < getGridAdapter().getCount(); i++) {
directDownloadEpisode((Episode) getGridAdapter().getItem(i));
}
}
@Override
public void onPermissionDenied(PermissionDeniedResponse response) {
Snackbar.make(mCoordinatorLayout, "My Anime Viewer will be unable to store any anime for offline reading.", Snackbar.LENGTH_SHORT).show();
}
@Override
public void onPermissionRationaleShouldBeShown(PermissionRequest permission, PermissionToken token) {
token.continuePermissionRequest();
}
});
}
}
}
}).onNeutral(new MaterialDialog.SingleButtonCallback() {
@Override
public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
dialog.dismiss();
getGridView().setChoiceMode(AbsListView.CHOICE_MODE_MULTIPLE);
getGridView().invalidateViews();
mMode = ((AppCompatActivity) getActivity()).startSupportActionMode(new RecordOptions((AppCompatActivity) getActivity()));
}
})
.build();
downloadAllorSelect.show();
}
});
}
mHeaderEpisodeView = (RelativeLayout) inflater.inflate(R.layout.header_anime_episode, null);
mHeaderEpisodeView.setBackgroundColor(ThemeManager.getInstance().getPrimaryColor(getActivity()));
ActivityCompat.setEnterSharedElementCallback(getActivity(), new SharedElementCallback() {
@Override
public View onCreateSnapshotView(Context context, Parcelable snapshot) {
View view = new View(context);
if (snapshot instanceof Bitmap) {
view.setBackground(new BitmapDrawable((Bitmap) snapshot));
}
return view;
}
@Override
public void onSharedElementStart(List<String> sharedElementNames,
List<View> sharedElements,
List<View> sharedElementSnapshots) {
ImageView sharedElement = (ImageView) mHeaderImageView;
for (int i = 0; i < sharedElements.size(); i++) {
if (sharedElements.get(i) == sharedElement) {
View snapshot = sharedElementSnapshots.get(i);
Drawable snapshotDrawable = snapshot.getBackground();
sharedElement.setBackground(snapshotDrawable);
sharedElement.setImageAlpha(0);
forceSharedElementLayout();
break;
}
}
}
private void forceSharedElementLayout() {
ImageView sharedElement = (ImageView) mHeaderImageView;
int widthSpec = View.MeasureSpec.makeMeasureSpec(sharedElement.getWidth(),
View.MeasureSpec.EXACTLY);
int heightSpec = View.MeasureSpec.makeMeasureSpec(sharedElement.getHeight(),
View.MeasureSpec.EXACTLY);
int left = sharedElement.getLeft();
int top = sharedElement.getTop();
int right = sharedElement.getRight();
int bottom = sharedElement.getBottom();
sharedElement.measure(widthSpec, heightSpec);
sharedElement.layout(left, top, right, bottom);
}
@Override
public void onSharedElementEnd(List<String> sharedElementNames,
List<View> sharedElements,
List<View> sharedElementSnapshots) {
ImageView sharedElement = (ImageView) mHeaderImageView;
sharedElement.setBackground(null);
sharedElement.setImageAlpha(255);
String lCover = MAVApplication.getInstance().getRepository().getCoverByUrl(mAnimeUrl);
if (!TextUtils.isEmpty(lCover)) {
ImageLoaderManager.getInstance(getActivity()).loadImage(lCover, mHeaderImageView);
mLoadImageCalled = true;
}
}
});
if (BuildUtils.isLollipopOrLater())
layout.getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
@Override
public boolean onPreDraw() {
layout.getViewTreeObserver().removeOnPreDrawListener(this);
ActivityCompat.startPostponedEnterTransition(getActivity());
return true;
}
});
return layout;
}
public void setDetails(final Anime pAnime) {
final AppCompatActivity pActivity = ((AppCompatActivity) getActivity());
if (pAnime != null) {
WriteLog.appendLog("Setting anime details for " + pAnime.getTitle());
mAnime = pAnime;
if (pActivity != null && !TextUtils.isEmpty(mAnime.getTitle()))
mNameTextView.setText(mAnime.getTitle());
if (mAliasTextView != null) {
if (!TextUtils.isEmpty(mAnime.getAliases()))
mAliasTextView.setText(mAnime.getAliases());
else {
mTitleAliasTextView.setVisibility(View.GONE);
mAliasTextView.setVisibility(View.GONE);
}
}
if (mAuthorTextView != null) {
if (!TextUtils.isEmpty(mAnime.getCreator()))
mAuthorTextView.setText(mAnime.getCreator());
else {
mTitleAuthorTextView.setVisibility(View.GONE);
mAuthorTextView.setVisibility(View.GONE);
}
}
if (mGenreTextView != null) {
if (!TextUtils.isEmpty(mAnime.getGenres()))
mGenreTextView.setText(mAnime.getGenres());
else {
mTitleGenreTextView.setVisibility(View.GONE);
mGenreTextView.setVisibility(View.GONE);
}
}
if (mStatusTextView != null)
mStatusTextView.setText(((mAnime.getStatus() == 0) ? " Ongoing" : " Completed"));
if (mSummaryTextView != null) {
if (!TextUtils.isEmpty(mAnime.getSummary()))
mSummaryTextView.setText(mAnime.getSummary());
else {
mTitleSummaryTextView.setVisibility(View.GONE);
mSummaryTextView.setVisibility(View.GONE);
}
}
}
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// We have a menu item to show in action bar.
setHasOptionsMenu(true);
final AppCompatActivity activity = ((AppCompatActivity) getActivity());
if (activity != null) {
mCoordinatorLayout = (CoordinatorLayout) activity.findViewById(R.id.coordinator_layout);
if (mHandler == null)
mHandler = new Handler();
if (mPrefs == null)
mPrefs = PreferenceManager.getDefaultSharedPreferences(activity);
mSortType = mPrefs.getBoolean(Constants.KEY_EPISODE_DEFAULT_SORT, true) ? 0 : 1;
mEpisodeHistory = mPrefs.getBoolean(Constants.KEY_EPISODE_HISTORY, true);
// Create an empty adapter we will use to display the loaded data.
//mAnime = MAVApplication.getInstance().getRepository().getAnimeByUrl(mAnimeUrl, true);
mAdapter = new EpisodeListAdapter(getActivity(), mPath, false, true);
initListViewHeaders();
//mAdapter.setData(mAnime);
if (mSortType == 1)
mAdapter.sort(Collections.reverseOrder(Episode.SortByPosition));
setGridAdapter(mAdapter);
getGridView().setOnItemLongClickListener(new RecordOptions(activity));
}
if (getGridAdapter().getCount() == 0) {
// Start out with a progress indicator.
setGridShown(false);
// Prepare the loader. Either re-connect with an existing one,
// or start a new one.
getLoaderManager().initLoader(0, null, this);
} else {
//mAnimeActionBar.setVisibility(View.INVISIBLE);
if (!TextUtils.isEmpty(mAnime.getCover()))
ImageLoaderManager.getInstance(getActivity()).loadImage(mAnime.getCover(), mHeaderImageView);
if (mPrefs.getBoolean(Constants.KEY_EPISODE_SHOW_WARNING, true))
if (!TextUtils.isEmpty(mAnime.getWarning()))
showCustomAlertDialog("Warning", mAnime.getWarning());
setDetails(mAnime);
//mAnime.save(getActivity());
activity.supportInvalidateOptionsMenu();
}
}
private void initListViewHeaders() {
if (mHeaderInfoView != null) {
getGridView().addHeaderView(mHeaderInfoView, null, false);
}
if (mHeaderEpisodeView != null) {
getGridView().addHeaderView(mHeaderEpisodeView, null, false);
}
}
public static class EpisodeSearchView extends SearchView {
public EpisodeSearchView(Context context) {
super(context);
}
// The normal SearchView doesn't clear its search text when
// collapsed, so we will do this for it.
@Override
public void onActionViewCollapsed() {
setQuery("", false);
super.onActionViewCollapsed();
}
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
}
private int mItemBaseID = 10100;
public static boolean mIsViewing = false;
@Override
public void onPrepareOptionsMenu(Menu menu) {
menu.clear();
// Place an action bar item for searching.
if (MAVApplication.getInstance().getRepository().isFavorite(mAnimeUrl))
menu.add(Menu.NONE, mItemBaseID, 0, R.string.favorite).setIcon(ThemeManager.getInstance(getActivity()).isLightBackground()
? R.drawable.ic_favorite_black_24dp : R.drawable.ic_favorite_white_24dp);
else
menu.add(Menu.NONE, mItemBaseID, 0, R.string.favorite).setIcon(ThemeManager.getInstance(getActivity()).isLightBackground()
? R.drawable.ic_favorite_border_black_24dp : R.drawable.ic_favorite_border_white_24dp);
MenuItemCompat.setShowAsAction(menu.getItem(menu.size() - 1), MenuItemCompat.SHOW_AS_ACTION_IF_ROOM);
menu.add(Menu.NONE, mItemBaseID + 1, 0, R.string.update)
.setIcon(ThemeManager.getInstance(getActivity()).isLightBackground() ? R.drawable.ic_refresh_black_24dp : R.drawable.ic_refresh_white_24dp);
MenuItemCompat.setShowAsAction(menu.getItem(menu.size() - 1), MenuItemCompat.SHOW_AS_ACTION_IF_ROOM);
MenuItem item = menu.add(Menu.NONE, mItemBaseID + 2, 0, "Search Episodes");
item.setIcon(ThemeManager.getInstance(getActivity()).isLightBackground() ? R.drawable.ic_search_black_24dp : R.drawable.ic_search_white_24dp);
MenuItemCompat.setShowAsAction(item, MenuItemCompat.SHOW_AS_ACTION_IF_ROOM
| MenuItemCompat.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW);
//mSearchView = new EpisodeSearchView(getActivity());
//mSearchView.setOnQueryTextListener(this);
//mSearchView.setOnCloseListener(this);
//mSearchView.setIconifiedByDefault(true);
//MenuItemCompat.setActionView(item, mSearchView);
menu.add(Menu.NONE, mItemBaseID + 3, 0, "Sort Episodes").setIcon(android.R.drawable.ic_menu_sort_alphabetically);
MenuItemCompat.setShowAsAction(menu.getItem(menu.size() - 1), MenuItemCompat.SHOW_AS_ACTION_IF_ROOM);
menu.add(Menu.NONE, mItemBaseID + 4, 0, R.string.download).setIcon(ThemeManager.getInstance(getActivity()).isLightBackground() ? R.drawable.ic_file_download_black_24dp : R.drawable.ic_file_download_white_24dp);
menu.add(Menu.NONE, mItemBaseID + 5, 0, R.string.mark_viewed);
menu.add(Menu.NONE, mItemBaseID + 6, 0, R.string.mark_unviewed);
//menu.add(Menu.NONE, mItemBaseID + 9, 0, "Show/Hide Viewed Episodes");
//menu.add(Menu.NONE, mItemBaseID + 10, 0, R.string.share);
//menu.add(Menu.NONE, mItemBaseID + 11, 0, "Find Alternate Sources");
}
@Override
public boolean onOptionsItemSelected(final MenuItem pItem) {
if (getActivity() == null)
return false;
return super.onOptionsItemSelected(pItem);
}
@Override
public boolean onQueryTextChange(String newText) {
// Called when the action bar search text has changed. Since this
// is a simple array adapter, we can just have it do the filtering.
mCurFilter = !TextUtils.isEmpty(newText) ? newText : null;
mAdapter.getFilter().filter(mCurFilter);
return true;
}
@Override
public boolean onQueryTextSubmit(String query) {
// Don't care about this.
return true;
}
@Override
public boolean onClose() {
if (!TextUtils.isEmpty(mSearchView.getQuery())) {
mSearchView.setQuery(null, true);
}
return true;
}
@Override
public void onGridItemClick(HeaderGridView l, View v, final int position, long id) {
final int actualPosition = position - getGridView().getHeaderViewsCount();
if (mMode == null) {
// Insert desired behavior here.
Episode lObject = (Episode) l.getAdapter().getItem(position);
if (lObject != null) {
getGridView().setSelection(actualPosition);
getGridView().setSelected(false);
final Episode lEpisode = lObject;
if (lEpisode != null) {
//if (!CastUtils.showQueuePopup(getActivity(), v, mAnime, lEpisode))
viewEpisode(actualPosition, lEpisode);
}
}
} else {
if (mSelectionMode == Constants.SELECT_MULTIPLE) {
if (mSelectedLowerBound == -1 || mSelectedUpperBound > actualPosition) {
mSelectedLowerBound = actualPosition;
} else if (mSelectedUpperBound == -1 || mSelectedUpperBound < actualPosition) {
if (actualPosition < mSelectedLowerBound) {
mSelectedUpperBound = mSelectedLowerBound;
mSelectedLowerBound = actualPosition;
} else
mSelectedUpperBound = actualPosition;
}
if (mSelectedLowerBound != -1 && mSelectedUpperBound != -1) {
for (int i = mSelectedLowerBound; i <= mSelectedUpperBound; i++) {
getGridView().setItemChecked(i, true);
updateItemAtPosition(i);
}
}
mAdapter.notifyDataSetChanged();
} else {
if (mSelectionMode == Constants.SELECT_SINGLE) {
updateItemAtPosition(actualPosition);
}
}
}
}
private void updateItemAtPosition(int position) {
if (position == -1)
return;
int visiblePosition = getGridView().getFirstVisiblePosition();
View view = getGridView().getChildAt(position - visiblePosition + getGridView().getHeaderViewsCount());
getGridView().getAdapter().getView(position + getGridView().getHeaderViewsCount(), view, getGridView());
}
private void viewEpisode(int position, Episode pEpisode) {
//WriteLog.appendLog(mTAG + ": viewEpisode({0}, {1})", "" + position, pEpisode.toString());
mIsViewing = true;
if (TextUtils.isEmpty(pEpisode.getLocalPath())) {
File lDownloadDir = new File(StorageUtils.getDataDirectory(), mAnime.getTitle() + "/" + pEpisode.getTitle() + "/");
if (lDownloadDir.exists()) {
pEpisode.setLocalPath(lDownloadDir.getAbsolutePath());
} else {
lDownloadDir = new File(StorageUtils.getDataDirectory(), FileUtils.getValidFileName(mAnime.getTitle()) + "/" + FileUtils.getValidFileName(pEpisode.getTitle()) + "/");
if (lDownloadDir.exists()) {
pEpisode.setLocalPath(lDownloadDir.getAbsolutePath());
}
}
}
if (!TextUtils.isEmpty(pEpisode.getLocalPath())) {
MAVApplication.getInstance().getRepository().insertOfflineHistoryRecord(pEpisode.getLocalPath(), true);
EpisodeUtils.viewEpisodeOffline(mTAG, getActivity(), mAnime, pEpisode, mCoordinatorLayout);
}
}
private void downloadEpisodes(ArrayList<Episode> episodes) {
if (mPrefs.getBoolean(Constants.KEY_EPISODE_SORT_BEFORE_DOWNLOAD, true))
Collections.sort(episodes, Episode.SortByPosition);
for (int i = 0; i < episodes.size(); i++)
directDownloadEpisode(episodes.get(i));
}
private void downloadEpisode(Episode pEpisode) {
if (pEpisode != null) {
if (MAVApplication.getInstance().getRepository().getDownloadTask(pEpisode.getUrl(), false) != null
&& !mLastEpisodeDownloaded.equals(pEpisode.getUrl())) {
Snackbar.make(mCoordinatorLayout, "Are you sure you want to download " + pEpisode.getTitle() + " again, then press download again", Snackbar.LENGTH_SHORT).show();
mLastEpisodeDownloaded = pEpisode.getUrl();
return;
}
EpisodeUtils.downloadEpisode(getActivity(), pEpisode);
} else {
WriteLog.appendLog("downloadEpisode because of null episode");
Snackbar.make(mCoordinatorLayout, "Something went wrong, episode object was null", Snackbar.LENGTH_SHORT).show();
}
}
private void directDownloadEpisode(Episode pEpisode) {
if (pEpisode != null) {
EpisodeUtils.downloadEpisode(getActivity(), pEpisode);
} else {
WriteLog.appendLog("downloadEpisode because of null episode");
Snackbar.make(mCoordinatorLayout, "Something went wrong, episode object was null", Snackbar.LENGTH_SHORT).show();
}
}
private void changeViewedStatusByEpisode(Episode pEpisode, boolean pIsViewed) {
if (pEpisode != null) {
if (mAnime != null)
MAVApplication.getInstance().getRepository().insertHistoryRecord(mAnime.getUrl(), pEpisode.getUrl(), pIsViewed);
pEpisode.setViewed(pIsViewed);
}
}
private void changeViewedStatusByPosition(int pPosition, boolean pIsViewed) {
WriteLog.appendLog("changeViewedStatusByPosition(" + pPosition + "," + pIsViewed + ")");
Episode pEpisode = mAdapter.getItem(pPosition);
if (pEpisode != null) {
MAVApplication.getInstance().getRepository().insertHistoryRecord(mAnime.getUrl(), pEpisode.getUrl(), pIsViewed);
pEpisode.setViewed(pIsViewed);
}
}
@Override
public AsyncTaskLoader<Anime> onCreateLoader(int id, Bundle args) {
WriteLog.appendLog("Anime loader started");
AsyncTaskLoader<Anime> loader = new AsyncTaskLoader<Anime>(getActivity()) {
FileFilter fileFilter = new FileFilter() {
@Override
public boolean accept(File file) {
boolean lShowBackup = mPrefs.getBoolean(Constants.KEY_LIBRARY_SHOW_BACKUPS, false);
boolean lShowCovers = mPrefs.getBoolean(Constants.KEY_LIBRARY_SHOW_COVERS, false);
boolean lShowData = mPrefs.getBoolean(Constants.KEY_LIBRARY_SHOW_COVERS, false);
return !file.getName().equals("Cache")
&& !file.getName().equals(".nomedia")
&& (lShowCovers ?
true : !file.getName().contains("cover"))
&& (lShowBackup ?
true : !file.getName().equals("Backup"))
&& (lShowData ?
true : (!file.getName().equals("Data")
&& !file.getName().endsWith(".json")));
}
};
@Override
public Anime loadInBackground() {
File pAnimeFile = new File(mPath, "anime.json");
if (pAnimeFile.exists()) {
WriteLog.appendLog("Anime data found at " + pAnimeFile.getAbsolutePath());
try {
Gson gson = new Gson();
BufferedReader br = new BufferedReader(new FileReader(pAnimeFile));
// This is how you tell gson about the generic type you want to get
// back:
// convert the json string back to object
mAnime = gson.fromJson(br, Anime.class);
br.close();
} catch (IOException e) {
WriteLog.appendLog("Loading anime data error");
WriteLog.appendLog(Log.getStackTraceString(e));
e.printStackTrace();
} catch (JsonSyntaxException e) {
WriteLog.appendLog("Old format, deleting to prevent crash");
pAnimeFile.delete();
}
} else {
mAnime = null;
}
if (mAnime != null) {
if (!pAnimeFile.getParentFile().getAbsolutePath().contains(FileUtils.getValidFileName(mAnime.getTitle()))) {
mAnime = null;
mEpisodes = null;
} else {
mEpisodes = new HashMap<String, Episode>();
Episode lEpisode = null;
if (mAnime.getEpisodes() != null && mAnime.getEpisodes().size() > 0) {
for (int i = 0; i < mAnime.getEpisodes().size(); i++) {
lEpisode = mAnime.getEpisodes().get(i);
if (TextUtils.isEmpty(lEpisode.getTitle())) {
lEpisode.setTitle(FileUtils.getFileName(lEpisode.getLocalPath()));
}
if (TextUtils.isEmpty(lEpisode.getLocalPath()))
continue;
mEpisodes.put(lEpisode.getLocalPath(), lEpisode);
}
} else {
File[] lFileList = pAnimeFile.getParentFile().listFiles(fileFilter);
if (lFileList != null) {
Arrays.sort(lFileList, new FileUtils.SortByFileName());
Arrays.sort(lFileList, new FileUtils.SortByFolder());
if (mEpisodes.isEmpty()) {
ArrayList<Episode> offlineEpisodes = new ArrayList<Episode>();
for (int i = 0; i < lFileList.length; i++) {
String fileName = lFileList[i].getName();
if (FileUtils.isVideo(FileUtils.getFileExtension(fileName))) {
lEpisode = new Episode();
lEpisode.setTitle(fileName);
lEpisode.setLocalPath(lFileList[i].getAbsolutePath());
lEpisode.setAnime(mAnime);
}
if (lEpisode != null && !TextUtils.isEmpty(lEpisode.getTitle()))
offlineEpisodes.add(lEpisode);
}
mAnime.setEpisodes(offlineEpisodes);
}
}
}
}
}
return mAnime;
}
};
// This is called when a new Loader needs to be created. This
// sample only has one Loader with no arguments, so it is simple.
loader.forceLoad();
return loader;
}
@Override
public void onLoadFinished(Loader<Anime> loader, final Anime data) {
WriteLog.appendLog(mTAG, "Anime loader finished");
// Set the new data in the adapter.
if (data != null) {
if (mAnime == null)
MAVApplication.getInstance().getRepository().insertAnime(data);
if (getArguments() != null)
getArguments().putString(Constants.ANIME_URL, data.getUrl());
mAnimeUrl = data.getUrl();
mAnime = data;
File lCoverFile = new File(mPath, "cover.png");
if (lCoverFile.exists()) {
String lCoverURL = "file:///" + lCoverFile.getAbsolutePath();
ImageLoaderManager.getInstance().loadImage(lCoverURL, mHeaderImageView);
} else {
if (!TextUtils.isEmpty(data.getCover())) {
ImageLoaderManager.getInstance(getActivity()).loadImage(data.getCover(), mHeaderImageView);
}
}
mAdapter.setData(data);
mAdapter.getFilter().filter(null);
//mAnime.save(getActivity());
}
// The list should now be shown.
if (isResumed()) {
setGridShown(true);
} else {
setGridShownNoAnimation(true);
}
mHandler.post(new Runnable() {
@Override
public void run() {
if (data != null) {
if (mPrefs.getBoolean(Constants.KEY_EPISODE_SHOW_WARNING, true))
if (!TextUtils.isEmpty(data.getWarning()))
showCustomAlertDialog("Warning", data.getWarning());
setDetails(mAnime);
}
}
});
}
@Override
public void onLoaderReset(Loader<Anime> loader) {
WriteLog.appendLog("Anime loader reset");
// Clear the data in the adapter.
mAdapter.setData(null);
}
public void dismissDialog() {
final FragmentManager fm = getFragmentManager();
if (fm == null)
return;
Fragment prev = fm.findFragmentByTag("cadfragment");
if (prev != null) {
DialogFragment df = (DialogFragment) prev;
df.dismiss();
}
}
private synchronized void showCustomAlertDialog(String title, String msg) {
final FragmentManager fm = getFragmentManager();
if (fm == null)
return;
// Create the fragment and show it as a dialog.
dismissDialog();
//DialogFragment newFragment = CustomAlertDialog.CADFragment.newInstance(android.R.drawable.ic_dialog_alert, title, msg);
//newFragment.show(fm, "cadfragment");
}
private synchronized void showMarkEpisodeDialog(int type) {
if (mAnime == null)
return;
final FragmentManager fm = getFragmentManager();
if (fm == null)
return;
// Create the fragment and show it as a dialog.
dismissDialog();
DialogFragment newFragment = new MarkEpisodeDialog();
newFragment.setTargetFragment(this, 0);
Bundle bundle = new Bundle();
bundle.putInt("type", type);
bundle.putInt("itype", InputType.TYPE_CLASS_NUMBER);
bundle.putInt("itype2", InputType.TYPE_CLASS_NUMBER);
bundle.putInt("min", 0);
bundle.putInt("max", mAnime.getEpisodes().size());
newFragment.setArguments(bundle);
newFragment.show(fm,
"mcdfragment");
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
private final class RecordOptions implements ActionMode.Callback, AdapterView.OnItemLongClickListener {
AppCompatActivity mContext;
Toolbar mToolbar;
Boolean mIsAllSelected = false;
public RecordOptions(AppCompatActivity context) {
mContext = context;
mToolbar = (Toolbar) mContext.findViewById(R.id.toolbar);
}
@Override
public boolean onItemLongClick(AdapterView<?> view, View row,
int position, long id) {
if (mMode == null) {
getGridView().setChoiceMode(AbsListView.CHOICE_MODE_MULTIPLE);
getGridView().invalidateViews();
mMode = mContext.startSupportActionMode(this);
} else {
getGridView().setChoiceMode(AbsListView.CHOICE_MODE_SINGLE);
getGridView().invalidateViews();
mMode.finish();
}
return (true);
}
@Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
menu.add(R.string.delete).setIcon(ThemeManager.getInstance(getActivity()).isLightBackground() ? R.drawable.ic_delete_black_24dp : R.drawable.ic_delete_white_24dp);
MenuItemCompat.setShowAsAction(menu.getItem(menu.size() - 1), MenuItemCompat.SHOW_AS_ACTION_IF_ROOM);
menu.add(R.string.download)
.setIcon(ThemeManager.getInstance(getActivity()).isLightBackground() ? R.drawable.ic_file_download_black_24dp : R.drawable.ic_file_download_white_24dp);
MenuItemCompat.setShowAsAction(menu.getItem(menu.size() - 1), MenuItemCompat.SHOW_AS_ACTION_IF_ROOM);
menu.add(R.string.mark_viewed);
MenuItemCompat.setShowAsAction(menu.getItem(menu.size() - 1), MenuItemCompat.SHOW_AS_ACTION_IF_ROOM);
menu.add(R.string.mark_unviewed);
MenuItemCompat.setShowAsAction(menu.getItem(menu.size() - 1), MenuItemCompat.SHOW_AS_ACTION_IF_ROOM);
return true;
}
@Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return false;
}
@Override
public boolean onActionItemClicked(final ActionMode mode,
MenuItem item) {
if (isAdded() && getView() != null) {
if (item.getTitle().equals(getString(R.string.select_mode))) {
AlertDialog.Builder builder = new AlertDialog.Builder(
getActivity());
builder.setTitle("Selection Mode");
builder.setSingleChoiceItems(Constants.SELECTION_CHOICES, mSelectionMode, new OnClickListener() {
@Override
public void onClick(DialogInterface pDialog, int pWhich) {
if (mSelectionMode != pWhich) {
mSelectionMode = pWhich;
if (pWhich == Constants.SELECT_ALL) {
mIsAllSelected = !mIsAllSelected;
if (mIsAllSelected)
WriteLog.appendLog("Selecting All: total count "
+ mAdapter.getCount());
else
WriteLog.appendLog("Unselecting All: total count "
+ mAdapter.getCount());
for (int i = 0; i < mAdapter.getCount(); i++)
getGridView().setItemChecked(i, mIsAllSelected);
mAdapter.notifyDataSetChanged();
mSelectedLowerBound = -1;
mSelectedUpperBound = -1;
mSelectionMode = Constants.SELECT_SINGLE;
}
}
pDialog.dismiss();
}
});
final AlertDialog alert = builder.create();
alert.show();
} else if (item.getTitle().toString().equals(getString(R.string.delete))) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Delete Episode(s)");
builder.setPositiveButton(android.R.string.yes, new OnClickListener() {
@Override
public void onClick(DialogInterface pDialog, int pWhich) {
pDialog.dismiss();
SparseBooleanArray checkArray = getGridView().getCheckedItemPositions();
int count = checkArray.size();
Episode lEpisode = null;
//String[] lToDeletePath = new String[count];
//int lToDeleteIndex = 0;
int indices[] = new int[count];
ArrayList<Episode> lEpisodesRemoved = new ArrayList<Episode>();
for (int i = 0; i < count; i++) {
if (checkArray.valueAt(i)) {
indices[i] = checkArray.keyAt(i) - getGridView().getHeaderViewsCount();
lEpisode = mAdapter.getItem(checkArray.keyAt(i) - getGridView().getHeaderViewsCount());
if (lEpisode != null && !TextUtils.isEmpty(lEpisode.getLocalPath())) {
//lToDeletePath[lToDeleteIndex] = lEpisode.getLocalPath();
//lToDeleteIndex++;
if (FileUtils.deleteDirectory(lEpisode.getLocalPath()))
lEpisodesRemoved.add(lEpisode);
}
}
}
for (int i = 0; i < lEpisodesRemoved.size(); i++) {
if (lEpisode != null) {
mAdapter.remove(lEpisodesRemoved.get(i));
}
}
//FileUtils.deleteAsync(lToDeletePath);
mAdapter.checkEpisodeStatus();
mode.finish();
}
});
builder.setNegativeButton(android.R.string.no, new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
final AlertDialog alert = builder.create();
alert.show();
} else if (item.getTitle().toString().equals(getString(R.string.download))) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Download Episode(s)");
builder.setPositiveButton(android.R.string.yes, new OnClickListener() {
@Override
public void onClick(DialogInterface pDialog, int pWhich) {
pDialog.dismiss();
SparseBooleanArray checkArray = getGridView().getCheckedItemPositions();
int count = checkArray.size();
for (int i = 0; i < count; i++) {
if (checkArray.valueAt(i)) {
downloadEpisode(mAdapter.getItem(checkArray.keyAt(i) - getGridView().getHeaderViewsCount()));
}
}
mode.finish();
}
});
builder.setNegativeButton(android.R.string.no, new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
final AlertDialog alert = builder.create();
alert.show();
} else if (item.getTitle().toString().equals(getString(R.string.mark_viewed))) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle(R.string.mark_viewed);
builder.setPositiveButton(android.R.string.yes, new OnClickListener() {
@Override
public void onClick(DialogInterface pDialog, int pWhich) {
pDialog.dismiss();
SparseBooleanArray checkArray = getGridView().getCheckedItemPositions();
int count = checkArray.size();
for (int i = 0; i < count; i++) {
if (checkArray.valueAt(i)) {
changeViewedStatusByEpisode(mAdapter.getItem(checkArray.keyAt(i) - getGridView().getHeaderViewsCount()), true);
}
}
mAdapter.checkEpisodeStatus();
mode.finish();
}
});
builder.setNegativeButton(android.R.string.no, new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
final AlertDialog alert = builder.create();
alert.show();
} else if (item.getTitle().toString().equals(getString(R.string.mark_unviewed))) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle(R.string.mark_unviewed);
builder.setPositiveButton(android.R.string.yes, new OnClickListener() {
@Override
public void onClick(DialogInterface pDialog, int pWhich) {
pDialog.dismiss();
SparseBooleanArray checkArray = getGridView().getCheckedItemPositions();
int count = checkArray.size();
for (int i = 0; i < count; i++) {
if (checkArray.valueAt(i)) {
changeViewedStatusByEpisode(mAdapter.getItem(checkArray.keyAt(i) - getGridView().getHeaderViewsCount()), false);
}
}
mAdapter.checkEpisodeStatus();
mode.finish();
}
});
builder.setNegativeButton(android.R.string.no, new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
final AlertDialog alert = builder.create();
alert.show();
} else {
mode.finish();
}
}
return true;
}
@Override
public void onDestroyActionMode(ActionMode mode) {
mSelectionMode = Constants.SELECT_SINGLE;
mSelectedLowerBound = -1;
mSelectedUpperBound = -1;
if (getView() != null) {
getGridView().clearChoices();
getGridView().setChoiceMode(AbsListView.CHOICE_MODE_SINGLE);
getGridView().invalidateViews();
}
mMode = null;
}
}
public void changeAnime(String pURL) {
mAnimeUrl = pURL;
getLoaderManager().restartLoader(0, null, this);
}
public void refresh() {
if (mAdapter != null) {
mAdapter.checkEpisodeStatus();
mAdapter.notifyDataSetChanged();
}
}
public void refresh(String animeURL) {
if (mAdapter != null) {
if (TextUtils.equals(animeURL, mAnimeUrl) && !mIsViewing) {
mAdapter.checkEpisodeStatus();
mAdapter.notifyDataSetChanged();
}
}
}
public void refresh(final String pAnimeURL, final String pEpisodeURL) {
WriteLog.appendLog("Refreshing episodes");
if (mAdapter != null) {
//mAdapter.checkEpisodeStatus(pAnimeURL, pEpisodeURL);
mAdapter.notifyDataSetChanged();
}
}
public void refreshEpisode(String animeURL, String episodeURL, int episodePos) {
if (mAdapter != null) {
if (TextUtils.equals(animeURL, mAnimeUrl) && !mIsViewing) {
//mAdapter.checkEpisodeStatus(episodeURL, episodePos);
mAdapter.notifyDataSetChanged();
}
}
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public static class MarkEpisodeDialog extends DialogFragment {
private EditText mRangeStart;
private EditText mRangeEnd;
protected int mType;
protected int mRangeMin;
protected int mRangeMax;
protected int mInputType;
protected int mInputType2;
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
public MarkEpisodeDialog newInstance(int type) {
MarkEpisodeDialog f = new MarkEpisodeDialog();
// Supply index input as an argument.
Bundle args = new Bundle();
args.putInt("type", type);
f.setArguments(args);
return f;
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
LayoutInflater inflater = LayoutInflater.from(getActivity());
final View lView = inflater.inflate(R.layout.dialog_input,
null);
super.onCreate(savedInstanceState);
Bundle args = getArguments();
mType = args.getInt("type", -1);
mInputType = args.getInt("itype", -1);
mInputType2 = args.getInt("itype2", -1);
mRangeMin = args.getInt("min", 0);
mRangeMax = args.getInt("max", 1);
mRangeStart = (EditText) lView.findViewById(R.id.dlg_input1);
mRangeEnd = (EditText) lView.findViewById(R.id.dlg_input2);
if (mInputType == -1)
mInputType = InputType.TYPE_NULL;
if (mInputType2 == -1)
mInputType2 = mInputType;
mRangeStart.setText("" + mRangeMin);
mRangeEnd.setText("" + mRangeMax);
if (mRangeStart != null) {
mRangeStart.setInputType(mInputType);
}
if (mRangeEnd != null) {
mRangeEnd.setInputType(mInputType2);
}
return new AlertDialog.Builder(getActivity())
.setView(lView)
.setCancelable(true)
.setTitle(mType == 1 ? getString(R.string.mark_viewed) : getString(R.string.mark_unviewed))
.setPositiveButton(R.string.ok, new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
try {
int rangeStart = Integer.parseInt(mRangeStart.getText().toString());
int rangeEnd = Integer.parseInt(mRangeEnd.getText().toString());
if (rangeStart >= mRangeMin - 1 && rangeEnd <= mRangeMax) {
dialog.dismiss();
for (int i = rangeStart; i < rangeEnd; i++) {
((LibraryMaterialFragment) getTargetFragment()).changeViewedStatusByPosition(i, mType == 1 ? true : false);
}
//((MainActivity) getActivity()).refresh();
}
} catch (NumberFormatException e) {
WriteLog.appendLog(Log.getStackTraceString(e));
e.printStackTrace();
}
}
})
.setNegativeButton(R.string.cancel, new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
}).create();
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public void onDestroyView() // necessary for restoring the dialog
{
if (getDialog() != null && getRetainInstance())
getDialog().setOnDismissListener(null);
super.onDestroyView();
}
}
@Override
public void onRefresh() {
getLoaderManager().restartLoader(0, null, this);
}
} | apache-2.0 |
ryandcarter/hybris-connector | src/main/java/org/mule/modules/hybris/model/CompositeCronJobDTO.java | 4212 | //
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2013.11.29 at 12:35:53 PM GMT
//
package org.mule.modules.hybris.model;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for compositeCronJobDTO complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="compositeCronJobDTO">
* <complexContent>
* <extension base="{}cronJobDTO">
* <sequence>
* <element name="compositeEntries" minOccurs="0">
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="compositeEntry" type="{}compositeEntryDTO" maxOccurs="unbounded" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </element>
* </sequence>
* </extension>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "compositeCronJobDTO", propOrder = {
"compositeEntries"
})
public class CompositeCronJobDTO
extends CronJobDTO
{
protected CompositeCronJobDTO.CompositeEntries compositeEntries;
/**
* Gets the value of the compositeEntries property.
*
* @return
* possible object is
* {@link CompositeCronJobDTO.CompositeEntries }
*
*/
public CompositeCronJobDTO.CompositeEntries getCompositeEntries() {
return compositeEntries;
}
/**
* Sets the value of the compositeEntries property.
*
* @param value
* allowed object is
* {@link CompositeCronJobDTO.CompositeEntries }
*
*/
public void setCompositeEntries(CompositeCronJobDTO.CompositeEntries value) {
this.compositeEntries = value;
}
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="compositeEntry" type="{}compositeEntryDTO" maxOccurs="unbounded" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"compositeEntry"
})
public static class CompositeEntries {
protected List<CompositeEntryDTO> compositeEntry;
/**
* Gets the value of the compositeEntry property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the compositeEntry property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getCompositeEntry().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link CompositeEntryDTO }
*
*
*/
public List<CompositeEntryDTO> getCompositeEntry() {
if (compositeEntry == null) {
compositeEntry = new ArrayList<CompositeEntryDTO>();
}
return this.compositeEntry;
}
}
}
| apache-2.0 |
spohnan/geowave | test/src/main/java/org/locationtech/geowave/test/KuduLocal.java | 9524 | /**
* Copyright (c) 2013-2019 Contributors to the Eclipse Foundation
*
* See the NOTICE file distributed with this work for additional information regarding copyright
* ownership. All rights reserved. This program and the accompanying materials are made available
* under the terms of the Apache License, Version 2.0 which accompanies this distribution and is
* available at http://www.apache.org/licenses/LICENSE-2.0.txt
*/
package org.locationtech.geowave.test;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.compress.archivers.ArchiveEntry;
import org.apache.commons.compress.archivers.ArchiveException;
import org.apache.commons.compress.archivers.ArchiveInputStream;
import org.apache.commons.compress.archivers.ArchiveStreamFactory;
import org.apache.commons.exec.CommandLine;
import org.apache.commons.exec.DefaultExecuteResultHandler;
import org.apache.commons.exec.DefaultExecutor;
import org.apache.commons.exec.ExecuteException;
import org.apache.commons.exec.ExecuteWatchdog;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.codehaus.plexus.archiver.tar.TarGZipUnArchiver;
import org.codehaus.plexus.logging.console.ConsoleLogger;
import com.jcraft.jsch.Logger;
public class KuduLocal {
// Tracking the cloudera precompiled package
// https://www.cloudera.com/documentation/enterprise/5-16-x/topics/cdh_ig_yumrepo_local_create.html#topic_30__section_sl2_xdw_wm
private static final org.slf4j.Logger LOGGER = org.slf4j.LoggerFactory.getLogger(KuduLocal.class);
private static final String KUDU_REPO_URL =
"https://archive.cloudera.com/cdh5/ubuntu/xenial/amd64/cdh/pool/contrib/k/kudu/";
private static final String KUDU_DEB_PACKAGE =
"kudu_1.7.0+cdh5.16.1+0-1.cdh5.16.1.p0.3~xenial-cdh5.16.1_amd64.deb";
private static final String KUDU_MASTER = "kudu-master";
private static final String KUDU_TABLET = "kudu-tserver";
private static final long STARTUP_DELAY_MS = 1500L;
private final int numTablets;
private final File kuduLocalDir;
private final File kuduDBDir; // storage for database files
// require a separate watchdog for each master/tablet server
private final List<ExecuteWatchdog> watchdogs;
public KuduLocal(final String localDir, final int numTablets) {
if (TestUtils.isSet(localDir)) {
kuduLocalDir = new File(localDir);
} else {
kuduLocalDir = new File(TestUtils.TEMP_DIR, "kudu");
}
if (!kuduLocalDir.exists() && !kuduLocalDir.mkdirs()) {
LOGGER.error("unable to create directory {}", kuduLocalDir.getAbsolutePath());
} else if (!kuduLocalDir.isDirectory()) {
LOGGER.error("{} exists but is not a directory", kuduLocalDir.getAbsolutePath());
}
kuduDBDir = new File(kuduLocalDir, "db");
watchdogs = new ArrayList<>();
this.numTablets = numTablets;
}
public boolean start() {
if (!isInstalled()) {
try {
if (!install()) {
return false;
}
} catch (IOException | ArchiveException e) {
LOGGER.error("Kudu installation error: {}", e.getMessage());
return false;
}
}
try {
startKuduLocal();
} catch (IOException | InterruptedException e) {
LOGGER.error("Kudu start error: {}", e.getMessage());
return false;
}
return true;
}
public boolean isRunning() {
return watchdogs.stream().anyMatch(w -> w.isWatching());
}
public void stop() {
for (final ExecuteWatchdog w : watchdogs) {
w.destroyProcess();
}
try {
Thread.sleep(STARTUP_DELAY_MS);
} catch (final InterruptedException e) {
}
}
public void destroyDB() throws IOException {
try {
FileUtils.deleteDirectory(kuduDBDir);
} catch (final IOException e) {
LOGGER.error("Could not destroy database files", e);
throw e;
}
}
private boolean isInstalled() {
final File kuduMasterBinary = new File(kuduLocalDir, KUDU_MASTER);
final File kuduTabletBinary = new File(kuduLocalDir, KUDU_TABLET);
final boolean okMaster = kuduMasterBinary.exists() && kuduMasterBinary.canExecute();
final boolean okTablet = kuduTabletBinary.exists() && kuduTabletBinary.canExecute();
return okMaster && okTablet;
}
private boolean install() throws IOException, ArchiveException {
LOGGER.info("Installing {}", KUDU_DEB_PACKAGE);
LOGGER.debug("downloading kudu debian package");
final File debPackageFile = new File(kuduLocalDir, KUDU_DEB_PACKAGE);
if (!debPackageFile.exists()) {
HttpURLConnection.setFollowRedirects(true);
final URL url = new URL(KUDU_REPO_URL + KUDU_DEB_PACKAGE);
try (FileOutputStream fos = new FileOutputStream(debPackageFile)) {
IOUtils.copy(url.openStream(), fos);
fos.flush();
}
}
LOGGER.debug("extracting kudu debian package data contents");
final File debDataTarGz = new File(kuduLocalDir, "data.tar.gz");
if (!debDataTarGz.exists()) {
try (FileInputStream fis = new FileInputStream(debPackageFile);
ArchiveInputStream debInputStream =
new ArchiveStreamFactory().createArchiveInputStream("ar", fis)) {
ArchiveEntry entry = null;
while ((entry = debInputStream.getNextEntry()) != null) {
if (debDataTarGz.getName().equals(entry.getName())) {
try (FileOutputStream fos = new FileOutputStream(debDataTarGz)) {
IOUtils.copy(debInputStream, fos);
}
break;
}
}
}
}
LOGGER.debug("extracting kudu data contents");
final TarGZipUnArchiver unarchiver = new TarGZipUnArchiver();
unarchiver.enableLogging(new ConsoleLogger(Logger.WARN, "Kudu Local Unarchive"));
unarchiver.setSourceFile(debDataTarGz);
unarchiver.setDestDirectory(kuduLocalDir);
unarchiver.extract();
for (final File f : new File[] {debPackageFile, debDataTarGz}) {
if (!f.delete()) {
LOGGER.warn("cannot delete {}", f.getAbsolutePath());
}
}
LOGGER.debug("moving kudu master and tablet binaries to {}", kuduLocalDir);
// move the master and tablet server binaries into the kudu local directory
final Path kuduBin =
Paths.get(kuduLocalDir.getAbsolutePath(), "usr", "lib", "kudu", "sbin-release");
final File kuduMasterBinary = kuduBin.resolve(KUDU_MASTER).toFile();
final File kuduTabletBinary = kuduBin.resolve(KUDU_TABLET).toFile();
kuduMasterBinary.setExecutable(true);
kuduTabletBinary.setExecutable(true);
FileUtils.moveFileToDirectory(kuduMasterBinary, kuduLocalDir, false);
FileUtils.moveFileToDirectory(kuduTabletBinary, kuduLocalDir, false);
if (isInstalled()) {
LOGGER.info("Kudu Local installation successful");
return true;
} else {
LOGGER.error("Kudu Local installation failed");
return false;
}
}
private void executeAsyncAndWatch(final CommandLine command)
throws ExecuteException, IOException {
LOGGER.info("Running async: {}", command.toString());
final ExecuteWatchdog watchdog = new ExecuteWatchdog(ExecuteWatchdog.INFINITE_TIMEOUT);
final DefaultExecutor executor = new DefaultExecutor();
executor.setWatchdog(watchdog);
executor.setWorkingDirectory(kuduLocalDir);
watchdogs.add(watchdog);
// Using a result handler makes the local instance run async
executor.execute(command, new DefaultExecuteResultHandler());
}
private void startKuduLocal() throws ExecuteException, IOException, InterruptedException {
if (!kuduDBDir.exists() && !kuduDBDir.mkdirs()) {
LOGGER.error("unable to create directory {}", kuduDBDir.getAbsolutePath());
} else if (!kuduDBDir.isDirectory()) {
LOGGER.error("{} exists but is not a directory", kuduDBDir.getAbsolutePath());
}
final File kuduMasterBinary = new File(kuduLocalDir.getAbsolutePath(), KUDU_MASTER);
final File kuduTabletBinary = new File(kuduLocalDir.getAbsolutePath(), KUDU_TABLET);
final CommandLine startMaster = new CommandLine(kuduMasterBinary.getAbsolutePath());
startMaster.addArgument("--fs_data_dirs");
startMaster.addArgument(new File(kuduDBDir, "master_fs_data").getAbsolutePath());
startMaster.addArgument("--fs_metadata_dir");
startMaster.addArgument(new File(kuduDBDir, "master_fs_metadata").getAbsolutePath());
startMaster.addArgument("--fs_wal_dir");
startMaster.addArgument(new File(kuduDBDir, "master_fs_wal").getAbsolutePath());
executeAsyncAndWatch(startMaster);
for (int i = 0; i < numTablets; i++) {
final CommandLine startTablet = new CommandLine(kuduTabletBinary.getAbsolutePath());
startTablet.addArgument("--fs_data_dirs");
startTablet.addArgument(new File(kuduDBDir, "t" + i + "_fs_data").getAbsolutePath());
startTablet.addArgument("--fs_metadata_dir");
startTablet.addArgument(new File(kuduDBDir, "t" + i + "_fs_metadata").getAbsolutePath());
startTablet.addArgument("--fs_wal_dir");
startTablet.addArgument(new File(kuduDBDir, "t" + i + "_fs_wal").getAbsolutePath());
executeAsyncAndWatch(startTablet);
}
Thread.sleep(STARTUP_DELAY_MS);
}
public static void main(final String[] args) {
final KuduLocal kudu = new KuduLocal(null, 1);
kudu.start();
}
}
| apache-2.0 |
GitHubAFeng/AFengAndroid | app/src/main/java/com/afeng/xf/ui/home/AboutMeActivity.java | 637 | package com.afeng.xf.ui.home;
import android.os.Bundle;
import com.afeng.xf.R;
import com.afeng.xf.base.BaseActivity;
import com.afeng.xf.utils.AFengUtils.StatusBarUtil;
/**
* Created by Administrator on 2017/6/26.
*/
public class AboutMeActivity extends BaseActivity {
@Override
protected int getLayoutId() {
return R.layout.activity_aboutme;
}
@Override
protected void initView(Bundle savedInstanceState) {
StatusBarUtil.hideSystemUI(this);
}
@Override
protected void setListener() {
}
@Override
protected void processLogic(Bundle savedInstanceState) {
}
}
| apache-2.0 |
wbsimms/TouchPiano | SimpleBuzzer/Resources.Designer.cs | 1297 | //------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.1
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace SimpleBuzzer
{
internal partial class Resources
{
private static System.Resources.ResourceManager manager;
internal static System.Resources.ResourceManager ResourceManager
{
get
{
if ((Resources.manager == null))
{
Resources.manager = new System.Resources.ResourceManager("SimpleBuzzer.Resources", typeof(Resources).Assembly);
}
return Resources.manager;
}
}
internal static Microsoft.SPOT.Font GetFont(Resources.FontResources id)
{
return ((Microsoft.SPOT.Font)(Microsoft.SPOT.ResourceUtility.GetObject(ResourceManager, id)));
}
[System.SerializableAttribute()]
internal enum FontResources : short
{
small = 13070,
NinaB = 18060,
}
}
}
| apache-2.0 |
vyouzhis/tea | src/com/lib/manager/admin_index.java | 1006 | package com.lib.manager;
import org.ppl.BaseClass.Permission;
import org.ppl.common.ShowMessage;
public class admin_index extends Permission {
public admin_index() {
// TODO Auto-generated constructor stub
String className = this.getClass().getCanonicalName();
// stdClass = className;
super.GetSubClassName(className);
}
@Override
public void Show() {
// TODO Auto-generated method stub
if (super.Init() == -1)
return;
String update = porg.getKey("update");
if(FoundRole()==-1 && update==null){
ShowMessage sm = ShowMessage.getInstance();
sm.forward("?update=1");
}
if(update!=null && Integer.valueOf(update)==1){
InitRole();
}
super.View();
}
public int FoundRole() {
String role = aclfetchMyRole();
if (role == null || role.length() < 2) {
return -1;
}
return 0;
}
public void InitRole() {
if(RoleUpdate()==0){
setRoot("role_update_tip", _CLang("ok_role_update"));
}
}
} | apache-2.0 |
mozilla-metrics/akela | src/main/java/com/mozilla/pig/eval/regex/EncodeChromeUrl.java | 1589 | /**
* Copyright 2010 Mozilla Foundation
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.mozilla.pig.eval.regex;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.pig.EvalFunc;
import org.apache.pig.data.Tuple;
/**
* EncodeChromeUrl is designed as a hack fix to some of our log data that
* contains URLs that have a bad unencoded piece of data.
*/
public class EncodeChromeUrl extends EvalFunc<String> {
private static final Pattern p = Pattern.compile("chrome://global/locale/intl.properties");
public String exec(Tuple input) throws IOException {
if (input == null || input.size() == 0) {
return null;
}
Matcher m = p.matcher((String)input.get(0));
return m.replaceAll("chrome%3A%2F%2Fglobal%2Flocale%2Fintl.properties");
}
}
| apache-2.0 |
ma459006574/pentaho-kettle | ui/src/org/pentaho/di/ui/core/dialog/Splash.java | 9220 | /*! ******************************************************************************
*
* Pentaho Data Integration
*
* Copyright (C) 2002-2013 by Pentaho : http://www.pentaho.com
*
*******************************************************************************
*
* 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.pentaho.di.ui.core.dialog;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Calendar;
import java.util.Timer;
import java.util.TimerTask;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.DisposeEvent;
import org.eclipse.swt.events.DisposeListener;
import org.eclipse.swt.events.PaintEvent;
import org.eclipse.swt.events.PaintListener;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.pentaho.di.core.Const;
import org.pentaho.di.core.SwtUniversalImage;
import org.pentaho.di.core.exception.KettleException;
import org.pentaho.di.core.logging.LogChannel;
import org.pentaho.di.core.logging.LogChannelInterface;
import org.pentaho.di.i18n.BaseMessages;
import org.pentaho.di.laf.BasePropertyHandler;
import org.pentaho.di.ui.spoon.Spoon;
import org.pentaho.di.ui.util.SwtSvgImageUtil;
import org.pentaho.di.version.BuildVersion;
/**
* Displays the Kettle splash screen
*
* @author Matt
* @since 14-mrt-2005
*/
public class Splash {
private Shell splash;
private Image kettle_image;
private Image kettle_icon;
private Image exclamation_image;
private Font verFont;
private Font licFont;
private Font devWarningFont;
private Color versionWarningBackgroundColor;
private Color versionWarningForegroundColor;
private int licFontSize = 8;
private static Class<?> PKG = Splash.class; // for i18n purposes, needed by Translator2!!
private static LogChannelInterface log;
public Splash( Display display ) throws KettleException {
log = new LogChannel( Spoon.APP_NAME );
Rectangle displayBounds = display.getPrimaryMonitor().getBounds();
// "kettle_splash.png"
kettle_image = loadAsResource( display, BasePropertyHandler.getProperty( "splash_image" ) );
// "spoon.ico"
kettle_icon = loadAsResource( display, BasePropertyHandler.getProperty( "splash_icon" ) );
// "exclamation.png"
exclamation_image = loadAsResource( display, BasePropertyHandler.getProperty( "exclamation_image" ) );
verFont = new Font( display, "Helvetica", 11, SWT.BOLD );
licFont = new Font( display, "Helvetica", licFontSize, SWT.NORMAL );
devWarningFont = new Font( display, "Helvetica", 10, SWT.NORMAL );
// versionWarningBackgroundColor = new Color(display, 255, 253, 213);
versionWarningBackgroundColor = new Color( display, 255, 255, 255 );
versionWarningForegroundColor = new Color( display, 220, 177, 20 );
splash = new Shell( display, SWT.APPLICATION_MODAL );
splash.setImage( kettle_icon );
splash.setText( BaseMessages.getString( PKG, "SplashDialog.Title" ) ); // "Pentaho Data Integration"
splash.addPaintListener( new PaintListener() {
public void paintControl( PaintEvent e ) {
String versionText =
BaseMessages.getString( PKG, "SplashDialog.Version" ) + " " + BuildVersion.getInstance().getVersion();
StringBuilder sb = new StringBuilder();
String line = null;
try {
BufferedReader reader =
new BufferedReader( new InputStreamReader( Splash.class.getClassLoader().getResourceAsStream(
"org/pentaho/di/ui/core/dialog/license/license.txt" ) ) );
while ( ( line = reader.readLine() ) != null ) {
sb.append( line + System.getProperty( "line.separator" ) );
}
} catch ( Exception ex ) {
sb.append( "" );
log.logError( BaseMessages.getString( PKG, "SplashDialog.LicenseTextNotFound" ), ex );
}
Calendar cal = Calendar.getInstance();
String licenseText = String.format( sb.toString(), cal );
e.gc.drawImage( kettle_image, 0, 0 );
// If this is a Milestone or RC release, warn the user
if ( Const.RELEASE.equals( Const.ReleaseType.MILESTONE ) ) {
versionText = BaseMessages.getString( PKG, "SplashDialog.DeveloperRelease" ) + " - " + versionText;
drawVersionWarning( e );
} else if ( Const.RELEASE.equals( Const.ReleaseType.RELEASE_CANDIDATE ) ) {
versionText = BaseMessages.getString( PKG, "SplashDialog.ReleaseCandidate" ) + " - " + versionText;
} else if ( Const.RELEASE.equals( Const.ReleaseType.PREVIEW ) ) {
versionText = BaseMessages.getString( PKG, "SplashDialog.PreviewRelease" ) + " - " + versionText;
} else if ( Const.RELEASE.equals( Const.ReleaseType.GA ) ) {
versionText = BaseMessages.getString( PKG, "SplashDialog.GA" ) + " - " + versionText;
}
e.gc.setFont( verFont );
e.gc.drawText( versionText, 290, 205, true );
// try using the desired font size for the license text
e.gc.setFont( licFont );
// if the text will not fit the allowed space
while ( !willLicenseTextFit( licenseText, e.gc ) ) {
licFontSize--;
if ( licFont != null ) {
licFont.dispose();
}
licFont = new Font( e.display, "Helvetica", licFontSize, SWT.NORMAL );
e.gc.setFont( licFont );
}
e.gc.drawText( licenseText, 290, 290, true );
}
} );
splash.addDisposeListener( new DisposeListener() {
public void widgetDisposed( DisposeEvent arg0 ) {
kettle_image.dispose();
kettle_icon.dispose();
exclamation_image.dispose();
verFont.dispose();
licFont.dispose();
devWarningFont.dispose();
versionWarningForegroundColor.dispose();
versionWarningBackgroundColor.dispose();
}
} );
Rectangle bounds = kettle_image.getBounds();
int x = ( displayBounds.width - bounds.width ) / 2;
int y = ( displayBounds.height - bounds.height ) / 2;
splash.setSize( bounds.width, bounds.height );
splash.setLocation( x, y );
splash.open();
TimerTask timerTask = new TimerTask() {
@Override
public void run() {
try {
splash.redraw();
LogChannel.UI.logBasic( "Redraw!" );
} catch ( Throwable e ) {
// ignore.
}
}
};
final Timer timer = new Timer();
timer.schedule( timerTask, 0, 100 );
splash.addDisposeListener( new DisposeListener() {
public void widgetDisposed( DisposeEvent arg0 ) {
timer.cancel();
}
} );
}
// load image from svg
private Image loadAsResource( Display display, String location ) {
SwtUniversalImage img = SwtSvgImageUtil.getImageAsResource( display, location );
Image image = new Image( display, img.getAsBitmap( display ), SWT.IMAGE_COPY );
img.dispose();
return image;
}
// determine if the license text will fit the allocated space
private boolean willLicenseTextFit( String licenseText, GC gc ) {
Point splashSize = splash.getSize();
Point licenseDrawLocation = new Point( 290, 290 );
Point requiredSize = gc.textExtent( licenseText );
int width = splashSize.x - licenseDrawLocation.x;
int height = splashSize.y - licenseDrawLocation.y;
boolean fitsVertically = width >= requiredSize.x;
boolean fitsHorizontally = height >= requiredSize.y;
return ( fitsVertically && fitsHorizontally );
}
private void drawVersionWarning( PaintEvent e ) {
drawVersionWarning( e.gc, e.display );
}
private void drawVersionWarning( GC gc, Display display ) {
gc.setBackground( versionWarningBackgroundColor );
gc.setForeground( versionWarningForegroundColor );
// gc.fillRectangle(290, 231, 367, 49);
// gc.drawRectangle(290, 231, 367, 49);
gc.setForeground( display.getSystemColor( SWT.COLOR_BLACK ) );
gc.drawImage( exclamation_image, 304, 243 );
gc.setFont( devWarningFont );
gc.drawText( BaseMessages.getString( PKG, "SplashDialog.DevelopmentWarning" ), 335, 241, true );
}
public void dispose() {
if ( !splash.isDisposed() ) {
splash.dispose();
}
}
public void hide() {
if ( !splash.isDisposed() ) {
splash.setVisible( false );
}
}
public void show() {
if ( !splash.isDisposed() ) {
splash.setVisible( true );
}
}
}
| apache-2.0 |
akiss77/glutin | src/android/mod.rs | 8925 | extern crate android_glue;
use libc;
use std::ffi::{CString};
use std::sync::mpsc::{Receiver, channel};
use {CreationError, Event, WindowBuilder};
use CreationError::OsError;
use events::ElementState::{Pressed, Released};
use events::Event::{MouseInput, MouseMoved};
use events::MouseButton::LeftMouseButton;
use std::collections::RingBuf;
use BuilderAttribs;
pub struct Window {
display: ffi::egl::types::EGLDisplay,
context: ffi::egl::types::EGLContext,
surface: ffi::egl::types::EGLSurface,
event_rx: Receiver<android_glue::Event>,
}
pub struct MonitorID;
mod ffi;
pub fn get_available_monitors() -> RingBuf <MonitorID> {
let mut rb = RingBuf::new();
rb.push_back(MonitorID);
rb
}
pub fn get_primary_monitor() -> MonitorID {
MonitorID
}
impl MonitorID {
pub fn get_name(&self) -> Option<String> {
Some("Primary".to_string())
}
pub fn get_dimensions(&self) -> (uint, uint) {
unimplemented!()
}
}
#[cfg(feature = "headless")]
pub struct HeadlessContext(int);
#[cfg(feature = "headless")]
impl HeadlessContext {
/// See the docs in the crate root file.
pub fn new(_builder: BuilderAttribs) -> Result<HeadlessContext, CreationError> {
unimplemented!()
}
/// See the docs in the crate root file.
pub unsafe fn make_current(&self) {
unimplemented!()
}
/// See the docs in the crate root file.
pub fn get_proc_address(&self, _addr: &str) -> *const () {
unimplemented!()
}
pub fn get_api(&self) -> ::Api {
::Api::OpenGl
}
}
#[cfg(feature = "headless")]
unsafe impl Send for HeadlessContext {}
#[cfg(feature = "headless")]
unsafe impl Sync for HeadlessContext {}
impl Window {
pub fn new(builder: BuilderAttribs) -> Result<Window, CreationError> {
use std::{mem, ptr};
if builder.sharing.is_some() {
unimplemented!()
}
let native_window = unsafe { android_glue::get_native_window() };
if native_window.is_null() {
return Err(OsError(format!("Android's native window is null")));
}
let display = unsafe {
let display = ffi::egl::GetDisplay(mem::transmute(ffi::egl::DEFAULT_DISPLAY));
if display.is_null() {
return Err(OsError("No EGL display connection available".to_string()));
}
display
};
android_glue::write_log("eglGetDisplay succeeded");
let (_major, _minor) = unsafe {
let mut major: ffi::egl::types::EGLint = mem::uninitialized();
let mut minor: ffi::egl::types::EGLint = mem::uninitialized();
if ffi::egl::Initialize(display, &mut major, &mut minor) == 0 {
return Err(OsError(format!("eglInitialize failed")))
}
(major, minor)
};
android_glue::write_log("eglInitialize succeeded");
let use_gles2 = match builder.gl_version {
Some((2, 0)) => true,
_ => false,
};
let config = unsafe {
let mut attribute_list = vec!();
if use_gles2 {
attribute_list.push_all(&[ffi::egl::RENDERABLE_TYPE as i32,
ffi::egl::OPENGL_ES2_BIT as i32]);
}
attribute_list.push_all(&[ffi::egl::RED_SIZE as i32, 1]);
attribute_list.push_all(&[ffi::egl::GREEN_SIZE as i32, 1]);
attribute_list.push_all(&[ffi::egl::BLUE_SIZE as i32, 1]);
attribute_list.push(ffi::egl::NONE as i32);
let mut num_config: ffi::egl::types::EGLint = mem::uninitialized();
let mut config: ffi::egl::types::EGLConfig = mem::uninitialized();
if ffi::egl::ChooseConfig(display, attribute_list.as_ptr(), &mut config, 1,
&mut num_config) == 0
{
return Err(OsError(format!("eglChooseConfig failed")))
}
if num_config <= 0 {
return Err(OsError(format!("eglChooseConfig returned no available config")))
}
config
};
android_glue::write_log("eglChooseConfig succeeded");
let context = unsafe {
let mut context_attributes = vec!();
if use_gles2 {
context_attributes.push_all(&[ffi::egl::CONTEXT_CLIENT_VERSION as i32, 2]);
}
context_attributes.push(ffi::egl::NONE as i32);
let context = ffi::egl::CreateContext(display, config, ptr::null(),
context_attributes.as_ptr());
if context.is_null() {
return Err(OsError(format!("eglCreateContext failed")))
}
context
};
android_glue::write_log("eglCreateContext succeeded");
let surface = unsafe {
let surface = ffi::egl::CreateWindowSurface(display, config, native_window, ptr::null());
if surface.is_null() {
return Err(OsError(format!("eglCreateWindowSurface failed")))
}
surface
};
android_glue::write_log("eglCreateWindowSurface succeeded");
let (tx, rx) = channel();
android_glue::add_sender(tx);
Ok(Window {
display: display,
context: context,
surface: surface,
event_rx: rx,
})
}
pub fn is_closed(&self) -> bool {
false
}
pub fn set_title(&self, _: &str) {
}
pub fn show(&self) {
}
pub fn hide(&self) {
}
pub fn get_position(&self) -> Option<(int, int)> {
None
}
pub fn set_position(&self, _x: int, _y: int) {
}
pub fn get_inner_size(&self) -> Option<(uint, uint)> {
let native_window = unsafe { android_glue::get_native_window() };
if native_window.is_null() {
None
} else {
Some((
unsafe { ffi::ANativeWindow_getWidth(native_window) } as uint,
unsafe { ffi::ANativeWindow_getHeight(native_window) } as uint
))
}
}
pub fn get_outer_size(&self) -> Option<(uint, uint)> {
self.get_inner_size()
}
pub fn set_inner_size(&self, _x: uint, _y: uint) {
}
pub fn create_window_proxy(&self) -> WindowProxy {
WindowProxy
}
pub fn poll_events(&self) -> RingBuf<Event> {
let mut events = RingBuf::new();
loop {
match self.event_rx.try_recv() {
Ok(event) => match event {
android_glue::Event::EventDown => {
events.push_back(MouseInput(Pressed, LeftMouseButton));
},
android_glue::Event::EventUp => {
events.push_back(MouseInput(Released, LeftMouseButton));
},
android_glue::Event::EventMove(x, y) => {
events.push_back(MouseMoved((x as int, y as int)));
},
},
Err(_) => {
break;
},
}
}
events
}
pub fn wait_events(&self) -> RingBuf<Event> {
use std::time::Duration;
use std::io::timer;
timer::sleep(Duration::milliseconds(16));
self.poll_events()
}
pub fn make_current(&self) {
unsafe {
ffi::egl::MakeCurrent(self.display, self.surface, self.surface, self.context);
}
}
pub fn get_proc_address(&self, addr: &str) -> *const () {
let addr = CString::from_slice(addr.as_bytes()).as_slice_with_nul().as_ptr();
unsafe {
ffi::egl::GetProcAddress(addr) as *const ()
}
}
pub fn swap_buffers(&self) {
unsafe {
ffi::egl::SwapBuffers(self.display, self.surface);
}
}
pub fn platform_display(&self) -> *mut libc::c_void {
self.display as *mut libc::c_void
}
pub fn get_api(&self) -> ::Api {
::Api::OpenGlEs
}
pub fn set_window_resize_callback(&mut self, _: Option<fn(uint, uint)>) {
}
pub fn hidpi_factor(&self) -> f32 {
1.0
}
}
unsafe impl Send for Window {}
unsafe impl Sync for Window {}
#[cfg(feature = "window")]
#[derive(Clone)]
pub struct WindowProxy;
impl WindowProxy {
pub fn wakeup_event_loop(&self) {
unimplemented!()
}
}
#[unsafe_destructor]
impl Drop for Window {
fn drop(&mut self) {
use std::ptr;
unsafe {
android_glue::write_log("Destroying gl-init window");
ffi::egl::MakeCurrent(self.display, ptr::null(), ptr::null(), ptr::null());
ffi::egl::DestroySurface(self.display, self.surface);
ffi::egl::DestroyContext(self.display, self.context);
ffi::egl::Terminate(self.display);
}
}
}
| apache-2.0 |
alesj/hs-data-poc | config/src/test/java/me/snowdrop/data/hibernatesearch/config/jpa/standalone/ops/repository/jpa/StandaloneJpaOpsRepository.java | 947 | /*
* Copyright 2017 Red Hat, Inc, and individual contributors.
*
* 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 me.snowdrop.data.hibernatesearch.config.jpa.standalone.ops.repository.jpa;
import me.snowdrop.data.hibernatesearch.ops.SimpleEntity;
import org.springframework.data.repository.PagingAndSortingRepository;
public interface StandaloneJpaOpsRepository
extends PagingAndSortingRepository<SimpleEntity, Long> {
}
| apache-2.0 |
shs96c/buck | src/com/facebook/buck/jvm/java/lang/model/MoreElements.java | 7041 | /*
* Copyright 2017-present Facebook, 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.facebook.buck.jvm.java.lang.model;
import com.facebook.buck.util.liteinfersupport.Nullable;
import com.facebook.buck.util.liteinfersupport.Preconditions;
import java.util.Map;
import java.util.stream.Stream;
import javax.lang.model.element.AnnotationMirror;
import javax.lang.model.element.AnnotationValue;
import javax.lang.model.element.Element;
import javax.lang.model.element.ElementKind;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.element.Modifier;
import javax.lang.model.element.NestingKind;
import javax.lang.model.element.PackageElement;
import javax.lang.model.element.TypeElement;
import javax.lang.model.element.VariableElement;
import javax.lang.model.type.DeclaredType;
import javax.lang.model.type.TypeKind;
import javax.lang.model.type.TypeMirror;
/**
* More utility functions for working with {@link Element}s, along the lines of those found on
* {@link javax.lang.model.util.Elements}.
*/
public final class MoreElements {
private MoreElements() {}
@Nullable
public static TypeElement getSuperclass(TypeElement type) {
TypeMirror superclassType = type.getSuperclass();
switch (superclassType.getKind()) {
case DECLARED:
case ERROR:
return (TypeElement) ((DeclaredType) superclassType).asElement();
case NONE:
return null;
// $CASES-OMITTED$
default:
throw new IllegalArgumentException(superclassType.toString());
}
}
public static Stream<TypeElement> getInterfaces(TypeElement type) {
return type.getInterfaces()
.stream()
.filter(it -> it.getKind() == TypeKind.DECLARED || it.getKind() == TypeKind.ERROR)
.map(it -> (TypeElement) ((DeclaredType) it).asElement());
}
public static Stream<TypeElement> getTransitiveSuperclasses(TypeElement type) {
Stream.Builder<TypeElement> builder = Stream.builder();
TypeElement walker = getSuperclass(type);
while (walker != null) {
builder.add(walker);
walker = getSuperclass(walker);
}
return builder.build();
}
public static boolean isTransitiveMemberClass(TypeElement inner, TypeElement outer) {
Element walker = inner.getEnclosingElement();
while (walker != null) {
if (walker == outer) {
return true;
}
walker = walker.getEnclosingElement();
}
return false;
}
public static TypeElement getTypeElement(Element element) {
if (element.getKind() == ElementKind.PACKAGE) {
throw new IllegalArgumentException();
}
Element walker = element;
while (!walker.getKind().isClass() && !walker.getKind().isInterface()) {
walker = Preconditions.checkNotNull(walker.getEnclosingElement());
}
return (TypeElement) walker;
}
public static TypeElement getTopLevelTypeElement(Element element) {
if (element.getKind() == ElementKind.PACKAGE) {
throw new IllegalArgumentException();
}
Element walker = element;
while (walker.getEnclosingElement() != null
&& walker.getEnclosingElement().getKind() != ElementKind.PACKAGE) {
walker = Preconditions.checkNotNull(walker.getEnclosingElement());
}
return (TypeElement) walker;
}
public static PackageElement getPackageElement(Element element) {
Element walker = element;
while (walker.getKind() != ElementKind.PACKAGE) {
walker = Preconditions.checkNotNull(walker.getEnclosingElement());
}
return (PackageElement) walker;
}
public static boolean isInnerClassConstructor(ExecutableElement e) {
return isConstructor(e) && isInnerClass((TypeElement) e.getEnclosingElement());
}
public static boolean isConstructor(ExecutableElement e) {
return e.getSimpleName().contentEquals("<init>");
}
public static boolean isInnerClass(TypeElement e) {
return e.getNestingKind() == NestingKind.MEMBER && !e.getModifiers().contains(Modifier.STATIC);
}
public static Element getOuterClass(ExecutableElement e) {
Element innerClass = e.getEnclosingElement();
Element outerClass = innerClass.getEnclosingElement();
if (outerClass == null) {
throw new IllegalArgumentException(
String.format("Cannot get outer class of element which isn't an inner class: %s", e));
}
return outerClass;
}
public static boolean isRuntimeRetention(AnnotationMirror annotation) {
DeclaredType annotationType = annotation.getAnnotationType();
TypeElement annotationTypeElement = (TypeElement) annotationType.asElement();
AnnotationMirror retentionAnnotation =
findAnnotation("java.lang.annotation.Retention", annotationTypeElement);
if (retentionAnnotation == null) {
return false;
}
VariableElement retentionPolicy =
(VariableElement)
Preconditions.checkNotNull(findAnnotationValue(retentionAnnotation, "value"));
return retentionPolicy.getSimpleName().contentEquals("RUNTIME");
}
public static boolean isSourceRetention(AnnotationMirror annotation) {
DeclaredType annotationType = annotation.getAnnotationType();
TypeElement annotationTypeElement = (TypeElement) annotationType.asElement();
AnnotationMirror retentionAnnotation =
findAnnotation("java.lang.annotation.Retention", annotationTypeElement);
if (retentionAnnotation == null) {
return false;
}
VariableElement retentionPolicy =
(VariableElement)
Preconditions.checkNotNull(findAnnotationValue(retentionAnnotation, "value"));
return retentionPolicy.getSimpleName().contentEquals("SOURCE");
}
@Nullable
private static AnnotationMirror findAnnotation(CharSequence name, Element element) {
for (AnnotationMirror annotationMirror : element.getAnnotationMirrors()) {
DeclaredType annotationType = annotationMirror.getAnnotationType();
TypeElement annotationTypeElement = (TypeElement) annotationType.asElement();
if (annotationTypeElement.getQualifiedName().contentEquals(name)) {
return annotationMirror;
}
}
return null;
}
@Nullable
private static Object findAnnotationValue(AnnotationMirror annotation, String name) {
for (Map.Entry<? extends ExecutableElement, ? extends AnnotationValue> entry :
annotation.getElementValues().entrySet()) {
if (entry.getKey().getSimpleName().contentEquals(name)) {
return entry.getValue().getValue();
}
}
return null;
}
}
| apache-2.0 |
lukiano/monadasync | scalaz/src/main/scala/monadasync/AsyncSemaphore.scala | 4823 | package monadasync
import java.util.concurrent.RejectedExecutionException
import scalaz.syntax.catchable._
import scalaz.syntax.monad._
import MonadAsync.syntax._
import scalaz.{ -\/, \/-, Catchable, Monad }
// Based on the one from Twitter-Util, but applies to any MonadAsync
class AsyncSemaphore[F[_]: MonadAsync: Monad: Catchable] protected (initialPermits: Int, maxWaiters: Option[Int]) {
/**
* Constructs a semaphore with no limit on the max number
* of waiters for permits.
*
* @param initialPermits must be positive
*/
def this(initialPermits: Int) = this(initialPermits, None)
/**
* Constructs a semaphore with `maxWaiters` as the limit on the
* number of waiters for permits.
*
* @param initialPermits must be positive
* @param maxWaiters must be non-negative
*/
def this(initialPermits: Int, maxWaiters: Int) = this(initialPermits, Some(maxWaiters))
require(maxWaiters.getOrElse(0) >= 0, s"maxWaiters must be non-negative: $maxWaiters")
require(initialPermits > 0, s"initialPermits must be positive: $initialPermits")
private[this] val waitq = new java.util.ArrayDeque[Permit => Unit]
private[this] var availablePermits = initialPermits
final class SemaphorePermit extends Permit {
/**
* Indicate that you are done with your Permit.
*/
def release(): Unit = {
AsyncSemaphore.this.synchronized {
Option(waitq.pollFirst()) match {
case Some(next) => next(new SemaphorePermit)
case None => availablePermits += 1
}
}
}
}
def numWaiters: Int = synchronized(waitq.size)
def numInitialPermits: Int = initialPermits
def numPermitsAvailable: Int = synchronized(availablePermits)
/**
* Acquire a Permit, asynchronously. Be sure to permit.release() in a 'finally'
* block of your onSuccess() callback.
*
* Interrupting this future is only advisory, and will not release the permit
* if the future has already been satisfied.
*
* @return a Future[Permit] when the Future is satisfied, computation can proceed,
* or a Future.Exception[RejectedExecutionException] if the configured maximum number of waitq
* would be exceeded.
*/
def acquire(): F[Permit] = {
synchronized {
if (availablePermits > 0) {
availablePermits -= 1
MonadAsync[F].now(new SemaphorePermit)
} else {
maxWaiters match {
case Some(max) if waitq.size >= max =>
Catchable[F].fail(new RejectedExecutionException("Max waiters exceeded"))
case _ =>
MonadAsync[F].async[Permit](waitq.addLast _)
}
}
}
}
/**
* Execute the function asynchronously when a permit becomes available.
*
* If the function throws a non-fatal exception, the exception is returned as part of the Future.
* For all exceptions, the permit would be released before returning.
*
* @return a Future[T] equivalent to the return value of the input function. If the configured
* maximum value of waitq is reached, Future.Exception[RejectedExecutionException] is
* returned.
*/
def acquireAndRun[T](func: => F[T]): F[T] =
acquire() flatMap { permit =>
try {
func.attempt flatMap {
case \/-(a) =>
permit.release()
a.now
case -\/(e) =>
permit.release()
Catchable[F].fail(e)
}
} catch {
case scala.util.control.NonFatal(e) =>
permit.release()
Catchable[F].fail(e)
case e: Throwable =>
permit.release()
throw e
}
}
/**
* Execute the function when a permit becomes available.
*
* If the function throws an exception, the exception is returned as part of the Future.
* For all exceptions, the permit would be released before returning.
*
* @return a Future[T] equivalent to the return value of the input function. If the configured
* maximum value of waitq is reached, Future.Exception[RejectedExecutionException] is
* returned.
*/
def acquireAndRunSync[T](func: => T): F[T] =
acquire() flatMap { permit =>
try {
val t = func
permit.release()
t.now
} catch {
case e: Throwable =>
permit.release()
Catchable[F].fail(e)
}
}
}
class AsyncMutex[F[_]: MonadAsync: Monad: Catchable] protected (maxWaiters: Option[Int]) extends AsyncSemaphore[F](1, maxWaiters) {
/**
* Constructs a mutex with no limit on the max number
* of waiters for permits.
*/
def this() = this(None)
/**
* Constructs a mutex with `maxWaiters` as the limit on the
* number of waiters for permits.
*/
def this(maxWaiters: Int) = this(Some(maxWaiters))
}
trait Permit {
def release(): Unit
}
| apache-2.0 |
ranoble/Megapode | src/main/java/com/gravspace/calculation/form/CookieParser.java | 1690 | package com.gravspace.calculation.form;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import org.apache.http.Header;
import scala.concurrent.Future;
import akka.actor.ActorRef;
import akka.actor.UntypedActorContext;
import akka.dispatch.Futures;
import com.gravspace.abstractions.ICalculation;
import com.gravspace.annotations.Calculation;
import com.gravspace.bases.CalculationBase;
import com.gravspace.util.Layers;
@Calculation
public class CookieParser extends CalculationBase implements ICalculation, ICookieParser {
public CookieParser(Map<Layers, ActorRef> routers,
ActorRef coordinatingActor, UntypedActorContext actorContext) {
super(routers, coordinatingActor, actorContext);
}
@Override
public Future<Map<String, String>> parseCookies(Header[] headers) {
for (Header header: headers){
if (StringUtils.equalsIgnoreCase(header.getName(), "cookie")){
return Futures.successful(parseCookies(header.getValue()));
}
}
Map<String, String> cookies = new HashMap<String, String>();
return Futures.successful(cookies);
}
public Map<String, String> parseCookies(String cookiePayload){
Map<String, String> cookies = new HashMap<String, String>();
String[] cookieStrings = StringUtils.split(cookiePayload, ";");
for (String cookie: cookieStrings){
String[] cookieValues = StringUtils.split(cookie.trim(), "=", 2);
try {
cookies.put(URLDecoder.decode(cookieValues[0].trim(), "UTF-8"),
URLDecoder.decode(cookieValues[1].trim(), "UTF-8"));
} catch (UnsupportedEncodingException e) {}
}
return cookies;
}
}
| apache-2.0 |
migzai/irc-api | src/test/java/com/ircclouds/irc/api/comms/MockConnectionImpl.java | 1268 | package com.ircclouds.irc.api.comms;
import java.io.*;
import java.net.*;
import java.nio.*;
import javax.net.ssl.*;
import mockit.*;
public class MockConnectionImpl implements IConnection
{
private BufferedReader reader;
private String filename;
private CharBuffer buffer = CharBuffer.allocate(2048);
public MockConnectionImpl(String aFileName)
{
filename = aFileName;
}
@Mock
public boolean open(String aHostname, int aPort, SSLContext aCtx, Proxy aProxy, boolean aResolveByProxy) throws IOException
{
InputStream _resourceAsStream = MockConnectionImpl.class.getResourceAsStream(filename);
if (_resourceAsStream != null)
{
return (reader = new BufferedReader(new InputStreamReader(_resourceAsStream))).ready();
}
throw new RuntimeException("Error locating resource.");
}
@Mock
public void close() throws IOException
{
if (reader != null)
{
reader.close();
}
}
@Mock
public int write(String aMessage) throws IOException
{
return aMessage.length();
}
@Mock
public String read() throws IOException
{
buffer.clear();
if (reader.read(buffer) == -1)
{
throw new EndOfStreamException();
}
buffer.flip();
return buffer.toString();
}
}
| apache-2.0 |
icza/sc2gears | src-sc2gearspluginapi/hu/belicza/andras/sc2gearspluginapi/impl/util/WordCloudTableInput.java | 1844 | /*
* Project Sc2gears
*
* Copyright (c) 2010 Andras Belicza <iczaaa@gmail.com>
*
* This software is the property of Andras Belicza.
* Copying, modifying, distributing, refactoring without the authors permission
* is prohibited and protected by Law.
*/
package hu.belicza.andras.sc2gearspluginapi.impl.util;
import hu.belicza.andras.sc2gearspluginapi.api.GuiUtilsApi;
/**
* A wrapper class that holds the information required to create and show a Word Cloud dialog taking a table as the input.
*
* @since "2.3"
*
* @author Andras Belicza
*
* @see GuiUtilsApi#createTableBox(javax.swing.JTable, javax.swing.JComponent, WordCloudTableInput)
*/
public class WordCloudTableInput {
/** The sub-title of the Word Cloud dialog. */
public final String title;
/** The column index to take the words from.
* {@link Object#toString()} will be used to obtain words from the table values. */
public final int wordColumnIndex;
/** The column index to take the frequencies from.
* Must contain {@link Integer}s. */
public final int frequencyColumnIndex;
/**
* Creates a new WordCloudTableInput.
* @param title the sub-title of the Word Cloud dialog
* @param wordColumnIndex the column index to take the words from, {@link Object#toString()} will be used to obtain words from the table values
* @param frequencyColumnIndex the column index to take the frequencies from, must contain {@link Integer}s
*/
public WordCloudTableInput( final String title, final int wordColumnIndex, final int frequencyColumnIndex ) {
this.title = title;
this.wordColumnIndex = wordColumnIndex;
this.frequencyColumnIndex = frequencyColumnIndex;
}
}
| apache-2.0 |
junkerm/specmate | bundles/specmate-nlp/src/com/specmate/nlp/util/NLPUtil.java | 9974 | package com.specmate.nlp.util;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.StringJoiner;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.apache.uima.cas.FeatureStructure;
import org.apache.uima.fit.util.JCasUtil;
import org.apache.uima.jcas.JCas;
import org.apache.uima.jcas.tcas.Annotation;
import com.specmate.nlp.api.ELanguage;
import com.specmate.nlp.util.NLPUtil.ConstituentType;
import de.tudarmstadt.ukp.dkpro.core.api.lexmorph.type.pos.POS;
import de.tudarmstadt.ukp.dkpro.core.api.segmentation.type.Sentence;
import de.tudarmstadt.ukp.dkpro.core.api.segmentation.type.Token;
import de.tudarmstadt.ukp.dkpro.core.api.syntax.type.chunk.Chunk;
import de.tudarmstadt.ukp.dkpro.core.api.syntax.type.constituent.Constituent;
import de.tudarmstadt.ukp.dkpro.core.api.syntax.type.dependency.Dependency;
public class NLPUtil {
enum ConstituentType {
VP("VP"), NP("NP");
private String constituentTypeName;
public String getName() {
return constituentTypeName;
}
private ConstituentType(String name) {
constituentTypeName = name;
}
}
public static List<Constituent> getVerbPhrases(JCas jCas, Sentence sentence) {
return getConstituents(jCas, sentence, ConstituentType.VP);
}
public static List<Constituent> getNounPhrases(JCas jCas, Sentence sentence) {
return getConstituents(jCas, sentence, ConstituentType.NP);
}
public static List<Chunk> getVerbPhraseChunks(JCas jCas, Sentence sentence) {
return getChunks(jCas, sentence, ConstituentType.VP);
}
public static List<Chunk> getNounPhraseChunks(JCas jCas, Sentence sentence) {
return getChunks(jCas, sentence, ConstituentType.NP);
}
public static void refineNpChunks(JCas jCas) {
JCasUtil.select(jCas, Chunk.class).stream().filter(c -> c.getChunkValue().contentEquals("NP")).forEach(c -> {
replaceWithSubChunks(jCas, c);
mergeDeterminerToChunk(jCas, c);
});
}
private static void mergeDeterminerToChunk(JCas jCas, Chunk c) {
List<POS> preceedingPOS = JCasUtil.selectPreceding(POS.class, c, 1);
if (preceedingPOS.size() == 1) {
POS pos = preceedingPOS.get(0);
if (pos.getPosValue().contentEquals("ART")) {
c.removeFromIndexes();
Chunk newChunk = new Chunk(jCas, pos.getBegin(), c.getEnd());
newChunk.setChunkValue("NP");
newChunk.addToIndexes();
}
}
}
private static void replaceWithSubChunks(JCas jCas, Chunk npChunk) {
List<Dependency> conDep = findCoveredDependencies(jCas, "cc", npChunk);
conDep.addAll(findCoveredDependencies(jCas, "KON", npChunk));
if (conDep.size() == 0) {
return;
}
npChunk.removeFromIndexes();
int begin = npChunk.getBegin();
for (Dependency dep : conDep) {
Token ccToken = dep.getDependent();
List<Token> preceeding = JCasUtil.selectPreceding(Token.class, ccToken, 1);
if (preceeding.size() == 0) {
continue;
}
Token before = preceeding.get(0);
Chunk chunk = new Chunk(jCas, begin, before.getEnd());
chunk.setChunkValue("NP");
chunk.addToIndexes();
// result.add(new Chunk(jCas, begin, before.getEnd()));
List<Token> following = JCasUtil.selectFollowing(Token.class, ccToken, 1);
if (following.size() > 0) {
begin = following.get(0).getBegin();
}
}
Chunk chunk = new Chunk(jCas, begin, npChunk.getEnd());
chunk.setChunkValue("NP");
chunk.addToIndexes();
}
public static Annotation getCoveringNounPhraseOrToken(JCas jCas, Token token) {
List<Chunk> chunk = JCasUtil.selectCovering(jCas, Chunk.class, token);
Annotation result;
if (chunk.size() > 0 && chunk.get(0).getChunkValue().equals(ConstituentType.NP.getName())) {
result = chunk.get(0);
} else {
result = token;
}
return result;
}
public static List<Chunk> getChunks(JCas jCas, Sentence sentence, ConstituentType type) {
return JCasUtil.selectCovered(jCas, Chunk.class, sentence).stream()
.filter(c -> c.getChunkValue().contentEquals(type.getName())).collect(Collectors.toList());
}
public static List<Constituent> getConstituents(JCas jCas, Sentence sentence, ConstituentType type) {
return JCasUtil.selectCovered(jCas, Constituent.class, sentence).stream()
.filter(c -> c.getConstituentType().contentEquals(type.getName())).collect(Collectors.toList());
}
public static String printPOSTags(JCas jcas) {
StringJoiner joiner = new StringJoiner(" ");
JCasUtil.select(jcas, Token.class).forEach(p -> {
joiner.add(p.getCoveredText()).add("(" + p.getPosValue() + ")");
});
return joiner.toString();
}
public static String printChunks(JCas jcas) {
StringJoiner joiner = new StringJoiner(" ");
JCasUtil.select(jcas, Chunk.class).forEach(c -> {
joiner.add(c.getCoveredText()).add("(" + c.getChunkValue() + ")");
});
return joiner.toString();
}
public static String printParse(JCas jcas) {
StringJoiner builder = new StringJoiner(" ");
Constituent con = JCasUtil.select(jcas, Constituent.class).iterator().next();
printConstituent(con, builder);
return builder.toString();
}
public static String printDependencies(JCas jcas) {
Collection<Dependency> dependencies = JCasUtil.select(jcas, Dependency.class);
StringJoiner builder = new StringJoiner("\n");
for (Dependency dep : dependencies) {
builder.add(dep.getGovernor().getCoveredText() + " <--" + dep.getDependencyType() + "-- "
+ dep.getDependent().getCoveredText());
}
return builder.toString();
}
private static void printConstituent(Constituent con, StringJoiner joiner) {
joiner.add("(").add(con.getConstituentType());
for (FeatureStructure fs : con.getChildren()) {
if (fs instanceof Constituent) {
printConstituent((Constituent) fs, joiner);
} else if (fs instanceof Token) {
Token token = (Token) fs;
joiner.add(token.getText());
}
}
joiner.add(")");
}
public static Collection<Sentence> getSentences(JCas jCas) {
return JCasUtil.select(jCas, Sentence.class);
}
public static Optional<Constituent> getSentenceConstituent(JCas jCas, Sentence sentence) {
return JCasUtil.selectCovered(Constituent.class, sentence).stream()
.filter(c -> c.getConstituentType().contentEquals("S") || c.getConstituentType().contentEquals("SBAR"))
.findFirst();
}
public static List<Constituent> getSentenceConstituents(JCas jCas) {
return getSentences(jCas).stream().map(s -> getSentenceConstituent(jCas, s))
.flatMap(o -> o.isPresent() ? Stream.of(o.get()) : Stream.empty()).collect(Collectors.toList());
}
public static <T extends Annotation> Annotation selectIfCovering(Class<T> clazz, Annotation covering) {
List<T> cov = JCasUtil.selectCovering(clazz, covering);
if (cov.isEmpty()) {
return covering;
} else {
return cov.get(0);
}
}
public static List<Dependency> findCoveredDependencies(JCas jCas, String depType, Annotation annotation) {
Collection<Dependency> dependencies = JCasUtil.selectCovered(jCas, Dependency.class, annotation);
return dependencies.stream().filter(dep -> dep.getDependencyType().equals(depType))
.collect(Collectors.toList());
}
public static Optional<Dependency> findDependency(JCas jCas, Annotation anno, String depType, boolean isGovernor) {
Collection<Dependency> dependencies = JCasUtil.select(jCas, Dependency.class);
return findDependency(dependencies, anno, depType, isGovernor);
}
public static Optional<Dependency> findDependency(Collection<Dependency> dependencies, Annotation anno,
String depType, boolean isGovernor) {
List<Token> tokens;
if (anno instanceof Token) {
tokens = Arrays.asList((Token) anno);
} else {
tokens = JCasUtil.selectCovered(Token.class, anno);
}
for (Dependency dep : dependencies) {
if (dep.getDependencyType().equals(depType)) {
if (tokens.contains(isGovernor ? dep.getGovernor() : dep.getDependent())) {
return Optional.of(dep);
}
}
}
return Optional.empty();
}
public static List<Dependency> findDependencies(Collection<Dependency> dependencies, Annotation anno,
String depType, boolean isGovernor) {
List<Token> tokens;
if (anno instanceof Token) {
tokens = Arrays.asList((Token) anno);
} else {
tokens = JCasUtil.selectCovered(Token.class, anno);
}
return dependencies.stream()
.filter(d -> d.getDependencyType().equals(depType) && tokens.contains(isGovernor ? d.getGovernor() : d.getDependent()))
.collect(Collectors.toList());
}
private static String DE_Pattern = "\\b(der|die|das|ein|eine|einen)\\b";
public static ELanguage detectLanguage(String text) {
if (text.matches("(?i)(.*)"+DE_Pattern+"(.*)")) {
return ELanguage.DE;
}
return ELanguage.EN;
}
public static Set<Annotation> collectAllDependents(JCas jCas, Annotation anno) {
Set<Annotation> result = new HashSet<Annotation>();
List<Token> tokens = JCasUtil.selectCovered(Token.class, anno);
for (Token token : tokens) {
collectAllDependents(jCas, token, result);
}
return result;
}
private static void collectAllDependents(JCas jCas, Token token, Set<Annotation> result) {
result.add(token);
Collection<Dependency> deps = JCasUtil.select(jCas, Dependency.class);
for (Dependency dep : deps) {
if (dep.getDependent() == token && dep.getGovernor() != token) {
collectAllDependents(jCas, dep.getGovernor(), result);
}
}
}
public static String printLemmas(JCas result) {
StringBuilder builder = new StringBuilder();
Collection<Token> tokens = JCasUtil.select(result, Token.class);
for (Token token : tokens) {
builder.append(token.getCoveredText()).append(" (").append(token.getLemmaValue()).append(") ");
}
return builder.toString();
}
}
| apache-2.0 |
liquid-mind/warp | src/main/internal/java/ch/shaktipat/saraswati/internal/scheduler/ScheduleEventCommand.java | 1209 | package ch.shaktipat.saraswati.internal.scheduler;
import ch.shaktipat.saraswati.common.Event;
import ch.shaktipat.saraswati.common.TimeSpecification;
import ch.shaktipat.saraswati.internal.pobject.PersistentScheduledEventImpl;
import ch.shaktipat.saraswati.pobject.oid.PEventQueueOID;
import ch.shaktipat.saraswati.pobject.oid.PScheduledEventOID;
public class ScheduleEventCommand extends SchedulerCommand
{
private PEventQueueOID targetEventQueueOID;
private TimeSpecification timeSpecification;
public ScheduleEventCommand( PersistentEventScheduler scheduler, PEventQueueOID targetEventQueueOID, TimeSpecification timeSpecification )
{
super( scheduler );
this.targetEventQueueOID = targetEventQueueOID;
this.timeSpecification = timeSpecification;
}
public PEventQueueOID getTargetEventQueueOID()
{
return targetEventQueueOID;
}
public TimeSpecification getTimeSpecification()
{
return timeSpecification;
}
@Override
public void executeInternal()
{
Event event = new TimeoutEvent();
PScheduledEventOID pScheduledEventOID = PersistentScheduledEventImpl.create( null, event, timeSpecification, targetEventQueueOID ).getOID();
setCommandResult( pScheduledEventOID );
}
}
| apache-2.0 |
ruoyousi/wexin-poc | server/test/testReg.js | 91 | var tmpStr='1233214561'
var regx=new RegExp("^[1-9]{10}$");
console.log(regx.test(tmpStr))
| apache-2.0 |
jenellefeole/begood2 | first.py | 71 | def main():
print "hello world"
if __name__ == "__main__":
main()
| apache-2.0 |
omindra/schema_org_java_api | core/main/java/org/schema/api/model/thing/action/achieveAction/LoseAction.java | 364 | package org.schema.api.model.thing.action.achieveAction;
import org.schema.api.model.thing.action.achieveAction.AchieveAction;
import org.schema.api.model.thing.Person;
public class LoseAction extends AchieveAction
{
private Person winner;
public Person getWinner()
{
return winner;
}
public void setWinner(Person winner)
{
this.winner = winner;
}
} | apache-2.0 |
kward/venue | touchosc/request.go | 3662 | package touchosc
import (
"fmt"
"github.com/golang/glog"
"github.com/kward/go-osc/osc"
)
// request holds the raw OSC message, and its lexed equivalent.
type request struct {
msg *osc.Message
// Lexed values.
request string
version string
layout string
page string
control string
command string
bank int
x, y int
label bool
}
// String returns a human readable representation of the request.
func (req request) String() string {
return fmt.Sprintf("{ msg: %v request: %q version: %q layout: %q page: %q control: %q command: %q bank: %d x: %d y: %d label: %v",
req.msg, req.request, req.version, req.layout, req.page, req.control, req.command, req.bank, req.x, req.y, req.label)
}
// isTablet returns true for tablet client requests.
func (req *request) isTablet() bool {
switch req.layout {
case "th", "tv":
return true
case "ph", "pv":
return false
}
glog.Errorf("invalid request: %s", req)
return false
}
// isHorizontal returns true for horizontally oriented client requests.
func (req *request) isHorizontal() bool {
switch req.layout {
case "th", "ph":
return true
case "tv", "pv":
return false
}
glog.Errorf("invalid request: %s", req)
return false
}
// The multi* UI controls report their x and y position as /x/y.
// In a vertical orientation, x and y correspond to the top-left of the control,
// with x increasing to the right and y increasing downwards.
// In a horizontal orientation, x and y correspond to the bottom-left of the
// control, with x increasing vertically and y increasing to the right.
//
// Vertical: 1, 1 is top-left, X inc right, Y inc down
// | 1 2 3 |
// | 2 2 3 |
// | 3 3 3 |dy=3
// dx=3
//
// Horizontal: 1, 1 is bottom-left, X inc up, Y inc right
// | 3 3 3 |
// | 2 2 3 |
// | 1 2 3 |
// multiPosition returns the absolute position on a Multi-* control.
//
// Assuming a 3x2 Multi-Push/-Toggle control, with coordinates mapped to the
// vertical orientation (see multiRotate()), the "absolute position" within the
// control can be seen as this:
// | 1/1 2/1 3/1 | --> | 1 2 3 |
// | 1/2 2/2 3/2 | | 4 5 6 |
//
// This is useful when one wants to turn a large XxY control into a single
// value.
//
// `x` and `y` correspond to the parsed OSC values for a control, and `dx`
// is the number of controls on the X axis.
func (req *request) multiPosition(dx, dy int) int {
if req.isHorizontal() {
x, y := req.multiRotate(dx)
return x + dy*(y-1)
}
return req.x + dx*(req.y-1)
}
// multiRotate returns the rotated position for a Multi-* control.
//
// When a 3x2 Multi-Push/-Toggle control is drawn in vertical orientation, its
// x/y coordinates look like this:
// | 1/1 2/1 3/1 |
// | 1/2 2/2 3/2 |
//
// Drawing that same 3x2 control in the horizontal orientation, the x/y
// coordinates rotate with the control, which looks like this:
// | 3/1 3/2 |
// | 2/1 2,2 |
// | 1/1 1/2 |
//
// Although the orientation may change, OSC clients will transmit the same
// coordinates for either orientation. From a code perspective though, it can be
// nice to always refer the upper-left coordinate as 1/1, as though it were in
// the vertical rotation. This function maps a horizontal coordinate into its
// vertical equivalent. Therefore, the coordinates translate like this:
// | 3/1 3/2 | | 1/1 2/1 |
// | 2/1 2,2 | --> | 1/2 2/2 |
// | 1/1 1/2 | | 1/3 2/3 |
// horizontal vertical-ref
//
// `x` and `y` correspond to the parsed OSC values for a control, and `dx`
// is the number of controls on the X axis.
func (req *request) multiRotate(dx int) (int, int) {
if req.isHorizontal() {
return req.y, dx - req.x + 1
}
return req.x, req.y
}
| apache-2.0 |
crosbymichael/containerd | cmd/ctr/app/main.go | 3643 | /*
Copyright The containerd Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package app
import (
"fmt"
"io/ioutil"
"github.com/containerd/containerd/cmd/ctr/commands/containers"
"github.com/containerd/containerd/cmd/ctr/commands/content"
"github.com/containerd/containerd/cmd/ctr/commands/events"
"github.com/containerd/containerd/cmd/ctr/commands/images"
"github.com/containerd/containerd/cmd/ctr/commands/install"
"github.com/containerd/containerd/cmd/ctr/commands/leases"
namespacesCmd "github.com/containerd/containerd/cmd/ctr/commands/namespaces"
"github.com/containerd/containerd/cmd/ctr/commands/plugins"
"github.com/containerd/containerd/cmd/ctr/commands/pprof"
"github.com/containerd/containerd/cmd/ctr/commands/run"
"github.com/containerd/containerd/cmd/ctr/commands/snapshots"
"github.com/containerd/containerd/cmd/ctr/commands/tasks"
versionCmd "github.com/containerd/containerd/cmd/ctr/commands/version"
"github.com/containerd/containerd/defaults"
"github.com/containerd/containerd/namespaces"
"github.com/containerd/containerd/version"
"github.com/sirupsen/logrus"
"github.com/urfave/cli"
"google.golang.org/grpc/grpclog"
)
var extraCmds = []cli.Command{}
func init() {
// Discard grpc logs so that they don't mess with our stdio
grpclog.SetLoggerV2(grpclog.NewLoggerV2(ioutil.Discard, ioutil.Discard, ioutil.Discard))
cli.VersionPrinter = func(c *cli.Context) {
fmt.Println(c.App.Name, version.Package, c.App.Version)
}
}
// New returns a *cli.App instance.
func New() *cli.App {
app := cli.NewApp()
app.Name = "ctr"
app.Version = version.Version
app.Description = `
ctr is an unsupported debug and administrative client for interacting
with the containerd daemon. Because it is unsupported, the commands,
options, and operations are not guaranteed to be backward compatible or
stable from release to release of the containerd project.`
app.Usage = `
__
_____/ /______
/ ___/ __/ ___/
/ /__/ /_/ /
\___/\__/_/
containerd CLI
`
app.EnableBashCompletion = true
app.Flags = []cli.Flag{
cli.BoolFlag{
Name: "debug",
Usage: "enable debug output in logs",
},
cli.StringFlag{
Name: "address, a",
Usage: "address for containerd's GRPC server",
Value: defaults.DefaultAddress,
EnvVar: "CONTAINERD_ADDRESS",
},
cli.DurationFlag{
Name: "timeout",
Usage: "total timeout for ctr commands",
},
cli.DurationFlag{
Name: "connect-timeout",
Usage: "timeout for connecting to containerd",
},
cli.StringFlag{
Name: "namespace, n",
Usage: "namespace to use with commands",
Value: namespaces.Default,
EnvVar: namespaces.NamespaceEnvVar,
},
}
app.Commands = append([]cli.Command{
plugins.Command,
versionCmd.Command,
containers.Command,
content.Command,
events.Command,
images.Command,
leases.Command,
namespacesCmd.Command,
pprof.Command,
run.Command,
snapshots.Command,
tasks.Command,
install.Command,
}, extraCmds...)
app.Before = func(context *cli.Context) error {
if context.GlobalBool("debug") {
logrus.SetLevel(logrus.DebugLevel)
}
return nil
}
return app
}
| apache-2.0 |
LenaShervarly/TreasureHunting | android/src/com/home/jsquad/knowhunt/android/location/LocationService.java | 3328 | package com.home.jsquad.knowhunt.android.location;
import android.app.Service;
import android.content.Intent;
import android.location.Location;
import android.os.Bundle;
import android.os.IBinder;
import android.support.annotation.Nullable;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.location.LocationListener;
import com.home.jsquad.knowhunt.android.instrumentation.MyObservable;
import org.osmdroid.util.GeoPoint;
public class LocationService extends Service implements
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener {
public static final String Command = "Command";
private GoogleApiClient _googleApiClient;
private LocationRequest _locationRequest;
public static MyObservable<GeoPoint> LocationChanged = new MyObservable<>();
private boolean _isRunning;
@Override
public int onStartCommand(Intent intent, int flags, int startId)
{
if (intent == null)
return START_STICKY;
TrackerCommand command = (TrackerCommand)intent.getSerializableExtra(Command);
switch (command)
{
case Start:
if (_googleApiClient == null)
setUpComponents();
_googleApiClient.connect();
_isRunning = true;
break;
case Stop:
if (_googleApiClient != null)
_googleApiClient.disconnect();
_isRunning = false;
break;
}
return START_STICKY;
}
private void setUpComponents() {
_locationRequest = new LocationRequest();
_locationRequest.setInterval(10000);
_locationRequest.setFastestInterval(5000);
_locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
_googleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
@Override
public void onLocationChanged(Location location)
{
if (!_isRunning)
return;
LocationChanged.notifyObservers(new GeoPoint(location.getLatitude(), location.getLongitude()));
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onConnected(@Nullable Bundle bundle) {
try {
LocationServices.FusedLocationApi.requestLocationUpdates(_googleApiClient,
_locationRequest, this);
}
catch(SecurityException ex)
{
ex.printStackTrace();
}
}
@Override
public void onConnectionSuspended(int i) {
// ToDo: notify user that we are not tracking her right now
}
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
public void onTaskRemoved(Intent rootIntent)
{
if (_googleApiClient != null)
_googleApiClient.disconnect();
stopSelf();
}
}
| apache-2.0 |
zmc969213509/eyts | app/src/main/java/com/guojianyiliao/eryitianshi/Utils/db/HomeDoctorDao.java | 2590 | package com.guojianyiliao.eryitianshi.Utils.db;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import com.guojianyiliao.eryitianshi.Data.entity.Inquiry;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Administrator on 2016/11/4 0004.
*/
public class HomeDoctorDao {
private Context context;
private HomeDoctorHelper homeDoctorHelper;
private SQLiteDatabase db;
public HomeDoctorDao(Context context) {
this.context = context;
homeDoctorHelper = new HomeDoctorHelper(context);
db = homeDoctorHelper.getReadableDatabase();
}
//添加
public void addHomeDoctor(Inquiry inquiry) {
ContentValues values = new ContentValues();
values.put("id", inquiry.getId());
values.put("icon", inquiry.getIcon());
values.put("title", inquiry.getTitle());
values.put("username", inquiry.getUsername());
values.put("chatCost", inquiry.getChatCost());
values.put("name", inquiry.getName());
values.put("hospital", inquiry.getHospital());
values.put("adept", inquiry.getAdept());
values.put("section", inquiry.getSection());
db.insert("doctor", null, values);
}
public List<Inquiry> findHomeDoctor() {
ArrayList<Inquiry> inquiryArrayList = new ArrayList<>();
Cursor cursor = db.query("doctor", null, null, null, null, null, null);
while (cursor.moveToNext()) {
String id = cursor.getString(cursor.getColumnIndex("id"));
String icon = cursor.getString(cursor.getColumnIndex("icon"));
String title = cursor.getString(cursor.getColumnIndex("title"));
String username = cursor.getString(cursor.getColumnIndex("username"));
String chatCost = cursor.getString(cursor.getColumnIndex("chatCost"));
String name = cursor.getString(cursor.getColumnIndex("name"));
String hospital = cursor.getString(cursor.getColumnIndex("hospital"));
String adept = cursor.getString(cursor.getColumnIndex("adept"));
String section = cursor.getString(cursor.getColumnIndex("section"));
Inquiry inquiry = new Inquiry(icon, title, name, chatCost, adept, section, hospital, id, username);
inquiryArrayList.add(inquiry);
}
return inquiryArrayList;
}
public void deldotor() {
db.delete("doctor", null, null);
}
public void closedb(){
db.close();
}
}
| apache-2.0 |
google-code-export/google-api-dfp-java | src/com/google/api/ads/dfp/v201306/InvalidColorErrorReason.java | 2869 | /**
* InvalidColorErrorReason.java
*
* This file was auto-generated from WSDL
* by the Apache Axis 1.4 Apr 22, 2006 (06:55:48 PDT) WSDL2Java emitter.
*/
package com.google.api.ads.dfp.v201306;
public class InvalidColorErrorReason implements java.io.Serializable {
private java.lang.String _value_;
private static java.util.HashMap _table_ = new java.util.HashMap();
// Constructor
protected InvalidColorErrorReason(java.lang.String value) {
_value_ = value;
_table_.put(_value_,this);
}
public static final java.lang.String _INVALID_FORMAT = "INVALID_FORMAT";
public static final java.lang.String _UNKNOWN = "UNKNOWN";
public static final InvalidColorErrorReason INVALID_FORMAT = new InvalidColorErrorReason(_INVALID_FORMAT);
public static final InvalidColorErrorReason UNKNOWN = new InvalidColorErrorReason(_UNKNOWN);
public java.lang.String getValue() { return _value_;}
public static InvalidColorErrorReason fromValue(java.lang.String value)
throws java.lang.IllegalArgumentException {
InvalidColorErrorReason enumeration = (InvalidColorErrorReason)
_table_.get(value);
if (enumeration==null) throw new java.lang.IllegalArgumentException();
return enumeration;
}
public static InvalidColorErrorReason fromString(java.lang.String value)
throws java.lang.IllegalArgumentException {
return fromValue(value);
}
public boolean equals(java.lang.Object obj) {return (obj == this);}
public int hashCode() { return toString().hashCode();}
public java.lang.String toString() { return _value_;}
public java.lang.Object readResolve() throws java.io.ObjectStreamException { return fromValue(_value_);}
public static org.apache.axis.encoding.Serializer getSerializer(
java.lang.String mechType,
java.lang.Class _javaType,
javax.xml.namespace.QName _xmlType) {
return
new org.apache.axis.encoding.ser.EnumSerializer(
_javaType, _xmlType);
}
public static org.apache.axis.encoding.Deserializer getDeserializer(
java.lang.String mechType,
java.lang.Class _javaType,
javax.xml.namespace.QName _xmlType) {
return
new org.apache.axis.encoding.ser.EnumDeserializer(
_javaType, _xmlType);
}
// Type metadata
private static org.apache.axis.description.TypeDesc typeDesc =
new org.apache.axis.description.TypeDesc(InvalidColorErrorReason.class);
static {
typeDesc.setXmlType(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201306", "InvalidColorError.Reason"));
}
/**
* Return type metadata object
*/
public static org.apache.axis.description.TypeDesc getTypeDesc() {
return typeDesc;
}
}
| apache-2.0 |
jyx2020/emi | emiClient/emi/app/src/main/java/com/jyx/emi/Adapter/SearchHistoryAdapter.java | 1222 | package com.jyx.emi.Adapter;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.jyx.emi.R;
import org.w3c.dom.Text;
import java.util.List;
/**
* Created by Administrator on 2016/6/18.
*/
public class SearchHistoryAdapter extends BaseAdapter{
private List<String> strings;
protected LayoutInflater mInflater;
public SearchHistoryAdapter(Context context,List<String> strings) {
this.strings=strings;
mInflater=LayoutInflater.from(context);
}
@Override
public int getCount() {
return strings.size();
}
@Override
public Object getItem(int position) {
return null;
}
@Override
public long getItemId(int position) {
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = mInflater.inflate(R.layout.list_item_search_history,null);
TextView tv_search_name= (TextView) view.findViewById(R.id.tv_search_name);
tv_search_name.setText(strings.get(position)+"");
return view;
}
}
| apache-2.0 |
googleapis/java-datastore | google-cloud-datastore/src/test/java/com/google/cloud/datastore/testing/ITLocalDatastoreHelperTest.java | 7602 | /*
* Copyright 2015 Google LLC
*
* 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.google.cloud.datastore.testing;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import com.google.cloud.NoCredentials;
import com.google.cloud.datastore.Datastore;
import com.google.cloud.datastore.DatastoreException;
import com.google.cloud.datastore.DatastoreOptions;
import com.google.cloud.datastore.Entity;
import com.google.cloud.datastore.Key;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.concurrent.TimeoutException;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.threeten.bp.Duration;
@RunWith(JUnit4.class)
public class ITLocalDatastoreHelperTest {
private static final double TOLERANCE = 0.00001;
private static final String PROJECT_ID_PREFIX = "test-project-";
private static final String NAMESPACE = "namespace";
private Path dataDir;
@Before
public void setUp() throws IOException {
dataDir = Files.createTempDirectory("gcd");
}
@After
public void tearDown() throws IOException {
LocalDatastoreHelper.deleteRecursively(dataDir);
}
@Test
public void testCreate() {
LocalDatastoreHelper helper = LocalDatastoreHelper.create(0.75);
assertTrue(Math.abs(0.75 - helper.getConsistency()) < TOLERANCE);
assertTrue(helper.getProjectId().startsWith(PROJECT_ID_PREFIX));
helper = LocalDatastoreHelper.create();
assertTrue(Math.abs(0.9 - helper.getConsistency()) < TOLERANCE);
assertTrue(helper.getProjectId().startsWith(PROJECT_ID_PREFIX));
}
@Test
public void testCreateWithBuilder() {
LocalDatastoreHelper helper =
LocalDatastoreHelper.newBuilder()
.setConsistency(0.75)
.setPort(8081)
.setStoreOnDisk(false)
.setDataDir(dataDir)
.build();
assertTrue(Math.abs(0.75 - helper.getConsistency()) < TOLERANCE);
assertTrue(helper.getProjectId().startsWith(PROJECT_ID_PREFIX));
assertFalse(helper.isStoreOnDisk());
assertEquals(8081, helper.getPort());
assertEquals(dataDir, helper.getGcdPath());
LocalDatastoreHelper incompleteHelper = LocalDatastoreHelper.newBuilder().build();
assertTrue(Math.abs(0.9 - incompleteHelper.getConsistency()) < TOLERANCE);
assertTrue(incompleteHelper.getProjectId().startsWith(PROJECT_ID_PREFIX));
}
@Test
public void testCreateWithToBuilder() throws IOException {
LocalDatastoreHelper helper =
LocalDatastoreHelper.newBuilder()
.setConsistency(0.75)
.setPort(8081)
.setStoreOnDisk(false)
.setDataDir(dataDir)
.build();
assertTrue(Math.abs(0.75 - helper.getConsistency()) < TOLERANCE);
assertTrue(helper.getProjectId().startsWith(PROJECT_ID_PREFIX));
assertFalse(helper.isStoreOnDisk());
assertEquals(8081, helper.getPort());
assertEquals(dataDir, helper.getGcdPath());
LocalDatastoreHelper actualHelper = helper.toBuilder().build();
assertLocalDatastoreHelpersEquivelent(helper, actualHelper);
Path dataDir = Files.createTempDirectory("gcd_data_dir");
actualHelper =
helper
.toBuilder()
.setConsistency(0.85)
.setPort(9091)
.setStoreOnDisk(true)
.setDataDir(dataDir)
.build();
assertTrue(Math.abs(0.85 - actualHelper.getConsistency()) < TOLERANCE);
assertTrue(actualHelper.isStoreOnDisk());
assertEquals(9091, actualHelper.getPort());
assertEquals(dataDir, actualHelper.getGcdPath());
LocalDatastoreHelper.deleteRecursively(dataDir);
}
@Test
public void testCreatePort() {
LocalDatastoreHelper helper = LocalDatastoreHelper.create(0.75, 8888);
DatastoreOptions options = helper.getOptions(NAMESPACE);
assertTrue(options.getHost().endsWith("8888"));
assertTrue(Math.abs(0.75 - helper.getConsistency()) < TOLERANCE);
helper = LocalDatastoreHelper.create();
options = helper.getOptions(NAMESPACE);
assertTrue(Math.abs(0.9 - helper.getConsistency()) < TOLERANCE);
assertFalse(options.getHost().endsWith("8888"));
assertFalse(options.getHost().endsWith("8080"));
helper = LocalDatastoreHelper.create(9999);
options = helper.getOptions(NAMESPACE);
assertTrue(Math.abs(0.9 - helper.getConsistency()) < TOLERANCE);
assertTrue(options.getHost().endsWith("9999"));
}
@Test
public void testOptions() {
LocalDatastoreHelper helper = LocalDatastoreHelper.create();
DatastoreOptions options = helper.getOptions();
assertTrue(options.getProjectId().startsWith(PROJECT_ID_PREFIX));
assertTrue(options.getHost().startsWith("localhost:"));
assertSame(NoCredentials.getInstance(), options.getCredentials());
options = helper.getOptions(NAMESPACE);
assertTrue(options.getProjectId().startsWith(PROJECT_ID_PREFIX));
assertTrue(options.getHost().startsWith("localhost:"));
assertSame(NoCredentials.getInstance(), options.getCredentials());
assertEquals(NAMESPACE, options.getNamespace());
}
@Test
public void testStartStopReset() throws IOException, InterruptedException, TimeoutException {
try {
LocalDatastoreHelper helper = LocalDatastoreHelper.create();
helper.start();
Datastore datastore = helper.getOptions().getService();
Key key = datastore.newKeyFactory().setKind("kind").newKey("name");
datastore.put(Entity.newBuilder(key).build());
assertNotNull(datastore.get(key));
helper.reset();
assertNull(datastore.get(key));
helper.stop(Duration.ofMinutes(1));
datastore.get(key);
Assert.fail();
} catch (DatastoreException ex) {
assertNotNull(ex.getMessage());
}
}
@Test
public void testStartStopResetWithBuilder()
throws IOException, InterruptedException, TimeoutException {
try {
LocalDatastoreHelper helper = LocalDatastoreHelper.newBuilder().build();
helper.start();
Datastore datastore = helper.getOptions().getService();
Key key = datastore.newKeyFactory().setKind("kind").newKey("name");
datastore.put(Entity.newBuilder(key).build());
assertNotNull(datastore.get(key));
helper.reset();
assertNull(datastore.get(key));
helper.stop(Duration.ofMinutes(1));
datastore.get(key);
Assert.fail();
} catch (DatastoreException ex) {
assertNotNull(ex.getMessage());
}
}
public void assertLocalDatastoreHelpersEquivelent(
LocalDatastoreHelper expected, LocalDatastoreHelper actual) {
assertEquals(expected.getConsistency(), actual.getConsistency(), 0);
assertEquals(expected.isStoreOnDisk(), actual.isStoreOnDisk());
assertEquals(expected.getGcdPath(), actual.getGcdPath());
}
}
| apache-2.0 |
GoogleCloudPlatform/django-cloud-deploy | django_cloud_deploy/crash_handling/__init__.py | 6296 | # Copyright 2018 Google LLC
#
# 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
#
# https://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.
"""A module handles crashes of the tool."""
import os
import platform
import shutil
import subprocess
import sys
import tempfile
import traceback
import urllib.parse
import jinja2
from django_cloud_deploy import __version__
from django_cloud_deploy.cli import io
from django_cloud_deploy.utils import webbrowser
class UserError(Exception):
"""Error caused by user's code."""
# A list of exceptions that should be displayed to the user rather than opening
# a Github issue.
_DISPLAYABLE_EXCEPTIONS = [UserError]
# The Github issue label for all issues generated by crash handling
_ISSUE_LABEL = 'crash handler'
with open(
os.path.join(os.path.dirname(__file__), 'template',
'issue_template.txt')) as f:
_ISSUE_TEMPLATE = f.read()
def handle_crash(err: Exception, command: str, console: io.IO = io.ConsoleIO()):
"""The tool's crashing handler.
Args:
err: The exception that was raised.
command: The command causing the exception to get thrown,
e.g. 'django-cloud-deploy new'.
console: Object to use for user I/O.
"""
# Only handle crashes caused by our code, not user's code.
# When deploying, our tool will run the code of user's Django project.
# If user's code has a bug, then an UserError will be raised. In this case,
# we do not want users to create a Github issue.
if any(
isinstance(err, exception_class)
for exception_class in _DISPLAYABLE_EXCEPTIONS):
# https://github.com/google/pytype/issues/225
raise err.__cause__ # pytype: disable=attribute-error
log_fd, log_file_path = tempfile.mkstemp(prefix='django-deploy-bug-report-')
issue_content = _create_issue_body(command)
issue_title = _create_issue_title(err, command)
log_file = os.fdopen(log_fd, 'wt')
log_file.write(issue_content)
log_file.close()
console.tell(
('Your "{}" failed due to an internal error.'
'\n\n'
'You can report this error by filing a bug on Github. If you agree,\n'
'a browser window will open and an Github issue will be\n'
'pre-populated with the details of this crash.\n'
'For more details, see: {}').format(command, log_file_path))
while True:
ans = console.ask('Would you like to file a bug? [y/N]: ')
ans = ans.strip().lower()
if not ans: # 'N' is default.
break
if ans in ['y', 'n']:
break
if ans.lower() == 'y':
_create_issue(issue_title, issue_content)
def _create_issue(issue_title: str, issue_content: str):
"""Open browser to create a issue on the package's Github repo.
Args:
issue_title: Title of the Github issue.
issue_content: Body of the Github issue.
"""
request_url = ('https://github.com/GoogleCloudPlatform/django-cloud-deploy/'
'issues/new?{}')
params = urllib.parse.urlencode({
'title': issue_title,
'body': issue_content,
'labels': _ISSUE_LABEL
})
url = request_url.format(params)
webbrowser.open_url(url)
def _create_issue_title(err: Exception, command: str) -> str:
"""Generate a Github issue title based on given exception and command."""
return '{}:{} during "{}"'.format(type(err).__name__, str(err), command)
def _create_issue_body(command: str) -> str:
"""Generate a Github issue body based on given exception and command.
Args:
command: The command causing the exception to get thrown,
e.g. 'django-cloud-deploy new'.
Returns:
Github issue body in string.
"""
template_env = jinja2.Environment()
gcloud_path = shutil.which('gcloud')
if gcloud_path:
try:
gcloud_version = subprocess.check_output(
[gcloud_path, 'info', '--format=value(basic.version)'],
stdin=subprocess.PIPE,
stderr=subprocess.PIPE,
universal_newlines=True).rstrip()
except subprocess.CalledProcessError as e:
gcloud_version = 'Error: {!r}'.format(e.stderr)
else:
gcloud_version = 'Not installed or not on PATH'
docker_path = shutil.which('docker')
if docker_path:
try:
docker_version = subprocess.check_output(
['docker', '--version'],
stdin=subprocess.PIPE,
stderr=subprocess.PIPE,
universal_newlines=True).rstrip()
except subprocess.CalledProcessError:
docker_version = 'Error: {!r}'.format(e.stderr)
else:
docker_version = 'Not installed or not on PATH'
cloud_sql_proxy_path = shutil.which('cloud_sql_proxy')
if cloud_sql_proxy_path:
try:
cloud_sql_proxy_version = subprocess.check_output(
[cloud_sql_proxy_path, '--version'],
stdin=subprocess.PIPE,
stderr=subprocess.PIPE,
universal_newlines=True).rstrip()
except subprocess.CalledProcessError:
cloud_sql_proxy_version = 'Error: {!r}'.format(e.stderr)
else:
cloud_sql_proxy_version = 'Not installed or not on PATH'
template = template_env.from_string(_ISSUE_TEMPLATE)
options = {
'django_cloud_deploy_version': __version__.__version__,
'command': command,
'gcloud_version': gcloud_version,
'docker_version': docker_version,
'cloud_sql_proxy_version': cloud_sql_proxy_version,
'python_version': sys.version.replace('\n', ' '),
'traceback': traceback.format_exc(),
'platform': platform.platform(),
}
content = template.render(options)
return content
| apache-2.0 |
clafonta/canyon | test/web/org/tll/canyon/buildtools/EscapeHtmlEntities.java | 2364 | /**
*
*/
package org.tll.canyon.buildtools;
import java.io.IOException;
import java.io.Reader;
import org.apache.commons.lang.StringEscapeUtils;
import org.apache.tools.ant.filters.BaseParamFilterReader;
import org.apache.tools.ant.filters.ChainableReader;
/**
* @author Mika
*
*/
public class EscapeHtmlEntities extends BaseParamFilterReader implements ChainableReader {
public static final String ESCAPE = "escape";
public static final String UNESCAPE = "unescape";
/** Data that must be read from, if not null. */
private String queuedData = null;
private String mode;
public EscapeHtmlEntities() {
super();
}
public EscapeHtmlEntities(final Reader rdr) {
super(rdr);
}
/* (non-Javadoc)
* @see java.io.FilterReader#read()
*/
public int read() throws IOException {
int ch = -1;
if (queuedData != null && queuedData.length() == 0) {
queuedData = null;
}
if (queuedData != null) {
ch = queuedData.charAt(0);
queuedData = queuedData.substring(1);
if (queuedData.length() == 0) {
queuedData = null;
}
} else {
queuedData = readFully();
if (queuedData == null) {
ch = -1;
} else {
queuedData = handleEntities(queuedData);
return read();
}
}
return ch;
}
/**
* @param queuedData2
* @return
*/
private String handleEntities(String queuedData2) {
if(ESCAPE.equalsIgnoreCase(mode)){
return StringEscapeUtils.escapeHtml(queuedData2);
} else {
return StringEscapeUtils.unescapeHtml(queuedData2);
}
}
/* (non-Javadoc)
* @see org.apache.tools.ant.filters.ChainableReader#chain(java.io.Reader)
*/
public Reader chain(Reader rdr) {
EscapeHtmlEntities filter = new EscapeHtmlEntities(rdr);
return filter;
}
/**
* @return Returns the mode.
*/
public String getMode() {
return mode;
}
/**
* @param mode The mode to set.
*/
public void setMode(String mode) {
this.mode = mode;
}
}
| apache-2.0 |
skjolber/external-nfc-api | core/src/main/java/com/github/skjolber/nfc/command/remote/CommandWrapper.java | 4466 | package com.github.skjolber.nfc.command.remote;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import com.github.skjolber.nfc.acs.AcrReader;
public class CommandWrapper {
private static final String TAG = CommandWrapper.class.getName();
protected byte[] returnValue(Integer picc, Exception exception) {
try {
ByteArrayOutputStream out = new ByteArrayOutputStream();
DataOutputStream dout = new DataOutputStream(out);
dout.writeInt(AcrReader.VERSION);
if (picc != null) {
dout.writeInt(AcrReader.STATUS_OK);
dout.writeInt(picc);
} else {
dout.writeInt(AcrReader.STATUS_EXCEPTION);
dout.writeUTF(exception.toString());
}
byte[] response = out.toByteArray();
// Log.d(TAG, "Send response length " + response.length + ":" + ACRCommands.toHexString(response));
return response;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
protected byte[] returnValue(String firmware, Exception exception) {
try {
ByteArrayOutputStream out = new ByteArrayOutputStream();
DataOutputStream dout = new DataOutputStream(out);
dout.writeInt(AcrReader.VERSION);
if (firmware != null) {
dout.writeInt(AcrReader.STATUS_OK);
dout.writeUTF(firmware);
} else {
dout.writeInt(AcrReader.STATUS_EXCEPTION);
dout.writeUTF(exception.toString());
}
byte[] response = out.toByteArray();
// Log.d(TAG, "Send response length " + response.length + ":" + ACRCommands.toHexString(response));
return response;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
protected byte[] returnValue(Boolean value, Exception exception) {
try {
ByteArrayOutputStream out = new ByteArrayOutputStream();
DataOutputStream dout = new DataOutputStream(out);
dout.writeInt(AcrReader.VERSION);
if (value != null) {
dout.writeInt(AcrReader.STATUS_OK);
dout.writeBoolean(value);
} else {
dout.writeInt(AcrReader.STATUS_EXCEPTION);
dout.writeUTF(exception.toString());
}
byte[] response = out.toByteArray();
// Log.d(TAG, "Send response length " + response.length + ":" + ACRCommands.toHexString(response));
return response;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
protected byte[] returnValue(byte[] value, Exception exception) {
try {
ByteArrayOutputStream out = new ByteArrayOutputStream();
DataOutputStream dout = new DataOutputStream(out);
dout.writeInt(AcrReader.VERSION);
if (value != null) {
dout.writeInt(AcrReader.STATUS_OK);
dout.writeInt(value.length);
dout.write(value);
} else {
dout.writeInt(AcrReader.STATUS_EXCEPTION);
dout.writeUTF(exception.toString());
}
byte[] response = out.toByteArray();
// Log.d(TAG, "Send response length " + response.length + ":" + ACRCommands.toHexString(response));
return response;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
protected byte[] returnValue(Byte picc, Exception exception) {
try {
ByteArrayOutputStream out = new ByteArrayOutputStream();
DataOutputStream dout = new DataOutputStream(out);
dout.writeInt(AcrReader.VERSION);
if (picc != null) {
dout.writeInt(AcrReader.STATUS_OK);
dout.writeByte(picc & 0xFF); // strictly speaking not necessary with an and
} else {
dout.writeInt(AcrReader.STATUS_EXCEPTION);
dout.writeUTF(exception.toString());
}
byte[] response = out.toByteArray();
// Log.d(TAG, "Send response length " + response.length + ":" + ACRCommands.toHexString(response));
return response;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
| apache-2.0 |
mduerig/jackrabbit-oak | oak-run/src/main/java/org/apache/jackrabbit/oak/index/indexer/document/flatfile/NodeStateEntrySorter.java | 6644 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.apache.jackrabbit.oak.index.indexer.document.flatfile;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.Comparator;
import java.util.List;
import java.util.function.Function;
import com.google.common.base.Stopwatch;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.jackrabbit.oak.commons.sort.ExternalSort;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static com.google.common.base.Charsets.UTF_8;
import static com.google.common.collect.ImmutableList.copyOf;
import static org.apache.commons.io.FileUtils.ONE_GB;
import static org.apache.jackrabbit.oak.commons.IOUtils.humanReadableByteCount;
import static org.apache.jackrabbit.oak.commons.PathUtils.elements;
import static org.apache.jackrabbit.oak.index.indexer.document.flatfile.NodeStateEntryWriter.getPath;
public class NodeStateEntrySorter {
private final Logger log = LoggerFactory.getLogger(getClass());
private static final int DEFAULTMAXTEMPFILES = 1024;
private final File nodeStateFile;
private final File workDir;
private final Charset charset = UTF_8;
private final Comparator<Iterable<String>> pathComparator;
private File sortedFile;
private boolean useZip;
private boolean deleteOriginal;
private long maxMemory = ONE_GB * 5;
public NodeStateEntrySorter(Comparator<Iterable<String>> pathComparator, File nodeStateFile, File workDir) {
this(pathComparator, nodeStateFile, workDir, getSortedFileName(nodeStateFile));
}
public NodeStateEntrySorter(Comparator<Iterable<String>> pathComparator, File nodeStateFile, File workDir, File sortedFile) {
this.nodeStateFile = nodeStateFile;
this.workDir = workDir;
this.sortedFile = sortedFile;
this.pathComparator = pathComparator;
}
public void setUseZip(boolean useZip) {
this.useZip = useZip;
}
public void setDeleteOriginal(boolean deleteOriginal) {
this.deleteOriginal = deleteOriginal;
}
public void setMaxMemoryInGB(long maxMemoryInGb) {
this.maxMemory = maxMemoryInGb * ONE_GB;
}
public void sort() throws IOException {
long estimatedMemory = estimateAvailableMemory();
long memory = Math.min(estimatedMemory, maxMemory);
log.info("Sorting with memory {} (estimated {})", humanReadableByteCount(memory), humanReadableByteCount(estimatedMemory));
Stopwatch w = Stopwatch.createStarted();
Comparator<NodeStateEntryHolder> comparator = Comparator.naturalOrder();
Function<String, NodeStateEntryHolder> func1 = (line) -> line == null ? null : new NodeStateEntryHolder(line, pathComparator);
Function<NodeStateEntryHolder, String> func2 = holder -> holder == null ? null : holder.getLine();
List<File> sortedFiles = ExternalSort.sortInBatch(nodeStateFile,
comparator, //Comparator to use
DEFAULTMAXTEMPFILES,
memory,
charset, //charset
workDir, //temp directory where intermediate files are created
false,
0,
useZip,
func2,
func1
);
log.info("Batch sorting done in {} with {} files of size {} to merge", w, sortedFiles.size(),
humanReadableByteCount(sizeOf(sortedFiles)));
if (deleteOriginal) {
log.info("Removing the original file {}", nodeStateFile.getAbsolutePath());
FileUtils.forceDelete(nodeStateFile);
}
Stopwatch w2 = Stopwatch.createStarted();
ExternalSort.mergeSortedFiles(sortedFiles,
sortedFile,
comparator,
charset,
false,
false,
useZip,
func2,
func1
);
log.info("Merging of sorted files completed in {}", w2);
log.info("Sorting completed in {}", w);
}
public File getSortedFile() {
return sortedFile;
}
private static File getSortedFileName(File file) {
String extension = FilenameUtils.getExtension(file.getName());
String baseName = FilenameUtils.getBaseName(file.getName());
return new File(file.getParentFile(), baseName + "-sorted." + extension);
}
private static long sizeOf(List<File> sortedFiles) {
return sortedFiles.stream().mapToLong(File::length).sum();
}
/**
* This method calls the garbage collector and then returns the free
* memory. This avoids problems with applications where the GC hasn't
* reclaimed memory and reports no available memory.
*
* @return available memory
*/
private static long estimateAvailableMemory() {
System.gc();
// http://stackoverflow.com/questions/12807797/java-get-available-memory
Runtime r = Runtime.getRuntime();
long allocatedMemory = r.totalMemory() - r.freeMemory();
long presFreeMemory = r.maxMemory() - allocatedMemory;
return presFreeMemory;
}
static class NodeStateEntryHolder implements Comparable<NodeStateEntryHolder> {
final String line;
final List<String> pathElements;
final Comparator<Iterable<String>> comparator;
public NodeStateEntryHolder(String line, Comparator<Iterable<String>> comparator) {
this.line = line;
this.comparator = comparator;
this.pathElements = copyOf(elements(getPath(line)));
}
public String getLine() {
return line;
}
@Override
public int compareTo(NodeStateEntryHolder o) {
return comparator.compare(this.pathElements, o.pathElements);
}
}
}
| apache-2.0 |