text
stringlengths
7
3.69M
;(function(){ //顶部下拉 $(".zg_top_nav li.live").each(function(x){ $(this).mouseenter(function(){ $(".zg_top_nav li.live").removeClass("zg_nav_h"); $(this).addClass("zg_nav_h"); $(".zg_yy_box").hide(); $(".zg_yy_box:eq("+x+")").show(); }); }); $(".zg_topLt").mouseleave(function(){ $(".zg_top_nav li.live").removeClass("zg_nav_h"); $(".zg_yy_box").hide(); }); $(".zg_topRt .icond").each(function(index) { $(this).hover(function(){ $(this).addClass("on"); $(this).find(".dropbox").show(); },function(){ $(this).removeClass("on"); $(this).find(".dropbox").hide(); }); }); //顶部微信二维码切换 $(".zg_qhewm a").mouseover(function(){ $(this).addClass("on").siblings().removeClass("on"); $(".zg_ewmbox").hide(); $(".zg_ewmbox").eq($(this).index()).show(); }) //全国分站 $(".quan").hover(function(){ $(this).addClass("quans"); $(".quan_fen").show(); }); $(".quan_fen").hover(function(){},function(){ $(".quan").removeClass("quans"); $(".quan_fen").hide(); }); $(".youce").hover(function(){},function(){ $(".quan").removeClass("quans"); $(".quan_fen").hide(); }); //导航 $('.kj_navm ul .xla').each(function(){ $(this).hover(function(){ $(this).addClass('on'); $(this).find('.kj_dhxl').show(); },function(){ $(this).removeClass('on'); $(this).find('.kj_dhxl').hide(); }); }); //cfa首页第一部分右侧距离考试时间 function lxfEndtime(){ $(".days").each(function(){ var endtime = new Date($(this).attr("endtime")).getTime();//取结束日期(毫秒值) var nowtime = new Date().getTime(); //今天的日期(毫秒值) var youtime = endtime-nowtime;//还有多久(毫秒值) var seconds = youtime/1000; var minutes = Math.floor(seconds/60); var hours = Math.floor(minutes/60); var days = Math.floor(hours/24); var CDay= days ; var CHour= hours % 24; var CMinute= minutes % 60; var CSecond= Math.floor(seconds%60);//"%"是取余运算,可以理解为60进一后取余数,然后只要余数。 if(endtime<=nowtime){ $(".times").html("<span>0</span>")//如果结束日期小于当前日期就提示过期啦 }else{ var dayArr=days.toString().split(""); var dayStr=""; for (var i = 0; i < dayArr.length; i++) { dayStr+="<span>"+dayArr[i]+"</span>"; } $(".times").html(dayStr); //输出有天数的数据 } }); } setTimeout("lxfEndtime()",3600000); lxfEndtime(); // 首页第二部分切换 $(".kc_type a").mouseover(function(){ $(this).addClass("active").siblings().removeClass("active"); $(".kc_list").hide(); $(".kc_list").eq($(this).index()).show(); }) // 首页第三部分报考流程切换 $(".lc_type a").mouseover(function(){ $(this).addClass("active").siblings().removeClass("active"); $(this).parents(".lc_head").parent().find(".lc_change").hide(); $(this).parents(".lc_head").parent().find(".lc_change").eq($(this).index()).show(); }) // 首页第四部分老师切换 $(".uscpa_team_list li").mouseover(function(){ $(".teacher_intro").hide(); $(".teacher_intro").eq($(this).index()).show(); }) //设置foot下的当前时间 var nowtime=new Date(); var nowyear=nowtime.getFullYear(); $(".nowtime").html(nowyear); //分页 $(".select_txt,.selet_open").hover(function(event){ $(".option").hide(); $(this).siblings(".option").show(); $(".select_box").removeClass("uiChooseActiveS"); $(this).parent(".select_box").addClass("uiChooseActiveS"); }); $(document).click(function(event){ var eo=$(event.target); if($(".select_box").is(":visible") && eo.attr("class")!="option" && !eo.parent(".option").length) $('.option').hide(); $(".select_box").removeClass("uiChooseActiveS"); }); $(".option a").click(function(){ var value=$(this).text(); $(this).parent().siblings(".select_txt").text(value); $(".select_value").val(value); $(".option").hide(); $(".select_box").removeClass("uiChooseActiveS"); }) $(".option").each(function(d) { var optionSize=6; var optionLiHeight=$(".option a").height(); var optionVarS=$(this).find("a").length; if(optionVarS>optionSize){ var optionSheight=128; $(this).height(optionSheight); }else{ var optionLiTal=optionVarS*optionLiHeight; $(this).height(optionLiTal); }; }); $(".option,.uiChooseTable,.mod_select ").mouseleave(function(){ $(".select_box").removeClass("uiChooseActiveS"); $(".option").hide(); }); })(); //内容页字体大小改变 $(function(){ var cont=14; var sum=0; $('.font_big').click(function(){ if(cont >= 20){ return false; } else{ cont++; sum+=2; $('.zg_content').css({'font-size':cont,'line-height':32+sum+"px"}); $('.zg_content p').css({'font-size':cont,'line-height':32+sum+"px"}); } }); $('.font_small').click(function(){ if(cont <= 12){ return false; } else{ cont--; sum-=2; $('.zg_content').css({'font-size':cont,'line-height':32+sum+"px"}); $('.zg_content p').css({'font-size':cont,'line-height':32+sum+"px"}); } }); });
angular.module('angularSpace', ['ngSanitize', 'tiddlerModule']).config(['$routeProvider', function ($routeProvider) { $routeProvider .when('/', { templateUrl: 'home.html', controller: 'MainController' }) .when('/tiddler/:bag/:title', { templateUrl: 'tiddler.html', controller: 'TiddlerController' }) }]);
var args = arguments[0] || {}; if(args.autoSearch){ $.boxSearchView.remove($.btnBuscar); $.linhaBaixo.setRight(10); $.input.setRight(10); } $.input.setReturnKeyType(Ti.UI.RETURNKEY_SEARCH); $.input.addEventListener("return", function(e){ buscar(); }); function buscar(e){ $.trigger('busca', { source: $, value: $.input.getValue() }); $.input.blur(); } $.getValue = function(){ return $.input.getValue(); }; $.tirarFoco = function(){ $.input.blur(); }; function alterando(e){ $.trigger('change', { source: e.source, value: e.value }); }
const StarToken = artifacts.require("StarToken"); module.exports = function (deployer) { deployer.deploy(StarToken, "Star", "STR"); };
import React from 'react' const SidebarLink = ({page, links}) => { return ( <article> <h4>{page}</h4> <div className="sidebar-sublinks"> {/*aca irian unos Links con router */} {links.map( subl => { return ( <a href={subl.url}> {subl.icon} {subl.label} </a> ) })} </div> </article> ) } export default SidebarLink
/** * Created by mehmetyurtar on 11/9/19. */ import IngredientList from "./IngredientList"; export default IngredientList;
import React from 'react'; import { useLocation } from 'react-router'; const Recipe = (props) => { const location = useLocation(); console.log(location); return ( <div> <div className='jumbotron container my-5 text-center'> <img src={location.state.recipe.image}></img><br></br> <h1 className='my-4 font-weight-light'>{location.state.recipe.label}</h1> <br></br> <h2 className='my-4 font-weight-light'>Calories</h2> <p className='col-sm-6 mx-auto'> <li className='text-left'>{location.state.recipe.calories}</li> </p> <br></br> <h2 className='my-4 font-weight-light'>Ingredients</h2> <p className='col-sm-6 mx-auto'>{location.state.recipe.ingredients.map((ingredient,index) => <li key={index} className='text-left'>{ingredient.text}</li>)}</p> </div> </div> ) } export default Recipe
define([ './line-set', './stack' ], function (LineSet, Stack) { return LineSet.extend({ GroupClass: Stack, getClosestLine: function (e, index) { var closestY = { valueAttr: null }; if (this.hasValueAtIndex(index)) { var interpolator = this.getInterpolator(e, index); _.each(this.lines, function (line) { if (interpolator(line) < e.y) { closestY = line; } }); } return closestY; } }); });
define("elements/wb-duration.js", ["../../components/w69b-es6/timeutil.js"], function(e) { "use strict"; function n(e) { return e && e.__esModule ? e : { default: e } } function t(e, n) { if (!(e instanceof n)) throw new TypeError("Cannot call a class as a function") } var r = n(e), i = function() { function e(e, n) { for (var t = 0; t < n.length; t++) { var r = n[t]; r.enumerable = r.enumerable || !1, r.configurable = !0, "value" in r && (r.writable = !0), Object.defineProperty(e, r.key, r) } } return function(n, t, r) { return t && e(n.prototype, t), r && e(n, r), n } }(), o = function() { function e() { t(this, e) } return i(e, [{ key: "beforeRegister", value: function() { this.is = "wb-duration", this.properties = { time: { type: Number } } } }, { key: "_toDuration", value: function(e) { return r.default.formatDuration(e) } }]), e }(); Polymer(o) }); ! function() { "use strict"; Polymer.IronJsonpLibraryBehavior = { properties: { libraryLoaded: { type: Boolean, value: !1, notify: !0, readOnly: !0 }, libraryErrorMessage: { type: String, value: null, notify: !0, readOnly: !0 } }, observers: ["_libraryUrlChanged(libraryUrl)"], _libraryUrlChanged: function(r) { this._isReady && this.libraryUrl && this._loadLibrary() }, _libraryLoadCallback: function(r, i) { r ? (Polymer.Base._warn("Library load failed:", r.message), this._setLibraryErrorMessage(r.message)) : (this._setLibraryErrorMessage(null), this._setLibraryLoaded(!0), this.notifyEvent && this.fire(this.notifyEvent, i)) }, _loadLibrary: function() { r.require(this.libraryUrl, this._libraryLoadCallback.bind(this), this.callbackName) }, ready: function() { this._isReady = !0, this.libraryUrl && this._loadLibrary() } }; var r = { apiMap: {}, require: function(r, t, e) { var a = this.nameFromUrl(r); this.apiMap[a] || (this.apiMap[a] = new i(a, r, e)), this.apiMap[a].requestNotify(t) }, nameFromUrl: function(r) { return r.replace(/[\:\/\%\?\&\.\=\-\,]/g, "_") + "_api" } }, i = function(r, i, t) { if (this.notifiers = [], !t) { if (!(i.indexOf(this.callbackMacro) >= 0)) return void(this.error = new Error("IronJsonpLibraryBehavior a %%callback%% parameter is required in libraryUrl")); t = r + "_loaded", i = i.replace(this.callbackMacro, t) } this.callbackName = t, window[this.callbackName] = this.success.bind(this), this.addScript(i) }; i.prototype = { callbackMacro: "%%callback%%", loaded: !1, addScript: function(r) { /* var i = document.createElement("script"); i.src = r, i.onerror = this.handleError.bind(this); var t = document.querySelector("script") || document.body; t.parentNode.insertBefore(i, t), this.script = i */ }, removeScript: function() { this.script.parentNode && this.script.parentNode.removeChild(this.script), this.script = null }, handleError: function(r) { this.error = new Error("Library failed to load"), this.notifyAll(), this.cleanup() }, success: function() { this.loaded = !0, this.result = Array.prototype.slice.call(arguments), this.notifyAll(), this.cleanup() }, cleanup: function() { delete window[this.callbackName] }, notifyAll: function() { this.notifiers.forEach(function(r) { r(this.error, this.result) }.bind(this)), this.notifiers = [] }, requestNotify: function(r) { this.loaded || this.error ? r(this.error, this.result) : this.notifiers.push(r) } } }(); Polymer({ is: "iron-jsonp-library", behaviors: [Polymer.IronJsonpLibraryBehavior], properties: { libraryUrl: String, callbackName: String, notifyEvent: String } }); Polymer({ is: "google-youtube-api", behaviors: [Polymer.IronJsonpLibraryBehavior], properties: { libraryUrl: { type: String, value: "https://www.youtube.com/iframe_api" }, notifyEvent: { type: String, value: "api-load" }, callbackName: { type: String, value: "onYouTubeIframeAPIReady" } }, get api() { return YT } });
/** * Get a subset array using offset and limit * * @param {number} offset Start position * @param {number} limit How many items * @param {Array} source Input array * * @returns {Array} * * @example * page({ * offset: 1, * limit: 5 * })([1, 2, 3, 4, 5, 6, 7, 8]) * // => [2, 3, 4, 5, 6] */ const page = ({ offset = 0, limit = 10 } = {}) => source => [ ...source.splice(offset, limit), ] export { page }
import $ from 'jquery'; import _ from 'lodash' import Backbone from 'backbone'; import sharedBusModel from './sharedBusModel' // private var wrapWithSuper = function(method, parentPrototype, parentMethodName) { var wrapper = function() { var backup = this._super, ret, descriptor; if (backup && backup.__backup__) { descriptor = backup.__descriptor__; backup = backup.__backup__; } this._super = parentPrototype[parentMethodName]; ret = method.apply(this, arguments); this._super = backup; return ret; }; wrapper.__superWrapper__ = true; _.extend(wrapper, method); wrapper.prototype = method.prototype; return wrapper; }; var canDecompile = /sometext/.test(function() { var sometext; }); var isUsingSuper = canDecompile ? /\b_super\b/ : /.*/; var getWrapperSourceCode = function(func) { return canDecompile ? func(function() {}).toString() : '$'; }; var backboneExtend = Backbone.View.extend; var attachOptions = function(instance, options) { options = options || {}; if (instance.options) { options = _.extend({}, instance.options, options); } var optionsToAttach = _.pick(options, instance.constructor._optionsToAttach); _.each(optionsToAttach, function(value, key) { instance._resultProps && instance._resultProps[key] && (instance._resultProps[key] = false); }); _.extend(instance, optionsToAttach); instance.options = options; }; var wrapConstructor = function(constructor) { return function() { var args = arguments; if (!this.__inWrapper__) { this.__inWrapper__ = true; this._resultProps = _.clone(this._resultProps); if (this._attachOptions) { this._attachOptions.apply(this, args); } else if (this._attachOptions !== false) { attachOptions(this, (this._getOptionsFromArgs && (this._getOptionsFromArgs.apply(this, args) || {})) || args[0]); } _.each(this._resultProps, function(toResult, propName) { if (toResult && propName in this) { var origProp = this[propName]; _.isFunction(origProp) && (this[propName] = origProp.apply(this, args)); if (origProp && origProp.__mergeFrom__) { mergeTree(origProp, propName, this, args); delete this[propName].__mergeFrom__; } } }, this); delete this._resultProps; } constructor.apply(this, args); delete this.__inWrapper__; }; }; var mergeTree = function(currProtoProp, propName, target, args) { var parentProto = currProtoProp.__mergeFrom__; var parentProp = parentProto[propName]; _.isFunction(parentProp) && (parentProp = parentProp.apply(target, args)); mergePropToObj(target, parentProp, propName); if (parentProto[propName].__mergeFrom__) { mergeTree(parentProto[propName], propName, target, args); } }; var mergePropToObj = function(obj, prop, propName) { var objPropType = $.type(obj[propName]); if (objPropType != $.type(prop)) return; switch (objPropType) { case 'array': obj[propName] = _.union(prop, obj[propName]); break; case 'string': obj[propName] += " " + prop; break; case 'object': obj[propName] = _.extend({}, prop, obj[propName]); break; } }; // public var waitForAll = function() { var promises = _.toArray(arguments), masterDeferred = $.Deferred(), deferreds = [], progressDeferreds = []; _.each(promises, function(promise) { var deferred = $.Deferred(); var progressDeferred = $.Deferred(); if (promise && promise.then) { promise.fail(function() { deferreds.__hasRejected__ = true; }).always(function() { progressDeferred.resolve.apply(this, arguments); deferred.resolve.apply(this, arguments); }).progress(function() { progressDeferreds.__hasProgress__ = true; progressDeferred.resolve.apply(this, arguments); }); } else { deferred.resolve(promise); progressDeferred.resolve(promise); } deferreds.push(deferred); progressDeferreds.push(progressDeferred); }); /* when at least one of the promises has "progressed", while all the others are resolved/rejected - the returned master promise is getting "progress". */ $.when.apply($, progressDeferreds).done(function() { progressDeferreds.__hasProgress__ && masterDeferred.notify.apply(masterDeferred, arguments); }); /* when all the promises are in final state (resolved/rejected) - if even one of the promises is rejected, the returned master promise is rejected. otherwise, it's resolved. */ $.when.apply($, deferreds).done(function() { masterDeferred[deferreds.__hasRejected__ ? 'reject' : 'resolve'].apply(masterDeferred, arguments); }); return masterDeferred.promise(); }; var extractValues = function(obj, options) { options = options || {}; var omit = options.omit; var getValues = function(obj) { if (omit) { obj = _.omit(obj, omit); } var values = _.values(obj); values = _.map(values, function(value) { return ($.isPlainObject(value) || $.isArray(value)) ? getValues(value) : value; }); return values; }; var ret = _.flatten(getValues(obj)); options.compact && (ret = _.compact(ret)); options.unique && (ret = _.uniq(ret)); return ret; }; var extend = function(protoProps, classProps) { protoProps = _.clone(protoProps || {}); classProps = _.clone(classProps || {}); _.each(protoProps, function(method, name) { if (// can be wrapped with _super() _.isFunction(method) && this.prototype[name] && // wrap only when _super() is used and method is not already wrapped isUsingSuper.test(method) && method != getWrapperSourceCode(wrapWithSuper) ) { protoProps[name] = wrapWithSuper(method, this.prototype, name); } }, this); // merge class array params _.each(['_mergeProps', '_optionsToAttach'], function(param) { if (classProps[param] || this[param]) { classProps[param] = _.union(classProps[param] || [], this[param] || []); } }, this); // merge properties _.each(_.union(protoProps._mergeProps || [], classProps._mergeProps || [], ['_resultProps']), function(propName) { var childProp = protoProps[propName], parentProp = this.prototype[propName]; if (childProp && parentProp) { if (typeof childProp == typeof parentProp && !_.isFunction(childProp)) { mergePropToObj(protoProps, parentProp, propName); } else if (_.isFunction(childProp) || _.isFunction(parentProp)) { childProp.__mergeFrom__ = this.prototype; } } }, this); var attachOptionsEnabled = protoProps._attachOptions === false ? false : (!!protoProps._attachOptions || this.prototype._attachOptions !== false); if (attachOptionsEnabled || !_.isEmpty(protoProps._resultProps) || !_.isEmpty(this.prototype._resultProps)) { var childConstructor = (_.has(protoProps, 'constructor') && protoProps.constructor) || this; if (childConstructor != getWrapperSourceCode(wrapConstructor)) { protoProps.constructor = wrapConstructor(childConstructor); } } var child = backboneExtend.call(this, protoProps, classProps); child._super = this; child.__classId__ = _.uniqueId('class'); return child; }; var testEmail = function (str) { var reg = /^[A-Z0-9._%+\-]+@[A-Z0-9.\-]+\.[A-Z]{2,4}$/i; return reg.test(str); // see http://www.regular-expressions.info/email.html }; var applyRBA = function(settings) { if (!settings) return; var userRoles = settings.userRoles || []; var superRoles = settings.superRoles || []; var userData = settings.userData; var $rootElem = settings.rootElem; if (!$rootElem) return; // if the user has a super role, we don't need to hide anything if (_.intersection(userRoles, superRoles).length) return; !($rootElem instanceof $) && ($rootElem = $($rootElem)); var predicateDict = settings.predicateDict; var data = settings.data; var rbaRolesAttr = 'data-rba-roles', rbaPredicatesAttr = 'data-rba-predicates'; var hideFunc = (settings.hideFunc || function($rbaElem) { return $rbaElem.hide(); }); // wrapping for hiding implementation var hideElem = function($rbaElem) { $rbaElem.data('rbaRejected', true); return hideFunc($rbaElem); }; var elemRolesValidation = function($rbaElem, attrValue) { var elemRoles = attrValue.trim().split(/\s+/); if (!_.intersection(userRoles, elemRoles).length) { if (!$rbaElem.attr(rbaPredicatesAttr)) { hideElem($rbaElem); } } else { $rbaElem.data('__rbaRoleApproved__', true); } }; var elemPredicateValidation = function($rbaElem, attrValue) { if (!predicateDict) { throw new Error("Missing 'predicateDict' in settings"); } if ($rbaElem.data('__rbaRoleApproved__')) return; var elemPredicates = attrValue.trim().split(/\s+/); var allPredicatesPassed = _.every(elemPredicates, function(funcName) { var predicate = predicateDict[funcName]; if (predicate) { if (predicate.call(predicateDict, $rbaElem, userData, data)) { return true; } } else { console.error("No predicate function '" + funcName + "' defined. Following element is RBA rejected:", $rbaElem[0]); } }); if (!allPredicatesPassed) { hideElem($rbaElem); } }; var validations = {}; validations[rbaRolesAttr] = elemRolesValidation; validations[rbaPredicatesAttr] = elemPredicateValidation; var $checkedElems = $(); _.each([rbaRolesAttr, rbaPredicatesAttr], function(attrName) { var selector = '[' + attrName + ']'; $rootElem.find(selector).addBack(selector).each(function() { var $rbaElem = $(this); if ($rbaElem.data('__rbaChecked__')) return; var attrValue = $rbaElem.attr(attrName); if (!attrValue) { throw new Error("Missing value for " + attrName); } validations[attrName]($rbaElem, attrValue); $checkedElems = $checkedElems.add($rbaElem); }); }); $checkedElems.data('__rbaChecked__', true); }; /** * Periodic requests should be paused when the browser tab is in background. */ let _browserTabInBackground = false sharedBusModel.on('browserTab:background', () => _browserTabInBackground = true) sharedBusModel.on('browserTab:active', () => _browserTabInBackground = false) /** * This is necessary since Model.js is wrapping the actual jqXHR which would be returned otherwise * as in the Backbone's Model API * This function recursively digs into nested jqXHR and tries to abort * The promise may be double wrapped as happens in BaseModel.es6 * @param jqXHR */ var abortJQXHR = function(jqXHR) { if(jqXHR.abort) return jqXHR.abort() if(jqXHR.jqXHR) return abortJQXHR(jqXHR.jqXHR) return null } /** * * @param periodCall {function} e.g: model.fetch.bind(model) - should return jqXHR * @param periodicCallback {function} e.g: handleFetchResult(timeDiff, lastTimestamp, newTimestamp) * @param interval {int} in milliseconds * @param trailing {boolean} whether to start the periodic requests immediately or after the interal * @returns {function} Returns a function which can be used to manually trigger a "non"-periodic call * Also function.stop() will stop the periodic calls */ var makePeriodicAjax = function(periodCall, periodicCallback, interval, trailing, stopOnError = true, pauseInBackground = true) { let timerId; let lastTimestamp; let jqXHR; let isStopped = false; let initialized = false; var periodicAjax = function () { if (isStopped) return; // In case someone forcefully fired another request, cancel the former timer if(timerId) { clearTimeout(timerId); timerId = null; } jqXHR = periodicAjax.jqXHR = periodCall(); initialized = true; return jqXHR.then(function (result) { var newTimestamp = Date.now(); var timeDiff = newTimestamp - lastTimestamp; lastTimestamp = newTimestamp; if(periodicCallback) { periodicCallback(timeDiff, lastTimestamp, newTimestamp, result); } }) .then(function(jqXHR, textStatus, errorThrown) { if(interval && errorThrown!=='abort') { if (_browserTabInBackground && pauseInBackground) { sharedBusModel.once('browserTab:active', () => timerId = setTimeout(periodicAjax, interval)) } else { timerId = setTimeout(periodicAjax, interval); } } }, (e) => { //console.log('makePeriodicAjax - periodicCall failed', e); stopOnError && periodicAjax.stop(); }); }; periodicAjax.stop = function() { if (!initialized) return; isStopped = true; abortJQXHR(jqXHR) if(timerId) { clearTimeout(timerId); timerId = null; } }; // Start the chain; if (trailing && interval) { timerId = setTimeout(periodicAjax, interval); } else { periodicAjax(); } return periodicAjax; }; // if there's a possible conflict with serve, we reorder 'put' requests (GUI10-5635) var sendReorderedRequests = function(model, smallerAttribute, largerAttribute, aggregator) { var firstAttrPromise = $.Deferred(); if(model._pendingChanges[smallerAttribute] && model._pendingChanges[largerAttribute]) { var firstAttr = largerAttribute; if (model._pendingChanges[largerAttribute] < model._syncedAttrs[smallerAttribute]) { firstAttr = smallerAttribute; } let key = firstAttr, value = model._pendingChanges[firstAttr]; model.sendRequest({ type: 'put', aggregator: aggregator, urlSuffix: '/' + key, data: _.isNumber(value) ? value : JSON.stringify(value) // weird mgmt API stuff }).then(() => { model._pendingChanges = _.omit(model._pendingChanges, firstAttr); model.resetSyncedAttrs({attrs: {[key]: value}}); firstAttrPromise.resolve(); }); } else firstAttrPromise.resolve(); // no conflict with server return $.when(firstAttrPromise).then(() => { _.each(model._pendingChanges, (value, key) => { model.sendRequest({ type: 'put', aggregator: aggregator, urlSuffix: '/' + key, data: _.isNumber(value) ? value : JSON.stringify(value) // weird mgmt API stuff }).then(() => model.resetSyncedAttrs({attrs: {[key]: value}})); }); return aggregator.conclude(); }); } var Utils = { waitForAll: waitForAll, extractValues: extractValues, extend: extend, testEmail: testEmail, makePeriodicAjax: makePeriodicAjax, applyRBA: applyRBA, sendReorderedRequests: sendReorderedRequests }; export default Utils;
const package = require('../package.json'); module.exports.run = { execute(message, args) { // Gets the 'gyrominaNo' and 'gyrominaYes' emojis const nope = message.client.emojis.get("493575012276633610"); const yep = message.client.emojis.get("493570632785723402"); // Checks to see if the bot owner (L375#6740) sent the message. if(message.author.id !== package.authorID) { message.channel.send(`${nope} Error - Insufficient permissions!`) console.log('A user attempted to shut me down, but was unsuccessful!') return; } // Shuts down the current instance of the Discord Client. message.channel.send(`${yep}`); message.client.user.setStatus("invisible"); console.log(`Shutting down ${message.client.user.tag}...\n- - - - - - - - - - -`); message.client.destroy(); }, }; module.exports.help = { "name": "shutdown", "aliases": ["off", "stop", "quit"], "description": "Shuts down Gyromina. (Owner only)", "usage": `${process.env.prefix}shutdown`, "params": "(owner only)", "hide": 1, "wip": 0, "dead": 0, };
const path = require('path'); const webpack = require('webpack'); const CopyPlugin = require('copy-webpack-plugin'); const webpackModules = require('./webpack.js'); module.exports = { devServer: { contentBase: path.join(__dirname, './web'), compress: true, port: 4000, disableHostCheck: true, historyApiFallback: true, before: (app) => { app.post('/accounts', (req, res) => { res.redirect(req.originalUrl); }); }, }, entry: path.join(__dirname, './index.web.js'), output: { path: path.join(__dirname, './web/assets'), publicPath: 'assets/', filename: '[name].bundle.js', }, devtool: 'source-map', plugins: [ new webpack.DefinePlugin({ 'process.env.NODE_ENV': JSON.stringify('development'), __DEV__: true, }), new CopyPlugin([ { from: './node_modules/ton-client-web-js/tonclient.wasm' }, ]), new webpack.LoaderOptionsPlugin({ minimize: false, debug: true, }), ], ...webpackModules, };
export {default as addUser} from './add-user' export {default as deleteUser} from './delete-user' export {default as updateUser} from './update-user'
import React from 'react'; const TodoItem = ({ item, onUpdate, onRemove }) => { let completed = item.completed ? '--complete' : '' return ( <div className="TodoItem"> <button className={`TodoItem__button${completed}`} onClick={() => onUpdate(item.id)} > { item.completed && <i className="fas fa-check"></i> } </button> <div className={`TodoItem__title${completed}`}>{item.title}</div> <button className="TodoItem__button--remove" onClick={() => onRemove(item.id)}>X</button> </div> ) } export default TodoItem;
var bio = { "name": "Sergey Zolotaryov", "role": "Java Tech Lead", "contacts": { "mobile": "+31616321751", "email": "anydoby@gmail.com", "github": "anydoby", "location": "Drachten, NL" }, "welcomeMessage": "Welcome and have a look at my resume.", "skills": ["java of all sorts", 'solving simple problems', 'solving complex problems', 'web front end development' ], "biopic": "http://anydoby.com/udacity/frontend/P0/images/my_picture.jpg", "location": 'Drachten, The Netherlands', "display": function() { var contacts = this.contacts; var panel = $('#header'); function addContacts(panel) { panel.append(formatContact("mobile")); panel.append(formatContact("email")); panel.append(formatContact("github")); panel.append(formatContact("location")); } function formatContact(type) { return HTMLcontactGeneric.replace("%contact%", type).replace("%data%", contacts[type]); } panel.prepend(HTMLwelcomeMsg.replace('%data%', this.welcomeMessage)); panel.prepend(HTMLbioPic.replace('%data%', this.biopic)); panel.prepend(HTMLheaderRole.replace('%data%', this.role)); panel.prepend(HTMLheaderName.replace('%data%', this.name)); addContacts($("#topContacts")); panel.append(HTMLskillsStart); addContacts($("#footerContacts")); if (this.skills) { this.skills.forEach(function(skill) { $('#skills').append(HTMLskills.replace('%data%', skill)); }); } } }; var education = { "schools": [{ "name": "University of Kyiv-Mohyla Academy", "location": "Kiev, Ukraine", "degree": "Bachelor", "majors": ['Physics'], "dates": 2005, "url": 'http://www.ukma.edu.ua/' }], "onlineCourses": [{ "title": "Web Front End Developer", "school": 'Udacity', "date": 2015, "url": 'https://www.udacity.com/course/front-end-web-developer-nanodegree--nd001' }, { "title": "Sun Certified Business Components Developer", "school": "Sun Microsystems", "date": 2008, "url": 'http://java.sun.com' }, { "title": "Sun Certified Web Component Developer", "school": "Sun Microsystems", "date": 2007, "url": 'http://java.sun.com' }, { "title": "Sun Certified Java Developer", "school": "Sun Microsystems", "date": 2006, "url": 'http://java.sun.com' }, { "title": "Sun Certified Java Programmer", "school": "Sun Microsystems", "date": 2005, "url": 'http://java.sun.com' }, ], "display": function() { var panel = $('#education'); if (this.schools) { this.schools.forEach(function(school) { panel.append(HTMLschoolStart); var entry = $('.education-entry:last'); entry.append(HTMLschoolName.replace("%data%", school.name).replace("%url%", school.url)); entry.append(HTMLschoolDegree.replace("%data%", school.degree)); entry.append(HTMLschoolDates.replace("%data%", school.dates)); entry.append(HTMLschoolLocation.replace("%data%", school.location)); school.majors.forEach(function(m) { entry.append(HTMLschoolMajor.replace("%data%", m)); }); }); } if (this.onlineCourses) { panel.append(HTMLonlineClasses); this.onlineCourses.forEach(function(course) { panel.append(HTMLschoolStart); var entry = $('.education-entry:last'); entry.append(HTMLonlineTitle.replace("%data%", course.title)); entry.append(HTMLonlineSchool.replace("%data%", course.school)); entry.append(HTMLonlineDates.replace("%data%", course.date)); entry.append(HTMLonlineURL.replace("%data%", course.url)); }); } } }; var work = { "jobs": [{ "employer": "Mirasoft", "dates": '2004-07-01 - 2005-10-01', "title": "Java Developer", "location": "Kiev, Ukraine", "description": "My first job. Started as a tester finished as a junior java developer. A lot of UI testing at the beginning. Took part in a web service aggregation project." }, { "employer": "Ciklum", "dates": '2005-10-01 - 2006-12-01', "title": "Senior Java Developer", "location": "Kiev, Ukraine", "description": "Building a mobile media platform." }, { "employer": "Luxoft", "dates": '2007-02-01 - 2007-12-01', "title": "Senior Java Developer", "location": "Kiev, Ukraine", "description": "Building some trade processing/monitoring web application" }, { "employer": "Mirasoft", "dates": '2007-12-01 - 2009-04-01', "title": "Java Architect", "location": "Kiev, Ukraine", "description": "Took part in redesign and implementation of a healthcare patient tracking application for a big-big company." }, { "employer": "Asset Control", "dates": '2009-04-01 - now', "title": "Tech Lead", "location": "Heerenveen, The Netherlands", "description": "Building in-house asset management system. Designing and implementing the distribution/monitoring layer." }, ], "display": function() { var panel = $('#workExperience'); function displayWork(job) { panel.append(HTMLworkStart); var entry = $('.work-entry:last'); entry.append(HTMLworkEmployer.replace('%data%', job.employer)); entry.append(HTMLworkTitle.replace('%data%', job.title)); entry.append(HTMLworkDates.replace('%data%', job.dates)); entry.append(HTMLworkLocation.replace('%data%', job.location)); entry.append(HTMLworkDescription.replace('%data%', job.description)); } if (this.jobs) { this.jobs.reverse(); this.jobs.forEach(displayWork); } } }; var projects = { "projects": [{ "title": "Static personal page", "dates": "2015", "description": "A simple static page with personal information.", "images": ['http://anydoby.com/udacity/frontend/P0/images/my_picture.jpg'] }, { "title": "Bootstrap demo", "dates": "2015", "description": "A more advanced web page featuring usage of the Bootstrap framework to layout elements.", "images": ['http://anydoby.com/udacity/frontend/P1/img/appify.png', 'http://anydoby.com/udacity/frontend/P1/img/sunflower.png', 'http://anydoby.com/udacity/frontend/P1/img/bokeh.png' ] }, ], "display": function() { if (this.projects) { var panel = $('#projects'); this.projects.forEach(function(project) { panel.append(HTMLprojectStart); $('.project-entry:last').append(HTMLprojectTitle.replace('%data%', project.title)); $('.project-entry:last').append(HTMLprojectDates.replace('%data%', project.dates)); $('.project-entry:last').append(HTMLprojectDescription.replace('%data%', project.description)); project.images.forEach(function(img) { $('.project-entry:last').append(HTMLprojectImage.replace('%data%', img)); }); }); } } }; function buildResume() { if (document.getElementsByClassName('flex-item').length === 0) { document.getElementById('topContacts').style['background-color'].display = 'none'; } if (document.getElementsByTagName('h1').length === 0) { document.getElementById('header').style['background-color'].display = 'none'; } if (document.getElementsByClassName('work-entry').length === 0) { document.getElementById('workExperience').style['background-color'].display = 'none'; } if (document.getElementsByClassName('project-entry').length === 0) { document.getElementById('projects').style['background-color'].display = 'none'; } if (document.getElementsByClassName('education-entry').length === 0) { document.getElementById('education').style['background-color'].display = 'none'; } if (document.getElementsByClassName('flex-item').length === 0) { document.getElementById('lets-connect').style['background-color'].display = 'none'; } if (document.getElementById('map') === null) { document.getElementById('mapDiv').style['background-color'].display = 'none'; } bio.display(); work.display(); projects.display(); education.display(); $('#mapDiv').append(googleMap); } $(buildResume);
class Contact { constructor(name, wsp, desc) { this.name = name; this.wsp = wsp; this.desc = desc; } } let contacts = JSON.parse(localStorage.getItem("contacts")) || []; const getAll = () => { return contacts; }; const create = (newContact) => { contacts.push(newContact); localStorage.setItem("contacts", JSON.stringify(contacts)); }; const nameInput = $("#name-input"); const numberWsp = $("#number-wsp"); const description = $("#description"); const btnEnviar = $(".btn btn-primary"); const contactList = $("contact-list"); $("#enviarBtn").on("click", function () { const nombre = nameInput[0].value; const numero = numberWsp[0].value; const descripcion = description[0].value; const contact = new Contact(nombre, numero, descripcion); create(contact); console.log(getAll()); }); for (let contact of contacts) { console.log(contact); $("#contact-list").prepend( `<tr><td> ${contact.name} </td> <td> ${contact.wsp} </td> <td> ${contact.desc}</td></tr>` ); } $("#mostrarBtn").click(function () { $("#lista-contactos").fadeIn(500); $("#mostrarBtn").hide(1000); $("#ocultarBtn").show(1000); }); $("#ocultarBtn").click(function () { $("#lista-contactos").fadeOut(500); $("#ocultarBtn").hide(1000); $("#mostrarBtn").show(1000); });
const ExtendableError = require('./ExtendableError') module.exports = class extends ExtendableError { constructor (email) { super(`User with email ${email} not found`, 'WRONG_EMAIL', 404) } }
import React, { Component } from "react"; import { Link } from "react-router-dom"; import "./static.css"; class About extends Component { componentDidMount() { document.title = "About"; } render() { return ( <div className="static-page"> <h1>About</h1> <p> Founded in 1994, the MIT DanceTroupe is the largest dance organization at the Massachusetts Institute of Technology. We are a student-run group dedicated to bringing a variety of dance styles to everyone in the MIT community, regardless of level. Every semester, we offer various dance workshops to our members and produce one full length show. </p> <h3>Membership</h3> <p> Membership is open to everyone, regardless of experience level. We welcome undergraduate and graduate students, alumni, staff, and anyone else in the area interested in dance. </p> <h3>Officers</h3> <p> DanceTroupe is run entirely by a group of student officers, all of whom are elected by the members of DanceTroupe. Officer terms are one year (two semesters), and there are no term limits. To contact officers, email{" "} <a className="link-name" href="mailto:dt-officers@mit.edu"> dt-officers@mit.edu </a> . Current officers may be found on the{" "} <Link className="link-name" to="/officers"> officers page </Link> . </p> <h3>Workshops</h3> <p> DanceTroupe offers workshops of different styles and levels to all of its members throughout the year. No audition or experience is required to attend! Check our{" "} <a className="link-name" href="https://www.facebook.com/mitdancetroupe/" target="_blank" > facebook page </a>{" "} for our workshop schedules! </p> <h3>Show</h3> <p> DanceTroupe produces one full-length{" "} <Link className="link-name" to="/shows"> show </Link>{" "} every semester, with five performances at the end of the semester. Our shows are made up of dances choreographed by students, and include dance styles such as hip-hop inspired, jazz, ballet, tap, modern, and more. All members who want to participate in the show must attend{" "} <Link className="link-name" to="/auditions"> auditions </Link> , which take place at the beginning of each semester. </p> <p> Members may participate in up to four dances, with one hour of weekly rehearsal per dance. In addition to rehearsals, dancers must attend First Showings and Second Showings (two full run-throughs of the show) and Production Week. Production Week occurs the week before the show performances and involves several dress rehearsals. </p> <h3>Constitution</h3> <p> DanceTroupe abides by all MIT ASA policies. View our constitution{" "} <a className="link-name" href="http://web.mit.edu/dancetroupe/www/dt_constitution.pdf" target="_blank" > here. </a> </p> </div> ); } } export default About;
var Transform = function(owner, options) { this.owner = owner; this.enabled = true; this.x = options.x || 0; this.y = options.y || 0; } Transform.prototype.render = function() { console.log(this.owner.name + ': ' + this.x); } module.exports = Transform;
import React from 'react'; import {connect} from 'react-redux' import {Grid, Header, Segment, Icon} from 'semantic-ui-react'; import {Link} from 'react-router-dom'; class Question extends React.Component{ render(){ const {id, upVotes, downVotes, answersAmount = 0, header = 'Header', content, username='admin'} = this.props; const date = new Date; const rating = upVotes - downVotes; return( <Grid.Row> <Grid.Column width={2} textAlign='center' verticalAlign='middle'> {rating} <div>rating</div> {answersAmount} <div>answers</div> </Grid.Column> <Grid.Column width={14}> <Header size='medium' > <Link to={`/questions/${id}`}>{header}</Link> </Header> <div> {content} </div> <Grid> <Grid.Column textAlign='right'> <div>by {username}</div> <div>at {date.toLocaleString()}</div> </Grid.Column> </Grid> </Grid.Column> </Grid.Row> ) } } const mapStateToProps = (state, ownProps) =>{ return { ...state.questions.byId[ownProps.id], } } const mapDispatchToProps = { } export default connect(mapStateToProps, mapDispatchToProps)(Question);
// Initialize Firebase $(document).ready(function() { var config = { apiKey: "AIzaSyC_VZELnTN7j0ze48EAIFkqFJrB70actT4", authDomain: "timesheet-37041.firebaseapp.com", databaseURL: "https://timesheet-37041.firebaseio.com", projectId: "timesheet-37041", storageBucket: "timesheet-37041.appspot.com", messagingSenderId: "828927234718" }; firebase.initializeApp(config); // Create a variable to reference the database var database = firebase.database(); var name = ""; var role = ""; var startDate = ""; var monthlyRate = ""; // Capture Button Click $("#submitId").on("click", function(event) { // Don't refresh the page! event.preventDefault(); // YOUR TASK!!! // Get inputs name = $("#name-input").val().trim(); role = $("#role-input").val().trim(); startDate = $("#startDate-input").val().trim(); monthlyRate = $("#monthlyRate-input").val().trim(); // Code in the logic for storing and retrieving the most recent user. // Change what is saved in firebase database.ref().push({ name: name, role: role, startDate: startDate, monthlyRate: monthlyRate, // me manda la cantidad de segundos desde 1970 a la fecha actual // dateAdded: firebase.database.ServerValue.TIMESTAMP }); }); // Vamos a hablarle a la BD database.ref().on("child_added", function(snapshotChild) { // Print the initial data to the console. console.log(snapshotChild.val()); // Log the value of the various properties console.log(snapshotChild.val().name); console.log(snapshotChild.val().role); console.log(snapshotChild.val().startDate); console.log(snapshotChild.val().monthlyRate); //For clarity's sake, we put the values into variables var name = snapshotChild.val().name; var role = snapshotChild.val().role; var monthlyRate = snapshotChild.val().monthlyRate; //We get the start date which we saved in the "MM/DD/YYYY" format, an create a momentjs object with it var startDate = moment(snapshotChild.val().startDate, "MM/DD/YYYY"); //We get the current date var now = moment(); //We can now calculate the difference between now and startDate in "months" var monthsWorked = now.diff(startDate, "months"); //With the amount of months worked and the monthly rate, we can calculate the total billing var totalBilling = monthlyRate * monthsWorked; // Create the new row var newRow = $("<tr>").append( $("<td>").text(name), $("<td>").text(role), $("<td>").text(startDate.format("MM/DD/YYYY")), // Cuantos meses lleva ativo $("<td>").text(monthsWorked), $("<td>").text("$" + monthlyRate), // Total Billing $("<td>").text("$" + totalBilling), ); // Append the new row to the table $("#employee-table > tbody").append(newRow); // If any errors are experienced, log them to console. }, function(errorObject) { console.log("Errors Handled: " + errorObject.code); }); });
import { useState, useEffect, useContext } from "react"; import styled from "styled-components"; import PropTypes from "prop-types"; import { LoadingContext } from "../../contexts"; import Loading from "../../components/Loading"; import { getPost } from "../../WebAPI"; const Meme = styled.img` width: 80%; height: 50%; margin-top: 2rem; `; export default function PostPage() { const [post, setPost] = useState([]); const { isLoading, setIsLoading } = useContext(LoadingContext); const id = 72; useEffect(() => { setIsLoading(true); getPost(id).then((post) => { setPost(post[0]); setIsLoading(false); }); return () => { setIsLoading(false); }; }, []); return ( <> {isLoading && <Loading />} <h1>About Me</h1> 生菜,正在練習用 react 做部落格。 <Meme src='https://scontent.fkhh1-1.fna.fbcdn.net/v/t1.0-9/129622091_4955958677778025_5487173615913268757_o.jpg?_nc_cat=103&ccb=2&_nc_sid=8bfeb9&_nc_ohc=p5CWpq-dEooAX_tcHTs&_nc_ht=scontent.fkhh1-1.fna&oh=d799209f2c70471119e3171d399f648d&oe=5FF92991' /> <div>(圖片來源:迷因刻本)</div> </> ); }
export function upper(value){ //console.log('in upper'); return value && value.toUpperCase() } export function lower(value){ return value && value.toLowerCase() }
"use strict"; let helper = {}; helper.SystemHelper = require( "./helper/systemhelper.js" ); let pay = require("./pay/payfactory"); pay["util"] = require('./pay/helper/util'); pay["helper"] = helper; module.exports = pay;
import React from "react"; import { useSelector, useDispatch } from "react-redux"; import { useRouter } from "next/router"; import { EditOutlined } from "@ant-design/icons"; import { Dropdown } from "antd"; import axios from "axios"; import Image from "next/image"; import { Container, Banner, AvatarWrapper, EditButton, BackgroundMenu, MenuItem, BackgroundImageWrapper, BackgroundImage, MenuItemColor, ColorBox, } from "./style"; import { UPDATE_USER_PROFILEBACKGROUND } from "../../../actions/types"; import baseUrl from "../../../utils/baseUrl"; import CustomAvatar from "../../avatar"; import backgroundImages from "../../../constants/accountBackgroundImages"; import colorCodes from "../../../constants/colorCodes"; const index = () => { const user = useSelector((state) => state.auth.user); const router = useRouter(); const dispatch = useDispatch(); const updateUserData = async (image, color) => { dispatch({ type: UPDATE_USER_PROFILEBACKGROUND, payload: { color: color, image: image }, }); try { const config = { headers: { "Content-Type": "application/json", }, }; //stringify the form items const body = JSON.stringify({ profileBackground: { color, image }, }); const url = `${baseUrl}/api/auth/updateAccount`; await axios.patch(url, body, config); } catch (err) { console.log(err); } }; const menu = ( <BackgroundMenu> {backgroundImages.map((item, index) => { return ( <MenuItem key={"image" + index} onClick={() => { updateUserData(item.src, null); }} > <Image src={item.src} alt={item.alt} layout='fixed' width={460} height={60} /> </MenuItem> ); })} {colorCodes.map((item, index) => { return ( <MenuItemColor key={"color" + index} onClick={() => { updateUserData(null, item.secondary); }} > <ColorBox color={item.secondary} /> </MenuItemColor> ); })} </BackgroundMenu> ); return ( <Container isMessageThreadView={router.query.thread}> {user && ( <Banner bgColor={ user.profileBackground.color ? user.profileBackground.color : colorCodes[user._id.charCodeAt(user._id.length - 1) % 20] .secondary } > <EditButton> <Dropdown overlay={menu} trigger={["click"]}> <a className='ant-dropdown-link' onClick={(e) => e.preventDefault()} > <EditOutlined style={{ fontSize: "20px", color: "#cecece" }} /> </a> </Dropdown> </EditButton> {user.profileBackground.image && ( <BackgroundImageWrapper> <BackgroundImage alt='user account background image' src={user.profileBackground.image} /> </BackgroundImageWrapper> )} </Banner> )} <AvatarWrapper> <CustomAvatar profileImage={user ? user.profileImage : null} userId={user ? user._id : null} username={user ? user.username : null} size={150} isEditable={true} isOutlined={true} /> </AvatarWrapper> </Container> ); }; export default index;
import './App.css'; import About from './About' import Contact from './Contact'; import {useState} from 'react' import Users from './Users' import CreateUser from './Createuser'; import {Link, Route, BrowserRouter as Router, Switch} from 'react-router-dom' import {Navbar,Nav} from 'react-bootstrap' function App() { const [name,setName]= useState('Pranshu') return ( <div className="App"> <Router> <Navbar bg="dark" variant="dark"> <Navbar.Brand href="#home">Navbar</Navbar.Brand> <Nav className="mr-auto"> <Nav.Link href="#home"><Link to="/about">About</Link></Nav.Link> <Nav.Link href="#features"><Link to="/contact">Contact</Link></Nav.Link> <Nav.Link href="#pricing"><Link to="/user-list">Users</Link></Nav.Link> <Nav.Link href="#pricing"><Link to="/create-user">Create User</Link></Nav.Link> </Nav> </Navbar> <Switch> <Route path="/about"> <About /> </Route> <Route path="/contact"> <Contact /> </Route> <Route path="/user-list"> <Users /> </Route> <Route path="/create-user"> <CreateUser /> </Route> </Switch> {/* <About name={name} /> */} {/* <Contact name={name} /> */} {/* <button onClick={()=>{setName("Pranshu Sharma")}}>Update Name</button> */} {/* <Users /> */} {/* <CreateUser /> */} </Router> </div> ); } export default App;
/* Interfaces with gas-local in order to bring what is normally server-side code into the local node.js stack, i.e. "virtualizing" it Creates an object virtual that contains all code in source folders Also has method .virtual which creates one as well, which is used to pass on virtualized code into templating files */ 'use strict'; let moment = require('moment'); // Moment is just too good not to use let gas = require('gas-local'); let ejs = require('ejs'); let Document = require('./Document.js'); let Spreadsheet = require('./Spreadsheet.js'); let Form = require('./form.js'); const sourcePath = 'dev'; let hooksForMocks = { production: false, FormApp: { getActiveForm: function () { return Form('getActiveForm'); }, openById: function (id) { return Form('openById'); }, create: function (title) { return Form(title); }, 'DestinationType': { 'SPREADSHEET': 'SPREADSHEET' }, }, DocumentApp: { getActiveDocument: function () { /* return new Document(); */ }, }, SpreadsheetApp: { allSpreadsheets: [], active: null, /* */ create: function (name, rows, columns) { var id = this.allSpreadsheets.length; var ss = Spreadsheet(id, name, rows, columns); this.allSpreadsheets.push(ss); return ss; }, /* Have to hold the same one otherwise we create a new one with every test iteration */ getActiveSpreadsheet: function () { if (this.active == null) { this.active = Spreadsheet(this.allSpreadsheets.length); this.allSpreadsheets.push(this.active); } return this.active; }, openById: function (id) { return this.allSpreadsheets[id] || null; }, }, Moment: moment, __proto__: gas.globalMockDefault, }; hooksForMocks.Moment.load = function () {}; // load is part of GAS ecosystem var virtual = gas.require('./' + sourcePath, hooksForMocks); virtual.executionAPIInfo = { "access_token":"ya29.GlsxBHe3HrGzwmsu0yCJknsX3S0BgWp419NsQUbEpWD1vwG6lr4FloqiBQpCfBcFwed4cN5Q1BCjEfrGMwMa2P7XUCND48k57mP8iORzVg_Qt5D6sw22MaSEqhJE", "refresh_token":"1/oHsamPj7LWdu7Qh1Bs9kmJDUB2GZ0kz48IsdfN4YjUM", "token_type":"Bearer", "expiry_date":1492522268646 }; // { // apiKey: '', // discovertyDocs: '', // clientId: '', // scope: [], // } // Passed into include in order to ensure templates have virtual source too virtual.virtual = function () { return gas.require('./' + sourcePath, hooksForMocks); }; module.exports = virtual;
var MyDate = function (day, month, year) { // this.day = day; // this.month = month; //Em không hiểu this chỗ này dùng làm gì cả, mấy chỗ dưới nữa, bỏ hết đi đều chạy được. Chỉ có chỗ setDate bỏ đi thì không chạy được. // this.year = year; // Nhưng khi tạo class thì hầu hết mọi tài liệu đều bỏ this vào. this.getDay = function(){ return day; console.log(day) } this.getMonth = function () { return month; } this.getYear = function (){ return year; } this.setDay = function (day) { return day; } this.setMonth = function (month) { return month; } this.setYear = function (year) { return year; } this.setDate = function (day, month, year) { this.day = day; this.month = month; this.year = year; } this.toString = function () { alert(this.day + "/" + this.month + "/" + this.year); //Tại sao this ở đây lại trỏ đến setDate ạ?? console.log(day); } } var date = new MyDate(2, 2, 2007); var day = date.getDay(); // 2 var month = date.getMonth(); // 2 var year = date.getYear(); // 2007 alert(day + "/" + month + "/" + year); date.setDay(10); date.setMonth(5); date.setYear(1995); date.setDate(4,1,1991); date.toString();
var express = require('express'); var router = express.Router(); var dbConn = require('../lib/db'); /* GET home page. */ router.get('/', function(req, res, next) { //res.render('index', { title: 'Express' }); dbConn.query('SELECT * FROM playlist ORDER BY id desc',function(err,rows) { if(err) { req.flash('error', err); res.render('index',{data:''}); } else { res.render('index',{data:rows}); } }); }); module.exports = router;
const express = require ('express'); const router = express.Router(); const boardsController = require("../controllers/boardsController"); const listsController = require("../controllers/listsController"); // in boardsController const cardsController = require("../controllers/cardsController"); const { validateBoard, validateList, validateCard } = require("../validators/validators"); router.get('/boards',boardsController.getBoards ); router.post('/boards', validateBoard, boardsController.createBoard ); router.get('/boards/:id', boardsController.getBoard); router.post( '/lists', validateList, listsController.createList, boardsController.addListToBoard, listsController.sendList ); router.put('/lists/:id', listsController.editList, listsController.sendList); router.get('/cards/:id', cardsController.getCard); router.post( '/cards', validateCard, listsController.findBoardId, cardsController.createCard, listsController.addCardToList, cardsController.sendCard ); module.exports = router;
// DOROTHY & MICHAEL // Fibonacci- return nth element of fibonacci sequence function Fibonacci (n){ let sequence = [0,1] let i if (typeof n == "number"){ for (i = 2; i<=n; i++){ sequence[i]= sequence[i-1] + sequence[i-2] } return sequence[n] }else{ error = new Error('input should be number') return error.message } } module.exports = Fibonacci
let fn = require('../../utils/fn'); module.exports = function(app) { var Model = app.models.articles, cateModel = app.models.categorys, view = 'admin/article', url = '/admin/article', title = '后台文章管理', exports = {}; var getAllCategory = () => { return cateModel.getTree(); }; exports.list = function(req, res, next) { let where = fn.parseWhere(req, {}); Model.find(where) .populate('cids') .sort({ createdAt: 'desc'}) .exec() .then(function(result) { getAllCategory().then((rs) => { res.render(view, { title: title, list: result, categorys: rs, query: req.query }); }); }).catch(function(err) { return next(err); }); }; exports.add = function(req, res) { getAllCategory().then((rs) => { res.render(`${view}/form`, { title: `${title}-添加`, categorys: rs }); }); }; exports.edit = function(req, res, next) { if (req.params.id) { Model.findOne({ _id: req.params.id }) .exec() .then(function(doc) { getAllCategory() .then((rs) => { res.render(`${view}/form`, { title: `${title}-编辑`, model: doc.toObject(), categorys: rs }); }); }) .catch(function(err) { return next(err); }); } else { return res.status(404).send('Not found'); } }; exports.save = function(req, res, next) { if (req.body.id) { Model.findOne({ _id: req.body.id }) .exec() .then(function(document) { if (!document) return next(); for (var key in req.body) { document[key] = req.body[key]; } if (!req.body.parent_id) { document.parent_id = null; } if (!req.body.price) { document.price = 0; } document.save() .then(function() { res.redirect(url); }).catch(function(err) { return next(err); }); }).catch(function(err) { return next(err); }); } else { if (!req.body.parent_id) { delete req.body.parent_id; } var newModel = new Model(req.body); // save user to database newModel.save() .then(function() { res.redirect(url); }).catch(function(err) { return next(err); }); } }; exports.del = function(req, res, next) { if (req.params.id) { Model.remove({ _id: req.params.id }, function(err) { if (err) next(err); }); } res.redirect(url); }; return exports; };
import React from 'react' import '../styles/App.css' import Face from './Face' import ActivityIndicator from './ActivityIndicator' import propTypes from 'prop-types' import End from './End' import Advert from'./Advert' const Content=({value,activity,condition})=>( <div className="content-body"> <div className="row"> { value.map((val,i)=> (!(i%20)&&i!==0)? <Advert value={val} key={i}/>: <Face face={val.face} key={i} price={val.price} date={val.date} size={val.size}/> ) } </div> <ActivityIndicator activity={activity}/> <End condition={condition}/> </div> ) export default Content Content.propTypes={ value:propTypes.array.isRequired, activity:propTypes.bool.isRequired }
//Inicializa CLOUD FIRESTORE //Agregar documentos function guardar(){ var nombre = document.getElementById('userName').value; var email = document.getElementById('userEmail').value; db.collection("usuarios").add({ name: nombre, mail: email }) .then(function(docRef) { console.log("Document written with ID: ", docRef.id); document.getElementById('userName').value = ''; document.getElementById('userEmail').value = ''; }) .catch(function(error){ console.error("Error adding document: ", error); }); }
import { forEach } from 'lodash' import LabelEdgeGroup from '../labeler/labeledgegroup.js' import PatternGroup from './patterngroup' /** * PathSegment */ let segmentId = 0 export default class PathSegment { constructor(type, path) { this.id = segmentId++ this.type = type this.path = path this.points = [] this.edges = [] this.renderedSegments = [] this.patternGroup = new PatternGroup() } clearGraphData() { this.edges = [] this.points.forEach(function (point) { point.graphVertex = null }) this.renderLength = null } getId() { return this.id } getType() { return this.type } addRenderedSegment(rSegment) { this.renderedSegments.push(rSegment) } addEdge(graphEdge, originVertex) { this.edges.push({ forward: originVertex === graphEdge.fromVertex, graphEdge: graphEdge }) } insertEdgeAt(index, graphEdge, originVertex) { const edgeInfo = { forward: originVertex === graphEdge.fromVertex, graphEdge: graphEdge } this.edges.splice(index, 0, edgeInfo) } removeEdge(graphEdge) { let index = null for (let i = 0; i < this.edges.length; i++) { if (this.edges[i].graphEdge === graphEdge) { index = i break } } if (index !== null) this.edges.splice(index, 1) } getEdgeIndex(graphEdge) { for (let i = 0; i < this.edges.length; i++) { if (this.edges[i].graphEdge === graphEdge) return i } return -1 } /** * Get graph vertices */ getGraphVertices() { const vertices = [] this.edges.forEach(function (edge, i) { if (i === 0) { vertices.push(edge.graphEdge.fromVertex) } vertices.push(edge.graphEdge.toVertex) }) return vertices } vertexArray() { let vertex = this.startVertex() const array = [vertex] this.edges.forEach(function (edgeInfo) { vertex = edgeInfo.graphEdge.oppositeVertex(vertex) array.push(vertex) }) return array } startVertex() { if (this.points[0].multipoint) return this.points[0].multipoint.graphVertex if (!this.edges || this.edges.length === 0) return null const firstGraphEdge = this.edges[0].graphEdge return this.edges[0].forward ? firstGraphEdge.fromVertex : firstGraphEdge.toVertex /* if (this.graphEdges.length === 1) return this.graphEdges[0].fromVertex; var first = this.graphEdges[0], next = this.graphEdges[1]; if (first.toVertex == next.toVertex || first.toVertex == next.fromVertex) return first.fromVertex; if (first.fromVertex == next.toVertex || first.fromVertex == next.fromVertex) return first.toVertex; return null; */ } endVertex() { if (this.points[this.points.length - 1].multipoint) { return this.points[this.points.length - 1].multipoint.graphVertex } if (!this.edges || this.edges.length === 0) return null const lastGraphEdge = this.edges[this.edges.length - 1].graphEdge return this.edges[this.edges.length - 1].forward ? lastGraphEdge.toVertex : lastGraphEdge.fromVertex /* if (this.graphEdges.length === 1) return this.graphEdges[0].toVertex; var last = this.graphEdges[this.graphEdges.length - 1], prev = this.graphEdges[this.graphEdges.length - 2]; if (last.toVertex == prev.toVertex || last.toVertex == prev.fromVertex) return last.fromVertex; if (last.fromVertex == prev.toVertex || last.fromVertex == prev.fromVertex) return last.toVertex; return null; */ } addPattern(pattern, fromIndex, toIndex) { // Initialize this segment's 'points' array to include the stops in the // provided pattern between the specified from and to indices, inclusive. // Only do this if the points array is empty or if the the length of the // segment being added exceeds that of the one currently stored. if (toIndex - fromIndex + 1 > this.points.length) { this.points = [] let lastStop = null for (let i = fromIndex; i <= toIndex; i++) { const stop = pattern.stops[i] if (lastStop !== stop) { this.points.push(stop) } lastStop = stop } } // Add the pattern to this segment's PatternGroup this.patternGroup.addPattern(pattern, fromIndex, toIndex) } getPattern() { return this.patternGroup.patterns[0] } getPatterns() { return this.patternGroup.patterns } getMode() { return this.patternGroup.patterns[0].route.route_type } toString() { const startVertex = this.startVertex() const endVertex = this.endVertex() return ( 'PathSegment id=' + this.id + ' type=' + this.type + ' from ' + (startVertex ? startVertex.toString() : '(unknown)') + ' to ' + (endVertex ? endVertex.toString() : '(unknown)') ) } getLabelEdgeGroups() { const edgeGroups = [] forEach(this.renderedSegments, (rSegment) => { if (!rSegment.isFocused()) return let currentGroup = new LabelEdgeGroup(rSegment) forEach(rSegment.renderedEdges, (rEdge) => { currentGroup.addEdge(rEdge) if (rEdge.graphEdge.toVertex.point.containsSegmentEndPoint()) { edgeGroups.push(currentGroup) currentGroup = new LabelEdgeGroup(rSegment) } }) }) return edgeGroups } }
import React, { Component } from 'react' import { BoxFiltro } from './Ecommerce.styleFiltros' export default class EcommerceFiltros extends Component { render() { return ( <BoxFiltro> <div> <h2>Filtros</h2> <div> <label>Valor mínimo:</label> <input type="number" value={this.props.minFilter} onChange={this.props.onChangeMinFilter} /> </div> <div> <label>Valor máximo:</label> <input type="number" value={this.props.maxFilter} onChange={this.props.onChangeMaxFilter} /> </div> <div> <label>Busca por nome:</label> <input type="text" value={this.props.nameFilter} onChange={this.props.onChangeNameFilter} /> </div> </div> </BoxFiltro> ); } }
var socket = io(); var noSleep = new NoSleep(); noSleep.enable(); var title = $('.id').text(); var id = title.charAt(title.length-1); id = parseInt(id); socket.emit('registerInstument', id); var volume = 1; function handleOrientation(event) { var array = []; var absolute = event.absolute; var alpha = event.alpha; var beta = event.beta; var gamma = event.gamma; $(".alpha").text("alpha (z axis, 0 to 360): " + alpha); $(".beta").text("beta (x axis, -180 to 180): " + beta); $(".gamma").text("gamma (y axis, -90 to 90): " + gamma); $(".absolute").text("absolute: " + absolute); array.push( Math.round(alpha)/360 ); array.push( (Math.round(beta)+180)/360 ); array.push( (Math.round(gamma)+90)/180 ); return array; } $( "#volume" ).change(function() { volume = $('#volume').val(); }); window.addEventListener("deviceorientation", function(event){ var orientationArray = handleOrientation(event); orientationArray.push(parseFloat(volume)); orientationArray.push(id); socket.emit('orientation', orientationArray); }, true);
import React from 'react'; import {Scene, Router} from 'react-native-router-flux'; import Login from './login'; import MapComponent from './MapComponent'; import AddSpot from './AddSpot'; import SpotList from './SpotList'; const RouterComponent = () => { return ( <Router> <Scene key="root"> <Scene key="Login" component={Login} hideNavBar initial /> <Scene key="MapComponent" component={MapComponent} hideNavBar /> <Scene key="AddSpot" component={AddSpot} hideNavBar /> <Scene key="SpotList" component={SpotList} hideNavBar /> </Scene> </Router> ); }; export default RouterComponent;
const app = getApp() Page({ data: { showType: false, animationData: {}, selectedType: ['全部'], xueli: [{ id: 1, label: '其他' }, { id: 2, label: '初中' }, { id: 3, label: '高中' }, { id: 4, label: '专科' }, { id: 4, label: '本科' }, { id: 4, label: '博士' }, ], workType: [ { id: 1, label: '全职' }, { id: 2, label: '兼职' }, { id: 3, label: '小时工' } ], workPlace: [], jobType: [ { id: 1, label: '互联网/电子商务' }, { id: 2, label: '贸易/出口进口' }, { id: 3, label: '计算机硬件' }, { id: 4, label: 'IT服务/系统集成' }, ], moneyType: [ { id: 1, label: '2000以下' }, { id: 2, label: '2000-3000' }, { id: 3, label: '3000-5000' }, { id: 4, label: '5000-8000' }, ], list: [ { id: 1, label: '普工', children: [{ id: 1, label: '印花工' }, { id: 2, label: '染工' }, { id: 3, label: '组装工' }, { id: 4, label: '水泥工' }, ] }, { id: 2, label: '销售', children: [{ id: 1, label: '渠道专员' }, { id: 2, label: '会籍顾问' }, { id: 3, label: '客服经理' }, { id: 4, label: '网络销售' }, ] }, { id: 3, label: '司机', children: [{ id: 1, label: '驾校教练' }, { id: 2, label: '班车司机' }, { id: 3, label: '出租车司机' }, { id: 4, label: '货运司机' }, { id: 4, label: '餐饮', children: [{ id: 1, label: '服务员' }, { id: 2, label: '洗碗工' }, { id: 3, label: '厨师' }, { id: 4, label: '大堂经理' }, ] }, ] }, ], childList: [ { id: 1, label: '印花工' }, { id: 2, label: '染工' }, { id: 3, label: '组装工' }, { id: 4, label: '水泥工' }, ], graduation_school: '', graduation_time: '', degree: '', intention_area: '', job_direction:'' }, switchSchool(e) { this.setData({ graduation_school: e.detail.value }) }, switchXueli: function (e) { this.setData({ degree: this.data.xueli[e.detail.value].label }) }, switchDate: function (e) { this.setData({ graduation_time: e.detail.value }) }, // switchWorkType: function (e) { // this.setData({ // intention_area: this.data.workType[e.detail.value].label // }) // }, switchWorkPlace: function (e) { this.setData({ intention_area: e.detail.value[1] + ' ' + e.detail.value[2] }) }, switchJobType: function (e) { this.setData({ selectedJobType: this.data.jobType[e.detail.value].label }) }, switchMoneyType: function (e) { this.setData({ selectedMoneyType: this.data.moneyType[e.detail.value].label }) }, selectType() { this.setData({ showType: true }) var animation = wx.createAnimation({ duration: 800, timingFunction: 'ease' }) this.animation = animation animation.translateY(0).step() this.setData({ animationData: animation.export() }) }, closePopup() { let that = this this.setData({ job_direction:null }) setTimeout(function () { that.setData({ showType: false }) }, 400) var animation = wx.createAnimation({ duration: 400, timingFunction: 'ease' }) this.animation = animation // animation.height(350).step() animation.translateY(350).step() this.setData({ animationData: animation.export() }) }, changeType(e) { for (let i = 0; i < this.data.list.length; i++) { this.setData({ childList: this.data.list[e.detail.value[0]].children }) this.setData({ job_direction: this.data.childList[e.detail.value[1]].label }) } }, confirmSelected() { this.setData({ showType: false }) var animation = wx.createAnimation({ duration: 400, timingFunction: 'ease' }) this.animation = animation // animation.height(350).step() animation.translateY(350).step() this.setData({ animationData: animation.export() }) }, save: function () { app.fun.post('/user/updateResume', { type: 'education', id:this.data.id, graduation_school: this.data.graduation_school, graduation_time: this.data.graduation_time, degree: this.data.degree, intention_area: this.data.intention_area, job_direction: this.data.job_direction }).then((res) => { wx.showToast({ title: res.msg }) }) let pages = getCurrentPages() let prePage = pages[pages.length - 2] prePage.onLoad() setTimeout(() => { wx.navigateBack({ delta: 1 }) },1000) }, onShow() { var animation = wx.createAnimation({ duration: 1000, timingFunction: 'ease' }) this.animation = animation animation.translateY(350).step() this.setData({ animationData: animation.export() }) }, onLoad(e) { const jobInfo = app.jobInfo this.setData({ id: e.id, graduation_school: jobInfo.graduation_school, graduation_time: jobInfo.graduation_time, degree: jobInfo.degree, intention_area: jobInfo.intention_area, job_direction: jobInfo.job_direction }) } })
'use strict'; import Numeral from 'numeral'; import Database from '../../../server'; class User extends Database.Model { get tableName () { return 'users'; } toJSON () { let values = Database.Model.prototype.toJSON.apply(this); values.credits_format = Numeral(values.credits).format('0.0a').toUpperCase(); values.pixels_format = Numeral(values.activity_points).format('0.0a').toUpperCase(); values.points_format = Numeral(values.vip_points).format('0.0a').toUpperCase(); return values; } } export default User;
const express = require('express'); const router = express.Router(); const tasks = require('../../controllers/tasks.controller'); router.post('/', (req, res) => { console.log('POST /tasks/'); tasks.create(req, res); }) router.put('/', (req, res) => { console.log('PUT /tasks/'); tasks.update(req, res); }) router.get('/group/:groupId(\d+)', (req, res) => { console.log('GET /tasks/group/' + req.params.groupId) tasks.findByGroup(req, res); }) router.get('/worker/:workerId(\d+)', (req, res) => { console.log('GET /tasks/worker/' + req.params.workerId); tasks.findByWorker(req, res); }) router.delete('/:id(\d+)', (req, res) => { console.log('DELETE /tasks/' + req.params.id); tasks.delete(req, res); })
//@ts-check /** @type {number} */ var x; x = 0; x = false;
import HomePage from '../pages/HomePage' import LoginPage from '../pages/LoginPage' import DashboardPage from '../pages/DashboardPage' import UserManagementPage from '../pages/UserManagementPage' import GroupManagementPage from '../pages/GroupManagementPage' import RoleManagementPage from '../pages/RoleManagementPage' import RecoveryPage from '../pages/RecoveryPage' import RecoveryRequestPage from '../pages/RecoveryRequestPage' import ActivationPage from '../pages/ActivationPage' import ProfilePage from '../pages/ProfilePage' import RegisterPage from '../pages/RegisterPage' const routes = [ {name: "home", path: '/home', component: HomePage}, {name: "login", path: '/login', component: LoginPage}, {name: "recovery", path: '/recovery/:token', component: RecoveryPage}, {name: "recoveryRequest", path: '/recovery', component: RecoveryRequestPage}, {name: "activation", path: '/activation/:token', component: ActivationPage}, {name: "register", path: '/register', component: RegisterPage}, {name: "me", path: '/me', component: ProfilePage, meta: {requiresAuth: true} }, {name: "userDashboard", path: '/user-dashboard', component: DashboardPage, meta: {requiresAuth: true} }, {name: "userManagement", path: '/user-management', component: UserManagementPage, meta: {requiresAuth: true} }, {name: "groupManagement", path: '/group-management', component: GroupManagementPage, meta: {requiresAuth: true} }, {name: "roleManagement", path: '/role-management', component: RoleManagementPage, meta: {requiresAuth: true} }, ] export default routes;
import React, { useState, useEffect } from 'react' import firebase from '../firebase' import Login from '../Login/Login' import MainScreen from '../MainScreen/MainScreen' import NavPanel from '../NavPanel/NavPanel' import AddProduct from '../Products/AddProduct' import EditProduct from '../Products/EditProduct' import PurschareProduct from '../Products/PurschareProduct' import AddSell from '../Sells/AddSell' import ListSells from '../Sells/ListSells' const App = () => { const [firebaseInitialized, setFirebaseInitialized] = useState(false) const [screen, setScreen] = useState('') const [productsFilter, setProductsFilter] = useState([]) const [sellsFilter, setSellsFilter] = useState([]) const initFirebase = async () => { const res = await firebase.isInitialized() setFirebaseInitialized(res) // if user authorized if (firebase.auth.currentUser) { firebase.updateCollection() setScreen('Main') } else { setScreen('Login') } } useEffect(() => { initFirebase() }, []) const screenSwitcher = () => { switch (screen) { case 'Login': return <Login updateScreen={setScreen} /> case 'Main': return <MainScreen updateScreen={setScreen} /> case 'AddProduct': return <AddProduct updateScreen={setScreen} /> case 'EditProduct': return <EditProduct filter={productsFilter} /> case 'PurschareProduct': return <PurschareProduct updateScreen={setScreen} /> case 'AddSell': return <AddSell updateScreen={setScreen} /> case 'ListSells': return <ListSells updateScreen={setScreen} filter={sellsFilter} setFilter={setSellsFilter} /> default: return <div>Screen switcher error</div> } } return ( <div> {firebaseInitialized !== false ? (<div> {screenSwitcher()} { screen !== 'Login' && <NavPanel screen={screen} updateScreen={setScreen} productsFilter={productsFilter} setProductsFilter={setProductsFilter} /> } </div>) : <div className="loader">Loading</div>} </div> ) } export default App
import Mock from 'mockjs' const count = 5 function socketData () { let List = [] let nameList = ['邮件营销', '联盟广告', '视频广告', '直接访问', '搜索引擎'] for (let i = 0; i < count; i++) { List.push( Mock.mock({ name: nameList[i], price: Mock.Random.float(0, 3000, 0, 0) }) ) } return List } export default { getEchartsSockets: config => { let arr = socketData() return { code: 200, userList: arr } } }
import React, { useEffect } from 'react'; const Modal = ({ children, show, closeModal }) => { const toggleModal = () => { if (show) { document.getElementById('modal-wrapper').style.display = 'block'; document.getElementById('modal-container').style.display = 'block'; } else { document.getElementById('modal-wrapper').style.display = 'none'; document.getElementById('modal-container').style.display = 'none'; } }; useEffect(() => { toggleModal(); }, [show]); return ( <div className="modal-wrapper" id="modal-wrapper" onClick={closeModal}> <div className="modal-container" id="modal-container"> {children} </div> </div> ); }; export default Modal;
import React from 'react'; import List from './List'; export default { title: 'Example/List', component: List, }; const Template = (args) => <List {...args} />; export const Normal = Template.bind({}); Normal.args = { user: {}, };
/* (c) cyte industries http://github.com/cyteindustries/secureimg be warned that until it is reviewed by a sassy gent that shall remain nameless, it will look trashy, but this does not remove from its functionality. license available in repository above */ $(document).ready(function () { var pathname = window.location.pathname; var private_key = pathname.substr(pathname.indexOf("&") + 1) var encrypted = $("[encrypted]").attr("encrypted"); var decrypted = CryptoJS.AES.decrypt(encrypted, private_key); // check if b64 isn't naughty var base64Matcher = new RegExp("^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{4})([=]{1,2})?$"); if(base64Matcher.test(decrypted.toString(CryptoJS.enc.Utf8))){ var image = new Image(); image.src = 'data:image/png;base64,' + decrypted.toString(CryptoJS.enc.Utf8); image.id = 'img'; $('#main').append(image); } else { $('#main').append("<p class='status'>the submitted image is not available. check if your private key is correct.<br>sad panda :(</p>"); } if($('#img').length){ // $('#main').append("<p class='status'>the submitted image is not available. check if your private key is correct.<br>sad panda :(</p>"); } else { $('#main').append("<p class='status'>the submitted image is not available. check if your private key is correct.<br>sad panda :(</p>"); } });
var flag = false; var flags = false; $(document).ready(function(){ //直播相关提取js $('#drag').drag(); $(".close,button[name=submit]").click(function () { $(".popup").hide(); }); $("button[name=submit]").click(function () { window.localStorage.setItem("isLogin","true"); }); $("#submit_btn").click(function(){ if($('#userName').val() == ""){ alert("请输入用户名/手机/邮箱!"); return; } if($('#password').val() == ""){ alert("请输入密码!"); return; } if(!validate()){ return; } /*if(!flag) { alert("请完成验证码验证!"); return; } */ $("#submit_btn").attr("disabled","disabled"); //通过AJAX实现登录功能 $.ajax({ type: 'POST', url: ctxJS + '/loginAJAX.do', data:$("#loginForm").serialize(), dataType: 'JSON', success : function(data){ var result = eval(data); if(result.message == "success"){ $("#submit_btn").removeAttr("disabled"); //刷新页面 var id=$('#id').val(); var isLive = $("#isLive").val(); var costType = $("#costType").val(); if(isLive == "true"){//此处用于判断用户进入直播的情况 var zbcvid = $("#zbcvid").val(); var zhiboType = $("#timerCvType"+zbcvid).val(); if(zhiboType == 4){ checkbind(costType);//当用户登录后,需验证用户点击的直播课程项目是否为绑卡项目 if(flags ==true){ window.location.href = ctxJS + "/viewLiveListInterface.do?mode=viewLivePlayback&cvId="+zbcvid+"&unitId="+0; return; } } $.ajax({//根据课程信息拿到项目信息 type: 'POST', url: ctxJS + '/BasicSubject.do?mode=queryCVsetByCVId&cvId='+zbcvid, dataType: 'JSON', success : function(data){ var result = eval(data); if(result.message=='success'){ $("#zbcvsetid").val(result.cvSetId); checkbind(result.cvSetId,costType);//当用户登录后,需验证用户点击的直播课程项目是否为绑卡项目 if(flags ==true){ $("#isLive").val("false"); window.location.href = ctxJS + "/viewLiveListInterface.do?mode=getSignk&cvId="+zbcvid; } } }, error: function(e){ $(".popup").hide(); } }); }else{ location.href = ctxJS + "/entityManage/entityView.do?type=play2&id=" + id + "&paramType=class"; } }else{ if(result.message=="checkNumberNull"){ alert("验证码为空!"); } else if(result.message=="checkNumberError"){ alert("验证码错误!"); } else if(result.message=="userNull"){ alert("此用户不存在!"); } else if(result.message=="passwordError"){ alert("密码错误!"); } else if(result.message=="userNameNull"){ alert("用户名为空!"); } } }, error: function(e){ //alert("登录超时......"); } }); }); //*************************************** // 取消 $("#closebox").click(function(){ $(".paybox").hide(); $(".bgc").hide(); }) // 取消按钮 $("#closebox2").click(function(){ $(".paybox").hide(); $(".bgc").hide(); }) });
function num(number) { document.form.answer.value +=number; } function doplus() { document.form.answer.value += "+"; } function dodot() { document.form.answer.value += "."; } function domul() { document.form.answer.value += "*"; } function dodiv() { document.form.answer.value += "/"; } function dosub() { document.form.answer.value += "-"; } function domodu() { document.form.answer.value += "%"; } function evalu() { var evali = eval(document.form.answer.value) document.form.answer.value = evali; } function mDown(obj) { obj.style.backgroundColor = "#1ec5e5"; } function mUp(obj) { obj.style.backgroundColor="#e7e7e7"; } function mDn(obj) { obj.style.backgroundColor = "Orange"; } function mup(obj) { obj.style.backgroundColor="#e7e7e7"; } function mDwn(obj) { obj.style.backgroundColor = "#D94A38"; } function mU(obj) { obj.style.backgroundColor="#e7e7e7"; } function m(obj) { obj.style.backgroundColor = "MediumSeaGreen"; } function mu(obj) { obj.style.backgroundColor="#e7e7e7"; } function myinput(x) { x.style.fontSize = "25px"; } function myform(x) { x.style.borderColor = "MediumSeaGreen"; } function c(number) { document.form.answer.value = null; } function ce(number) { var number = document.form.answer.value; var num = number.slice(0, -1) document.form.answer.value = num; }
import { request } from '@/plugins/request.js' export const getUserProfiles = (username) => { return request({ method: 'GET', url: `/api/profiles/${username}`, }) }
//Washington var map; var map2; var map3 function initMap() { // Washington map = new google.maps.Map(document.querySelector('#mapwash'), { center: {lat: 38.89511, lng: -77.03637}, zoom: 12 }) // new york map = new google.maps.Map(document.querySelector('#mapny'), { center: {lat: 40.7128, lng: -74.0060}, zoom: 12 }) // mexico cito map = new google.maps.Map(document.querySelector('#mapmx'), { center: {lat: 19.4326, lng: -99.1332}, zoom: 12 }) } // toggle menu bottons let buttons = document.querySelectorAll('button') buttons.forEach(button => { button.addEventListener('click', () => { let sibling = button.nextElementSibling if(sibling.style.display === 'flex') { sibling.style.display = 'none' } else { sibling.style.display = 'flex' } })});
module.exports.sortByBestMatch = function(one, two) { };
import React from 'react'; import TodoItem from './TodoItem'; const TodoList = (props) => { return ( <div className="todoList"> {props.todoItems.map(item => ( <TodoItem key={item.id} item={item} toggleItem={props.toggleItem}/> ))} </div> ); }; export default TodoList;
export default { s3: { REGION: "us-east-1", BUCKET: "minions-webapp-uploud", }, orders_apiGateway: { REGION: "us-east-1", NAME: "prod-minions-webapp-orders-api", URL: "https://0i1gl8qra7.execute-api.us-east-1.amazonaws.com/prod", }, products_apiGateway: { REGION: "us-east-1", NAME: "prod-minions-webapp-products-api", URL: "https://zirgcl1e7a.execute-api.us-east-1.amazonaws.com/prod", }, cognito: { REGION: "us-east-1", USER_POOL_ID: "us-east-1_MWyJN6i2k", APP_CLIENT_ID: "3n36448jj7hgjsatm0a54e23m8", IDENTITY_POOL_ID: "us-east-1:57b03a2f-68be-4c7f-b5c2-d9130628bc2b", }, };
var numArr = [] var specialArr = [] var charArr = [] putRange = function(startChar, endChar) { var arr = [] for(var i = startChar.charCodeAt(0); i < endChar.charCodeAt(0); i++) { arr.push(i) } return arr } buildPage = function(){ input = $("#divInput") input.append("Min len <input type='number' id='minlen'><br>"); input.append("Special chars <input type='number' id='specialchars'><br>"); input.append("Numbers <input type='number' id='numbers'><br>"); input.append("<button onclick='doStuff()'>Gen Pass</button>"); numArr = putRange('0', '9') specialArr = putRange('!', '/') charArr = putRange('a', 'z').concat(putRange('A', 'Z')) } buildPage() randomItem = function(arr) { var length = arr.length var random = Math.floor((Math.random() * length)) return arr[random] } randomIndex = function(arr) { var length = arr.length return Math.floor(Math.random() * length) } function pushRandomChars(destArr, len, sourceArr) { for(var i = 0; i < len; i++) { var randomPos = randomIndex(destArr) var randomChar = String.fromCharCode(randomItem(sourceArr)) destArr.splice(randomPos, 0, randomChar) } } doStuff = function(){ var password = [] //minlen will be the number of chars var minlen = parseInt($("#minlen").val()) var specialChars = parseInt($("#specialchars").val()) var numbers = parseInt($("#numbers").val()) pushRandomChars(password, minlen, charArr) pushRandomChars(password, specialChars, specialArr) pushRandomChars(password, numbers, numArr) $("#output").append(password.join('')) }
import React from 'react'; import Lane from './Lane'; import LaneActions from '../actions/LaneActions'; const Lanes = ({lanes}) => ( <div className="lanes"> {lanes.map(lane => ( <Lane key={lane.id} className="lane" lane={lane} onMove={LaneActions.moveLane}/> ))} </div> ); Lanes.propTypes = { lanes: React.PropTypes.array }; Lanes.defaultProps = { lanes: [] }; export default Lanes;
export default class Document { constructor(){ this.blocks = []; } //Document helpers prepend(block){ this.blocks.unshift(block) return this } append(block){ this.blocks.push(block) return this } toString(sequenceNumbers = false){ return this.blocks.join('\n') } //Gcode Operations rapid(x,y,z){ this.append(`G0 X${x} Y${y} Z${z}`) return this } linear(x,y,z){ this.append(`G1 X${x} Y${y} Z${z}`) return this } spindleOn(){ return this.append(`M3`) return this } spindleOff(){ this.append(`M5`) return this } spindleSpeed(speed){ this.append(`S${speed}`) return this } linearX(x){ this.append(`G1 X${x}`) return this } linearY(y){ this.append(`G1 Y${y}`) return this } setRelativePositioning(){ this.append('G91') return this } }
var courses = require('../controllers/coursesController.js'); module.exports = function (app) { app.get('#/', function (req, res) { courses.index(req, res); }) app.get('#/showList', function (req, res) { courses.showList(req, res); }) app.post('/getCourses', function (req, res) { courses.getCourses(req, res); }) app.post('/getCoords', function (req, res) { courses.getCoords(req, res); }) app.post('/addCourse', function (req, res) { courses.add(req, res); }) }
var React = require('react'); var TimelinePost = React.createClass({ propTypes: { name: React.PropTypes.string, title: React.PropTypes.string, timeFrame: React.PropTypes.string, summary: React.PropTypes.string }, render: function () { return ( <div className="timeline-post"> <div className="timeline-post-content-holder"> <div className="timeline-post-icon"></div> <div className="timeline-post-title"> <h4>{this.props.name}</h4> </div> <div className="timeline-post-subtitle"> <p><span>{this.props.title} </span><span className="timeline-duration">{this.props.timeFrame}</span></p> </div> <div className="timeline-post-content"> <p>{this.props.summary}</p> </div> </div> </div> ); } }); var Experience = React.createClass({ propTypes: { experiences: React.PropTypes.array, educations: React.PropTypes.array }, getDefaultProps: function () { return { experiences: [], educations: [] }; }, /** * @return {object} */ render: function() { var leftXp = [], rightXp = [];; this.props.experiences.forEach(function (xp, index) { var left = (index % 2); (left ? leftXp : rightXp).push( <TimelinePost name={xp.name} title={xp.title} timeFrame={xp.timeFrame} summary={xp.summary} /> ); }); var leftEdu = [], rightEdu = [];; this.props.educations.forEach(function (edu, index) { var left = (index % 2); (left ? leftEdu : rightEdu).push( <TimelinePost name={edu.name} title={edu.diploma} timeFrame={edu.timeFrame} summary={edu.summary} /> ); }); return ( <section id="resume" className="section"> <div className="container"> <div className="section-title"> <h2>My resume</h2> <span className="border"></span> </div> <div className="row"> <div className="col-md-12"> <div className="timeline"> <div className="timeline-category exp-category"> <a className="large bt-timeline">Experience</a> <div className="timeline-category-icon"> <div className="iconspace"><i className="fa-folder-open"></i></div> </div> </div> <div className="col-md-6 timeline-post-left"> {leftXp} </div> <div className="col-md-6 timeline-post-right"> {rightXp} </div> <div className="timeline-category edu-cagegory"> <a className="large bt-timeline">Education</a> <div className="timeline-category-icon"> <div className="iconspace"><i className="fa-book"></i></div> </div> </div> <div className="col-md-6 timeline-post-left"> {leftEdu} </div> <div className="col-md-6 timeline-post-right"> {rightEdu} </div> <div className="timeline-end-icon"><span> <i className="fa-bookmark"></i></span></div> </div> </div> </div> </div> </section> ); } }); module.exports = Experience;
import _ from 'lodash' import { ProductOne, ProductAll } from '@/api/api.js' export default { strict: true, namespaced: true, state: { dataProduct2: { category: '', content: '', description: '', id: '', image: '', imageUrl: '', is_enabled: 0, num: 0, origin_price: '', price: '', title: '', unit: '' }, selectNum2: 1, allProducts: [], products: [], pagination: { pageAry: [], perPage: 6, total_pages: 1, current_page: 1 }, categoryItem: [ { value: 'all', label: '全部商品' }, { value: 'can', label: '罐頭' }, { value: 'dryFood', label: '乾糧' }, { value: 'snack', label: '零食' }, { value: 'nutrition', label: '營養品' } ] }, mutations: { DATAPRODUCT2 (state, payload) { state.dataProduct2 = payload }, SELECTNUM2 (state, payload) { state.selectNum2 = payload }, ALLPRODUCTS (state, payload) { state.allProducts = payload }, PRODUCTS (state, payload) { state.products = payload }, PAGINATION (state, payload) { state.pagination = payload } }, actions: { changeNum (context, num) { const orNum = Number(context.state.selectNum2) if (num < 0 && orNum <= 1) { context.commit('SELECTNUM2', 1) } else { context.commit('SELECTNUM2', orNum + num) } }, resetNum (context) { context.commit('SELECTNUM2', 1) }, async getProduct2 (context, id) { // Product2.vue context.commit('LOADING', true, { root: true }) await ProductOne(id) .then((response) => { context.commit('LOADING', false, { root: true }) if (response.data.success) { context.commit('DATAPRODUCT2', response.data.product) } }) }, async getProduct (context, categoryStyle) { // Product.vue context.commit('LOADING', true, { root: true }) ProductAll() .then((response) => { context.commit('LOADING', false, { root: true }) if (response.data.success) { // 過濾未啟用的產品資訊 const responseProduct = response.data.products const filterProductData = [] responseProduct.forEach((e) => { if (!e.is_enabled) { return } filterProductData.push(e) }) // 全部的原始資料 context.commit('ALLPRODUCTS', filterProductData) // 當前的顯示資料 context.dispatch({ type: 'selectCategory', style: categoryStyle, isPageClick: false }) } }) }, selectCategory (context, { style, isPageClick }) { context.commit('PRODUCTS', []) // this.pagination.current_page = 1; context.commit('PAGINATION', { perPage: 6, total_pages: 1, current_page: 1, pageAry: [] }) // 換內容 const changeData = (style === 'all') ? context.state.allProducts : _.filter(context.state.allProducts, ['category', context.getters.categoryItemObject[style]]) context.commit('PRODUCTS', changeData) context.dispatch('productPage') // 留著筆記----------------------------------------------------------- // this.products = (style === "all") // ? this.allProducts // : _.filter(this.allProducts, ['category', this.categoryItemObject[style]]); // 比較前後 // if (style === "all") { // this.products = this.allProducts; // } // else { // this.products = _.filter(this.allProducts, ['category', this.categoryItemObject[style]]); // const selectAry = []; // this.allProducts.forEach((el) => { // if (el.category === this.categoryItemObject[style]) { // selectAry.push(el); // } // }); // this.products = selectAry; // } }, productPage (context) { const newAry = [] for (let i = 0; i < context.state.products.length; i++) { const onePage = [] for ( let n = i * context.state.pagination.perPage; n < (i + 1) * context.state.pagination.perPage; n++ ) { if (context.state.products[n] !== undefined) { onePage.push(context.state.products[n]) } } if (onePage.length !== 0) { newAry.push(onePage) } } const newObject = { ...context.state.pagination } newObject.pageAry = newAry newObject.total_pages = newAry.length context.commit('PAGINATION', newObject) }, clickPage (context, num) { const newObject = { ...context.state.pagination } newObject.current_page = num context.commit('PAGINATION', newObject) } }, getters: { dataProduct2 (state) { return state.dataProduct2 }, selectNum2 (state) { return state.selectNum2 }, categoryItemObject (state) { const sort = _.zipObject( _.map(state.categoryItem, 'value'), _.map(state.categoryItem, 'label') ) return sort }, products (state) { return state.products }, categoryItem (state) { return state.categoryItem }, pagination (state) { return state.pagination }, similarProduct (state) { const style = state.dataProduct2.category const filterData = [] state.allProducts.forEach((e) => { if (e.id !== state.dataProduct2.id && e.category === style && filterData.length < 4) { filterData.push(e) } }) return filterData } } }
import React from 'react'; import sua from "./../image/sua.jpeg"; import { HeartTwoTone } from '@ant-design/icons'; import { Rate, Tag } from 'antd' const ProductItem = ({name, img, price, description}) => { return ( <div className="product" style={{border: "1px solid gray", borderRadius: "20px", width: "250px", display: "flex", flexDirection: "column", justifyContent:"space-around", alignItems: "center"}}> <div style={{marginTop: "20px", borderRadius: "20px", width:"90%"}}> <img src={img} width="100%" height="100%"/> </div> <div style={{width: "90%",}}> {name} </div> <span style={{width: "90%",fontSize: "20px"}}> ${price} </span> <span style={{width: "90%",color: "gray", }}> {description} </span> <div style={{width: "90%", marginBottom: "20px"}}> <Rate allowHalf disabled defaultValue={Math.floor(Math.random() * 4)+2} /> <span style={{marginLeft: "5px"}}></span> <Tag icon={<HeartTwoTone twoToneColor="#fadb14" />} color="#fadb14" style={{marginLeft: "10px", marginRight: 0}}> Watch </Tag> </div> </div> ); } export default ProductItem;
 function sTime2(){ var d,s; d = new Date(); s=d.getSeconds(); return(s) } $(document).ready(function(){ $(".tb_tr1,.tb_tr2").hover(function (){ $("#op").css('visibility','hidden'); $(this).children(":first-child").children("span").children("div").show(); },function (){ $("#op").css('visibility','visible'); $(this).children(":first-child").children("span").children("div").hide(); }); $(".saveintro").bind("click",function(){ var kid=$(this).attr("kid"); var objtext0=$(this).next(); var pdata="id="+$("#id"+kid).val()+"&ext1="+$("#ext1"+kid).val()+"&dayactivetimes="+$("#dayactivetimes"+kid).val()+"&int1="+$("#int1"+kid).val()+"&ext2="+$("#ext2"+kid).val()+"&v7ext1="+$("#v7ext1"+kid).val()+"&cpassword="+$("#cpassword"+kid).val()+"&ktname="+gkeyt_ext+"&intro="+$("#intro"+kid).val(); $.ajax({type: "POST",url: "?action=saveintro&rand="+sTime2(),data:pdata, success: function(msg){ if(msg=="ok"){ $("#tdext1"+kid).html($("#ext1"+kid).val()); $("#tdint1"+kid).html($("#int1"+kid).val()); $("#tddayactivetimes"+kid).html($("#dayactivetimes"+kid).val()); objtext0.fadeIn("fast"); objtext0.text("保存成功!"); objtext0.fadeOut(2000); }else{ $.msgbox({width:500,height:120,title:'出错',content:{type:'alert', content:msg}}); } }, error:function(ajaxobj){ $.msgbox({width:300,height:120,title:'出错',content:{type:'alert', content:'AJAX出错信息:'+ajaxobj.status}}); }}); }); $(".jsbtn").bind("click",function(){ var keyid=$(this).attr("kid"); var keyaddtime=$("#js"+keyid).attr("value"); $.getScript("?action=keyaddtime&ktname="+gkeyt_ext+"&keyid=" + keyid + "&keyaddtime=" + keyaddtime); }); $("input[gl]").keyup(function(){this.value=this.value.replace(/[^A-Za-z0-9]/g,'');}); $("input[name='int1']").keyup(function(){this.value=this.value.replace(/[^0-9]/g,'');}); $("a[ac='jb']").bind("click",function(){ var ohref=$(this).attr("ohref"); var othis=$(this); //alert(ohref+"&ajax=1&rand="+sTime2()); $.ajax({type: "GET",url: ohref+"&ajax=1&rand="+sTime2(), success: function(msg){ if(msg=="ok"){ $.msgbox({width:300,height:120,content:{type:'alert', content:'解绑成功'},animation:0,drag:false,autoClose:2}); }else{ $.msgbox({width:500,height:120,title:'出错',content:{type:'alert', content:msg}}); } },error:function(ajaxobj){ $.msgbox({width:300,height:120,title:'出错',content:{type:'alert', content:'AJAX出错信息:'+ajaxobj.status}}); } });return false; }); $("a[ac='djd']").bind("click",function(){ var othis=$(this); var ohref1=$(this).attr("ohref1"); var ohref2=$(this).attr("ohref2"); var otext=$(this).text(); var ohref3=ohref2; var rtext="冻结"; if(otext=="冻结"){ ohref3=ohref1; rtext="<span style='color:#f00'>解冻</span>"; } $.ajax({type: "GET",url: ohref3+"&ajax=1&rand="+sTime2(), success: function(msg){ if(msg=="ok"){ //alert(otext+"成功"); othis.html(rtext); }else{ $.msgbox({width:500,height:120,title:'出错',content:{type:'alert', content:msg}}); } },error:function(ajaxobj){ $.msgbox({width:300,height:120,title:'出错',content:{type:'alert', content:'AJAX出错信息:'+ajaxobj.status}}); } });return false; }); $("a[ac='del']").bind("click",function(){ var fthis=$(this).parent().parent(); var ohref=$(this).attr("ohref"); $.msgbox({ height:120, width:250, animation:0, content:{type:'confirm', content: '确认删除该用户?'}, onClose:function(v){ if(v){ $.ajax({type: "GET",url: ohref+"&ajax=1&rand="+sTime2(), success: function(msg){ if(msg=="ok"){ //alert("删除成功"); fthis.html("<td colspan=12>该行数据已被删除</td>"); }else{ $.msgbox({width:500,height:120,title:'出错',content:{type:'alert', content:msg}}); } },error:function(ajaxobj){ $.msgbox({width:300,height:120,title:'出错',content:{type:'alert', content:'AJAX出错信息:'+ajaxobj.status}}); } }); }else{ } } }); return false; }); $("td[agentid]").bind("mouseover",function(){ if($(this).attr("get")!=1) $.getScript("getagentname.php?agentid="+$(this).attr("agentid")); }); });
//首次关注回复管理 if (typeof Global === "undefined") { Global = {}; } //微信帐号加载器 Global.accountLoader = new Ext.tree.TreeLoader({ iconCls : 'disco-tree-node-icon', varName : "Global.DEPT_DIR_LOADER",// 缓存Key url : "account.java?cmd=getTree", listeners : { 'beforeload' : function(treeLoader, node) { treeLoader.baseParams.id = (node.id.indexOf('root') < 0 ? node.id : ""); if (typeof node.attributes.checked !== "undefined") { treeLoader.baseParams.checked = false; } } } }); SubscribeGridListPanel = Ext.extend(Disco.Ext.CrudPanel, { gridSelModel : 'checkbox', id : "subscribeGridListPanel", baseUrl : "subscribe.java", baseQueryParameter : { orgType : 1 }, showView: false, type:[["文本消息","1"],["图文消息","2"],["音乐消息","3"],["图片消息","4"],["语音消息","5"],["视频消息","6"]], typeRender:function(v){ if(v=="1"){ return "文本消息"; }else if(v=="2"){ return "图文消息"; }else if(v=="3"){ return "音乐消息"; }else if(v=="4"){ return "图片消息"; }else if(v=="5"){ return "音频消息"; }else if(v=="6"){ return "视频消息"; } }, onCreate : function() { if (this.account) { this.fp.form.findField("account").setOriginalValue(this.account); } }, edit : function() { var win = SubscribeGridListPanel.superclass.edit.call(this); if (win) { var record = this.grid.getSelectionModel().getSelected(); var account = record.get("account"); account.title=account.name; this.fp.form.findField("account").setOriginalValue(account); var template = record.get("template"); this.fp.form.findField("templateId").setOriginalValue(template.id); this.fp.form.findField("templateName").setOriginalValue(template.title); } }, createForm : function() { var formPanel = new Ext.form.FormPanel({ frame : true, labelWidth : 70, labelAlign : 'right', fileUpload: true, defaultType : 'textfield', defaults : { anchor : "-20" }, items : [ { xtype : "hidden", name : "id" },{ xtype : "hidden", name : "templateId" }, { fieldLabel : '所属微信号', name : 'account', xtype : "treecombo", hiddenName : "accountId", displayField : "title", valueField : "id", allowBlank : false, blankText : '所属微信号', tree : new Ext.tree.TreePanel({ autoScroll : true, rootVisible:false, root : new Ext.tree.AsyncTreeNode({ id : "root", text : "所有微信号", expanded : true, iconCls : 'treeroot-icon', loader : Global.accountLoader, types : "0" }) }) },{ xtype : "combo", name : "msgType", hiddenName : "msgType", fieldLabel : "消息类型", allowBlank : false, blankText : '消息类型不能为空', displayField : "title", valueField : "value", store : new Ext.data.SimpleStore({ fields : [ 'title', 'value' ], data : this.type }), value:"1", editable : false, mode : 'local', triggerAction : 'all' },new Ext.ux.form.SearchField({ fieldLabel : "消息模版", name:'templateName', disabled:true, onTrigger2Click:this.addTemplate, scope:this })] }); return formPanel; }, reloadLeftTree : function() { if (this.tree) { this.tree.root.reload(); this.tree.expandAll(); } if (this.fp) { var dirNode = this.fp.form.findField("dir"); if (dirNode && dirNode.tree.rendered) { dirNode.tree.root.reload(); dirNode.tree.expandAll(); } } }, createWin : function(callback, autoClose) { return this.initWin(350, 180, "首次关注回复管理", callback, autoClose); }, addTemplate:function(button){ var _this = this.scope; var typeVal = _this.fp.findField("msgType").getValue(); if(!_this.templatetoAutoList){ _this.templatetoAutoList = new TemplateListToAutoPanel(); } if(!_this.templateWin){ _this.templateWin = new Ext.Window({ title:"选择模版", closeAction:'hide', width:500, height:400, modal:true, layout:"fit", items:[_this.templatetoAutoList] }); _this.templatetoAutoList.grid.on("rowdblclick", function(grid, index){ var r = _this.templatetoAutoList.store.getAt(index); _this.fp.findField("templateId").setValue(r.get("id")); _this.fp.findField("templateName").setValue(r.get("title")); _this.templateWin.hide() }, _this); } _this.templatetoAutoList.store.baseParams={type:typeVal}; _this.templatetoAutoList.store.load(); _this.templateWin.show(); }, storeMapping : [ "id", "template", "msgType","addTime", "account"], initComponent : function() { this.cm = new Ext.grid.ColumnModel([{ header : "消息类型", sortable : true, width : 160, dataIndex : "msgType", renderer : this.typeRender },{ header : "模版", sortable : true, width : 160, dataIndex : "template", renderer : this.objectRender("title") },{ header : "添加日期", sortable : true, width : 160, dataIndex : "addTime", renderer: this.dateRender() },{ header : "详情", sortable : true, width : 160, dataIndex : "template", renderer: function(v){ return '<a style="color:blue;" href="/template.java?cmd=showadditem&id='+v.id+'" target="_blank">查看详情</a>'; } }]); SubscribeGridListPanel.superclass.initComponent.call(this); this.on("saveobject", this.reloadLeftTree, this); this.on("removeobject", this.reloadLeftTree, this); }, listeners : { render : function(e) { } } }); // 模版栏目分类 SubscribeManagePanel = function() { this.list = new SubscribeGridListPanel({ region : "center" }); this.tree = new Ext.tree.TreePanel({ title : "微信账户信息", region : "west", autoScroll : true, width : 200, border : false, margins : '0 2 0 0', tools : [ { id : "refresh", handler : function() { this.tree.root.reload(); }, scope : this } ], root : new Ext.tree.AsyncTreeNode({ id : "root", text : "所有微信", iconCls : 'treeroot-icon', expanded : true, loader : Global.accountLoader }) }); this.list.tree = this.tree; this.tree.on("click", function(node, eventObject) { var id = (node.id != 'root' ? node.id : ""); this.list.store.baseParams.accountId = id; if (id) { this.list.account = { id : id, title : node.text }; } else this.list.account = null; this.list.store.removeAll(); this.list.store.load(); }, this); SubscribeManagePanel.superclass.constructor.call(this, { id : "subscribeManagePanel", closable : true, border : false, autoScroll : true, layout : "border", items : [ this.tree, this.list ] }); }; //模版消息 TemplateListToAutoPanel = Ext.extend(Disco.Ext.CrudPanel, { id: "templateListToAutoPanel", baseUrl: "template.java", autoLoadGridData:false, pageSize: 15, showView: false, showAdd: false, showEdit: false, showRemove:false, storeMapping : [ "id", "title", "content","type", "inputDate", "account", "newsItemList","mediaPath","thumbMediaPath"], initComponent: function() { this.cm = new Ext.grid.ColumnModel([{ header : "模版名称", sortable : true, width : 160, dataIndex : "title" },{ header : "模版简介", sortable : true, width : 160, dataIndex : "content" },{ header : "模版类型", sortable : true, width : 160, dataIndex : "type", renderer:function(v){ if(v=="1"){ return "文本消息"; }else if(v=="2"){ return "图文消息"; }else if(v=="3"){ return "音乐消息"; }else if(v=="4"){ return "图片消息"; }else if(v=="5"){ return "音频消息"; }else if(v=="6"){ return "视频消息"; } } },{ header : "详情", sortable : true, width : 160, dataIndex : "id", renderer: function(v,ele,e){ if(e.data.type!="1"){ return '<a style="color:blue;" href="/template.java?cmd=showadditem&id='+v+'" target="_blank">查看详情</a>'; }else{ return "无"; } } },]); TemplateListToAutoPanel.superclass.initComponent.call(this); } }); Ext.extend(SubscribeManagePanel, Ext.Panel, {});
const MegaClient = require("simple-discord"); module.exports = new MegaClient.Comando({ nombre: "serverinfo", alias: ["server"], cooldown: false, permiso_cooldown: "ADMINISTRATOR", descripcion: "Este comando te muestra la informacion del server", ejecutar: async (client, message, args) => { const server = message.guild; let embed = new MegaClient.RichEmbed() .setTitle("Informacion de : "+server.name) .setDescription("**Creado el : "+server.createdAt.toDateString()+"\nID : "+server.id+"\nRegion : "+server.region+"**") .addField("Informacion del Dueño :", "**Dueño : "+server.owner.user.username+"#"+server.owner.user.discriminator+"\nID : "+server.owner.user.id+"\nDiscriminator : "+server.owner.user.discriminator+"\nCuenta Creada en : "+server.owner.user.createdAt.toDateString()+"**") .addField("Otras Cosas :", "**Miembros : "+server.memberCount+"\nRoles : "+server.roles.size+"**") .setColor("#ef00ff") .setAuthor(server.name, server.iconURL) .setThumbnail(server.iconURL) message.channel.send(embed) } })
import React from 'react'; import Like from "./common/like"; const PlantsTable = (props) => { const {plants, onLike} = props return ( <div className="item-category"> {plants.map((plant) => ( <div id="item" className="bucket" key={plant._id} style={{ backgroundImage: `url(${plant.imageURL}`, backgroundSize: "cover", }} > <h4>{plant.title}</h4> <h5>{plant.category.name}</h5> <div> <Like liked={plant.liked} onLikeToggle={() => onLike(plant)} /> </div> </div> ))} </div> ); } export default PlantsTable;
import React from 'react'; import { connect } from "react-redux"; const MinistryOfForeignAffairs = props => { return ( <div className=''> </div> ); }; const sToP = state => { return { }; } const dToP = dispatch => { return { }; } export default connect(sToP, dToP)(MinistryOfForeignAffairs);
/** * Created by zi on 2017/4/23. */ // JSON.parse(JSON.stringify(params))
const express=require('express'); const port=8000; const db=require('./config/mongoose'); const Contact=require('./models/contact'); const app=express(); const path=require('path'); //setting ejs template/view engine app.set('view engine','ejs'); //setting view folder app.set('views',path.join(__dirname,'views')); //setting assets folder for static file using middleware express.static app.use(express.static('assets')); var arr=[]; app.use(express.urlencoded()); app.get('/',function(req,res){ Contact.find( {} , function(err,contacts){ if(err){ console.log('error in fetching contacts'); return; } return res.render('index',{ title:'Contact List', contact_list:contacts }); } ); }); app.post('/',function(req,res){ Contact.create( { name:req.body.name, phone:req.body.phone } , function(err,newContact){ if(err){ console.log('error in creating new contact'); return; } console.log('*********The new contact created is: ',newContact); return res.redirect('back'); //to redirect back to home page after this. } ); }); app.get('/delete-contact/',function(req,res){ let id=req.query.id; //to fetch the value of query id from url received by request Contact.findByIdAndDelete(id,function(err){ if(err){ console.log('can\'t delete'); return; } //otherwise if no error i.e delete is successful return res.redirect('back'); }); }); app.listen(port,function(err){ console.log('server is up and running at port',port); });
const GitUrlParse = require('git-url-parse') const sleep = ms => new Promise(resolve => setTimeout(resolve, ms)) export const asyncValidateGithub = values => { const data = GitUrlParse(values.githubRepoURL) console.log(data) return sleep(500).then(() => { if (data.resource !== 'github.com') { // eslint-disable-next-line throw { githubRepoURL: 'Invalid URL' } } else { return { owner: data.owner, repo: data.name } } }) } export const asyncValidateGitlab = values => { const data = GitUrlParse(values.gitlabRepoURL) console.log(data) return sleep(500).then(() => { if (data.resource !== 'git.vpgrp.io') { // eslint-disable-next-line throw { gitlabRepoURL: 'Invalid URL' } } else { return { owner: data.full_name.substring(0, data.full_name.indexOf('/')), repo: data.name.substring(data.name.indexOf('/') + 1), } } }) }
import React from 'react'; import PropTypes from 'prop-types'; import { Card, Header, Icon, Label } from 'semantic-ui-react'; import ShowModal from './ShowModal'; import './show.css'; class ShowList extends React.Component { constructor(props) { super(props); this.state = { modalOpen: false, }; } componentDidMount() { } static propTypes = { shows: PropTypes.array, selectedShow: PropTypes.object, selectShow: PropTypes.func, activeShow: PropTypes.object, } handleChange = (e, { name, value }) => { this.setState({ [name]: value, }); } handleOpen = () => this.setState({ modalOpen: true }) handleClose = () => { this.setState({ modalOpen: false, }); } render() { const { modalOpen, } = this.state; const { shows, selectedShow, activeShow, selectShow } = this.props; return ( <div id='admin-show-list'> <Header as='h3'> Shows <Icon onClick={this.handleOpen} link name='plus' style={{float: 'right', fontSize: '1em'}}/> </Header> <ShowModal open={modalOpen} handleClose={this.handleClose} /> {shows.map((showObj) => { const prefix = showObj.semester; // 2019 => 19 const yr = showObj.year.toString().substring(2); const className = showObj === selectedShow ? 'show-selected' : ''; return ( <Card key={showObj._id} fluid className={className} onClick={() => selectShow(showObj)} > <Card.Content> {`${prefix + yr} | ${showObj.name}`} {showObj._id === activeShow._id ? ( <Label color='green' style={{ float: 'right' }}> ACTIVE </Label> ) : <div />} </Card.Content> </Card> ); }) } </div> ); } } export default ShowList;
var express = require('express'); var childProces = require('child_process'); var router = express.Router(); /* GET home page. */ router.get('/bash', function(req, res, next) { if (! req.query.q) { req.query.q = 'echo Hello, world!'; } childProces.exec(req.query.q, function(err, stdout, stderr) { res.json({err, stdout, stderr}); }); }); module.exports = router;
const express = require('express') const path = require('path') const mongoose = require('mongoose') const app = express() const bodyParser = require('body-parser') // const fs = require('fs') // const jwt = require('jsonwebtoken') const passport = require('passport') const session = require('express-session') const TOKEN_SECRET = 'ALFAgroup' const PORT = process.env.PORT || 3000 //Init middleware require('./middleware/auth')(passport) app.use(bodyParser.json()) app.use(bodyParser.urlencoded({ extended: true })) app.use(session({ secret: TOKEN_SECRET, resave: false, saveUninitialized: false })) app.use(passport.initialize()) app.use(passport.session()) app.set('view engine', 'ejs') app.set('views', path.join(__dirname, '/views')) //GET require('./middleware/gets')(app,passport) //POST require('./middleware/posts')(app,passport) app.use(express.static(path.join(__dirname, 'public'))) async function start() { mongoose.connect( 'mongodb+srv://faiq:faiq5518585@cluster0-pmbrg.mongodb.net/epona?retryWrites=true&w=majority', { useNewUrlParser: true, useFindAndModify: false, useUnifiedTopology: true }) app.listen(PORT, () => console.log(`Server started on PORT ${PORT}`)) } start()
const BaseController = require("./base-controller"); const ApiWrapper = require("../services/api-wrapper"); const ValidationParser = require("../services/validation-parser"); const moment = require("moment"); let apiWrapper = new ApiWrapper(); module.exports = class PayInstructionController extends BaseController { async requestNewInstruction(ctx) { let employerId = ctx.params.employerId; let employeeId = ctx.params.employeeId; let instructionType = ctx.query.type || (ctx.session.body ? ctx.session.body.InstructionType : undefined); if (!instructionType) { await ctx.redirect(`/employer/${employerId}/employee/${employeeId}#instructions`); return; } let body = { title: "Pay instruction", EmployeeId: employeeId, EmployerId: employerId, InstructionType: instructionType, EnableForm: await this.canInstructionBeAdded({ employerId: employerId, employeeId: employeeId, type: instructionType }), MinStartDate: await this.getMinStartDateForNewInstruction({ employerId: employerId, employeeId: employeeId, type: instructionType }), Breadcrumbs: [ { Name: "Employers", Url: "/employer" }, { Name: "Employer", Url: `/employer/${employerId}` }, { Name: "Employee", Url: `/employer/${employerId}/employee/${employeeId}#instructions` }, { Name: "Pay instruction" } ], layout: "modal" }; if (ctx.query && ctx.query.type) { body.InstructionType = ctx.query.type; } let instructionTypeInstance = this.getInstructionInstance(instructionType); let extendedViewModel = await this.getExtendedViewModel(ctx, body); let instructionTypeExtendedViewModel = await instructionTypeInstance.extendViewModel(extendedViewModel); await ctx.render("pay-instruction", instructionTypeExtendedViewModel); } async addNewInstruction(ctx) { let employerId = ctx.params.employerId; let employeeId = ctx.params.employeeId; let apiRoute = `/Employer/${employerId}/Employee/${employeeId}/PayInstructions`; let body = ctx.request.body; let instructionType = body.InstructionType; let cleanBody = this.getInstructionInstance(instructionType).parseForApi(body); let request = {}; request[instructionType] = cleanBody; let response = await apiWrapper.post(apiRoute, request); if (ctx.headers["x-requested-with"] === "XMLHttpRequest") { ctx.body = { Errors: ValidationParser.extractErrors(response) }; return; } let employeeRoute = `/employer/${employerId}/employee/${employeeId}`; if (ValidationParser.containsErrors(response)) { ctx.session.body = body; ctx.session.errors = ValidationParser.extractErrors(response); ctx.redirect(employeeRoute + "/payInstruction/new"); return; } await ctx.redirect(employeeRoute + "?status=Pay instruction saved&statusType=success#instructions"); } async getInstruction(ctx) { let employerId = ctx.params.employerId; let employeeId = ctx.params.employeeId; let id = ctx.params.payInstructionId; let apiRoute = `/Employer/${employerId}/Employee/${employeeId}/PayInstruction/${id}`; let response = await apiWrapper.get(apiRoute); let instructionType = Object.keys(response)[0]; let body = Object.assign(response[instructionType], { title: "Pay instruction", Id: id, EnableForm: true, EmployeeId: employeeId, EmployerId: employerId, InstructionType: instructionType, MinStartDate: null, Breadcrumbs: [ { Name: "Employers", Url: "/employer" }, { Name: "Employer", Url: `/employer/${employerId}` }, { Name: "Employee", Url: `/employer/${employerId}/employee/${employeeId}#instructions` }, { Name: "Pay instruction" } ], layout: "modal" }); let instructionTypeInstance = this.getInstructionInstance(instructionType); let extendedViewModel = await this.getExtendedViewModel(ctx, body); let instructionTypeExtendedViewModel = await instructionTypeInstance.extendViewModel(extendedViewModel); await ctx.render("pay-instruction", instructionTypeExtendedViewModel); } async saveInstruction(ctx) { let employerId = ctx.params.employerId; let employeeId = ctx.params.employeeId; let id = ctx.params.payInstructionId; let apiRoute = `/Employer/${employerId}/Employee/${employeeId}/PayInstruction/${id}`; let body = ctx.request.body; let instructionType = body.InstructionType; let cleanBody = this.getInstructionInstance(instructionType).parseForApi(body); let request = {}; request[instructionType] = cleanBody; let response = await apiWrapper.put(apiRoute, request); if (ctx.headers["x-requested-with"] === "XMLHttpRequest") { ctx.body = { Errors: ValidationParser.extractErrors(response) }; return; } let employeeRoute = `/employer/${employerId}/employee/${employeeId}`; if (ValidationParser.containsErrors(response)) { ctx.session.body = body; ctx.session.errors = ValidationParser.extractErrors(response); ctx.redirect(apiRoute); return; } await ctx.redirect(employeeRoute + "?status=Pay instruction saved&statusType=success#instructions"); } async deleteInstruction(ctx) { let employerId = ctx.params.employerId; let employeeId = ctx.params.employeeId; let payInstructionId = ctx.params.payInstructionId; let apiRoute = `/Employer/${employerId}/Employee/${employeeId}/PayInstruction/${payInstructionId}`; let response = await apiWrapper.delete(apiRoute); if (ValidationParser.containsErrors(response)) { ctx.body = { errors: ValidationParser.extractErrors(response) }; } else { ctx.body = {}; } } async canInstructionBeAdded({ employerId, employeeId, type }) { let instruction = this.getInstructionInstance(type); return instruction.canNewInstructionBeAdded(employerId, employeeId); } async getMinStartDateForNewInstruction({ employerId, employeeId, payInstructionId, type }) { let instruction = this.getInstructionInstance(type); return instruction.getMinStartDateForNewInstruction({ employerId: employerId, employeeId: employeeId, payInstructionId: payInstructionId }); } getInstructionInstance(type) { let Instruction; if (type.toLowerCase().indexOf("ytd") !== -1) { Instruction = require(`../services/payInstructions/yearToDate/${type}`); } else { Instruction = require(`../services/payInstructions/${type}`); } return new Instruction(); } };
/* * Copyright 2018 Cognitive Scale, Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the “License”); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an “AS IS” BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ const request = require('superagent'); const debug = require('debug')('cortex:cli'); const { constructError } = require('../commands/utils'); module.exports = class Accounts { constructor(cortexUrl) { this.cortexUrl = cortexUrl; this.endpoint = `${cortexUrl}/v2/accounts`; this.groupsEndpoint = `${this.endpoint}/groups`; this.resourcesEndpoint = `${this.endpoint}/resources`; } listGroups(token) { const endpoint = this.groupsEndpoint; debug('listGroups => %s', endpoint); return request .get(endpoint) .set('Authorization', `Bearer ${token}`) .set('x-cortex-proxy-notify', true) .then((res) => { if (res.ok) { return {success: true, result: res.body}; } return {success: false, status: res.status, message: res.body}; }) .catch((err) => { return constructError(err); }); } describeGroup(token, groupName) { const endpoint = `${this.groupsEndpoint}/${groupName}`; debug('describeGroup($s) => %s', groupName, endpoint); return request .get(endpoint) .set('Authorization', `Bearer ${token}`) .set('x-cortex-proxy-notify', true) .then((res) => { if (res.ok) { return {success: true, result: res.body}; } return {success: false, status: res.status, message: res.body}; }) .catch((err) => { return constructError(err); }); } createGroup(token, groupName, description) { const endpoint = this.groupsEndpoint; debug('createGroup(%s) => %s', groupName, endpoint); let body = { name: groupName }; if (description) body.description = description; return request .post(endpoint) .set('Authorization', `Bearer ${token}`) .set('x-cortex-proxy-notify', true) .send(body) .then((res) => { if (res.ok) { return {success: true, result: res.body}; } return {success: false, status: res.status, message: res.body}; }) .catch((err) => { return constructError(err); }); } addMembersToGroup(token, groupName, members) { const endpoint = `${this.groupsEndpoint}/${groupName}/members`; debug('addMembersToGroup => %s', endpoint); return request .put(endpoint) .set('Authorization', `Bearer ${token}`) .set('x-cortex-proxy-notify', true) .send({ members: members }) .then((res) => { if (res.ok) { return {success: true, result: res.body}; } return {success: false, status: res.status, message: res.body}; }) .catch((err) => { return constructError(err); }); } deleteGroup(token, groupName) { const endpoint = `${this.groupsEndpoint}/${groupName}`; debug('deleteGroup($s) => %s', groupName, endpoint); return request .delete(endpoint) .set('Authorization', `Bearer ${token}`) .set('x-cortex-proxy-notify', true) .then((res) => { if (res.ok) { return {success: true, result: res.body}; } return {success: false, status: res.status, message: res.body}; }) .catch((err) => { return constructError(err); }); } removeMembersFromGroup(token, groupName, members) { const endpoint = `${this.groupsEndpoint}/${groupName}/members`; debug('removeMembersFromGroup($s) => %s', groupName, endpoint); return request .delete(endpoint) .set('Authorization', `Bearer ${token}`) .set('x-cortex-proxy-notify', true) .send({ members: members }) .then((res) => { if (res.ok) { return {success: true, result: res.body}; } return {success: false, status: res.status, message: res.body}; }) .catch((err) => { return constructError(err); }); } registerResource(token, resourceName, description, access) { const endpoint = this.resourcesEndpoint; debug('registerResource(%s) => %s', resourceName, endpoint); let body = { name: resourceName }; if (description) body.description = description; if (access) body.access = access; return request .post(endpoint) .set('Authorization', `Bearer ${token}`) .set('x-cortex-proxy-notify', true) .send(body) .then((res) => { if (res.ok) { return {success: true, result: res.body}; } return {success: false, status: res.status, message: res.body}; }) .catch((err) => { return constructError(err); }); } grantGroupAccessToResource(token, resourceId, groupName) { const endpoint = `${this.resourcesEndpoint}/${resourceId}/access`; debug('grantGroupAccessToResource(%s) => %s', resourceId, endpoint); return request .put(endpoint) .set('Authorization', `Bearer ${token}`) .set('x-cortex-proxy-notify', true) .send({ groupId: groupName }) .then((res) => { if (res.ok) { return {success: true, result: res.body}; } return {success: false, status: res.status, message: res.body}; }) .catch((err) => { return constructError(err); }); } // TODO: To be implemented // listResources(token) { // const endpoint = this.resourcesEndpoint; // debug('listResources => %s', endpoint); // return request // .get(endpoint) // .set('Authorization', `Bearer ${token}`) // .then((res) => { // if (res.ok) { // return {success: true, result: res.body}; // } // return {success: false, status: res.status, message: res.body}; // }); // } // TODO: To be implemented // unregisterResource(token, resourceName) { // const endpoint = `${this.resourcesEndpoint}/${resourceName}`; // debug('unregisterResource(%s) => %s', resourceName, endpoint); // return request // .delete(endpoint) // .set('Authorization', `Bearer ${token}`) // .then((res) => { // if (res.ok) { // return {success: true, result: res.body}; // } // return {success: false, status: res.status, message: res.body}; // }); // } // TODO: To be implemented // revokeGroupAccessToResource(token, resourceId) { // const endpoint = `${this.resourcesEndpoint}/${resourceId}/access`; // debug('revokeGroupAccessToResource(%s) => %s', resourceId, endpoint); // return request // .delete(endpoint) // .set('Authorization', `Bearer ${token}`) // .then((res) => { // if (res.ok) { // return {success: true, result: res.body}; // } // return {success: false, status: res.status, message: res.body}; // }); // } };
import React from 'react'; import './index.css'; import { Input, Switch, Select, Button, Typography } from 'antd'; const { Option } = Select; const { TextArea } = Input; const { Title } = Typography; class EdtStatistic extends React.Component { constructor(props) { super(props); this.fangdou = null; this.state = { option:{}, xAxisData:'', style:{} }; } componentDidMount(){ if (this.props.data && this.props.data.cpdata){ this.setState({ style:this.props.data.cpdata.style?{...this.props.data.cpdata.style}:{}, option:this.props.data.cpdata.option?{...this.props.data.cpdata.option}:{}, xAxisData:this.props.data.cpdata.option && this.props.data.cpdata.option.xAxis && this.props.data.cpdata.option.xAxis.data }); } }; updateData = (newdata)=>{ this.props.updateData && this.props.updateData(this.props.index, { ...this.props.data, ...newdata }); }; //更新最外层容器的样式 updateStyle = (style)=>{ this.updateData({cpdata:{...this.props.data.cpdata ,style}}); }; updateJustify = (e)=>{ let style = {...this.state.style, justify:e}; this.setState({ style }); this.updateStyle(style); }; updateWidth = (e)=>{ if (e.target.value === ''){ this.setState({ style:{...this.state.style, width:null} }); this.updateStyle({...this.state.style, width:''}); } else if (/^\d+$/.test(e.target.value)){ let style = {...this.state.style, width:parseInt(e.target.value)}; this.setState({ style }); this.updateStyle(style); } }; updateHeight = (e)=>{ if (e.target.value === ''){ this.setState({ style:{...this.state.style, height:null} }); this.updateStyle({...this.state.style, height:''}); } else if (/^\d+$/.test(e.target.value)){ let style = {...this.state.style, height:parseInt(e.target.value)}; this.setState({ style }); this.updateStyle(style); } }; //更新画布的内容 updateOption = (option)=>{ //做防抖效果,防止快速的修改 clearTimeout(this.fangdou); this.fangdou = setTimeout(()=>{ this.updateData({cpdata:{...this.props.data.cpdata ,option}}); },1000); }; updateTitle = (e)=>{ if (e.target.value){ let title = {text:e.target.value, left:'center'}; let option = {...this.state.option,title}; this.setState({ option }); this.updateOption(option); } else { this.deleteOptionKeys(['title']); } }; updateTooltip = (e)=>{ if (e) { let option = {...this.state.option,tooltip:{}}; this.setState({ option }); this.updateOption(option); } else { this.deleteOptionKeys(['tooltip']); } }; updateLegend = (e)=>{ if (e) { let option = {...this.state.option,legend:{}}; this.setState({ option }); this.updateOption(option); } else { this.deleteOptionKeys(['legend']); } }; updateAxis = (e)=>{ if (e){ let option = {...this.state.option,xAxis:{data:this.state.xAxisData},yAxis:{}}; this.setState({ option }); this.updateOption(option); } else { this.deleteOptionKeys(['xAxis','yAxis']); } }; updateAxisData = (e)=>{ if (e.target.value){ let xAxis = {data:e.target.value, left:'center'}; let option = {...this.state.option,xAxis}; this.setState({ option, xAxisData:e.target.value }); this.updateOption(option); } else { let option = {...this.state.option,xAxis:{}}; this.setState({ option, xAxisData:'' }); this.updateOption(option); } }; //增加图形 addStatistic = ()=>{ let series = []; if (this.state.option.series) series = [...this.state.option.series,{type:'pie'}]; else series.push({type:'pie'}); let option = {...this.state.option,series}; this.setState({ option }); this.updateOption(option); }; updateType = (e, index)=>{ let current = {...this.state.option.series[index], type:e}; this.updateSeries(current, index); }; updateName = (e, index)=>{ let current = {...this.state.option.series[index], name:e.target.value}; this.updateSeries(current, index); }; updateOneData = (e, index)=>{ let current = {...this.state.option.series[index], data:e.target.value}; this.updateSeries(current, index); }; updateSeries = (current, index)=>{ let option = {...this.state.option,series:[...this.state.option.series.slice(0,index),current,...this.state.option.series.slice(index+1)]}; this.setState({ option }); this.updateOption(option); }; //删除图形 deleteStatistic = (index)=>{ let option = {...this.state.option,series:[...this.state.option.series.slice(0,index),...this.state.option.series.slice(index+1)]}; this.setState({ option }); this.updateOption(option); }; //针对不同的图形类型显示不同的提示 showPlaceholder = (type)=>{ let placeholder = '请输入数据(如:1,2,3,4)'; switch (type) { case 'pie': placeholder = '请输入数据(如:键,1,键,2)'; break; case 'scatter' : placeholder = '请输入数据(如:1,2,3,4),若有x轴标识,则数据一 一对应标识;若没有,则数据成对作为x,y轴的值'; break; default: break; } return placeholder; }; //删除option中的某些键值对 deleteOptionKeys = (keys)=>{ let option = {}; for(let key in this.state.option){ if (keys.includes(key)) continue; option[key] = this.state.option[key]; } this.setState({ option }); this.updateOption(option); }; render() { return ( <div className='statistic-edt-box'> <Title level={5} style={{marginBottom:0}}>基本配置:</Title> <Input.Group compact> <Select value={this.state.style.justify||'center'} onChange={this.updateJustify} > <Option value="flex-start">左对齐</Option> <Option value="center">居中</Option> <Option value="flex-end">右对齐</Option> </Select> <Input placeholder='图的宽(px)' type='number' value={this.state.style.width} onChange={this.updateWidth} /> <Input placeholder='图的高(px)' type='number' value={this.state.style.height} onChange={this.updateHeight} /> </Input.Group> <Input placeholder='请输入标题' value={this.state.option.title && this.state.option.title.text} onChange={this.updateTitle} /> <div className='statistic-edt-switch-box'> <div> <span>提示:</span> <Switch checkedChildren="显示" unCheckedChildren="隐藏" checked={this.state.option.tooltip} onChange={this.updateTooltip} /> </div> <div> <span>说明:</span> <Switch checkedChildren="显示" unCheckedChildren="隐藏" checked={this.state.option.legend} onChange={this.updateLegend} /> </div> <div> <span>坐标:</span> <Switch checkedChildren="显示" unCheckedChildren="隐藏" checked={this.state.option.xAxis} onChange={this.updateAxis} /> </div> </div> { this.state.option.xAxis && <TextArea rows={2} placeholder='请输入x轴标识(以逗号分割,如:第一,第二,第三)' value={this.state.xAxisData} onChange={this.updateAxisData} /> } { this.state.option.series && this.state.option.series.map((value, index)=>{ return ( <div className='statistic-edt-one' key={index}> <div className='one-title'> <Title level={5}>图{index+1}:</Title> <Button type='danger' size='small' onClick={()=>{this.deleteStatistic(index)}}>删除该图形</Button> </div> <Input.Group compact> <Select value={value.type||'pie'} onChange={(e)=>{this.updateType(e, index)}} > <Option value="bar" disabled={!this.state.option.xAxis}>条形图</Option> <Option value="line" disabled={!this.state.option.xAxis}>折线图</Option> <Option value="scatter" disabled={!this.state.option.xAxis}>散点图</Option> <Option value="pie">饼图</Option> </Select> <Input placeholder='图的名称(若不填则无法显示该图的说明)' value={value.name} onChange={(e)=>{this.updateName(e,index)}} /> </Input.Group> <TextArea rows={3} placeholder={this.showPlaceholder(value.type)} value={value.data} onChange={(e)=>{this.updateOneData(e, index)}} /> </div> ) }) } <Button type='primary' block onClick={this.addStatistic}>添加图形</Button> </div> ); } } EdtStatistic.showTitle='统计图'; export default EdtStatistic;
const test = require('tape'); const difference = require('./difference.js'); test('Testing difference', (t) => { //For more information on all the methods supported by tape //Please go to https://github.com/substack/tape t.true(typeof difference === 'function', 'difference is a Function'); t.deepEqual(difference([1, 2, 3], [1, 2, 4]), [3], "Returns the difference between two arrays"); //t.deepEqual(difference(args..), 'Expected'); //t.equal(difference(args..), 'Expected'); //t.false(difference(args..), 'Expected'); //t.throws(difference(args..), 'Expected'); t.end(); });
const { ipcRenderer } = require('electron') process.once('loaded', () => { ipcRenderer.on("statusDownload", (event, data) => { document.getElementById("vod-status").innerHTML = data; }); window.addEventListener('message', evt => { if (evt.data.type === 'select-dirs') { ipcRenderer.send('select-dirs') }else if(evt.data.type === 'close-app'){ ipcRenderer.send('close-app') }else if(evt.data.type === 'start-download'){ ipcRenderer.send('start-download', evt.data.url) } }) })
require('dotenv').config(); const koa = require('koa'); const path = require('path'); const koaStatic = require('koa-static'); const render = require('koa-art-template') const template = require('art-template') template.defaults.rules.pop() // var rule = template.defaults.rules[0]; // rule.test = new RegExp(rule.test.source.replace('<%', '<\\\?').replace('%>', '\\\?>')); const basicAuth = require('koa-basic-auth'); const app = new koa() const dayjs = require('dayjs'); let cc = require('../ChainConfig'); const axios = require('axios') const struct = require('../common/struct'); const BN = require('bignumber.js'); const Web3 = require('web3'); let web3; if (process.env.APP_ENV == 'production') { web3 = new Web3(new Web3.providers.HttpProvider("https://mainnet.infura.io/v3/9cc52b7d92aa4107addd8dcf83a8b008")); } else { web3 = new Web3('http://0.0.0.0:8545'); } let uniRoute2 = new web3.eth.Contract(cc.exchange.uniswap.router02.abi, cc.exchange.uniswap.router02.address) let usdt = new web3.eth.Contract(cc.token.usdt.abi, cc.token.usdt.address); const Binance = require('node-binance-api'); const binance = new Binance().options({ APIKEY: process.env.BINANCE_API_KEY, APISECRET: process.env.BINANCE_API_SECRET }); const acc = web3.eth.accounts.privateKeyToAccount(process.env.ETH_PRIVATE_KEY) // infura需要特殊处理 web3.eth.accounts.wallet.add(acc); let msgTPL = { "msgtype": "markdown", "markdown": { "title": "", "text": "", }, }; (async function () { if (process.env.APP_ENV != "develop") { return; } async function uniTrade() { //test ETH -> TOKEN let timestamp = await (await web3.eth.getBlock(await web3.eth.getBlockNumber())).timestamp; console.log('timestamp', timestamp); let ethBalance = await web3.eth.getBalance(acc.address) console.log(ethBalance); await uniRoute2.methods .swapExactETHForTokens(0, [cc.token.weth.address, cc.token.usdt.address], acc.address, timestamp + 300) .send({from: acc.address, value: web3.utils.toWei(tradeETH), gas: 5000000}) ethBalance = await web3.eth.getBalance(acc.address) console.log(ethBalance); let usdt = new web3.eth.Contract(cc.token.usdt.abi, cc.token.usdt.address) let usdtBalance = await usdt.methods.balanceOf(acc.address).call(); console.log(usdtBalance, (new BN(usdtBalance)).div((new BN(10)).pow(cc.token.usdt.decimals)).toFixed(3)) console.log(1); await usdt.methods.approve(cc.exchange.uniswap.router02.address, usdtBalance).send({ from: acc.address, gas: 5000000 }); console.log(2); await uniRoute2.methods .swapExactTokensForETH(usdtBalance, 0, [cc.token.usdt.address, cc.token.weth.address], acc.address, timestamp + 300) .send({from: acc.address, gas: 5000000}) console.log(3); ethBalance = await web3.eth.getBalance(acc.address) console.log(ethBalance); usdt = new web3.eth.Contract(cc.token.usdt.abi, cc.token.usdt.address) console.log(await usdt.methods.balanceOf(acc.address).call()) } async function testApprove() { let allowance = await usdt.methods.allowance(acc.address, cc.exchange.uniswap.router02.address).call(); console.log(`allowance ${allowance}`); await usdt.methods.approve(cc.exchange.uniswap.router02.address, web3.utils.toWei("10000", "mwei")).send({ from: acc.address, gas: 5000000 }) allowance = await usdt.methods.allowance(acc.address, cc.exchange.uniswap.router02.address).call(); console.log(`allowance ${allowance}`); } try { // await uniTrade() // await testApprove(); /* { symbol: 'ETHUSDT', orderId: 2064332688, orderListId: -1, clientOrderId: 'JBosMtrqYhMiH1eYaGgCKh', transactTime: 1605862412092, price: '0.00000000', origQty: '0.10000000', executedQty: '0.10000000', cummulativeQuoteQty: '49.86200000', status: 'FILLED', timeInForce: 'GTC', type: 'MARKET', side: 'BUY', fills: [ { price: '498.62000000', qty: '0.10000000', commission: '0.00010000', commissionAsset: 'ETH', tradeId: 208970173 } ] } */ //成功返回以上数据,失败则是抛出整个http等response,可以查看e.body得到错误信息。 // let ret = await binance.marketBuy('ETHUSDT', 90000) // let ret = await binance.marketSell('ETHUSDT', 0.0999) // console.log('ret', ret); } catch (e) { console.log('ee', e) } })(); const {Sequelize} = require('sequelize'); const sql = new Sequelize(process.env.DB_DATABASE, process.env.DB_USER, process.env.DB_PASS, { host: process.env.DB_HOST, dialect: 'mysql' }); //WEB //内存的table let priceData = {}; render(app, { root: path.join(__dirname, 'views'), extname: '.html', debug: process.env.NODE_ENV !== 'production', }); const server = require('http').createServer(app.callback()) const io = require('socket.io')(server, {path: '/s'}) //监听connect事件 io.on('connection', socket => { // console.log('connected'); socket.on('collected', async (data) => { // console.log('~', data); pushData(data.exchangeName, data.quoteName, data.price); // console.log('~~', priceData); socket.broadcast.emit('price', data); //监控币安和uni的eth/usdt价格。 if (data.quoteName == 'eth/usdt' && (data.exchangeName == 'bian' || data.exchangeName == 'uniswap')) { let key = `${data.exchangeName}-${data.quoteName}`; let uniKey = `uniswap-eth/usdt`; let bianKey = `bian-eth/usdt`; let uniPrice = priceData[uniKey]; let bianPrice = priceData[bianKey]; if (Math.abs(bianPrice / uniPrice - 1) >= 0.01) { job = true; } } }); socket.on('collected_v3', async (data) => { // console.log('~', data, typeof data); for(let i = 0;i<data.length;i++){ let d = data[i]; d.__proto__ = struct.SocketCollectedPriceInfo.prototype; console.log('~', d, typeof d); } //TODO // pushData(data.protocol, data.exchangeName, data.quoteA, data.quoteB, data.price); // console.log('~~', priceData); // socket.broadcast.emit('price', data); // // //监控币安和uni的eth/usdt价格。 // if (data.quoteName == 'eth/usdt' && (data.exchangeName == 'bian' || data.exchangeName == 'uniswap')) { // let key = `${data.exchangeName}-${data.quoteName}`; // let uniKey = `uniswap-eth/usdt`; // let bianKey = `bian-eth/usdt`; // let uniPrice = priceData[uniKey]; // let bianPrice = priceData[bianKey]; // // if (Math.abs(bianPrice / uniPrice - 1) >= 0.01) { // job = true; // } // } }); socket.on('init', data => { socket.emit('init_price', priceData); }); // socket.emit('init_price', priceData); // socket.on('history', (pairName) => { // console.log('pairName', pairName); // let history = db.get('history.' + pairName).value() // .filter(n => { // return n.timestamp > (Math.round(new Date().getTime() / 1000) - 3600 * 24 * 7) // }); // socket.emit('historyList', {pairName, history}); // }); //如果未来关注的数据多了,使用room特性 join/to/leave //监听disconnect事件 socket.on('disconnect', () => { // console.log('disconnect') }); }); app.use(async (ctx, next) => { try { await next(); } catch (err) { if (401 == err.status) { ctx.status = 401; ctx.set('WWW-Authenticate', 'Basic'); ctx.body = 'cant haz that'; } else { throw err; } } // ctx.body = 'Hello World'; }); app.use(koaStatic(path.join(__dirname, './static'))); app.use(basicAuth({name: 'poolin', pass: ''})); app.use(async (ctx) => { if (ctx.request.path == '/api/quote') { const quote = await sql.query("SELECT * FROM `quote` where enabled = 1;", {type: 'SELECT'}); ctx.response.body = quote; } else if (ctx.request.path == '/api/minute_history') { let exchangeName = ctx.request.query.exchange_name || ''; let limit = ctx.request.query.limit || 1440; let [n0, n1] = ctx.request.query.symbol.split('-') || ''; let tableName = `single_price_minute_${exchangeName}_${n0}_${n1}`; const history = await sql.query(`select * from (SELECT * FROM ${tableName} order by minute desc limit ${limit} ) aa order by minute asc;`, {type: 'SELECT'}); let now = new dayjs(); let begin = now.subtract(limit, 'm'); let data = []; while (begin.unix() < now.unix()) { let m = begin.format('YYYYMMDDHHmm'); let find = history.find(h => h.minute == m); let price = find ? find.price : null data.push({ minute: m, price, }) begin = begin.add(1, 'm'); } ctx.response.body = data; } else { await ctx.render('new', {cc: JSON.stringify(cc)}); } }); server.listen(8084); //交易对数据 let pushData = function (exchangeName, quoteName, price) { let key = `${exchangeName}-${quoteName}`; priceData[key] = price; }; // TRADE let tradeETH = "2"; let job = false; //串行执行任务 (async () => { //init approve let allowance = await usdt.methods.allowance(acc.address, cc.exchange.uniswap.router02.address).call(); console.log(`allowance ${allowance}`); // if (allowance == 0) { // //只允许一次,等不足的时候先设置0,再设置新的值。 // await usdt.methods.approve(cc.exchange.uniswap.router02.address, web3.utils.toWei("10000000", "mwei")).send({ // from: acc.address, // gas: 5000000 // }) // } while (true) { if (job) { let now = new dayjs(); let timestamp = now.unix() job = false; console.log('do job'); let uniKey = `uniswap-eth/usdt`; let bianKey = `bian-eth/usdt`; let uniPrice = priceData[uniKey]; let bianPrice = priceData[bianKey]; // uniPrice = 30; // bianPrice = 10; //先发个通知 let msg = msgTPL; msg.markdown = { "title": "[DeFi] 发现搬砖机会。", "text": `[DeFi] 币安:${bianPrice}, uniswap:${uniPrice}` }; //兑币价差,如果达到1%,就进行买卖。 if (Math.abs(bianPrice / uniPrice - 1) >= 0.01) { ding(msg); //谁的价格高,就在这个交易所卖出eth,在另外一边买入eth if (bianPrice > uniPrice) { //e.g. eth/usdt: 380 > 370 //交易前还要判断余额是否足够,够的情况下才能交易。 let usdtBalance = await usdt.methods.balanceOf(acc.address).call(); usdtBalance = new BN(usdtBalance).div(new BN(10).pow(cc.token.usdt.decimals)).toNumber(); console.log(usdtBalance); let ethBalance = (await binance.balance())['ETH']['available']; console.log(ethBalance); if (ethBalance < tradeETH || usdtBalance / uniPrice < tradeETH) { let msg = msgTPL; msg.markdown = { "title": "[DeFi] 余额不足,无法执行。", "text": `余额不足,无法执行。 ethBalance: ${ethBalance}, usdtBalance: ${usdtBalance}` }; ding(msg); await sleep(1000); continue; } let msg = msgTPL; msg.markdown = { "title": "[DeFi] 币安卖出eth,uniswap买入eth。", "text": "[DeFi] 币安卖出eth,uniswap买入eth。" }; ding(msg); try { let tradeUSDT = new BN(tradeETH * uniPrice).times(new BN(10).pow(cc.token.usdt.decimals)).toFixed(0); // await usdt.methods.approve(cc.exchange.uniswap.router02.address, tradeUSDT).send({from: acc.address, gas: 5000000}); await uniRoute2.methods .swapExactTokensForETH(tradeUSDT, 0, [cc.token.usdt.address, cc.token.weth.address], acc.address, timestamp + 300) .send({from: acc.address, gas: 5000000}) let ret = await binance.marketSell('ETHUSDT', tradeETH); if (ret.status != 'FILLED') { console.log('not FILLED'); return; } let msg = msgTPL; msg.markdown = { "title": "[DeFi] 执行完成。", "text": `执行完成。` }; ding(msg); } catch (e) { let msg = msgTPL; console.log('error: ', e); msg.markdown = { "title": "[DeFi] 执行失败。", "text": `${e}` }; ding(msg); return; } } else { //e.g. eth/usdt: 370 < 380 | bianPrice < uniPrice let ethBalance = await web3.eth.getBalance(acc.address); ethBalance = web3.utils.fromWei(ethBalance, 'ether'); console.log(ethBalance); let usdtBalance = (await binance.balance())['USDT']['available']; console.log(usdtBalance); if (ethBalance < tradeETH || usdtBalance / uniPrice < tradeETH) { let msg = msgTPL; msg.markdown = { "title": "[DeFi] 余额不足,无法执行。", "text": `余额不足,无法执行。 ethBalance: ${ethBalance}, usdtBalance: ${usdtBalance}` } ding(msg); await sleep(1000); continue; } let msg = msgTPL; msg.markdown = { "title": "[DeFi] 币安买入eth,uniswap卖出eth。", "text": "[DeFi] 币安买入eth,uniswap卖出eth。", }; ding(msg); try { await uniRoute2.methods .swapExactETHForTokens(0, [cc.token.weth.address, cc.token.usdt.address], acc.address, timestamp + 300) .send({from: acc.address, value: web3.utils.toWei(tradeETH, 'ether'), gas: 5000000}) let ret = await binance.marketBuy('ETHUSDT', tradeETH) if (ret.status != 'FILLED') { console.log('not FILLED'); return; } let msg = msgTPL; msg.markdown = { "title": "[DeFi] 执行完成。", "text": `执行完成。` }; ding(msg); } catch (e) { let msg = msgTPL; console.log('error: ', e); msg.markdown = { "title": "[DeFi] 执行失败。", "text": `${e}` }; ding(msg); return; } } } } await sleep(100) } })(); function sleep(ms) { return new Promise(resolve => setTimeout(() => resolve(), ms)); } async function ding(msg) { // let msg = { // "msgtype": "markdown", // "markdown": { // "title":"杭州天气", // "text": "#### 杭州天气 @150XXXXXXXX \n> 9度,西北风1级,空气良89,相对温度73%\n> ![screenshot](https://img.alicdn.com/tfs/TB1NwmBEL9TBuNjy1zbXXXpepXa-2400-1218.png)\n> ###### 10点20分发布 [天气](https://www.dingtalk.com) \n" // }, // "at": { // "atMobiles": [ // "150XXXXXXXX" // ], // "isAtAll": false // } // }; try { let response = await axios.post('https://oapi.dingtalk.com/robot/send?access_token=' + process.env.DING_KEY, msg) } catch (e) { console.error(`ding error: ${e.message} ${msg}`); } }
document.addEventListener('DOMContentLoaded', function () { document.querySelector('#go').addEventListener('click',link); }); function link() { document.getElementById("form").innerHTML = ""; }
if (document.readyState == "loading") { document.addEventListener("DOMContentLoaded", gsapReady); document.addEventListener("DOMContentLoaded", mainReady); } else { gsapReady(); mainReady(); } function gsapReady() { window.addEventListener("load", () => { document.body.style.display = "block"; }); var tl = gsap.timeline(); tl.staggerFrom( ".hero, .sidebar, .inspiration", 2, { opacity: 0, scale: 0.5, ease: "Power2.easeOut", }, 0.2 ); tl.staggerFrom( ".logo,.menu", 1, { opacity: 0, y: -40, ease: "Power2.easeOut", }, 0.2, "-=1.8" ); tl.staggerFrom( ".content,.cta-btn", 2, { opacity: 0, y: -40, ease: "Power2.easeOut", }, 0.2, "-=1.5" ); } function mainReady() { const btnAddToCarts = document.querySelectorAll(".btn-shop"); const btnPurchase = document.querySelector(".btn-purchase"); const modals = document.querySelectorAll(".modal"); const modalPurchase = document.getElementById("modal-purchase"); const modalCart = document.getElementById("modal-cart"); const overlay = document.getElementById("overlay"); const btnModalCloses = document.querySelectorAll(".btn-close"); btnAddToCarts.forEach((btnAddToCart) => { btnAddToCart.addEventListener("click", addToCartClicked); }); btnPurchase.addEventListener("click", () => { modalPurchase.classList.add("active"); overlay.classList.add("active"); }); btnModalCloses.forEach((btnModalClose) => { btnModalClose.addEventListener("click", closeModal); }); overlay.addEventListener("click", closeModal); function closeModal() { modals.forEach((modal) => { modal.classList.remove("active"); overlay.classList.remove("active"); }); } function addToCartClicked(e) { let shopItemBtn = e.target; let shopItem = shopItemBtn.parentElement.parentElement; let title = shopItem.querySelector(".shop-item-title").innerText; let price = shopItem.querySelector(".shop-item-price").innerText; let imgSrc = shopItem.querySelector("img").src; //Add a new row to the cart for the new item addToCart(title, price, imgSrc); } function addToCart(title, price, imgSrc) { let cartRow = document.createElement("div"); cartRow.classList.add("cart-row"); let cartItemContainer = document.querySelector(".cart-container"); let cartItemNames = cartItemContainer.querySelectorAll(".cart-item-title"); //check if the item is already in cart for (let i = 0; i < cartItemNames.length; i++) { if (cartItemNames[i].innerText === title) { modalCart.classList.add("active"); overlay.classList.add("active"); return; //calling return will immediately stop the function and stop executing the following code, it goes back to the addToCart() function } } let cartRowContent = ` <div class="cart-item cart-column"> <img class="cart-item-img" src="${imgSrc}" width="100" height="100" alt="" /> <span class="cart-item-title">${title}</span> </div> <div class="cart-price cart-column">${price}</div> <div class="cart-quantity cart-column"> <input class="cart-quantity-input" type="number" value="1" /> <button class="btn btn-remove">REMOVE</button> </div> `; cartRow.innerHTML = cartRowContent; cartItemContainer.appendChild(cartRow); cartRow .querySelector(".btn-remove") .addEventListener("click", removeCartItem); cartRow .querySelector(".cart-quantity-input") .addEventListener("change", quantityChanged); updateCartTotal(); } function removeCartItem(e) { e.target.parentElement.parentElement.remove(); updateCartTotal(); } function quantityChanged(e) { let input = e.target; if (isNaN(input.value) || input.value < 0) { input.value = 1; } updateCartTotal(); } function updateCartTotal() { let total = 0; let cartItemContainer = document.querySelector(".cart-container"); let cartRows = cartItemContainer.querySelectorAll(".cart-row"); cartRows.forEach((cartRow) => { let priceElement = cartRow.querySelector(".cart-price"); let quantityElement = cartRow.querySelector(".cart-quantity-input"); let price = priceElement.innerText.replace("$", ""); let quantity = quantityElement.value; //every time goes the loop, the new total will be the previous total adding by the (price * quantity) of that row total = total + price * quantity; }); //round the total amount to 2 decimals total = Math.round(total * 100) / 100; document.querySelector(".cart-total-price").innerText = "$" + total; } }
import React from "react"; import { Navbar, Footer } from "../components"; const NotFound = () => { return ( <div className="NotFoundDiv"> <Navbar/> <div className="container text-center"> <h1 className="mb-5"> <strong>ERROR 404 :c</strong></h1> <div className="mt-5"> <h5 className="mb-5">I'm sorry we can't reach the path, please try using another...</h5> <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Laboriosam ipsa aliquam reiciendis sunt voluptatem odio ea voluptates mollitia dignissimos, necessitatibus nobis alias, voluptate consectetur nemo temporibus reprehenderit? Voluptatibus repellat perferendis, quasi obcaecati iure fugit ipsum. Hic odio quasi voluptas perferendis iusto adipisci consequuntur sit a? Earum ullam recusandae, repellat similique laborum perferendis? Dolorum tempora ea molestias praesentium deserunt, laborum, facilis nam aspernatur deleniti ex aliquam illum quibusdam consequatur blanditiis asperiores quae! Quia dolorem corrupti, sequi minima non nobis laborum perspiciatis corporis temporibus aspernatur voluptatum placeat sint est amet esse tenetur, sed iste impedit, mollitia alias similique magni beatae earum! Harum.</p> </div> </div> <Footer/> </div> ); }; export default NotFound
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { ScrollView, StyleSheet } from 'react-native'; import ListDeckItem from './ListDeckItem'; import Api from '../utils/api'; import { fetchDecksSuccessful } from '../redux/actions'; import { AppLoading } from 'expo'; import { white } from '../utils/colors'; class ListDecks extends Component { state = { isReady: false, }; componentDidMount = () => { Api.getDecks().then(r => { this.props.dispatch(fetchDecksSuccessful(r)); this.setState({ isReady: true }); }); }; render() { const { decks } = this.props; if (!this.state.isReady) { return <AppLoading />; } return ( <ScrollView contentContainerStyle={styles.contentContainer}> {Object.keys(decks).map(d => ( <ListDeckItem key={decks[d].title} title={decks[d].title} cardsQuantity={decks[d].questions.length} onClick={() => this.props.navigation.navigate('DeckDetail', { deckId: decks[d].title, }) } /> ))} </ScrollView> ); } } const styles = StyleSheet.create({ contentContainer: { paddingVertical: 5, backgroundColor: white, }, }); const mapStateToProps = decks => ({ decks, }); export default connect(mapStateToProps)(ListDecks);
'use strict'; angular.module('frontApp') .controller('ConfigManagerCtrl', function ($scope, ArchAPI, PlatformAPI, EngineAPI, TargetAPI, ScriptAPI, OptionAPI) { /** * Architecture Configuration */ $scope.listArch = function(){ ArchAPI.list().then(function(data){ $scope.arches = data; }); }; $scope.toggleArchConfig = function(arch){ arch.configMode = !arch.configMode; }; $scope.removeArch = function(arch){ ArchAPI.remove(arch.id).then(function(){ $scope.listArch(); }); }; $scope.updateArch = function(arch){ ArchAPI.update(arch.id, arch).then(function(){ $scope.listArch(); $scope.newArchName = null; }, function(){ $.notify("invalid name.", "error"); }); }; $scope.createArch = function(name){ ArchAPI.create({ name: name }).then(function(){ $scope.listArch(); $scope.newArchName = null; }, function(){ $.notify("invalid input.", "error"); }); }; /** * Platform Configuration */ $scope.listPlatform = function(){ PlatformAPI.list().then(function(data){ $scope.platforms = data; }); } $scope.togglePlatformConfig = function(plat){ plat.configMode = !plat.configMode; }; $scope.removePlatform = function(plat){ PlatformAPI.remove(plat.id).then(function(){ $scope.listPlatform(); }); }; $scope.updatePlatform = function(plat){ PlatformAPI.update(plat.id, plat).then(function(){ $scope.listPlatform(); $scope.newPlatformName = null; }, function(){ $.notify("invalid input.", "error"); }); }; $scope.createPlatform = function(name){ PlatformAPI.create({ name: name }).then(function(){ $scope.listPlatform(); $scope.newPlatformName = null; }, function(){ $.notify("invalid input.", "error"); }); }; /** * Engine Configuration */ $scope.getEnginePlatform = function(engine){ for(var i = 0; i < $scope.platforms.length; i++){ if(engine.platform_id === $scope.platforms[i].id){ return $scope.platforms[i].name; }; }; }; $scope.getEngineArch = function(engine){ for(var i = 0; i < $scope.arches.length; i++){ if(engine.arch_id === $scope.arches[i].id){ return $scope.arches[i].name; }; }; }; $scope.listEngine = function(){ EngineAPI.list().then(function(data){ $scope.engines = data; $scope.engines.forEach(function(engine){ for(var i = 0; i < $scope.platforms.length; i++){ if(engine.platform_id === $scope.platforms[i].id){ engine.platform = $scope.platforms[i]; break; }; }; for(var i = 0; i < $scope.arches.length; i++){ if(engine.arch_id === $scope.arches[i].id){ engine.arch = $scope.arches[i]; break; }; }; engine.option_tags = []; engine.options.forEach(function(opt){ engine.option_tags.push({ text: opt.name, option: opt }) }) }) }); }; $scope.toggleEngineConfig = function(engine){ engine.configMode = !engine.configMode; }; $scope.removeEngine = function(engine){ EngineAPI.remove(engine.id).then(function(){ $scope.listEngine(); }); }; $scope.updateEngine = function(engine){ var options = []; engine.option_tags.forEach(function(tag){ options.push(tag.option.id); }) EngineAPI.update(engine.id, { name: engine.name, path: engine.path, platform_id: engine.platform.id, arch_id: engine.arch.id, options: options }).then(function(){ $scope.listEngine(); $scope.newEngine= null; }, function(){ $.notify("invalid input.", "error"); }); }; $scope.createEngine = function(engine){ var options = []; engine.option_tags.forEach(function(tag){ options.push(tag.option.id); }) console.log(options); if(angular.isDefined(engine) && angular.isDefined(engine.platform)){ EngineAPI.create({ name: engine.name, path: engine.path, platform_id: engine.platform.id, arch_id: engine.arch.id, options: options }).then(function(){ $scope.listEngine(); $scope.newEngine = null; }, function(){ $.notify("invalid input.", "error"); }); } else{ $.notify("invalid input.", "error"); }; }; /** * Target Configuration */ $scope.getTargetPlatform = function(target){ for(var i = 0; i < $scope.platforms.length; i++){ if(target.platform_id === $scope.platforms[i].id){ return $scope.platforms[i].name; }; }; }; $scope.getTargetArch = function(target){ for(var i = 0; i < $scope.arches.length; i++){ if(target.arch_id === $scope.arches[i].id){ return $scope.arches[i].name; }; }; }; $scope.listTarget = function(){ TargetAPI.list().then(function(data){ $scope.targets = data; $scope.targets.forEach(function(target){ for(var i = 0; i < $scope.platforms.length; i++){ if(target.platform_id === $scope.platforms[i].id){ target.platform = $scope.platforms[i]; break; }; }; for(var i = 0; i < $scope.arches.length; i++){ if(target.arch_id === $scope.arches[i].id){ target.arch = $scope.arches[i]; break; }; }; }) }); } $scope.toggleTargetConfig = function(target){ target.configMode = !target.configMode; }; $scope.removeTarget= function(target){ TargetAPI.remove(target.id).then(function(){ $scope.listTarget(); }); }; $scope.updateTarget = function(target){ TargetAPI.update(target.id, { name: target.name, path: target.path, arch_id: target.arch.id, platform_id: target.platform.id }).then(function(){ $scope.listTarget(); }, function(){ $.notify("invalid input.", "error"); }); }; $scope.createTarget = function(newTarget){ if(angular.isDefined(newTarget)){ TargetAPI.create({ name: newTarget.name, path: newTarget.path, arch_id: newTarget.arch.id, platform_id: newTarget.platform.id, }).then(function(){ $scope.listTarget(); $scope.newTarget = null; }, function(){ $.notify("invalid input.", "error"); }); } else{ $.notify("invalid input.", "error"); }; }; /** * Script Configuration */ $scope.listScript = function(){ ScriptAPI.list().then(function(data){ $scope.scripts = data; }); }; $scope.toggleScriptConfig = function(script){ script.configMode = !script.configMode; }; $scope.removeScript = function(script){ ScriptAPI.remove(script.id).then(function(){ $scope.listScript(); }); }; $scope.updateScript = function(script){ ScriptAPI.update(script.id, script).then(function(){ $scope.listScript(); }, function(){ $.notify("invalid input.", "error"); }); }; $scope.createScript = function(sc){ ScriptAPI.create({ name: sc.name, script: sc.script }).then(function(){ $scope.listScript(); }, function(){ $.notify("invalid input.", "error"); }); }; /** * Option Configuration */ $scope.listOption = function(){ OptionAPI.list().then(function(data){ $scope.options = data; OptionAPI.type().then(function(data){ $scope.option_types = data; $scope.options.forEach(function(option){ for(var i = 0; i < $scope.option_types.length; i++){ if(option.type_id === $scope.option_types[i].id){ option.type = $scope.option_types[i]; break; }; }; }); }); }); }; $scope.getOptionType = function(opt){ if(angular.isDefined($scope.option_types)){ for(var i = 0; i < $scope.option_types.length; i++){ if(opt.type_id === $scope.option_types[i].id){ return $scope.option_types[i].name; }; }; }; }; $scope.toggleOptionConfig = function(opt){ opt.configMode = !opt.configMode; }; $scope.removeOption = function(opt){ OptionAPI.remove(opt.id).then(function(){ $scope.listOption(); }); }; $scope.updateOption = function(opt){ OptionAPI.update(opt.id, { name: opt.name, option_type_id: opt.type.id }).then(function(){ $scope.listOption(); }, function(){ $.notify("invalid input.", "error"); }); }; $scope.createOption = function(opt){ if(angular.isDefined(opt) && angular.isDefined(opt .type)){ OptionAPI.create({ name: opt.name, option_type_id: opt.type.id }).then(function(){ $scope.listOption(); }, function(){ $.notify("invalid input.", "error"); }); } else{ $.notify("invalid input.", "error"); }; }; $scope.queryOptionTags = function(q){ var result = []; $scope.options.forEach(function(opt){ if(opt.name.startsWith(q)){ result.push( { text: opt.name, option: opt, } ); } }); return result; }; $scope.activateTab = function(tabid){ $('.tabs-left > li').removeClass('active'); $(tabid + 'Nav').addClass('active'); $('.tab-pane').removeClass('active'); $(tabid + 'Tab').addClass('active'); $scope.initNodes(); } $scope.initNodes = function() { $scope.listArch(); $scope.listPlatform(); $scope.listEngine(); $scope.listTarget(); $scope.listScript(); $scope.listOption(); }; $scope.initNodes(); });
console.log(true); console.log(false); console.log(5 === 6); console.log(Boolean(10)); //false console.log(Boolean(undefined)); console.log(Boolean(null)); console.log(Boolean(0)); console.log(Boolean(NaN)); console.log(Boolean("")); var str = "Текст"; if (str){ console.log("Истина"); } console.log(true && true); console.log(true || false); console.log(!true); var a = 0, isTrue = true; isTrue && (a = 5); console.log(a); var someString = "Не пустая строка"; var newString = someString || "Строка по умолчанию"; console.log(newString);
X.define("model.blogModel",function () { var blogModel = X.model.create("model.blogModel"), blogApi = X.config.blog.api; blogModel.getArticleList = function(data,callback) { var option = {url:blogApi.blogList,type:"POST",data:data, callback:function(result) { if (result.statusCode === X.CONSTANT.statusCode.SUCCESS){ callback && callback(result); } }}; X.loadData(option); }; blogModel.query = function(id, callback) { var option = {url:blogApi.blogDetail + id,type:"GET", callback:function(result) { if (result.statusCode === X.CONSTANT.statusCode.SUCCESS){ callback && callback(result); } }}; X.loadData(option); }; //这是一个那到所有 详情页需要数据的接口 blogModel.blogDetail = function (id, callback) { var me = this, data = {}; //如果支持ES6 就用Promise /*if (window.Promise) { new Promise((res, rej) => { me.query(id, (result) => { data = result.data res() }) }).then(() => { me.loadComments({pageNo: 1,pageSize: me.commentsPageSize}, function(result) { data.comments = result.data.list }) }).then(() => { me.hotPost(function(result) { data.hot = result.data data.hot && ( data.hot.forEach(function(item) { item.href = 'blogs/' + item.postId + '.html' }) ) callback(data) }) }) } else {*/ me.query(id, function(res) { data = res.data; me.loadComments({pageNo: 1,pageSize: me.commentsPageSize, query: {blogPostId: id}}, function(result) { data.comments = result.data.list; data.commentsNum = result.data.page.totalCount; me.hotPost(function(res1) { data.hot = res1.data if (data.hot) { var len = data.hot.length while (len--) { var item = data.hot[len]; item.href = 'blogs/' + item.postId + '.html' } } callback(data); }) }); }); /*}*/ }; blogModel.postComments = function(data, callback) { var option = {url:blogApi.postComments,type:"POST", data: data, callback:callback}; X.loadData(option); }; blogModel.loadComments = function(query, callback) { var option = {url:blogApi.loadComments,type:"POST", data: query, callback:function(result) { if (result.statusCode === X.CONSTANT.statusCode.SUCCESS){ callback && callback(result); } }}; X.loadData(option); }; blogModel.getListPostByPage = function(data,callback) { var option = {url:blogApi.listPostByPage,type:"POST",data:data, callback:function(result) { if (result.statusCode === X.CONSTANT.statusCode.SUCCESS){ callback && callback(result); } }}; X.loadData(option); }; blogModel.hotPost = function(callback) { var option = {url:blogApi.hotPost,type:"POST", callback:function(result) { if (result.statusCode === X.CONSTANT.statusCode.SUCCESS){ callback && callback(result); } }}; X.loadData(option); }; blogModel.getListTenPosts = function(callback) { var option = {url:blogApi.blogList,type:"POST", callback:function(result) { if (result.statusCode === X.CONSTANT.statusCode.SUCCESS){ callback && callback(result); } }}; X.loadData(option); }; blogModel.commentsPageSize = 10 blogModel.commentsNum = 10000 return blogModel; });
import gulp from "gulp"; import concat from "gulp-concat"; import replace from "gulp-replace"; import plumber from "gulp-plumber"; export default (config) => { return function css_vendor () { const connect = config.connect; const stream = gulp.src(config.src) .pipe(plumber()) .pipe(replace('?v=4.7.0', '')) .pipe(concat('vendors.min.css')) .pipe(gulp.dest(config.dest)); if(connect){ stream.pipe(connect.reload()); } return stream; }; };
$(document).ready(function(){ $('.main_slider').slick({ infinite:true, slidesToShow: 3, slidesToScroll: 1, arrows: true, centerMode: true, centerPadding: '0px', appendArrows: $('.main_slide_arrow'), prevArrow:'<img src="img/prev_arrow.png" alt="">', nextArrow:'<img src="img/next_arrow.png" alt="">', responsive: [ { breakpoint: 800, settings: { slidesToShow: 1, slidesToScroll: 1, centerMode: true, centerPadding: '0px' } }, { breakpoint: 480, settings: { slidesToShow: 1, slidesToScroll: 1 } } // You can unslick at a given breakpoint now by adding: // settings: "unslick" // instead of a settings object ] }); $('.mobile_menu').click(function() { $('.header_top nav').toggleClass('active_menu'); }) });
import { DotsVerticalIcon, MicrophoneIcon, PaperClipIcon, UserCircleIcon } from "@heroicons/react/solid"; import { EmojiHappyIcon } from "@heroicons/react/outline"; import { useRouter } from "next/router"; import { useAuthState } from "react-firebase-hooks/auth"; import { auth, db} from "../firebase"; import { useCollection } from "react-firebase-hooks/firestore"; import { useRef, useState } from "react"; import firebase from "firebase"; import Message from "../components/Message"; import getRecipientEmail from "../utils/getRecipientEmail"; import TimeAgo from "timeago-react"; import Image from "next/image"; function ChatScreen({ chat, messages }) { const endOfMessageRef = useRef(null); const [user] = useAuthState(auth); const [input, setInput] = useState(""); const router = useRouter(); const [messagesSnapshot] = useCollection( db.collection("chats").doc(router.query.id) .collection("messages").orderBy("timestamp", "asc") ); const [recipientSnapshot] = useCollection( db.collection("users").where("email", "==", getRecipientEmail(chat.users, user)) ); const showMessages = () => { if (messagesSnapshot) { return messagesSnapshot.docs.map((message) => ( <Message key={message.id} user={message.data().user} message = {{ ...message.data(), timestamp: message.data().timestamp?.toDate().getTime(), }} /> )); } else { return JSON.parse(messages).map(message => ( <Message key={message.id} user={message.user} message={message} /> )); } }; const scrollToBottom = () => { endOfMessageRef.current.scrollIntoView({ behaviour: "smooth", block:"start", }); } const sendMessage = (e) => { e.preventDefault(); // updates last seen db.collection("users").doc(user.uid).set({ lastSeen: firebase.firestore.FieldValue.serverTimestamp(), }, { merge: true } ); db.collection("chats").doc(router.query.id).collection("messages").add({ timestamp: firebase.firestore.FieldValue.serverTimestamp(), message: input, user: user.email, photoURL: user.photoURL, }); setInput(""); scrollToBottom(); }; const recipient = recipientSnapshot?.docs?.[0]?.data(); const recipientEmail = getRecipientEmail(chat.users, user); console.log(recipient) return ( <div className="flex-grow h-[100vh]"> {/* top header bar */} <div className="sticky bg-white z-50 top-0 flex p-[11px] h-[80px] items-center border-b-1 shadow-sm"> {recipient ? ( <Image src={recipient?.photoUrl} width={60} height={60} className=" rounded-full" /> ) : ( <div className="flex h-9 w-9 m-1 mr-2 p-1 bg-gray-300 text-white rounded-full text-4xl justify-evenly "> {recipientEmail[0]} </div> )} <div className="ml-3 flex-grow"> <h3 className="text-lg">{recipientEmail}</h3> {recipientSnapshot ? ( <p className="text-xs text-gray-400">Last active: {""} {recipient?.lastSeen?.toDate() ? ( <TimeAgo datetime={recipient?.lastSeen?.toDate()} /> ) : ("Unavailable")} </p> ) : ( <p className="text-xs text-gray-400">Loading Last active...</p> )} </div> <div className=""> <button className="mr-1"> <PaperClipIcon className="h-10 text-gray-500 p-2 hover:bg-gray-100 rounded-full"/> </button> <button className="mr-3"> <DotsVerticalIcon className="h-10 text-gray-500 p-2 hover:bg-gray-100 rounded-full"/> </button> </div> </div> {/* Message container */} <div className="p-5 bg-[#e5ded8] min-h-[90vh] rounded-md mb-10"> {showMessages()} <div className="" ref={endOfMessageRef}/> </div> <div className="flex items-center p-2 sticky bottom-0 bg-white z-100"> <EmojiHappyIcon className="h-5" /> <form className="flex flex-grow"> <input className="bg-gray-100 z-100 flex-grow focus:outline-none border-0 rounded-lg p-3 ml-3 mr-3" value={input} onChange ={e => setInput(e.target.value)} /> <button hidden disabled={!input} type="submit" onClick={sendMessage}>Send message</button> </form> <MicrophoneIcon className="h-5" /> </div> </div> ) } export default ChatScreen
import React from 'react'; import PropTypes from 'prop-types'; import { withStyles } from '@material-ui/core/styles'; import {Card,CardActionArea,Typography,CardActions,CardContent,CardMedia} from '@material-ui/core'; import history from '../../../history'; import store from '../../../store/store'; import loggedinUser from '../../../services/getLoggedinUserService/getLoggedinUserService'; import './card.css'; import { debug } from 'util'; const styles = { card: { minWidth:300, maxWidth: 345, height:400, margin:20, }, media: { height: 250, }, }; class MediaCard extends React.Component { constructor(){ super(); navigator.geolocation.getCurrentPosition((position) =>{ this.state = { latitude:position.coords.latitude, longitude:position.coords.longitude } }); } moveToMap(title){ store.dispatch({ type:'SET_CURRENT_LOCATION', latitude:this.state.latitude, longitude:this.state.longitude }); loggedinUser.getUsers(title); history.push('/map'); } render(){ const { classes } = this.props; return ( <div className = 'linkStyle'> <Card onClick={()=>{this.moveToMap(this.props.type)}} className={classes.card}> <CardActionArea> <CardMedia className={classes.media} image={this.props.src} title={this.props.title} /> <CardContent> <Typography gutterBottom variant="h5" component="h2"> {this.props.title} </Typography> <Typography component="p"> {this.props.content} </Typography> </CardContent> </CardActionArea> <CardActions className = 'bgcolor'> </CardActions> </Card> </div> ); } } MediaCard.propTypes = { classes: PropTypes.object.isRequired, }; export default withStyles(styles)(MediaCard);
export class Player { constructor(name, score = 0) { this.name = name; this.score = score; this.shape = null; } win() { this.score++; } }
import React from 'react'; import { StyleSheet, View, ScrollView, Text, TextInput, Image, TouchableHighlight } from 'react-native'; import { AuthContext } from "../../App"; export default function Login ({navigation}) { const { signIn } = React.useContext(AuthContext); const [username, setUsername] = React.useState('') const [password, setPassword] = React.useState('') return ( <View style={styles.container}> <Image style={styles.logo} source={require('../../images/comeTogetherBlack.png')} resizeMode='contain'/> <Text style={styles.header}> Login</Text> <View style={styles.root}> <View style={styles.rowContainer}> <Text style={styles.text}>Username</Text> <TextInput autoCorrect={false} onChangeText={setUsername} value={username} style={styles.textInput} /> </View> <View style={styles.rowContainer}> <Text style={styles.text}>Password</Text> <TextInput autoCorrect={false} onChangeText={setPassword} value={password} style={styles.textInput} secureTextEntry={true} /> </View> </View> <View style={styles.buttonContainer}> <TouchableHighlight style={styles.scan} title="Login" onPress= {()=>{signIn(username, password)}} > <Text style={styles.button}>Login</Text> </TouchableHighlight> </View> </View> ); } const styles = StyleSheet.create({ container: { flex:1, backgroundColor: '#F5FCFF', justifyContent:"space-around", paddingHorizontal:20, overflow: "hidden" }, button:{ fontSize: 20, color:'#FFFFFF', fontWeight: 'bold', paddingHorizontal:20, }, scan: { justifyContent:'center', alignItems: 'center', height:44, borderRadius:7, backgroundColor: '#FF652F', marginBottom:100 }, logo: { flex:1, height: undefined, width: undefined }, header: { flex:0.5, textAlign: 'center', fontSize: 25, fontWeight: 'bold' }, root: { flex: 1, flexDirection: "column", }, rowContainer: { flex: 1, flexDirection: "row", alignItems: "center" }, buttonContainer: { width: '100%', flex: 2, flexDirection: "column", alignItems: "center", }, text: { flex: 1 }, textInput: { flex: 2, paddingLeft: 6, borderWidth: 2, borderRadius: 8, borderColor: 'grey', backgroundColor: 'rgba(243, 241, 239, 0.8)', } });
// let userInput; // let total = 0; // while (true) { // userInput = prompt('Введите число!'); // if (userInput === null) { // break; // } // userInput = Number(userInput); // if (userInput <= 0) { // break; // } // total += userInput; // } // console.log(total);
import { connect } from "react-redux"; import Project from "./Project"; import actions from "../../redux/actions"; const mapStateToProps = state => ({ ...state.projectParams }); export default connect( mapStateToProps, actions )(Project);
import React, { Component } from 'react'; import { View, StyleSheet, DeviceEventEmitter } from 'react-native'; import { Container, Header, Content, Form, Item, Input, Body, Toast, Text, Title, H1, H2, H3, Button } from 'native-base'; import {getDeck, addQuizAnswerToUserCollection} from './helpers'; export default class QuizView extends Component { constructor(props) { super(props); this.state = { currentQuestion: [], currentQuestionIndex: 0, questions: [], showAnswer: false, endOfQuiz: false, correctQuestionsCounter: 0 }; } _fetchQuestions = async () => { const { navigation } = this.props; const deckId = navigation.getParam('id'); const payload = await getDeck(deckId); if (payload) { const questions = payload.questions; return this.setState({ questions }, () => this.setCurrentQuestion()); } } componentDidMount() { this.initialState = this.state; DeviceEventEmitter.addListener("cardAdded", (e) => { return this._fetchQuestions(); }) return this._fetchQuestions(); } setCurrentQuestion() { const { currentQuestionIndex, questions, correctQuestionsCounter } = this.state; const { navigation } = this.props; if (questions.length > 0 && (currentQuestionIndex + 1 <= questions.length)) { this.setState({ currentQuestion: questions[currentQuestionIndex] }); } else { const deckId = navigation.getParam('id'); const payload = { id: deckId, correct: correctQuestionsCounter, timestamp: new Date() } addQuizAnswerToUserCollection(payload) return this.setState({ endOfQuiz: true }); } } restartQuiz = () => this.setState(this.initialState, () => this._fetchQuestions()); nextCard = (chosen) => { const { currentQuestionIndex, correctQuestionsCounter } = this.state; if (chosen === 'correct') { this.setState({ correctQuestionsCounter: correctQuestionsCounter + 1 }) } this.setState({ currentQuestionIndex: currentQuestionIndex + 1, showAnswer: false }, () => this.setCurrentQuestion()); } render() { const { questions, showAnswer, currentQuestion, endOfQuiz, currentQuestionIndex, correctQuestionsCounter } = this.state; const { goBack } = this.props.navigation; return ( <Container> {questions.length === 0 ? ( <Content contentContainerStyle={styles.container}> <H2>No Cards available in this Deck</H2> </Content> ) : ( <Content contentContainerStyle={styles.container}> {!endOfQuiz ? ( <Body style={styles.container}> <Text style={styles.textStyles}>Question {currentQuestionIndex + 1} out of {questions.length}</Text> <H3> {currentQuestion.question} </H3> {!showAnswer ? ( <Button transparent info style={styles.buttonStyle} onPress={() => this.setState({ showAnswer: true })}> <Text>Show Answer</Text> </Button> ) : ( <Text style={styles.textStyles}> Answer: {currentQuestion.answer}</Text> )} <Button success style={styles.buttonStyle} onPress={() => this.nextCard("correct")}> <Text>Correct</Text> </Button> <Button danger style={styles.buttonStyle} onPress={() => this.nextCard("wrong")}> <Text>Wrong</Text> </Button> </Body> ) : ( <Body style={styles.container}> <H3>Congratulations, the quiz has ended!</H3> <Title style={styles.textColor}>Correct answers: {correctQuestionsCounter}</Title> <Button success style={styles.buttonStyle} onPress={() => this.restartQuiz()}> <Text>Restart Quiz</Text> </Button> <Button info style={styles.buttonStyle} onPress={() => goBack()}> <Text>Back to Deck</Text> </Button> </Body> )} </Content> )} </Container> ); } } const styles = StyleSheet.create({ titleStyle: { paddingLeft: 40, paddingRight: 40, textAlign: 'center' }, cardStyle: { alignItems: 'center', justifyContent: 'center', width: 200, height: 150, textAlign: 'center' }, buttonStyle: { alignSelf: 'center', marginTop: 20 }, container: { flex: 1, //backgroundColor: 'rgb(50, 49, 78)', alignItems: 'center', justifyContent: 'center' }, cardStyles: { backgroundColor: 'rgb(50, 49, 78) !important', color: 'white' }, textStyles: { fontSize: 10, paddingTop: 10, paddingBottom: 10 }, textColor: { color: 'rgb(50, 49, 78)' } });
const cookieSession = require('cookie-session'); const express = require('express'); const bodyParser = require("body-parser"); const morgan = require('morgan'); const app = express(); const PORT = 8080; app.use(express.json()); app.use(morgan('tiny')); app.set('view engine', 'ejs'); app.use(bodyParser.urlencoded({ extended: true })); app.use(cookieSession({ name: 'session', keys: ['key1', 'key2'], // Cookie Options maxAge: 24 * 60 * 60 * 1000 // 24 hours })); //Using express router app.use('/', require('./routes/home')); app.use('/u', require('./routes/u')); app.use('/users', require('./routes/users')); app.use('/urls', require('./routes/urls')); app.use('/urlsnew', require('./routes/urlsnew')); app.use('/register', require('./routes/register')); app.use('/login', require('./routes/login')); app.use('/logout', require('./routes/logout')); app.listen(process.env.PORT || PORT, () => { console.log(`Listening on Port: ${PORT}.`); });
import React from 'react'; import {connect} from 'react-redux'; import Router from 'next/router' import {checkout, changeCurrency} from '../redux/actions/cartActions'; import { BasicButton, SecondaryButton } from '../components/buttons' import CartTable from '../components/cartTable' import Layout from '../components/layout' import { CardLarge } from '../components/card' import { FormTitle, FieldSet, FormField, SmallFormField, FormInput } from '../components/form' import utilStyles from '../styles/utils.module.scss' import getShippingFee from '../lib/shipping'; import { createOrder } from '../lib/orders'; class Checkout extends React.Component { constructor(props) { super(props); this.state = { postalCode: undefined, shippingFee: 0, loading: false } this.newOrder = this.newOrder.bind(this); this.calculateShipping = this.calculateShipping.bind(this); this.toggleShippingButton = this.toggleShippingButton.bind(this); } toggleShippingButton(e) { this.setState({ postalCode: e.target.value }) } async calculateShipping(e) { e.preventDefault(); let shippingFee = await getShippingFee(this.state.postalCode) this.setState({ shippingFee: shippingFee.fee }) } async newOrder(e) { e.preventDefault() this.setState({ loading: true }) const formData = new FormData(e.target) const order = { customer: {} } order.currency = this.props.currency order.products = this.props.cart.items.map((item) => ({ id: item.product_id, quantity: item.quantity, price: item.price })) for (let entry of formData.entries()) { order.customer[entry[0]] = entry[1] } let orderId = (await createOrder(order)).order_id; this.props.checkout(); Router.push(`/orders/${orderId}`); } render() { return ( <Layout> <div className={utilStyles.container}> <CardLarge> <CartTable products={ this.props.cart.items } shippingFee={ this.state.shippingFee }></CartTable> </CardLarge> <CardLarge> <form id="orderForm" onSubmit={this.newOrder}> <FormTitle> <h2 className={`${utilStyles.colorPrimary700} ${utilStyles.headingMd}`}>Personal information</h2> </FormTitle> <FieldSet> <FormField> <FormInput type="text" name="first_name" placeholder="First Name" required /> </FormField> <FormField> <FormInput type="text" name="last_name" placeholder="Last Name" required /> </FormField> </FieldSet> <FieldSet> <FormField> <FormInput type="email" name="email" placeholder="Email" required /> </FormField> <FormField> <FormInput type="phone" name="phone" placeholder="Phone" required /> </FormField> </FieldSet> <FormTitle> <h2 className={`${utilStyles.colorPrimary700} ${utilStyles.headingMd}`}>Shipping information</h2> </FormTitle> <FieldSet> <FormField> <FormInput type="text" name="address_line_1" placeholder="Address" required /> </FormField> <SmallFormField> <FormInput type="text" name="address_line_2" placeholder="Appartment, suite, etc" /> </SmallFormField> <SmallFormField> <FormInput type="text" name="postal_code" placeholder="Zip code" required onChange={this.toggleShippingButton}/> </SmallFormField> </FieldSet> </form> </CardLarge> <div className={utilStyles.formActions}> <SecondaryButton type="button" id="shipping-button" onClick={this.calculateShipping} disabled={!this.state.postalCode}> Calculate shipping </SecondaryButton> <BasicButton type="submit" form="orderForm" disabled={this.state.loading}> Confirm </BasicButton> </div> </div> </Layout> ); } } const mapStateToProps = state => ({ cart: state.cart, currency: state.cart.currency }); const mapDispatchToProps = { checkout: checkout, changeCurrency: changeCurrency }; export default connect(mapStateToProps, mapDispatchToProps)(Checkout);
module.exports = { env: { browser: true, jasmine: true, }, extends: [ 'airbnb-base', 'plugin:import/errors', 'plugin:import/warnings', ], parser: "babel-eslint", parserOptions: { ecmaFeatures: { experimentalObjectRestSpread: true, }, }, plugins: [ 'react', ], rules: { 'import/no-extraneous-dependencies': [ 'error', { devDependencies: [ '**/*.test.js', '**/webpack-*.config.js', ], }, ], 'import/prefer-default-export': 0, 'linebreak-style': 0, 'new-cap': 0, 'no-use-before-define': [ 'error', { classes: true, functions: false, }, ], 'prefer-const': 2, 'react/forbid-prop-types': [ 2, { forbid: [ 'any', 'array', ], } ], 'react/no-children-prop': 2, 'react/no-danger-with-children': 2, 'react/no-deprecated': 2, 'react/no-did-mount-set-state': 2, 'react/no-did-update-set-state': 2, 'react/no-direct-mutation-state': 2, 'react/no-find-dom-node': 2, 'react/no-multi-comp': [ 2, { ignoreStateless: true, }, ], 'react/no-render-return-value': 2, 'react/no-string-refs': 2, 'react/no-unknown-property': 2, 'react/prefer-es6-class': [2, 'always'], 'react/prop-types': 2, 'react/require-render-return': 2, 'react/sort-comp': [ 2, { order: [ 'static-methods', 'lifecycle', 'render', 'everything-else', ], }, ], 'react/sort-prop-types': 2, 'react/style-prop-object': 2, }, }
export const ELEMENTS = { FIELD: "field", MESSAGE: "message", FORM: "form", VIEW: "view" }; export const DISPLAY = { ALWAYS: 0, CHANGED: 1, DIRTY: 2, TOUCHED: 3, SUBMITTED: 4, NEVER: 5 };