text
stringlengths
7
3.69M
var fs = require("fs"); var readerStream = fs.createReadStream('001.jpg'); var writerStream = fs.createWriteStream('002.jpg'); readerStream.pipe(writerStream); console.log("程序编写完成!")
/****************************************************************************** jsBVH.js - General-Purpose Non-Recursive Bounding-Volume Hierarchy Library Version 0.2.1, April 3rd 2010 Copyright (c) 2010 Jon-Carlos Rivera 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. Jon-Carlos Rivera - imbcmdth@hotmail.com ******************************************************************************/ var isArray = function (o) { return Object.prototype.toString.call(o) === '[object Array]'; }; /** * NTree - A simple n-tree structure for great results. * @constructor */ var jsBVH = function (dimensions, width) { // Variables to control tree // Number of "interval pairs" per node var _Dimensions = 2; if (!isNaN(dimensions)) { _Dimensions = dimensions; } // Maximum width of any node before a split var _Max_Width = _Dimensions * 3; if (!isNaN(width)) { _Max_Width = width; } // Minimum width of any node before a merge var _Min_Width = Math.floor(_Max_Width / _Dimensions); var _make_Empty = function () { var i, d = []; for (i = 0; i < _Dimensions; i++) { d.push({ a: 0, b: 0 }); } return d; }; var _make_Intervals = function (intervals, d) { var i; if (!isArray(d)) d = []; for (i = 0; i < _Dimensions; i++) { d[i] = { a: intervals[i].a, b: intervals[i].b }; } return d; }; // Start with an empty root-tree var _T = { d: _make_Empty(), id: "root", nodes: [] }; /* @function * @description Function to generate unique strings for element IDs * @param {String} n The prefix to use for the IDs generated. * @return {String} A guarenteed unique ID. */ var _name_to_id = (function () { // hide our idCache inside this closure var idCache = {}; // return the api: our function that returns a unique string with incrementing number appended to given idPrefix return function (idPrefix) { var idVal = 0; if (idPrefix in idCache) { idVal = idCache[idPrefix]++; } else { idCache[idPrefix] = 0; } return idPrefix + "_" + idVal; } })(); /* expands intervals A to include intervals B, intervals B is untouched * [ rectangle a ] = expand_rectangle(rectangle a, rectangle b) * @static function */ var _expand_intervals = function (a, b) { var i, n; if (a.length != _Dimensions || b.length != _Dimensions) { return false; } // Should probably be an error. for (i = 0; i < _Dimensions; i++) { n = Math.min(a[i].a, b[i].a); a[i].b = Math.max(a[i].a + a[i].b, b[i].a + b[i].b) - n; a[i].a = n; } return a; }; /* generates a minimally bounding intervals for all intervals in * array "nodes". If intervals is set, it is modified into the MBV. Otherwise, * a new set of intervals is generated and returned. * [ rectangle a ] = make_MBR(rectangle array nodes, rectangle rect) * @static function */ var _make_MBV = function (nodes, intervals) { var d; if (nodes.length < 1) { //throw "_make_MBV: nodes must contain at least one object to bound!"; return _make_Empty(); } if (!intervals) { intervals = _make_Intervals(nodes[0].d); } else { _make_Intervals(nodes[0].d, intervals); } for (var i = nodes.length - 1; i > 0; i--) { _expand_intervals(intervals, nodes[i].d); } return (intervals); }; // This is my special addition to the world of r-trees // every other (simple) method I found produced crap trees // this skews insertions to prefering squarer and emptier nodes var _jons_ratio = function (intervals, count) { // Area of new enlarged rectangle var i, sum = 0, mul = 1; for (i = 0; i < _Dimensions; i++) { sum += intervals[i].b; mul *= intervals[i].b; } sum /= dimensions; var lgeo = mul / Math.pow(sum, _Dimensions); // return the ratio of the perimeter to the area - the closer to 1 we are, // the more "square" or "cubic" a volume is. conversly, when approaching zero the // more elongated a rectangle is return (mul * count / lgeo); }; /* returns true if intervals "a" overlaps intervals "b" * [ boolean ] = overlap_intervals(intervals a, intervals b) * @static function */ var _make_overlap_intervals = function (a) { if (a.length != _Dimensions) { return (function (a, b) { return false; }); } // Should probably be an error. var i, ret_val = true; return (function (a, b) { if (b.length != _Dimensions) { ret_val = false; } // Should probably be an error. for (i = 0; i < _Dimensions; i++) { ret_val = ret_val && (a[i].a < (b[i].a + b[i].b) && (a[i].a + a[i].b) > b[i].a); } return ret_val; }); }; var _overlap_intervals = function (a, b) { var i, ret_val = true; if (a.length != _Dimensions || b.length != _Dimensions) { ret_val = false; } // Should probably be an error. for (i = 0; i < _Dimensions; i++) { ret_val = ret_val && (a[i].a < (b[i].a + b[i].b) && (a[i].a + a[i].b) > b[i].a); } return ret_val; }; /* returns true if intervals "a" overlaps intervals "b" * [ boolean ] = contains_intervals(intervals a, intervals b) * @static function */ var _make_contains_intervals = function (a) { var i, ret_val = true; if (a.length != _Dimensions) { return (function (a, b) { return false; }); } // Should probably be an error. return (function (a, b) { if (b.length != _Dimensions) { ret_val = false; } // Should probably be an error. for (i = 0; i < _Dimensions; i++) { ret_val = ret_val && ((a[i].a + a[i].b) <= (b[i].a + b[i].b) && a[i].a >= b[i].a); } return ret_val; }); }; var _contains_intervals = function (a, b) { var i, ret_val = true; if (a.length != _Dimensions || b.length != _Dimensions) { ret_val = false; } // Should probably be an error. for (i = 0; i < _Dimensions; i++) { ret_val = ret_val && ((a[i].a + a[i].b) <= (b[i].a + b[i].b) && a[i].a >= b[i].a); } return ret_val; }; /* find the best specific node(s) for object to be deleted from * [ leaf node parent ] = _remove_subtree(rectangle, object, root) * @private */ var _remove_subtree = function (options) { var hit_stack = []; // Contains the elements that overlap var count_stack = []; // Contains the elements that overlap var ret_array = []; var current_depth = 1; var intervals = options.intervals; var obj = options.object; var root = options.root; var comparators = options.comparators; if (!intervals || !comparators.overlap_intervals(intervals, root.d)) return ret_array; var ret_obj = { d: _make_Intervals(intervals), target: obj }; count_stack.push(root.nodes.length); hit_stack.push(root); do { var tree = hit_stack.pop(); var i = count_stack.pop() - 1; if ("target" in ret_obj) { // We are searching for a target while (i >= 0) { var ltree = tree.nodes[i]; if (comparators.overlap_intervals(ret_obj.d, ltree.d)) { if ((ret_obj.target && "leaf" in ltree && ltree.leaf === ret_obj.target) || (!ret_obj.target && ("leaf" in ltree || comparators.contains_intervals(ltree.d, ret_obj.d)))) { // A Match !! // Yup we found a match... // we can cancel search and start walking up the list if ("nodes" in ltree) { // If we are deleting a node not a leaf... ret_array = _search_subtree({ intervals: ltree.d, return_nodes: true, return_array: [], root: ltree, comparators: comparators }); tree.nodes.splice(i, 1); } else { ret_array = tree.nodes.splice(i, 1); } // Resize MBR down... _make_MBV(tree.nodes, tree.d); delete ret_obj.target; if (tree.nodes.length < _Min_Width) { // Underflow ret_obj.nodes = _search_subtree({ intervals: tree.d, return_nodes: true, return_array: [], root: tree, comparators: comparators }); } break; } /* else if("load" in ltree) { // A load }*/ else if ("nodes" in ltree) { // Not a Leaf current_depth += 1; count_stack.push(i); hit_stack.push(tree); tree = ltree; i = ltree.nodes.length; } } i -= 1; } } else if ("nodes" in ret_obj) { // We are unsplitting tree.nodes.splice(i + 1, 1); // Remove unsplit node // ret_obj.nodes contains a list of elements removed from the tree so far if (tree.nodes.length > 0) { _make_MBV(tree.nodes, tree.d); } for (var t = 0; t < ret_obj.nodes.length; t++) { _insert_subtree({ node: ret_obj.nodes[t], root: tree, comparators: comparators }); } ret_obj.nodes.length = 0; if (hit_stack.length == 0 && tree.nodes.length <= 1) { // Underflow..on root! ret_obj.nodes = _search_subtree({ intervals: tree.d, return_nodes: true, return_array: ret_obj.nodes, root: tree, comparators: comparators }); tree.nodes.length = 0; hit_stack.push(tree); count_stack.push(1); } else if (hit_stack.length > 0 && tree.nodes.length < _Min_Width) { // Underflow..AGAIN! ret_obj.nodes = _search_subtree({ intervals: tree.d, return_nodes: true, return_array: ret_obj.nodes, root: tree, comparators: comparators }); tree.nodes.length = 0; } else { delete ret_obj.nodes; // Just start resizing } } else { // we are just resizing _make_MBV(tree.nodes, tree.d); } current_depth -= 1; } while (hit_stack.length > 0); return (ret_array); }; /* choose the best damn node for rectangle to be inserted into * [ leaf node parent ] = _choose_leaf_subtree(rectangle, root to start search at) * @private */ var _choose_leaf_subtree = function (options) { var best_choice_index = -1; var best_choice_stack = []; var best_choice_area; var intervals = options.intervals; var root = options.root; var comparators = options.comparators; var load_callback = function (local_tree, local_node) { return (function (data) { local_tree._attach_data(local_node, data); }); }; best_choice_stack.push(root); var nodes = root.nodes; do { if (best_choice_index != -1) { best_choice_stack.push(nodes[best_choice_index]); nodes = nodes[best_choice_index].nodes; best_choice_index = -1; } for (var i = nodes.length - 1; i >= 0; i--) { var ltree = nodes[i]; if ("leaf" in ltree) { // Bail out of everything and start inserting best_choice_index = -1; break; } /*else if(ltree.load) { throw( "Can't insert into partially loaded tree ... yet!"); //jQuery.getJSON(ltree.load, load_callback(this, ltree)); //delete ltree.load; }*/ // Area of new enlarged rectangle var old_lratio = _jons_ratio(ltree.d, ltree.nodes.length + 1); var copy_of_intervals = _make_Intervals(ltree.d); _expand_intervals(copy_of_intervals, intervals); // Area of new enlarged rectangle var lratio = _jons_ratio(copy_of_intervals, ltree.nodes.length + 2); if (best_choice_index < 0 || Math.abs(lratio - old_lratio) < best_choice_area) { best_choice_area = Math.abs(lratio - old_lratio); best_choice_index = i; } } } while (best_choice_index != -1); return (best_choice_stack); }; /* split a set of nodes into two roughly equally-filled nodes * [ an array of two new arrays of nodes ] = linear_split(array of nodes) * @private */ var _linear_split = function (nodes) { var n = _pick_linear(nodes); while (nodes.length > 0) { _pick_next(nodes, n[0], n[1]); } return (n); }; /* insert the best source rectangle into the best fitting parent node: a or b * [] = pick_next(array of source nodes, target node array a, target node array b) * @private */ var _pick_next = function (nodes, a, b) { // Area of new enlarged rectangle var area_a = _jons_ratio(a.d, a.nodes.length + 1); var area_b = _jons_ratio(b.d, b.nodes.length + 1); var high_area_delta; var high_area_node; var lowest_growth_group; for (var i = nodes.length - 1; i >= 0; i--) { var l = nodes[i]; var copy_of_intervals = _make_Intervals(a.d); _expand_intervals(copy_of_intervals, l.d); var change_new_area_a = Math.abs(_jons_ratio(copy_of_intervals, a.nodes.length + 2) - area_a); copy_of_intervals = _make_Intervals(b.d); _expand_intervals(copy_of_intervals, l.d); var change_new_area_b = Math.abs(_jons_ratio(copy_of_intervals, b.nodes.length + 2) - area_b); if (!high_area_node || !high_area_delta || Math.abs(change_new_area_b - change_new_area_a) < high_area_delta) { high_area_node = i; high_area_delta = Math.abs(change_new_area_b - change_new_area_a); lowest_growth_group = change_new_area_b < change_new_area_a ? b : a; } } var temp_node = nodes.splice(high_area_node, 1)[0]; if (a.nodes.length + nodes.length + 1 <= _Min_Width) { a.nodes.push(temp_node); _expand_intervals(a.d, temp_node.d); } else if (b.nodes.length + nodes.length + 1 <= _Min_Width) { b.nodes.push(temp_node); _expand_intervals(b.d, temp_node.d); } else { lowest_growth_group.nodes.push(temp_node); _expand_intervals(lowest_growth_group.d, temp_node.d); } }; /* pick the "best" two starter nodes to use as seeds using the "linear" criteria * [ an array of two new arrays of nodes ] = pick_linear(array of source nodes) * @private */ var _pick_linear = function (nodes) { var lowest_high = new Array(_Dimensions); for (i = 0; i < _Dimensions; i++) lowest_high[i] = nodes.length - 1; var highest_low = new Array(_Dimensions); for (i = 0; i < _Dimensions; i++) highest_low[i] = 0; var t1, t2, l, i, d; for (i = nodes.length - 2; i >= 0; i--) { l = nodes[i]; for (d = 0; d < _Dimensions; d++) { if (l.d[d].a > nodes[highest_low[d]].d[d].a) { highest_low[d] = i; } else if (l.d[d].a + l.d[d].b < nodes[lowest_high[d]].d[d].a + nodes[lowest_high[d]].d[d].b) { lowest_high[d] = i; } } } d = 0; var difference, last_difference = 0; for (i = 0; i < _Dimensions; i++) { difference = Math.abs((nodes[lowest_high[i]].d[i].a + nodes[lowest_high[i]].d[i].b) - nodes[highest_low[i]].d[i].a); if (difference > last_difference) { d = i; last_difference = difference; } } if (lowest_high[d] > highest_low[d]) { t1 = nodes.splice(lowest_high[d], 1)[0]; t2 = nodes.splice(highest_low[d], 1)[0]; } else { t2 = nodes.splice(highest_low[d], 1)[0]; t1 = nodes.splice(lowest_high[d], 1)[0]; } return ([{ d: _make_Intervals(t1.d), nodes: [t1] }, { d: _make_Intervals(t2.d), nodes: [t2] }]); }; var _attach_data = function (node, more_tree) { node.nodes = more_tree.nodes; node.x = more_tree.x; node.y = more_tree.y; node.w = more_tree.w; node.h = more_tree.h; return (node); }; /* non-recursive internal insert function * [] = _insert_subtree(rectangle, object to insert, root to begin insertion at) * @private */ var _insert_subtree = function (options /*node, root*/ ) { var bc; // Best Current node if (!("node" in options)) { options.node = { d: options.intervals, leaf: options.object }; } var node = options.node; var root = options.root; var comparators = options.comparators; // Initial insertion is special because we resize the Tree and we don't // care about any overflow (seriously, how can the first object overflow?) if (root.nodes.length == 0) { _make_Intervals(node.d, root.d); root.nodes.push(node); return; } // Find the best fitting leaf node // choose_leaf returns an array of all tree levels (including root) // that were traversed while trying to find the leaf var tree_stack = _choose_leaf_subtree({ intervals: node.d, root: root, comparators: comparators }); var ret_obj = node; //{x:rect.x,y:rect.y,w:rect.w,h:rect.h, leaf:obj}; // Walk back up the tree resizing and inserting as needed do { //handle the case of an empty node (from a split) if (bc && "nodes" in bc && bc.nodes.length == 0) { var pbc = bc; // Past bc bc = tree_stack.pop(); for (var t = 0; t < bc.nodes.length; t++) if (bc.nodes[t] === pbc || bc.nodes[t].nodes.length == 0) { bc.nodes.splice(t, 1); break; } } else { bc = tree_stack.pop(); } // If there is data attached to this ret_obj if ("leaf" in ret_obj || "nodes" in ret_obj || isArray(ret_obj)) { // Do Insert if (isArray(ret_obj)) { for (var ai = 0; ai < ret_obj.length; ai++) { _expand_intervals(bc.d, ret_obj[ai].d); } bc.nodes = bc.nodes.concat(ret_obj); } else { _expand_intervals(bc.d, ret_obj.d); bc.nodes.push(ret_obj); // Do Insert } if (bc.nodes.length <= _Max_Width) { // Start Resizeing Up the Tree ret_obj = { d: _make_Intervals(bc.d) }; } else { // Otherwise Split this Node // linear_split() returns an array containing two new nodes // formed from the split of the previous node's overflow var a = _linear_split(bc.nodes); ret_obj = a; //[1]; if (tree_stack.length < 1) { // If are splitting the root.. bc.nodes.push(a[0]); tree_stack.push(bc); // Reconsider the root element ret_obj = a[1]; } } } else { // Otherwise Do Resize //Just keep applying the new bounding rectangle to the parents.. _expand_intervals(bc.d, ret_obj.d); ret_obj = { d: _make_Intervals(bc.d) }; } } while (tree_stack.length > 0); }; this.envelope = function () { if (_T && "d" in _T) { // Return a copy return _make_Intervals(_T.d); } else { return _make_Empty(); } } // Intersect with overall tree bounding-box // Returns a segment contained within the pointing box var _intersect_Intervals = function (ray, intervals) { if (!intervals) { if (_T && "d" in _T) { intervals = _T.d; // By default, use the scene bounding box } else { return false; } } var i, j; var parameters = [ [], [] ]; // inv_direction and sign can be pre-computed per ray var inv_direction = []; var sign = []; // Initialize values for (i = 0; i < _Dimensions; i++) { parameters[0].push(intervals[i].a); parameters[1].push(intervals[i].a + intervals[i].b); j = 1 / ray[i].b; inv_direction.push(j); sign.push((j <= 0) ? 1 : 0); } var omin, omax, tmin, tmax; omin = (parameters[sign[0]][0] - ray[0].a) * inv_direction[0]; omax = (parameters[1 - sign[0]][0] - ray[0].a) * inv_direction[0]; for (i = 1; i < _Dimensions; i++) { tmin = (parameters[sign[i]][i] - ray[i].a) * inv_direction[i]; tmax = (parameters[1 - sign[i]][i] - ray[i].a) * inv_direction[i]; if ((omin > tmax) || (tmin > omax)) { return false; } if (tmin > omin) { omin = tmin; } if (tmax < omax) { omax = tmax; } } if (omin >= Infinity || omax <= -Infinity) { return false; } if (omin < 0 && omax < 0) return false; if (omin < 0) omin = 0; var rs = _make_Empty(); for (i = 0; i < _Dimensions; i++) { rs[i].a = ray[i].a + ray[i].b * omin; rs[i].b = ray[i].a + ray[i].b * omax; } return (rs); }; this.intersect_ray = _intersect_Intervals; /* non-recursive internal search function * [ nodes | objects ] = _search_subtree(intervals, [return node data], [array to fill], root to begin search at) * @private */ var _intersect_subtree = function (options) { var hit_stack = []; // Contains the elements that overlap var ray = options.ray; var return_node = options.return_nodes; var return_array = options.return_array; var root = options.root; var comparators = options.comparators; if (_intersect_Intervals(ray, root.d) === false) return (return_array); var load_callback = function (local_tree, local_node) { return (function (data) { local_tree._attach_data(local_node, data); }); }; hit_stack.push(root.nodes); do { var nodes = hit_stack.pop(); for (var i = nodes.length - 1; i >= 0; i--) { var ltree = nodes[i]; var intersect_points = _intersect_Intervals(ray, ltree.d); if (intersect_points !== false) { if ("nodes" in ltree) { // Not a Leaf hit_stack.push(ltree.nodes); } else if ("leaf" in ltree) { // A Leaf !! var tmin = (intersect_points[0].a - ray[0].a) / ray[0].b; if (!return_node) return_array.push({ intersect: tmin, object: ltree.leaf }); else return_array.push({ intersect: tmin, object: ltree }); } /* else if("load" in ltree) { // We need to fetch a URL for some more tree data jQuery.getJSON(ltree.load, load_callback(this, ltree)); delete ltree.load; // i++; // Replay this entry }*/ } } } while (hit_stack.length > 0); return (return_array); }; /* non-recursive internal yield_to function * [ nodes | objects ] = _yield( options ) * @private */ var _yield_to = function (options) { var hit_stack = []; // Contains the nodes that overlap var intervals = options.intervals; var root = options.root; var comparators = options.comparators; var node = null; var yield_leaf = options.yield.leaf; var yield_node = options.yield.node; if (!comparators.overlap_intervals(intervals, root.d)) return; hit_stack.push(root.nodes); do { var nodes = hit_stack.pop(); for (var i = nodes.length - 1; i >= 0; i--) { var ltree = nodes[i]; if (comparators.overlap_intervals(intervals, ltree.d)) { if ("nodes" in ltree) { // Not a Leaf yield_node(ltree); hit_stack.push(ltree.nodes); } else if ("leaf" in ltree) { // A Leaf !! yield_leaf(ltree); } } } } while (hit_stack.length > 0); return; }; /* non-recursive internal search function * [ nodes | objects ] = _search_subtree(intervals, [return node data], [array to fill], root to begin search at) * @private */ var _search_subtree = function (options) { var hit_stack = []; // Contains the elements that overlap var intervals = options.intervals; var return_node = options.return_nodes; var return_array = options.return_array; var root = options.root; var comparators = options.comparators; if (!comparators.overlap_intervals(intervals, root.d)) return (return_array); var load_callback = function (local_tree, local_node) { return (function (data) { local_tree._attach_data(local_node, data); }); }; hit_stack.push(root.nodes); do { var nodes = hit_stack.pop(); for (var i = nodes.length - 1; i >= 0; i--) { var ltree = nodes[i]; if (comparators.overlap_intervals(intervals, ltree.d)) { if ("nodes" in ltree) { // Not a Leaf hit_stack.push(ltree.nodes); } else if ("leaf" in ltree) { // A Leaf !! if (!return_node) return_array.push(ltree.leaf); else return_array.push(ltree); } /* else if("load" in ltree) { // We need to fetch a URL for some more tree data jQuery.getJSON(ltree.load, load_callback(this, ltree)); delete ltree.load; // i++; // Replay this entry }*/ } } } while (hit_stack.length > 0); return (return_array); }; /* quick 'n' dirty function for plugins or manually drawing the tree * [ tree ] = NTree.get_tree(): returns the raw tree data. useful for adding * @public * !! DEPRECATED !! */ this.get_tree = function () { return _T; }; /* quick 'n' dirty function for plugins or manually loading the tree * [ tree ] = NTree.set_tree(sub-tree, where to attach): returns the raw tree data. useful for adding * @public * !! DEPRECATED !! */ this.set_tree = function (new_tree, where) { if (!where) where = _T; return (_attach_data(where, new_tree)); }; this.dimensions = function () { return _Dimensions; } /* non-recursive intersect function * [ nodes | objects ] = NTree.intersect( options ) * @public */ this.intersect = function (options) { if (arguments.length < 1) { throw "Wrong number of arguments. intersect() requires an options object." } if (!("return_nodes" in options)) { options.return_nodes = false; // obj == false for conditionals } if (!("return_array" in options)) { options.return_array = []; } if (!("ray" in options)) { throw "Wrong number of arguments. intersect() requires a ray." } options.root = _T; // should not ever be specified by outside return (_intersect_subtree(options)); }; /* End of NTree.intersect() */ /* non-recursive yield_to function * NTree.yield_to( options ) * @public */ this.yield_to = function (options) { if (arguments.length < 1) { throw "Wrong number of arguments. yield_to() requires an options object." } if (!("return_nodes" in options)) { options.return_nodes = false; // obj == false for conditionals } if (!("return_array" in options)) { options.return_array = []; } if (!("comparators" in options)) { if (!("intervals" in options)) { // If no comparator object is defined, you must define "intervals". throw "Wrong number of options. yield_to() requires at least a set of intervals of " + _Dimensions + "-dimensions."; } else if (options.intervals.length != _Dimensions) { throw "Wrong number of dimensions in input volume. The tree has a rank of " + _Dimensions + "-dimensions."; } else { options.comparators = {}; } } if (!("overlap_intervals" in options["comparators"])) { if (!("intervals" in options)) { // If no default comparators are defined, you must define "intervals". throw "Wrong number of options. yield_to() requires at least a set of intervals of " + _Dimensions + "-dimensions."; } else if (options.intervals.length != _Dimensions) { throw "Wrong number of dimensions in input volume. The tree has a rank of " + _Dimensions + "-dimensions."; } else { options.comparators.overlap_intervals = _overlap_intervals; //Defaults } } if (!("yield" in options)) { options.yield = {}; } if (!("leaf" in options["yield"])) { options.yield.leaf = function (leaf) {}; //Defaults } if (!("node" in options["yield"])) { options.yield.node = function (node) {}; //Defaults } options.root = _T; // should not ever be specified by outside return (_yield_to(options)); }; /* End of NTree.yield_to() */ /* non-recursive search function * [ nodes | objects ] = NTree.search(intervals, [return node data], [array to fill]) * @public */ this.search = function (options /*intervals, return_node, return_array*/ ) { if (arguments.length < 1) { throw "Wrong number of arguments. search() requires an options object." } /*if( !("intervals" in options) ) { throw "Wrong number of options. search() requires at least a set of intervals of " + _Dimensions + "-dimensions."; }*/ if (options.intervals.length != _Dimensions) { throw "Wrong number of dimensions in input volume. The tree has a rank of " + _Dimensions + "-dimensions."; } if (!("return_nodes" in options)) { options.return_nodes = false; // obj == false for conditionals } if (!("return_array" in options)) { options.return_array = []; } if (!("comparators" in options)) { if (!("intervals" in options)) { // If no comparator object is defined, you must define "intervals". throw "Wrong number of options. search() requires at least a set of intervals of " + _Dimensions + "-dimensions."; } else { options.comparators = {}; } } if (!("overlap_intervals" in options["comparators"])) { if (!("intervals" in options)) { // If no default comparators are defined, you must define "intervals". throw "Wrong number of options. search() requires at least a set of intervals of " + _Dimensions + "-dimensions."; } else { options.comparators.overlap_intervals = _overlap_intervals; //Defaults } } if (!("contains_intervals" in options["comparators"])) { if (!("intervals" in options)) { // If no default comparators are defined, you must define "intervals". throw "Wrong number of options. search() requires at least a set of intervals of " + _Dimensions + "-dimensions."; } else { options.comparators.contains_intervals = _contains_intervals; } } options.root = _T; // should not ever be specified by outside return (_search_subtree.apply(this, [options])); }; /* End of NTree.search() */ /* non-recursive insert function * [] = NTree.insert(intervals, object to insert) */ this.insert = function (options /*intervals, obj*/ ) { if (arguments.length < 1) { throw "Wrong number of arguments. insert() requires an options object." } if (options.intervals.length != _Dimensions) { throw "Wrong number of dimensions in input volume. The tree has a rank of " + _Dimensions + "-dimensions."; } if (!("object" in options)) { throw "Wrong number of options. insert() requires an object to insert."; } if (!("comparators" in options)) { if (!("intervals" in options)) { // If no comparator object is defined, you must define "intervals". throw "Wrong number of options. insert() requires at least a set of intervals of " + _Dimensions + "-dimensions."; } else { options.comparators = {}; } } if (!("overlap_intervals" in options["comparators"])) { if (!("intervals" in options)) { // If no default comparators are defined, you must define "intervals". throw "Wrong number of options. insert() requires at least a set of intervals of " + _Dimensions + "-dimensions."; } else { options.comparators.overlap_intervals = _overlap_intervals; //Defaults } } if (!("contains_intervals" in options["comparators"])) { if (!("intervals" in options)) { // If no default comparators are defined, you must define "intervals". throw "Wrong number of options. insert() requires at least a set of intervals of " + _Dimensions + "-dimensions."; } else { options.comparators.contains_intervals = _contains_intervals; } } options.root = _T; // should not ever be specified by outside return (_insert_subtree(options /*{d:_make_Intervals(intervals), leaf:obj}, _T*/ )); }; /* End of NTree.insert() */ /* non-recursive function that deletes a specific * [ number ] = NTree.remove(intervals, obj) */ this.remove = function (options /*intervals, obj*/ ) { var arguments_array = []; if (arguments.length < 1) { throw "Wrong number of arguments. remove() requires an options object." } if (options.intervals.length != _Dimensions) { throw "Wrong number of dimensions in input volume. The tree has a rank of " + _Dimensions + "-dimensions."; } if (!("object" in options)) { options.object = false; // obj == false for conditionals } if (!("comparators" in options)) { if (!("intervals" in options)) { // If no comparator object is defined, you must define "intervals". throw "Wrong number of options. remove() requires at least a set of intervals of " + _Dimensions + "-dimensions."; } else { options.comparators = {}; } } if (!("overlap_intervals" in options["comparators"])) { if (!("intervals" in options)) { // If no default comparators are defined, you must define "intervals". throw "Wrong number of options. remove() requires at least a set of intervals of " + _Dimensions + "-dimensions."; } else { options.comparators.overlap_intervals = _overlap_intervals; //Defaults } } if (!("contains_intervals" in options["comparators"])) { if (!("intervals" in options)) { // If no default comparators are defined, you must define "intervals". throw "Wrong number of options. remove() requires at least a set of intervals of " + _Dimensions + "-dimensions."; } else { options.comparators.contains_intervals = _contains_intervals; } } options.root = _T; // should not ever be specified by outside if (options.object === false) { // Do area-wide delete var numberdeleted = 0; var ret_array = []; do { numberdeleted = ret_array.length; ret_array = ret_array.concat(_remove_subtree.apply(this, [options])); } while (numberdeleted != ret_array.length); return ret_array; } else { // Delete a specific item return (_remove_subtree.apply(this, [options])); } }; /* End of NTree.remove() */ this.toJSON = function () { if (_T) return (JSON.stringify(_T)); }; this.makeTree = function (obj) { if (obj) _T = obj; }; this.fromJSON = function (json) { var temp = JSON.parse(json); if (temp) _T = temp; }; }; /* End of NTree */
Dropdown = require('./webdriver-components/dropdown.js'); Button = require('./webdriver-components/button.js'); const { LOG_LEVELS } = require('../../support/constants.js'); var BrowserWaits = require('../../support/customWaits'); const CucumberRepprter = require('../../support/reportLogger'); class CreateCaseStartPage { constructor(){ this.caseCaseFilterContainer = $('exui-filter-case ccd-create-case-filters'); this.header = '#content h1'; this._jurisdiction = new Dropdown('#cc-jurisdiction'); this._caseType = new Dropdown('#cc-case-type'); this._event = new Dropdown('#cc-event'); this._submitButton = new Button('#content button'); this._jurisdictionSelector = '#cc-jurisdiction'; this._startBtn = element(by.xpath('//button[text() = \'Start\']')); this.jurisdictionOptions = $$('#cc-jurisdiction option'); } async selectJurisdiction(jurisdiction){ let locatorString = '//*[@id = \'cc-jurisdiction\']/option['; let i = 0; const options = jurisdiction.split('|'); for (const option of options) { if (i === 0) { locatorString += `contains(text(), '${option.trim()}')`; } else { locatorString += ` or contains(text(), '${option.trim()}')`; } i++; } locatorString = locatorString + ']'; var e = element(by.xpath(locatorString)); await BrowserWaits.waitForElement(e); await e.click(); } async selectCaseType(caseType){ let locatorString = '//*[@id = \'cc-case-type\']/option['; let i = 0; const options = caseType.split('|'); for (const option of options) { if (i === 0) { locatorString += `contains(text(), '${option.trim()}')`; } else { locatorString += ` or contains(text(), '${option.trim()}')`; } i++; } locatorString = locatorString + ']'; var e = element(by.xpath(locatorString)); await BrowserWaits.waitForElement(e); await e.click(); // await this._caseType.selectFromDropdownByText(option); } async selectEvent(option){ var e = element(by.xpath('//*[@id = "cc-event"]/option[text() = "' + option + '"]')); await BrowserWaits.waitForElement(e); await e.click(); // await this._event.selectFromDropdownByText(option); } async startCaseCreation(jurisdiction, caseType, event){ this.selectJurisdiction(jurisdiction); this.selectCaseType(caseType); this.selectEvent(event); } async clickStartButton() { await this._submitButton.waitForElementToBeClickable(); await this._submitButton.click(); // await BrowserWaits.waitForElementClickable(this._startBtn); // await browser.executeScript('arguments[0].scrollIntoView()', // this._startBtn.getWebElement()); // await this._startBtn.click(); } async getPageHeader(){ await BrowserWaits.waitForElement($(this.header)); return await $(this.header).getText(); } async amOnPage(){ try{ await BrowserWaits.waitForElement(this.caseCaseFilterContainer); return true; }catch(err){ await CucumberRepprter.AddMessage('Create case page not displayed ' + err.message + ' : ' + err.stack), LOG_LEVELS.Error; return false; } } async getLoadedJurisdictionsCount(){ return await this.jurisdictionOptions.count(); } } module.exports = CreateCaseStartPage;
// CHARACTER COUNTER function $(() => { $('.new-tweet textarea').on('input', function() { const textAmount = $(this).val().length; const remaining = 140 - textAmount; const counter = $('.counter'); counter.text(remaining); if (remaining < 0) { counter.addClass('negative-count'); } else { counter.removeClass('negative-count'); } }); });
import React from 'react'; import store from 'store'; import StarRating from 'ui/starRating'; require("assets/styles/reviews.scss"); export default React.createClass({ render: function(){ return ( <div className="reviewFlex prodDetailContainer"> {this.props.reviews.map(function(item, i) { return ( <div className="eachReview" key={i}> <div className="reviewTitle">{item.title}</div> <StarRating rating={item.rating} /> <div className="reviewText">{item.text}</div> </div> ) })} </div> ) } })
import { connect } from 'react-redux'; import { OPEN_FILE, NEXT_PAGE, PREV_PAGE, START_ADD_NOTE, SCALE_CHANGED, SET_PAGE_NUMBER, } from '../actions/file'; import FileControl from '../components/FileControl'; function mapStateToProps(state) { const { file } = state; const { currentPageNum, scale } = file || {}; return { apiState: file.apiState, dataApi: file.dataApi, pageNum: currentPageNum, scale, }; } function mapDispatchToProps(dispatch) { return { openFile: () => dispatch({ type: OPEN_FILE }), nextPage: () => dispatch({ type: NEXT_PAGE }), prevPage: () => dispatch({ type: PREV_PAGE }), addNote: () => dispatch({ type: START_ADD_NOTE }), scaleChanged: (event, value) => dispatch({ type: SCALE_CHANGED, scale: value }), textChanged: (e) => dispatch({ type: SET_PAGE_NUMBER, page: e.target.value }), }; } export default connect(mapStateToProps, mapDispatchToProps)(FileControl);
const { ApolloServer, gql } = require('apollo-server'); const data = require('./data/pokemon.json'); const types = gql` """ Height of the pokemon, ranges between a minimum and maximum value """ type Height { minimum: String maximum: String } """ Weight of the pokemon, ranges between a minimum and maximum value """ type Weight { minimum: String maximum: String } type Pokemon { """ Definiting trait of the Pokemon e.g. "Seed Pokémon" """ classification: String """ All eventual evolutions of the pokemon, should be ordered by sequence e.g. [B, C] - A > B > C """ evolutions: [Pokemon] height: Height """ ID as in Pokedex e.g. "050" """ id: ID! imgSrc: String name: String resistances: [String] types: [String] weaknesses: [String] weight: Weight } `; const queries = gql` type Query { pokemon: [Pokemon]! """ Provide full ID as in Pokedex including leading zeros e.g. id: "003" """ pokemonById(id: String!): Pokemon """ Provide full or partial name, will return all matches (not case sensitive) e.g. name: "pika" """ pokemonByPartialName(name: String!): [Pokemon]! """ Provide name (not case sensitive) e.g. name: "pikachu" """ pokemonByName(name: String!): Pokemon """ Provide type, will return all matches (not case sensitive) e.g. type: "poison" """ pokemonByType(type: String!): [Pokemon]! } `; const typeDefs = gql` ${types} ${queries} `; const resolvers = { Pokemon: { evolutions: ({ evolutions }) => { if (!evolutions) { return []; } return evolutions.map((ev) => data.find((d) => d.id === ev.id)); }, }, Query: { pokemon: () => data, pokemonByName: (_, params) => { return data.find( (monster) => monster.name.toLowerCase() === params.name.toLowerCase() ); }, pokemonByPartialName: (_, params) => { return data.filter((monster) => monster.name.toLowerCase().includes(params.name.toLowerCase()) ); }, pokemonById: (_, params) => { return data.find((monster) => monster.id === params.id); }, pokemonByType: (_, params) => { return data.filter((monster) => { return monster.types.some((type) => { return type.toLowerCase() === params.type.toLowerCase(); }); }); }, }, }; const resolveCorsOptions = () => { if (!process.env.CORS_ORIGIN) { return {}; } return { cors: { allowedHeaders: 'Content-Type,Authorization', methods: 'POST', origin: new RegExp(process.env.CORS_ORIGIN), }, }; }; const server = new ApolloServer({ ...resolveCorsOptions(), introspection: true, resolvers, typeDefs, }); const PORT = process.env.PORT || 4000; server.listen({ port: PORT }).then(({ url }) => { console.log(`🚀 Server ready at ${url}`); });
const chartSize = { width: 1000, height: 600 }; const margin = { left: 100, right: 10, top: 20, bottom: 150 }; const width = chartSize.width - margin.left - margin.right; const height = chartSize.height - margin.top - margin.bottom; const removePaths = () => d3 .select("#chart-area") .selectAll("path") .remove(); const initChart = () => { const svg = d3 .select("#chart-area svg") .attr("width", chartSize.width) .attr("height", chartSize.height); const g = svg .append("g") .attr("class", "prices") .attr("transform", `translate(${margin.left},${margin.top})`); g.append("text") .attr("class", "x axis-label") .attr("x", width / 2) .attr("y", height + 140) .text("Dates"); g.append("text") .attr("transform", "rotate(-90)") .attr("class", "y axis-label") .attr("y", -60) .attr("x", -height / 2) .text("Closed Price"); g.append("g").attr("class", "y-axis"); g.append("g") .attr("class", "x-axis") .attr("transform", `translate(0,${height})`); }; const update = (quotes, noOfAverageDays) => { const line = d3 .line() .x(q => x(q.Time)) .y(q => y(q.Close)); const smaLine = d3 .line() .x(q => x(q.Time)) .y(q => y(q.sma)); const svg = d3.select("#chart-area svg"); const firstQuote = _.first(quotes); const lastQuote = _.last(quotes); const maxValue = _.get(_.maxBy(quotes, "Close"), "Close", 0); const minValue = _.get(_.minBy(quotes, "Close"), "Close", 0); const x = d3 .scaleTime() .range([0, width]) .domain([new Date(firstQuote.Date), new Date(lastQuote.Date)]); const x_axis = d3.axisBottom(x); svg.select(".x-axis").call(x_axis); const y = d3 .scaleLinear() .domain([minValue, maxValue]) .range([height, 0]); const y_axis = d3.axisLeft(y).ticks(10); svg.select(".y-axis").call(y_axis); const g = svg.select(".prices"); g.append("path") .attr("class", "close") .attr("d", line(quotes)); g.append("path") .attr("class", "sma") .attr("d", smaLine(quotes.slice(noOfAverageDays - 1))); }; const parseNumerics = ({ Date, Volume, AdjClose, ...numerics }) => { _.forEach(numerics, (v, k) => (numerics[k] = +v)); const Time = new window.Date(Date); return { Date, Time, ...numerics }; }; const calculateAverages = transactions => { let totalWinAmount = 0; let totalLossAmount = 0; let totalWins = 0; let totalLosses = 0; for (let index = 0; index < transactions.length; index++) { const transaction = transactions[index]; const net = transaction.sell.Close - transaction.buy.Close; if (net > 0) { totalWinAmount += net; totalWins++; } else { totalLossAmount += net; totalLosses++; } } const totalTransactions = transactions.length; const averageWinAmount = totalWinAmount / totalWins; const averageLossAmount = totalLossAmount / totalLosses; const netAmount = totalWinAmount + totalLossAmount; const winPercentage = _.round((totalWins / totalTransactions) * 100, 2); return { totalLossAmount, totalWinAmount, totalLosses, totalWins, averageWinAmount, averageLossAmount, netAmount, winPercentage, totalTransactions }; }; const removeStatsTable = () => { d3.select(".statTable") .selectAll("tbody") .remove(); }; const drawStatsTable = transactions => { const statFields = [ "played", "wins", "losses", "win %", "loss multiple", "", "average win", "average loss", "win multiple", "", "net", "expectancy" ]; const { totalWinAmount, totalLosses, totalWins, averageWinAmount, averageLossAmount, netAmount, winPercentage, totalTransactions } = calculateAverages(transactions); const table = d3.selectAll(".statTable"); const tableBody = table.append("tbody"); const stats = [ totalTransactions, totalWins, totalLosses, `${winPercentage}%`, _.round(totalLosses / totalWins, 2), "", _.round(averageWinAmount), _.round(-averageLossAmount), _.round(averageWinAmount / -averageLossAmount, 2), "", _.round(netAmount), _.round(totalWinAmount / totalTransactions) ]; const rows = tableBody .selectAll("tr") .data(statFields) .enter() .append("tr") .text(d => d) .append("td") .text((d, i) => stats[i]); }; const removeTransactionTable = () => { const table = d3.select("#transactions"); table.selectAll("tbody").remove(); }; const drawTransactionTable = transactions => { const table = d3.select("#transactions"); const tableBody = table.append("tbody"); const rows = tableBody .selectAll("tr") .data(transactions) .enter() .append("tr"); const cells = rows .selectAll("td") .data(d => { const buyPrice = _.round(d.buy.Close); const sellPrice = _.round(d.sell.Close); const difference = sellPrice - buyPrice; return [d.buy.Date, buyPrice, d.sell.Date, sellPrice, difference]; }) .enter() .append("td") .text(d => d); }; const transaction = (buy, sell) => { return { buy, sell }; }; const detectTransaction = (quotes, noOfDays) => { const transactions = []; let stockBought = false; let buy = []; for (let index = noOfDays; index < quotes.length; index++) { const { sma, Close } = quotes[index]; if (Close > sma && !stockBought) { stockBought = true; buy = quotes[index]; } if ((Close < sma || index == quotes.length - 1) && stockBought) { stockBought = false; transactions.push(transaction(buy, quotes[index])); } } return transactions; }; const analysedata = (quotes, noOfDays) => { for (let index = noOfDays; index <= quotes.length; index++) { const hundredQuotes = quotes.slice(index - noOfDays, index); const hundredDayAverage = _.sum(_.map(hundredQuotes, "Close")) / noOfDays; quotes[index - 1].sma = _.round(hundredDayAverage); } return detectTransaction(quotes, noOfDays); }; const formatDate = time => { return new Date(time).toJSON().split("T")[0]; }; const showSlider = (times, quotes) => { const slider = d3 .sliderHorizontal() .min(0) .max(times.length - 1) .width(800) .default([0, times.length - 1]) .tickFormat(index => times[_.floor(index)].toString().split(" ")[3]) .on("onchange", val => { const startDate = quotes[_.floor(val[0])].Date; const endDate = quotes[_.floor(val[1])].Date; d3.select("#range-label").text(`${startDate} to ${endDate}`); const quotesBetweenRange = quotes.slice(_.floor(val[0]), _.floor(val[1])); removePaths(); update(quotesBetweenRange, d3.select(".averageInput").property("value")); }); d3.select("#slider-container") .append("svg") .attr("width", 1000) .attr("height", 100) .append("g") .attr("transform", "translate(30,30)") .call(slider); }; const showAverageInput = quotes => { a = d3 .select(".some") .append("input") .attr("class", "averageInput") .attr("type", "number") .attr("min", "1") .attr("value", 100) .attr("max", "3000") .on("input", function() { analysedata(quotes, this.value); removePaths(); update(quotes, this.value); const trans = detectTransaction(quotes, this.value); removeTransactionTable(); removeStatsTable(); drawTransactionTable(trans); drawStatsTable(trans); }); }; const visualizeQuotes = quotes => { const transactions = analysedata(quotes, 100); initChart(); showSlider(_.map(quotes, "Time"), quotes); update(quotes, 100); drawTransactionTable(transactions); drawStatsTable(transactions); showAverageInput(quotes); }; const main = () => { d3.csv("data/equity.csv", parseNumerics).then(visualizeQuotes); }; window.onload = main;
module.exports = function(app) { // require('./input/btn-promis')(app); // require('./input/input-checkbox')(app); // require('./input/input-dropdown')(app); // require('./input/input-focus')(app); // require('./input/input-pagination')(app); // require('./input/input-slider')(app); // require('./input/input-tags')(app); require('./output/alert-error')(app); // require('./output/img-slider')(app); // require('./social/social-shareFb')(app); // require('./social/social-shareGl')(app); // require('./social/social-shareTw')(app); require('./uiElem/header-site')(app); require('./wrap/svg-i')(app); require('./wrap/window-modal')(app); require('./wrap/window-modalHash')(app); require('./wrap/window-modalHashOut')(app); };
// eslint-disable-next-line no-unused-vars import React from 'react'; import './UXPinWrapper.css'; export default function UXPinWrapper({ children }) { if (!document.getElementById('chi-css')) { const chiCss = document.createElement('link'); chiCss.setAttribute('rel', 'stylesheet'); chiCss.setAttribute('href', 'https://assets.ctl.io/chi/3.15.0/chi.css'); chiCss.setAttribute('id', 'chi-css'); document.head.appendChild(chiCss); } if (!document.getElementById('chi-js')) { const chiJs = document.createElement('script'); chiJs.setAttribute('src', 'https://assets.ctl.io/chi/3.15.0/js/chi.js'); chiJs.setAttribute('id', 'chi-js'); document.head.appendChild(chiJs); } if (!document.getElementById('chi-ce-module')) { const chiCeModule = document.createElement('script'); chiCeModule.setAttribute('src', 'https://assets.ctl.io/chi/3.15.0/js/ce/ux-chi-ce/ux-chi-ce.esm.js'); chiCeModule.setAttribute('type', 'module'); chiCeModule.setAttribute('id', 'chi-ce-module'); document.head.appendChild(chiCeModule); } if (!document.getElementById('chi-ce-nomodule')) { const chiCeNomodule = document.createElement('script'); chiCeNomodule.setAttribute('src', 'https://assets.ctl.io/chi/3.15.0/js/ce/ux-chi-ce/ux-chi-ce.js'); chiCeNomodule.setAttribute('nomodule', ''); chiCeNomodule.setAttribute('id', 'chi-ce-nomodule'); document.head.appendChild(chiCeNomodule); } /* eslint-disable */ return ( <div className="chi" style={{resize: 'both'}}> {children} </div> ); /* eslint-enable */ }
/* Ser autenticavel significa ter o metodo autenticar. Duck typing (formato usado em linguagem interpretadas e fracamente tipadas) - aplicação do duck test: "Se ele anda como um pata e fala como um pato, então deve ser um pato" */ export class SistemaAutenticacao { static login(autenticavel, senha) { if (SistemaAutenticacao.ehAutenticavel(autenticavel)) { return autenticavel.autenticar(senha); } return false; } // Verifica se o objeto implementa a "interface" autenticavel (classes que contenham o método autenticar) static ehAutenticavel(autenticavel) { // Propiedades (campos ou funções) são chaves dentro do objeto na memória return "autenticar" in autenticavel && autenticavel.autenticar instanceof Function; } }
import React from 'react'; import styled from 'styled-components'; class MapCircle extends React.Component { makeLeft = number => { if (typeof number !== 'number') return 0; if (number < 10) return 0; else if (number >= 10 && number < 100) return 5; else return 12; }; render() { const { count, name, type, position, getRoomIdList } = this.props; const colorTable = { room: ['white', '#326cf9', '#326cf9', '#326cf9', 'white', '#326cf9'], subway: ['#1ba885', 'white', '#1ba885', 'white', '#1ba885', '#1ba885'], univ: ['#8782ea', 'white', '#8782ea', 'white', '#8782ea', '#8782ea'], }; const typeTable = { room: count, subway: <i className="fas fa-subway" />, univ: <i className="fas fa-university" />, }; const cicleClick = type => { if (type === 'room') { getRoomIdList(position.room_id.slice(0, 10).join(',')); } }; return ( <CircleBox ref={this.props.innerRef} onClick={() => cicleClick(type)}> <Count left={name && name.length * 12 + 42 + this.makeLeft(typeTable[type])} type={type} colorTable={colorTable} > {typeTable[type]} </Count> <Area type={type} colorTable={colorTable}> {name} </Area> </CircleBox> ); } } export default React.forwardRef((props, ref) => ( <MapCircle innerRef={ref} {...props} /> )); const CircleBox = styled.div` display: flex; align-items: center; flex-wrap: nowrap; position: absolute; cursor: pointer; font-size: 12px; `; const Count = styled.h1` position: relative; left: ${({ left }) => `-${left}px`}; height: 25px; padding: 0 8px; color: ${({ type, colorTable }) => colorTable[type][0]}; background-color: ${({ type, colorTable }) => colorTable[type][1]}; border: 1px solid ${({ type, colorTable }) => colorTable[type][2]}; border-radius: 50px; text-align: center; line-height: 25px; font-weight: bold; `; const Area = styled.p` position: relative; height: 25px; padding: 0 10px 0 30px; color: ${({ type, colorTable }) => colorTable[type][3]}; background-color: ${({ type, colorTable }) => colorTable[type][4]}; border: 1px solid ${({ type, colorTable }) => colorTable[type][5]}; border-radius: 30px; text-align: center; line-height: 25px; `;
const sha256 = require("js-sha256"); module.exports = db => { // Salt for Hash const SALT = "aKiRa is a PokeMON"; /** * =========================================== * Controller logic * =========================================== */ // Controllers for Creating New Tweet const newTweetForm = (req, res) => { let checkSessionCookieHash = sha256( req.cookies.user_id + "logged_id" + SALT ); if (req.cookies.loggedIn === checkSessionCookieHash) { res.render("tweets/NewTweet", { cookies: req.cookies }); } else { res.send("You must be logged in to post a tweet!"); } }; const newTweetPost = (req, res) => { // use user model method `create` to create new user entry in db db.tweets.newTweet(req.body, (err, queryResult) => { if (err) { console.log("Errror creating tweet:", err); res.sendStatus(500); } if (queryResult.rowCount >= 1) { console.log("Tweet Posted"); } else { console.log("User could not be created"); } // redirect to home page after creation res.redirect("/"); }); }; // Controller for passing the tweets props from queryResult on to index.jsx to be rendered in the form const showAllTweetsForm = (req, res) => { db.tweets.showAllTweets(req.body, (err, queryResult) => { if (err) { console.err("Error getting Tweets: ", err); } res.render("index", { tweets: queryResult, cookies: req.cookies }); }); }; const showFollowingTweetsForm = (req, res) => { db.tweets.showFollowingTweets(req.cookies, (err, queryResult) => { if (err) { console.err("Error Showing Following Tweets: ", err); } res.render("index", { tweets: queryResult, cookies: req.cookies }); }); }; const showFollowerTweetsForm = (req, res) => { db.tweets.showFollowerTweets(req.cookies, (err, queryResult) => { if (err) { console.err("Error Showing Following Tweets: ", err); } res.render("index", { tweets: queryResult, cookies: req.cookies }); }); }; const showSingleTweetForm = (req, res) => { db.tweets.showSingleTweetForm(req.params, (err, queryResult) => { if (err) { console.log("Error showing Single Tweet:", err); } res.render("tweets/SingleTweetForm", { tweets: queryResult, cookies: req.cookies }); }); }; /** * =========================================== * Export controller functions as a module * =========================================== */ return { newTweetForm, newTweetPost, showAllTweetsForm, showFollowingTweetsForm, showFollowerTweetsForm, showSingleTweetForm }; };
const dbConnection = require("../database/db_connection"); const postData = ( first_name, last_name, interests, email, phone_number) => { return new Promise((resolve,reject)=>{ dbConnection.query( "INSERT INTO contacts (first_name,last_name,interests,email,phone_number) VALUES ($1, $2, $3 ,$4,$5)", [first_name, last_name, interests, email, phone_number], (err, res) => { if(err) { reject(err); }else{ resolve(res); } }); }); } module.exports = postData;
import './App.css'; import img from './assets/img-2.jpeg'; import RegistrationForm from './components/registrationForm'; function App() { return ( <div className="app-layout"> <img src={img} alt="medical professional on their mobile device" className="bg-img"/> <RegistrationForm/> </div> ); } export default App;
#!/usr/bin/env node 'use strict'; var args , c , mpq , mpqFile , archive , user , userVars = [ "magic" , "userDataSize" , "mpqHeaderOffset" , "userDataHeaderSize" , "content" ] args = process.argv.slice(2) mpq = require('../lib/mpq.js') if (args[0] === "-I") { if (args[1] !== undefined) { mpqFile = new mpq(args[1]) mpqFile.printHeaders() } else { console.error("Please specify a [filename] for -I") process.exit(1) } } else { console.error("Please use 'mpqjs -I [filename]'") process.exit(1) } // MPQ archive header // ------------------ // magic 'MPQ\x1a' // header_size 44 // archive_size 232992 // format_version 1 // sector_size_shift 3 // hashTableOffset 232576 // blockTableOffset 232832 // hashTable_entries 16 // blockTable_entries 10 // extended_blockTableOffset 0 // hashTableOffset_high 0 // blockTableOffset_high 0 // offset 1024 // MPQ user data header // -------------------- // magic 'MPQ\x1b' // user_data_size 512 // mpq_headerOffset 1024 // user_data_header_size 60 // content '\x05\x08\x00\x02,StarCraft II replay\x1b11\x02\x05\x0c\x00\t\x02\x02\t\x02\x04\t\x08\x06\t\x04\x08\t\xda\xba\x02\n\t\xbe\xb3\x02\x04\t\x04\x06\t\xfe\xd1\x02'
var SLEEP_TIME = 15000; var SLEEP_ONE_SECOND = 1000; var MESSAGE_TIME = 30; var EPISODES_COUNT_OFFSET = 1; var EPISODES_LENGTH_OFFSET = 2; var STREAMING = "streaming"; var OPENING = "opening"; var ENDING = "ending"; var SYNC = "sync"; var syncPorperties = ["isStreaming","isSkipingOpening", "isSkipingEnding", "openingStart", "openingEnd", "endingStart"]; var videoPlayer = document.getElementById('video1_html5_api'); var videoDiv = document.getElementById("video1"); var video_button_div = document.createElement("div"); var video_button = document.createElement("button"); var parentActiveEpisode = document.getElementsByClassName('active')[2].parentElement; var activeEpisode = parentActiveEpisode.firstChild; var episodes = document.getElementsByClassName('episodes')[0].childNodes; var episodeLabel = document.getElementsByClassName("singletitlebottom")[0].childNodes[3].childNodes[1]; var animeName = document.querySelector('a[id="titleleft"]');
// get our const snsApp = { fb: { appId: 0, //DP }, tw: { appId: 0, }, instagram: { appId: 0 } } module.exports = { fb (opts) { //share dialog, need appId if(!opts) { console.log('empty share information') return } const pre = 'https://www.facebook.com/dialog/feed' const obj = { app_id: snsApp.fb.appId, redirect_uri: opts.redirect, picture: opts.img, name: opts.title, link: opts.link, description: opts.desc, display: 'popup', show_error: 'yes', } return `${pre}?${qs.stringify(obj)}` }, tw (opts) { const pre = 'https://twitter.com/share?text={0}&via=RINGS.TV&url={1}' const obj = { text: opts.desc, via: 'RINGS.TV', url: opts.redirect } return `${pre}?${qs.stringify(obj)}` }, wx (opts) { }, instagram (opts) { } }
import React from 'react'; import styled from 'styled-components'; import PropTypes from 'prop-types'; import { Card } from 'semantic-ui-react'; const Footer = styled.div` display: flex; justify-content: space-between; `; const CardFooter = ({ children }) => { return ( <Card.Content as="footer"> <Footer>{children}</Footer> </Card.Content> ); }; CardFooter.propTypes = { children: PropTypes.node.isRequired }; export default CardFooter;
$(function() { $('.page-header h1').dblclick(function(event) { location.reload(); }); $('.challenge-card').flip({ trigger: 'manual' }); $('.clue-card').click( function(event) { var card = $(this).parent('.challenge-card'); if (card.hasClass('done')) { card.children('.clue-card')//. //zoomTo({ targetsize: 0.1, root: $('.container') }); } else { card.addClass('done').flip(true); } }); $('.dollar-level-card'). click(function(event) { $(this).fadeOut(400, function() { $(this).next('.clue-card'). fadeIn(400)//. //zoomTo({ targetsize: 0.5 }); }); }); });
setInterval(()=> { let date = new Date(); //Gets local time let hour = date.getHours(); let min = date.getMinutes(); let sec = date.getSeconds(); //Correctly displays time based on standard time format let timeOfDay = (hour >= 12) ? 'PM' : 'AM'; hour = (hour < 10) ? "0" + hour : (hour == 0) ? 12 : (hour > 12) ? "0" + (hour - 12) : hour; min = (min < 10) ? "0" + min : min; sec = (sec < 10) ? "0" + sec : sec; document.getElementById("time").innerHTML = `${hour}:${min}:${sec} ${timeOfDay}`; })
import React from 'react'; import BigButton from './BigButton'; function BottomButtons (props) { return ( <div id='bottom-buttons-area' className='flexFixedSize flexContainerRow'> <BigButton text='Next' onClick={props.nextClick}/> <BigButton text='Submit'/> </div> ); } export default BottomButtons;
'use strict' const hdr = require('hdr-histogram-js') const highestTrackableValue = 3.6e12 // 1 hour class Histogram { constructor () { this._histogram = hdr.build({ highestTrackableValue }) this.reset() } get min () { return this._min } get max () { return this._max } get avg () { return this._count === 0 ? 0 : this._sum / this._count } get sum () { return this._sum } get count () { return this._count } get median () { return this.percentile(50) } get p95 () { return this.percentile(95) } percentile (percentile) { return this._histogram.getValueAtPercentile(percentile) } record (value) { if (this._count === 0) { this._min = this._max = value } else { this._min = Math.min(this._min, value) this._max = Math.max(this._max, value) } this._count++ this._sum += value this._histogram.recordValue(value) } reset () { this._min = 0 this._max = 0 this._sum = 0 this._count = 0 this._histogram.reset() } } module.exports = Histogram
import React from 'react'; import BootstratTable from 'react-bootstrap-table-next'; import 'react-bootstrap-table-next/dist/react-bootstrap-table2.min.css'; function occupancyFormatter(cell, row) { return ( <label> <span>{cell.numAdults} adultos</span> <span data-visible="accommodation">&nbsp;·&nbsp;</span> <span>{cell.numChilds} niños</span> <span data-visible="accommodation">&nbsp;·&nbsp;</span> <span>{cell.numChilds} bebes</span> </label> ) } const columns = [ { dataField: 'roomName', text: 'Habitación' }, { dataField: 'offerName', text: 'Oferta' }, { dataField: 'boardName', text: 'Régimen' }, { dataField: 'occupancy', text: 'Ocupación', formatter : occupancyFormatter, }, { dataField: 'netPrice', text: 'Precio', sort: true }, { dataField: 'currency', text: '' }]; const sortOption = { // No need to configure sortFunc per column sortFunc: (a, b, order, dataField) => { ///Quitamos la ',' al valor para poder hacer una ordenación correcta const valueA = Number(a.replace(/(,)/g,"")); const valueB = Number(b.replace(/(,)/g,"")); if (order === 'asc') { return valueA- valueB; // asc } return valueB- valueA; // asc } }; const defaultSorted = [ { dataField: "netPrice", order: "asc" } ]; const SearchDataResultComponent = (props) => { if( props.result.isFetching ) return (<div id="search-results">Loading....</div>); return( <div id="search-results"> <BootstratTable keyField='rateCode' data={props.result.data} columns={columns} bordered={ false } defaultSorted={defaultSorted} sort={ sortOption } striped hover condensed noDataIndication="Lo sentimos, no hay tarifas disponibles" /> </div> ); } export default SearchDataResultComponent;
import React from 'react'; import Markdown from 'react-markdown'; class Report extends React.Component { constructor(props) { super(props); this.state = { kmom: props.match.params.kmom, content: "", output: "" }; } loadData() { let that = this; fetch("https://me-api.daib17.me/reports/" + this.state.kmom) .then(function (response) { return response.json(); }) .then(function (result) { that.setState({ content: result.data.content }); }) .catch(function() { that.setState({ output: "Report not found." }); }); } componentDidMount() { this.loadData(); } componentDidUpdate(prevProps) { if (this.props.match.params.kmom !== prevProps.match.params.kmom) { this.setState({ kmom: this.props.match.params.kmom, content: "", output: "" }, this.loadData); } } render() { return ( <div className="main"> <h1>{this.state.kmom}</h1> <hr /> <Markdown source={this.state.content} /> <br /> <p>{this.state.output}</p> </div> ); } } export default Report;
const Gridfunc = { adjacentTop: function (position) { if (position - 5 > 0) { return position - 5; } else return false; }, adjacentBottom: function (position, gridSize) { if ((position + 5 > 0) && (position + 5 <= gridSize)) { return position + 5; } else return false; }, adjacentLeft: function (position) { if (position === 0) { return false; } else if ((position - 1) % 5 === 0) { return false; } else return position - 1; }, adjacentRight: function (position, gridSize) { if (position + 1 > gridSize) { return false; } else if (position % 5 === 0) { return false; } else return position + 1; }, adjacent: function (position1, position2, gridSize) { if ( (this.adjacentTop(position1) === position2) || (this.adjacentBottom(position1, gridSize) === position2) || (this.adjacentLeft(position1) === position2) || (this.adjacentRight(position1, gridSize) === position2) ) { return true; } else return false; }, singleTile: function (array) { if (array.length === 1) { return true; } else return false; }, twoAdjacentTiles: function (array, gridSize) { if (array.length != 2) { return false; } else if (this.adjacent(array[0], array[1], gridSize)) { return true; } else return false; }, threeAdjacentTiles: function (array, gridSize) { if (array.length != 3) { return false; } else if (!(this.twoAdjacentTiles([array[0], array[1]], gridSize))) { return false; } else if ( (array[1] === this.adjacentBottom(array[0], gridSize)) && (array[2] === this.adjacentBottom(array[1], gridSize)) || (array[1] === this.adjacentRight(array[0], gridSize)) && (array[2] === this.adjacentRight(array[1], gridSize)) ) { return true; } else return false; }, fourAdjacentTiles: function (array, gridSize) { if (array.length != 4) { return false; } else if (!(this.threeAdjacentTiles([array[0], array[1], array[2]], gridSize))) { return false; } else if ( (array[2] === this.adjacentBottom(array[1], gridSize)) && (array[3] === this.adjacentBottom(array[2], gridSize)) || (array[2] === this.adjacentRight(array[1], gridSize)) && (array[3] === this.adjacentRight(array[2], gridSize)) ) { return true; } else return false; }, twoByTwoSquare: function (array, gridSize) { if (array.length != 4) { return false; } else if ( (this.adjacent(array[0], array[1], gridSize)) && (this.adjacent(array[2], array[3], gridSize)) && (this.adjacentBottom(array[0], gridSize) === array[2]) ) { return true; } else return false; }, validSelectionGroup: function (array, gridSize) { if ( this.singleTile(array) || this.twoAdjacentTiles(array, gridSize) || this.threeAdjacentTiles(array, gridSize) || this.fourAdjacentTiles(array, gridSize) || this.twoByTwoSquare(array, gridSize) ) { return true; } else return false; }, //returns [lst tile in row, number of free tiles in row] freeTilesInRow: function (position, columns) { if (position % columns === 0) { return [position, 1]; } else { var i = 0; while (i < columns) { var lastTile = position + i; if (lastTile % columns === 0) { break; } i++; } } return [lastTile, i + 1]; }, freeTilesInColumn: function (position, columns, tiles) { var lastInRow = this.freeTilesInRow(position, columns); var lastInRow = lastInRow[0]; return 1 + ((tiles - lastInRow) / columns); }, createGroupSizeStrings: function (position, cols, tiles) { var columns = this.freeTilesInRow(position, cols); var columns = columns[1]; var rows = this.freeTilesInColumn(position, cols, tiles); var colStrings = []; var i = 1; while (i <= columns) { colStrings.push(`${i}x`); i++; } var colsAndRows = []; for (var col of colStrings) { var j = 1; while (j <= rows) { colsAndRows.push(`${col}${j}`); j++; } } return colsAndRows; }, convertStringsToPairs: function (array) { var pairs = []; for (var string of array) { pairs.push([string.split('x')[0], string.split('x')[1]]); } return pairs; }, makeArrayOfPairsAndStrings: function (position, cols, tiles) { var strings = this.createGroupSizeStrings(position, cols, tiles); var pairs = this.convertStringsToPairs(strings); var array = pairs.map(function (pair, i) { return [pairs[i], strings[i]]; }); return array; }, findRow: function (position, columns, tiles) { var rows = tiles / columns; var row = parseInt((position / rows) + 1); return row; } }; module.exports = Gridfunc;
function str2XML(text) { var doc; if (window.ActiveXObject) { doc = new ActiveXObject('Microsoft.XMLDOM'); doc.async = 'false'; doc.loadXML(text); } else { var parser = new DOMParser(); doc = parser.parseFromString(text, 'text/xml'); } return doc; } function requestFileAsync(filePath, obj, onload) { onUtilityRespond = function(fileData) { onload(fileData, obj); }; utilityPort.postMessage({id: "loadFile", filePath: filePath}); } // XSLT converter function XsltConverter(formatter, pageFormatter, onload) { this.fileNameRegEx = pageFormatter.fileNameRegEx; requestFileAsync(resolvePath(formatter.xsl), this, function(fileData, obj) { obj.formatterXsl = fileData; requestFileAsync(resolvePath(pageFormatter.xsl), obj, function(fileData, obj) { obj.pageXsl = fileData; obj._embed(); onload(); }); }); } XsltConverter.prototype = { _embed: function() // embed pageXsl into formatterXsl { var pageData = this.pageXsl.match(/<!--\s*BEGIN\s*-->\s*([\s\S]*)\s*<!--\s*END\s*-->/m); this.xsl_data = this.formatterXsl.replace(/<!--\s*PAGE_INCLUDE\s*-->/, pageData[1]); }, convert: function(page_data) { var xml_data = HTMLtoXML(page_data); xml_data = xml_data.replace(/\s+xmlns="[^"]*"/, ""); // HACK!!! var xsl_doc = str2XML(this.xsl_data); var xml_doc = str2XML(xml_data); var result = applyXSLT(xsl_doc, xml_doc); var title = xml_doc.evaluate(this.fileNameRegEx, xml_doc, null, XPathResult.ANY_TYPE, null) .iterateNext().textContent; return {xml: result, title: title}; }, serialize: function(xmlData) { var serializer = new XMLSerializer(); return serializer.serializeToString(xmlData); }, };
/** * @author loth / http://3dflashlo.wordpress.com/ * * Character game with map collision and height test */ 'use strict'; var HeroGame = {}; HeroGame.ToRad = Math.PI/180; HeroGame.Player = function( container, camera, scene, revers, debug ){ this.revers = revers || false; this.obj = new THREE.Group(); /*var shadow = new THREE.Mesh( new THREE.PlaneBufferGeometry( 1, 1 ), new THREE.MeshBasicMaterial( { color:0x666666, transparent:true, opacity:0.5, blending:THREE.MultiplyBlending }) ); shadow.geometry.applyMatrix(new THREE.Matrix4().makeRotationX(90*HeroGame.ToRad)); shadow.position.y = 0.05 this.obj.add(shadow)*/ this.obj.position.y = 0.5; scene.add(this.obj); this.velocity = new THREE.Vector3( 0, 0, 0 ); this.rotation = new THREE.Vector3( 0, 0, 0 ); this.newRotation = new THREE.Vector3( 0, 0, 0 ); this.model = false; this.timeScale = 1; this.delta = 0; this.isMove = false; this.isJump = false; this.isFall = false; this.onGround = true; this.weights = {}; this.levelOrigin = new THREE.Vector3(0,0,0); this.level = new THREE.Vector3(0,0,0); this.ease = new THREE.Vector3(); this.easeRot = new THREE.Vector3(); this.cfg = { speed:0.025, maxSpeed:0.25, g:9.8, posY:0, maxJump:4, maxHeight:4 }; this.miniMap = new HeroGame.Minimap( this.revers, debug ); this.navigation = new HeroGame.Navigation( container, camera, this.revers ); this.navigation.target = this.getPosition().clone(); this.navigation.target.add(new THREE.Vector3(0, 1.2, 0)); this.navigation.moveCamera(); }; HeroGame.Player.prototype = { constructor: HeroGame.Player, addHero:function(m, size){ size = size || 0.023; this.hero = m; if( this.revers ){ this.hero.scale.set(size,size,size); this.hero.rotation.y = 180 * HeroGame.ToRad; } else this.hero.scale.set(size,size,-size); this.animLength = this.hero.animations.length; var i = this.animLength, name; while(i--){ name = this.hero.animations[i].name; this.weights[name] = 0; if(name=='idle') this.weights[name] = 1; this.hero.animations[i].play( 0, this.weights[name] ); } this.obj.add(this.hero); this.model = true; }, update:function(delta){ TWEEN.update(); this.delta = delta; THREE.AnimationHandler.update( this.delta ); this.move(); }, move:function(k) { var key = this.navigation.key; // jumping if( key[6] && this.onGround ){ this.isJump = true; this.onGround = false;} //acceleration and speed limite if (key[0] && this.onGround) this.ease.z = (this.ease.z > this.cfg.maxSpeed) ? this.cfg.maxSpeed : this.ease.z+this.cfg.speed; if (key[1] && this.onGround) this.ease.z = (this.ease.z < -this.cfg.maxSpeed)? -this.cfg.maxSpeed : this.ease.z-this.cfg.speed; if(this.revers){ if (key[3] && this.onGround) this.ease.x = (this.ease.x > this.cfg.maxSpeed) ? this.cfg.maxSpeed : this.ease.x+this.cfg.speed; if (key[2] && this.onGround) this.ease.x = (this.ease.x < -this.cfg.maxSpeed)? -this.cfg.maxSpeed : this.ease.x-this.cfg.speed; } else { if (key[2] && this.onGround) this.ease.x = (this.ease.x > this.cfg.maxSpeed) ? this.cfg.maxSpeed : this.ease.x+this.cfg.speed; if (key[3] && this.onGround) this.ease.x = (this.ease.x < -this.cfg.maxSpeed)? -this.cfg.maxSpeed : this.ease.x-this.cfg.speed; } //deceleration if (!key[0] && !key[1]) { if (this.ease.z > this.cfg.speed) this.ease.z -= this.cfg.speed; else if (this.ease.z < -this.cfg.speed) this.ease.z += this.cfg.speed; else this.ease.z = 0; } if (!key[2] && !key[3]) { if (this.ease.x > this.cfg.speed) this.ease.x -= this.cfg.speed; else if (this.ease.x < -this.cfg.speed) this.ease.x += this.cfg.speed; else this.ease.x = 0; } // ease var mx = 0; var mz = 0; if(this.ease.z!==0 || this.ease.x!==0){ if(this.ease.z>0){this.WalkFront(); mz = 1;} else if(this.ease.z<0){this.WalkBack(); mz = -1;} if(!this.revers){ if(this.ease.x<0){this.stepLeft(mz);mx=-1} else if(this.ease.x>0){this.stepRight(mz);mx=1;} } else { if(this.ease.x<0){this.stepRight(mz);mx=-1} else if(this.ease.x>0){this.stepLeft(mz);mx=1;} } } else { this.stopWalk(); } // stop if no move if (this.ease.x == 0 && this.ease.z == 0 && !this.navigation.mouse.down && this.onGround) return; //console.log(controls.object.rotation) // find direction of player this.easeRot.y = this.navigation.cam.h * HeroGame.ToRad; var rot = this.navigation.unwrapDegrees(Math.round(this.navigation.cam.h)); this.easeRot.x = Math.sin(this.easeRot.y) * this.ease.x + Math.cos(this.easeRot.y) * this.ease.z; this.easeRot.z = Math.cos(this.easeRot.y) * this.ease.x - Math.sin(this.easeRot.y) * this.ease.z; //this.setRotation(-(this.navigation.cam.h+90)*HeroGame.ToRad); this.setRotation(-(this.easeRot.y+(90*HeroGame.ToRad))); //this.setRotation(-(this.parent.nav.cam.h+90)*HeroGame.ToRad) //if(this.revers)this.level.x = this.levelOrigin.x + this.easeRot.x; //else this.level.x = this.levelOrigin.x-this.easeRot.x; this.level.z = this.levelOrigin.z+this.easeRot.z; // update 2d map this.miniMap.drawMap(); // test pixel collision var nohitx = 0; var nohitz = 0; var lock = this.miniMap.lock; if(this.revers){ if(rot >= 45 && rot <= 135){ if(this.level.z < this.levelOrigin.z) if(!lock[0] && !lock[4] && !lock[5]) nohitz = 1; if(this.level.z > this.levelOrigin.z) if(!lock[1] && !lock[6] && !lock[7]) nohitz = 1; if(this.level.x > this.levelOrigin.x) if(!lock[2] && !lock[4] && !lock[6]) nohitx = 1; if(this.level.x < this.levelOrigin.x) if(!lock[3] && !lock[5] && !lock[7]) nohitx = 1; } else if (rot <= -45 && rot >= -135){ if(this.level.z > this.levelOrigin.z) if(!lock[0] && !lock[4] && !lock[5]) nohitz = 1; if(this.level.z < this.levelOrigin.z) if(!lock[1] && !lock[6] && !lock[7]) nohitz = 1; if(this.level.x < this.levelOrigin.x) if(!lock[2] && !lock[4] && !lock[6]) nohitx = 1; if(this.level.x > this.levelOrigin.x) if(!lock[3] && !lock[5] && !lock[7]) nohitx = 1; } else if (rot < 45 && rot > -45){ if(this.level.z < this.levelOrigin.z) if(!lock[2] && !lock[4] && !lock[6]) nohitz = 1; if(this.level.z > this.levelOrigin.z) if(!lock[3] && !lock[5] && !lock[7]) nohitz = 1; if(this.level.x < this.levelOrigin.x) if(!lock[0] && !lock[4] && !lock[5]) nohitx = 1; if(this.level.x > this.levelOrigin.x) if(!lock[1] && !lock[6] && !lock[7]) nohitx = 1; } else { if(this.level.z > this.levelOrigin.z) if(!lock[2] && !lock[4] && !lock[6]) nohitz = 1; if(this.level.z < this.levelOrigin.z) if(!lock[3] && !lock[5] && !lock[7]) nohitz = 1; if(this.level.x > this.levelOrigin.x) if(!lock[0] && !lock[4] && !lock[5]) nohitx = 1; if(this.level.x < this.levelOrigin.x) if(!lock[1] && !lock[6] && !lock[7]) nohitx = 1; } } else { if(rot >= 45 && rot <= 135){ if(this.level.z < this.levelOrigin.z) if(!lock[0] && !lock[4] && !lock[5]) nohitz = 1; if(this.level.z > this.levelOrigin.z) if(!lock[1] && !lock[6] && !lock[7]) nohitz = 1; if(this.level.x < this.levelOrigin.x) if(!lock[2] && !lock[4] && !lock[6]) nohitx = 1; if(this.level.x > this.levelOrigin.x) if(!lock[3] && !lock[5] && !lock[7]) nohitx = 1; } else if (rot <= -45 && rot >= -135){ if(this.level.z > this.levelOrigin.z) if(!lock[0] && !lock[4] && !lock[5]) nohitz = 1; if(this.level.z < this.levelOrigin.z) if(!lock[1] && !lock[6] && !lock[7]) nohitz = 1; if(this.level.x > this.levelOrigin.x) if(!lock[2] && !lock[4] && !lock[6]) nohitx = 1; if(this.level.x < this.levelOrigin.x) if(!lock[3] && !lock[5] && !lock[7]) nohitx = 1; } else if (rot < 45 && rot > -45){ if(this.level.z > this.levelOrigin.z) if(!lock[2] && !lock[4] && !lock[6]) nohitz = 1; if(this.level.z < this.levelOrigin.z) if(!lock[3] && !lock[5] && !lock[7]) nohitz = 1; if(this.level.x < this.levelOrigin.x) if(!lock[0] && !lock[4] && !lock[5]) nohitx = 1; if(this.level.x > this.levelOrigin.x) if(!lock[1] && !lock[6] && !lock[7]) nohitx = 1; } else { if(this.level.z < this.levelOrigin.z) if(!lock[2] && !lock[4] && !lock[6]) nohitz = 1; if(this.level.z > this.levelOrigin.z) if(!lock[3] && !lock[5] && !lock[7]) nohitz = 1; if(this.level.x > this.levelOrigin.x) if(!lock[0] && !lock[4] && !lock[5]) nohitx = 1; if(this.level.x < this.levelOrigin.x) if(!lock[1] && !lock[6] && !lock[7]) nohitx = 1; } } this.level.y = this.miniMap.posY + this.cfg.posY; var diff = Math.abs(this.levelOrigin.y - this.level.y); //this.levelOrigin.y = this.level.y; if(this.levelOrigin.y>this.level.y){ // down if(diff<this.cfg.maxHeight) this.levelOrigin.y = this.level.y; else{ this.isFall = true; this.onGround=false;} } else { if(diff<this.cfg.maxHeight) this.levelOrigin.y = this.level.y; //else {nohitz=0; nohitx=0} } if(nohitx)this.levelOrigin.x = this.level.x; if(nohitz)this.levelOrigin.z = this.level.z; /*var diff = Math.abs(this.levelOrigin.y - this.level.y); if(diff<this.cfg.maxHeight) this.levelOrigin.y = this.level.y; else{ this.isFall = true; this.onGround=false;} */ // gravity if(this.isJump){ this.ease.y += this.cfg.g * this.delta; if(this.ease.y>this.cfg.maxJump){ this.isFall = true; this.isJump = false; } } if(this.isFall){ this.ease.y -= this.cfg.g * this.delta; if(diff<this.cfg.maxHeight && this.ease.y<0){ this.isFall = false; this.ease.y = 0; this.onGround=true; } //if(this.ease.y<0){ this.isFall = false; this.ease.y = 0; this.onGround=true; } } //if(this.ease.y>this.cfg.maxJump) this.ease.y -= this.cfg.g * this.delta; this.levelOrigin.y += this.ease.y; // update 2d map this.miniMap.updatePosition(this.levelOrigin.x, -this.easeRot.y, this.levelOrigin.z); //this.player.position.lerp(this.levelOrigin, 0.1); this.lerp(this.levelOrigin, 0.5); //this.lerp(this.levelOrigin, this.delta); this.navigation.target = this.getPosition().clone(); this.navigation.target.add(new THREE.Vector3(0, 1.2, 0)); this.navigation.moveCamera(); }, getPosition:function(){ return this.obj.position; }, setPosition:function(x,y,z){ this.obj.position.set(x,y,z); }, setRotation:function(y){ this.rotation.y = y; if(this.isMove){ this.newRotation.lerp(this.rotation, 0.25); this.obj.rotation.y = this.newRotation.y; } }, lerp:function(v,f){ this.obj.position.lerp(v,f); }, WalkFront:function(){ if(this.model){ this.timeScale=1; this.easing({idle:0, walk:1, step_left:0, step_right:0}); } this.isMove = true; }, WalkBack:function(){ if(this.model){ this.timeScale=-1; this.easing({idle:0, walk:1, step_left:0, step_right:0}); } this.isMove = true; }, stepLeft:function(){ if(this.model){ this.easing({idle:0, walk:0, step_left:1, step_right:0}); } this.isMove = true; }, stepRight:function(){ if(this.model){ this.easing({idle:0, walk:0, step_left:0, step_right:1}); } this.isMove = true; }, stopWalk:function(){ if(this.model){ if(this.weights['walk']!==0 || this.weights['step_right']!==0 || this.weights['step_left']!==0){ this.easing({idle:1, walk:0, step_left:0, step_right:0}); } } this.isMove = false; }, easing:function(newWeights){ var _this = this; this.tween = new TWEEN.Tween( this.weights ) .to( newWeights, 200 ) .easing( TWEEN.Easing.Linear.None ) .onUpdate( function () {_this.weight()} ) .start(); }, weight:function(t){ var i = this.animLength, name; while(i--){ name = this.hero.animations[i].name; this.hero.animations[i].weight = this.weights[name]; if(name=='walk'){ this.hero.animations[i].timeScale = this.timeScale; } } } }; // ----------------------- Minimap HeroGame.Minimap = function(revers, debug){ this.revers = revers || false; //this.wsize = {w:window.innerWidth, h:window.innerHeight} //this.rr = renderer; this.debug = debug || false; this.ar8 = typeof Uint8Array!="undefined"?Uint8Array:Array; this.miniSize = { w:64, h:64, f:0.25 }; this.cc = {r:255, g:0, b:0, a:255}; this.miniGlCanvas = document.createElement('canvas'); this.miniTop = document.createElement('canvas'); this.mapTest = document.createElement('canvas'); this.mmCanvas = document.createElement('canvas'); this.mmCanvas.width = this.mmCanvas.height = 64; this.tmCanvas = document.createElement('canvas'); this.tmCanvas.width = this.tmCanvas.height = 16; this.miniGlCanvas.width = this.miniTop.width = this.miniSize.w; this.miniGlCanvas.height = this.miniTop.height = this.miniSize.h; this.mapTest.width = 16; this.mapTest.height = 16; this.miniGlCanvas.style.cssText = 'position:absolute; bottom:10px; left:10px; border:3px solid #74818b;'; this.miniTop.style.cssText = 'position:absolute; bottom:13px; left:13px;'; this.mapTest.style.cssText = 'position:absolute; bottom:35px; left:35px;'; this.mmCanvas.style.cssText = 'position:absolute; bottom:100px; left:10px; border:3px solid #74818b;'; var body = document.body; body.appendChild( this.miniGlCanvas ); body.appendChild( this.miniTop ); body.appendChild( this.mapTest ); if(this.debug)body.appendChild( this.mmCanvas ); this.posY = 0; this.oldColors = []; this.init(); }; HeroGame.Minimap.prototype = { constructor: HeroGame.Minimap, init:function() { this.setMapTestSize(8); this.renderer = new THREE.WebGLRenderer({ canvas:this.miniGlCanvas, precision: "lowp", antialias: false }); this.renderer.setSize( this.miniSize.w, this.miniSize.h ); //this.renderer.sortObjects = false; //this.renderer.sortElements = false; this.renderer.setClearColor( 0xff0000, 1 ); this.scene = new THREE.Scene(); //this.tTexture = new THREE.WebGLRenderTarget(this.miniSize.w, this.miniSize.h, { minFilter: THREE.LinearFilter, magFilter: THREE.NearestFilter, format: THREE.RGBFormat }); var w = 3;//6;// 500*this.miniSize.f; this.camera = new THREE.OrthographicCamera( -w , w , w , -w , 0.1, 400 ); this.camera.position.x = 0; this.camera.position.z = 0; this.camera.position.y = 100;//(200)*this.miniSize.f; if(this.revers) this.camera.scale.x = -1; this.camera.lookAt( new THREE.Vector3(0,0,0) ); this.player = new THREE.Object3D(); this.player.position.set(0,0,0); this.scene.add(this.player); this.player.add(this.camera); this.gl = this.renderer.getContext(); //this.gl = this.rr.getContext(); this.initTopMap(); this.deepShader = new THREE.ShaderMaterial({ uniforms: HeroGame.deepShader.uniforms, vertexShader: HeroGame.deepShader.vs, fragmentShader: HeroGame.deepShader.fs }); }, addGeometry:function(geo){ var mesh = new THREE.Mesh( geo, this.deepShader); //mesh.scale.set(1,1,-1); mesh.position.set(0,0,0); this.scene.add(mesh); }, add:function(mesh){ //var mesh = new THREE.Mesh( geo, ); mesh.material = this.deepShader; if(!this.revers)mesh.scale.set(1,1,-1); mesh.position.set(0,0,0); this.scene.add(mesh); }, updatePosition:function(x,y,z){ this.player.position.x = x; this.player.position.z = z; this.player.rotation.y = y; }, drawMap:function(){ this.renderer.render( this.scene, this.camera ); this.gl.readPixels(this.zsize[0], this.zsize[1], this.zsize[2], this.zsize[2], this.gl.RGBA, this.gl.UNSIGNED_BYTE, this.zone); /*this.rr.setSize( this.miniSize.w, this.miniSize.h ); this.rr.setClearColor( 0xff0000, 1 ); this.rr.render( this.scene, this.camera );//, this.tTexture, true); this.rr.getContext().readPixels(this.zsize[0], this.zsize[1], this.zsize[2], this.zsize[2], this.gl.RGBA, this.gl.UNSIGNED_BYTE, this.zone); this.rr.setSize( this.wsize.w, this.wsize.h );*/ //this.drawMiniMap(); if(this.debug){ // revers y pixel data var m = 0, n = 0; for(var y = 15; y>=0; y--){ for(var x = 0; x<16; x++){ n = ((y*16)*4)+(x*4); this.zoneInv[m+0] = this.zone[n+0]; this.zoneInv[m+1] = this.zone[n+1]; this.zoneInv[m+2] = this.zone[n+2]; this.zoneInv[m+3] = this.zone[n+3]; m+=4 } } this.drawBIGMap(); } // collision var i = 9; while(i--){ this.lock[i] = this.colorTest(this.pp[i]); } // height this.posY = this.zone[this.pp[8]+1]/10; this.player.position.y = this.posY; if(this.ctxTest) this.drawMapTest(); }, /*drawMiniMap:function(){ var ctx = this.miniGlCanvas.getContext('2d'); //ctx.drawImage(this.tTexture.image,0,0, 64, 64); var imageObject=new Image(); imageObject.onload=function(){ ctx.clearRect(0,0,64,64); ctx.drawImage(imageObject,0,0, 64, 64); } imageObject.src=this.rr.domElement.toDataURL(); },*/ drawBIGMap:function(){ var c = this.mmCanvas; var ctx2 = c.getContext('2d'); var ctx = this.tmCanvas.getContext('2d'); var image = ctx.getImageData(0, 0, 16, 16); var i = this.zoneInv.length; while(i--) image.data[i] = this.zoneInv[i]; ctx.fillStyle = 'black'; ctx.fillRect(0,0, 16, 16); ctx.putImageData(image, 0, 0); var imageObject=new Image(); imageObject.onload=function(){ ctx2.clearRect(0,0,64,64); ctx2.drawImage(imageObject,0,0, 64, 64); } imageObject.src=this.tmCanvas.toDataURL(); }, colorTest:function(n){ var b=0, z=this.zone, c=this.cc, w = this.oldColors[n] || 0; // test out if(z[n]==c.r && z[n+1]==c.g && z[n+2]==c.b && z[n+3]==c.a) b = 1; // test max height if((z[n]-w) > 10) b = 1; else this.oldColors[n] = z[n]; return b; }, /*heightTest:function(n){ return this.zone[n] || 0; },*/ setMapTestSize:function(s){ //this.zsize = [(this.miniSize.w*0.5)-s, (this.miniSize.h*0.5)-s, s*2]; this.zsize = [(this.miniSize.w*0.5)-s, (this.miniSize.h*0.5)-s, s*2]; this.lock = [0,0,0,0, 0,0,0,0]; var max =((s*2)*(s*2))*4; //[ front, back, left, right, fl, fr, bl, br, middle]; // 0 1 2 3 4 5 6 7 8 this.pp = [max-(s*4), s*4, max*0.5, max*0.5 + (((s*4)*2)-4), 211*4, 222*4, 34*4, 45*4, max*0.5+(s*4)];//+ (s*4)]; this.zone = new this.ar8(max); this.zoneInv = new this.ar8(max); }, initTopMap:function(){ var ctx3 = this.miniTop.getContext("2d"); ctx3.fillStyle = 'black'; ctx3.fillRect(0, 0, 1, this.miniSize.h); ctx3.fillRect(this.miniSize.w-1, 0, 1, this.miniSize.h); ctx3.fillRect(1, 0, this.miniSize.w-2, 1); ctx3.fillRect(1,this.miniSize.h-1, this.miniSize.w-2, 1); ctx3.save(); ctx3.translate((this.miniSize.w*0.5), (this.miniSize.h*0.5)); this.drawPlayer(ctx3); ctx3.restore(); this.ctxTest = this.mapTest.getContext("2d"); }, drawMapTest:function() { this.ctxTest.clearRect ( 0 , 0 , 16 , 16 ); var id = this.ctxTest.createImageData(16,16); var d = id.data; var i = 7; while(i--)d[i] = 0; if(this.lock[1]) this.dp(d, this.pp[0]); if(this.lock[0]) this.dp(d, this.pp[1]); if(this.lock[2]) this.dp(d, this.pp[2]); if(this.lock[3]) this.dp(d, this.pp[3]); if(this.lock[6]) this.dp(d, this.pp[4]); if(this.lock[7]) this.dp(d, this.pp[5]); if(this.lock[4]) this.dp(d, this.pp[6]); if(this.lock[5]) this.dp(d, this.pp[7]); this.ctxTest.putImageData( id, 0, 0); }, dp:function(d, p) { d[p] = 255; d[p+1] = 255; d[p+3] = 255; }, drawPlayer:function(ctx) { ctx.fillStyle = "rgba(255,255,200,0.2)"; ctx.globalAlpha = 1.0; ctx.beginPath(); ctx.moveTo(0, 0); ctx.lineTo(30, -30); ctx.lineTo(-30, -30); ctx.closePath(); ctx.fill(); ctx.fillStyle = "rgba(200,200,100,1)"; ctx.fillRect(-2, -2, 4, 4); } }; // ----------------------- Navigation HeroGame.Navigation = function(container, camera, revers){ this.revers = revers || false; this.camera = camera; this.container = container; this.cam = { h:90, v:90, distance:200, automove:false, vmax:179.99, vmin:0.01 }; this.mouse = { x:0, y:0, ox:0, oy:0, h:0, v:0, mx:0, my:0, down:false, over:false, moving:true, button:0 }; this.vsize = { w:window.innerWidth, h:window.innerHeight}; this.target = new THREE.Vector3(); this.key = [0,0,0,0,0,0,0]; this.rayTest = null; this.initEvents(true); this.initCamera(); } HeroGame.Navigation.prototype = { constructor: HeroGame.Navigation, initCamera : function (h,v,d) { this.cam.h = h || 90; this.cam.v = v || 90; this.cam.distance = d || 3; this.moveCamera(); }, moveCamera : function () { this.camera.position.copy(this.Orbit(this.target, this.cam.h, this.cam.v, this.cam.distance)); this.camera.lookAt(this.target); }, Orbit : function (origine, h, v, distance) { origine = origine || new THREE.Vector3(); var p = new THREE.Vector3(); var phi = v*HeroGame.ToRad; var theta = h*HeroGame.ToRad; p.x = (distance * Math.sin(phi) * Math.cos(theta)) + origine.x; p.z = (distance * Math.sin(phi) * Math.sin(theta)) + origine.z; p.y = (distance * Math.cos(phi)) + origine.y; return p; }, unwrapDegrees:function(r){ r = r % 360; if (r > 180) r -= 360; if (r < -180) r += 360; return r; }, initEvents : function (isWithKey){ var _this = this; // disable context menu document.addEventListener("contextmenu", function(e){ e.preventDefault(); }, false); this.container.addEventListener( 'mousemove', function(e) {_this.onMouseMove(e)}, false ); this.container.addEventListener( 'mousedown', function(e) {_this.onMouseDown(e)}, false ); this.container.addEventListener( 'mouseout', function(e) {_this.onMouseUp(e)}, false ); this.container.addEventListener( 'mouseup', function(e) {_this.onMouseUp(e)}, false ); if (typeof window.ontouchstart !== 'undefined') { this.container.addEventListener( 'touchstart', function(e) {_this.onMouseDown(e)}, false ); this.container.addEventListener( 'touchend', function(e) {_this.onMouseUp(e)}, false ); this.container.addEventListener( 'touchmove', function(e) {_this.onMouseMove(e)}, false ); } this.container.addEventListener( 'mousewheel', function(e) {_this.onMouseWheel(e)}, false ); this.container.addEventListener( 'DOMMouseScroll', function(e) {_this.onMouseWheel(e)}, false ); if(isWithKey) this.bindKeys(); }, onMouseRay : function(x,y){ this.mouse.mx = ( this.mouse.x / this.vsize.w ) * 2 - 1; this.mouse.my = - ( this.mouse.y / this.vsize.h ) * 2 + 1; this.rayTest(); }, onMouseMove : function(e){ e.preventDefault(); var px, py; if(e.touches){ this.mouse.x = e.clientX || e.touches[ 0 ].pageX; this.mouse.y = e.clientY || e.touches[ 0 ].pageY; } else { this.mouse.x = e.clientX; this.mouse.y = e.clientY; } if(this.rayTest !== null) this.onMouseRay(); if (this.mouse.down ) { document.body.style.cursor = 'move'; if(this.revers) this.cam.h = (-(this.mouse.x - this.mouse.ox) * 0.3) + this.mouse.h; else this.cam.h = ((this.mouse.x - this.mouse.ox) * 0.3) + this.mouse.h; this.cam.v = (-(this.mouse.y - this.mouse.oy) * 0.3) + this.mouse.v; if(this.cam.v<this.cam.vmin) this.cam.v = this.cam.vmin; if(this.cam.v>this.cam.vmax) this.cam.v = this.cam.vmax; this.moveCamera(); } }, onMouseDown : function(e){ e.preventDefault(); var px, py; if(e.touches){ px = e.clientX || e.touches[ 0 ].pageX; py = e.clientY || e.touches[ 0 ].pageY; } else { px = e.clientX; py = e.clientY; // 0: default 1: left 2: middle 3: right this.mouse.button = e.which; } this.mouse.ox = px; this.mouse.oy = py; this.mouse.h = this.cam.h; this.mouse.v = this.cam.v; this.mouse.down = true; if(this.rayTest !== null) this.onMouseRay(px,py); }, onMouseUp : function(e){ this.mouse.down = false; document.body.style.cursor = 'auto'; }, onMouseWheel : function (e) { var delta = 0; if(e.wheelDeltaY){delta=e.wheelDeltaY*0.01;} else if(e.wheelDelta){delta=e.wheelDelta*0.05;} else if(e.detail){delta=-e.detail*1.0;} this.cam.distance-=(delta*10)*0.01; this.moveCamera(); }, // ACTIVE KEYBOARD bindKeys:function(){ var _this = this; document.onkeydown = function(e) { e = e || window.event; console.log('key') switch ( e.keyCode ) { case 38: case 87: case 90: _this.key[0] = 1; break; // up, W, Z case 40: case 83: _this.key[1] = 1; break; // down, S case 37: case 65: case 81: _this.key[2] = 1; break; // left, A, Q case 39: case 68: _this.key[3] = 1; break; // right, D case 17: case 67: _this.key[4] = 1; break; // ctrl, C case 69: _this.key[5] = 1; break; // E case 32: _this.key[6] = 1; break; // space case 16: _this.key[7] = 1; break; // shift } } document.onkeyup = function(e) { e = e || window.event; switch( e.keyCode ) { case 38: case 87: case 90: _this.key[0] = 0; break; // up, W, Z case 40: case 83: _this.key[1] = 0; break; // down, S case 37: case 65: case 81: _this.key[2] = 0; break; // left, A, Q case 39: case 68: _this.key[3] = 0; break; // right, D case 17: case 67: _this.key[4] = 0; break; // ctrl, C case 69: _this.key[5] = 0; break; // E case 32: _this.key[6] = 0; break; // space case 16: _this.key[7] = 0; break; // shift } } //self.focus(); } } /** * @author loth / http://3dflashlo.wordpress.com/ * * Simple deep y shader */ HeroGame.deepShader={ attributes:{}, uniforms:{ deep: {type: 'f', value: 0.03904} }, fs:[ 'precision lowp float;', 'varying vec4 vc;', 'void main(void) { gl_FragColor = vc; }' ].join("\n"), vs:[ 'uniform float deep;', 'varying float dy;', 'varying vec4 vc;', 'void main(void) {', 'gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);', 'dy = position.y*deep;', 'if(position.y>0.){vc = vec4(dy,dy,dy, 1.0);}else{vc = vec4(0,0,-dy, 1.0);}', '}' ].join("\n") };
window.Algorithmia = window.Algorithmia || {}; Algorithmia.api_key = "simXy0OhJ0Yi7WR3m4osSRiRrdG1" var numTasks = 0; function callAlgorithm() { startTask(); // Get the img URL var img = document.getElementById("imgUrl").value; // Remove any whitespaces around the url img = img.trim(); // Check if URL is an image // Call the Image Resizing Function getPlaces(img); // getPlaces(img) // document.getElementById("urlAddress").innerHTML = img; } function getPlaces(url) { var input = { "image": url, "numResults": 7 }; Algorithmia.client(Algorithmia.api_key) .algo("algo://deeplearning/Places365Classifier/0.1.9") .pipe(input) .then(function (output) { if (output.error) { // Error Handling var statusLabel = document.getElementById("status-label") statusLabel.innerHTML = '<div class="alert alert-danger" role="alert">Uh Oh! Something went wrong: ' + output.error.message + ' </div>'; taskError(); } else { addPlaces(output.result.predictions, url); console.log("got output", output.result); } }) } function addPlaces(result, img){ for (var i = 0; i < result.length; i++){ var num = result[i].prob * 100; var n = num.toFixed(2); n = n + "%" var table = document.getElementById("tbody") var row = table.insertRow(-1); var cell1 = row.insertCell(0); var cell2 = row.insertCell(1); cell1.innerHTML = '<span class="label label-success">'+result[i].class;+'</span>'; cell2.innerHTML = n; } // Check if img is a Data URI var checkImg = img.split('://').shift(); var prefix = ['data']; if (prefix.indexOf(checkImg) > -1){ // Retrieve original binary from Data API as base64 Algorithmia.client(Algorithmia.api_key) .algo("algo://util/Data2Base64/0.1.0") .pipe(img) .then(function(output) { if(output.error){ // Error Handling var statusLabel = document.getElementById("status-label") statusLabel.innerHTML = '<div class="alert alert-danger" role="alert">Uh Oh! Something went wrong: ' + output.error.message + ' </div>'; taskError(); } else { // Decode base64 img var outputImageOriginal = output.result; var src = "data:image/jpeg;base64,"; src += outputImageOriginal; // Add img to DOM document.getElementById("userImg").src = src; finishTask(); } }); } else { // Add img to DOM document.getElementById("userImg").src = img; finishTask(); } } function analyzeDefault(img) { document.getElementById("imgUrl").value = img; callAlgorithm(); } function startTask() { numTasks++; document.getElementById("overlay").classList.remove("hidden"); // Clear error messages var statusLabel = document.getElementById("status-label") statusLabel.innerHTML = ""; // Clear table $("#tbody").empty(); // Clear image var image = document.getElementById("userImg").src image.src = ""; } function finishTask() { numTasks--; if(numTasks <= 0) { document.getElementById("overlay").classList.add("hidden"); document.getElementById("explainer").classList.add("hidden"); document.getElementById("results").classList.remove("hidden"); document.getElementById("social").classList.remove("invisible"); document.getElementById("marketing").classList.remove("hidden"); } } function taskError() { numTasks = 0; document.getElementById("overlay").classList.add("hidden"); document.getElementById("explainer").classList.add("display"); document.getElementById("explainer").classList.remove("hidden"); document.getElementById("results").classList.add("hidden"); document.getElementById("social").classList.add("invisible"); document.getElementById("marketing").classList.add("hidden"); } function initDropzone() { window.Dropzone.autoDiscover = false; var dropzone = new Dropzone("#file-dropzone", { options: { sending: function() {} }, acceptedFiles: "image/*", previewTemplate: "<div></div>", maxFilesize: 10, filesizeBase: 1024, createImageThumbnails: false, clickable: true }); dropzone.__proto__.cancelUpload = function() {}; dropzone.__proto__.uploadFile = function() {}; dropzone.__proto__.uploadFiles = function() {}; dropzone.on("processing", function(file) { startTask(); var reader = new FileReader(); reader.addEventListener("load", function () { console.log("Calling algorithm with uploaded image."); getPlaces(reader.result); dropzone.removeFile(file); }, false); reader.readAsDataURL(file); console.log("Reading uploaded image..."); }); dropzone.on("error", function(file, err) { dropzone.removeFile(file); var statusLabel = document.getElementById("status-label") statusLabel.innerHTML = '<div class="alert alert-danger" role="alert">Uh oh! ' + err + ' </div>'; taskError(); }); } initDropzone();
import styled from "styled-components"; import { LikeAnimation } from "./Keyframes"; export const Like = styled.div` position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); i { color: #ff2e63; font-size: 5rem; z-index: 50; opacity: 0; } .showAnimation { animation: ${LikeAnimation} .8s ease-in-out; } .removeAnimation { animation: ${LikeAnimation} .8s ease-in-out; } `;
/** * Created by Jorge on 23/05/2015. */ define(function (require) { var Question = require('./Question'); function Survey(data) { var title = data.title; var description = data.description; var questions = []; if (data.questions != undefined) data.questions.forEach(function (question) { questions.push(new Question(question)); }); this.getTitle = function () { return title; }; this.getDescription = function () { return description; }; this.getQuestions = function () { return questions; } } return Survey; });
var request = require('request'); var cheerio = require('cheerio'); var result = []; request.get('http://axe-level-1.herokuapp.com/', function (error, response, body) { if (!error && response.statusCode == 200) { var $ = cheerio.load(body); var tds = $('tr').find('td'); for(var i=6 ; i<tds.length ; i=i+6) { var pipe = { "name":tds[i].children[0].data, "grades":{ "國語":tds[i+1].children[0].data, "數學":tds[i+2].children[0].data, "自然":tds[i+3].children[0].data, "社會":tds[i+4].children[0].data, "健康教育":tds[i+5].children[0].data } }; result.push(pipe); } } console.log(JSON.stringify(result)); } );
import { Dep } from './dep.js' // 负责更新视图 class Watcher { constructor(vm, key, updater) { this.vm = vm this.key = key this.updaterFn = updater // 创建实例时,把当前实例指定到Dep.target静态属性上 Dep.target = this // 读一下key,触发get vm[key] // 置空 Dep.target = null } // 未来执行dom更新函数,由dep调用的 update() { this.updaterFn.call(this.vm, this.vm[this.key]) } }
/** * 使用MySQL模块,连接数据库,执行SELECT语句 */ var mysql = require('mysql'); //require中的第三方模块名必须与node_modules目录下的文件夹名一致 //1 创建到数据库服务器的连接 var conn = mysql.createConnection({ host : '127.0.0.1', user : 'root', password : '', database : 'jd' }); //2 提交SQL语句给服务器执行 var sql = "SELECT * FROM jd_user"; conn.query(sql, function(err, result){ console.log('SELECT语句执行完成') console.log(result); // [ {},{},{} ] 行对象 for(var i=0; i<result.length; i++){ var u = result[i]; console.log(`${u.uid} ${u.userName} ${u.age}`); } }); //3 断开连接 conn.end();
export default class Weather { constructor(data) { this.humidity = data.main.humidity this.temp = data.main.temp this.high = data.main.temp_max this.low = data.main.temp_min this.name = data.name this.country = data.sys.country this.description = data.weather[0].description this.icon = data.weather[0].icon this.fahr = 0 } }
const vision = require('@google-cloud/vision'); const client = new vision.ImageAnnotatorClient({ });
var hoverEffect = false; // set true for hover effect, set false for no hover effect var searchEngine = 'google'; // default search engine - set google for google search, bing for bing search, yahoo for yahoo search var numberOfScreens = 3; // set number of screens (1 or 2 or 3) var blockName = new Array(); // set names of blocks blockName[1] = 'Home'; blockName[2] = 'Various'; blockName[3] = 'Info'; var bookmark = new Array(); bookmark[0] = new Array(); bookmark[1] = new Array(); bookmark[2] = new Array(); // set your bookmarks here: (If you do not fill 'thumb' for thumbnail will be used title) // 1. BLOCK bookmark[0][0] = { 'title':'Facebook', 'url':'https://facebook.com', 'thumb':'facebook.png' }; bookmark[0][1] = { 'title':'Instagram', 'url':'https://instagram.com', 'thumb':'instagram.png' }; bookmark[0][2] = { 'title':'Onet', 'url':'https://onet.pl', 'thumb':'onet.png' }; bookmark[0][3] = { 'title':'AntyWeb', 'url':'https://antyweb.pl', 'thumb':'antyweb.png' }; bookmark[0][4] = { 'title':'Wykop', 'url':'https://wykop.pl', 'thumb':'wykop.png' }; bookmark[0][5] = { 'title':'GMail', 'url':'https://gmail.com', 'thumb':'gmail.png' }; bookmark[0][6] = { 'title':'pepper', 'url':'https://pepper.pl', 'thumb':'pepper.png' }; bookmark[0][7] = { 'title':'Allegro', 'url':'https://allegro.pl', 'thumb':'allegro.png' }; bookmark[0][8] = { 'title':'AliExpress', 'url':'https://aliexpress.com', 'thumb':'aliexpress.png' }; bookmark[0][9] = { 'title':'Netflix', 'url':'https://netflix.com', 'thumb':'netflix.png' }; bookmark[0][10] = { 'title':'YouTube', 'url':'https://youtube.com', 'thumb':'youtube.png' }; bookmark[0][11] = { 'title':'RMF ON', 'url':'https://rmfon.pl/play,6', 'thumb':'rmfon.png' }; // end of 1. BLOCK // 2. BLOCK bookmark[1][0] = { 'title':'Lublin112', 'url':'https://lublin112.pl', 'thumb':'lublin112.png' }; bookmark[1][1] = { 'title':'Niebezpiecznik', 'url':'https://niebezpiecznik.pl', 'thumb':'niebezpiecznik.png' }; bookmark[1][2] = { 'title':'Mistrzowie', 'url':'https://mistrzowie.org', 'thumb':'mistrzowie.png' }; bookmark[1][3] = { 'title':'Sadistic', 'url':'https://sadistic.pl', 'thumb':'sadistic.png' }; bookmark[1][4] = { 'title':'JoeMonster', 'url':'https://joemonster.org', 'thumb':'joemonster.png' }; bookmark[1][5] = { 'title':'RuneScape', 'url':'http://runescape.com', 'thumb':'runescape.png' }; bookmark[1][6] = { 'title':'DobreProgramy', 'url':'https://dobreprogramy.pl', 'thumb':'dobreprogramy.png' }; bookmark[1][7] = { 'title':'Chip', 'url':'https://chip.pl', 'thumb':'chip.png' }; bookmark[1][8] = { 'title':'Android', 'url':'http://android.com.pl', 'thumb':'android.png' }; bookmark[1][9] = { 'title':'DarkW', 'url':'https://darkw.pl', 'thumb':'darkw.png' }; bookmark[1][10] = { 'title':'P2mForum', 'url':'https://p2mforum.info', 'thumb':'p2mforum.png' }; bookmark[1][11] = { 'title':'WinClub', 'url':'https://winclub.pl', 'thumb':'' }; // end of 2. BLOCK // 3. BLOCK bookmark[2][0] = { 'title':'LinkedIn', 'url':'https://www.linkedin.com/', 'thumb':'linkedin.png' }; bookmark[2][1] = { 'title':'lifehacker', 'url':'http://lifehacker.com/', 'thumb':'lifehacker.png' }; bookmark[2][2] = { 'title':'IMDb', 'url':'http://www.imdb.com/', 'thumb':'imdb.png' }; bookmark[2][3] = { 'title':'Last.fm', 'url':'https://www.last.fm/', 'thumb':'lastfm.png' }; bookmark[2][4] = { 'title':'wikipedia', 'url':'https://pl.wikipedia.org/', 'thumb':'wikipedia.png' }; bookmark[2][5] = { 'title':'StackOverflow', 'url':'https://stackoverflow.com/', 'thumb':'stackoverflow.png' }; bookmark[2][6] = { 'title':'engadged', 'url':'https://www.engadget.com/', 'thumb':'engadget.png' }; bookmark[2][7] = { 'title':'dropbox', 'url':'https://www.dropbox.com/', 'thumb':'dropbox.png' }; bookmark[2][8] = { 'title':'weather', 'url':'https://www.weather.com/', 'thumb':'weather.png' }; bookmark[2][9] = { 'title':'Reddit', 'url':'https://www.reddit.com/', 'thumb':'reddit.png' }; bookmark[2][10] = { 'title':'BBC news', 'url':'https://www.bbc.com/news', 'thumb':'bbcnews.png' }; bookmark[2][11] = { 'title':'Eurosport', 'url':'https://www.eurosport.com/', 'thumb':'eurosport.png' }; // end of 3. BLOCK
/* eslint-disable no-underscore-dangle */ /** * Title: Token handler * Description: Handle token related routes * Author: Samin Yasar * Date: 27/October/2021 */ // Dependencies const dataLibrary = require("../../lib/data"); const utilities = require("../../helpers/utilities"); const config = require("../../helpers/config"); // Module scaffolding const tokenHandler = {}; // Defination of handle function tokenHandler.handle = (requestProps, callback) => { const acceptedMethods = ["get", "post", "put", "delete"]; if (acceptedMethods.indexOf(requestProps.method) > -1) { tokenHandler._token[requestProps.method](requestProps, callback); } else { // Don't accept request callback(405); } }; // Utilities tokenHandler._token = {}; // Get method tokenHandler._token.get = (requestProps, callback) => { const userName = typeof requestProps.queryStringObj.userName === "string" && requestProps.queryStringObj.userName.trim().length >= 0 ? requestProps.queryStringObj.userName : null; if (userName) { // Lookup the token dataLibrary.read("tokens", userName, (err, tokenData) => { if (!err && tokenData) { const tokenObj = utilities.parseJSON(tokenData); callback(200, tokenObj); } else { callback(404, { error: "Your requested user's token couldn't find.", }); } }); } else { callback(400, { error: "Please provide an username to get token.", }); } }; // Post method tokenHandler._token.post = (requestProps, callback) => { const userName = typeof requestProps.reqBody.userName === "string" && requestProps.reqBody.userName.trim().length > 0 ? requestProps.reqBody.userName : null; const password = typeof requestProps.reqBody.password === "string" && requestProps.reqBody.password.trim().length > 0 ? utilities.encrypt(requestProps.reqBody.password) : null; if (userName && password) { dataLibrary.read("users", userName, (err, readData) => { if (!err && readData) { const userData = utilities.parseJSON(readData); if (password === userData.password) { const tokenId = utilities.createRandomString(config.minTokenLength, 20); const validationTime = Date.now() + 60 * 60 * 1000; const tokenObj = { userName, tokenId, validationTime, }; // stores the token in file system dataLibrary.create("tokens", userName, tokenObj, (createError) => { if (!createError) { callback(200, tokenObj); } else { callback(500, { error: "Couldn't create token file.", }); } }); } else { callback(400, { error: "Your password was incorrect.", }); } } else { callback(400, { error: "Your requested user couldn't found.", }); } }); } else { callback(400, { error: "Please provide your username and password.", }); } }; // Put method tokenHandler._token.put = (requestProps, callback) => { const userName = typeof requestProps.reqBody.userName === "string" && requestProps.reqBody.userName.trim().length >= 0 ? requestProps.reqBody.userName : null; const extend = !!( typeof requestProps.reqBody.extend === "boolean" && requestProps.reqBody.extend === true ); if (userName && extend) { dataLibrary.read("tokens", userName, (readError, readData) => { if (!readError && readData) { const tokenData = utilities.parseJSON(readData); if (tokenData.validationTime > Date.now()) { tokenData.validationTime = Date.now() + 60 * 60 * 1000; dataLibrary.update("tokens", userName, tokenData, (updateError) => { if (!updateError) { callback(200, { message: "Successfully extend validation time of your requested user's token.", }); } else { callback(500, { error: "Couldn't extend the validation time of your requested user's token.", }); } }); } else { callback(400, { error: "Your requested user's token is already expired!", }); } } else { callback(404, { error: "Your requested user's have no token.", }); } }); } else { callback(400, { error: "Please provide a username and extend value.", }); } }; // Delete method tokenHandler._token.delete = (requestProps, callback) => { const userName = typeof requestProps.queryStringObj.userName === "string" && requestProps.queryStringObj.userName.trim().length >= 0 ? requestProps.queryStringObj.userName : null; if (userName) { // Lookup the tokenId dataLibrary.read("tokens", userName, (readError, readData) => { if (!readError && readData) { dataLibrary.delete("tokens", userName, (deleteError) => { if (!deleteError) { callback(200, { message: "Successfully deleted the user's token.", }); } else { callback(500, { error: "Couldn't delete the user's token.", }); } }); } else { callback(404, { error: "Your requested user's have no token.", }); } }); } else { callback(400, { error: "Please provide a username to delete that token.", }); } }; // Verify token tokenHandler._token.verify = (tokenId, userName, callback) => { dataLibrary.read("tokens", userName, (err, data) => { if (!err && data) { const tokenData = utilities.parseJSON(data); if (tokenData.tokenId === tokenId && tokenData.validationTime > Date.now()) { callback(true); } else { callback(false); } } else { callback(false); } }); }; // Export module module.exports = tokenHandler;
const mysql = require('mysql'); const console = require('./Console')('MySQL Bridge'); const uuid = require('uuid').v4; //https://github.com/mysqljs/mysql#connection-options let config; try { config = require('../config.json'); } catch (err) { console.error('Cannot read Config File.'); console.debug(err); process.exit(); } let connection; module.exports = { connect: () => { return new Promise((resolve, reject) => { connection = mysql.createConnection(config.mysql); connection.connect((err) => { if (err) reject(err); else { connection.query('CREATE TABLE IF NOT EXISTS `'+config.mysql.database+'`.`tickets` ( `ID` VARCHAR(36) NOT NULL , `NAME` VARCHAR(200) NOT NULL , `BOOKED` DATE NOT NULL ) ENGINE = InnoDB;', (err) => { if (err) reject(err); else resolve(`${config.mysql.user}@${config.mysql.host}`) }) } }) }) }, //TODO Check if ticket invalidate checkTicket: (ticket) => { return new Promise((resolve, reject) => { console.debug(ticket); if (ticket) { if (ticket.id) { connection.query('SELECT * FROM tickets WHERE id=' + connection.escape(ticket.id), (err, result) => { if (err) reject(err); else { resolve(result); if (config.behavior.OneTimeTicket) { module.exports.invalidateTicket(ticket).catch((err) => { console.error('Cannot invalidate Ticket: ' + ticket.id); console.debug(err); }) } } }); } else { reject(new Error('Missing Variables')); } } else { reject(new Error('Missing Variables')); } }) }, invalidateTicket: (ticket) => { return new Promise((resolve, reject) => { console.debug(ticket); if (ticket) { if (ticket.id) { connection.query('UPDATE `tickets` SET `VALID`=0 WHERE id=' + connection.escape(ticket.id), (err) => { if (err) reject(err); else { resolve(); } }); } else { reject(new Error('Missing Variables')); } } else { reject(new Error('Missing Variables')); } }) }, addTicket: (data) => { return new Promise((resolve, reject) => { const ticket = uuid(); if (data.name) { connection.query('INSERT INTO `tickets`(`ID`, `NAME`, `BOOKED`) VALUES (' + connection.escape(ticket) + ',"' + data.name + '",CURRENT_DATE())', function (err) { if (err) reject(err); else { resolve(ticket); } }) } else { reject('No Name given.') } }) } };
module.exports = { siteMetadata: { title: `Starmap`, }, plugins: [ { resolve: `gatsby-source-filesystem`, options: { name: `data`, path: `${__dirname}/src/data/`, }, }, { resolve: `gatsby-transformer-csv`, options: { colParser: { hip: '!number', hd: '!number', hr: '!number', ra: '!number', dec: '!number', dist: '!number', pmra: '!number', pmdec: '!number', rv: '!number', mag: '!number', absmag: '!number', ci: '!number', x: '!number', y: '!number', z: '!number', vx: '!number', vy: '!number', vz: '!number', var_max: '!number', var_min: '!number', lum: '!number', comp: '!number', comp_primary: '!number', pmdecrad: '!number', pmrarad: '!number', decrad: '!number', rarad: '!number', }, }, }, `gatsby-plugin-react-helmet`, ], };
var Event = function (title, apply) { this.title = title; this.apply = apply; // (scenario) -> void } var SupplyShift = function (title, res, mag, positive) { return new Event(title, function (scenario) { if (positive) { scenario.marketPrices[res] /= mag; } else { } }); } //supply increase // //supply decrease //demand increase //demand decrease //price floor //price ceiling //unit tax var increaseSupply = new Event([ ], function (scenario, resource, magnitude) { });
/* jshint node:true, esversion:6 */ 'use strict'; /*! * Common functions for the MIDI WebSocket bridging client/server. * Hugo Hromic - http://github.com/hhromic * * Copyright 2016 Hugo Hromic * * 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. */ // show all current ports for a given MIDI input/output instance exports.showPorts = (midi, description) => { console.log('%s:', description); const numDevices = midi.getPortCount(); for (var idx=0; idx<numDevices; idx++) console.log('[%d] %s', idx, midi.getPortName(idx)); console.log(); }; // parse a string into a list of MIDI devices indexes exports.parseMidiDevicesIndexes = string => { if (string === undefined || string === null) return []; var midiDevicesIndexes = []; string.split(',').forEach(function (item) { const ports = item.split(':'); ports[0] = parseInt(ports[0]); ports[1] = parseInt(ports[1]); midiDevicesIndexes.push({ input: isNaN(ports[0]) ? undefined : ports[0], output: isNaN(ports[1]) ? undefined : ports[1], }); }); return midiDevicesIndexes; };
import { html, LitElement } from 'lit-element'; import '@polymer/iron-icon/iron-icon.js'; import '@polymer/iron-icons/iron-icons.js'; import homepageStyles from '../../style/homepage.scss'; import sharedStyles from '../../style/app.scss'; import tagMenuLabels from '../../style/tag-menu-labels.scss'; class tagsSideLabels extends LitElement { static get styles() { return [sharedStyles, homepageStyles, tagMenuLabels]; } render() { return html` <nav class="level tag-menu-label"> <div class="level-left"> <div class="level-item"> <tags-button></tags-button> </div> </div> <div class="level-right"> <div class="level-item"> <a class="button tag-menu-button"> <span class="icon"> <iron-icon icon="delete"></iron-icon> </span> </a> </div> </div> </nav> `; } } window.customElements.define('tags-side-labels', tagsSideLabels);
import { DISPLAY_DATA, FILTER_DATA, NEXT_DATA } from './types'; import { feed } from '../config'; import { chunkData } from '../utils'; import _ from 'lodash'; /** * Action to display data on first mount * @method displayData * @param {Number} results - number of results to display * @return {Object} object to be sent to the reducer * The payload is data split */ export function displayData(results = 10) { const pages = chunkData(feed.data, results); return { type: DISPLAY_DATA, payload: pages }; } /** * Action to filter data * @method filterData * @param {Object} ------ - object containing elements to filter with * @param {String} search - term searched on description * @param {bool} checked - videos from users that have more than 10 likes * @param {Number} results - number of results to display * @return {Object} object to be sent to the reducer * The payload is data split */ export function filterData({search, checked, results}) { let { data } = feed; if(search !== ''){ //Videos after search data = data.filter(element => element.description !== null && element.description.includes(search) && element); }else{ //All videos in case of deleting searched term data = feed.data; } if(checked){ //videos from users that have more than 10 likes data = data.filter(element => element.user.metadata.connections.likes.total > 10 && element); } const pages = chunkData(data, results); return { type: FILTER_DATA, payload: pages }; } /** * Action to pass the next page of data * @method nextData * @param {Object} data - data split on pages from state * @param {Number} actualPage - number of actual page from state * @return {Object} object to be sent to the reducer * The payload is next page to display or the last one */ export function nextData(data, actualPage) { let page = _.size(data);// Number of last page if(page > actualPage){ page = actualPage+1; } return { type: NEXT_DATA, payload: page } }
import Controller from '@ember/controller'; import { computed } from '@ember-decorators/object'; export default class SimpleController extends Controller { // BEGIN-SNIPPET docs-example-rows.js @computed get columns() { return [ { name: 'A', valuePath: 'A', width: 180 }, { name: 'B', valuePath: 'B', width: 180 }, { name: 'C', valuePath: 'C', width: 180 }, { name: 'D', valuePath: 'D', width: 180 }, ]; } @computed get rows() { return [ { A: 'A', B: 'B', C: 'C', D: 'D' }, { A: 'A', B: 'B', C: 'C', D: 'D' }, { A: 'A', B: 'B', C: 'C', D: 'D' }, { A: 'A', B: 'B', C: 'C', D: 'D' }, { A: 'A', B: 'B', C: 'C', D: 'D' }, { A: 'A', B: 'B', C: 'C', D: 'D' }, { A: 'A', B: 'B', C: 'C', D: 'D' }, { A: 'A', B: 'B', C: 'C', D: 'D' }, { A: 'A', B: 'B', C: 'C', D: 'D' }, { A: 'A', B: 'B', C: 'C', D: 'D' }, { A: 'A', B: 'B', C: 'C', D: 'D' }, ]; } // END-SNIPPET // BEGIN-SNIPPET docs-example-tree-rows.js treeEnabled = true; @computed get rowsWithChildren() { return [ { A: 'A', B: 'B', C: 'C', D: 'D', children: [ { A: 'A', B: 'B', C: 'C', D: 'D' }, { A: 'A', B: 'B', C: 'C', D: 'D' }, { A: 'A', B: 'B', C: 'C', D: 'D' }, ], }, { A: 'A', B: 'B', C: 'C', D: 'D', children: [ { A: 'A', B: 'B', C: 'C', D: 'D' }, { A: 'A', B: 'B', C: 'C', D: 'D' }, { A: 'A', B: 'B', C: 'C', D: 'D' }, ], }, { A: 'A', B: 'B', C: 'C', D: 'D', children: [ { A: 'A', B: 'B', C: 'C', D: 'D' }, { A: 'A', B: 'B', C: 'C', D: 'D' }, { A: 'A', B: 'B', C: 'C', D: 'D' }, ], }, ]; } // END-SNIPPET // BEGIN-SNIPPET docs-example-rows-with-collapse.js collapseEnabled = true; @computed get rowsWithCollapse() { return [ { A: 'A', B: 'B', C: 'C', D: 'D', isCollapsed: true, children: [ { A: 'A', B: 'B', C: 'C', D: 'D' }, { A: 'A', B: 'B', C: 'C', D: 'D' }, { A: 'A', B: 'B', C: 'C', D: 'D' }, ], }, { A: 'A', B: 'B', C: 'C', D: 'D', isCollapsed: true, children: [ { A: 'A', B: 'B', C: 'C', D: 'D' }, { A: 'A', B: 'B', C: 'C', D: 'D' }, { A: 'A', B: 'B', C: 'C', D: 'D' }, ], }, { A: 'A', B: 'B', C: 'C', D: 'D', isCollapsed: true, children: [ { A: 'A', B: 'B', C: 'C', D: 'D' }, { A: 'A', B: 'B', C: 'C', D: 'D' }, { A: 'A', B: 'B', C: 'C', D: 'D' }, ], }, ]; } // END-SNIPPET }
var inputString = "building" var inputArray = inputString.split("") var rev = [] console.log(inputArray) // for (var i = inputArray.length; -= 1; // console.log(inputArray[]); for (var i = 0; i < inputArray.length; i += 1){ console.log(inputArray[i]) rev.unshift(inputArray[i]) } console.log(rev) rev = rev.join("") console.log(rev)
// Lib entry file, exported to /public folder on publish const boostPublish = require('./boostpow-publish'); window.addEventListener('load', function() { boostPublish.init(); }); window.boostPublish = boostPublish;
import { useContext } from "react"; import { PlanetContext } from "../contexts/PlanetContext"; import { NavLink } from "react-router-dom"; import Chevron from "../assets/icon-chevron.svg"; import useStyles from "../styles/mobileMenu-style"; function MobileMenu({ resetApp }) { const { planets } = useContext(PlanetContext); const { mobileMenu, circle, link } = useStyles(); return ( <nav> <ul className={mobileMenu}> {planets.map((planet) => { return ( <NavLink to={`/${planet.name}`} key={planet.name} onClick={resetApp} className={link} > <li> <span className={circle} style={{ backgroundColor: planet.color }} ></span> {planet.name} </li> <img src={Chevron} alt="chevron right" /> </NavLink> ); })} </ul> </nav> ); } export default MobileMenu;
var React = require('react'); var RewardsStore = require('../../stores/RewardsStore'); var RewardsActions = require('../../actions/rewardActions'); var Link = require('react-router').Link; var RewardDetail = React.createClass({ contextTypes: { router: React.PropTypes.object.isRequired }, getInitialState: function () { return { reward: RewardsStore.getRewardById(this.props.params.id), user: RewardsStore.getUser(), confirmation: false } }, componentWillMount: function() { if(Object.keys(this.state.reward).length === 0) { RewardsActions.getReward('/api/rewards/' + this.props.params.id); } RewardsStore.addChangeListener(this._onChange); }, componentWillUnmount: function() { RewardsStore.removeChangeListener(this._onChange); }, _onChange: function() { this.setState( this._getState() ) }, _getState: function() { return { reward: RewardsStore.getReward(), user: RewardsStore.getUser(), confirmation: false } }, _requestApplication: function() { if(this._affordReward()){ var date = new Date(); RewardsActions.sendReward({ userID: this.state.user._id, newReward: this.state.reward, action: 'submitNewRequest', newRequest: { type: "Reward", collection: 'rewards', name: this.state.reward.name, summary: this.state.reward.summary, description: "Applied for a Reward - " + this.state.reward.name, date: date, id: date.getTime(), state: "Pending", subject: this.state.reward } }); this.context.router.push('/rewards'); } }, _hideConfirmationDialog: function() { this._handleConfirmation(false); }, _showConfirmationDialog: function() { this._handleConfirmation(true); }, _handleConfirmation: function(show) { this.setState( { confirmation:show } ) }, _affordReward: function() { return this.state.user.totalPoints >= this.state.reward.points; }, render: function() { return ( <div className="container reward-detail"> <div className="row"> <div className="content-item col-xs-12 col-sm-6"> <h3 className="content-item-title"><i className="fa fa-trophy"></i><span className="spacing"></span>{this.state.reward.name}</h3> <label className="form-label">Description</label> <p>{this.state.reward.description}</p> <label className="form-label">Points</label> <p>{(this.state.reward.points || '').toLocaleString('pt')}</p> <button className="button submit" onClick={this._showConfirmationDialog}>Apply</button> <div> <Link to="/rewards" className="button">Back</Link> </div> </div> </div> <div id="confirmation" className={this.state.confirmation ? "modal show" : "modal"}> <div className="modal-dialog"> <div className="modal-content"> <div className="modal-header"> <button type="button" className="close" data-dismiss="modal" aria-hidden="true" onClick={this._hideConfirmationDialog}>&times;</button> <h4 className="modal-title">Confirmation</h4> </div> <div className="modal-body"> {this._affordReward() ? <p>Are you sure you want to apply for this reward? Your request will be revised </p> : <p>You can't afford this reward!</p> } </div> <div className="modal-footer"> <button type="button" className="button" data-dismiss="modal" onClick={this._hideConfirmationDialog}>Close</button> {this._affordReward() ? <button type="button" className="button submit" onClick={this._requestApplication}>Accept</button> : null } </div> </div> </div> </div> </div> ); } }); module.exports = RewardDetail;
var sql = require('../../connect_db'); var user = function (user) { this.username = user.username; this.password = user.password; }; user.identify_user = function (username, password, result) { var filter = [username, password]; sql.query("select * from tedi.users where username= ? and password= ?;", filter, function (err, res) { if (err) { console.log("Error: ", err); result(null, err); } else { result(null, res); } }); }; user.registerUser = function (data, result) { sql.query("insert into tedi.users " + "values(?,?,?,?,?,?,?,?,?,?);", data, function (err, res) { if (err) { //console.log("Error: ",err); return result(null, err); } else { return result(null, res); } }); } module.exports = user;
/** * Escapes characters that can not be in an XML element. */ function escapeElement(value) { return value.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;'); } /** * @api private */ module.exports = { escapeElement: escapeElement };
// Code for accordion $(".content").hide(); $(".heading").append('<span class="arrow"></span>'); $('.heading').click(function(){ var heading = $(this).attr('data-heading'); var con = $("[data-content='" + heading + "']"); con.slideToggle(200); if(con.attr('newTile')){ con.removeAttr('newTile'); $(this).find( ".arrow" ).css({ '-webkit-transform': '', '-moz-transform': '', '-ms-transform': '', '-o-transform': '', 'transform': '', 'zoom': 1 }); } else{ con.attr('newTile', heading); var degree = -90; $(this).find( ".arrow" ).css({ '-webkit-transform': 'rotate(' + degree + 'deg)', '-moz-transform': 'rotate(' + degree + 'deg)', '-ms-transform': 'rotate(' + degree + 'deg)', '-o-transform': 'rotate(' + degree + 'deg)', 'transform': 'rotate(' + degree + 'deg)', 'zoom': 1 }); } }) // Code end for accordion
import React from "react"; import HeaderCocina from "../componentes/HeaderCocina"; // import BotonesPedidos from "../componentes/pedidosCocina"; import '../style/principalCocina.css'; import Check from '../componentes/check' class PrincipalCocina extends React.Component { render() { return ( <div> <div className= "Container2"> <HeaderCocina/> <div className="grid"> <div className="parteUno"> {/*<BotonesPedidos/> <BotonesPedidos/> <BotonesPedidos/> <BotonesPedidos/> <BotonesPedidos/> <BotonesPedidos/> <BotonesPedidos>*/} </div> <div className="parteDos"> <div className="factura"> <div className="title">RESUMEN PEDIDO:</div><div className="resumenFactura"> LALALA </div></div> </div> <Check/> </div> </div> </div> ) } }; export default PrincipalCocina
const nodemailer = require("nodemailer"); import generateInline from "../../../../templates/notifyNewMessage"; import connectDb from "../../../../utils/connectDb"; import User from "../../../../models/User"; import Authenticate from "../../../../middleware/auth"; connectDb(); const handler = async (req, res) => { switch (req.method) { case "POST": await handlePostRequest(req, res); break; default: res.status(405).send(`Method ${req.method} not allowed`); break; } }; // @route POST api/verification/send/forgotPassword // @desc send user email with link to verify their registered email address // @res // @access Public async function handlePostRequest(req, res) { const { recieverUserId, senderUsername, messagesUrl } = req.body; try { const { email } = await User.findById(recieverUserId); if (!email) return res.status(400).send("Bad Request"); //generate email html let htmlBody = generateInline(senderUsername, messagesUrl); //create nodemailer instance var transporter = nodemailer.createTransport({ service: process.env.EMAIL_SERVICE, auth: { user: process.env.EMAIL_USER, pass: process.env.EMAIL_PASS, }, }); var mailOptions = { from: `BoardRack <${process.env.EMAIL_USER}>`, to: email, subject: "New Message", html: htmlBody, }; //send email let info = await transporter.sendMail(mailOptions); if (!info) { res.status(500).send("Could Not Send Email"); } res.status(200).send("Email Sent"); } catch (err) { console.error(err.message); res.status(500).send("Server Error"); } } export default Authenticate(handler);
'use strict'; angular.module('angularTemplateRetrieverApp') .controller('MainCtrl', function ($scope, templateRetriever, $timeout) { $scope.awesomeThings = [ 'HTML5 Boilerplate', 'AngularJS', 'Karma' ]; templateRetriever.getTemplate('/views/templateOne.html') .then(function (template){ console.log(template); $timeout(function(){ $scope.awesomeThings.push(template); }, 500); }); });
import axios from "axios"; export const me = async () => { try { const res = await axios.get("/auth/account"); return res; } catch (err) { console.error(err); } }; export const logout = async () => { try { const res = await axios.post("/auth/logout"); return res; } catch (err) { console.error(err); } }; // export const auth = async (email, password, method) => { // let res; // try { // res = await axios.post(`/auth/${method}`, { email, password }); // } catch (authError) { // return dispatch(getUser({ error: authError })); // } // try { // dispatch(getUser(res.data)); // history.push("/home"); // } catch (dispatchOrHistoryErr) { // console.error(dispatchOrHistoryErr); // } // }; // this should only be reddit based, no local login // after getting reddit credentials there needs to be a redirect where the user can put in their wallet address or easily create one if they dont already have one export const login = async () => { try { const res = await axios.get("/auth/reddit"); console.log(res, "RES"); return res; } catch (err) { console.error(err); } }; // get user transactions export const transactionHistory = async (id) => { try { const res = await axios.get(`/api/transactions/${id}`); return res; } catch (err) { console.error(err); } };
export default { xsmall: 12, small: 14, medium: 16, large: 18, }
import Workbook from "react-excel-workbook"; const isTrue = value => value == "true" || value == true; const filteredColumns = columns => { return columns.filter(column => { if ( column.hidden !== null && !isTrue(column.hidden) && isTrue(column.export) ) { return true; } else { return false; } }); }; /** * Component export excel file. * @type function * @param {array} sheets is a page of document * [ * { * name: "Sheet 1", * columns: [] // column for sheet 1 * }, * { * name: "Sheet 2", * columns: [] // column for sheet 2 * }, * { * ...sheet xxx * } * ] * @param {array} datas is a data of document * [ * ...data for sheet 1, * ...data for sheet 2, * ...data for sheet xxx * ] * @param {string} fileName is a file name of document * (i.e. xxx.xlsx) */ const Excel = ({ sheets = [], datas = [], fileName = "" }) => { return ( <Workbook filename={fileName} element={<button id="exportExcelButton" style={{ display: "none" }} />} > {sheets.map((sheet, sheetIndex) => { const columns = filteredColumns(sheet.columns); return ( <Workbook.Sheet key={sheet.name + sheetIndex} data={datas[sheetIndex]} name={sheet.name} > {columns.map((column, columnIndex) => ( <Workbook.Column key={column.header + columnIndex} label={column.header} value={column.field} /> ))} </Workbook.Sheet> ); })} </Workbook> ); }; export default Excel;
import React, { Component } from 'react' import { StyleSheet, View, Text, Image, TextInput, TouchableOpacity, ScrollView, Dimensions } from 'react-native'; const { width, scale } = Dimensions.get('window'); const s = width / 640; export default class Goods extends Component { render() { return ( <View style={{ flex: 1 }}> <View style={{ backgroundColor: '#fff' }}> <View style={{ width: '80%', flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', height: 50, backgroundColor: '#eeeeee', borderRadius: 5, marginTop: 12, marginLeft: '10%' }}> <TextInput placeholder='请输入商品名称' style={{ fontSize: 18 * s, marginLeft: 10 }} /> <TouchableOpacity style={{ width: 50, height: 50, marginRight: 10 }}> <Image style={{ width: 50, height: 50 }} source={require("../../assets/task1/search.png")} /> </TouchableOpacity> </View> <View style={{ flexDirection: 'row', justifyContent: 'space-evenly', height: 85 }}> <Text style={styles.top1}>综合</Text> <Text style={styles.tops}>销量</Text> <Text style={styles.tops}>新品</Text> <Text style={styles.tops}>价格</Text> <Text style={styles.tops}>信用</Text> </View> </View> <ScrollView> <View style={{ height: '100%', width: '100%', flexDirection: 'row', justifyContent: "space-evenly", flexWrap: 'wrap', backgroundColor: '#f4f4f4' }}> <View style={styles.box}> <Image style={styles.img1} source={require('../../assets/task1/shj.png')} /> <Text style={styles.word}>Oishi/上好佳玉米卷20包膨化休闲食品Oishi/上好佳</Text> <Text style={styles.price}>36.00</Text> </View> <View style={styles.box}> <Image style={styles.img2} source={require('../../assets/task1/ls.png')} /> <Text style={styles.word}>Oishi/上好佳玉米卷20包膨化休闲食品Oishi/上好佳</Text> <Text style={styles.price}>36.00</Text> </View> <View style={styles.box}> <Image style={styles.img1} source={require('../../assets/task1/shj.png')} /> <Text style={styles.word}>Oishi/上好佳玉米卷20包膨化休闲食品Oishi/上好佳</Text> <Text style={styles.price}>36.00</Text> </View> <View style={styles.box}> <Image style={styles.img2} source={require('../../assets/task1/ls.png')} /> <Text style={styles.word}>Oishi/上好佳玉米卷20包膨化休闲食品Oishi/上好佳</Text> <Text style={styles.price}>36.00</Text> </View> <View style={[styles.box, styles.box1]}> <Image style={styles.img1} source={require('../../assets/task1/shj.png')} /> <Text style={styles.word}>Oishi/上好佳玉米卷20包膨化休闲食品Oishi/上好佳</Text> <Text style={styles.price}>36.00</Text> </View> <View style={[styles.box, styles.box1]}> <Image style={styles.img2} source={require('../../assets/task1/ls.png')} /> <Text style={styles.word}>Oishi/上好佳玉米卷20包膨化休闲食品Oishi/上好佳</Text> <Text style={styles.price}>36.00</Text> </View> </View> </ScrollView> </View> ) } } const styles = StyleSheet.create({ tops: { fontSize: 20 * s, lineHeight: 80, color: '#333333' }, top1: { fontSize: 20 * s, lineHeight: 80, color: '#f23030' }, box: { height: 320, width: '45%', backgroundColor: '#fff', margin: 10 }, box1: { marginBottom: 80 }, img1: { width: 115, height: 150, marginLeft: '20%', marginTop: 45 }, img2: { width: 155, height: 150, marginLeft: '15%', marginTop: 45 }, word: { fontSize: 16 * s, marginTop: 30, marginLeft: 5, color: '#666666' }, price: { fontSize: 16 * s, color: '#f23030', marginTop: 15, marginLeft: 5 } });
import { fromJS } from 'immutable'; import { SHOW_LOGOUT_DIALOG, CANCEL_LOGOUT_DIALOG, AGREE_LOGOUT_DIALOG } from './constants'; // The initial state of the App export const initialState = fromJS({ show: false }); function logoutDialogReducer(state = initialState, action) { switch (action.type) { case SHOW_LOGOUT_DIALOG: return state.set('show', true); case CANCEL_LOGOUT_DIALOG: return state.set('show', false); case AGREE_LOGOUT_DIALOG: return state.set('show', false); default: return state; } } export default logoutDialogReducer;
const { MenuItems } = require('../models') const CreateMenuItem = async (req, res) => { try { const newMenuItem = await MenuItems.create(req.body) res.send(newMenuItem) } catch (error) { throw error } } const FindMenuItemsByRestaurant = async (req, res) => { try { const menuItemsByRestaurant = await MenuItems.findAll({ where: { restaurantId: req.params.restaurant_id } }) res.send(menuItemsByRestaurant) } catch (error) { throw error } } const MenuItemById = async (req, res) => { const ItemById = await MenuItems.findByPk(req.params.menu_item_id) res.send(ItemById) } module.exports = { CreateMenuItem, FindMenuItemsByRestaurant, MenuItemById }
'use strict'; var slidingWindow = require('@instana/core').util.slidingWindow; var logger = require('@instana/core').logger.getLogger('metrics'); exports.setLogger = function(_logger) { logger = _logger; }; var windowOpts = { duration: 1000 }; var minorGcWindow = slidingWindow.create(windowOpts); var majorGcWindow = slidingWindow.create(windowOpts); var incrementalMarkingsWindow = slidingWindow.create(windowOpts); var processWeakCallbacksWindow = slidingWindow.create(windowOpts); var gcPauseWindow = slidingWindow.create(windowOpts); exports.payloadPrefix = 'gc'; exports.currentPayload = { minorGcs: 0, majorGcs: 0, incrementalMarkings: 0, weakCallbackProcessing: 0, gcPause: 0, statsSupported: true }; try { var gcStats = require('gcstats.js'); gcStats.on('stats', function(stats) { // gcstats exposes start and end in nanoseconds var pause = (stats.end - stats.start) / 1000000; gcPauseWindow.addPoint(pause); var type = stats.gctype; if (type === 1) { minorGcWindow.addPoint(1); } else if (type === 2) { majorGcWindow.addPoint(1); } else if (type === 4) { incrementalMarkingsWindow.addPoint(1); } else if (type === 8) { processWeakCallbacksWindow.addPoint(1); } else if (type === 15) { minorGcWindow.addPoint(1); majorGcWindow.addPoint(1); incrementalMarkingsWindow.addPoint(1); processWeakCallbacksWindow.addPoint(1); } exports.currentPayload.statsSupported = true; exports.currentPayload.usedHeapSizeAfterGc = stats.after.usedHeapSize; }); } catch (e) { exports.currentPayload.statsSupported = false; logger.info( 'Could not load gcstats.js. You will not be able to see GC information in ' + 'Instana for this application. This typically occurs when native addons could not be ' + 'installed during module installation (npm install). See the instructions to learn more ' + 'about the requirements of the collector: ' + 'https://www.instana.com/docs/ecosystem/node-js/installation/#native-addons' ); } var reducingIntervalHandle; // always active exports.activate = function() { reducingIntervalHandle = setInterval(function() { exports.currentPayload.minorGcs = minorGcWindow.sum(); exports.currentPayload.majorGcs = majorGcWindow.sum(); exports.currentPayload.incrementalMarkings = incrementalMarkingsWindow.sum(); exports.currentPayload.weakCallbackProcessing = processWeakCallbacksWindow.sum(); exports.currentPayload.gcPause = gcPauseWindow.sum(); }, 1000); reducingIntervalHandle.unref(); }; exports.deactivate = function() { clearInterval(reducingIntervalHandle); };
import { green500, green600, green700, purple500, purple600, purple700, grey50, grey100, grey200, grey300, grey400, grey500, grey600, grey700, grey800, grey900, darkBlack, fullBlack, white } from 'material-ui/styles/colors' // GK: theme structure following https://github.com/jxnblk/styled-system/blob/master/README.md // and https://github.com/cloudflare/cf-ui/blob/master/packages/cf-style-const/src/variables.js export default { breakpoints: { mobile: '30em', // 480px, mobileWide: '37.5em', // 600px, tablet: '48em', // 768px, tabletWide: '56.25em', // 900px, desktop: '64em', // 1024px, desktopWide: '90em', // 1440px, desktopXL: '120em' // 1920px }, space: [ // exponential spacing because // http://tachyons.io/docs/layout/spacing/ '0rem', // [0] SR: to override default allofthespace with noneofthespace '0.25rem', // [1] '0.5rem', // [2] '1rem', // [3] '2rem', // [4] '4rem', // [5] '8rem', // [6] '16rem', // [7] '32rem' // [8] ], fontSizes: [ // typographic scale because // http://spencermortensen.com/articles/typographic-scale/ // and // https://blog.madewithenvy.com/responsive-typographic-scales-in-css-b9f60431d1c4 '0.8rem', // [0] 10pt '0.95rem', // [1] 11pt '1rem', // [2] 12pt '1.2rem', // [3] 14pt '1.4rem', // [4] 16pt '1.5rem', // [5] 18pt '1.7rem', // [6] 21pt '2rem', // [7] 24pt '3rem', // [8] 36pt '4rem', // [9] 48pt '5rem', // [10] 60pt '6rem', // [11] 72pt '8rem' // [12] 96pt ], fonts: { primary: 'Roboto, sans-serif', logo: '"Roboto", sans-serif' }, colors: { primary1: green500, primary2: green600, primary3: green700, accent1: purple500, accent2: purple600, accent3: purple700, greys: [ grey50, // [0] grey100, // [1] grey200, // [2] grey300, // [3] grey400, // [4] grey500, // [5] grey600, // [6] grey700, // [7] grey800, // [8] grey900 // [9] ], text: darkBlack, alternateText: white, canvas: white, border: grey300, shadow: fullBlack }, fontWeights: { thin: 100, light: 300, regular: 400, medium: 500, bold: 700, black: 900 }, em: '1em', rem: '1rem', borderRadius: '2px', zIndexMax: 1000 }
class addPersons { constructor(idTable, fileUrl) { this.idTable = idTable this.fileUrl = fileUrl this.data = null } clearTable() { //console.log("clearTable"); var dvTable = $('#' + this.idTable) dvTable.html('') } rowTableClickHandler(thisThis, thisTr) { console.log('clicked ' + $(thisTr).attr('id')) var id = parseInt($(thisTr).attr('id')) $('#Name').html(thisThis.data[id].Name) $('#Workman').html('Исполнитель - ' + thisThis.data[id].Workman) $('#Status').html('Состояние - ' + thisThis.data[id].Status) $('#Date').html('Срок - ' + thisThis.data[id].Date) $('#Description').html('Описание задачи - ' + thisThis.data[id].Description) $(thisTr).addClass('event-active-row') $(thisTr) .siblings() .removeClass('event-active-row') } addDataToTable() { //console.log("addDataTotable"); var obj = this.data this.clearTable() var table = $('#' + this.idTable) //table[0].border = "1"; var columns = Object.keys(obj[0]) var columnCount = columns.length var row = $(table[0].insertRow(-1)) for (var i = 0; i < columnCount; i++) { if (i == 0 || i == 1 || i == 3 || i == 4) { var headerCell = $('<th />') if (columns[i] == 'Name') { headerCell.html('Задача') } else if (columns[i] == 'Workman') { headerCell.html('Ответственный') } else if (columns[i] == 'Date') { headerCell.html('Срок') } else if (columns[i] == 'Status') { headerCell.html('Статус') } else { headerCell.html('N/A') } row.append(headerCell) } } for (var i = 0; i < obj.length; i++) { row = $(table[0].insertRow(-1)) row.addClass('hand-cursor') row.attr('id', i) for (var j = 0; j < columnCount; j++) { if (j == 0 || j == 1 || j == 3 || j == 4) { var cell = $('<td />') cell.html(obj[i][columns[j]]) row.append(cell) } } } var thisThis = this document.querySelectorAll('#' + this.idTable + ' tr').forEach(e => e.addEventListener('click', function() { thisThis.rowTableClickHandler(thisThis, this) }) ) $('#persons-table tr:eq(0) td:first-child span').click() $('#0').trigger('click') } fillTable() { //console.log("fillTable"); if (this.data == null) { var thisThis = this console.time('load persons') d3.json(this.fileUrl, function(error, persons) { console.timeEnd('load persons') if (error) console.log(error) thisThis.data = persons thisThis.addDataToTable() }) } else { this.addDataToTable() } } }
import { Selector, RequestLogger } from 'testcafe'; import locators from '../page-objects/components/locators'; import chessboardPage from '../page-objects/pages/chessboardPage'; import https from 'https'; import global from '../global' import gloabal from '../global'; const GLOBAL = new gloabal() const getLocator = new locators() const ChessBoardPage = new chessboardPage() var initialWindow, window2, window3 = null fixture`Check drag and drop` .page`http://localhost:8080/` .before(async t => { console.log('Before ALL') }) .beforeEach(async t => { console.log('Setting up game session for Player 1,2,3') await t.setTestSpeed(0.1) await t.setPageLoadTimeout(5000) const baseUrl = GLOBAL.BASE_URL initialWindow = await t.getCurrentWindow(); await t.maximizeWindow() window2 = await t.openWindow(baseUrl); window3 = await t.openWindow(baseUrl); await t.switchToWindow(initialWindow); await ChessBoardPage.setUpEnv() await t.switchToWindow(window2); await ChessBoardPage.clickButton_join_a_game() await ChessBoardPage.verifyPlayerDetails(2, false) await t.switchToWindow(window3); await ChessBoardPage.verifyPlayerDetails(3, false) console.log('Focus on window: User 1') await t.switchToWindow(initialWindow); await ChessBoardPage.verifyPlayerDetails(1, true) }) .after(async t => { console.log('After ALL') }) .afterEach(async t => { console.log('After each test') initialWindow, window2, window3 = null console.log('===================================================') }) test('Valid peices are accisable as per turn', async t => { // player 1: C1 to D3 console.log('User 1: perfroms drag and drop event ') await ChessBoardPage.performDragAndDropEvent(getLocator.whiteSourcePosition(), getLocator.whiteTargetPosition()) console.log('User 1: Drag and drop event is verified') await ChessBoardPage.verifyValuesInAPIandDatabase() console.log('Focus on window: User 2') await t.switchToWindow(window2); await ChessBoardPage.verifyPlayerDetails(2, true) await ChessBoardPage.verifyMoveExists(getLocator.whiteTargetPosition()) await ChessBoardPage.verifyMoveDoesNotExists(getLocator.whiteSourcePosition()) console.log('User 2: screen details and messages are correct') console.log('User 2: chess board is updated') console.log('Focus on window: User 3') await t.switchToWindow(window3); await ChessBoardPage.verifyPlayerDetails(3, false) await ChessBoardPage.verifyMoveExists(getLocator.WhiteNewTargetPosition()) await ChessBoardPage.verifyMoveDoesNotExists(getLocator.whiteSourcePosition()) console.log('User 3: screen details and messages are correct') console.log('User 3: chess board is updated') // player 2: G8 to E6 console.log('Focus on window: User 2') await t.switchToWindow(window2); console.log('User 2: performs drag and drop') await ChessBoardPage.verifyPlayerDetails(2, true) await ChessBoardPage.performDragAndDropEvent(getLocator.blackSourcePosition(), getLocator.blackTargetPosition()) await t.wait(1000) await ChessBoardPage.verifyMoveExists(getLocator.blackNewTargetPosition()) await ChessBoardPage.verifyMoveDoesNotExists(getLocator.blackSourcePosition()) await ChessBoardPage.verifyPlayerDetails(2, false) console.log('User 2: screen details and messages are correct') console.log('User 2: chess board is updated') await ChessBoardPage.verifyValuesInAPIandDatabase() console.log('Focus on window: User 3') await t.switchToWindow(window3); await ChessBoardPage.verifyPlayerDetails(3, false) await ChessBoardPage.verifyMoveExists(getLocator.WhiteNewTargetPosition()) await ChessBoardPage.verifyMoveDoesNotExists(getLocator.whiteSourcePosition()) await ChessBoardPage.verifyMoveExists(getLocator.blackNewTargetPosition()) await ChessBoardPage.verifyMoveDoesNotExists(getLocator.blackSourcePosition()) console.log('User 3: screen details and messages are correct') console.log('User 3: chess board is updated') // player1: G1 to F3 console.log('Focus on window: User 1') await t.switchToWindow(initialWindow); await t.wait(1000) await ChessBoardPage.verifyPlayerDetails(1, true) await ChessBoardPage.verifyMoveDoesNotExists(getLocator.whiteSourcePosition()) await ChessBoardPage.verifyMoveDoesNotExists(getLocator.WhiteNewTargetPosition()) await ChessBoardPage.verifyMoveExists(getLocator.blackNewTargetPosition()) await ChessBoardPage.verifyMoveDoesNotExists(getLocator.blackSourcePosition()) await ChessBoardPage.verifyMoveExists(getLocator.WhiteNewTargetPosition2ndAttempt()) console.log('User 1: screen details and messages are correct') console.log('User 1: chess board is updated') await ChessBoardPage.performDragAndDropEvent(getLocator.whiteSourcePosition2(), getLocator.whiteTargetPosition2()) await t.wait(1000) await ChessBoardPage.verifyPlayerDetails(1, false) await ChessBoardPage.verifyMoveDoesNotExists(getLocator.whiteSourcePosition2()) await ChessBoardPage.verifyValuesInAPIandDatabase() // Player 2: B8 to C6 console.log('Focus on window: User 2') await t.switchToWindow(window2); console.log('User 2: performs drag and drop') await ChessBoardPage.verifyPlayerDetails(2, true) await ChessBoardPage.performDragAndDropEvent(getLocator.blackSourcePosition2(), getLocator.blackTargetPosition2()) await t.wait(1000) await ChessBoardPage.verifyMoveExists(getLocator.blackNewTargetPosition2()) await ChessBoardPage.verifyMoveDoesNotExists(getLocator.blackSourcePosition2()) await ChessBoardPage.verifyPlayerDetails(2, false) console.log('User 2: screen details and messages are correct') console.log('User 2: chess board is updated') await ChessBoardPage.verifyValuesInAPIandDatabase() console.log('Focus on window: User 3') await t.switchToWindow(window3); await ChessBoardPage.verifyPlayerDetails(3, false) await ChessBoardPage.verifyMoveExists(getLocator.blackNewTargetPosition2()) await ChessBoardPage.verifyMoveExists(getLocator.blackNewTargetPosition()) await ChessBoardPage.verifyMoveExists(getLocator.WhiteNewTargetPosition2ndAttempt()) await ChessBoardPage.verifyMoveExists(getLocator.WhiteNewTargetPosition2ndAttempt2()) console.log('Focus on window: User 1') await t.switchToWindow(initialWindow); await t.wait(1000) await ChessBoardPage.verifyPlayerDetails(1, true) await ChessBoardPage.verifyMoveExists(getLocator.blackNewTargetPosition2()) await ChessBoardPage.verifyMoveExists(getLocator.blackNewTargetPosition()) await ChessBoardPage.verifyMoveExists(getLocator.WhiteNewTargetPosition2ndAttempt()) await ChessBoardPage.verifyMoveExists(getLocator.WhiteNewTargetPosition2ndAttempt2()) });
export default { loadAgenda: (context, courseID) => { let fetch = new XMLHttpRequest(); fetch.onreadystatechange = function(){ if (this.readyState == 4 && this.status == 200){ let resp = JSON.parse(this.response); let newAgenda = { courseID: courseID, text: resp.text, } context.commit('setAgenda', newAgenda); } }; let requstData = { courseID : courseID, }; fetch.open("POST", "/api/agenda/load", true); fetch.setRequestHeader("X-Requested-With", "XMLHttpRequest") fetch.setRequestHeader("Content-Type", "application/json"); fetch.send(JSON.stringify(requstData)); }, updateAgenda: (context, newAgenda) => { let fetch = new XMLHttpRequest(); fetch.onreadystatechange = function(){ let success = (this.readyState == 4 && this.status == 200); context.commit('saveAgendaStatus', success); }; fetch.open("POST", "/api/agenda/save", true); fetch.setRequestHeader("X-Requested-With", "XMLHttpRequest") fetch.setRequestHeader("Content-Type", "application/json"); fetch.send(JSON.stringify(newAgenda)); }, loadTodolist: () => { }, updateTodo: () => { }, }
define([ './../descriptor/Descriptor' ], function ( Descriptor ) { 'use strict'; return function(/*SagaModel*/){ return { //Override me configureSchema: function(){}, _getSchemaAttributes: function(){ if (!this.__schemaAttributes) { this.__schemaAttributes = {}; } return this.__schemaAttributes; }, _addSchemaAttribute: function(attribute, descriptorData){ if (!attribute) { return; } // if (this.get(attribute, {lazyCreation:false}) && this._hasSchemaAttribute(attribute)) { // throw new Error('Attribute already use and setted'); // } var descriptor = new Descriptor(descriptorData); this._getSchemaAttributes()[attribute] = descriptor; }, _removeSchemaAttribute: function(attribute){ if (!this._hasSchemaAttribute(attribute)) { return; } this._getSchemaAttributes()[attribute].clear(); delete this._getSchemaAttributes()[attribute]; }, _hasSchemaAttribute: function(attribute){ return this._getSchemaDescription(attribute) !== undefined; }, _getSchemaDescription: function(attribute){ return this._getSchemaAttributes()[attribute]; }, generateSchemaAttribute: function(attribute, options){ // if (this._hasSchemaAttribute(attribute)) { // throw new Error('Attribute already use'); // } options = _.defaults(options|| {}, { // type:'PRIMITIVE', /* PRIMITIVE, COLLECTION, MODEL */ // generator:null, /* RemoteModel or RemoveCollection*/ attribute:attribute }); this._addSchemaAttribute(attribute, options); return this._generateGetSetForAttribute.apply(this, [attribute, options]); } }; }; });
let ref = require("http"); let myFunction = function (request, response) { console.log("Hey There!"); } server = ref.createServer(myFunction); server.listen(8080);
var ADD_TODO = 'ADD_TODO'; var DELETE_TODO = 'DELETE_TODO'; var EDIT_TODO = 'EDIT_TODO'; var COMPLETE_TODO = 'COMPLETE_TODO'; var COMPLETE_ALL = 'COMPLETE_ALL'; var CLEAR_COMPLETED = 'CLEAR_COMPLETED';
/*请在该区域内声明或者获取所要使用的全局变量*/ /********************************************begin************************************/ /*Global Variable Area */ let disArray = ["0px","-600px","-1200px","-1800px","-2400px","-3000px","-3600px"]; let wrap = document.getElementsByClassName("wrap")[0]; let container = document.getElementsByClassName("container")[0]; let images = document.querySelectorAll(".wrap img"); let leftArrow = document.getElementsByClassName("arrow_left")[0]; let rightArrow = document.getElementsByClassName("arrow_right")[0]; let spans = document.getElementsByClassName("buttons")[0].children; /*********************************************end*************************************/ /* 任务一 * 请参考css中的style参数、html中的内容、下方的效果要求,然后在下面区域内编写代码。 * 效果要求: * ①点击左箭头prev和右箭头next的时候,可以切换到前一张图片和下一张图片。(左右箭头为html中的a标签) * ②每切换一张图片,右下角的数字标记对应变化。 * 如:一开始,第1张图片显示出来,右下角的1-5的数值中,数值1位红色,2-4为绿色,表示当前显示第1张图片。 * 点击next箭头,图片切换到第2张,同时,右下角红色数值从1切换为2,数值1,3,4,5为绿色。 * ③当当前图片为第1张时,点击prev箭头,切换到第5张图片,且数值5置为红色。 * 当当前图片为第5张时,点击next箭头,切换到第1张图片,且数值1置为红色。 * ④切换图片的过程不要求,可直接切换,也可动画切换,但要求保证一定的切换动画合理性,不能出去明显的衔接不当。 * ⑤本部分只能使用原生JS。 */ /********************************************begin************************************/ /*Code Here*/ //距离对应属性,属性对应按钮 leftArrow.addEventListener("click",prevPic,false); rightArrow.addEventListener("click",nextPic,false); //当前img的顺序数值,0到6的数 function thisCenter() { for (let i = 0; i < disArray.length; i++) { if (wrap.style.left === disArray[i]) return i; } } //当img顺序数值超过范围时改变他们,以继续循环 function checkCenter(num) { if (num === -1) return 4; else if (num === 7) return 2; else return num; } //清楚所有span的class name,即取消红色底色 function clearSpans() { for (let j = 0; j < spans.length; j++) spans[j].className = ""; } //将img顺序数值与span对应 function matchSpan(num) { let spanNum; switch (num) { case 0:spanNum = 4;break; case 1:spanNum = 0;break; case 2:spanNum = 1;break; case 3:spanNum = 2;break; case 4:spanNum = 3;break; case 5:spanNum = 4;break; case 6:spanNum = 0;break; } return spanNum; } //函数 function prevPic() { let nextCenter = checkCenter(thisCenter() - 1); wrap.style.left = disArray[nextCenter]; clearSpans(); spans[matchSpan(nextCenter)].className = "on"; } //函数 function nextPic() { let nextCenter = checkCenter(thisCenter() + 1); wrap.style.left = disArray[nextCenter]; clearSpans(); spans[matchSpan(nextCenter)].className = "on"; } /*********************************************end*************************************/ /* 任务二 * 请参考css中的style参数、html中的内容、下方的效果要求,然后在下面区域内编写代码。 * 效果要求: * ①轮播可以自动播放,切换图片间隔为2s,每一次切换的效果与点击next箭头的效果一致。 * ②当鼠标移入轮播区域内时,停止自动播放。 * ③当鼠标不在轮播区域内时,开始自动播放。 * ④页面刚加载完成时,如果鼠标不在轮播区域内,自动开始自动播放;否则,等待直到鼠标移出轮播区域,再进行自动播放。 * ⑤本部分只能使用原生JS。 */ /********************************************begin************************************/ /*Code Here*/ function startRoll() { let count = window.setInterval(nextPic,2000); container.addEventListener("mouseover", function (){ clearInterval(count) } ,false); } window.addEventListener("load",startRoll,false); container.addEventListener("mouseout", startRoll, false); /*********************************************end*************************************/ /* 任务三 * 请参考css中的style参数、html中的内容、下方的效果要求,然后在下面区域内编写代码。 * 效果要求: * ①点击右下角的任意一个数值,能够切换到对应图片,且相应数值变为红色。 * ②进行①操作过后,是否自动播放,其规则与上一个任务一致。 * ③本部分只能使用原生JS。 */ /********************************************begin************************************/ /*Code Here*/ for (let i = 0; i < spans.length; i++) { spans[i].addEventListener("click",clickBtn,false); function clickBtn() { clearSpans(); spans[i].className = "on"; wrap.style.left = -600 * (i + 1) + "px"; } } /*********************************************end*************************************/ /*任务四 * 请参考css中的style参数、html中的内容、下方的效果要求,然后在下面区域内编写代码。 * 效果要求: * ①点击某一非表头的单元格,可以编辑其内容,编辑完毕后点击其他部位,可以在界面上显示修改后的内容。 * ②点击单元格后,光标自动定位于单元格的首个字符或者汉字前。 * ③本部分可以使用jQuery,也可以使用原生JS。 */ /********************************************begin************************************/ /*Code Here*/ $(function(){ //定义方法 $('table td').click(function(){ //定义点击事件 if(!$(this).is('.input')){ //如果当前不是.input类 $(this).addClass('input').html('<input type="text" value="'+ $(this).text() +'" />'); $(this).find('input').css({"outline":"none","height":"18px","width":"190px","font-weight":"bold","font-size":"16px"}); $(this).find('input').focus().blur(function(){ //当前添加类获得元素新插入一个input通过遍历获得input定义伪类,当失去焦点以后在定义一个方法 $(this).parent().removeClass('input').html($(this).val() || ""); //当前查找每个元素,删除掉input类获得input所有元素的值并且和0 }); } }) }); /*********************************************end*************************************/
import React, {Component} from "react"; import "./style.css"; import logo from "../../images/followLogo.svg"; import {Collapse, Navbar, NavbarToggler, NavbarBrand, Nav, NavItem, NavLink} from "reactstrap"; class FollowNavbar extends Component { constructor(props) { super(props); this.toggleNavbar = this.toggleNavbar.bind(this); this.state = { collapsed: true }; } toggleNavbar() { this.setState({ collapsed: !this.state.collapsed }); } render(){ return ( <div className="navbarWrapper"> <Navbar color="faded" light> <NavbarBrand href="/Home" className="mr-auto"> <img src={logo} alt="Follow Logo" className="navLogo"></img> </NavbarBrand> <NavbarToggler onClick={this.toggleNavbar} className="mr-2 NavbarToggler" /> <Collapse isOpen={!this.state.collapsed} navbar> <Nav navbar> <NavItem> <NavLink href="">Account Information</NavLink> </NavItem> <NavItem> <NavLink href="/">Logout</NavLink> </NavItem> </Nav> </Collapse> </Navbar> </div> ); } } export default FollowNavbar;
import React, {Component} from 'react'; import 'antd/dist/antd.css'; import {Table, LocaleProvider} from 'antd'; import zhCN from 'antd/lib/locale-provider/zh_CN'; import PropTypes from 'prop-types' import ReactHTMLTableToExcel from 'react-html-table-to-excel'; import ReactDOM from 'react-dom' const screenWidth = window.screen.width const tableWidth = screenWidth - 200 export default class TableView extends Component { static propTypes = { columns: PropTypes.array.isRequired, data: PropTypes.array.isRequired, pageNo: PropTypes.number, pageSize: PropTypes.number, total: PropTypes.number }; static defaultProps = { pageNo: 0, pageSize: 10 }; componentWillReceiveProps(Props) { //console.log(Props) this.setState({ data: Props.data, total: Props.total, selectedRowKeys: [], pageNo: Props.pageNo }) } state = { selectedRowKeys: [], columns: [], data: [], xSlide: 1300, pageNo: 0, pageSize: 10, total: 0, }; selectRow = (record) => { //console.log(record) } onSelectedRowKeysChange = (selectedRowKeys) => { console.log(selectedRowKeys) this.setState({selectedRowKeys}, () => { this.props.onSelectedRowKeys && this.props.onSelectedRowKeys(this.state.selectedRowKeys) }); } componentWillMount() { this.state.columns = this.props.columns this.state.total = this.props.total this.state.pageSize = this.props.pageSize this.state.xSlide = this.props.columns.length * 100 > tableWidth ? this.props.columns.length * 100 : tableWidth if (this.props.minWidth) { this.state.xSlide = this.props.minWidth } //console.log(this.state.xSlide) this.state.data = this.props.data } componentDidMount() { const tableCon = ReactDOM.findDOMNode(this.refs['table']) const table = tableCon.querySelector('table') table.setAttribute('id', 'table-to-xls') } onChangePagintion = (e) => { this.props.onChangePagintion(e) // this.state.pageNo = 0 } render() { const {selectedRowKeys, total, pageSize} = this.state; const rowSelection = { selectedRowKeys, onChange: this.onSelectedRowKeysChange, }; return ( <div> {this.props.showExcel && <ReactHTMLTableToExcel id="test-table-xls-button" className="download-table-xls-button" table="table-to-xls" filename="table" sheet="tablexls" buttonText="导出数据"/> } <LocaleProvider locale={zhCN}> <Table ref='table' rowKey={record => record.registered} size='middle' style={{width: tableWidth, margin: '0 auto'}} scroll={{x: this.state.xSlide}} pagination={{ pageSize: this.state.pageSize, total: this.state.total, onChange: this.onChangePagintion, current: this.props.pageNo }} rowSelection={this.props.hiddenSelection ? null : rowSelection} columns={this.state.columns} dataSource={this.state.data} onRow={(record) => ({ onClick: () => { this.selectRow(record); }, })} /> </LocaleProvider> </div> ); } }
var Marionette = require('marionette'), Backbone = require('backbone'), Config = require('config'), Utils = require('utils'), Modal = require('helpers/modal'), Mapa = require('utilsMaps')('principal'), Singleton = require('singleton'), _ = require('underscore'); var Self = null; module.exports = Marionette.ItemView.extend({ template: require('templates/arvore.tpl'), events: { 'change .checkbox-action': 'toggleLayerVisibility', 'mouseover #layers-container .leaf': 'highlightMarker', 'mouseout #layers-container .leaf': 'unhighlightMarker', 'click .layer-add': 'layerAdd', 'click .layer-edit': 'layerEdit', 'click .layer-check-all': 'layersToggleCheckAll', 'click .layer-uncheck-all': 'layersToggleCheckAll', 'click .layer-collapse-all': 'layersCollapseAll', 'click .layer-expand-all': 'layersExpandAll', 'click .layer-fold': 'toggleLayerFold', 'click .layer-redefine': 'renderLayers', 'click .show-profile': 'showProfile' }, initialize: function () { Self = this; Singleton.explorerView = this; }, destroy: function () { delete Singleton.explorerView; }, onRender: function () { Self.renderLayers(); }, arvoreTakeSnapshot: function () { Self.arvoreSnapshot = []; // Armazena o estado de collapseds da árvore Self.$('.layer-collapsed').each(function (idx, el) { if (Self.$(el).hasClass('layer-collapsed')) { Self.arvoreSnapshot.push(Self.$(el).attr('data-slug-for-collapse')); } }); // Guarda o scrollTop para reposicionar depois que salvar o cadastro Self.filtrosScrollTop = $('#region-filtros').scrollTop(); }, highlightMarker: function (ev) { ev.preventDefault(); var id = $(ev.currentTarget).attr('data-id'); if (Mapa && Mapa.getObjects()['entidade-cultural']) { var allmarkers = Mapa.getObjects()['entidade-cultural'], wkt = Mapa.getObjects()['entidade-cultural'][id]; if (wkt) { if (allmarkers) { _.each(allmarkers, function (marker) { marker.setIcon(marker.icon.replace(/(\-alpha)?\.png/i, '-alpha.png')); }); wkt.setIcon(wkt.icon.replace(/(\-alpha)?\.png/i, '.png')); } } } }, unhighlightMarker: function (ev) { ev.preventDefault(); if (Mapa && Mapa.getObjects()['entidade-cultural']) { var allmarkers = Mapa.getObjects()['entidade-cultural']; if (allmarkers) { _.each(allmarkers, function (marker) { marker.setIcon(marker.icon.replace(/(\-alpha)?\.png/i, '.png')); }); } } }, layerAdd: function (ev) { ev.preventDefault(); var slug = Self.$(ev.currentTarget).attr('data-slug'); if (!Utils.session()) { Backbone.history.navigate('#/cadastro/' + slug); return false; } if (Utils.pode('ENTIDADE_CADASTRAR')) { require('utilsMaps')('hideAll'); Backbone.history.navigate('#/cadastro/' + slug); } else { Modal.alert('Sem permissões suficientes para esta ação'); } }, layerEdit: function (ev) { ev.preventDefault(); var id = Self.$(ev.currentTarget).attr('data-id'); var slug = Self.$(ev.currentTarget).attr('data-slug'); if (!Utils.session()) { Backbone.history.navigate('#/cadastro/' + slug + '/' + id); return false; } if (Utils.pode('ENTIDADE_EDITAR')) { require('utilsMaps')('hideAll'); Backbone.history.navigate('#/cadastro/' + slug + '/' + id); } else { Modal.alert('Sem permissões suficientes para esta ação'); } }, layersToggleCheckAll: function (ev) { ev.preventDefault(); var isChecked = Self.$(ev.currentTarget).hasClass('layer-check-all'); Self.$('.layer-group input.checkbox-action').prop('checked', isChecked); Self.$('.layer-subgroup input.checkbox-action').prop('checked', isChecked); Self.$('.layer-subgroup .list-group input.checkbox-action').prop('checked', isChecked).trigger('change'); }, layersCollapseAll: function (ev) { ev.preventDefault(); Self.$('.layer-group, .layer-subgroup').addClass('layer-collapsed'); }, layersExpandAll: function (ev) { if (ev) { ev.preventDefault(); } Self.$('.layer-group, .layer-subgroup').removeClass('layer-collapsed'); }, renderLayers: function (ev) { if (ev) { ev.preventDefault(); } Utils.loadingMessage('Carregando o conteúdo...'); Utils.collectionFromURLAsync(Config.baseURL + '/geo/arvore', function (arvore) { Utils.loadingMessageHide(); // Verifica se o mapa já carregou if (Singleton.painel.mapaView.Mapa) { // Deleta os possíveis objetos do mapa Singleton.painel.mapaView.Mapa.clearObjects('entidade-cultural'); } // Cria uma collection vazia no painel. No último loop serão adicionados models Singleton.painel.collection = new Backbone.Collection(); var $layerGroupElement = '', permissoes = []; // Lê as permissões necessárias uma única vez antes de renderizar a árvore permissoes.entidadeCadastrar = Utils.pode('ENTIDADE_CADASTRAR'); permissoes.entidadeEditar = Utils.pode('ENTIDADE_EDITAR'); Self.$('#layers-container').html(''); arvore.each(function (tipologia) { var counters = { total: _.reduce(tipologia.get('tipos'), function (memoTipologia, tipo) { return memoTipologia + tipo.entidades.length; }, 0), semGeolocalizacao: _.reduce(tipologia.get('tipos'), function (memoTipologia, tipo) { return memoTipologia + _.reduce(tipo.entidades, function (memo, obj) { return memo + (obj.wkt === undefined ? 1 : 0); }, 0); }, 0), naoModerados: _.reduce(tipologia.get('tipos'), function (memoTipologia, tipo) { return memoTipologia + _.reduce(tipo.entidades, function (memo, obj) { return memo + (obj.moderado ? 0 : 1); }, 0); }, 0) }; $layerGroupElement = $layerGroupElement + '<div class="layer-group layer-foldable layer-collapsed" data-slug-for-collapse="' + tipologia.get('slug') + '">' + '<div class="layer-group-title">' + '<div class="checkbox checkbox-default">' + '<i class="glyphicon glyphicon-chevron-down layer-fold"></i> ' + '<input type="checkbox" class="checkbox-action" data-slug="' + tipologia.get('slug') + '" data-entity="tipologia" style="styled">' + '<label>' + '<span class="label label-success" data-toggle="tooltip" data-placement="top" title="Total">' + counters.total + '</span>' + (counters.semGeolocalizacao > 0 ? '<span class="label label-warning" data-toggle="tooltip" data-placement="top" title="Geolocalização indefinida">' + counters.semGeolocalizacao + '</span>' : '') + (counters.naoModerados > 0 ? '<span class="label label-danger" data-toggle="tooltip" data-placement="top" title="Em análise">' + counters.naoModerados + '</span>' : '') + ' ' + tipologia.get('tituloPlural') + ' ' + '</label>' + '</div>' + '</div>'; _.each(tipologia.get('tipos'), function (tipo) { var counters = { total: tipo.entidades.length, semGeolocalizacao: _.reduce(tipo.entidades, function (memo, obj) { return memo + (obj.wkt === undefined ? 1 : 0); }, 0), naoModerados: _.reduce(tipo.entidades, function (memo, obj) { return memo + (obj.moderado ? 0 : 1); }, 0) }; $layerGroupElement = $layerGroupElement + '<div class="layer-subgroup layer-collapsed layer-foldable" data-slug-for-collapse="' + tipo.slug + '">' + '<div class="layer-inline">' + '<div class="checkbox checkbox-default">' + (tipo.entidades.length > 0 ? '<i class="glyphicon glyphicon-chevron-down layer-fold"></i> ' : '<span style="margin-left: 8px">&nbsp;</span> ') + '<input type="checkbox" class="checkbox-action" data-id="' + tipologia.get('slug') + '-' + tipo.slug + '" data-entity="tipo" style="styled">' + '<label>' + (permissoes.entidadeCadastrar ? '<i class="glyphicon glyphicon-plus layer-add" data-slug="' + tipo.slug + '" data-toggle="tooltip" data-placement="left" title="Adicionar"></i> ' : '') + '<span class="label label-success" data-toggle="tooltip" data-placement="top" title="Total">' + counters.total + '</span>' + (counters.semGeolocalizacao > 0 ? '<span class="label label-warning" data-toggle="tooltip" data-placement="top" title="Geolocalização indefinida">' + counters.semGeolocalizacao + '</span>' : '') + (counters.naoModerados > 0 ? '<span class="label label-danger" data-toggle="tooltip" data-placement="top" title="Em análise">' + counters.naoModerados + '</span>' : '') + ' ' + tipo.tituloPlural + ' ' + '</label>' + '</div>' + '</div>' + '<ul class="list-group">'; _.each(tipo.entidades, function (entidade) { $layerGroupElement = $layerGroupElement + '<li class="layer-item">' + '<div class="layer-inline">' + '<div class="leaf" data-id="' + entidade.id + '">' + '<div class="checkbox checkbox-default">' + '<input type="checkbox" class="checkbox-action" data-id="' + entidade.id + '" data-entity="entidade-cultural" style="styled">' + '<label>' + (permissoes.entidadeEditar ? '<i class="glyphicon glyphicon-pencil layer-edit" data-id="' + entidade.id + '" data-slug="' + tipo.slug + '" data-toggle="tooltip" data-placement="left" title="Editar"></i> ' : '') + (entidade.wkt ? '<img src="assets/img/marker/' + tipologia.get('slug') + '.png" width="10"> ' : '<span class="label label-warning" data-toggle="tooltip" data-placement="top" title="Geolocalização indefinida">!</span> ') + (entidade.moderado ? '' : '<span class="label label-danger" data-toggle="tooltip" data-placement="top" title="Em análise">!</span> ') + '<span class="show-profile" data-id="' + entidade.id + '">' + entidade.nome + '</span>' + '</label>' + '</div>' + '</div>' + '</div>' + '</li>'; // Guarda o slug da tipologia na entidade para saber qual ícone usar no mapa entidade.slugTipologia = tipologia.get('slug'); // Adiciona um novo Model à Collection principal Singleton.painel.collection.push( new Backbone.Model(entidade) ); }); $layerGroupElement = $layerGroupElement + '</ul>' + '</div>'; }); $layerGroupElement = $layerGroupElement + '</div>'; }); // Plota a árvore na DIV Self.$('#layers-container').html($layerGroupElement); // Inicializa os tooltips da tela Self.$('[data-toggle="tooltip"]').tooltip(); // Marca somente os itens da árvore de acordo com o párâmetro de URL if (Singleton.painel.options.slugTipologia) { Self.$('[data-slug=' + Singleton.painel.options.slugTipologia + '][data-entity=tipologia]').trigger('click').parent().children('i').trigger('click'); } else { // Marca tudo da árvore Self.$('.layer-check-all').trigger('click'); } // Aplica o snapshot de collapse da árvore, se houver if (Self.arvoreSnapshot) { Self.layersExpandAll(); // Aplica o snapshot de collapse da árvore _.each(Self.arvoreSnapshot, function (nodeSlug) { Self.$('[data-slug-for-collapse="' + nodeSlug + '"]').addClass('layer-collapsed'); }); // Reposiciona o scroll salvo dos filtros $('#region-filtros').scrollTop(Self.filtrosScrollTop); } } ); }, showProfile: function (ev) { ev.preventDefault(); Utils.loadingMessage('Abrindo detalhe...'); Modal.showView(new ProfileView({ id: $(ev.currentTarget).attr('data-id') })); }, toggleLayerFold: function (ev) { // Expande e recolhe o layer clicado, através de pôr e tirar a classe abaixo Self.$(ev.currentTarget).closest('.layer-foldable').toggleClass('layer-collapsed'); }, toggleLayerVisibility: function (ev) { // Captura o elemnto input type="checkbox" clicado var $inputCheckbox = Self.$(ev.currentTarget); // Verifica se está checked ou não var isChecked = $inputCheckbox.prop('checked'); // Lê o ID (ou slug) do checkbox clicado var id = $inputCheckbox.attr('data-id'); // Define as ações dependendo do nível da árvore de camadas (layer level) switch ($inputCheckbox.attr('data-entity')) { case 'tipologia': { // Ao checar um elemento do nível mais alto, checa seus respectivos filhos e executa o change do último nível $inputCheckbox .parents('.layer-group').find('.layer-subgroup input.checkbox-action').prop('checked', isChecked) .parents('.layer-subgroup').find('.list-group input.checkbox-action').prop('checked', isChecked).trigger('change'); } break; case 'entidade-cultural': { // Localiza o respectivo Model na Collection var model = Singleton.painel.collection.get(parseInt(id)); if (isChecked) { if (model.get('wkt')) { // Define qual imagem utilizar no marker model.set('icon', 'assets/img/marker/' + model.get('slugTipologia') + '.png'); Singleton.mapaView.plotarWKT(model); } } else { // Limpa o objeto do mapa, caso ele exista if (Singleton.painel.mapaView.Mapa) { Mapa.clearObjects('entidade-cultural', model.get('id')); } } // Atualiza o status checked no model que está na collection da árvore model.set('isChecked', isChecked); } break; case 'tipo': { // Ao checar um elemento do nível intermediário, checa seus respectivos filhos e executa o change do último nível $inputCheckbox .parents('.layer-subgroup').find('.list-group input.checkbox-action').prop('checked', isChecked).trigger('change'); } break; } } });
import React, { Component } from 'react'; import { Link } from 'react-router-dom'; class ButtonDropDown extends Component { renderDropDown() { return ( <div> <ul id='dropdown1' className='dropdown-content'> <li><Link to="/new/simplenote">Simple</Link></li> <li><a>Cornel</a></li> <li><a>Two Column</a></li> <li><a>Outline</a></li> </ul> </div> ); } render() { return ( <div> <a className='dropdown-button btn' data-activates='dropdown1'> <i className="material-icons left">add</i> New Notes </a> {this.renderDropDown()} </div> ); } } export default ButtonDropDown;
#!/usr/bin/gjs const Lang = imports.lang; const vmath = imports.gi.vmath;
import React from 'react'; import colors from '../../styles/colors'; import '../../styles/style.scss'; import { Dropdown } from './Dropdown'; export default { title: 'Dropdown', component: Dropdown }; const tween = { type: "tween", delay: "0", duration: "2", ease: [0.44, 0, 0.56, 1] } // Dropdown Base export const DropdownBase = () => { const [dropOpen, setDrop] = React.useState(false); const [optionSelected, setOption] = React.useState('Placeholder'); return ( <Dropdown cls="dropdown-base"> <p className="dropdown-label">Dropdown label</p> <div className="dropdown-picker" onClick={() => { dropOpen ? setDrop(false) : setDrop(true) }}> <span className="choice">{optionSelected}</span> <svg className="icon-down" width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg"> <path d="M4 6L8 10L12 6" stroke={colors.$gray10} stroke-linecap="round" stroke-linejoin="round"/> </svg> </div> <div transition={tween} style={{ display: dropOpen ? 'flex' : 'none'}} className="dropdown-list"> <div className="option" onClick={() => { setOption('Option 1') setDrop(false) }}><span >Option 1</span></div> <div className="option" onClick={() => { setOption('Option 2') setDrop(false) }}><span >Option 2</span></div> <div className="option" onClick={() => { setOption('Option 3') setDrop(false) }}><span >Option 3</span></div> </div> </Dropdown> )}; //Dropdown Error export const DropdownError = () => ( <Dropdown cls="dropdown-base"> <p className="dropdown-label">Dropdown label</p> <div className="dropdown-picker error"> <span className="choice">Placeholder 1</span> <svg className="icon-down" width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg"> <path d="M4 6L8 10L12 6" stroke={colors.$gray10} stroke-linecap="round" stroke-linejoin="round"/> </svg> </div> <small className="small-error-text">Wrong option</small> </Dropdown> ); //Dropdown Disabled export const DropdownDisabled = () => ( <Dropdown cls="dropdown-base"> <p className="dropdown-label">Dropdown label</p> <div className="dropdown-picker disabled"> <span className="choice disabled-text">Placeholder 1</span> <svg className="icon-down icon-down-disabled" width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg"> <path d="M4 6L8 10L12 6" stroke={colors.$gray10} stroke-linecap="round" stroke-linejoin="round"/> </svg> </div> </Dropdown> );
#!/usr/bin/env node var config = require('./config.json'); var fs = require('fs'); var express = require('express'); var app = express(); var queue = require('queue-async'); var tasks = queue(1); var spawn = require('child_process').spawn; var mandrillMailer = require('mailer'), username = config.email.user, password = config.email.password; app.use(express.bodyParser()); // Receive webhook post app.post('/hooks/upload-to-s3/:repository', function(req, res) { // Close connection res.send(202); // Run build script // Queue request handler tasks.defer(function(req, res, cb) { var data = req.body; var branch = 'master'; var params = []; data.repo = data.repository.name; data.branch = data.ref.split('/')[2]; data.owner = data.repository.owner.name; var repo = req.params.repository; var source = config.env[repo]['location']; var type = config.env[repo]['type']; // Process webhook data into params for scripts params.push(data.repo); params.push(data.branch); params.push(data.owner); params.push('git@' + config.gh_server + ':' + data.owner + '/' + data.repo + '.git'); params.push(source); params.push('https://' + config.gh_server + '/' + data.owner + '/' + data.repo + '.git'); var checkForImageAdd = req.body.head_commit.added[0]; // We just need to send mail and upload only when image is added to img folder if(checkForImageAdd.indexOf('app/img/') > -1) { run(config.scripts.uploadToS3, params, function(err) { if (err) { console.log(' Failed to upload to S3 ' + err); send('Failed to upload images to s3: ' + data.owner + '/' + data.repo + '- Failed to update' + err, data.repo + ' - Failed to upload images to S3', data); return; } console.log('Successfully uploaded images to s3: ' + data.owner + '/' + data.repo); send('Successfully uploaded images to s3: ' + data.owner + '/' + data.repo + '- Succesfully updated', data.repo + ' - Succesfully uploaded to S3', data); return; }); } else { console.log(" Since images are not added so no need to upload to S3"); } }, req, res); }); // Receive webhook post app.post('/hooks/jekyll/:repository', function(req, res) { // Close connection res.send(202); // Queue request handler tasks.defer(function(req, res, cb) { var data = req.body; var branch = 'master'; var params = []; // Parse webhook data for internal variables data.repo = data.repository.name; data.branch = data.ref.split('/')[2]; data.owner = data.repository.owner.name; // End early if not permitted account if (config.accounts.indexOf(data.owner) === -1) { console.log(data.owner + ' is not an authorized account.'); if (typeof cb === 'function') cb(); return; } var repo = req.params.repository; if(config.env[repo] == undefined) { console.log(data.owner + 'Update repository not found'); if (typeof cb === 'function') cb(); return; } var source = config.env[repo]['location']; var type = config.env[repo]['type']; // End early if not permitted branch if (data.branch !== branch) { console.log('Not ' + branch + ' branch.'); if (typeof cb === 'function') cb(); return; } // Process webhook data into params for scripts /* repo */ params.push(data.repo); /* branch */ params.push(data.branch); /* owner */ params.push(data.owner); /* giturl */ params.push('git@' + config.gh_server + ':' + data.owner + '/' + data.repo + '.git'); /* source */ params.push(source); /* giturlhttps*/ params.push('https://' + config.gh_server + '/' + data.owner + '/' + data.repo + '.git'); // This configuration builds the jekyll site. Check if the location type is of jekyll before proceeding if (type === 'jekyll') { // Run inspect jekyll script which check jekyll build failures, which doesn't allow to pull unless it is resolved. runjekyll(config.scripts.inspect, params, function(err){ var resultant = err.split('$$'); // used to get the status code. if (resultant[1] === '1') { console.log('Failed to build: ' + data.owner + '/' + data.repo); send('Your website at ' + data.owner + '/' + data.repo + ' failed to build <br><br>' + resultant[2], data.repo + ' - Error building site', data); if (typeof cb === 'function') cb(); return; } else { // Run build script run(config.scripts.build, params, function(err) { if (err) { console.log('Failed to build: ' + data.owner + '/' + data.repo); send('Your website at ' + data.owner + '/' + data.repo + ' failed to build.', data.repo + ' - Error building site', data); if (typeof cb === 'function') cb(); return; } // Done running scripts console.log('Successfully rendered: ' + data.owner + '/' + data.repo); send('Your website at ' + data.owner + '/' + data.repo + ' was succesfully published.', data.repo + ' - Succesfully published', data); if (typeof cb === 'function') cb(); return; }); } }); } // Else run your own script to match up the needs. }, req, res); }); // Start server var port = process.env.PORT || 4000; app.listen(port); console.log('Listening on port ' + port); function runjekyll(file, params, cb) { var process = spawn(file, params); var errData = ''; process.stdout.on('data', function (data) { console.log('' + data); }); process.stderr.on('data', function (data) { errData += data.toString(); console.warn('' + data); }); process.on('exit', function (code) { if (typeof cb === 'function') { var message = "CODE$$"+code+"$$"+errData; // $$ is used as a delimited for splitting purpose. cb(message); } }); } function run(file, params, cb) { var process = spawn(file, params); process.stdout.on('data', function (data) { console.log('' + data); }); process.stderr.on('data', function (data) { console.warn('' + data); }); process.on('exit', function (code) { if (typeof cb === 'function') cb(code !== 0); }); } function send(body, subject, data) { if (config.email && data.pusher.email) { var message = { host: config.email.host, port: config.email.port, to: data.pusher.email, from: config.email.from, subject: subject, html: body, authentication: config.email.authentication, username: username, password: password }; mandrillMailer.send(message , function (err, result){ if(err) { console.warn(err); } } ); } }
function selectView(view) { $('.display').not('#' + view + "Display").hide(); $("#editCompanyTypeId option:first").attr('selected', 'selected'); $('#editCompanyName').val(''); $("#addCompanyTypeId option:first").attr('selected', 'selected'); $('#addCompanyName').val(''); $("*[id*='-ajax-link-target']") .each(function () { $(this).empty(); }); $('#' + view + "Display").show(); } $(document).ready(function () { getAllCompanies(); $('.back-to-companies').click(function() { getAllCompanies(); }); $('#add').click(function() { selectView("add"); }); $('#submitAdd').click(addCompanyOnSaveClick); $('#submitEdit').click(editCompanyOnSaveClick); }); // gets all companies using ajax request function getAllCompanies() { $.ajax({ url: '/api/company', type: 'GET', dataType: 'json', success: function (data) { displayData(data); selectView("summary"); } }); } // display companies data function displayData(companies) { $('#tableBody').empty(); $.each(companies, function(index, company) { $('#tableBody').append("<tr><td>" + company.CompanyId + "</td><td> " + company.CompanyTypeName + "</td><td>" + company.CompanyName + "</td><td>" + company.NumberOfStuff + "</td><td><a href='javascript:void(0);' class='edit-item' onclick='editCompany(this);'>Редактировать</a></td>" + "<td><a href='javascript:void(0);' class='delete-item' onclick='deleteCompany(this);'>Удалить</a></td></tr>"); }); } function editCompany(el) { var id = $(el).closest('tr').children().first().text(); getCompany(id); selectView("edit"); } function deleteCompany(el) { var id = $(el).closest('tr').children().first().text(); $.ajax({ url: '/api/company/' + id, type: 'DELETE', contentType: "application/json;charset=utf-8", success: function (result) { if (result) getAllCompanies(); else alert("Could not delete"); } }); } function editCompanyOnSaveClick(e) { e.preventDefault(); // get actual company information var company = { CompanyId: $('#editCompanyId').val(), CompanyName: $('#editCompanyName').val(), CompanyTypeId: $('#editCompanyTypeId').val() }; $.ajax({ url: '/api/company/company', type: 'PUT', data: JSON.stringify(company), contentType: "application/json;charset=utf-8", success: function (result) { if (result) { getAllCompanies(); } else alert("Could not update company with id=" + company.CompanyId); } }); } function addCompanyOnSaveClick(e) { e.preventDefault(); // get actual company information var company = { CompanyName: $('#addCompanyName').val(), CompanyTypeId: $('#addCompanyTypeId').val() }; $.ajax({ url: '/api/company/', type: 'POST', data: JSON.stringify(company), contentType: "application/json;charset=utf-8", success: function (result) { if (result) getAllCompanies(); else alert("Could not add company '" + company.CompanyName + "'"); } }); } // get company data by specified company id and insert it into edit block function getCompany(id) { $.ajax({ url: '/api/company/' + id, type: 'GET', dataType: 'json', success: function (company) { if (company != null) { $("#editCompanyId").val(company.CompanyId); $("#editCompanyName").val(company.CompanyName); $("#editCompanyTypeId").val(company.CompanyTypeId); } else alert("Could not get company information by id=" + id); } }); }
import React from "react"; import './App.css'; import 'semantic-ui-css/semantic.min.css' import { Button, Table, TableBody, TableRow } from 'semantic-ui-react' class App extends React.Component { constructor(props) { super(props); this.state = { items: [], isLoaded: true, sortType: "", search: "" }; } componentDidMount = () => { fetch("https://mindfuleducation-cdn.s3.eu-west-1.amazonaws.com/misc/data.json") .then(res => res.json()) .then(res => { this.setState({ items: res.getColleges, }); }); } onSort(sortType){ this.setState({sortType}) } searchFilter(event) { console.log(event.target.value); this.setState({search : event.target.value}); } render() { var { items, sortType, search } = this.state; items.sort((a,b) => { if(sortType === "asc") { var isReversed = 1; } else if(sortType === "desc") { var isReversed = -1; } return isReversed * a.name.localeCompare(b.name) }) var filteredCollege = items.filter((item) => { return item.name.indexOf(search) !== -1; }) var itemInfo = filteredCollege.map(item => ( <TableRow key={item.id}> <Table.Cell>{item.name}</Table.Cell> <Table.Cell>{item.groupPrefix}</Table.Cell> <Table.Cell><img src={item.logo}/></Table.Cell> <Table.Cell>{item.ofstedRating}</Table.Cell> </TableRow> )); return( <div className="App"> <h1>Partners</h1> <a href="search" className="search">Name</a> <div class="ui input" id="searchBox"><input type="text" onChange={this.searchFilter.bind(this)}/></div> <a href="search" className="search">Prefix</a> <div class="ui input" id="searchBox"><input type="text"/></div> <a href="search" className="search">Ofsted Rating</a> <div class="ui input" id="searchBox"><input type="text" id="rating" placeholder="Ofsted Rating"/></div> <Table celled> <Table.Header> {<Table.Row> <Table.HeaderCell onClick={()=>this.onSort(this.state.sortType==="asc"?"desc":"asc")}>Partner</Table.HeaderCell> <Table.HeaderCell onClick={()=>this.onSort(this.state.sortType==="asc"?"desc":"asc")}>Prefix</Table.HeaderCell> <Table.HeaderCell>Logo/Preroll</Table.HeaderCell> <Table.HeaderCell>Ofsted Rating</Table.HeaderCell> </Table.Row>} </Table.Header> <TableBody> {itemInfo} </TableBody> </Table> </div> ); } } export default App;
(function () { return { lineSymbols: { 'truckHistory': { 'lineColor': '#ff0000', 'lineWidth': 3, 'lineJoin': 'round', // miter, round, bevel 'lineCap': 'round', // butt, round, square 'lineDasharray': [10, 5, 5], // null 'lineOpacity ': 1 } }, plotSymbols: { police: { markerFile: '../static/assets/symbols/plot/PlottingPoliceman.png', markerWidth: 32, markerHeight: 38, markerDx: 0, markerDy: 0, markerOpacity: 1 }, doctor: { markerFile: '../static/assets/symbols/plot/PlottingDoctor.png', markerWidth: 32, markerHeight: 38, markerDx: 0, markerDy: 0, markerOpacity: 1 }, fireman: { markerFile: '../static/assets/symbols/plot/PlottingFireman.png', markerWidth: 32, markerHeight: 38, markerDx: 0, markerDy: 0, markerOpacity: 1 }, ambulance: { markerFile: '../static/assets/symbols/plot/PlottingAmbulance.png', markerWidth: 32, markerHeight: 38, markerDx: 0, markerDy: 0, markerOpacity: 1 }, truck: { markerFile: '../static/assets/symbols/plot/PlottingTruck.png', markerWidth: 32, markerHeight: 38, markerDx: 0, markerDy: 0, markerOpacity: 1 }, bus: { markerFile: '../static/assets/symbols/plot/PlottingBus.png', markerWidth: 32, markerHeight: 38, markerDx: 0, markerDy: 0, markerOpacity: 1 } }, animateMarkerSymbols: { // AnimateMarkerLayer not support markerFile use url eventWarnUnRead: { markerFile: 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADwAAAA8CAYAAAA6/NlyAAAU0UlEQVRoQ817W4wk13ne9//nnLp0V3fPZXf2phWX5MYyKNsPspIgbwLyEMRJECXBCApp2SSVLI0ECWA/GjBAIEAQwEAeAjgAF0FE2JadaA04F0FG3vzgwEASO7FjSyazvC9ndjk7M33vqjrn/L9xanYc7Wqk5XK15BZQaAy6p7u++v77/xXhh3D8m3/2N/PGnxptqpwqgXPOy2YhWhlFpYYrT1S2ICfM5qSfY4m+VF0Zlbknnrbg2ZJpvorYD/A7e/N4iL29+uXf/d3wsJdLH+ULtre3zV8Dsk+tIxutQt7A9heZWbMwG07iKSaMrFAPoJ4w+grKRdUKEZ/0e0QUjGpjoEtVzJWw8KrLAB5TiHtMethYmtdSL4Fx/a3FaX/t2jUBoA96/R8J8L/e3i4Ho2xzILQ5iuGUgDYjY90ohk6lBKiIRHkkyhjIWNUSYFjxPb+nqhoJGiwHBbwTqa1qo4oWSkso5mJwuGJze2n0g9b7m4cLTH4faK9duxYfFWDa3t7mn+r3Xda2ZVFg3UY6R5CzOWQLoE0BRkzUc1GsElxr2AnIsagxqsapJnrvApwoogSYWRtmUaZoJAYWeKvSEtBGokZB08C05xm3QsCOEbPXuGZy6OrF+mHRfOkBgH8oho9N+HSer+WFnK+Cni+DnIfilBhUAPqq6BFRDiBLgD0hA8g6VTYKJlW+l+EEuENMJFCSQCTCiIB6F9AQpFXiFsCKSGcRNANhEkB7S4P3JqK7bbb44KWr/3X5YZn+gYAVoKtXrth1HPZca9YzwhkQPZEJztsoZ0gxiowCQE6iORGyZMZIAYqQEWCdgAmafJeFwBFE6XsZUIIqKxJuIahE6kBHELyN2pCiFYIHUWNUVgSsBFRHpQPP9G5gvSHG3jAr2T9bVfPPX73q7wf8BwJ+5coVt2zb/gVenBkFfsoCF4j0NCk2VHkIpj4gBVQLVmQKZEKcgLrEdPJdKAwBHAkmGDINGxOBFK7ViUYXJTho8l9Jp09sE3lWbZH8mJBMu2aRFSvqdCp0IaCxGN6rHXYi87tY4s2//Ru/cfiRAL8M8DPb2zZYO+xx2MqVLuZETxvoOWWMFDRQoh6plgQtSJGDukici6EMiswoHCXAOAKsiWGBCZGMJvM2UCKIIfJEnRlLMm0hikoIHVh0gBPTDWkHeMWCjm0QLz1j0hizF5jfCSLfYU8792P6RIa/sb2dhXU7XK9xftD4ywy9qMynA2gdJqUZ9JEAA6WJWgJaCFMuxHnLKAjIrKhlUUuU/BdsYqRsJZRPPHEQSrepLSzqnpWQGQGoM21JTBMFJTQJMKk2BDSRKLG7siIroyl96VKYF55oGgzfSqDF6Fv3Y/pewF00/qJzw4HT82UMl6ogP8KKc6IYiKEqMPWUqQelvgFKkqM0JIQcgpyC5hzFWVGTAhURMYuQjQq3CtQbe5ggiAWj6Rksew7BmeTWyaQ71oUpRsc+mOS/3CijEVBDqisruiTVJRJgwhLM80g0bg3f8gZvNyzf3mPZAd5cvnT1D77Hp+8CfByNn+ybM/0ozzjVp1zQc0Z0g4BKmfreUF+JOpYJ1AOhBNCZdbYKrjpoTb4KpvPEVBmQdlGKVZGM1XhB+juFMbGEYBhdDE+QU8gGEHPStnJS90xsc+MDU9uZs2oy66UoViAsCVhAdY5UnTFNvOPdhcEbc8NvL9C++9LVa5N7ffouwF97/vnChrC+4cKni6g/bqM+AcGGhQxZ0RegijYFKupD0WfRHouWHBOrsPkymMF+zfkqfqh09/0CTMwIbWXRllbqzMSQsRfLDQzqDixoSehYXhDRTEDzyDz3hvZbxvs18Vtt9N+5UePmvQXKXRf29WefXXc9PNUXfbqM8WkWnCPFEKqDxDAonVyRat8E6WdeinzlC9uItStl00ZyrYBT2HmI45h9YVJJRUlppFnLQlumX0AN6NKIzpVoIURzYZpHUCpJJwI6jEzvTtj86YHDO7NJu/8L166tji+nu7BjU35i4M6Vop91wNNW4gUonSLVDigpOtDptEH6zktZrHxeLIOzy2hMnYA+BMof8K8+Z63XM2l6JnjHrRiqCZgLYSFs5oFpDkIqSmZQzAJod+HM6zNjr9eR33rh1VfHdwE+ro23PJ4YxvBjIFxS0AYIa5wAKwaADlhR2ShVlsAu26JYRWsXkU0jKXt2vvkoDmVocIzQM9JUTtqC29bxQgzfYRizSJgDNDWKqQK3587stpZed8H/4d969drNuwB/48r2SEJ+qRfj5UGQHyXCBTE8JJEhAxWnCA0MTZSqaGOvWPni42D23psXsxTMLOq+C4u+rX1mFkSYK2MWwTOBzhJgIR03hg+EzHWv+j/f64d39r591F52Jv3fvvL3toTzH2foj1jFpwGcIcKQRYc2HrEbDQ9dG6vBrCnLZMYfA7P3Ak5Mp8heV04mm0VY9Wx9ZMo0U9VZajIIHcPTaDCJxO/Nyfzpbcdverfa+af/9tqcUvN+aVydN2z/su0A6xaATYKOjGBgRIcADaKhYb4K/dFhnZUzbx+lz97PLZrC6GyzkFVl28RyNMmHaaqEqajOiDAFaBKYbi4NvbGE/j8f6td/9ld/e59++ee+svUp7y/0hf6KE73sRNdZdY0JQwINSXXY+TDRsFiEYv3Wyhbzlh+lz94PcIrePmOsKhtmm0W96tmlEmbCNI2gSeqoSHTCpLda4htC8fVozP/5u//uN2/Rv3/puWcGAed6UT5ngUtWdMgqIyClI4yIeMhBBlkbq3Iesh9Gnr0foA/7fl3ZuH+2DMuBWwlxx3BkTFUxYWAM1duB6INI/FrT4n/8352d9+k3X3rur5dtPNUT/YwVXFCiNYWOErsgHUXQWrmM1frtuujNWvfDyLMfFtD9Plf3neyfS6bt6iOTpimSWUOnUE05edxac+iJXl8x/96fTer36Lde/IdfyqBrRcQlo3o2AU7MMjBU6JoQrfVmvr+1s8x6M3/iEO5+F/ao3m/L5Mu5LirXtpmZR8tT0BFYKCZKNGmNmXqm6wvl39+NdIO++fyXX+Tkq8BFELagmmZTI6sYsupIgVFv5nubOytbLvyJQ7hHBeh+3yuGNGSMeWXD+HRvtezbuQJjho6dyCEpTZJPe8PvjJn++LbSLfqdn/3yP1fiSgjnCDidApZVHTnRFLBGie1y7ovN3ZqLxwzw8Q1ZDFzYO99rZ8MsFSJjUoytyKFVPVRgIkQ39olemzp7m7714rO/KECfFadIdMNBR1YwgiY/TieG5TwU67tLKudHeftxO1aVi7fP9dr5MOuGAqmmJsWhER0n0ADenxhzfZ7xAf3nrz73L1hROpF1Fl136AqODqgqRilw9WY+37i5QvGYAq4r10XrxSBbBsY0EE1Sj0zAYSHxgER3V868VRse07Wv/vS/ykSKQnUti5KAjhgp99IQSOmJhuVjDnjVd3JwroyrLj1h4okmK8sTVRxUQfYN9GbDdKMlntJ//Mc/88tZjHkVZZSJjNIkUggpHY1MlGHehEFvFvLBQYN89YjaoYf0keP0VA/cKvmsZ57MrZkIcFiFeDtTveXBu4FpdiJgT7S+sryZL8Nw64NlOZh5Z1uBiY+oHXqEgAde9jONH3imXU80PxFww7SxsOZUb+6HF3bmxXDa2k+ylLzf/fiBDPt44EQ+CISb0fLJgD3T+tKaU+XKD8/uLYpq6t0n2Sw8DOCBD/tWdO9EwPbYhxlrLZsN14bR+rTp9eetK6YBtnl8TfrgfBmXla1xkg/HZNK8c5cP90McpqAFQorMXQ2dWsPMh0E59/lwr0GxfDyDVhelz5dxVblVKilbQylopb74oIrxdibYXbK+F6yd0LWvPvcvHajIQ1jPuho6VVh3aunULUFTWioe5zx8Jy2F5dAlSqaBedIwTYjooAhhnxU7teW3uzz8zRef/SXt5st6ykSslzGNdY7y71G11eXhVGlxuXg8K62jNrHnZ0O3bJmnqbxkwqFROXRRDwW0Ozd4q3HmkH7nhS//fFdLg86y6qaNumYhI07j2VSEKIbFzJebu6vHrpY+HucuKxfGW2Uz67ulJ07D97GFdKWlgY498c7c0PWZoQP6Ly8++1ULHdgon4LSlmfaYNBaCmDmTpnZn/ty/THslo4H9osq85NRvqoLM2PFmFXTOQHRRFXSPvnGB8Z8Z8/gNv3Wiz/9pZ6EURHkEojP1oY2CLxmVZI/j1gw6i18b21vlZVzb5IwoVt7PQaHL1gXGxmWw6ydl3bujZk5lbERjNO4R4CJQieN6tu3rfnfN8A36Vf/0Vd+ahDDRhXjZad0LiqtKdGISNeSSacmomhiNZi2ZTlvXTYPMO3jkZ7qntHJmVKWA1cHyzMhmrLoJE0tfQJMNFbCIZheW0T9738S+D165YWv/NUNyOlRjJ91KhdT/5vSUpp0pBSVANsQB2UT+/2Zz3r7DblaPtE28dh3U5fUjWsru0rjnQSUFJPEbgBPPeNQGHuk/B2L8Ht/42v/4T36lRe+fPFMwPkh8HkmfYoTw9A1EKWc3M2mu3GtyqCc+mLtVm3y1IR9gsex79Z9G1ZVVjc5LyPxJHICnUY8SClpIqS3G+IdNea1psEf/oNf//Vdenl7u/qJks/3mD5vBH/JKE4rIa1H70RpTeOfAVSH5TKUg9tN58s2rT3le2VIH8d96Hx3M9e6cq13vAyW035pKqCpMKacppaqqSferZnfaFivI9Sv//00l375C1+wn3nq7FYB82OFyOVC5CKlYbxiqJRaRe5SkxWpnJd+UceyWHhXHLbsmk/GtJNqYHymCHXlamEslGl2ZNI0DYRZMm3bjXbwzoToj8ZMb1hvbv3Mr/3aovPFrz3/xbXM9S4Noj7dC/oZp3KeBCMlDBPgNIx3IpVRrVjQz5c+7x+2NlsEvhO1PxafTgP4kBlNA/jpZt40PbPq9sOKebdiScP4bl+sYyE6UOCNCfEfvI/s7V6WLV66etXfAfyFAji9NhL75JD0c0b0SRePJpYgDNKqNIHVO3ti18ayXMYiX3h7J2p/LIDbwspkM5NmkDU+o7RiWQAJLCVW54AeASa97dm83xJfr2P7x4fF+u6Vq1dTmXi0uD7eDz+d5xdyEz9no17OJW4Z1XUQVXpnN5xWLgSpTNS0H+65WrLEsl1G7gb08nCL8BOWZ50sIjHbqfV6NsxOFb4pzYo0yR06XeacoLP0im6hptNoeGdlzfUF0xt+iTef+y450zEznZhlu8KGJXu5DHi6F+JlB5xRlW4/TIyKBJUR6dOR/KEPQckRWbaMtlvB1A8ndbgX8HE0bo6kD8Fnpgk5r5R5lVQAJLpAUudB0zJ8LqTJj8dC+vbKmj/aD+6dYO3hC6++mtrG7rjLFF+58nd6Wdvf2iR6omrlswa4SNC0FE8dVOfDpNLpO4S5H4lKISqzOqadky3qyEmH06l2PoL04bulDpEJsTDS9o02PRfqzLTBUrrwBQstk26LksZDuyA1Byf/xYEw7QaiNxfQP7l+P43HN7a3zeF6nW81vXMO9FlL9FQuetZG2bBR+wStOo0WqC+UtFooI1FBEYVrY5IrZUmIloAP9hvKHlDc8heMFkab3Eq0HGDJR0OtN9So4U6fRUpLFl2yyIJVUsBKopZZavJrg9c86K1JNO//J++n98qMTww2v/38F9fgepdslCfzQE9mImezmEa3OlBO5kx9kPaIUAq4EEWphKTKy0lhszraar82eS2UBKWdfOnO6/f46bGpkaYVqDaV0zZJGzITxNyRIIJSbVcLaMXAIum0KOm1RJdWZQ6lQ295z7N5d57bP5vZ+L49DNMvXbuW1Hx3HScCfuXKT7qt9mKfqH/eID6TCz2RBdkyilSF9YnQi5QY505nqcSFkCZBeGaS3DBqxkEzjmKNgFiPxKXHQfIv/ImOdFnQTugtYim2zsRo4SlJEpP0UNEkVV7SW6KTLGGVJEuJ4TsmPRei3RXx63Xh3vaedkNdj7997Vp4GZ1w9f6Ajz/xzWefXUcPT5HopUxw0UTdMiIjJlQR6GlS4inlylRERo+ONJZWgMwbKhRwVsBGlBlq6E5WOP7+oxaEVAkSE+Cks2RKIL1VbZPAVIiaBJoTYGid1HidEg+d/04EfFuStOE+zJ4YtO69G//ryhV3cz6v2l48y8qXi6CfzoOes6nWBsoEOMn7A6EMhgsizTNJgDVrmTMhSgJTk2SIttNLn5C2lDQwtE0CcVDIoEk86knQMRwYrX4X6ASYJR5FZ8LNmujN1mXv3o/ZDwX4+EOvXNke9ZF9umr1YhXlU0b0tIEOhXQA5VIYpTecQzV3qg6qLhh2EeyUNM20kyqe71XEH1kzVIg06aRJEQqVxor6CEQwtZLEpURNTELTlIqgs7QzIpF9Id5Zgd6alnzz+/nsA5n0/wf8kw54qre+wobh7HxOep6hF4zKKatJtEZlIHQCcSOS5MOOGCaAXWCyEWQjw5wUt5JZG1VxgDciIRNNgvDQApHArYHUnJ6BIGr9Uen4QWTskMi7IcqtWXRj5/3i+/nsRwJ8/E/HArZKzemSwrk8IFVjm0kPwpBCNfk0kqw4MwkHYDyR88zGU1LEn/hUizpAconBRI2GKAgQ2vRK1GQaF6Sd0m4egMOGza3a6G5T885e04wf9GGPB6qBj0vQ9X4/38KiiGo3A5mLzLKVpRVrUgxwajZQZlGS9D9JJIxSEtMSCSX9fxLXJpVw96xDes5Fk5bW6tFjAApESQwzt5FpQaJjgPYa6M30rAPEH/jgZm2Wrb61WDzw4zwPBPhe8/iVf7JdOV+er6LfHGocQu0wMq0R0M9Ecyty5zGAJBQnTsr4pKFO0emozNMUw0NMryCVpIxX9T5FY2dnojxTxrTVeDAG3ZpIdnDc9dx7LR/274cCnHrp08+cLqp5yNeywoYlFb5nehoxJJINijLIiPKMNDeSTnJEwipdXkbyVc9olNkH1ZSW2qXSMpKOe4JbA9bp3NtAvGjnWtWrsmyPu54PC/ChfPh+P5JuAE6fLoZlOcqMnMkNrRWsZU+0dEFLp+nRnvSYQypCuurLe2tWntLzSYi1anOgmC+Fbrctbrz89a9P7/ebD/r+nwN0SiRLqA1PVQAAAABJRU5ErkJggg==', markerWidth: 60, markerHeight: 60, markerDx: 0, markerDy: 30 }, eventWarnRead: { markerFile: 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADwAAAA8CAYAAAA6/NlyAAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAAOdAAADnQBaySz1gAAAB90RVh0U29mdHdhcmUATWFjcm9tZWRpYSBGaXJld29ya3MgOLVo0ngAAAGZSURBVGiB7ZvbsoMgDEU3zvlv7ZfbJ85QJJBwNcB6tpDljqNVMPd9ozUffFiTnDhN61pMC2GuYIoWJ6CacC1JilryxcKtRX1KxbOFe4v65IpnCUtlL1xVj7PkSIuFubLS4nN/L5VmC3NESyVLxuWKH5yDRspyx+Z2XjLh1EAtRXPmSyUdTfhtspw5UzX/tZi0NXb+nDrIhKkzNVrWhaollnJQWIOsRSr9EB79BFWTkAvrtgS8M12LpLYfYU2t7MNtbXbCGuAE8y+sOd0Urls0YY2yqZqnamkOBzDXrYjCOpIJa2xnS6z2NVt6Jcx1X4/rV3M7u4Q8lkt4C8/OFp6dLTw7W3h2jtCb+hmetEIOJ06zXsKjC+jNlP+HYxxAn+VCPaGuX2C39C8a25r91pJqa43SPq7bVC0t+vIA6E6ZqtF3muLroYSHsMZbFDddgEhYU2tLZIFIS2uQrrqoJTXRaPHY/LHLci9Mkw7QU7hUFlhwcelrlw9LxpDcSvcCcS6jVw103QLgsswmD59ltvGEWGKjVow3bcX7AiCf2zCVKry3AAAAAElFTkSuQmCC', markerWidth: 60, markerHeight: 60, markerDx: 0, markerDy: 30 }, eventWarnReadCore: { markerType: 'ellipse', markerFill: 'rgb(88, 214, 141)', markerFillOpacity: 1, markerLineColor: '#34495e', markerLineWidth: 2, markerLineOpacity: 1, markerLineDasharray: [], markerWidth: 12, markerHeight: 12, markerDx: 0, markerDy: 0, markerOpacity: 1 }, eventWarnReadCore2: { markerFile: 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABQAAAAUCAYAAACNiR0NAAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAAOdAAADnQBaySz1gAAAB90RVh0U29mdHdhcmUATWFjcm9tZWRpYSBGaXJld29ya3MgOLVo0ngAAABbSURBVDiN1ZNLDgAQDERbcf8rj50FHRpKmPXLS78KQCKTQm1fCPMMUNFuyBAo5dlSLJFHbLbskTHu/FK81TH+/bM5LxzdmJWWv9Oyt0qLo59SgajXW82HZ7ObArfaIRvAaarvAAAAAElFTkSuQmCC', markerWidth: 20, markerHeight: 20, markerDx: 0, markerDy: 10 }, eventWarnUnReadCore: { markerFile: 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABQAAAAUCAYAAACNiR0NAAAA7UlEQVQ4T9WUvxLBQBDGvz0dBUFHw6SXNxBPhDeJNzpPIPoMTZSEgs6tuTH+5i7HjEKu3W9/t9/uzhJ+/OjHPJQYuPP6daqJQAHy0RY1EczS26yXtlZZLW87/gKEIJ/Ie8EqtEFzQF0ZV4U0wx54wefABM0Bs64/fLVpNseAbKfJ6D2aA267Pn+6SgIIvTSZP+tLCeyPARE5bTNiOqmwma0OhZazTm+gSEiAGoVQRtTaJFPnULTgCq3EdqCatNLVzBS3LraGnqkSERDeExn6E2mq7KZxHge9lzcxH1X83rOPLDsHUiBwVvgt/P+BFyrNWBXV4J05AAAAAElFTkSuQmCC', markerWidth: 20, markerHeight: 20, markerDx: 0, markerDy: 10 }, eventWarnLevel1: { markerType: 'ellipse', markerFill: '#e60012', markerFillOpacity: 1, markerLineColor: '#34495e', markerLineWidth: 2, markerLineOpacity: 1, markerLineDasharray: [], markerWidth: 16, markerHeight: 16, markerDx: 0, markerDy: 0, markerOpacity: 1 }, eventWarnLevel2: { markerType: 'ellipse', markerFill: '#ff9e01', markerFillOpacity: 1, markerLineColor: '#34495e', markerLineWidth: 2, markerLineOpacity: 1, markerLineDasharray: [], markerWidth: 14, markerHeight: 14, markerDx: 0, markerDy: 0, markerOpacity: 1 }, eventWarnLevel3: { markerType: 'ellipse', markerFill: '#f3da2d', markerFillOpacity: 1, markerLineColor: '#34495e', markerLineWidth: 2, markerLineOpacity: 1, markerLineDasharray: [], markerWidth: 13, markerHeight: 13, markerDx: 0, markerDy: 0, markerOpacity: 1 }, eventWarnLevel4: { markerType: 'ellipse', markerFill: '#338fff', markerFillOpacity: 1, markerLineColor: '#34495e', markerLineWidth: 2, markerLineOpacity: 1, markerLineDasharray: [], markerWidth: 12, markerHeight: 12, markerDx: 0, markerDy: 0, markerOpacity: 1 } }, pictureMarkerSymbols: { } } })()
/** * Copyright 2016 Google 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. */ goog.provide('audioCat.state.effect.ReverbEffect'); goog.require('audioCat.audio.Constant'); goog.require('audioCat.state.effect.Effect'); goog.require('audioCat.state.effect.field.BooleanField'); goog.require('audioCat.state.effect.field.GradientField'); goog.require('audioCat.utility.Unit'); /** * An effect that introduces reverb. * @param {!audioCat.state.effect.EffectModel} model The model of the effect * that describes details about the model such as name and description. * @param {!audioCat.utility.IdGenerator} idGenerator Generates IDs unique * throughout the application. * @param {number=} opt_duration How long each reverberation lasts. Optional. * @param {number=} opt_decay How long the collective reverb lasts. Optional. * @param {boolean=} opt_reversed Whether the reverb is initially reversed. * Optional. Defaults to false. * @constructor * @extends {audioCat.state.effect.Effect} */ audioCat.state.effect.ReverbEffect = function( model, idGenerator, opt_duration, opt_decay, opt_reversed) { goog.base(this, model, idGenerator); /** * The field that controls the duration of the reverb. * @private {!audioCat.state.effect.field.GradientField} */ this.durationField_ = new audioCat.state.effect.field.GradientField( 'duration', // The name of the field. 'How long each reverberation lasts.', // Description. audioCat.utility.Unit.MS, audioCat.audio.Constant.REVERB_DURATION_MIN, audioCat.audio.Constant.REVERB_DURATION_MAX, 0, // Decimal places to round values to for display. audioCat.audio.Constant.REVERB_DURATION_DEFAULT, // Default value. opt_duration // Initial value. ); /** * The field that controls how quickly the reverb decays. * @private {!audioCat.state.effect.field.GradientField} */ this.decayField_ = new audioCat.state.effect.field.GradientField( 'decay', // The name of the field. 'How steeply the reverb decays.', // Description. audioCat.utility.Unit.MS, audioCat.audio.Constant.REVERB_DECAY_MIN, audioCat.audio.Constant.REVERB_DECAY_MAX, 0, // Decimal places to round values to for display. audioCat.audio.Constant.REVERB_DECAY_DEFAULT, // Default value. opt_decay // Initial value. ); /** * The field that controls whether the effect is reversed. * @private {!audioCat.state.effect.field.BooleanField} */ this.reversedField_ = new audioCat.state.effect.field.BooleanField( 'reversed', 'reverse the reverb', opt_reversed); }; goog.inherits(audioCat.state.effect.ReverbEffect, audioCat.state.effect.Effect); /** * @return {!audioCat.state.effect.field.GradientField} The field controlling * the duration of each reverberation. */ audioCat.state.effect.ReverbEffect.prototype.getDurationField = function() { return this.durationField_; }; /** * @return {!audioCat.state.effect.field.GradientField} The field controlling * how quickly a collective reverb decays. */ audioCat.state.effect.ReverbEffect.prototype.getDecayField = function() { return this.decayField_; }; /** * @return {!audioCat.state.effect.field.BooleanField} The field controlling * whether the reverb is reversed. */ audioCat.state.effect.ReverbEffect.prototype.getReversedField = function() { return this.reversedField_; }; /** @override */ audioCat.state.effect.ReverbEffect.prototype.retrieveDisplayables = function() { return [this.durationField_, this.decayField_, this.reversedField_]; };
const Service = require("./service/service"); const argv = require('yargs').argv // example exacute command // node src/server.js --country=PE --campaign=202004,202005 option => --personalization=sr,opm,odd // this discomment for debbuger // argv = { // country: "PE", // campaign: "202004", // personalization: "sr" // } if (!argv.country || !argv.campaign) { console.log("Check if the country, personalization and campaign parameters exist"); } else { if (!argv.personalization) argv.personalization = "ODD,SR,OPM,OPT,LAN,LMG,HV,CAT,LIQ,REV"; const service = new Service(); argv.country = argv.country.toUpperCase(); argv.personalization = argv.personalization.toUpperCase(); const params = { country: argv.country, campaign: argv.campaign.toString().split(","), personalization: argv.personalization.split(",") }; (async () => { await service.execTask(params); })(); }
import Swiper from 'swiper'; const sizeW = window.innerWidth; export const parameters = { direction: 'vertical', height: sizeW < 960 ? 200 : 300, watchSlidesVisibility: true, centeredSlides: true, shortSwipes: false, longSwipes: false, touchRatio: 0.9, keyboard: { enabled: true, onlyInViewport: false, }, } const mySwiper = new Swiper('.swiper-container', parameters); export default mySwiper;
function testerCollisions(coordonneesBalle, coordonneesJoueur) { var constantes = { rayonBalle :32, rayonJoueur : 25 } if(coordonneesBalle!=null && coordonneesJoueur!=null) { if(!coordonneesJoueur.explose) { if(Math.abs(coordonneesJoueur.horizontal-coordonneesBalle.x) <= (constantes.rayonBalle+constantes.rayonJoueur) && Math.abs(coordonneesJoueur.vertical-coordonneesBalle.y) <= (constantes.rayonBalle+constantes.rayonJoueur)) { window.dispatchEvent(window.Evenement.mortJoueur); } } else if(!coordonneesBalle.immunisee) { if(pythagore(coordonneesJoueur.horizontal-coordonneesBalle.x,coordonneesJoueur.vertical-coordonneesBalle.y)<=(constantes.rayonBalle+2*constantes.rayonJoueur)) { window.dispatchEvent(window.Evenement.explosionAvecJoueur); } } } }
#!/usr/bin/env node /** * Developer: BelirafoN * Date: 12.04.2016 * Time: 15:44 */ "use strict"; let argv = require('yargs').argv; const AmiSurrogateServer = require('../lib/AmiTestServer'); const meta = require('../package.json'); const defaultOptions = { port: 5038, authTimeout: 30000, defaultOptions: 50, credentials: { username: 'test', secret: 'test' } }; if (argv.help) { console.log(`-`.repeat(36)); console.log(`| asterisk ami test server `.toUpperCase() + `v${meta.version} |`); console.log(`-`.repeat(36)); console.log(); console.log(`* --port - listening port, default ${defaultOptions.port}`); console.log(`* --username - username for auth on server, default '${defaultOptions.credentials.username}'`); console.log(`* --secret - secret for auth on server, default '${defaultOptions.credentials.secret}'`); console.log(`* --auth-timeout - authorization timeout, default ${defaultOptions.authTimeout} ms`); console.log(`* --max-clients - max count of client connections, default ${defaultOptions.maxConnections}`); return; } let options = Object.keys(defaultOptions).reduce((result, key) => { result[key] = argv[key] ? argv[key] : defaultOptions[key]; return result; }, {}); new AmiSurrogateServer(options) .on('listening', () => console.log('listening')) // .on('connection', authClientsCount => console.log(`authClientsCount: ${authClientsCount}`)) .listen(options.port) .catch(error => console.log(error));
/* begin copyright text * * Copyright © 2016 PTC Inc., Its Subsidiary Companies, and /or its Partners. All Rights Reserved. * * end copyright text */ /*global module*/ /* jshint node: true */ /* jshint strict: global */ /* jshint camelcase: false */ 'use strict'; var acl = require('../../acl.js'); var utils = require('../../utils.js'); var debug = require('debug')('vxs:cds.options'); module.exports = function options(req, res) { var user = req.user; debug("In routes/cds/options.js, user=" + user + " baseUrl= " + req.baseUrl + " path=" + req.path); var url = req.baseUrl + req.path; //this is hardcoded when defining each route (see index.js). //If that definition changes, the code below will also need to change var numPathComponentsForAcl = 3; var resource = url.split('/').slice(0,numPathComponentsForAcl+1).join('/'); debug("Checking permissions for resource " + resource); acl.getAllowedMethodsPromise(user, resource) .then (function(result) { var allowsHeader = ''; //intersect supported methods for the route with methods allowed by acl var supported = req.params.archive? ['delete', 'get', 'post', 'put', 'options'] :['get', 'post', 'put', 'options']; if(result && result.indexOf("*") >= 0) { allowsHeader = supported.toString().toUpperCase(); } else if(result && result.length >0) { var allowedAndSupported = utils.intersectArrays(result, supported); allowsHeader = allowedAndSupported.toString().toUpperCase(); } res.status(200); res.setHeader('Allow', allowsHeader); res.end(); }) .catch(function(err) { console.error(err.stack || err); res.status(500).send("*** " + err); }) .done(); };
import { GET_USER_SUCCESS, GET_USER_FAILURE, GET_USER_REQUEST, } from "./user.types"; import axios from "axios"; import { setAlert } from "../alert/alert.actions"; export const getUser = (id) => async (dispatch) => { try { dispatch({ type: GET_USER_REQUEST }); const res = await axios.get(`/api/users/${id}`); dispatch({ type: GET_USER_SUCCESS, payload: res.data.user, }); } catch (e) { setAlert(e.message, "danger"); dispatch({ type: GET_USER_FAILURE, }); } };
import { GraphQLID, GraphQLString, GraphQLNonNull, GraphQLList } from 'graphql' import userType from '../types/user' import resolve from '../resolvers/editUserOrganizationRole' import { OrganizationInput } from '../types/inputs' import { RoleEnum } from '../types/enums' const editUserOrganizationRole = { name: 'editUserOrganizationRole', type: userType, args: { userId: { type: new GraphQLNonNull(GraphQLID) }, organization: { type: new GraphQLNonNull(OrganizationInput) }, role: { type: RoleEnum } }, resolve } export default editUserOrganizationRole
const mongoose = require('mongoose'); const imagesSchema = new mongoose.Schema({ FrontImage: String, BackImage: String, userID: String }) const img = new mongoose.model('images', imagesSchema) module.exports = img;
export function getLetterMatchCount(guessedWord, secretWord) { const secretLetters = secretWord.split(''); const guessedLetterSet = new Set(guessedWord.split('')); // count how many letters the sets have in common return secretLetters.filter(letter => guessedLetterSet.has(letter)).length; }
const express = require("express"); const app = express(); const { resolve } = require("path"); // Replace if using a different env file or config const stripe = require("stripe")(process.env.STRIPE_SECRET_KEY); app.use(express.static(".")); app.use(express.json()); const calculateOrderAmount = items => { return 1400; }; app.post("/create-payment-intent", async (req, res) => { const { items, currency } = req.body; // Create a PaymentIntent with the order amount and currency const paymentIntent = await stripe.paymentIntents.create({ amount: calculateOrderAmount(items), currency: currency }); // Send publishable key and PaymentIntent details to client res.send({ publishableKey: process.env.STRIPE_PUBLISHABLE_KEY, clientSecret: paymentIntent.client_secret }); }); app.get("/greet", async (req, res) => { res.send("Hello world"); }); app.listen(4242, () => console.log(`Node server listening on port ${4242}!`));
const pkg = require('./package'); const env = process.env.NODE_ENV || 'production'; let config = require(`./config/${env}.env`); const bodyParser = require('body-parser'); module.exports = { mode: 'universal', /* ** Headers of the page */ head: { title: pkg.name, meta: [ { charset: 'utf-8' }, { name: 'viewport', content: 'width=device-width, initial-scale=1' }, { hid: 'description', name: 'description', content: pkg.description }, ], link: [{ rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' }], }, /* ** Customize the progress-bar color */ loading: { color: '#fff' }, /* ** Global CSS */ css: ['~/assets/css/reset.css'], /* ** Plugins to load before mounting the App */ plugins: [ '~/plugins/axios', // 扩展axios请求方法 ], /* ** Nuxt.js modules */ modules: [ '@nuxtjs/axios', [ '@nuxtjs/proxy', { onProxyReq: (proxyReq, req, res) => { // ClientRequest, IncomingMessage, ServerResponse console.log('query---------->', req.query); console.log('body----------->', req.body); }, onProxyRes: (proxyReq, req = {}, res = {}) => { let now = new Date(); console.log( new Date().toString(), '[proxy]', `[${req.method}]`, `URL: ${req.url}`, `CODE: ${res.statusCode}`, `TIME: ${now.getTime() - req.__startTime || 0}ms` ); }, }, ], // 配置选项 [ '@nuxtjs/component-cache', { max: 10000, maxAge: 1000 * 60 * 0.1, // 0.1分钟 }, ], '@nuxtjs/sitemap', ], /* ** Axios module configuration */ axios: { // See https://github.com/nuxt-community/axios-module#options baseURL: config.baseURL, browserBaseURL: '/', // config.feServerBaseUrl }, proxy: { // 替换/api // '/api/': { target: 'https://www.bitdeer.com', pathRewrite: { '^/api/': '' } }, // 拼接/api '/api': config.baseURL, }, serverMiddleware: [ bodyParser.json(), //必须用此中间件,否则proxy拿不到body ], /* ** Build configuration */ build: { /* ** You can extend webpack config here */ publicPath: env === 'production' ? 'http://lizhuang.static.com/static' : '/_nuxt/', filenames: { app: ({ isDev }) => (isDev ? '[name].js' : '[name].[contenthash:8].js'), chunk: ({ isDev }) => (isDev ? '[name].js' : '[name].[contenthash:8].js'), css: ({ isDev }) => (isDev ? '[name].css' : '[name].[contenthash:8].css'), }, extend(config, ctx) { // console.log(config, '!!!!!!!!!!!!!!!!!!!', ctx) // Run ESLint on save if (ctx.isDev && ctx.isClient) { config.module.rules.push({ enforce: 'pre', test: /\.(js|vue)$/, loader: 'eslint-loader', exclude: /(node_modules)/, }); } }, }, sitemap: { hostname: 'https://www.bitdeer.com', gzip: true, exclude: [], }, };
"use strict"; module.exports = function (sequelize, DataTypes) { var Sign = sequelize.define('signup', { userName: DataTypes.STRING, email: DataTypes.STRING, password: DataTypes.STRING, }); return Sign; }; // export default signSchema
#!/usr/bin/env node //I love this library so damn much const cheerio = require('cheerio') //Stolen from banner const data = ` <option value="ACC">Accounting</option> <option value="ASE">Aerospace Engineering</option> <option value="ANT">Anthropology</option> <option value="ARA">Arabic Language _ Literature</option> <option value="ARC">Architecture</option> <option value="ART">Art and Art History</option> <option value="BIO">Biology</option> <option value="BME">Biomedical Engineering</option> <option value="BIS">Business Information Systems</option> <option value="BLW">Business Legal Issues</option> <option value="CHE">Chemical Engineering</option> <option value="CHM">Chemistry</option> <option value="CVE">Civil Engineering</option> <option value="COE">Computer Engineering</option> <option value="CMP">Computer Science</option> <option value="DES">Design</option> <option value="ECO">Economics</option> <option value="ELE">Electrical Engineering</option> <option value="NGN">Engineering</option> <option value="EGM">Engineering Management</option> <option value="ESM">Engineering Systems/Management</option> <option value="ENG">English Language</option> <option value="ELP">English Language Preparation</option> <option value="ELT">English Language Teaching</option> <option value="ENV">Environmental Sciences</option> <option value="EWE">Environmental and Water Eng'g</option> <option value="FLM">Film</option> <option value="FIN">Finance</option> <option value="GEO">Geography</option> <option value="HIS">History</option> <option value="INE">Industrial Engineering</option> <option value="IDE">Interior Design</option> <option value="INS">International Studies</option> <option value="MGT">Management</option> <option value="MIS">Management Information Systems</option> <option value="MKT">Marketing</option> <option value="MCM">Mass Communication</option> <option value="MBA">Master of Business Admin</option> <option value="MTH">Math</option> <option value="MCE">Mechanical Engineering</option> <option value="MTR">Mechatronics</option> <option value="MUM">Multimedia</option> <option value="MUS">Music</option> <option value="PET">Petroleum Engineering</option> <option value="PHI">Philosophy</option> <option value="PHY">Physics</option> <option value="POL">Political Science</option> <option value="MBAP">Pre-MBA</option> <option value="PSY">Psychology</option> <option value="QBA">Quantitative Business Analysis</option> <option value="SOC">Sociology</option> <option value="STA">Statistics</option> <option value="ABRD">Study Abroad Credit(s)</option> <option value="SCM">Supply Chain Management</option> <option value="THE">Theatre</option> <option value="TRA">Translation</option> <option value="UPA">University Preparation</option> <option value="UPL">Urban Planning</option> <option value="VIS">Visual Communication</option> <option value="WST">Women Studies</option> <option value="WRI">Writing Studies</option>` //Load data const $ = cheerio.load(data) //Init json result var json = {} //Loop through every <option> tag $('option').each(function(i, item){ //Grab the values we need const key = $(item).text().toLowerCase() const val = $(item).attr('value') //Append them to the json result json[key] = val; }) //Output JSON result console.log(JSON.stringify(json)) //Boom. The power of Javascript.
module.exports = function ArboreanApparel(mod) { mod.warn("Arborean Apparel is out of commission - install Unicast instead"); mod.command.add("aa", () => { mod.command.message("Arborean Apparel is out of commission - install Unicast instead"); }) };
/*--------------------------------------------------------------------------------------------------- * jQuery Comet Plugin * Copyright (c) 2009 Dunghoangit (Hoang Viet Dung) * * Develop by dunghoangit * dunghoang.it@gmail.com * Please attribute the author if you use it. * * Updated on 1:21 AM 6/25/2010 *---------------------------------------------------------------------------------------------------*/ var isCometStated = false; var isCometEnabled = true; (function($) { $.fn .extend({ comet: function(options) { var defaults = { params: {} }; var options = $.extend(defaults, options); var connect = function() { $.post('chat/pub',options.params, function(data) { if(data){ if(data.message){ $('#last_update').text(data.date); $.each(data.message,function(k,v){ $('#chat_data').prepend('<div>'+v.date+' <b>'+v.User+'</b>: '+v.message+'</div>'); }); $('#members').html(''); $.each(data.members,function(k,v){ $('#members').prepend('<div><b>'+v+'</b></div>'); }); } options.params.timestamp = data.timestamp; connect(); } }, "json"); }; $(this).ajaxError( function(event, request, settings) { alert('error in: ' + settings.url + ' \n'+'error:\n' + xhr.responseText ); } ); return this.each(function() { if (isCometEnabled) { setTimeout(connect,1000); } isCometStated = true; }); } }); })(jQuery);
jQuery.extend(jQuery.validator.messages, { required:"此项必填。", remote:"改名称已经存在,请更改其他名称", email:"请输入一个合法的电子邮件地址。", url:"请输入合法网址。", date:"请输入合法日期。", dateISO:"请输入合法日期(ISO格式)。", number:"请输入合法数字。", digits:"请只输入数字。", creditcard:"请输入一个有效的信用卡号。", equalTo:"请再次输入相同的值。", maxlength:jQuery.validator.format("请输入不超过{0}个字符。"), minlength:jQuery.validator.format("请输入至少{0}个字符。"), rangelength:jQuery.validator.format("请输入介于{0}和{1}个长的字符值。"), range:jQuery.validator.format("请输入介于{0}和{1}的值。"), max:jQuery.validator.format("请输入一个小于或等于{0}的值。"), min:jQuery.validator.format("请输入一个大于或等于{0}的值。") }); var CompanyForm = function () { return { init: function () { var wizform = $('#companyForm'); /*-----------------------------------------------------------------------------------*/ /* Validate the form elements /*-----------------------------------------------------------------------------------*/ wizform.validate({ doNotHideMessage: true, errorClass: 'error-span', errorElement: 'span', rules: { companyName: { required: true, minlength: 4, maxlength: 64, remote:{ type:"GET", url: $clientURL+"verifyCompanyName", data:{ id:function(){return $("#companyId").val();} } } }, address: { required: true }, 'usersByCreator.mobile':{ required: true } }, invalidHandler: function (event, validator) { // alert_success.hide(); // alert_error.show(); }, highlight: function (element) { $(element) .closest('.form-group').removeClass('has-success').addClass('has-error'); }, unhighlight: function (element) { $(element) .closest('.form-group').removeClass('has-error'); }, success: function (label) { if (label.attr("for") == "gender") { label.closest('.form-group').removeClass('has-error').addClass('has-success'); label.remove(); } else { label.addClass('valid') .closest('.form-group').removeClass('has-error').addClass('has-success'); } } }); } }; }();
function inicio(){ var guardar = $("#guardar"); codigoPostal(); guardar.click(function(){ $("#form").submit(); }); } function codigoPostal(){ $("#form").form({ inline:true, fields:{ codigoPostal:{ identifier:"codigoPostal", rules:[{ type:"empty", prompt:"El campo es requerido" },{ type:"maxLength[5]", prompt:"El codigo postal no puede contener mas de 5 caracteres" },{ type:"minLength[5]", prompt:"El codigo postal debe contener mas de 5 caracteres" }] } }, onSuccess: function(event,fields){ event.preventDefault(); console.log(fields.codigoPostal); ajax(fields.codigoPostal); } }).submit(function(e){ e.preventDefault(); }); } function estado(resultado){ $("#estado").val(resultado); } function municipio(resultado){ $("#municipio").val(resultado); } function ajax(codigoPostal){ $.ajax({ url:"http://requenadev.swi.mx/some/api/listado-cp/"+codigoPostal, dataType:"json", type:"GET", data:{}, beforeSend:function(){ $("#modal").modal("show"); $("#municipio").val(""); $("#estado").val(""); $("#dropdown").html(""); } }) .done(function(respuesta){ colonias(respuesta.colonias); estado(respuesta.estado); municipio(respuesta.municipio); alerta(true,"listo, ahora se por donde vives :)"); }) .fail(function(e){ alerta(false,"No se pudo conectar"); }) .always(function(){ $("#modal").modal("hide"); }); } function colonias(respuesta){ for(var i in respuesta){ var texto="<option value="+respuesta[i]+">"+respuesta[i]+"</option>" $("#dropdown").append(texto); } } window.onload=inicio;
/* eslint-disable react/jsx-one-expression-per-line */ import React from 'react' import { makeIntArray } from '_story' import TableResponsive from '.' const makeRow = i => ({ id: `${i.repeat(8)}-${i.repeat(4)}-${i.repeat(4)}-${i.repeat(4)}-${i.repeat( 12 )}`, first_name: 'Example', last_name: 'User', email: `user-${i}@example.com`, phone: `${i.repeat(3)}-${i.repeat(3)}-${i.repeat(4)}`, created_at: `2020-${i.padStart(2, '0')}-01`, updated_at: null, deleted_at: null, }) const tableData = makeIntArray(9).map(i => makeRow(`${i}`)) const Demo = () => ( <> <h1>TableResponsive</h1> <p> The <em>TableResponsive</em> component applies theming to the HTML{' '} <code>table</code> tab and its children, <code>thead</code>,{' '} <code>tbody</code>, <code>tr</code>, <code>td</code>, and <code>td</code>. </p> <p> The <em>Table</em> component works using standard HTML children and does not require any other Horns components to create fully themed tables. </p> <h2>Rows from Prop</h2> <p> Unlike the <em>Table</em> component, the <em>TableResponsive</em> does not accept children and must generate the table content using the{' '} <em>rowData</em> prop. This is because the component needs to map over the </p> <TableResponsive rowData={tableData} minWidth="1200px" /> </> ) Demo.story = { name: 'TableResponsive', } export default Demo
//set env variable to test to access the test database process.env.NODE_ENV = 'test'; const db = require('../../server/models'); //Require the dev-dependencies let chai = require('chai'); let chaiHttp = require('chai-http'); let app = require('../../app'); let should = chai.should(); chai.use(chaiHttp); describe('User', () => { before(function(done) { this.timeout(10000); db.sequelize.sync({ force: true, logging: false }).then(() => { done(); }); }); describe('/POST user', () => { it('it should POST user details to database', (done) => { let user = { username: 'John Doe', email: 'pheonixera@gmail.com', password: 'synix123', confirmPassword: 'synix123', createdAt: new Date(), updatedAt: new Date() }; chai.request(app) .post('/api/v1/users/register') .send(user) .end((err, res) => { // there should be a 201 status code // (indicating that something was "created") res.should.have.status(200); res.body.should.be.a('object'); // there should be no errors should.not.exist(err); // the response should be JSON res.type.should.equal('application/json'); // all attributs of user should be generated res.body.should.have.all.keys('user', 'message'); res.body['message'].should.equal('Authentication successful'); done(); }); }).timeout(5000); it('it should get all registered user', (done) => { chai.request(app) .get('/api/v1/users') .end((err, res) => { res.type.should.equal('application/json'); res.should.have.status(200); should.not.exist(err); res.body['allUsers'].should.be.a('array'); // Only one user have been registered on database res.body['allUsers'].length.should.be.eql(1); done(); }); }).timeout(5000); it('it should get a single registered user', (done) => { let userId = 1; chai.request(app) .get('/api/v1/users/' + userId) .end((err, res) => { res.type.should.equal('application/json'); res.should.have.status(200); should.not.exist(err); res.body['user'].should.be.a('object'); res.body['user'].should.have.all.keys( 'id', 'userId', 'username', 'email', 'admin', 'memValue', 'createdAt', 'updatedAt'); done(); }); }).timeout(5000); // Each username should be unique it('it should not post user credentials to database where username exist on the database', (done) => { let user = { username: 'John Doe', email: 'pheonixera@gmail.com', password: 'synix123', confirmPassword: 'synix123', createdAt: new Date(), updatedAt: new Date() }; chai.request(app) .post('/api/v1/users/register') .send(user) .end((err, res) => { // there should be a 406 status code // (indicating that nothing was "created") res.should.have.status(409); res.type.should.equal('application/json'); res.body['message'].should.equal('username already exist'); done(); }); }).timeout(5000); // User email should be unique it('it should not post user credentials to database where email exist on the database', (done) => { let user = { username: 'John Daniel', email: 'pheonixera@gmail.com', password: 'synix123', confirmPassword: 'synix123', createdAt: new Date(), updatedAt: new Date() }; chai.request(app) .post('/api/v1/users/register') .send(user) .end((err, res) => { res.should.have.status(409); // response should be a text bearing the error message res.type.should.equal('application/json'); res.body['message'].should.equal('This email is registered'); done(); }); }).timeout(5000); it('it should not post user credentials to database where any field is empty', (done) => { let user = { username: '', email: 'linux@gmail.com', password: 'synix123', confirmPassword: 'synix123', createdAt: new Date(), updatedAt: new Date() }; chai.request(app) .post('/api/v1/users/register') .send(user) .end((err, res) => { res.should.have.status(400); res.body['message'].should.equal('Some fields are empty'); done(); }); }).timeout(5000); }); // Integraton test for user sign in describe('/POST /users/signin', () => { it('it should generate and send token', (done) => { let user = { username: 'John Doe', password: 'synix123' }; chai.request(app) .post('/api/v1/users/signin') .send(user) .end((err, res) => { res.should.have.status(200); res.body.should.have.all.keys('message', 'user'); res.body['message'].should.equal('Authentication successful'); should.not.exist(err); // the response should be JSON res.type.should.equal('application/json'); done(); }); }).timeout(5000); }); });