text
stringlengths
7
3.69M
import styled from 'styled-components'; const Footer = (props)=>{ return( <Container> <h3>all rights reserved © Adruich</h3> </Container> ) }; export default Footer; const Container = styled.footer` display:flex; height:50px; background-color: #090b13; justify-content:center; align-items:center; letter-spacing:1.6px; z-index:3; font-size:12px; `;
// { "framework": "Vue"} if(typeof app=="undefined"){app=weex} if(typeof eeuiLog=="undefined"){var eeuiLog={_:function(t,e){var s=e.map(function(e){return e="[object object]"===Object.prototype.toString.call(e).toLowerCase()?JSON.stringify(e):e});if(typeof this.__m==='undefined'){this.__m=app.requireModule('debug')}this.__m.addLog(t,s)},debug:function(){for(var e=[],t=arguments.length;t--;)e[t]=arguments[t];this._("debug",e)},log:function(){for(var e=[],t=arguments.length;t--;)e[t]=arguments[t];this._("log",e)},info:function(){for(var e=[],t=arguments.length;t--;)e[t]=arguments[t];this._("info",e)},warn:function(){for(var e=[],t=arguments.length;t--;)e[t]=arguments[t];this._("warn",e)},error:function(){for(var e=[],t=arguments.length;t--;)e[t]=arguments[t];this._("error",e)}}} /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) { /******/ return installedModules[moduleId].exports; /******/ } /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ i: moduleId, /******/ l: false, /******/ exports: {} /******/ }; /******/ /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ /******/ // Flag the module as loaded /******/ module.l = true; /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ /******/ /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ /******/ // define getter function for harmony exports /******/ __webpack_require__.d = function(exports, name, getter) { /******/ if(!__webpack_require__.o(exports, name)) { /******/ Object.defineProperty(exports, name, { enumerable: true, get: getter }); /******/ } /******/ }; /******/ /******/ // define __esModule on exports /******/ __webpack_require__.r = function(exports) { /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); /******/ } /******/ Object.defineProperty(exports, '__esModule', { value: true }); /******/ }; /******/ /******/ // create a fake namespace object /******/ // mode & 1: value is a module id, require it /******/ // mode & 2: merge all properties of value into the ns /******/ // mode & 4: return value when already ns object /******/ // mode & 8|1: behave like require /******/ __webpack_require__.t = function(value, mode) { /******/ if(mode & 1) value = __webpack_require__(value); /******/ if(mode & 8) return value; /******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value; /******/ var ns = Object.create(null); /******/ __webpack_require__.r(ns); /******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value }); /******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key)); /******/ return ns; /******/ }; /******/ /******/ // getDefaultExport function for compatibility with non-harmony modules /******/ __webpack_require__.n = function(module) { /******/ var getter = module && module.__esModule ? /******/ function getDefault() { return module['default']; } : /******/ function getModuleExports() { return module; }; /******/ __webpack_require__.d(getter, 'a', getter); /******/ return getter; /******/ }; /******/ /******/ // Object.prototype.hasOwnProperty.call /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; /******/ /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(__webpack_require__.s = "./src/pages/homePages/editpage.vue?entry=true"); /******/ }) /************************************************************************/ /******/ ({ /***/ "./node_modules/_querystringify@2.1.1@querystringify/index.js": /*!********************************************************************!*\ !*** ./node_modules/_querystringify@2.1.1@querystringify/index.js ***! \********************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var has = Object.prototype.hasOwnProperty, undef; /** * Decode a URI encoded string. * * @param {String} input The URI encoded string. * @returns {String|Null} The decoded string. * @api private */ function decode(input) { try { return decodeURIComponent(input.replace(/\+/g, ' ')); } catch (e) { return null; } } /** * Attempts to encode a given input. * * @param {String} input The string that needs to be encoded. * @returns {String|Null} The encoded string. * @api private */ function encode(input) { try { return encodeURIComponent(input); } catch (e) { return null; } } /** * Simple query string parser. * * @param {String} query The query string that needs to be parsed. * @returns {Object} * @api public */ function querystring(query) { var parser = /([^=?&]+)=?([^&]*)/g, result = {}, part; while (part = parser.exec(query)) { var key = decode(part[1]), value = decode(part[2]); // // Prevent overriding of existing properties. This ensures that build-in // methods like `toString` or __proto__ are not overriden by malicious // querystrings. // // In the case if failed decoding, we want to omit the key/value pairs // from the result. // if (key === null || value === null || key in result) continue; result[key] = value; } return result; } /** * Transform a query string to an object. * * @param {Object} obj Object that should be transformed. * @param {String} prefix Optional prefix. * @returns {String} * @api public */ function querystringify(obj, prefix) { prefix = prefix || ''; var pairs = [], value, key; // // Optionally prefix with a '?' if needed // if ('string' !== typeof prefix) prefix = '?'; for (key in obj) { if (has.call(obj, key)) { value = obj[key]; // // Edge cases where we actually want to encode the value to an empty // string instead of the stringified value. // if (!value && (value === null || value === undef || isNaN(value))) { value = ''; } key = encodeURIComponent(key); value = encodeURIComponent(value); // // If we failed to encode the strings, we should bail out as we don't // want to add invalid strings to the query. // if (key === null || value === null) continue; pairs.push(key + '=' + value); } } return pairs.length ? prefix + pairs.join('&') : ''; } // // Expose the module. // exports.stringify = querystringify; exports.parse = querystring; /***/ }), /***/ "./node_modules/_requires-port@1.0.0@requires-port/index.js": /*!******************************************************************!*\ !*** ./node_modules/_requires-port@1.0.0@requires-port/index.js ***! \******************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Check if we're required to add a port number. * * @see https://url.spec.whatwg.org/#default-port * @param {Number|String} port Port number we need to check * @param {String} protocol Protocol we need to check against. * @returns {Boolean} Is it a default port for the given protocol * @api private */ module.exports = function required(port, protocol) { protocol = protocol.split(':')[0]; port = +port; if (!port) return false; switch (protocol) { case 'http': case 'ws': return port !== 80; case 'https': case 'wss': return port !== 443; case 'ftp': return port !== 21; case 'gopher': return port !== 70; case 'file': return false; } return port !== 0; }; /***/ }), /***/ "./node_modules/_url-parse@1.4.7@url-parse/index.js": /*!**********************************************************!*\ !*** ./node_modules/_url-parse@1.4.7@url-parse/index.js ***! \**********************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /* WEBPACK VAR INJECTION */(function(global) { function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } var required = __webpack_require__(/*! requires-port */ "./node_modules/_requires-port@1.0.0@requires-port/index.js"), qs = __webpack_require__(/*! querystringify */ "./node_modules/_querystringify@2.1.1@querystringify/index.js"), slashes = /^[A-Za-z][A-Za-z0-9+-.]*:\/\//, protocolre = /^([a-z][a-z0-9.+-]*:)?(\/\/)?([\S\s]*)/i, whitespace = "[\\x09\\x0A\\x0B\\x0C\\x0D\\x20\\xA0\\u1680\\u180E\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200A\\u202F\\u205F\\u3000\\u2028\\u2029\\uFEFF]", left = new RegExp('^' + whitespace + '+'); /** * Trim a given string. * * @param {String} str String to trim. * @public */ function trimLeft(str) { return (str ? str : '').toString().replace(left, ''); } /** * These are the parse rules for the URL parser, it informs the parser * about: * * 0. The char it Needs to parse, if it's a string it should be done using * indexOf, RegExp using exec and NaN means set as current value. * 1. The property we should set when parsing this value. * 2. Indication if it's backwards or forward parsing, when set as number it's * the value of extra chars that should be split off. * 3. Inherit from location if non existing in the parser. * 4. `toLowerCase` the resulting value. */ var rules = [['#', 'hash'], // Extract from the back. ['?', 'query'], // Extract from the back. function sanitize(address) { // Sanitize what is left of the address return address.replace('\\', '/'); }, ['/', 'pathname'], // Extract from the back. ['@', 'auth', 1], // Extract from the front. [NaN, 'host', undefined, 1, 1], // Set left over value. [/:(\d+)$/, 'port', undefined, 1], // RegExp the back. [NaN, 'hostname', undefined, 1, 1] // Set left over. ]; /** * These properties should not be copied or inherited from. This is only needed * for all non blob URL's as a blob URL does not include a hash, only the * origin. * * @type {Object} * @private */ var ignore = { hash: 1, query: 1 }; /** * The location object differs when your code is loaded through a normal page, * Worker or through a worker using a blob. And with the blobble begins the * trouble as the location object will contain the URL of the blob, not the * location of the page where our code is loaded in. The actual origin is * encoded in the `pathname` so we can thankfully generate a good "default" * location from it so we can generate proper relative URL's again. * * @param {Object|String} loc Optional default location object. * @returns {Object} lolcation object. * @public */ function lolcation(loc) { var globalVar; if (typeof window !== 'undefined') globalVar = window;else if (typeof global !== 'undefined') globalVar = global;else if (typeof self !== 'undefined') globalVar = self;else globalVar = {}; var location = globalVar.location || {}; loc = loc || location; var finaldestination = {}, type = _typeof(loc), key; if ('blob:' === loc.protocol) { finaldestination = new Url(unescape(loc.pathname), {}); } else if ('string' === type) { finaldestination = new Url(loc, {}); for (key in ignore) { delete finaldestination[key]; } } else if ('object' === type) { for (key in loc) { if (key in ignore) continue; finaldestination[key] = loc[key]; } if (finaldestination.slashes === undefined) { finaldestination.slashes = slashes.test(loc.href); } } return finaldestination; } /** * @typedef ProtocolExtract * @type Object * @property {String} protocol Protocol matched in the URL, in lowercase. * @property {Boolean} slashes `true` if protocol is followed by "//", else `false`. * @property {String} rest Rest of the URL that is not part of the protocol. */ /** * Extract protocol information from a URL with/without double slash ("//"). * * @param {String} address URL we want to extract from. * @return {ProtocolExtract} Extracted information. * @private */ function extractProtocol(address) { address = trimLeft(address); var match = protocolre.exec(address); return { protocol: match[1] ? match[1].toLowerCase() : '', slashes: !!match[2], rest: match[3] }; } /** * Resolve a relative URL pathname against a base URL pathname. * * @param {String} relative Pathname of the relative URL. * @param {String} base Pathname of the base URL. * @return {String} Resolved pathname. * @private */ function resolve(relative, base) { if (relative === '') return base; var path = (base || '/').split('/').slice(0, -1).concat(relative.split('/')), i = path.length, last = path[i - 1], unshift = false, up = 0; while (i--) { if (path[i] === '.') { path.splice(i, 1); } else if (path[i] === '..') { path.splice(i, 1); up++; } else if (up) { if (i === 0) unshift = true; path.splice(i, 1); up--; } } if (unshift) path.unshift(''); if (last === '.' || last === '..') path.push(''); return path.join('/'); } /** * The actual URL instance. Instead of returning an object we've opted-in to * create an actual constructor as it's much more memory efficient and * faster and it pleases my OCD. * * It is worth noting that we should not use `URL` as class name to prevent * clashes with the global URL instance that got introduced in browsers. * * @constructor * @param {String} address URL we want to parse. * @param {Object|String} [location] Location defaults for relative paths. * @param {Boolean|Function} [parser] Parser for the query string. * @private */ function Url(address, location, parser) { address = trimLeft(address); if (!(this instanceof Url)) { return new Url(address, location, parser); } var relative, extracted, parse, instruction, index, key, instructions = rules.slice(), type = _typeof(location), url = this, i = 0; // // The following if statements allows this module two have compatibility with // 2 different API: // // 1. Node.js's `url.parse` api which accepts a URL, boolean as arguments // where the boolean indicates that the query string should also be parsed. // // 2. The `URL` interface of the browser which accepts a URL, object as // arguments. The supplied object will be used as default values / fall-back // for relative paths. // if ('object' !== type && 'string' !== type) { parser = location; location = null; } if (parser && 'function' !== typeof parser) parser = qs.parse; location = lolcation(location); // // Extract protocol information before running the instructions. // extracted = extractProtocol(address || ''); relative = !extracted.protocol && !extracted.slashes; url.slashes = extracted.slashes || relative && location.slashes; url.protocol = extracted.protocol || location.protocol || ''; address = extracted.rest; // // When the authority component is absent the URL starts with a path // component. // if (!extracted.slashes) instructions[3] = [/(.*)/, 'pathname']; for (; i < instructions.length; i++) { instruction = instructions[i]; if (typeof instruction === 'function') { address = instruction(address); continue; } parse = instruction[0]; key = instruction[1]; if (parse !== parse) { url[key] = address; } else if ('string' === typeof parse) { if (~(index = address.indexOf(parse))) { if ('number' === typeof instruction[2]) { url[key] = address.slice(0, index); address = address.slice(index + instruction[2]); } else { url[key] = address.slice(index); address = address.slice(0, index); } } } else if (index = parse.exec(address)) { url[key] = index[1]; address = address.slice(0, index.index); } url[key] = url[key] || (relative && instruction[3] ? location[key] || '' : ''); // // Hostname, host and protocol should be lowercased so they can be used to // create a proper `origin`. // if (instruction[4]) url[key] = url[key].toLowerCase(); } // // Also parse the supplied query string in to an object. If we're supplied // with a custom parser as function use that instead of the default build-in // parser. // if (parser) url.query = parser(url.query); // // If the URL is relative, resolve the pathname against the base URL. // if (relative && location.slashes && url.pathname.charAt(0) !== '/' && (url.pathname !== '' || location.pathname !== '')) { url.pathname = resolve(url.pathname, location.pathname); } // // We should not add port numbers if they are already the default port number // for a given protocol. As the host also contains the port number we're going // override it with the hostname which contains no port number. // if (!required(url.port, url.protocol)) { url.host = url.hostname; url.port = ''; } // // Parse down the `auth` for the username and password. // url.username = url.password = ''; if (url.auth) { instruction = url.auth.split(':'); url.username = instruction[0] || ''; url.password = instruction[1] || ''; } url.origin = url.protocol && url.host && url.protocol !== 'file:' ? url.protocol + '//' + url.host : 'null'; // // The href is just the compiled result. // url.href = url.toString(); } /** * This is convenience method for changing properties in the URL instance to * insure that they all propagate correctly. * * @param {String} part Property we need to adjust. * @param {Mixed} value The newly assigned value. * @param {Boolean|Function} fn When setting the query, it will be the function * used to parse the query. * When setting the protocol, double slash will be * removed from the final url if it is true. * @returns {URL} URL instance for chaining. * @public */ function set(part, value, fn) { var url = this; switch (part) { case 'query': if ('string' === typeof value && value.length) { value = (fn || qs.parse)(value); } url[part] = value; break; case 'port': url[part] = value; if (!required(value, url.protocol)) { url.host = url.hostname; url[part] = ''; } else if (value) { url.host = url.hostname + ':' + value; } break; case 'hostname': url[part] = value; if (url.port) value += ':' + url.port; url.host = value; break; case 'host': url[part] = value; if (/:\d+$/.test(value)) { value = value.split(':'); url.port = value.pop(); url.hostname = value.join(':'); } else { url.hostname = value; url.port = ''; } break; case 'protocol': url.protocol = value.toLowerCase(); url.slashes = !fn; break; case 'pathname': case 'hash': if (value) { var _char = part === 'pathname' ? '/' : '#'; url[part] = value.charAt(0) !== _char ? _char + value : value; } else { url[part] = value; } break; default: url[part] = value; } for (var i = 0; i < rules.length; i++) { var ins = rules[i]; if (ins[4]) url[ins[1]] = url[ins[1]].toLowerCase(); } url.origin = url.protocol && url.host && url.protocol !== 'file:' ? url.protocol + '//' + url.host : 'null'; url.href = url.toString(); return url; } /** * Transform the properties back in to a valid and full URL string. * * @param {Function} stringify Optional query stringify function. * @returns {String} Compiled version of the URL. * @public */ function toString(stringify) { if (!stringify || 'function' !== typeof stringify) stringify = qs.stringify; var query, url = this, protocol = url.protocol; if (protocol && protocol.charAt(protocol.length - 1) !== ':') protocol += ':'; var result = protocol + (url.slashes ? '//' : ''); if (url.username) { result += url.username; if (url.password) result += ':' + url.password; result += '@'; } result += url.host + url.pathname; query = 'object' === _typeof(url.query) ? stringify(url.query) : url.query; if (query) result += '?' !== query.charAt(0) ? '?' + query : query; if (url.hash) result += url.hash; return result; } Url.prototype = { set: set, toString: toString }; // // Expose the URL parser and some additional properties that might be useful for // others or testing. // Url.extractProtocol = extractProtocol; Url.location = lolcation; Url.trimLeft = trimLeft; Url.qs = qs; module.exports = Url; /* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! (webpack)/buildin/global.js */ "C:\\Users\\10844\\AppData\\Roaming\\npm\\node_modules\\eeui-cli\\node_modules\\_webpack@4.42.1@webpack\\buildin\\global.js"))) /***/ }), /***/ "./node_modules/_weex-ui@0.8.4@weex-ui/packages/utils/index.js": /*!*********************************************************************!*\ !*** ./node_modules/_weex-ui@0.8.4@weex-ui/packages/utils/index.js ***! \*********************************************************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var url_parse__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! url-parse */ "./node_modules/_url-parse@1.4.7@url-parse/index.js"); /* harmony import */ var url_parse__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(url_parse__WEBPACK_IMPORTED_MODULE_0__); function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } function _typeof2(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof2 = function _typeof2(obj) { return typeof obj; }; } else { _typeof2 = function _typeof2(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof2(obj); } /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ var Utils = { UrlParser: url_parse__WEBPACK_IMPORTED_MODULE_0___default.a, _typeof: function _typeof(obj) { return Object.prototype.toString.call(obj).slice(8, -1).toLowerCase(); }, isPlainObject: function isPlainObject(obj) { return Utils._typeof(obj) === 'object'; }, isString: function isString(obj) { return typeof obj === 'string'; }, isNonEmptyArray: function isNonEmptyArray() { var obj = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : []; return obj && obj.length > 0 && Array.isArray(obj) && typeof obj !== 'undefined'; }, isObject: function isObject(item) { return item && _typeof2(item) === 'object' && !Array.isArray(item); }, isEmptyObject: function isEmptyObject(obj) { return Object.keys(obj).length === 0 && obj.constructor === Object; }, decodeIconFont: function decodeIconFont(text) { // 正则匹配 图标和文字混排 eg: 我去上学校&#xe600;,天天不&#xe600;迟到 var regExp = /&#x[a-z|0-9]{4,5};?/g; if (regExp.test(text)) { return text.replace(new RegExp(regExp, 'g'), function (iconText) { var replace = iconText.replace(/&#x/, '0x').replace(/;$/, ''); return String.fromCharCode(replace); }); } else { return text; } }, mergeDeep: function mergeDeep(target) { for (var _len = arguments.length, sources = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { sources[_key - 1] = arguments[_key]; } if (!sources.length) return target; var source = sources.shift(); if (Utils.isObject(target) && Utils.isObject(source)) { for (var key in source) { if (Utils.isObject(source[key])) { if (!target[key]) { Object.assign(target, _defineProperty({}, key, {})); } Utils.mergeDeep(target[key], source[key]); } else { Object.assign(target, _defineProperty({}, key, source[key])); } } } return Utils.mergeDeep.apply(Utils, [target].concat(sources)); }, appendProtocol: function appendProtocol(url) { if (/^\/\//.test(url)) { var bundleUrl = weex.config.bundleUrl; return "http".concat(/^https:/.test(bundleUrl) ? 's' : '', ":").concat(url); } return url; }, encodeURLParams: function encodeURLParams(url) { var parsedUrl = new url_parse__WEBPACK_IMPORTED_MODULE_0___default.a(url, true); return parsedUrl.toString(); }, goToH5Page: function goToH5Page(jumpUrl) { var animated = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; var callback = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null; var Navigator = weex.requireModule('navigator'); var jumpUrlObj = new Utils.UrlParser(jumpUrl, true); var url = Utils.appendProtocol(jumpUrlObj.toString()); Navigator.push({ url: Utils.encodeURLParams(url), animated: animated.toString() }, callback); }, env: { isTaobao: function isTaobao() { var appName = weex.config.env.appName; return /(tb|taobao|淘宝)/i.test(appName); }, isTrip: function isTrip() { var appName = weex.config.env.appName; return appName === 'LX'; }, isBoat: function isBoat() { var appName = weex.config.env.appName; return appName === 'Boat' || appName === 'BoatPlayground'; }, isWeb: function isWeb() { var platform = weex.config.env.platform; return (typeof window === "undefined" ? "undefined" : _typeof2(window)) === 'object' && platform.toLowerCase() === 'web'; }, isIOS: function isIOS() { var platform = weex.config.env.platform; return platform.toLowerCase() === 'ios'; }, /** * 是否为 iPhone X or iPhoneXS or iPhoneXR or iPhoneXS Max * @returns {boolean} */ isIPhoneX: function isIPhoneX() { var deviceHeight = weex.config.env.deviceHeight; if (Utils.env.isWeb()) { return (typeof window === "undefined" ? "undefined" : _typeof2(window)) !== undefined && window.screen && window.screen.width && window.screen.height && (parseInt(window.screen.width, 10) === 375 && parseInt(window.screen.height, 10) === 812 || parseInt(window.screen.width, 10) === 414 && parseInt(window.screen.height, 10) === 896); } return Utils.env.isIOS() && (deviceHeight === 2436 || deviceHeight === 2688 || deviceHeight === 1792 || deviceHeight === 1624); }, isAndroid: function isAndroid() { var platform = weex.config.env.platform; return platform.toLowerCase() === 'android'; }, isTmall: function isTmall() { var appName = weex.config.env.appName; return /(tm|tmall|天猫)/i.test(appName); }, isAliWeex: function isAliWeex() { return Utils.env.isTmall() || Utils.env.isTrip() || Utils.env.isTaobao(); }, /** * 获取weex屏幕真实的设置高度,需要减去导航栏高度 * @returns {Number} */ getPageHeight: function getPageHeight() { var env = weex.config.env; var navHeight = Utils.env.isWeb() ? 0 : Utils.env.isIPhoneX() ? 176 : 132; return env.deviceHeight / env.deviceWidth * 750 - navHeight; }, /** * 获取weex屏幕真实的设置高度 * @returns {Number} */ getScreenHeight: function getScreenHeight() { var env = weex.config.env; return env.deviceHeight / env.deviceWidth * 750; } }, /** * 版本号比较 * @memberOf Utils * @param currVer {string} * @param promoteVer {string} * @returns {boolean} * @example * * const { Utils } = require('@ali/wx-bridge'); * const { compareVersion } = Utils; * eeuiLog.log(compareVersion('0.1.100', '0.1.11')); // 'true' */ compareVersion: function compareVersion() { var currVer = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '0.0.0'; var promoteVer = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '0.0.0'; if (currVer === promoteVer) return true; var currVerArr = currVer.split('.'); var promoteVerArr = promoteVer.split('.'); var len = Math.max(currVerArr.length, promoteVerArr.length); for (var i = 0; i < len; i++) { var proVal = ~~promoteVerArr[i]; var curVal = ~~currVerArr[i]; if (proVal < curVal) { return true; } else if (proVal > curVal) { return false; } } return false; }, /** * 分割数组 * @param arr 被分割数组 * @param size 分割数组的长度 * @returns {Array} */ arrayChunk: function arrayChunk() { var arr = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : []; var size = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 4; var groups = []; if (arr && arr.length > 0) { groups = arr.map(function (e, i) { return i % size === 0 ? arr.slice(i, i + size) : null; }).filter(function (e) { return e; }); } return groups; }, /* * 截断字符串 * @param str 传入字符串 * @param len 截断长度 * @param hasDot 末尾是否... * @returns {String} */ truncateString: function truncateString(str, len) { var hasDot = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true; var newLength = 0; var newStr = ''; var singleChar = ''; var chineseRegex = /[^\x00-\xff]/g; var strLength = str.replace(chineseRegex, '**').length; for (var i = 0; i < strLength; i++) { singleChar = str.charAt(i).toString(); if (singleChar.match(chineseRegex) !== null) { newLength += 2; } else { newLength++; } if (newLength > len) { break; } newStr += singleChar; } if (hasDot && strLength > len) { newStr += '...'; } return newStr; }, /* * 转换 obj 为 url params参数 * @param obj 传入字符串 * @returns {String} */ objToParams: function objToParams(obj) { var str = ''; for (var key in obj) { if (str !== '') { str += '&'; } str += key + '=' + encodeURIComponent(obj[key]); } return str; }, /* * 转换 url params参数为obj * @param str 传入url参数字符串 * @returns {Object} */ paramsToObj: function paramsToObj(str) { var obj = {}; try { obj = JSON.parse('{"' + decodeURI(str).replace(/"/g, '\\"').replace(/&/g, '","').replace(/=/g, '":"') + '"}'); } catch (e) { eeuiLog.log(e); } return obj; }, animation: { /** * 返回定义页面转场动画起初的位置 * @param ref * @param transform 运动类型 * @param status * @param callback 回调函数 */ pageTransitionAnimation: function pageTransitionAnimation(ref, transform, status, callback) { var animation = weex.requireModule('animation'); animation.transition(ref, { styles: { transform: transform }, duration: status ? 250 : 300, // ms timingFunction: status ? 'ease-in' : 'ease-out', delay: 0 // ms }, function () { callback && callback(); }); } }, uiStyle: { /** * 返回定义页面转场动画起初的位置 * @param animationType 页面转场动画的类型 push,model * @param size 分割数组的长度 * @returns {} */ pageTransitionAnimationStyle: function pageTransitionAnimationStyle(animationType) { if (animationType === 'push') { return { left: '750px', top: '0px', height: weex.config.env.deviceHeight / weex.config.env.deviceWidth * 750 + 'px' }; } else if (animationType === 'model') { return { top: weex.config.env.deviceHeight / weex.config.env.deviceWidth * 750 + 'px', left: '0px', height: weex.config.env.deviceHeight / weex.config.env.deviceWidth * 750 + 'px' }; } return {}; } } }; /* harmony default export */ __webpack_exports__["default"] = (Utils); /***/ }), /***/ "./node_modules/_weex-ui@0.8.4@weex-ui/packages/wxc-cell/index.js": /*!************************************************************************!*\ !*** ./node_modules/_weex-ui@0.8.4@weex-ui/packages/wxc-cell/index.js ***! \************************************************************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _index_vue__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./index.vue */ "./node_modules/_weex-ui@0.8.4@weex-ui/packages/wxc-cell/index.vue"); /* harmony import */ var _index_vue__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_index_vue__WEBPACK_IMPORTED_MODULE_0__); /* harmony reexport (default from non-harmony) */ __webpack_require__.d(__webpack_exports__, "default", function() { return _index_vue__WEBPACK_IMPORTED_MODULE_0___default.a; }); /***/ }), /***/ "./node_modules/_weex-ui@0.8.4@weex-ui/packages/wxc-cell/index.vue": /*!*************************************************************************!*\ !*** ./node_modules/_weex-ui@0.8.4@weex-ui/packages/wxc-cell/index.vue ***! \*************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { var __vue_exports__, __vue_options__ var __vue_styles__ = [] /* styles */ __vue_styles__.push(__webpack_require__(/*! !C:/Users/10844/AppData/Roaming/npm/node_modules/eeui-cli/lib/loaders/eeui-loader/lib/style-loader!C:/Users/10844/AppData/Roaming/npm/node_modules/eeui-cli/lib/loaders/eeui-loader/lib/style-rewriter?id=data-v-149d58ea!C:/Users/10844/AppData/Roaming/npm/node_modules/eeui-cli/lib/loaders/eeui-loader/lib/selector?type=styles&index=0!./index.vue */ "C:\\Users\\10844\\AppData\\Roaming\\npm\\node_modules\\eeui-cli\\lib\\loaders\\eeui-loader\\lib\\style-loader.js!C:\\Users\\10844\\AppData\\Roaming\\npm\\node_modules\\eeui-cli\\lib\\loaders\\eeui-loader\\lib\\style-rewriter.js?id=data-v-149d58ea!C:\\Users\\10844\\AppData\\Roaming\\npm\\node_modules\\eeui-cli\\lib\\loaders\\eeui-loader\\lib\\selector.js?type=styles&index=0!./node_modules/_weex-ui@0.8.4@weex-ui/packages/wxc-cell/index.vue") ) /* script */ __vue_exports__ = __webpack_require__(/*! !C:/Users/10844/AppData/Roaming/npm/node_modules/eeui-cli/lib/loaders/eeui-loader/lib/script-loader!babel-loader!C:/Users/10844/AppData/Roaming/npm/node_modules/eeui-cli/lib/loaders/eeui-loader/lib/selector?type=script&index=0!./index.vue */ "C:\\Users\\10844\\AppData\\Roaming\\npm\\node_modules\\eeui-cli\\lib\\loaders\\eeui-loader\\lib\\script-loader.js!C:\\Users\\10844\\AppData\\Roaming\\npm\\node_modules\\eeui-cli\\node_modules\\_babel-loader@8.1.0@babel-loader\\lib\\index.js!C:\\Users\\10844\\AppData\\Roaming\\npm\\node_modules\\eeui-cli\\lib\\loaders\\eeui-loader\\lib\\selector.js?type=script&index=0!./node_modules/_weex-ui@0.8.4@weex-ui/packages/wxc-cell/index.vue") /* template */ var __vue_template__ = __webpack_require__(/*! !C:/Users/10844/AppData/Roaming/npm/node_modules/eeui-cli/lib/loaders/eeui-loader/lib/template-compiler?id=data-v-149d58ea!C:/Users/10844/AppData/Roaming/npm/node_modules/eeui-cli/lib/loaders/eeui-loader/lib/selector?type=template&index=0!./index.vue */ "C:\\Users\\10844\\AppData\\Roaming\\npm\\node_modules\\eeui-cli\\lib\\loaders\\eeui-loader\\lib\\template-compiler.js?id=data-v-149d58ea!C:\\Users\\10844\\AppData\\Roaming\\npm\\node_modules\\eeui-cli\\lib\\loaders\\eeui-loader\\lib\\selector.js?type=template&index=0!./node_modules/_weex-ui@0.8.4@weex-ui/packages/wxc-cell/index.vue") __vue_options__ = __vue_exports__ = __vue_exports__ || {} if ( typeof __vue_exports__.default === "object" || typeof __vue_exports__.default === "function" ) { if (Object.keys(__vue_exports__).some(function (key) { return key !== "default" && key !== "__esModule" })) {eeuiLog.error("named exports are not supported in *.vue files.")} __vue_options__ = __vue_exports__ = __vue_exports__.default } if (typeof __vue_options__ === "function") { __vue_options__ = __vue_options__.options } __vue_options__.__file = "F:\\workspace\\weexZruup\\zruupApp\\node_modules\\_weex-ui@0.8.4@weex-ui\\packages\\wxc-cell\\index.vue" __vue_options__.render = __vue_template__.render __vue_options__.staticRenderFns = __vue_template__.staticRenderFns __vue_options__._scopeId = "data-v-149d58ea" __vue_options__.style = __vue_options__.style || {} __vue_styles__.forEach(function (module) { for (var name in module) { __vue_options__.style[name] = module[name] } }) if (typeof __register_static_styles__ === "function") { __register_static_styles__(__vue_options__._scopeId, __vue_styles__) } module.exports = __vue_exports__ /***/ }), /***/ "./src/pages/homePages/editpage.vue?entry=true": /*!*****************************************************!*\ !*** ./src/pages/homePages/editpage.vue?entry=true ***! \*****************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { var __vue_exports__, __vue_options__ var __vue_styles__ = [] /* styles */ __vue_styles__.push(__webpack_require__(/*! !C:/Users/10844/AppData/Roaming/npm/node_modules/eeui-cli/lib/loaders/eeui-loader/lib/style-loader!C:/Users/10844/AppData/Roaming/npm/node_modules/eeui-cli/lib/loaders/eeui-loader/lib/style-rewriter?id=data-v-2c762c0e!C:/Users/10844/AppData/Roaming/npm/node_modules/eeui-cli/lib/loaders/eeui-loader/lib/selector?type=styles&index=0!./editpage.vue */ "C:\\Users\\10844\\AppData\\Roaming\\npm\\node_modules\\eeui-cli\\lib\\loaders\\eeui-loader\\lib\\style-loader.js!C:\\Users\\10844\\AppData\\Roaming\\npm\\node_modules\\eeui-cli\\lib\\loaders\\eeui-loader\\lib\\style-rewriter.js?id=data-v-2c762c0e!C:\\Users\\10844\\AppData\\Roaming\\npm\\node_modules\\eeui-cli\\lib\\loaders\\eeui-loader\\lib\\selector.js?type=styles&index=0!./src/pages/homePages/editpage.vue") ) /* script */ __vue_exports__ = __webpack_require__(/*! !C:/Users/10844/AppData/Roaming/npm/node_modules/eeui-cli/lib/loaders/eeui-loader/lib/script-loader!babel-loader!C:/Users/10844/AppData/Roaming/npm/node_modules/eeui-cli/lib/loaders/eeui-loader/lib/selector?type=script&index=0!./editpage.vue */ "C:\\Users\\10844\\AppData\\Roaming\\npm\\node_modules\\eeui-cli\\lib\\loaders\\eeui-loader\\lib\\script-loader.js!C:\\Users\\10844\\AppData\\Roaming\\npm\\node_modules\\eeui-cli\\node_modules\\_babel-loader@8.1.0@babel-loader\\lib\\index.js!C:\\Users\\10844\\AppData\\Roaming\\npm\\node_modules\\eeui-cli\\lib\\loaders\\eeui-loader\\lib\\selector.js?type=script&index=0!./src/pages/homePages/editpage.vue") /* template */ var __vue_template__ = __webpack_require__(/*! !C:/Users/10844/AppData/Roaming/npm/node_modules/eeui-cli/lib/loaders/eeui-loader/lib/template-compiler?id=data-v-2c762c0e!C:/Users/10844/AppData/Roaming/npm/node_modules/eeui-cli/lib/loaders/eeui-loader/lib/selector?type=template&index=0!./editpage.vue */ "C:\\Users\\10844\\AppData\\Roaming\\npm\\node_modules\\eeui-cli\\lib\\loaders\\eeui-loader\\lib\\template-compiler.js?id=data-v-2c762c0e!C:\\Users\\10844\\AppData\\Roaming\\npm\\node_modules\\eeui-cli\\lib\\loaders\\eeui-loader\\lib\\selector.js?type=template&index=0!./src/pages/homePages/editpage.vue") __vue_options__ = __vue_exports__ = __vue_exports__ || {} if ( typeof __vue_exports__.default === "object" || typeof __vue_exports__.default === "function" ) { if (Object.keys(__vue_exports__).some(function (key) { return key !== "default" && key !== "__esModule" })) {eeuiLog.error("named exports are not supported in *.vue files.")} __vue_options__ = __vue_exports__ = __vue_exports__.default } if (typeof __vue_options__ === "function") { __vue_options__ = __vue_options__.options } __vue_options__.__file = "F:\\workspace\\weexZruup\\zruupApp\\src\\pages\\homePages\\editpage.vue" __vue_options__.render = __vue_template__.render __vue_options__.staticRenderFns = __vue_template__.staticRenderFns __vue_options__._scopeId = "data-v-2c762c0e" __vue_options__.style = __vue_options__.style || {} __vue_styles__.forEach(function (module) { for (var name in module) { __vue_options__.style[name] = module[name] } }) if (typeof __register_static_styles__ === "function") { __register_static_styles__(__vue_options__._scopeId, __vue_styles__) } module.exports = __vue_exports__ module.exports.el = 'true' new Vue(module.exports) /***/ }), /***/ "C:\\Users\\10844\\AppData\\Roaming\\npm\\node_modules\\eeui-cli\\lib\\loaders\\eeui-loader\\lib\\script-loader.js!C:\\Users\\10844\\AppData\\Roaming\\npm\\node_modules\\eeui-cli\\node_modules\\_babel-loader@8.1.0@babel-loader\\lib\\index.js!C:\\Users\\10844\\AppData\\Roaming\\npm\\node_modules\\eeui-cli\\lib\\loaders\\eeui-loader\\lib\\selector.js?type=script&index=0!./node_modules/_weex-ui@0.8.4@weex-ui/packages/wxc-cell/index.vue": /*!***************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************!*\ !*** C:/Users/10844/AppData/Roaming/npm/node_modules/eeui-cli/lib/loaders/eeui-loader/lib/script-loader.js!C:/Users/10844/AppData/Roaming/npm/node_modules/eeui-cli/node_modules/_babel-loader@8.1.0@babel-loader/lib!C:/Users/10844/AppData/Roaming/npm/node_modules/eeui-cli/lib/loaders/eeui-loader/lib/selector.js?type=script&index=0!./node_modules/_weex-ui@0.8.4@weex-ui/packages/wxc-cell/index.vue ***! \***************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../utils */ "./node_modules/_weex-ui@0.8.4@weex-ui/packages/utils/index.js"); // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // /* harmony default export */ __webpack_exports__["default"] = ({ props: { label: { type: String, default: '' }, title: { type: String, default: '' }, extraContent: { type: String, default: '' }, desc: { type: String, default: '' }, link: { type: String, default: '' }, hasTopBorder: { type: Boolean, default: false }, hasMargin: { type: Boolean, default: false }, hasBottomBorder: { type: Boolean, default: true }, hasArrow: { type: Boolean, default: false }, arrowIcon: { type: String, default: 'https://gw.alicdn.com/tfs/TB11zBUpwMPMeJjy1XbXXcwxVXa-22-22.png' }, hasVerticalIndent: { type: Boolean, default: true }, cellStyle: { type: Object, default: () => ({}) }, autoAccessible: { type: Boolean, default: true } }, methods: { cellClicked(e) { const link = this.link; this.$emit('wxcCellClicked', { e }); link && _utils__WEBPACK_IMPORTED_MODULE_0__["default"].goToH5Page(link, true); } } }); /***/ }), /***/ "C:\\Users\\10844\\AppData\\Roaming\\npm\\node_modules\\eeui-cli\\lib\\loaders\\eeui-loader\\lib\\script-loader.js!C:\\Users\\10844\\AppData\\Roaming\\npm\\node_modules\\eeui-cli\\node_modules\\_babel-loader@8.1.0@babel-loader\\lib\\index.js!C:\\Users\\10844\\AppData\\Roaming\\npm\\node_modules\\eeui-cli\\lib\\loaders\\eeui-loader\\lib\\selector.js?type=script&index=0!./src/pages/homePages/editpage.vue": /*!********************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************!*\ !*** C:/Users/10844/AppData/Roaming/npm/node_modules/eeui-cli/lib/loaders/eeui-loader/lib/script-loader.js!C:/Users/10844/AppData/Roaming/npm/node_modules/eeui-cli/node_modules/_babel-loader@8.1.0@babel-loader/lib!C:/Users/10844/AppData/Roaming/npm/node_modules/eeui-cli/lib/loaders/eeui-loader/lib/selector.js?type=script&index=0!./src/pages/homePages/editpage.vue ***! \********************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var weex_ui_packages_wxc_cell__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! weex-ui/packages/wxc-cell */ "./node_modules/_weex-ui@0.8.4@weex-ui/packages/wxc-cell/index.js"); // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // var picker = weex.requireModule('picker'); var eeui = app.requireModule('eeui'); /* harmony default export */ __webpack_exports__["default"] = ({ components: { WxcCell: weex_ui_packages_wxc_cell__WEBPACK_IMPORTED_MODULE_0__["default"] }, data: function data() { return { timeValue: '', dateValue: '', value: '', value2: '', items: ['大一', '大二', '大三', '大四', '高一', '高二', '高三'], items2: ['身高', '体重', '跑步', '跳远'] }; }, methods: { wxcCellClicked: function wxcCellClicked(e) { this.pick(); }, wxcCellClicked2: function wxcCellClicked2(e) { this.pick2(); }, pick: function pick() { var _this = this; picker.pick({ items: this.items }, function (event) { if (event.result === 'success') { _this.value = _this.items[event.data]; } }); }, pick2: function pick2() { var _this2 = this; picker.pick({ items: this.items2 }, function (event) { if (event.result === 'success') { _this2.value2 = _this2.items2[event.data]; } }); } }, created: function created() { // 添加 字体图标 var domModule = weex.requireModule('dom'); domModule.addRule('fontFace', { 'fontFamily': "iconfont", 'src': "url('http://at.alicdn.com/t/font_1628280_p78f7z67jyq.ttf')" }); } }); /***/ }), /***/ "C:\\Users\\10844\\AppData\\Roaming\\npm\\node_modules\\eeui-cli\\lib\\loaders\\eeui-loader\\lib\\style-loader.js!C:\\Users\\10844\\AppData\\Roaming\\npm\\node_modules\\eeui-cli\\lib\\loaders\\eeui-loader\\lib\\style-rewriter.js?id=data-v-149d58ea!C:\\Users\\10844\\AppData\\Roaming\\npm\\node_modules\\eeui-cli\\lib\\loaders\\eeui-loader\\lib\\selector.js?type=styles&index=0!./node_modules/_weex-ui@0.8.4@weex-ui/packages/wxc-cell/index.vue": /*!*****************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************!*\ !*** C:/Users/10844/AppData/Roaming/npm/node_modules/eeui-cli/lib/loaders/eeui-loader/lib/style-loader.js!C:/Users/10844/AppData/Roaming/npm/node_modules/eeui-cli/lib/loaders/eeui-loader/lib/style-rewriter.js?id=data-v-149d58ea!C:/Users/10844/AppData/Roaming/npm/node_modules/eeui-cli/lib/loaders/eeui-loader/lib/selector.js?type=styles&index=0!./node_modules/_weex-ui@0.8.4@weex-ui/packages/wxc-cell/index.vue ***! \*****************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************/ /*! no static exports found */ /***/ (function(module, exports) { module.exports = { "wxc-cell": { "flexDirection": "row", "alignItems": "center", "paddingLeft": "24", "paddingRight": "24", "backgroundColor": "#ffffff" }, "cell-margin": { "marginBottom": "24" }, "cell-title": { "flex": 1 }, "cell-indent": { "paddingBottom": "30", "paddingTop": "30" }, "has-desc": { "paddingBottom": "18", "paddingTop": "18" }, "cell-top-border": { "borderTopColor": "#e2e2e2", "borderTopWidth": "1" }, "cell-bottom-border": { "borderBottomColor": "#e2e2e2", "borderBottomWidth": "1" }, "cell-label-text": { "fontSize": "30", "color": "#666666", "width": "188", "marginRight": "10" }, "cell-arrow-icon": { "width": "22", "height": "22" }, "cell-content": { "color": "#333333", "fontSize": "30", "lineHeight": "40" }, "cell-desc-text": { "color": "#999999", "fontSize": "24", "lineHeight": "30", "marginTop": "4", "marginRight": "30" }, "extra-content-text": { "fontSize": "28", "color": "#999999", "marginRight": "4" } } /***/ }), /***/ "C:\\Users\\10844\\AppData\\Roaming\\npm\\node_modules\\eeui-cli\\lib\\loaders\\eeui-loader\\lib\\style-loader.js!C:\\Users\\10844\\AppData\\Roaming\\npm\\node_modules\\eeui-cli\\lib\\loaders\\eeui-loader\\lib\\style-rewriter.js?id=data-v-2c762c0e!C:\\Users\\10844\\AppData\\Roaming\\npm\\node_modules\\eeui-cli\\lib\\loaders\\eeui-loader\\lib\\selector.js?type=styles&index=0!./src/pages/homePages/editpage.vue": /*!**********************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************!*\ !*** C:/Users/10844/AppData/Roaming/npm/node_modules/eeui-cli/lib/loaders/eeui-loader/lib/style-loader.js!C:/Users/10844/AppData/Roaming/npm/node_modules/eeui-cli/lib/loaders/eeui-loader/lib/style-rewriter.js?id=data-v-2c762c0e!C:/Users/10844/AppData/Roaming/npm/node_modules/eeui-cli/lib/loaders/eeui-loader/lib/selector.js?type=styles&index=0!./src/pages/homePages/editpage.vue ***! \**********************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************/ /*! no static exports found */ /***/ (function(module, exports) { module.exports = { "navbarb": { "width": "750", "height": "100", "backgroundColor": "#1eb76e" }, "headtext": { "fontSize": "30", "color": "#ffffff" }, "iconshow": { "fontFamily": "iconfont", "fontSize": 50, "color": "#2fdc7e" }, "celltitle": { "flexDirection": "row", "marginLeft": 15, "alignItems": "center" }, "icontit": { "fontSize": 30, "color": "#199153", "marginLeft": 10 }, "beiaerebox": { "width": 750, "alignItems": "center", "marginTop": 20 }, "beiaere": { "width": 689, "height": 100, "borderColor": "#999999", "borderWidth": 1, "fontSize": 28 }, "button": { "width": 680, "height": 90, "marginTop": 200 } } /***/ }), /***/ "C:\\Users\\10844\\AppData\\Roaming\\npm\\node_modules\\eeui-cli\\lib\\loaders\\eeui-loader\\lib\\template-compiler.js?id=data-v-149d58ea!C:\\Users\\10844\\AppData\\Roaming\\npm\\node_modules\\eeui-cli\\lib\\loaders\\eeui-loader\\lib\\selector.js?type=template&index=0!./node_modules/_weex-ui@0.8.4@weex-ui/packages/wxc-cell/index.vue": /*!*****************************************************************************************************************************************************************************************************************************************************************************************************************************!*\ !*** C:/Users/10844/AppData/Roaming/npm/node_modules/eeui-cli/lib/loaders/eeui-loader/lib/template-compiler.js?id=data-v-149d58ea!C:/Users/10844/AppData/Roaming/npm/node_modules/eeui-cli/lib/loaders/eeui-loader/lib/selector.js?type=template&index=0!./node_modules/_weex-ui@0.8.4@weex-ui/packages/wxc-cell/index.vue ***! \*****************************************************************************************************************************************************************************************************************************************************************************************************************************/ /*! no static exports found */ /***/ (function(module, exports) { module.exports={render:function (){var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h; return _c('div', { class: ['wxc-cell', _vm.hasTopBorder && 'cell-top-border', _vm.hasBottomBorder && 'cell-bottom-border', _vm.hasMargin && 'cell-margin', _vm.hasVerticalIndent && 'cell-indent', _vm.desc && 'has-desc'], style: _vm.cellStyle, attrs: { "accessible": _vm.autoAccessible, "ariaLabel": (_vm.label + "," + _vm.title + "," + _vm.desc) }, on: { "click": _vm.cellClicked } }, [_vm._t("label", [(_vm.label) ? _c('div', [_c('text', { staticClass: ["cell-label-text"] }, [_vm._v(_vm._s(_vm.label))])]) : _vm._e()]), _c('div', { staticClass: ["cell-title"] }, [_vm._t("title", [_c('text', { staticClass: ["cell-content"] }, [_vm._v(_vm._s(_vm.title))]), (_vm.desc) ? _c('text', { staticClass: ["cell-desc-text"] }, [_vm._v(_vm._s(_vm.desc))]) : _vm._e()])], 2), _vm._t("value"), _vm._t("default"), (_vm.extraContent) ? _c('text', { staticClass: ["extra-content-text"] }, [_vm._v(_vm._s(_vm.extraContent))]) : _vm._e(), (_vm.hasArrow) ? _c('image', { staticClass: ["cell-arrow-icon"], attrs: { "src": _vm.arrowIcon, "ariaHidden": true } }) : _vm._e()], 2) },staticRenderFns: []} module.exports.render._withStripped = true /***/ }), /***/ "C:\\Users\\10844\\AppData\\Roaming\\npm\\node_modules\\eeui-cli\\lib\\loaders\\eeui-loader\\lib\\template-compiler.js?id=data-v-2c762c0e!C:\\Users\\10844\\AppData\\Roaming\\npm\\node_modules\\eeui-cli\\lib\\loaders\\eeui-loader\\lib\\selector.js?type=template&index=0!./src/pages/homePages/editpage.vue": /*!**********************************************************************************************************************************************************************************************************************************************************************************************!*\ !*** C:/Users/10844/AppData/Roaming/npm/node_modules/eeui-cli/lib/loaders/eeui-loader/lib/template-compiler.js?id=data-v-2c762c0e!C:/Users/10844/AppData/Roaming/npm/node_modules/eeui-cli/lib/loaders/eeui-loader/lib/selector.js?type=template&index=0!./src/pages/homePages/editpage.vue ***! \**********************************************************************************************************************************************************************************************************************************************************************************************/ /*! no static exports found */ /***/ (function(module, exports) { module.exports={render:function (){var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h; return _c('div', { staticClass: ["app"] }, [_c('navbar', { staticClass: ["navbarb"] }, [_c('navbar-item', { attrs: { "type": "back" } }), _c('navbar-item', { attrs: { "type": "title" } }, [_c('text', { staticClass: ["headtext"] }, [_vm._v("编辑运动")])])], 1), _c('div', { staticClass: ["cellList"] }, [_c('wxc-cell', { attrs: { "label": "标题", "hasArrow": false, "title": "体制测评", "hasMargin": true } }), _c('wxc-cell', { attrs: { "label": "年级", "title": _vm.value, "hasArrow": true, "hasMargin": true }, on: { "wxcCellClicked": _vm.wxcCellClicked } }), _c('wxc-cell', { attrs: { "label": "运动项目", "title": _vm.value2, "hasArrow": true, "hasMargin": true }, on: { "wxcCellClicked": _vm.wxcCellClicked2 } })], 1), _vm._m(0), _c('div', { staticClass: ["beiaerebox"] }, [_c('textarea', { staticClass: ["beiaere"] }), _c('button', { staticClass: ["button"], attrs: { "eeui": { text: '保存', backgroundColor: '#1eb76e' } } })], 1)], 1) },staticRenderFns: [function (){var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h; return _c('div', { staticClass: ["celltitle"] }, [_c('text', { staticClass: ["iconshow"] }, [_vm._v("")]), _c('text', { staticClass: ["icontit"] }, [_vm._v("备注")])]) }]} module.exports.render._withStripped = true /***/ }), /***/ "C:\\Users\\10844\\AppData\\Roaming\\npm\\node_modules\\eeui-cli\\node_modules\\_webpack@4.42.1@webpack\\buildin\\global.js": /*!***********************************!*\ !*** (webpack)/buildin/global.js ***! \***********************************/ /*! no static exports found */ /***/ (function(module, exports) { function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } var g; // This works in non-strict mode g = function () { return this; }(); try { // This works if eval is allowed (see CSP) g = g || new Function("return this")(); } catch (e) { // This works if the window reference is available if ((typeof window === "undefined" ? "undefined" : _typeof(window)) === "object") g = window; } // g can still be undefined, but nothing to do about it... // We return undefined, instead of nothing here, so it's // easier to handle this case. if(!global) { ...} module.exports = g; /***/ }) /******/ });
define([],function () { var settings = { supportedLanguages : ['pl','en'], roomName : null, userName : null, owner : false, // flag if the user is owner of the session imageSettings : null, // take over from user model useWebWorker:false, // use web worker for reading files enableConsoleLog:false, previewMaxHeight:100, init : function(){ this.calculateMaxDimensions(); }, reset : function(){ this.roomName = null; this.owner = false; }, calculateMaxDimensions : function(){ this.maxHeight = 1200; this.maxWidth = 2000; }, generateRoomId : function(){ var LENGTH = 5; var rand = function() { return Math.random().toString(36).substr(2, LENGTH); // remove `0.` }; return rand(); } }; return settings; });
$(document).ready(function() { $(document).ready(function() { $.ajax("text.txt", { }).done(function(text) { $('#text').html(text); }); }); $('h2').click(function() { $.getJSON("json.json", function(data) { $('#text2').html('<p>' + data.title + '</p>'); list = '<ul>' for(var i = 0; i < data.movies.length; i++) { list += '<ol>' + data.movies[i] + '</ol>' } list += '</ul>' $('#text3').html(list); }); }); });
import React from 'react'; import ReactDOM from 'react-dom'; import Board from './Board'; import Header from './Header'; import Footer from './Footer'; import './index.css'; var destination = document.querySelector("#root") ReactDOM.render( <div> <Header/> <Board/> <Footer/> </div>, destination );
'use strict' exports.generic = require('./generic'); exports.repository = require('./repository'); exports.schedule = require('./schedule'); exports.checkAuthInfo = function(authInfo){ exports.generic.checkUndefinedOrNull(authInfo.userName, 'authInfo.userName'); exports.generic.checkUndefinedOrNull(authInfo.password, 'authInfo.password'); };
import 'babel-polyfill'; import React from 'react'; import { render } from 'react-dom'; import injectTapEventPlugin from 'react-tap-event-plugin'; import Application from 'application'; injectTapEventPlugin(); render(Application, document.getElementById('app'));
import { get, patch, post } from './config'; export const getDesktopMainScreen = async () => await get('compose/desktop-main-screen') export const usersCheck = async (phone, notifyError) => await get('users/check', { phone }, notifyError); export const usersMe = async () => await get('users/me'); export const tokenObtain = async (params = { phone: '', password: '' }) => await post('token/obtain', params); export const tokenRefresh = async (params = { refreshToken: '' }) => await post('token/refresh', params); export const logout = async () => await get('logout'); export const paymentsPay = async ( params = { amount: '', account_id: '', user_id: '', idempotency: '' } ) => await post('payments/pay', params); export const withdrawal = async ( params = { account_id: 0, amount: 0, notes: '', withdrawal_type: 1, recepient: { swift: '', bank_code: '', bank_account_id: '', branch_code: '', bank_address: '', bank_name: '' }, idempotency: '' } ) => await post('withdrawal', params); export const getSessions = async () => await get('sessions'); export const killSession = async id => await patch('sessions', { id }); //cards export const getCards = async () => await get('/cards/active'); export const patchCardsOTP = async (params = { request_id: 0, otp: '' }) => await patch('/cards/otp', params); export const getNewOTP = async (params = { request_id: 0 }) => await post('/cards/otp', params); export const cardsNew = async ( params = { account_id: 0, type_id: 0, assoc_number: '', failed_id: 0, pin: '' } ) => await post('/cards/new', params); export const getCardsNew = async request_id => await get('/cards/new', { request_id }); export const cardsRequestState = async () => await get('/cards/request_states', {});
import React, { Component } from "react"; import { View, Text, StyleSheet, ScrollView, Dimensions } from "react-native"; import { global } from "../style/global"; import { LineChart, BarChart, PieChart, ProgressChart, ContributionGraph, StackedBarChart, } from "react-native-chart-kit"; var colorArr = [ "#ff000070", "#2700ff70", "#ff00c870", "#04ff0070", "#00ffdc70", "#ff520070", "#efff0070", "#b944a070", "#b9444470", "#4493b970", "#4b44b970", "#8cb94470", "#44b95870", "#b98a4470", "#b9ab4470", ]; class cautraloicheck extends Component { constructor(props) { super(props); this.state = { width: Dimensions.get("window").width * (this.isPor() ? 0.86 : 0.86), data: [], soluongtl: 0, }; Dimensions.addEventListener("change", () => { this.setState({ width: Dimensions.get("window").width * (this.isPor() ? 0.86 : 0.86), }); }); } isPor = () => { const screen = Dimensions.get("screen"); return screen.height >= screen.width; }; componentDidMount() { let { data } = this.state; data = this.props.data.NoiDung.map((item, index) => { return { name: item.Option, population: item.SoLg, color: colorArr[index], legendFontColor: "#7F7F7F", legendFontSize: 10, }; }); let total = this.props.data.NoiDung.reduce((sum, item) => { return sum + item.SoLg; }, 0); this.setState({ data, soluongtl: total, }); } renderhtml = () => {}; render() { return ( <View style={global.inputGroup}> <View> <View style={{ borderBottomColor: "#eeeeee", borderBottomWidth: 1 }}> <Text style={{ fontSize: 18, fontWeight: "500" }}> {this.props.data.TenCauHoi} </Text> </View> <ScrollView style={{ minHeight: 100, maxHeight: 2000, marginTop: 20, }} nestedScrollEnabled={true} > <View style={styles.content}> <PieChart data={this.state.data} width={Dimensions.get("window").width * 0.76} height={220} chartConfig={{ width: 100, backgroundColor: "#e26a00", backgroundGradientFrom: "#fb8c00", backgroundGradientTo: "#ffa726", decimalPlaces: 0, // optional, defaults to 2dp color: (opacity = 1) => `rgba(255, 255, 255, ${opacity})`, labelColor: (opacity = 1) => `rgba(255, 255, 255, ${opacity})`, style: { borderRadius: 16, width: 100, }, propsForDots: { r: "6", strokeWidth: "2", stroke: "#ffa726", }, }} bezier style={{ width: 100, marginVertical: 8, borderRadius: 16, }} accessor="population" backgroundColor="transparent" paddingLeft="15" xAxisLabel="Append" /> </View> </ScrollView> <Text style={{ marginTop: 10, paddingTop: 10, borderTopWidth: 1, borderTopColor: "#eeeeee", }} > Tổng số câu trả lời : {this.state.soluongtl} </Text> </View> </View> ); } } const styles = StyleSheet.create({ content: { marginTop: 10, marginBottom: 5, }, }); export default cautraloicheck;
import React, {Component} from 'react'; import ReactDOM from 'react-dom'; import {Provider} from 'react-redux'; import {Router} from 'react-router-dom' import Layout from "./components/Layout"; import store from "./store"; import history from './history'; import "bootstrap/js/src/modal.js"; const app = document.getElementById("app"); ReactDOM.render(<Provider store={store}><Router history={history}><Layout /></Router></Provider>, app);
import Vue from 'vue' import vuex from 'vuex' Vue.use(vuex); import fortune from "./module/fortune" export default new vuex.Store ({ state : { loginAccount : '' }, modules : { fortune: fortune }, mutations: { updateLoginAccount: function (state,value) { state.loginAccount = value; } }, actions : { } })
import { all } from 'redux-saga/effects'; import journal from './journal/sagas'; function* rootSaga() { yield all([journal()]); } export default rootSaga;
import { projects } from './_work'; export function get(req, res, next) { res.end(JSON.stringify(projects)); }
const express = require('express'); const router = express.Router(); const Campground = require('../models/campground'); const middleware = require('../middleware'); //INDEX ROUTE - display all campgrounds router.get('/', function(req, res) { Campground.find({}, function(err, allcampgrounds) { if (err) { console.log('error occured'); } else { res.render('campgrounds/index', { campgrounds: allcampgrounds, page: 'campgrounds' }); } }); }); //CREATE ROUTE - create/add new campground router.post('/', middleware.isLoggedIn, function(req, res) { const name = req.body.name; const image = req.body.image; const price = req.body.price; const description = req.body.description; const author = { id: req.user._id, username: req.user.username }; const newCampground = { name: name, image: image, price: price, description: description, author }; Campground.create(newCampground, function(err, campground) { if (err) { console.log('error occured'); } else { res.redirect('/campgrounds'); } }); }); // NEW ROUTE - display form to create new campground router.get('/new', middleware.isLoggedIn, function(req, res) { res.render('campgrounds/newcamp'); }); // SHOW ROUTE - shows more info about one campground router.get('/:id', function(req, res) { //find the campground with provided id Campground.findById(req.params.id) .populate('comments') .exec(function(err, foundCampground) { if (err || !foundCampground) { req.flash('error', 'Campground not found.'); res.redirect('/campgrounds'); } else { //render show template for found campground res.render('campgrounds/show', { campground: foundCampground }); } }); }); // EDIT ROUTE - form to edit campgrounds router.get('/:id/edit', middleware.checkCampgroundOwnership, function( req, res ) { Campground.findById(req.params.id, function(err, campground) { res.render('campgrounds/edit', { campground: campground }); }); }); // UPDATE ROUTE - updating edited data for campground router.put('/:id', middleware.checkCampgroundOwnership, function(req, res) { req.body.campground.body = req.sanitize(req.body.campground.body); const id = req.params.id; const campgroundData = req.body.campground; Campground.findByIdAndUpdate(id, campgroundData, function(err, campground) { if (err) { res.redirect('/campgrounds'); } else { res.redirect('/campgrounds/' + id); } }); }); // DELETE ROUTE - deleting campground router.delete('/:id', middleware.checkCampgroundOwnership, function(req, res) { Campground.findByIdAndRemove(req.params.id, function(err, campground) { if (err) { console.log(err); } else { res.redirect('/campgrounds'); } }); }); module.exports = router;
/***************************************************************** ** Author: Asvin Goel, goel@telematique.eu ** ** A plugin for animating slide content. ** ** Version: 0.1.0 ** ** License: MIT license (see LICENSE.md) ** ******************************************************************/ window.RevealAnimate = window.RevealAnimate || { id: 'RevealAnimate', init: function(deck) { initAnimate(deck); }, play: function() { play(); }, pause: function() { pause(); }, seek: function(timestamp) { seek(timestamp); }, }; const initAnimate = function(Reveal){ var config = Reveal.getConfig().animate || {}; var autoplay = config.autoplay; var playback = false; var isRecording = false; var timer = null; var initialized = 0; function parseJSON(str) { str = str.replace(/(\r\n|\n|\r|\t)/gm,""); // remove line breaks and tabs var json; try { json = JSON.parse(str, function (key, value) { if (value && (typeof value === 'string') && value.indexOf("function") === 0) { // we can only pass a function as string in JSON ==> doing a real function // eval("var jsFunc = " + value); var jsFunc = new Function('return ' + value)(); return jsFunc; } return value; }); } catch (e) { return null; } return json; } function load( element, config, filename, callback ) { var xhr = new XMLHttpRequest(); xhr.onload = function() { if (xhr.readyState === 4) { callback( element, config, xhr.responseText ); } else { callback( "Failed to get file. ReadyState: " + xhr.readyState + ", Status: " + xhr.status ); } }; xhr.open( 'GET', filename, true ); xhr.send(); } function parseComments( element ) { var config = {}; var comments = element.innerHTML.trim().match(/<!--[\s\S]*?-->/g); //console.log(comments) if ( comments !== null ) for (var k = 0; k < comments.length; k++ ){ comments[k] = comments[k].replace(/<!--/,''); comments[k] = comments[k].replace(/-->/,''); var config = parseJSON(comments[k]); //console.warn(comments[k], config); if ( config ) { if ( config.animation && Array.isArray(config.animation) && config.animation.length && !Array.isArray(config.animation[0]) ) { // without fragments the animation can be specified as a single array (animation steps) config.animation = [ config.animation ]; } break; } } //console.warn(element, config); return config; } function getAnimatedSVG( container ) { var elements = SVG.find('svg'); var svg = elements.toArray().find(element => element.node.parentElement == container); //console.warn("FOUND",svg.node); return svg; } /***************************************************************** ** Set up animations ******************************************************************/ function setupAnimations( container, config ) { //console.warn("setupAnimations"); if ( !config ) return; container.svg = getAnimatedSVG( container ); // pre-animation setup var setup = config.setup; if ( setup ) { for (var i = 0; i < setup.length; i++ ){ try { if ( setup[i].element ) { //console.log(setup[i].element,setup[i].modifier,setup[i].parameters); var elements = container.svg.find(setup[i].element); if ( !elements.length ) { console.warn("Cannot find element to set up with selector: " + setup[i].element + "!"); } //console.warn(elements); //console.log("element(" + setup[i].element + ")." + setup[i].modifier + "(" + setup[i].parameters + ")"); //console.log("element(" + setup[i].element + ")." + setup[i].modifier + "(" + setup[i].parameters + ")"); for (var j = 0; j < elements.length; j++ ){ if ( typeof setup[i].modifier === "function" ) { // if modifier is function execute it setup[i].modifier.apply(elements[j],setup[i].parameters); } else { // apply modifier to element elements[j][setup[i].modifier].apply(elements[j],setup[i].parameters); } } } else { // no element is provided if ( typeof setup[i].modifier === "function" ) { // if modifier is function execute it setup[i].modifier.apply(container.svg,setup[i].parameters); } else { // apply modifier to root container.svg[setup[i].modifier].apply(container.svg,setup[i].parameters); } } } catch( error ) { console.error("Error '" + error + "' setting up element " + JSON.stringify(setup[i])); } } //console.warn(container.svg.node.getAttribute("style")); } container.animation = new SVG.Timeline().persist(true); container.animationSchedule = []; // completion time of each fragment animation // setup animation var animations = config.animation; if ( animations ) { container.animationSchedule.length = animations.length; var timestamp = 0; for (var fragment = 0; fragment < animations.length; fragment++ ){ container.animationSchedule[fragment] = {}; container.animationSchedule[fragment].begin = timestamp; for (var i = 0; i < animations[fragment].length; i++ ){ try { // add each animation step var elements = container.svg.find(animations[fragment][i].element); //console.log("element(" + animations[fragment][i].element + ")." + animations[fragment][i].modifier + "(" + animations[fragment][i].parameters + ")"); if ( !elements.length ) { console.warn("Cannot find element to animate with selector: " + animations[fragment][i].element + "!"); } for (var j = 0; j < elements.length; j++ ){ elements[j].timeline( container.animation ); var anim = elements[j].animate(animations[fragment][i].duration,animations[fragment][i].delay,animations[fragment][i].when) anim[animations[fragment][i].modifier].apply(anim,animations[fragment][i].parameters); } //console.log("Duration:", anim.duration()); timestamp = anim.duration(); } catch( error ) { console.error("Error '" + error + "' setting up animation " + JSON.stringify(animations[fragment][i])); } } // set animationSchedule for each fragment animation var schedule = container.animation.schedule(); if ( schedule.length ) { timestamp = schedule[schedule.length-1].end; } container.animationSchedule[fragment].end = timestamp; } container.animation.stop(); //console.warn(container.animation.schedule()); // console.warn("Schedule", container.animationSchedule); } // setup current slide if ( Reveal.getCurrentSlide().contains( container ) ) { Reveal.layout(); // Update layout to account for svg size animateSlide(0); } initialized += 1; } function initialize() { //console.log("Initialize animations"); // Get all animations var elements = document.querySelectorAll("[data-animate]"); for (var i = 0; i < elements.length; i++ ){ var config = parseComments( elements[i] ); var src = elements[i].getAttribute("data-src"); if ( src ) { var element = elements[i]; load( elements[i], config, src, function( element, config, response ) { if ( printMode ) { // do not load svg multiple times element.removeAttribute("data-src") } element.innerHTML = response + element.innerHTML; setupAnimations( element, config ); }); } else { setupAnimations( elements[i], config ); } } } function play() { //console.log("Play",Reveal.getCurrentSlide()); var elements = Reveal.getCurrentSlide().querySelectorAll("[data-animate]"); for (var i = 0; i < elements.length; i++ ){ //console.warn("Play",elements[i]); if ( elements[i].animation ) { elements[i].animation.play(); } } autoPause(); } function pause() { //console.log("Pause"); if ( timer ) { clearTimeout( timer ); timer = null; } var elements = Reveal.getCurrentSlide().querySelectorAll("[data-animate]"); for (var i = 0; i < elements.length; i++ ){ if ( elements[i].animation ) { elements[i].animation.pause(); } } } function autoPause() { if ( timer ) { clearTimeout( timer ); timer = null; } var fragment = Reveal.getIndices().f + 1 || 0; // in reveal.js fragments start with index 0, here with index 1 var elements = Reveal.getCurrentSlide().querySelectorAll("[data-animate]"); for (var i = 0; i < elements.length; i++ ){ if ( elements[i].animation && elements[i].animationSchedule[fragment] ) { //console.log( elements[i].animationSchedule[fragment].end, elements[i].animation.time()); var timeout = elements[i].animationSchedule[fragment].end - elements[i].animation.time(); timer = setTimeout(pause,timeout); } //console.log("Auto pause",elements[i], timeout); } } function seek( timestamp ) { //console.log("Seek", timestamp); var elements = Reveal.getCurrentSlide().querySelectorAll("[data-animate]"); var fragment = Reveal.getIndices().f + 1 || 0; // in reveal.js fragments start with index 0, here with index 1 for (var i = 0; i < elements.length; i++ ){ //console.log("Seek",timestamp,elements[i].animationSchedule[fragment].begin + (timestamp || 0) ); if ( elements[i].animation && elements[i].animationSchedule[fragment] ) { elements[i].animation.time( elements[i].animationSchedule[fragment].begin + (timestamp || 0) ); } } if ( timer ) { // update time if animation is running autoPause(); } } // Control animation function animateSlide( timestamp ) { // pause(); //console.log("Animate slide", timestamp); if ( timestamp !== undefined ) { seek( timestamp); } if ( Reveal.isAutoSliding() || autoplay || playback || isRecording ) { //console.log("Start animation"); play(); } else { pause(); } //console.log("Done"); } /***************************************************************** ** Print ******************************************************************/ var printMode = ( /print-pdf/gi ).test( window.location.search ); //console.log("createPrintout" + printMode) function initializePrint( ) { //return; //console.log("initializePrint", document.querySelectorAll(".pdf-page").length); if ( !document.querySelectorAll(".pdf-page").length ) { // wait for pdf pages to be created setTimeout( initializePrint, 500 ); return; } initialize(); createPrintout(); } function createPrintout( ) { //console.log("createPrintout", document.querySelectorAll(".pdf-page").length, document.querySelectorAll("[data-animate]").length ); if ( initialized < document.querySelectorAll("[data-animate]").length ) { //console.log("wait"); // wait for animations to be loaded setTimeout( createPrintout, 500 ); return; } var pages = document.querySelectorAll(".pdf-page"); for ( var i = 0; i < pages.length; i++ ) { var fragment = -1; var current = pages[i].querySelectorAll(".current-fragment"); for ( var j = 0; j < current.length; j++ ) { if ( Number(current[j].getAttribute("data-fragment-index")) > fragment ) { fragment = Number(current[j].getAttribute("data-fragment-index") ); } } fragment += 1; var elements = pages[i].querySelectorAll("[data-animate]"); for ( var j = 0; j < elements.length; j++ ) { //console.log(i,fragment, elements[j]); if ( elements[j].animation && elements[j].animationSchedule && elements[j].animationSchedule[fragment] ) { //console.log(i,fragment, elements[j].animationSchedule[fragment].begin); elements[j].animation.time( elements[j].animationSchedule[fragment].end ); } var fragments = elements[j].querySelectorAll("svg > [data-fragment-index]"); //console.log(i,fragment, elements[j], fragments); for ( var k = 0; k < fragments.length; k++ ) { if ( fragments[k].getAttribute("data-fragment-index") < fragment ) { fragments[k].classList.add("visible"); } } } } } /***************************************************************** ** Event listeners ******************************************************************/ Reveal.addEventListener( 'ready', function( event ) { //console.log('ready '); /* if ( printMode ) { initializePrint(); return; } */ initialize(); if ( printMode ) { initializePrint(); return; } Reveal.addEventListener('slidechanged', function(){ //console.log('slidechanged',Reveal.getIndices()); animateSlide(0); }); Reveal.addEventListener( 'overviewshown', function( event ) { // pause animation pause(); } ); /* Reveal.addEventListener( 'overviewhidden', function( event ) { } ); */ Reveal.addEventListener( 'paused', function( event ) { //console.log('paused '); // pause animation pause(); } ); /* Reveal.addEventListener( 'resumed', function( event ) { console.log('resumed '); // resume animation } ); */ Reveal.addEventListener( 'fragmentshown', function( event ) { //console.log("fragmentshown",event); animateSlide(0); } ); Reveal.addEventListener( 'fragmenthidden', function( event ) { //console.log("fragmentshown",event); animateSlide(0); } ); } ); /***************************************************************** ** Playback ******************************************************************/ document.addEventListener('seekplayback', function( event ) { //console.log('event seekplayback ' + event.timestamp); // set animation to event.timestamp animateSlide(event.timestamp); }); document.addEventListener('startplayback', function( event ) { //console.log('event startplayback ' + event.timestamp); playback = true; animateSlide(event.timestamp); }); document.addEventListener('stopplayback', function( event ) { //console.log('event stopplayback ', event); playback = false; animateSlide(); }); document.addEventListener('startrecording', function( event ) { //console.log('event startrecording ' + event.timestamp); isRecording = true; animateSlide(0); }); document.addEventListener('stoprecording', function( event ) { //console.log('event stoprecording ' + event.timestamp); isRecording = false; animateSlide(); }); this.play = play; this.pause = pause; this.seek = seek; return this; };
import React from 'react'; import Enzyme, {mount} from 'enzyme'; import Adapter from 'enzyme-adapter-react-16'; import QuestionArtistScreen from './question-artist-screen'; import withActivePlayer from '../../hocs/with-active-player/with-active-player'; const QuestionArtistScreenWrapped = withActivePlayer(QuestionArtistScreen); Enzyme.configure({ adapter: new Adapter(), }); const questionArtist = { artist: `Пелагея`, src: `https://upload.wikimedia.org/wikipedia/commons/4/4e/BWV_543-fugue.ogg`, options: [ { artist: `Пелагея`, picture: `https://htmlacademy-react-3.appspot.com/guess-melody/static/artist/Quincas_Moreira.jpg`, id: 0, }, { artist: `Меладзе`, picture: `https://htmlacademy-react-3.appspot.com/guess-melody/static/artist/Jesse_Gallagher.jpg`, id: 1, }, { artist: `Шнуров`, picture: `https://htmlacademy-react-3.appspot.com/guess-melody/static/artist/sextile.jpg`, id: 2, }, ] }; it(`When user answers the question, "handleAnswer" callback gets current question's artist and user answer as arguments`, () => { const onAnswer = jest.fn(); const questionArtistScreen = mount(<QuestionArtistScreenWrapped question={questionArtist} onAnswer={onAnswer}/>); const answerRadio = questionArtistScreen.find(`.artist__input`); answerRadio.at(0).simulate(`change`, {preventDefault: () => {}}); expect(onAnswer.mock.calls.length).toBe(1); expect(onAnswer.mock.calls[0][0]).toBe(questionArtist); expect(onAnswer.mock.calls[0][1]).toBe(questionArtist.options[0].artist); });
import Reforma from '@reforma/core' import { createField } from '../field' describe('Field', () => { test('primitive type field', () => { const field = createField(Reforma.integer) isField(field) hasType(field, Reforma.integer) canName(field) canSetId(field) canCalc(field) canValidate(field) }) test('non-primitive type field', () => { const field = createField(Reforma.arrayOf(Reforma.string)) isField(field) hasType(field, Reforma.arrayOf(Reforma.string)) canName(field) cannotSetId(field) canCalc(field) canValidate(field) }) function isField(field) { expect(field.__isField__).toBe(true) } function hasType(field, type) { expect(field.getType()).toBe(type) } function canName(field) { expect(field.getName()).toBeNull() // invalid name assignment expect(() => field.setName('isThisName?')).toThrow('Illegal field name: isThisName?') // valid name assignment expect(() => field.setName('validName')).not.toThrow() expect(field.getName()).toBe('validName') // second valid name assignment expect(() => field.setName('anotherValidName')).toThrow('Field name is already defined') expect(field.getName()).toBe('validName') } function canSetId(field) { expect(field.getId()).toBe(false) // `.id` getter can be chained expect(field.id).toBe(field) expect(field.getId()).toBe(true) // `.setId` cannot be chained expect(field.setId(false)).toBeUndefined() expect(field.getId()).toBe(false) } function cannotSetId(field) { expect(field.getId()).toBe(false) expect('id' in field).toBe(false) expect('setId' in field).toBe(false) } function canCalc(field) { expect(() => field.calc('something')).toThrow('Specify function in `calc`') expect(field.getCalc()).toBeNull() expect(field.isCalculable).toBe(false) const fn = jest.fn() // `.calc` can be chained expect(field.calc(fn)).toBe(field) expect(field.getCalc()).toBe(fn) expect(field.isCalculable).toBe(true) // subsequent `.calc` calls are banned expect(() => field.calc(jest.fn())).toThrow('Only single assignment permitted in `calc`') expect(field.getCalc()).toBe(fn) } function canValidate(field) { expect(field.getValidators()).toEqual([]) // validators can be chained const fn1 = jest.fn() const fn2 = jest.fn() expect(field.validate(fn1).validate(fn2)).toBe(field) expect(field.getValidators()).toEqual([fn1, fn2]) // only function is allowed expect(() => field.validate('non-function')).toThrow('Specify function in `validate`') } })
const Lesson = require("../models/Lesson"); const errorWrapper = require("../helpers/error/errorWrapper"); const CustomError = require("../helpers/error/customError"); const getAllLesson = errorWrapper(async (req, res, next) => { return res.status(200).json(res.advanceQueryResults); }); // const getAllLesson = errorWrapper(async (req, res, next) => { // const lessons = await Lesson.find().populate({ // path:"comments", // select:"mark" // }); // return res.status(200).json({ // success: true, // data: lessons, // }); // }); const getLessonByCategoryId = errorWrapper(async (req, res, next) => { const { category_id } = req.params; const lessons = await Lesson.find({ category: category_id }).populate({ path: "category", select: "title", }); res.status(200).json({ success: true, data: lessons, }); }); const getLessonByUserId = errorWrapper(async (req, res, next) => { const { user_id } = req.params; const lessons = await Lesson.find({ user: user_id }); res.status(200).json({ success: true, data: lessons, }); }); const addNewLesson = errorWrapper(async (req, res, next) => { const information = req.body; const lesson = await Lesson.create({ ...information, user: req.user.id, }); res.status(200).json({ success: true, message: lesson, }); }); const getSingleLesson = errorWrapper(async (req, res, next) => { const lesson_id = req.params.id || req.params.lesson_id; const lesson = await Lesson.findById(lesson_id).populate([{ path: "user", select: "name profile_image", },{ path:"comments", select:"mark" }]); res.status(200).json({ success: true, data: lesson, }); }); const editLesson = errorWrapper(async (req, res, next) => { const lesson_id = req.params.id || req.params.lesson_id; const { title, content, url, instructor, image, category } = req.body; let lesson = await Lesson.findById(lesson_id); lesson.title = title; lesson.content = content; lesson.url = url; lesson.instructor = instructor; lesson.category = category; lesson.image = image; lesson = await lesson.save(); res.status(200).json({ success: true, data: lesson, }); }); const deleteLesson = errorWrapper(async (req, res, next) => { const lesson_id = req.params.id || req.params.lesson_id; await Lesson.findByIdAndRemove(lesson_id); res.status(200).json({ success: true, data: {}, }); }); const likeLesson = errorWrapper(async (req, res, next) => { const lesson_id = req.params.id || req.params.lesson_id; const lesson = await Lesson.findById(lesson_id); if (lesson.likes.includes(req.user.id)) { return next(new CustomError("You already liked this lesson", 400)); } lesson.likes.push(req.user.id); lesson.likeCount += 1; await lesson.save(); return res.status(200).json({ success: true, data: lesson, }); }); const undoLikeLesson = errorWrapper(async (req, res, next) => { const lesson_id = req.params.id || req.params.lesson_id; const lesson = await Lesson.findById(lesson_id); if (!lesson.likes.includes(req.user.id)) { return next( new CustomError("You can not undo like operation for this lesson", 400) ); } const index = lesson.likes.indexOf(req.user.id); lesson.likes.splice(index, 1); lesson.likeCount -= 1; await lesson.save(); res.status(200).json({ success: true, data: lesson, }); }); const dislikeLesson = errorWrapper(async (req, res, next) => { const lesson_id = req.params.id || req.params.lesson_id; const lesson = await Lesson.findById(lesson_id); if (lesson.dislikes.includes(req.user.id)) { return next(new CustomError("You already liked this lesson", 400)); } lesson.dislikes.push(req.user.id); lesson.dislikeCount += 1; await lesson.save(); return res.status(200).json({ success: true, data: lesson, }); }); const undoDislikeLesson = errorWrapper(async (req, res, next) => { const lesson_id = req.params.id || req.params.lesson_id; const lesson = await Lesson.findById(lesson_id); if (!lesson.dislikes.includes(req.user.id)) { return next( new CustomError("You can not undo like operation for this lesson", 400) ); } const index = lesson.dislikes.indexOf(req.user.id); lesson.dislikes.splice(index, 1); lesson.dislikeCount -= 1; await lesson.save(); res.status(200).json({ success: true, data: lesson, }); }); module.exports = { addNewLesson, getAllLesson, getSingleLesson, editLesson, deleteLesson, likeLesson, undoLikeLesson, dislikeLesson, undoDislikeLesson, getLessonByCategoryId, getLessonByUserId, };
// JavaScript - Node v6.11.0 let room = {'a': 0, 'b': 0, 'c': 0}; let rooms = {'a': room, 'b': room, 'c': room};
export default [ { _tag: 'CSidebarNavTitle', _children: ['Modulo Principal'] }, { _tag: 'CSidebarNavItem', name: 'Dashboard', to: '/', icon: 'cil-speedometer', badge: { color: 'info', text: 'PRINCIPAL', } }, { _tag: 'CSidebarNavItem', name: 'Reportes', to: '/reports', icon: 'cil-chart-line', }, { _tag: 'CSidebarNavTitle', _children: ['Administracion'] }, { _tag: 'CSidebarNavItem', name: 'Usuarios', to: '/users', icon: 'cil-group', }, { _tag: 'CSidebarNavItem', name: 'Categorias', to: '/categories', icon: 'cil-tags', }, { _tag: 'CSidebarNavItem', name: 'Ventas', to: '/entries', icon: 'cil-dollar', }, { _tag: 'CSidebarNavDivider' } ]
const PostModel = require('../models/post') const CommentModel = require('../models/comment') const CategoryModel = require('../models/category') module.exports = { async index(ctx, next) { const pageSize = 10 const currentPage = parseInt(ctx.query.page) || 1 // 分类名 const cname = ctx.query.c let cid if (cname) { // 查询分类id const cateogry = await CategoryModel.findOne({ name: cname }) cid = cateogry._id } // 根据是否有分类来控制查询语句 const query = cid ? { category: cid } : {} const allPostsCount = await PostModel.find(query).count() const pageCount = Math.ceil(allPostsCount / pageSize) const pageStart = currentPage - 2 > 0 ? currentPage - 2 : 1 const pageEnd = pageStart + 4 >= pageCount ? pageCount : pageStart + 4 const posts = await PostModel.find(query).skip((currentPage - 1) * pageSize).limit(pageSize) // 根据是否有分类来控制分页链接 const baseUrl = cname ? `${ctx.path}?c=${cname}&page=` : `${ctx.path}?page=` await ctx.render('index', { title: '一寸的床', posts, pageSize, currentPage, allPostsCount, pageCount, pageStart, pageEnd, baseUrl }) }, async create(ctx, next) { if (ctx.method === 'GET') { if (ctx.session.user) { // 新建文章时选择 const categories = await CategoryModel.find({}) await ctx.render('posts/create', { title: '新建文章', categories, }) } else { ctx.redirect('sign/signin') } return } const post = Object.assign(ctx.request.body, { author: ctx.session.user._id, }) const res = await PostModel.create(post) ctx.flash = { success: '发表文章成功' } ctx.redirect(`/posts/${res._id}`) }, async show(ctx, next) { // 因为之前在 Schema 中,关联了 User 集合, // 所以这里直接使用 populate 引用 const post = await PostModel.findById(ctx.params.id).populate([{ path: 'author', select: 'username' }, { path: 'category', select: ['title', 'name'] } ]) // 查找评论 const comments = await CommentModel.find({ "postId": ctx.params.id }).populate({ path: 'commentator', select: 'username', }) await ctx.render('posts/post', { title: post.title, post, comments, }) }, async edit(ctx, next) { if (ctx.method === 'GET') { const post = await PostModel.findById(ctx.params.id) if (!post) { ctx.body = '文章不存在' } else if (post.author.toString() !== ctx.session.user._id.toString()) { console.log(post.title, post.author, ctx.session.user._id) ctx.body = '没有权限' } else { // 编辑文章时选择分类 const categories = await CategoryModel.find({}) await ctx.render('posts/edit', { title: '更新文章', post, categories, }) } return } const { title, category, content } = ctx.request.body await PostModel.findByIdAndUpdate(ctx.params.id, { title, category, content, }) ctx.flash = { success: '更新文章成功' } ctx.redirect(`/posts/${ctx.params.id}`) }, async delete(ctx, next) { const post = await PostModel.findById(ctx.params.id) if (!post) { ctx.body = '文章不存在' } else if (post.author.toString() !== ctx.session.user._id.toString()) { ctx.body = '没有权限' } else { await PostModel.findByIdAndRemove(ctx.params.id) ctx.flash = { success: '删除成功' } ctx.redirect('/') } }, }
const initialState = { items:[] } export default function itemsReducer(state = initialState, action) { switch(action.type) { case 'INSERT_ITEM': return { items: [...state.items, action.payload.item] }; case 'REMOVE_ITEM': return { items: state.items.filter((item, index) => index !== action.payload.item_index) } case 'UPDATE_ITEM': return { items: updateItems(state.items, action.payload) } default: return state; } } function updateItems(items, data) { items[data.item_index] = data.item_value; return items; }
module.exports = { remote: { require: jest.fn(), } };
;(function(window, document) { 'use strict'; /** * Get the value of a querystring * @param {String} field The field to get the value of * @param {String} url The URL to get the value from (optional) * @return {String} The field value */ window.getQueryString = function(field, url) { var href = url ? url : window.location.href; var reg = new RegExp('[?&]' + field + '=([^&#]*)', 'i'); var string = reg.exec(href); return string ? string[1] : null; }; /** * Disable / Re-enable a form submittable element<br> * Use this instead of the HTML5 disabled prop * @param {String|jQuery|Object} selector The selector for element to toggle * @param {Boolean} disable Whether to disable or re-enable * @param {Boolean} child Whether to change cursor on child instead */ window.toggleElemDisabled = function(selector, disable, child) { var select_elem = null; if (typeof selector === 'string' || selector instanceof String) { select_elem = $(selector); } else if (selector instanceof jQuery) { select_elem = selector; } else { console.err("toggleElemDisabled(): invalid selector argument"); return; } /* by default change cursor on parent not child */ child = child || false; if (disable) { if (!child) { select_elem.parent().css({'cursor': 'not-allowed'}); } else { select_elem.css({'cursor': 'not-allowed'}); } select_elem.css({ 'background-color': '#EEEEEE', 'opacity': '0.7', 'pointer-events': 'none' }); select_elem.prop('readonly', true); select_elem.prop('tabindex', -1); select_elem.prop('disabled', true); } else { if (!child) { select_elem.parent().removeAttr('style'); } select_elem.removeAttr('style'); select_elem.prop('readonly', false); select_elem.prop('tabindex', 0); select_elem.prop('disabled', false); } }; /** * Recursively search DOM tree until test is true<br> * Starts at and includes selected node, tests each descendant<br> * Note that test callback applies to jQuery objects throughout * @param {String|jQuery|Object} selector The selector for start node * @param {Function} test Test to apply to each node * @return {jQuery|null} Returns found node or null */ window.descendingSearch = function(selector, test) { var select_node = null; if (typeof selector === 'string' || selector instanceof String) { select_node = $(selector); } else if (selector instanceof jQuery) { select_node = selector; } else { return null; } var num_nodes = select_node.length || 0; if (num_nodes > 1) { for (var i = 0; i < num_nodes; i++) { if (test(select_node[i])) { return select_node[i]; } } } else { if (test(select_node)) { return select_node; } } var node_list = select_node.children(); if (node_list.length <= 0) { return null; } descendingSearch(node_list, test) }; /** * Validate form fields in a selected node<br> * The optional test function is passed a an array of fields found<br> * Note that in this project our forms are usually the 1st child in a modal body<br> * If provided the test function should return an object of this structure:<br> * <pre> * { * result: boolean - whether the test passed or failed * err_node: element|jQuery|Object - the node that caused the failure * err_msg: String - the error message to display * } * </pre> * @param {String|jQuery|Object} selector Selector for a node with fields * @param {Function} test Custom validation test to run * @returns {Boolean} Whether the validation passed * @throws {Error} If selector is invalid */ window.validateFields = function(selector, test) { var select_node = null; if (typeof selector === 'string' || selector instanceof String) { select_node = $(selector); } else if (selector instanceof jQuery) { select_node = selector; } else if (typeof selector === "object" || selector instanceof Object) { select_node = $(selector); } else { throw new Error("validateFields(): invalid selector argument"); } /* grab the fields */ var elems = select_node.find('input,textarea,select,output').filter(':not(:hidden)').get(); /* check the builtin form validation */ for (var i = 0; i < elems.length; i++) { if (!elems[i].reportValidity()) { return false; } } /* if supplied, run the custom test function */ if (typeof test === 'function') { var resp = test(elems); if (resp.result === false) { var err_elem = null; if (resp.err_node instanceof jQuery) { err_elem = resp.err_node.get(0); } else { err_elem = resp.err_node; } err_elem.setCustomValidity(resp.err_msg); err_elem.reportValidity(); setTimeout(function() { err_elem.setCustomValidity(''); }, 2500); return false; } } return true; }; /** * Checks if selected element has a particular event listener<br> * Works for on<event> DOM events, and dynamic events added using jquery<br> * Events added dynamically using addEventListener will not be found * @param {String|jQuery|Object} selector Selector for a node with fields * @param {String} event Event listener type to check for * @returns {Boolean} * @throws {Error} If selector is invalid */ function hasEventListener(selector, event) { var element = undefined; if (typeof selector === 'string' || selector instanceof String) { element = $(selector).get(0); } else if (selector instanceof jQuery) { element = selector.get(0); } else if (typeof selector === "object" || selector instanceof Object) { element = $(selector).get(0); } if (element === undefined) { throw new Error("validateFields(): invalid selector argument"); } if (element.hasAttribute('on'+event)) { return true; } else if ($._data(element, "events").hasOwnProperty(event)) { return true; } return false; } /** * Show notification in top notification bar * @param {String} msg message to display * @param {Boolean} error whether the notification is an error */ window.showNotification = function(msg, error = false) { var top_bar = $('.top-bar'); var msg_bar = $('.message-bar'); var visible_modals = $('.modal').filter(':not(:hidden)'); // hide modals if shown visible_modals.modal('hide'); // stop the animation if already running top_bar.stop(true, true); // change the notification accordingly if (error === true) { msg_bar.removeClass("alert-success"); msg_bar.addClass("alert alert-danger"); msg_bar.html("<strong>Failed!</strong> " + msg); } else { msg_bar.removeClass("alert-danger"); msg_bar.addClass("alert alert-success"); msg_bar.html("<strong>Success!</strong> " + msg); } // start the animation showing the notification top_bar.show(); top_bar.slideUp(10000, function() { top_bar.hide(); }); }; /** * Update reload kamailio button to indicate if reload is required * @param {Boolean} required whether a reload is required */ window.reloadKamRequired = function(required = true) { var reload_button = $('#reloadkam'); if (reload_button.length > 0) { if (required) { reload_button.removeClass('btn-primary'); reload_button.addClass('btn-warning'); } else { reload_button.removeClass('btn-warning'); reload_button.addClass('btn-primary'); } } }; })(window, document);
export const colorScheme1 = [ "#7AC2E2", "#689EBE", "#577B9A", "#455A75", "#323C52" ]; export const colorScheme2 = [ "#323C52", "#5E4C74", "#9B5682", "#D46378", "#F8805D" ] export const colorScheme3 = [ "#F8805D", "#FF6373", "#F94B93", "#DF44BA", "#A852E1" ] export const colorScheme4 = [ "#A852E1", "#D25FCE", "#EA76BF", "#F691B9", "#FAADBC" ] export const colorScheme5 = [ "#FAADBC", "#FD97AB", "#FF7F9B", "#FF6589", "#FF4578" ] export const colorScheme6 = [ "#FF4578", "#FA6A88", "#F28699", "#E99FA9", "#DCB6BB" ]
export const generateAddresses = (count) => { let res = []; for (let i = 0; i < count; i++) { let address = '0x'; for (let j = 0; j < 40; j++) { address = address + Math.floor(Math.random()*10).toString(); } res.push(address); } return res; }
import React, { useContext, useEffect, useState } from 'react'; import { userContext } from '../../App'; import Header from '../Header/Header'; import './Order.css' const Orders = () => { const [loading, setLoading] = useState(true); const [loggedInUser, setLoggedInUser] = useContext(userContext); const [orders, setOrders] = useState([]); useEffect(() => { const url = `https://banana-tart-33572.herokuapp.com/orders?email=${loggedInUser.email}` fetch(url) .then(response => response.json()) .then(data => { setOrders(data) setLoading(false) }) }, [loggedInUser]); console.log(orders); return ( <div> <Header></Header> { loading ? ( <div class="d-flex justify-content-center text-muted mt-5"> <div class="spinner-border" role="status"> <span class="sr-only ">Loading...</span> </div> </div> ) : ( <table className="order-card"> <thead> <tr> <th>Book</th> <th>Author</th> <th>Quantity</th> <th>Price</th> <th>Pachesing Date</th> </tr> </thead> { orders.map(order => <tr> <td>{order.bookName}</td> <td>{order.bookAuthor}</td> <td>{order.quantity}</td> <td>{order.bookPrice}</td> <td>{(new Date(order.orderDate)).toDateString('dd/MM/yyyy')}</td> </tr>) } <tbody> </tbody> </table> ) } </div> ); }; export default Orders;
const R = require('ramda') class DataBase { constructor() { this.db = {} } saveEntity(entity, collection) { const newEntityCollection = R.pipe( R.propOr([],collection), R.concat([entity]) )(this.db) this.db = R.assocPath([collection], newEntityCollection, this.db) } updateEntity(id, payload, collection) { const entity = R.pipe( R.propOr([], collection), R.find(R.propEq('_id', id)) )(this.db) if(!entity || entity.length < 1) return null const updatedEntity = R.mergeRight(entity, payload) const updatedCollection = R.pipe( R.propOr([], collection), R.reject(R.whereEq({ _id: updatedEntity._id })), R.concat([updatedEntity]) )(this.db) this.db = R.assocPath([collection], updatedCollection, this.db) return updatedEntity } deleteEntity(id, collection) { const updatedCollection = R.pipe( R.propOr([], collection), R.reject(R.whereEq({ _id: id })), )(this.db) this.db = R.assocPath([collection], updatedCollection, this.db) return true } getEntities(query, collection) { if(!query) return R.propOr([], collection, this.db) return R.pipe ( R.propOr([], collection), R.filter(R.whereEq(query)) )(this.db) } getEntityById(_id, collection) { return R.find(R.propEq('_id', _id), this.db[collection]) } } const db = new DataBase() class MockedDatabase extends DataBase { constructor(data) { super() this.db = data } } module.exports = { DataBase, MockedDatabase, db, }
let pos = 0; const pacArray = [ ['./images/PacMan1.png', './images/PacMan2.png'], ['./images/PacMan3.png', './images/PacMan4.png'], ]; let direction = 0; const pacMen = []; // This array holds all the pacmen // This function returns an object with random values function setToRandom(scale) { return { x: Math.random() * scale, y: Math.random() * scale, }; } // Factory to make a PacMan at a random position with random velocity function makePac() { // returns an object with random values scaled {x: 33, y: 21} let velocity = setToRandom(10); // {x:?, y:?} let position = setToRandom(200); // Add image to div id = game let game = document.getElementById('game'); let newimg = document.createElement('img'); newimg.style.position = 'absolute'; newimg.src = './images/PacMan1.png'; newimg.width = 100; // TODO: set position here if(pos === window.innerwidth + newimg) direction = 1; if(pos < 0) direction = 0; // TODO add new Child image to game game.appendChild(newimg); // return details in an object return { position, velocity, newimg, }; } function update() { // loop over pacmen array and move each one and move image in DOM pacMen.forEach((item) => { checkCollisions(item); item.position.x += item.velocity.x; item.position.y += item.velocity.y; item.newimg.style.left = item.position.x; item.newimg.style.top = item.position.y; }); setTimeout(update, 20); } function checkCollisions(item) { if(item.position.x + item.velocity.x + item.newimg.width > window.innerWidth || item.position.x + item.velocity.x < 0) item.velocity.x = -item.velocity.x; if(item.position.y + item.velocity.y + item.newimg.height > window.innerHeight || item.position.y + item.velocity.y < 0) item.velocity.y = - item.velocity.y; // TODO: detect collision with all walls and make pacman bounce } function makeOne() { pacMen.push(makePac()); // add a new PacMan } //don't change this line if (typeof module !== 'undefined') { module.exports = { checkCollisions, update, pacMen }; }
import Rails from 'rails-ujs' export default class Editable { constructor() { app.document .on('click focus', '[data-editable="update"]', (e) => { this._start(e) }) .on('click', '[data-editable="save"]', (e) => { this._stop() }) .on('click', '[data-editable="cancel"]', (e) => { this._cancel(e) }) .on('keydown', '[data-editable="update"]', (e) => { this._onKeydown(e) }) .on('click', () => { this._stop() }) } _start(e) { e.stopPropagation() if (this._currentEl) return this._currentEl = $(e.target) this._originalText = this._currentEl.text() this._editBtn = $(this._currentEl.data('edit')) this._autosave = !this._currentEl.data('save') if(!this._autosave) this._resize(0) this._hideEdit() } _stop(save = true) { if (!this._currentEl) return if (save) this._save() this._currentEl = null this._originalText = null this._editBtn = null } _save() { this._showEdit() const value = this._currentEl.val() if (value.length && value == this._originalText) { return this._showMarkup() } $(this._currentEl.data('update')).text(value) this._saveRemote(this._prepareData(value)) } _prepareData(value) { var data = {} const modelName = this._currentEl.data('model') data[modelName] = {} data[modelName][this._currentEl.data('attribute')] = value return data } _saveRemote (data) { $.ajax({ type: this._getType(), url: this._currentEl.data('url'), data: data }) } _getType() { return this._currentEl.data('type') || 'PUT' } _cancel(e) { e.stopPropagation() this._showEdit() this._showMarkup() } _onKeydown(e) { // 27 ESC // 13 ENTER const escaping = e.which == 27 const entering = e.which == 13 const autosaving = this._autosave && entering if (entering && !this._currentEl) { return e.preventDefault() } if (entering && !this._autosave) { return this._resize() } if (!(this._currentEl && (autosaving || escaping))) return e.preventDefault() this._currentEl.blur() if (escaping && this._originalText) this._currentEl.val(this._originalText) this._stop(!escaping) } _showMarkup() { const id = this._currentEl.data('show') if (!id) return const el = $(id) if (el.length) { el.show() this._currentEl.parent().remove() } this._removeParent() this._stop(false) } _removeParent() { const id = this._currentEl.data('parent') if (!id) return $(id).remove() } _showEdit() { if (this._editBtn && this._editBtn.length) this._editBtn.show() } _hideEdit() { if (this._editBtn && this._editBtn.length) this._editBtn.hide() } _resize(extraRows = 1) { const el = this._currentEl[0] const rows = this._currentEl.val().split("\n").length this._currentEl.height((rows + extraRows) * 21) } }
import React from 'react'; import styles from './ImageList.module.css'; import ImageCard from './ImageCard.component'; const ImageList = (props) => { console.log(props.images); return ( <div className={styles.ImageList}> {props.images.map((image) => ( <ImageCard key={image.id} image={image} /> ))} </div> ); }; export default ImageList;
var add = { add: function(first, second){ console.log(first + second); } }; module.exports = add
const mongoose = require("mongoose"); mongoose.set("debug", true); mongoose.connect(`${process.env.MONGODB_URI}`); mongoose.Promise = Promise; module.exports.Todo = require("./todo.js");
import { FETCH_DATA, CHANGE_VALUE, SELECT_PROGRESS_BAR, fetchData, changeProgressBarValue, selectProgressBar, default as progressBarDemoReducer } from 'routes/ProgressBarDemo/modules/ProgressBarDemoReducer' describe('(Redux Module) ProgressBarDemo', () => { it('Should export a constant FETCH_DATA.', () => { expect(FETCH_DATA).to.equal('FETCH_DATA') }) it('Should export a constant CHANGE_VALUE.', () => { expect(CHANGE_VALUE).to.equal('CHANGE_VALUE') }) it('Should export a constant SELECT_PROGRESS_BAR.', () => { expect(SELECT_PROGRESS_BAR).to.equal('SELECT_PROGRESS_BAR') }) describe('(Reducer)', () => { it('Should be a function.', () => { expect(progressBarDemoReducer).to.be.a('function') }) it('Should initialize with a state object.', () => { expect(progressBarDemoReducer(undefined, {})).to.be.a('object') }) }) describe('(Action Creator) fetchData', () => { it('Should be exported as a function.', () => { expect(fetchData).to.be.a('function') }) it('Should return an action with type "FETCH_DATA".', () => { expect(fetchData()).to.have.property('type', FETCH_DATA) }) it('Should assign the argument to the "data" property.', () => { let _data = { "buttons": [ 38, 15, -49, -9 ], "bars": [ 73, 41, 36, 89 ], "limit": 110 }; expect(fetchData(_data)).to.have.property('data', _data) }) }) describe('(Action Creator) changeProgressBarValue', () => { it('Should be exported as a function.', () => { expect(changeProgressBarValue).to.be.a('function') }) it('Should return an action with type "CHANGE_VALUE".', () => { expect(changeProgressBarValue()).to.have.property('type', CHANGE_VALUE) }) it('Should assign the argument to the "value" property.', () => { expect(changeProgressBarValue(50)).to.have.property('value', 50); expect(changeProgressBarValue(23)).to.have.property('value', 23); expect(changeProgressBarValue(-45)).to.have.property('value', -45); expect(changeProgressBarValue(-17)).to.have.property('value', -17); }) }) describe('(Action Creator) selectProgressBar', () => { it('Should be exported as a function.', () => { expect(selectProgressBar).to.be.a('function') }) it('Should return an action with type "CHANGE_VALUE".', () => { expect(selectProgressBar()).to.have.property('type', SELECT_PROGRESS_BAR) }) it('Should assign the argument to the "progressBarIndex" property.', () => { expect(selectProgressBar(0)).to.have.property('progressBarIndex', 0); expect(selectProgressBar(1)).to.have.property('progressBarIndex', 1); expect(selectProgressBar(2)).to.have.property('progressBarIndex', 2); }) }) })
import React, { useEffect, useState } from 'react'; import socketIOClient from 'socket.io-client'; import logo from './logo.svg'; import './App.css'; import Namespaces from './components/Namespaces'; import Rooms from './components/Rooms'; import ChatArea from './components/ChatArea'; const username = prompt('What is your name?'); function App() { const [socket, setSocket] = useState(); const [nsSocket, setNsSocket] = useState(); const [namespaces, setNamespaces] = useState([]) const [selectedNamespace, setSelectedNamespace] = useState(); const [rooms, setRooms] = useState(); const [selectedRoom, setSelectedRoom] = useState(); const [currentNumberOfUsers, setCurrentNumberOfUsers] = useState(0); const [messageToClients, setMessageToClients] = useState([]); useEffect(() => { let s = socketIOClient('http://localhost:9000', { query: { username } }); setSocket(s); }, []); useEffect(() => { if(socket) { socket.on('nsList', nsData => { setNamespaces(nsData); if(!selectedNamespace && nsData.length) { setSelectedNamespace(nsData[0]); } }); } }, [socket]); useEffect(() => { if(selectedNamespace) { if(nsSocket) { nsSocket.close(); } const { endpoint } = selectedNamespace; let s = socketIOClient('http://localhost:9000' + endpoint); setNsSocket(s); } }, [selectedNamespace]) const handleClickNamespace = (namespace) => { setSelectedNamespace(namespace); } useEffect(() => { if(nsSocket) { nsSocket.on('nsRoomLoad', (nsRooms) => { setRooms(nsRooms); }); nsSocket.on('messageToClients', (msg) => { setMessageToClients(currMessages => [...currMessages, msg]); }) } }, [nsSocket]); const handleClickRoom = (room) => { setSelectedRoom(room); } useEffect(() => { if(selectedRoom) { const { roomTitle } = selectedRoom; nsSocket.emit('joinRoom', roomTitle, (newNumberOfMembers) => { setCurrentNumberOfUsers(newNumberOfMembers); }); nsSocket.on('historyCatchUp', history => { setMessageToClients(history); }); nsSocket.on('updateMembers', (numOfMembers) => { setCurrentNumberOfUsers(numOfMembers); }) } }, [selectedRoom]); const handleClickSend = (text) => { nsSocket.emit('newMessageToServer', text); } return ( <div className="App"> <Namespaces namespaces={namespaces} onClickNamespace={handleClickNamespace} selectedNamespace={selectedNamespace}/> <Rooms rooms={rooms} onClickRoom={handleClickRoom}/> <ChatArea currentNumberOfUsers={currentNumberOfUsers} onClickSend={handleClickSend} messageToClients={messageToClients} /> </div> ); } export default App;
console.log('js czech'); var app = angular.module('FoodApp', []); app.controller('FoodController', function() { console.log('FoodController loaded'); var self = this; self.message = 'sup'; self.food = 'candy'; }); function Foods() { console.log('food check'); //connect to server here }
import Round from "./round"; export default class Match { constructor(date, opponent, bounty,matchdata=[]) { //match data is supposed to be a json file this.dateStarted = date; this.opponent = opponent; this.reward = bounty; this.currentRound = 0; this.roundData = matchdata; this.rounds = Array(this.roundData.length).fill(null); for (let i = 0; i < this.rounds.length; i++) { if (this.rounds[i] == null) this.rounds[i] = new Round(this.roundData[i].questions[0].categoryTitle, this.roundData[i].questions.length, 'you',this.roundData[i]); } } getDate = () => this.date; getOpponent = () => this.opponent; getReward = () => this.reward; setCurrentRound = index => (this.currentRound = index); getCurrentRound = () => this.currentRound; fillRounds = () => { }; }
import request from '@/utils/request'; export function UploadAvatar(data) { return request({ url: '/profile', method: 'post', data: data, }); } export function getProfile(query) { return request({ url: '/profile', method: 'get', params: query, }); } export function update_password(data){ return request({ url: 'profile/changepass', method: 'put', data: data, }); }
import Fonts from './fonts' import Events from './events' import Colors from './colors' import RouteType from './route' import { apiEndpoint, project } from './environment' export { Fonts, Events, Colors, project, RouteType, apiEndpoint, }
const express = require("express"); const router = express.Router(); const passport = require("passport"); const FacebookStrategy = require("passport-facebook").Strategy; require("./facebook-setup.js"); router.get("/facebook-login", passport.authenticate("facebook")); router.get("/success", (req, res) => { res.send("Auth Success!"); }); router.get("/fail", async (req, res) => { res.send("Auth Fail."); }); router.get( "/callback", passport.authenticate("facebook", (err, prof) => { // User-Data in prof. }) ); module.exports = router;
const { List, Struct, Byte, ui8, b1, Pointer, Variable, ui16, b2, sui16, ByteArr, } = require("../index.js"); const Buffer = require("buffer/").Buffer; const Status = Byte.define( [ ["playerState", b2], ["deviceTime", b1], ["geoData", b1], ["presenceSensor", b1], ["errorFlag", b1], ["timerEnabled", b1], ["powerOn", b1], ], ui8, "status" ); const Type = Struct.define([ ["type", ByteArr.define(8, ui8)], ]) const Header = Struct.define([ Type, ["status", Status], ]); const Test = Struct.define([ Header, ["strTest", sui16], ["host", ui16], ["ip", List.define(ui8, 4)], ]); const status = { powerOn: 0, timerEnabled: 0, errorFlag: 0, presenceSensor: 0, geoData: 0, deviceTime: 1, playerState: 0, }; const test = { type: 11, status, strTest: "VP", host: 128, ip: [127, 0, 0, 1], }; console.log({ Test }); const p = new Pointer(new Buffer(Test.size), 0); const v = new Variable(Test, p); v.pack(test); const unpacked = v.unpack(p); console.log({ buffer: p.buf, unpacked });
import React, { Component } from 'react'; import axios from 'axios'; // import './App.css'; import Results from './Results'; import Inputs from './Inputs'; class App extends Component { state = { results: '', queryObj: {}, toptags: [], resultsList: [] } getTopTags = (artist) => { let lastFMurl = `http://ws.audioscrobbler.com/2.0/`; lastFMurl += `?method=artist.gettoptags&artist=${artist}`; lastFMurl += `&api_key=${process.env.REACT_APP_LASTM_KEY}&format=json`; setTimeout( () => axios.get(lastFMurl) .then( results => { let toptags = results.data.toptags; console.log(toptags.tag[0].name); let tempArr = [toptags.tag[0].name, toptags.tag[1].name]; this.setState({toptags: [...this.state.toptags,...tempArr]}) }).catch( err => { console.log(artist + 'caused tag error'); }) , 1000) } findTally = () => { let arr = this.state.toptags; let tally = {}; let a = ''; for (let i = 0; i < arr.length; i++) { a = arr[i]; tally[a] = (tally[a] || 0) + 1; } var sortable = []; for (var tag in tally) { sortable.push([tag, tally[tag]]); } sortable.sort(function(a, b) { return a[1] - b[1]; }).reverse(); this.setState({resultsList: sortable}); console.log(sortable); } getLastFM = (type, entry) => { // Set the API root URL let lastFMurl = `http://ws.audioscrobbler.com/2.0/`; let keyAndFormat = `&api_key=${process.env.REACT_APP_LASTM_KEY}&format=json`; let methods = ''; switch (type){ case 'user': // Get user's library methods += `?method=library.getartists&limit=200&page=2&user=${entry}`; break; case 'user chart list': // Get user's charts methods += `?method=user.getweeklychartlist&user=${entry}`; break; case 'artist': // Get similar artists methods += `?method=artist.getSimilar&&artist=${entry}`; break; case 'artist top tags': // Get top tags methods += `?method=artist.gettoptags&artist=${entry}`; break; case 'user top tags': // Get user's top assigned tags methods += `?method=user.gettoptags&user=${entry}`; break; default: console.log('No matching cases'); break; } axios.get(lastFMurl + methods + keyAndFormat) .then( results => { this.setState({queryObj: results.data}) console.log(results.data); }) .catch( err => { console.log(err) }); // lastFMurl = `http://ws.audioscrobbler.com/2.0/&api_key=${process.env.REACT_APP_LASTM_KEY}&format=json`; // this.state.queryObj.artists.forEach(curr => { // console.log(curr.name); // }); } render() { return ( <div> <Inputs queryObj={this.state.queryObj} getLastFM={this.getLastFM} getTopTags={this.getTopTags} findTally={this.findTally} /> <Results resultsList={this.state.resultsList} results={this.state.results} /> </div> ); } } export default App;
const ExamHall = require('../model/examhall'); const { mainUserEnums } = require('../config/enums'); exports.createExamHall = async (req, res) => { try { const body = req.body; if (!body.usedCount) { body.usedCount = body.maxCount; } const examHall = ExamHall(body); await examHall.save(); return res.status(201).json({ msg: "exam hall Created", data: examHall, }); } catch (error) { if (error.errors.name) { return res.status(403).json({ msg: error.errors.name.properties.message }); } return res.status(500).json({ msg: "Error Occured" }); } } exports.examHallList = async (req, res) => { try { const examHallData = await ExamHall.find(); return res.json({ data: examHallData }); } catch (error) { return res.status(500).json({ msg: "Error Occured" }); } } exports.examHallEdit = async (req, res) => { try { const { name, maxcount, usedcount } = req.body; let databaseBody = {}; if (name) { databaseBody['name'] = name; } if (maxcount) { databaseBody['maxCount'] = maxcount; } if (usedcount) { databaseBody['usedCount'] = usedcount; } const examID = req.examhall._id; await ExamHall.updateOne({ _id: examID }, { $set: databaseBody }); return res.json({ msg: "ExamHall updated" }); } catch (error) { return res.status(500).json({ msg: "error Occured" }); } } exports.examHallDelete = async (req, res) => { try { const examHallID = req.examhall._id; await ExamHall.deleteOne({ _id: examHallID }); return res.json({ msg: "Examhall Deleted" }); } catch (error) { return res.status(500).json({ msg: "Error Occured", status: false }); } } exports.examhallByID = async (req, res, next, id) => { try { if (!id.match(/^[0-9a-fA-F]{24}$/)) { return res.status(406).json({ status: false, msg: "This ExamHall is not acceptable" }); } const examHall = await ExamHall.findOne({ _id: id }); if (!examHall) return res.status(401).json({ msg: "This ExamHall doesn't exist" }); req.examhall = examHall; next(); } catch (error) { return res.status(500).json({ msg: "error Occured" }); } }
require('dotenv').config(); const rp = require('request-promise'); const { createUser, getUserInfoWithJoin, insertFbLoginUserTable, insertFBProfile, } = require('../../Model/v1/user'); const UserResponseModel = require('../../responseModel/userResponse'); const { handleAccessTokenAndRemainingTime } = require('../../common/common'); // 登入 const userSignin = async (req, res) => { const { provider, email, password } = req.body; const fbLoginToken = req.body.access_token; const { newAccessToken, tokenExpiredDate, hashedResult, } = handleAccessTokenAndRemainingTime(provider, email, password, 1, fbLoginToken); // 要更新token try { if (provider === 'facebook') { const fbLoginInsertUserTableResult = await insertFbLoginUserTable(provider, newAccessToken, tokenExpiredDate, hashedResult); if (fbLoginInsertUserTableResult.affectedRows > 0) { const insertUserId = fbLoginInsertUserTableResult.insertId; // 打 request 拿取 fb 個資並存入DB const options = { uri: 'https://graph.facebook.com/me', qs: { fields: 'id,name,email,picture', access_token: fbLoginToken, }, json: true, }; const fbResponse = await rp(options); // 把FB個資存到DB const fbUserName = fbResponse.name; const fbPicture = fbResponse.picture.data.url; const fbEmail = fbResponse.email; const insertFBUserProfileResult = await insertFBProfile(insertUserId, fbUserName, fbPicture, fbEmail); if (insertFBUserProfileResult.affectedRows > 0) { res.json({ data: { access_token: newAccessToken, access_expired: tokenExpiredDate, user: { id: insertUserId, provider: 'facebook', name: fbUserName, email: fbEmail, picture: fbPicture, }, }, }); } } } } catch (err) { console.log('更新用戶token失敗'); throw err; } }; // 註冊 const userSignup = async (req, res) => { // provider這邊先寫死 const provider = 'native'; // picture也先寫死 const picture = 'https://school.appworks.tw/wp-content/uploads/2018/09/cropped-AppWorks-School-Logo-thumb.png'; const { name, email, password } = req.body; // token生成 const { newAccessToken, expiredTimeRange, tokenExpiredDate, hashedResult, } = handleAccessTokenAndRemainingTime(provider, email, password, 1, ''); try { const creatUserResult = await createUser(provider, name, hashedResult, email, picture, newAccessToken, tokenExpiredDate); if (creatUserResult.affectedRows > 0) { const getInsertUserResults = await getUserInfoWithJoin(provider, creatUserResult.insertId); const getInsertUserResult = getInsertUserResults[0]; const userResModel = new UserResponseModel(newAccessToken, expiredTimeRange * 60, getInsertUserResult.userId, provider, getInsertUserResult.native_user_name, getInsertUserResult.native_user_email, getInsertUserResult.native_user_picture); res.json({ data: userResModel.assembleSignInSignUpRes(), }); } } catch (err) { console.log('創建User錯誤'); throw err; } }; const getUserProfie = async (req, res) => { const { userInfo } = req; res.json({ data: { id: userInfo.id, provider: userInfo.provider, name: userInfo.username, email: userInfo.userEmail, picture: userInfo.userPicture, }, }); }; module.exports = { userSignin, userSignup, getUserProfie, };
import React from 'react' export default function Schedule() { return ( <div> <div class="card"> <div class="card-body"> <h5 class="card-title">Schedule</h5> <p class="card-text">To Be Announced...</p> </div> </div> </div> ) }
#!/usr/bin/env node const pug = require('pug') const sass = require('node-sass') const fs = require('fs') const path = require('path') const preocessInputData = new Promise((res, rej) => { const stdin = process.openStdin(); let data = ""; stdin.on('data', function (chunk) { data += chunk; }); stdin.on('end', function () { res(data) }); }) const prepareModel = original => { let errorCountReducer = (acc, cur) => acc + cur.summary.errorCount; const tools = original.tools.map(x => ({ total: x.summary.errorCount, pageCount: x.summary.pageCount, techName: x.tool, version: x.version, name: x.name, paths: x.paths })) const totalErrorCount = original.tools.reduce(errorCountReducer, 0) return Object.assign({}, {original, totalErrorCount, tools}) } const includeJs = model => (new Promise((res, rej) => { fs.readFile(path.join(__dirname, 'assets', 'report.js'), 'utf8', (err, contents) => { if (err) { rej(err) } else { const updatedModel = Object.assign({}, model); updatedModel.assets = Object.assign({}, model.assets, {javascript: contents}) res(updatedModel) } }) })) const includeSass = model => (new Promise((res, rej) => { sass.render({ file: 'assets/style.scss' }, (err, result) => { if (err) { rej(err) } else { res(result.css.toString().split('\n').join('')) } }) })) .then(stylesheet => Object.assign( {}, model, { assets: Object.assign( {}, model.assets, {stylesheet} ) })) preocessInputData .then(JSON.parse) .then(prepareModel) .then(includeSass) .then(includeJs) .then(model => pug.renderFile('template.pug', model)) .then(console.log) .catch(e => { console.error('Something went wrong when preparing report') console.error('error was [%s] with message [%s]', e.name, e.message) console.error(e.stack) process.exit(1) })
import React from 'react'; const Img = ({ imageSrc, imageAlt, imageClass, onClick }) => { return ( <img src={imageSrc} alt={imageAlt} className={imageClass} onClick={onClick} /> ); }; export default Img;
import React from 'react'; import PropTypes from 'prop-types'; import {withStyles} from '@material-ui/core/styles'; import ExpansionPanel from '@material-ui/core/ExpansionPanel'; import ExpansionPanelSummary from '@material-ui/core/ExpansionPanelSummary'; import ExpansionPanelDetails from '@material-ui/core/ExpansionPanelDetails'; import ExpandMoreIcon from '@material-ui/icons/ExpandMore'; const styles = { fontColor: '#1a73ba', }; function TrainingsPanel(props) { const {trainings} = props; return ( <div style={{backgroundColor:'#f0f0f0'}}> {trainings.map(training => { return ( <ExpansionPanel> <ExpansionPanelSummary expandIcon={<ExpandMoreIcon/>}> <div style={{width:'100%'}}> <div style={{float:'left',color: "#1a73ba", fontSize:'14px', width:'20%'}}>{training.trainingName}</div> <div style={{fontSize:'10px',color:"#212121",width:'70%'}}>{training.trainingForRoles}</div> <div style={{fontSize:'10px',color:"#505050",float:'right',width:'10%'}}><b>{training.participantCount}</b> Interested</div> </div> </ExpansionPanelSummary> <ExpansionPanelDetails> <div style={{width:'100%',backgroundColor:'#fafafa',color: "#000000",height:'22px'}}> <div style={{float:'left', fontSize:'12px', width:'30%'}}>{"12/11/2011"}</div> <div style={{float:'left', fontSize:'12px', width:'20%'}}>{training.location}</div> <div style={{float:'left', fontSize:'12px', width:'25%'}}>{training.trainerCount} TRAINERS</div> <div style={{float:'left', fontSize:'12px', width:'25%'}}>{training.participantCount} PARTICIPANTS</div> </div> </ExpansionPanelDetails> </ExpansionPanel>)} ) } </div> ); } TrainingsPanel.propTypes = { classes: PropTypes.object.isRequired, trainings: PropTypes.array.isRequired }; export default withStyles(styles)(TrainingsPanel);
// JavaScript Document $("document").ready(function() { $("#cheat_frm_link").click(function(){ /*$("#cheat_frm").submit(function(){ });*/ $.ajax({ type: "POST", url: "http://localhost/csrf_demo/transfer.php", data: $("#cheat_frm").serialize(), // serializes the form's elements. success: function(data) { //window.location.href = "http://www.amazon.in"; window.location.href= "test.php"; } }); }); $("#secure_cheat_frm_link").click(function(){ /*$("#cheat_frm").submit(function(){ });*/ $.ajax({ type: "POST", url: "http://localhost/csrf_demo/secure-transfer.php", data: $("#cheat_frm").serialize(), // serializes the form's elements. success: function(data) { //window.location.href = "http://www.amazon.in"; window.location.href= "test.php"; } }); }); });
import contact01 from '../assets/images/contact-01.png'; import contact02 from '../assets/images/contact-02.png'; import contact03 from '../assets/images/contact-03.png'; import contact04 from '../assets/images/contact-04.png'; import contact05 from '../assets/images/contact-05.png'; export class experienceContact extends HTMLElement { constructor() { super(); this.template(); this.addresData = this.querySelector(".address"); this.telephoneData = this.querySelector(".tel"); this.emailData = this.querySelector(".email"); this.websiteData = this.querySelector(".websitelink"); this.contact5Data = this.querySelector(".contact5"); } set address(address) { this._address = address; if (address) { this.addresData.innerHTML = this._address; } } get address() { return this._address; } set telephone(tel) { this._telephone = tel; if (tel) { this.telephoneData.innerHTML = this._telephone; } } set email(email) { this._email = email; if (email) { this.emailData.innerHTML = this._email; } } set website(data) { this._website = data; if (data) { this.websiteData.innerHTML = `<a href="${data.link}">${data.name}</a>`; } } set socialIdentifiers(data) { this._contact5 = data; if (data) { this.contact5Data.innerHTML = data; } } template() { this.innerHTML = ` <div class="exp-contact"> <ul class="list-contact"> <li> <div class="icon"> <img src="${contact01}" alt="icon-contact"> </div> <div class="post-contact address">${this.address}</div> </li> <li> <div class="icon"><img src="${contact02}" alt="icon-contact"></div> <div class="post-contact tel"></div> </li> <li> <div class="icon"><img src="${contact03}" alt="icon-contact"></div> <div class="post-contact email"></div> </li> <li> <div class="icon"><img src="${contact04}" alt="icon-contact"></div> <div class="post-contact websitelink"></div> </li> <li> <div class="icon"><img src="${contact05}" alt="icon-contact"></div> <div class="post-contact contact5"></div> </li> </ul> </div> `; } }
import React from 'react' import PropTypes from 'prop-types' import NavBar from 'components/organisms/NavBar' import Footer from 'components/organisms/Footer' const MainLayout = ({ title, children, routes, styles }) => ( <div className={styles.wrapper}> <NavBar routes={routes} /> <main className={styles.main}> {children} </main> <Footer className={styles.footer} title={title} links={routes.map(route => ({ href: route.path, text: route.title, }))} /> </div> ) MainLayout.propTypes = { children: PropTypes.oneOfType([ PropTypes.element, PropTypes.arrayOf(PropTypes.element), ]).isRequired, routes: PropTypes.array.isRequired, styles: PropTypes.shape({ wrapper: PropTypes.string, main: PropTypes.string, navBar: PropTypes.string, footer: PropTypes.string, }), title: PropTypes.string, } export default MainLayout
import React, { Component } from 'react'; import Card from 'react-bootstrap/Card'; import ListGroup from 'react-bootstrap/ListGroup'; import Button from 'react-bootstrap/Button'; class ShowOrders extends Component { constructor() { super(); this.state = { } } render() { return ( <Card style={{ width: '18rem' }}> <Card.Body> <Card.Title>Orden #{this.props.id}</Card.Title> <Card.Subtitle className="mb-2 text-muted">{this.props.name}</Card.Subtitle> <ListGroup> {this.props.items.map((item, index)=>( <ListGroup.Item variant="light">{item.product}</ListGroup.Item> )) } <ListGroup.Item variant="dark">{this.props.status}</ListGroup.Item> </ListGroup> <Button variant="primary" id={this.props.id} value={this.props.status} onClick={(e)=>{this.props.onChangeStatus(this.props.id, this.props.status)}}> Change Status </Button> </Card.Body> </Card> ) } } export default ShowOrders;
var data = { "defs": [ "$ Compare (#{files}) with the one from (#{numbers}) minutes ago {8}", "$ 「(#{files})」ファイルが(#{numbers})分前から(変化した|変わった)ところを(#{display}) {8}", "% git diff HEAD '@{#{$2} minutes ago}' #{$1} {8}", "$ Compare (#{files}) with the one from (#{numbers}) hours ago {8}", "$ 「(#{files})」ファイルが(#{numbers})時間前から(変化した|変わった)ところを(#{display}) {8}", "% git diff HEAD '@{#{$2} hours ago}' #{$1} {8}", "$ (#{numbers})分前の「(#{files})」ファイルと現在の(もの|バージョン)を比較する {8}", "% git diff HEAD '@{#{$1} minutes ago}' #{$2} {8}", "$ Compare (#{files}) with the one from (#{numbers}) days ago {8}", "% git diff HEAD '@{#{$2} days ago}' #{$1} {8}", "$ (#{numbers})日前の「(#{files})」ファイルと現在のものを(比較する|比べる) {8}", "% git diff HEAD '@{#{$1} days ago}' #{$2} {8}", "$ 現在の「(#{files})」ファイルを(#{numbers})日前のものを(比較する|比べる) {8}", "% git diff HEAD '@{#{$2} days ago}' #{$1} {8}", "$ (1つ|ひとつ)前のバージョンの(#{files})と比較 {8}", "$ (1つ|ひとつ)前のバージョンの(#{files})からの変更点 {8}", "% git diff $(git rev-list -n 1 HEAD -- #{$2})^ -- #{$2} {8}", "$ (#{files})を(1つ|ひとつ)前のバージョンと比較 {8}", "$ (#{files})の(1つ|ひとつ)前のバージョンからの変更点 {8}", "% git diff $(git rev-list -n 1 HEAD -- #{$1})^ -- #{$1} {8}", "$ (#{files})の最新版の変更点を(#{display}) {8}", "$ 最新の(#{files})の変更個所は? {8}", "$ (#{files})は最後にどこを変えた? {8}", "$ (#{files})の(一番新しい|最新の)変更は? {8}", "% git diff $(git rev-list -n 1 HEAD -- #{$1})^ -- #{$1} {8}", "$ (2つ|ふたつ)前のバージョンの(#{files})と比較 {8}", "$ (2つ|ふたつ)前のバージョンの(#{files})からの変更点を(#{display}) {8}", "% git diff $(git rev-list -n 1 HEAD -- #{$2})^^ -- #{$2} {8}", "$ Compare (#{files}) with the one from 2 versions before {8}", "$ (#{files})を(2つ|ふたつ)前のバージョンと比較 {8}", "$ (#{files})の(2つ|ふたつ)前のバージョンのからの変更点を(#{display}) {8}", "% git diff $(git rev-list -n 1 HEAD -- #{$1})^^ -- #{$1} {8}", "$ ファイルを大きい順に表示する {9}", "% git ls-files | xargs du -s | sort -r -n {9}", "$ 直前のコミットを取り消す {10}", "% git reset --soft HEAD^ {10}", "$ ひとつ前のコミットの状態に完全に戻す {10}", "% git reset --hard HEAD^ {10}", "$ コミット後の変更を全部消す {10}", "% git reset --hard HEAD {10}", "$ すごい昔の状態で動作を確認したい {10}", "% git reset --hard 昔のコミットのハッシュ値 {10}", "$ 直前のリセットをなかったことにする {10}", "% git reset --hard ORIG_HEAD {10}", "$ 過去のあらゆる操作履歴を見る {11}", "% git reflog {11}", "$ 過去のコミット履歴を見る {11}", "% git log {11}", "$ ブランチ(のリスト)?を(#{display}) {14}", "% git branch {14}", "$ (#{params})というブランチを作成する {14}", "% git branch #{$1} {14}", "$ (#{branches})というブランチを(#{del}) {14}", "% git branch -d #{$1} {14}", "$ 現在の編集状態を(#{display}) {18}", "$ 編集中のファイルを(#{display}) {18}", "% git status {18}", "$ (#{numbers})個前までのコミットをまとめる {22}", "% git rebase -i HEAD~#{$1} {22}", "$ ひとつ前の「(#{files})」ファイルを(#{display}) {24}", "$ 1バージョン前の「(#{files})」ファイルを(#{display}) {24}", "% git show HEAD~:#{$1} {24}", "$ ふたつ前の「(#{files})」ファイルを(#{display}) {24}", "$ 2バージョン前の「(#{files})」ファイルを(#{display}) {24}", "% git show HEAD~~:#{$1} {24}", "$ (#{numbers})個前の「(#{files})」ファイルを(#{display}) {24}", "$ (#{numbers})バージョン前の「(#{files})」ファイルを(#{display}) {24}", "% git show HEAD~#{$1}:#{$2} {24}", "$ Show (#{files}) from (#{numbers}) versions before {24}", "% git show HEAD~#{$2}:#{$1} {24}", "$ (#{numbers})分前の「(#{files})」ファイルを(#{display}) {24}", "% git show '@{#{$1} minutes ago}':#{$2} {24}", "$ (#{numbers})時間前の「(#{files})」ファイルを(#{display}) {24}", "% git show '@{#{$1} hours ago}':#{$2} {24}", "$ (#{numbers})日前の「(#{files})」ファイルを(#{display}) {24}", "% git show '@{#{$1} days ago}':#{$2} {24}", "$ 昨日の「(#{files})」ファイルを(#{display}) {24}", "% git show @{yesterday}:#{$1} {24}", "$ (#{numbers})分前(から|以降に)(#{modified})ファイルをリストする {26}", "% git diff --name-only '@{#{$1} minutes ago}' {26}", "$ (#{numbers})時間前(から|以降に)(#{modified})ファイルをリストする {26}", "% git diff --name-only '@{#{$1} hours ago}' {26}", "$ (#{numbers})日前(から|以降に)(#{modified})ファイルをリストする {26}", "% git diff --name-only '@{#{$1} days ago}' {26}", "$ (#{numbers})日前からの変更を(#{display}) {26}", "% git log --stat --since=\"#{$1} days ago\" {26}", "$ 編集中のファイルをリストする {27}", "% git ls-files -m {27}", "$ (#{params})という文字列がはじめて出現した(バージョン|コミット)の情報を(#{display}) {28}", "% git log -1 `git rev-list --all | xargs git grep '#{$1}' | tail -1 | ruby -e \"STDIN.each {|line| puts line[0..39] }\"` {28}", "$ (#{params})という文字列がはじめて出現した(バージョン|コミット)に一時的に戻す {28}", "% git checkout `git rev-list --all | xargs git grep '#{$1}' | tail -1 | ruby -e \"STDIN.each {|line| puts line[0..39] }\"` {28}", "$ (#{numbers})個前のバージョンに一時的に戻す {29}", "% git checkout HEAD~#{$1} {29}", "$ (#{numbers})日前の状態に一時的に戻す {29}", "% git checkout \"@{#{$1} days ago}\" {29}", "$ (#{numbers})時間前の状態に一時的に戻す {29}", "% git checkout \"@{#{$1} hours ago}\" {29}", "$ (#{numbers})分前の状態に一時的に戻す {29}", "% git checkout \"@{#{$1} mins ago}\" {29}", "$ 「(#{params})」という文字列を含むファイルを捜す {30}", "% git grep '#{$1}' {30}", "$ 「(#{params})」という文字列を含むファイルを全履歴から捜す {30}", "% git rev-list --all | xargs git grep '#{$1}' {30}", "$ ブランチ名を(#{params})に変える {31}", "% git branch -m #{$1} {31}", "$ ファイルの(編集|修正)のランキングを(#{display}) {34}", "$ (よく|頻繁に)(編集|修正)(されてる|されている)ファイルを(#{display}) {34}", "$ ファイルの編集頻度を(#{display}) {34}", "$ ファイルを編集頻度順にソート {34}", "% git log --name-only --pretty=\"format:\" | grep -ve \"^$\" | sort | uniq -c | sort -r {34}", "$ (1つ|ひとつ)前のコミットで(削除した|消した)(#{files})を(復元する|元に戻す) {36}", "% git checkout $(git rev-list -n 1 HEAD -- #{$2})^ -- #{$2} {36}", "$ Show the edit history of (#{files}) from (#{numbers}) minites ago {8}", "$ ファイル「(#{files})」の(#{numbers})分前からの(#{change})履歴を(#{display}) {37}", " % git log --since \"#{$2} minutes ago\" #{$1} {37}", " $ (#{numbers})分前からのファイル「(#{files})」の(#{change})履歴を(#{display}) {37}", " % git log --since \"#{$1} minutes ago\" #{$2} {37}", " $ ファイル「(#{files})」の(#{numbers})分前からの(#{change})を(#{display}) {37}", " % git diff HEAD \"@{#{$2} minutes ago}\" #{$1} {37}", " $ (#{numbers})分前からのファイル「(#{files})」の(#{change})を(#{display}) {37}", " % git diff HEAD \"@{#{$1} minutes ago}\" #{$2} {37}", " $ ファイル「(#{files})」の(#{numbers})時間前からの(#{change})履歴を(#{display}) {37}", " % git log --since \"#{$2} hours ago\" #{$1} {37}", " $ Show the edit history of (#{files}) from (#{numbers}) hours ago {8}", " $ (#{numbers})時間前からのファイル「(#{files})」の(#{change})履歴を(#{display}) {37}", " % git log --since \"#{$1} hours ago\" #{$2} {37}", " $ ファイル「(#{files})」の(#{numbers})時間前からの(#{change})を(#{display}) {37}", " % git diff HEAD \"@{#{$2} hours ago}\" #{$1} {37}", " $ (#{numbers})時間前からのファイル「(#{files})」の(#{change})を(#{display}) {37}", " % git diff HEAD \"@{#{$1} hours ago}\" #{$2} {37}", "$ Show the edit history of (#{files}) from (#{numbers}) days ago {37}", " $ ファイル「(#{files})」の(#{numbers})日前からの(#{change})履歴を(#{display}) {37}", " % git log --since \"#{$2} days ago\" #{$1} {37}", " $ (#{numbers})日前からのファイル「(#{files})」の(#{change})履歴を(#{display}) {37}", " % git log --since \"#{$1} days ago\" #{$2} {37}", " $ ファイル「(#{files})」の(#{numbers})日前からの(#{change})を(#{display}) {37}", " % git diff HEAD \"@{#{$2} days ago}\" #{$1} {37}", " $ (#{numbers})日前からのファイル「(#{files})」の(#{change})を(#{display}) {37}", " % git diff HEAD \"@{#{$1} days ago}\" #{$2} {37}", "$ 現在の状況を(#{display}) {38}", "% git status {38}", "$ 「(#{files})」というファイルを「(#{params})」という名前に(変更|移動|改名|リネーム)する {39}", "% git mv #{$1} #{$2} {39}", "$ ファイル「(#{files})」を(#{del}) {40}", "% git rm #{$1} {40}", "$ ブランチを(表示|リスト)する {41}", "% git branch {41}", "$ 「(#{params})」というブランチを作成する {41}", "% git branch #{$1} {41}", "$ 「(#{params})」というブランチを(#{del}) {41}", "% git branch -d #{$1} {41}", " $ (仕事|変更)を一時的に退避 {43}", " % git stash save {43}", " $ ファイル「(#{files})」の編集履歴を完全に(#{del})がワーキングツリーは残す {44}", " % git filter-branch -f --index-filter 'git rm --cached --ignore-unmatch #{$1}' HEAD {44}", " $ ファイル「(#{files})」の編集履歴を完全に(#{del}) {44}", " % git filter-branch -f --index-filter 'git rm --ignore-unmatch #{$1}' HEAD {44}", "$ 編集履歴をGitHubに反映させる {44}", "% git push origin --force --all {44}", "$ 直前のコミットのコメントを修正する {45}", "% git commit --amend {45}", "$ ファイルを新しい順に(リスト|表示)する {46}", "% git ls-files | xargs ls -1 -t {46}", "$ (#{files})に(#{params})という名前が(出現した|書かれた)のはいつ? {47}", "% git blame #{$1} | grep #{$2} {47}", "$ (#{params})という名前が(#{files})に(出現した|書かれた)のはいつ? {47}", "% git blame #{$2} | grep #{$1} {47}", "$ これまで追加/削除された行数を表示する {48}", "% git log --numstat --pretty=\"%H\" | awk 'NF==3 {plus+=$1; minus+=$2} END {printf(\"+%d, -%d\\\\n\", plus, minus)}' {48}", "$ (#{files})に(#{params})という名前が(出現した|書かれた)のはいつ? {50}", "% git blame #{$1} | grep #{$2} {50}", "$ ツリー状にログを表示する {51}", "% git log --graph --all --format=\"%x09%an%x09%h %d %s\" {51}", "$ 最初に「(#{params})」という文字列を含むコミットをした時から現在までに追加されたファイルはどれとどれ? {52}", "% git log --oneline --date=iso-strict --format='%cd %s' | grep #{$1} | tail -1 | awk '{print $1}' | xargs githelp-changed {52}" ], "pages": [ "このサイトについて", "やりたいことの例", "Git情報源", "意義", "関連文献", "使い方", "疑問", "ファイルリスト", "古いファイルとの比較", "ファイルを大きい順に表示", "Reset関連", "操作履歴", "branches", "タグ", "ブランチの表示", "アイデア", "GitHelp論文構成案", "Gitのマニュアルページ", "編集中のファイル", "レポジトリ", "コミットID", "コミット", "コミットをまとめる", "バージョン指定", "古いファイル表示", "Glossary", "最近編集したファイルのリストを表示する", "編集中のファイルをリストする", "文字列がはじめて出現したバージョンを捜す", "古いバージョンに一時的に戻す", "変数や単語が出現しているファイルを捜す", "ブランチ名", "ユーザ情報", "引数パラメタ", "ファイルの編集回数のランキング", "リモートブランチを消す", "ファイル復元", "最近の変更を知る", "現在の状況", "ファイル名変更", "ファイル削除", "ブランチ", "テンプレート", "一時的に仕事を退避", "特定のファイルの履歴を消す", "コメント修正", "新しい順にファイルを表示", "文字列の出現を調べる", "追加/削除された行数", "数字パラメタ", "文字列の出現判定", "ツリー状にログを表示する", "ファイル追加", "args", "増井俊之" ] }; module.exports = data;
import firebase from 'firebase'; require('@firebase/firestore') var firebaseConfig = { apiKey: "AIzaSyCBWgni3eeIzD0GtY57lS669q9Iid9EGJ8", authDomain: "book-santa-568cc.firebaseapp.com", databaseURL: "https://book-santa-568cc.firebaseio.com", projectId: "book-santa-568cc", storageBucket: "book-santa-568cc.appspot.com", messagingSenderId: "1058138844344", appId: "1:1058138844344:web:45f7c554518c3de7e9d84d" }; // Initialize Firebase firebase.initializeApp(firebaseConfig); export default firebase.firestore();
module.exports = function (numUno,numDos){ return numUno + numDos }
var webServer = "http://talkypool.cafe24.com/work/enriching"; var imgServer = ""; var wasServer = "http://talkypool.cafe24.com/work/enriching"; var loginType = ""; var pageType = ""; var isIndex = false; var ie = getIE(); var isFlash = swfobject.hasFlashPlayerVersion("1"); var isMobile = jQuery.browser.mobile; if(isMobile){ window.location = "/mobile/"; } //others var profileGetURL = webServer + "/profile_image/"; var profileSaveURL = webServer + "/proc/save_profile.jsp"; //proc var loginCheckURL = wasServer + "/proc/login_check.jsp"; var loginCheckURL2 = webServer + "/proc/login_check.jsp"; var logoutURL = webServer + "/proc/login_check.jsp"; var joinSubmitURL = webServer + "/proc/join_proc.jsp"; var joinEventSubmitURL = webServer + "/proc/joinEvent_proc.jsp"; // var onlineBoardURL = webServer + "/proc/board_list_proc.jsp"; var onlineSubmitURL = webServer + "/proc/board_insert_proc.jsp"; var onlinelikeSubmitURL = webServer + "/proc/board_like_proc.jsp"; var countURL = webServer + "/proc/user_count_proc.jsp"; var onlineDeleteURL = webServer + "/proc/board_delete_proc.jsp"; //page var joinURL = webServer + "/index2.jsp?pageType=join"; var joinEventURL = webServer + "/index2.jsp?pageType=event"; var lobbyURL = webServer + "/lobby.jsp"; var fblikeURL = webServer + "/facebook_like.jsp"; //sns var twLoginURL = webServer + "/twitter/tw_login.jsp"; // var eventFormURL = webServer + "/event_form.jsp"; var joinFormURL = webServer + "/join_form.jsp"; var loginFormURL = webServer + "/login_form.jsp"; $(document).ready(function(){ $('a').click(function(){ if($(this).attr('href') == "#"){ return false; } }); $('.gnb_menu').mouseenter(function(){ $(this).find('.gnb_gif').show(); }); $('.gnb_menu').mouseleave(function(){ $(this).find('.gnb_gif').hide(); }); //$('.arr_btn').append('<span class="arr" style="width:0px;height:31px;overflow:hidden;display:inline-block" ><img src="'+imgServer+'/images/common/login/btn_arr.png" alt="" /></span>'); $('.arr_btn').mouseenter(function(){ $(this).find('span').stop().animate({width:20},{duration:300, easing:"easeOutQuad"}); }); $('.arr_btn').mouseleave(function(){ $(this).find('span').stop().animate({width:0},{duration:300, easing:"easeOutQuad"}); }); //initStep1(); //alert(ie); loginComplete = function(data){ if(data.result == "logout"){ window.location.reload(); }else if(data.result == "success"){ window.location.reload(); }else if(data.result == "wrong"){ alert('아이디 또는 비밀번호가 맞지 않습니다.'); } } joinProcess = function(data){ if(data.result == "goEvent"){ eventConfirm(); }else if(data.result == "goRegist"){ registConfirm(); }else if(data.result == "notLogin"){ notLogin(); } } joinComplete = function(data){ if(data.result == "success"){ if(data.type == "default"){ alert("주주되기가 완료되었습니다."); $(".join_step1_section").hide(); thisMovie('main_flash').onSignupFinish(); //window.location = lobbyURL+"?loginCheck=1"; }else{ $('.join_section').hide(); $('.event_section').show(); //$(".event_section_container").load( "/ajax_event_section.jsp .event_section"); } }else if(data.result == "already"){ alert("이미 가입된 아이디 입니다."); }else if(data.result == "failed"){ alert("가입하기가 실패했습니다."); } } joinEventComplete = function(data){ //console.log(data); if(data.result == "success"){ alert("이벤트 응모가 완료되었습니다."); $(".event_section").hide(); $(".join_step1_section").hide(); $(".join_section").hide(); parent.thisMovie('main_flash').onSignupFinish(); //window.location = lobbyURL+"?loginCheck=1"; }else if(data.result == "already"){ alert("이미 응모된 전화번호 입니다."); } } visual = $('#visual'); contents = $('#contents'); container = $('#container'); visualHei = visual.height(); var bodyPosition = $('body').css('position'); $(window).scroll(function(){ //console.log($('body').css('position')); if($('body').css('position') != 'relative'){ return; } scroll(); resize(); }); scroll(); $(window).resize(function(){ resize(); }); resize(); $('#gotop').hide(); }); var visualHei; var visual; var contents; var container; function scroll(){ var top = $(window).scrollTop()/2; //console.log(top); var hei = visualHei-top; hei = hei < 350 ? 350 : visualHei-top; //console.log( $(document).height()+top ); //visual.height(hei); visual.css({'height':hei}); initGoTop(); } function resize(){ var hei = $(window).height(); var h = visual.height() + container.height(); contents.css({'min-height':h+117, 'height':hei-117}); } function initGoTop(){ if($(window).scrollTop() > 100) { $('#gotop').fadeIn(); }else{ $('#gotop').fadeOut(); } } function eventConfirm(){ if (confirm("주주가입 이벤트에 응모하지 않으셨습니다. 응모하시겠습니까?") == true){ window.location = joinURL; }else{ if(isLogin){ }else{ if(isIndex){ window.location = lobbyURL; }else{ window.location.reload(); } } //window.location.reload();//온라인미팅에서 새로고침되면 안됨 } } function registConfirm(){ if (confirm("가입되어 있지 않은 계정입니다. 주주가입을 하시겠습니까?") == true){ window.location = joinURL; }else{ return; } } function notLogin(){ if (confirm("로그인 되어있지 않거나 주주가입이 필요합니다. 주주가입을 하시겠습니까?") == true){ window.location = joinURL; }else{ return; } } function loadUserCount(){ $.ajax({ type: "POST", url: countURL, data: { } , dataType: 'jsonp' }); userCountComplete = function(data){ if(data.result == "success"){ userTotalCount = parseInt(data.obj.userTotalCount); var n1 = parseInt(data.obj.firstType)/userTotalCount*100; var n2 = parseInt(data.obj.secondType)/userTotalCount*100; var n3 = parseInt(data.obj.thirdType)/userTotalCount*100; var n4 = parseInt(data.obj.fourthType)/userTotalCount*100; var per1 = $('.percent').eq(0); var per2 = $('.percent').eq(1); var per3 = $('.percent').eq(2); var per4 = $('.percent').eq(3); $('.bar').eq(0).delay(200).animate({width:n1+"%"},{duration:1000, easing:"easeInOutExpo", step:function(now,fx){ per1.html( Math.floor(now)+"%" ); }}); $('.bar').eq(1).delay(400).animate({width:n2+"%"},{duration:1000, easing:"easeInOutExpo", step:function(now,fx){ per2.html( Math.floor(now)+"%" ); }}); $('.bar').eq(2).delay(600).animate({width:n3+"%"},{duration:1000, easing:"easeInOutExpo", step:function(now,fx){ per3.html( Math.floor(now)+"%" ); }}); $('.bar').eq(3).delay(800).animate({width:n4+"%"},{duration:1000, easing:"easeInOutExpo", step:function(now,fx){ per4.html( Math.floor(now)+"%" ); }}); setCounter(); } } } function setCounter(){ var total = userTotalCount; total = "123239"; total = Math.floor(Math.random()*999999).toString(); //console.log(total); if(total.length < 6){ var s = ""; for(var i = 0;i < 6 - total.length;i++){ s += "0"; } total = s + total; } for(var i = 0;i < total.length;i++){ var str = total.substr(i,1); var n = parseInt(str); /* console.log(str); */ $('.count').eq(i).delay(i*200).animate({'background-position-y':-450-(n*45)}, {duration:1500, easing:"easeInOutExpo"}); } } onLoopStart = function(){ } function moveTop(){ $('body,html').animate({'scrollTop':0},{duration:600, easing:"easeOutExpo"}); } // ------------------------------------------------------ 로그인 / 가입하기 ------------------------------------------------------ function join(){ if(isIndex){ goLogin(); }else{ window.location = joinURL; } } function mypage(){ window.location = lobbyURL; } function findID(){ //popup = window.open(url,'TwitterLogin','width=700, height=550, toolbar=0, directories=0, status=0, menubar=0, scrollbars=0, resizable=0'); window.open(wasServer + '/findid.jsp', '', 'width=360, height=440, resizable=0, scrollbars=no, status=0, titlebar=0, toolbar=0, left=300, top=200' ); } function findPW(){ window.open(wasServer + '/findpw.jsp', '', 'width=360, height=440, resizable=0, scrollbars=no, status=0, titlebar=0, toolbar=0, left=300, top=200' ); } function closeFind(){ $('.findid_step1').hide(); $('.findpw_step1').hide(); } var isLoginOn = false; function login(){ if(isLoginOn){ closeLoginPopup(); }else{ openLoginPopup(); } } function openLoginPopup(){ $('.login_container').show(); $('.login_section').stop().animate({'margin-top':'0'}, {duration:1000, easing:"easeInOutExpo"}); isLoginOn = true; } function closeLoginPopup(){ $('.login_section').stop().animate({'margin-top':'-260px'}, {duration:1000, easing:"easeInOutExpo"}); setTimeout(function(){ $('.login_container').hide(); }, 1000); isLoginOn = false; } function logout(){ $.ajax({ type: "POST", url: logoutURL, data: { type: "logout" } , // success: twitterLoginComplete2, dataType: 'jsonp' }); } function goLogin(){ $('.main_popup').animate({'right':-300}, {duration:1000, easing:"easeInOutExpo"}); $('.main_popup a').attr('tabindex', -1); try{ thisMovie('main_flash').goLogin(); }catch(e){ } } // ------------------------------------------------------ Default ------------------------------------------------------ function loginDefault(type){ loginType = type; var image = imgServer + "/images/join/face50x50.jpg"; if(type == "join"){ setJoinIcon("", "default", ""); setProfileImage(image); }else{ if(!checkLoginId( $('#user_id') )){ return; } if(!checkLoginPassword( $('#user_pw') )){ return; } getLoginCheck("default", $('#user_id').val(), $('#user_pw').val(), image, ""); } } // ------------------------------------------------------ index / Lobby ------------------------------------------------------ var indexArrNum = 0; function initIndexContents(){ $('.con2_list .more').focusin(function(e){ indexArrNum = $('.con2_list .more').index(this); $('.con2_list').css({left:-indexArrNum*270}); return false; }); } function indexContentsLeft(){ $('.con2_arrow .left a').css({'cursor':'default'}); indexArrNum = indexArrNum <= 0 ? 0 : indexArrNum-1; //console.log(indexArrNum); $('.con2_list').stop().animate({left:-indexArrNum*270}, {duration:1000, easing:"easeInOutExpo"}); setIndexContentsArrow(indexArrNum); } function indexContentsRight(){ indexArrNum = indexArrNum >= 2 ? 2 : indexArrNum+1; //console.log(indexArrNum); $('.con2_list').stop().animate({left:-indexArrNum*270}, {duration:1000, easing:"easeInOutExpo"}); setIndexContentsArrow(indexArrNum); } function setIndexContentsArrow(index){ if(index == 0){ $('.con2_arrow .left a').css({'cursor':'default'}); $('.con2_arrow .right a').css({'cursor':'auto'}); }else if(index == 1){ $('.con2_arrow .left a').css({'cursor':'auto'}); $('.con2_arrow .right a').css({'cursor':'auto'}); }else if(index == 2){ $('.con2_arrow .left a').css({'cursor':'auto'}); $('.con2_arrow .right a').css({'cursor':'default'}); } } //------------------------------------------------------------------------------------------------------ $(function () { $(".play_btn").hide(); setPlayBtn(1); }); var onClickPlayBtn = function(){ thisMovie('main_flash').onClickPlayBtn(); } var showPlayBtn = function () { $(".play_btn").fadeIn(); } var hidePlayBtn = function () { $(".play_btn").fadeOut(); } var setPlayBtn = function (attr) { if(attr == 0 ){ $(".play_btn a img").eq(0).hide(); $(".play_btn a img").eq(1).show(); }else{ $(".play_btn a img").eq(0).show(); $(".play_btn a img").eq(1).hide(); } } function getUserData(){ return User.type+","+User.image; }
import Cycle from '@cycle/core' import { makeDOMDriver, hJSX } from '@cycle/dom' function main({ DOM }) { const decrement$ = DOM.select('.decrement').events('click').map(_ => -1) const increment$ = DOM.select('.increment').events('click').map(_ => +1) const count$ = increment$.merge(decrement$) .scan((x, y) => x + y) .startWith(0) return { DOM: count$.map(count => <div> <input type="button" className="decrement" value=" - "/> <input type="button" className="increment" value=" + "/> <div> Clicked {count} times~ </div> </div> ) } } Cycle.run(main, { DOM: makeDOMDriver('#container'), })
// The Vue build version to load with the `import` command // (runtime-only or standalone) has been set in webpack.base.conf with an alias. import Vue from 'vue' import App from './App' import router from './router' import ViewUI from 'view-design'; import 'view-design/dist/styles/iview.css'; Vue.use(ViewUI); //引入g2 import G2 from '@antv/g2' //引入 data-set模块 import DataSet from '@antv/data-set'; Vue.prototype.DataSet=DataSet; Vue.use(G2) import Vant from 'vant'; import 'vant/lib/index.css'; Vue.use(Vant) import './assets/flexible.js' import axios from 'axios';//引入axios import Qs from 'qs';//引入Qs import $ from 'jquery' /* * 配置axios*/ var token; Vue.prototype.token=token; Vue.prototype.$axios=axios.create(); Vue.prototype.axios = axios.create({ baseURL:' http://101.37.65.219',//http://116.62.67.239:1027 // http://192.168.0.103:9001 timeout: 30000, // withCredentials: true, headers: {'Content-Type': 'application/x-www-form-urlencoded',"X-Requested-With": "XMLHttpRequest","token":token}, transformRequest: [data => { data = Qs.stringify(data); return data; }] }); Vue.config.productionTip = false; //动态改变页面标题 router.beforeEach((to, from, next) => { /* 路由发生变化修改页面title */ if (to.meta.title) { document.title = to.meta.title } next() }) /* eslint-disable no-new */ new Vue({ el: '#app', router, components: { App }, template: '<App/>' }) //上传文件 Vue.prototype.$http = axios.create({ baseURL:'http://101.37.65.219',//http://118.31.247.144:1027 // http://192.168.0.103:9001 // timeout: 20000 }); //添加请求拦截器 axios.interceptors.request.use(function(config){ store.state.isShow=true; //在请求发出之前进行一些操作 return config }) //定义一个响应拦截器 axios.interceptors.response.use(function(config){ store.state.isShow=false;//在这里对返回的数据进行处理 return config })
// Variable Names and Normalisation //to make consistent to a standard var resultLinkHref = '#';
import React, { useState } from 'react'; import { Panel, Slider, Divider, Toggle, Progress, InputNumber, Grid, Row, Col } from 'rsuite'; import { Linechart } from '../linechart/linechart'; import { useInterval } from './useInterval' import axios from 'axios' import './actuator.css'; export const Actuator = ({ name }) => { const { Line } = Progress const url = 'http://localhost:5000/actuator' const [position, setPosition] = useState(0) const [speed, setSpeed] = useState(-1) const [timestamp, setTimestamp] = useState(0) const [history, setHistory] = useState([]) const [y, setY] = useState([]) const [x, setX] = useState([]) const post = (action, value) => axios.post(`${url}/${action}/${value * 2.55}`) useInterval(() => { let pin = 0 axios.get(`${url}/${pin}/${timestamp}`).then(response => { let data = response.data let newPosition = (data[data.length - 1].value / 2.55) setSpeed(speed < 0 ? 0 : Math.abs((position - newPosition) / 0.5)) setPosition(newPosition) setTimestamp(data[data.length - 1].timestamp) let newY = y data.map((e, i) => newY.push({ position: parseInt(e.value / 2.55), speed: parseInt(speed), timestamp: e.timestamp })) setY(newY.slice(-2000)) let newX = x data.map(e => newX.push(e.timestamp)) setX(newX) let sliced = newX.slice(-2000) let newHistory = [] if (sliced.length === 2000) { for (let i = 1; i <= 2000; i += 200) { newHistory.push(`${new Date(sliced[i]).toISOString().slice(14, 19)}`) } setHistory(newHistory) } }) }, 500); return ( <Panel header={name} bordered> <div className='right'> <Toggle size="lg" onChange={checked => post('enabled', checked)}/> </div> <div className='yellow'> <span>Posicao</span> <Slider progress defaultValue={0} onChange={value => post('position', value)} /> <br /> <span>Posicao atual: {parseInt(position) * 2}mm ( {position.toFixed(2)}% )</span> <Line percent={position} showInfo={false} strokeColor="#dba709" /> <Divider /> </div> <div className='blue'> <span>Velocidade maxima</span> <Slider progress defaultValue={0} onChange={value => post('speed', value)} /> <br/> <span>Velocidade atual: {parseInt(speed) * 2}mm/s ( {speed.toFixed(2)}% )</span> <Line percent={speed} showInfo={false}/> <Divider /> </div> <Grid fluid> <Row> <Col sm={8} xs={12}> <span>Aceleracao (ms)</span> <InputNumber step={100} min={0} onChange={value => post('acceleration', value)} /> </Col> <Col sm={8} xs={12}> <span>Desaceleracao (ms)</span> <InputNumber step={100} min={0} onChange={value => post('slowdown', value)} /> </Col> </Row> </Grid> <Divider /> <Linechart y={[ { name: "Posicao", data: y.map(e => e.position) }, { name: "Velocidade", data: y.map(e => e.speed) } ]}></Linechart> <div className="xAxis"> {history.map((e, i) => e !== 'NaN.NaN' && <span key={i}>{e}</span> )} </div> </Panel> ) }
import React from 'react'; import './App.css'; import Auth from './components/Auth'; import { BrowserRouter as Router, Route } from "react-router-dom"; import HomeUsers from './containers/HomeUsers'; function App() { return ( <Router> <Route exact path="/" component={Auth}/> <Route path="/HomeUsers" component={HomeUsers}/> </Router> ); } export default App;
// This file starts our server, we defer to localhost:3000 // if a process port and url are not defined var app = require('./server/server.js'); // var db = require('./server/dbConfig.js'); //only need for database update var port = process.env.PORT || 3000; var url = process.env.URL || 'localhost'; app.listen(port, url); console.log('Listening on', url, ':', port); // var http = require('http'); // var express = require('express'); // var path = require('path'); // var bodyParser = require('body-parser'); // var app = express(); // require('./routes.js')(app); // app.set('port', process.env.PORT || 3000); // //this tells Express to parse the incoming body data. This will be called before other // //route handlers, to req.body can be passed directly to driver code as js object. // app.use(bodyParser()); // //this tells press to use express.static middleware to serve files in response to incoming requests // //maps local subfolder 'public' (which we don't have yet) to the base route '/' // //'path' module creates a platform-independent subfolder string. // //anything in /public can now be accessed by name. // app.use(express.static(path.join(__dirname, 'public')));
import { useRouter } from "next/dist/client/router"; import React from "react"; import { connect } from "react-redux"; import { createStructuredSelector } from "reselect"; import { selectProducts } from "../../redux/user/user.selector"; import Head from "next/head"; import Image from "next/image"; import { addItem } from "../../redux/cart/cart.action"; const Product = ({ products, additem }) => { const route = useRouter(); const prodItem = products.filter( (p, i) => p.id == window.location.pathname.split("/")[2] )[0]; console.log(prodItem); console.log(products); console.log(window.location.pathname.split("/")[2]); return ( <> <div> <div> <div> <h2 className="text-3xl mb-8 font-semibold">{prodItem.title}</h2> </div> <div className="flex flex-col md:flex-row h-[400px]"> <div className="md:w-1/2 relative"> {" "} <Image src={prodItem.image} height="380" width="380" />{" "} </div> <div className="md:w-1/2 flex flex-col items-start space-y-6 justify-center text-left"> <h3 className="text-xl font-semibold">{prodItem.title}</h3> <p className="text-sm"> Category: {prodItem.category}</p> <p className="text-sm">{prodItem.description}</p> <p className="text-xl font-semibold">${prodItem.price}</p> <button className="px-3 rounded-lg text-white py-2 bg-gray-700 hover:bg-gray-900" onClick={() => { additem(prodItem) }} >Add to cart</button> </div> </div> </div> </div> </> ); }; const mapDispatchToProps = (dispatch) => ({ additem: () => dispatch(addItem()), }); const mapStateToProps = createStructuredSelector({ products: selectProducts, }); export default connect(mapStateToProps, mapDispatchToProps)(Product);
//MEDIUM QUESTIONS:- // QUESTION NO.1 const str="word searches are super fun"; const start='s'; var words=str.split(' '); function specialReverse(str) { for(i=0;i<words.length;i++) { if(words[i][0] === start) { words[i]= words[i].split('').reverse().join(''); } } return(words.join(" ")); } console.log(specialReverse(str)); //QUESTION NO.2 var array=["@","@","@","@"]; var test=0; function testJackpot(array){ check=array.map(item => item === array[0]); for(x of check) { if(x!=true) test=1; } if(test==0) return(true); else return(false); } console.log(testJackpot(array)); //QUESTION NO.3 let chars = ['abc', 'abc', 'abc', 'ABC', 'B']; function removeDups(chars) { let uniqueChars = chars.filter((c, index) => { return chars.indexOf(c) === index; }); return uniqueChars; } console.log(removeDups(chars));
import React from "react"; import {Link} from "gatsby"; export function Footer() { return ( <footer class="footer"> <div class="content has-text-centered"> <p> <strong>Offset me!</strong> by{" "} <a href="http://www.suchanek.io">Jakub Suchánek</a> and{" "} <a href="https://www.lawrencejb.com">Lawrence Berry</a>. </p> </div> </footer> ); }
'use strict'; const config = require('config'); const logger = require('logger'); const World = require('lib/world'); const world = new World(config); require('lib/process-events').register(world); require('lib/server').start(world, config, function startCallback(error) { if(error) { return logger.error('World Server Startup Error', error); } });
$(document).ready(function () { // Hopefully so that the code is easier to follow we define our selectors // now var langnames = "div.language"; var langchooser = "#lang-chooser"; // This function handles everything to do with changing the language // including: // - Updating the dropdown selection // - If the facility is available, saving the user preference var changeLanguage = function(short) { // Unhide the relevant language $(langnames + "#" + short).show(); // Update the dropdown $(langchooser).val(short); // If local storage is available, save the language so the change // is persistent both accross page loads and entire sessions if (typeof(Storage) !== undefined) { localStorage.setItem("lang", short); }; // Get the current path var l = window.location; var path = l.pathname; // Replace the lang part of the path // Handle the index page if (path == "/") { path = '/' + short + "/index.html"; } else { // Otherwise we are assuming that we are on a 'normal' page path = '/' + short + path.substr(3); } // Build the new url var url = l.protocol + '//' + l.host + path; // Open it window.open(url, "_self"); }; // In case there already is a saved preference, load that language // otherwise load the default if (localStorage.lang) { var new_lang = localStorage.lang; } else { var new_lang = "en"; }; // Get the current language from the url var l = window.location; var current_lang = l.pathname.substr(1,2); // If the current language is different from the requested one chnage the // page if (current_lang !== new_lang) { changeLanguage(new_lang); } else { // If not just ensure that the dropdown is correct $(langchooser).val(current_lang); } // Finally this code is only run when the user makes a choice using the // dropdown in the footer $(langchooser).change(function() { var new_lang = $(langchooser).val(); changeLanguage(new_lang); }); });
import Vue from 'vue' import VueRouter from 'vue-router' import Home from '../views/Home.vue' import Admin from '../views/Admin.vue' import NoticeAdmin from '../views/NoticeAdmin.vue' import FeedBackAdmin from '../views/FeedBackAdmin.vue' import FengcaiAdmin from '../views/FengcaiAdmin.vue' import UserAdmin from '../views/UserAdmin.vue' import ClassAdmin from '../views/ClassAdmin.vue' import Tongji from '../views/Tongji.vue' import Classchoose from '../views/Classchoose.vue' import Classcount from '../views/Classcount.vue' import Navbar from '../components/Navbar.vue' import Datil from '../views/Datil.vue' Vue.use(VueRouter) const routes = [ { path: '/', name: 'Home', components: { head:Navbar, main:Home } }, { path: '/admin', name: 'Admin', components: { head:Navbar, main:Admin } }, { path: '/noticeadmin', name: 'NoticeAdmin', components: { head:Navbar, main:NoticeAdmin } }, { path: '/feedbackadmin', name: 'FeedBackAdmin', components: { head:Navbar, main:FeedBackAdmin } }, { path: '/classadmin', name: 'ClassAdmin', components: { head:Navbar, main:ClassAdmin } }, { path: '/fengcaiadmin', name: 'FengcaiAdmin', components: { head:Navbar, main:FengcaiAdmin } }, { path: '/useradmin', name: 'UserAdmin', components: { head:Navbar, main:UserAdmin } }, { path: '/tongji', name: 'Tongji', components: { head:Navbar, main:Tongji } }, { path: '/datil', name: 'Datil', components: { head:Navbar, main:Datil } }, { path: '/choose', name: 'Choose', components: { head:Navbar, main:Classchoose } }, { path: '/classcount', name: 'Classcount', components: { head:Navbar, main:Classcount } } ] const router = new VueRouter({ mode: 'history', base: process.env.BASE_URL, routes }) export default router
import { put, takeLatest } from 'redux-saga/effects'; import axios from 'axios'; import {useSelector, useDispatch} from 'react-redux'; function* getPlaylistE(action) { try { const playlist= yield axios.get('/playlist/energetic'); console.log('got a response on playlist:', playlist.data); yield put({ type: 'GET_PLAYLIST', payload: playlist.data}); } catch { console.log('error on playlist'); } } function* getPlaylistSad (action){ try{ //const playlistId = action.payload; const playlist= yield axios.get('/playlist/sad'); console.log('got a response on playlist:', playlist.data); yield put({ type: 'GET_PLAYLIST', payload: playlist.data }); } catch (err){ console.log('error on playlist', err); } } function* getPlaylistChill(action) { try { const playlist= yield axios.get('/playlist/chill'); console.log('got a response on playlist:', playlist.data); yield put({ type: 'GET_PLAYLIST', payload: playlist.data }); } catch (err){ console.log('error on playlist', err); } } function* playlistSaga() { yield takeLatest('FETCH_SAD_PLAYLIST', getPlaylistSad); yield takeLatest('FETCH_CHILL_PLAYLIST', getPlaylistChill); yield takeLatest('FETCH_ENERGETIC_PLAYLIST', getPlaylistE) } export default playlistSaga;
'use strict'; const os = require('os'); const path = require('path'); const electron = require('electron'); const app = electron.app; const BrowserWindow = electron.BrowserWindow; const shell = electron.shell; const appName = app.getName(); function sendAction(action) { const win = BrowserWindow.getAllWindows()[0]; if (process.platform === 'darwin') { win.restore(); } win.webContents.send(action); } const viewSubmenu = [{ label: 'Reset Text Size', accelerator: 'CmdOrCtrl+0', click() { sendAction('zoom-reset'); } }, { label: 'Increase Text Size', accelerator: 'CmdOrCtrl+Plus', click() { sendAction('zoom-in'); } }, { label: 'Decrease Text Size', accelerator: 'CmdOrCtrl+-', click() { sendAction('zoom-out'); } }]; const helpSubmenu = [{ label: `${appName} Website`, click() { shell.openExternal('http://beatplus.github.io/Protonmail/'); } }, { label: `${appName} Source Code`, click() { shell.openExternal('https://github.com/BeatPlus/Protonmail') } }, { label: 'Report an issue', click() { const body = ` <!-- Please succinctly describe your issue and steps to reproduce it. --> - ${app.getName()} ${app.getVersion()} Electron ${process.versions.electron} ${process.platform} ${process.arch} ${os.release()}`; shell.openExternal(`https://github.com/BeatPlus/Protonmail/issues/new?body=${encodeURIComponent(body)}`); } }]; if (process.platform !== 'darwin') { helpSubmenu.push({ type: 'separator' }, { label: `About ${appName}`, click() { electron.dialog.showMessageBox({ title: `About ${appName}`, message: `${appName} ${app.getVersion()}`, detail: 'Unofficial Protonmail desktop app, created by Matthew Core <BeatPlus> and Hayden Suarez-Davis <HaydenSD>.', icon: path.join(__dirname, 'static', process.platform === 'linux' ? 'Icon-linux-about.png' : 'IconTray.png'), buttons: ['Close'] }); } }); } const MenuTpl = [{ label: 'File', submenu: [{ label: 'Compose new email', accelerator: 'CmdOrCtrl+N', click() { sendAction('new-email'); } }, { label: 'Close composer', accelerator: 'Esc', click() { sendAction('close-composer'); } }, { label: 'Log Out', click() { sendAction('log-out'); } }, { type: 'separator' }, { label: 'Quit', accelerator: 'CmdOrCtrl+Q', click() { app.quit(); } }] }, { label: 'Edit', submenu: [{ label: 'Cut', accelerator: 'CmdOrCtrl+X', role: 'cut' }, { label: 'Copy', accelerator: 'CmdOrCtrl+C', role: 'copy' }, { label: 'Paste', accelerator: 'CmdOrCtrl+V', role: 'paste' }, { type: 'separator' }, { label: 'Toggle Dark Mode', accelerator: 'CmdOrCtrl+D', click() { sendAction('toggle-dark-mode'); } }, { label: 'Preferences', accelerator: 'CmdOrCtrl+,', click() { sendAction('show-preferences'); } }] }, { label: 'View', submenu: viewSubmenu }, { label: 'Help', role: 'help', submenu: helpSubmenu }]; module.exports = electron.Menu.buildFromTemplate(MenuTpl);
import { BEGIN_AJAX_CALL, AJAX_CALL_ERROR, AJAX_CALL_SUCCESS } from './types'; export function beginAjaxCall() { return { type: BEGIN_AJAX_CALL }; } export function ajaxCallError( payload ) { return { type: AJAX_CALL_ERROR, payload } } export function ajaxCallSuccess( payload ) { return { type: AJAX_CALL_SUCCESS, payload } }
const path = require('path') const config = require('./config/index') const ProgressBarPlugin = require('progress-bar-webpack-plugin') const webpack = require('webpack') const HtmlWebpackPlugin = require('html-webpack-plugin') const FriendlyErrors = require('friendly-errors-webpack-plugin') const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin const isDev = process.env.NODE_ENV === 'development' const isProd = process.env.NODE_ENV === 'production' const isTest = process.env.NODE_ENV === 'testing' const projectRoot = path.resolve(__dirname) const assetsPath = (_path) => { const assetsSubDirectory = isProd ? config.build.assetsSubDirectory : config.dev.assetsSubDirectory return path.posix.join(assetsSubDirectory, _path) } const conf = { entry: {}, resolveLoader: { modules: [ `${projectRoot}/node_modules` ] }, resolve: { extensions: ['.js', '.css'], modules: [ `${projectRoot}/node_modules` ] }, module: { rules: [{ enforce: 'pre', test: /\.js$/, loader: 'eslint-loader', options: { formatter: require('eslint-friendly-formatter') } }, { test: /\.js$/, loader: 'babel-loader' }] }, plugins: [ new webpack.DefinePlugin({ DEV: isDev, PROD: isProd, TEST: isTest }), new ProgressBarPlugin(), new FriendlyErrors() ] } if (isDev) { conf.mode = 'development' conf.devtool = '#source-map' conf.entry['rangeslider-js'] = `${projectRoot}/src/dev.js` conf.module.rules.push({ test: /\.css$/, use: ['style-loader', 'css-loader'] }) conf.plugins.push( new HtmlWebpackPlugin({ filename: 'index.html', template: `dev.html`, inject: true }) ) } else { conf.mode = 'production' conf.entry = { 'rangeslider-js.min': `${projectRoot}/src/index.js` } conf.devtool = false conf.output = { path: config.build.assetsRoot, filename: assetsPath('[name].js'), chunkFilename: assetsPath('[id].js'), library: 'rangesliderJs', libraryExport: 'default', libraryTarget: 'umd' } conf.plugins.push( new HtmlWebpackPlugin({ filename: 'index.html', template: 'prod.html', inject: false }), new webpack.LoaderOptionsPlugin({ minimize: true, debug: false }) ) if (config.build.bundleAnalyzerReport) { conf.plugins.push(new BundleAnalyzerPlugin()) } } module.exports = conf
const Discord = require('discord.js'); const Events = require('./events'); const log = require('./utils/logger'); const config = require('../config.json'); const bot = new Discord.Client(); const events = new Events(bot); log('info', 'Starting the bot...'); Promise.all([ events.load(), bot.login(config.token), ]).then((status) => { log('success', 'Bot connected.'); log('debug', status); }).catch((error) => { log('error', error.message); process.exit(1); });
(function() { // 这些变量和函数的说明,请参考 rdk/app/example/web/scripts/main.js 的注释 var imports = [ 'rd.controls.ProgressBar' ]; var extraModules = [ ]; var controllerDefination = ['$scope', 'ProgressbarFactory', main]; function main(scope, ProgressbarFactory ) { scope.progressbar = ProgressbarFactory.createInstance(); scope.start = function(){ scope.progressbar.start(); } scope.stop = function(){ scope.progressbar.complete(); } } var controllerName = 'DemoController'; //========================================================================== // 从这里开始的代码、注释请不要随意修改 //========================================================================== define(/*fix-from*/application.import(imports)/*fix-to*/, start); function start() { application.initImports(imports, arguments); rdk.$injectDependency(application.getComponents(extraModules, imports)); rdk.$ngModule.controller(controllerName, controllerDefination); } })();
import React from "react" import './style.css'; function Card(props) { return ( <div class="col-lg-4 col-md-6 col-sm-12"> <div class="card project-card"> <br/> <h5 className="card-title" style={{textDecorationLine: 'underline', textAlign: 'center', fontWeight: 'bold'}}>{props.title}</h5> <a href={props.live}><img className="img-fluid card-img-top project-img" src={props.image} alt={props.alt}/></a> <div className="card-body" style={{textAlign: 'center'}}> <p className="card-text">{props.description}</p> <br></br> <br></br> <h5 classname="technologies">Technologies:</h5> <br/> <p> {props.tech}</p> <a href = {props.repo}><button id="github" >Repository <i class="fab fa-github"></i></button> </a> </div> </div> </div> ) } export default Card;
import Car from './car.js' import NeuralNetwork from './neuralNetwork.js' export default class CarPopulation { constructor({ cvs, obstacles, carPopulation, carSpeed, mutationRate, mutationAmount, hiddenNeurons, inputAmount }) { this.cvs = cvs this.ctx = cvs.ctx this.carSpeed = carSpeed this.obstacles = obstacles this.mutationRate = mutationRate this.mutationAmount = mutationAmount this.hiddenNeurons = hiddenNeurons this.population = carPopulation this.bestCar this.cars = [] this.generation = 0 this.inputAngles = [] for (let i = 0; i <= 180; i += 180/(inputAmount-1)) this.inputAngles.push(i) this.createCarPopulation() } livingCars(callback) { for (let i = this.cars.length - 1; 0 <= i; i--) { if (!this.cars[i].isDead) { callback(this.cars[i]) } } } createCarPopulation() { this.generation++ this.cars = [] const coord = { x: this.cvs.canvas.width * 0.25, y: this.cvs.canvas.height * 0.2 } const height = (this.cvs.canvas.width * 0.01).toFixed() const width = (this.cvs.canvas.width * 0.02).toFixed() const shape = [this.inputAngles.length, this.hiddenNeurons, 2] for (let i = 0; i < this.population; i++) { let brain if (this.generation == 1) { brain = new NeuralNetwork(shape) } else if (i == 0 && this.generation != 1) { brain = this.bestCar.brain } else { brain = new NeuralNetwork(shape, this.bestCar.brain.weights, this.bestCar.brain.biases) } this.cars.push(new Car({ cvs: this.cvs, obstacles: this.obstacles, brain: brain, speed: this.carSpeed, x: coord.x, y: coord.y, height: height, width: width, mutationRate: this.mutationRate, inputAngles: this.inputAngles })) if (i != 0) { this.cars[i].brain.mutate(this.mutationRate, this.mutationAmount) } else { this.cars[i].color = "rgb(0, 0, 0)" } } } getBestCar() { let bestCarI = 0 let newBestCarFound = false if (!this.bestCar) { this.bestCar = this.cars[0] } for (let i = 0; i < this.cars.length; i++) { if (this.bestCar.score < this.cars[i].score) { this.bestCar.score = this.cars[i].score bestCarI = i newBestCarFound = true } } if (!newBestCarFound) { return this.bestCar } return this.cars[bestCarI] } newGeneration() { this.bestCar = this.getBestCar() this.createCarPopulation() } isDead() { for (let i = 0; i < this.cars.length; i++) { if (!this.cars[i].isDead) { return false } } return true } }
/* mongoDB Schema for rooms false = free room true = occupied room */ const mongoose = require ('mongoose'); var RoomSchema = mongoose.Schema({ name: { type: String, unique: true, required: true, }, availability: { type: Boolean, required: true, default: false } }); var Room = mongoose.model('Room', RoomSchema); var rooms = {}; rooms["noroom"] = false; /* Function to put the default diseases in the system */ function populateDatabase () { for (prop in rooms) { var room = Room({ name: prop, availability: rooms[prop] }); // simply save the default room in the system room.save().then((disease) => { // do nothing }, (err) => { // do nothing }); } } populateDatabase(); module.exports = {rooms, Room};
var RoboHydraHead = require("robohydra").heads.RoboHydraHead; var RoboHydraJsonHead = (path, getObject) => new RoboHydraHead({ path, handler: function(req, res) { res.headers['content-type'] = 'application/json; charset=utf-8'; var response = getObject(req, res); if( response !== undefined ) { res.send(JSON.stringify(response)); } else { res.statusCode = 404; res.send(); } } }); exports.RoboHydraJsonHead = RoboHydraJsonHead;
/** * Created by kristjan.kiolein on 17.03.2016. */ (function ($) { $(function () { }); })(jQuery);
import React from 'react'; import Table from '@material-ui/core/Table'; import TableBody from '@material-ui/core/TableBody'; import TableCell from '@material-ui/core/TableCell'; import TableContainer from '@material-ui/core/TableContainer'; import TableHead from '@material-ui/core/TableHead'; import TableRow from '@material-ui/core/TableRow'; import Paper from '@material-ui/core/Paper'; import moment from 'moment'; import '../style.css' import api from '../../../utils/api'; import { SweetError, SweetOrderUpdated, SweetWait, SweetWrong } from '../../../SweetAlert'; const MaterialTable = ({orders}) => { const handleOrderStatus = async (e,order) => { SweetWait() try { const res = await api.post('/updateorder',{id:order._id , status:e.target.value}) const { success , error } = res.data if(success) SweetOrderUpdated() else SweetError(error) } catch (error) { SweetWrong() } } return ( <TableContainer component={Paper} style={{overflowY:'auto', maxHeight:500}}> <Table style={{minWidth:650}} aria-label="simple table"> <TableHead> <TableRow> <TableCell>Customers Order Id</TableCell> <TableCell align="center">Phone</TableCell> <TableCell align="center">Address</TableCell> <TableCell align="center" style={{minWidth:180}}>Order Date</TableCell> <TableCell align="center" style={{minWidth:180}}>Status</TableCell> <TableCell align="center">Price(Rs)</TableCell> <TableCell align="center">Payment Status</TableCell> </TableRow> </TableHead> <TableBody> {orders?.map((order) => ( <TableRow key={order._id}> <TableCell scope="row" className="order-id"> {order._id} </TableCell> <TableCell align="center">{order.phone}</TableCell> <TableCell align="center">{order.address}</TableCell> <TableCell align="center">{moment(order.createdAt).format('DD-MMM-YY')}</TableCell> <TableCell align="center"> <select name="paymentMethod" defaultValue={order.status} onChange={(e) => handleOrderStatus(e,order)} className="form-select text-sm shadow p-2 w-full"> <option value="order_placed" >Order Placed</option> <option value="order_confirm">Order Confirm</option> <option value="order_prepare" >Preparing Food</option> <option value="order_out">Order Out</option> <option value="order_deliverd">Order Deliverd</option> </select> </TableCell> <TableCell align="center">{order.totalPrice}</TableCell> <TableCell align="center">{order.paymentType}</TableCell> </TableRow> ))} </TableBody> </Table> </TableContainer> ) } export default MaterialTable
function currySauce(inputFunc) { let curriedFunc = function (currency) { return inputFunc(',', '$', true, currency); }; return curriedFunc; } currySauce( function currencyFormatter(separator, symbol, symbolFirst, value) { let result = Math.trunc(value) + separator; result += value.toFixed(2).substr(-2,2); if (symbolFirst) return symbol + ' ' + result; else return result + ' ' + symbol; });
"use strict"; var chalk = require("chalk"); function Logger() { this._silent = false; this._debug = false; } Logger.prototype.configure = function (params) { if (params.silet) { this._silent = true; } if (params.debug) { this._debug = true; } return this; } Logger.prototype.error = function (msg) { if (!this._silent) { console.log(chalk.red(msg)); } }; Logger.prototype.debug = function (msg) { if (!this._silent && this._debug) { console.log(chalk.blue(msg)); } }; Logger.prototype.success = function (msg) { if (!this._silent) { console.log(chalk.green(msg)); } }; module.exports = new Logger();
import React from 'react' import styled from '@emotion/styled' import moment from 'moment' import Head from '../components/Head' import DocsHeader from '../components/DocsHeader' import Footer from '../components/Footer' export const Wrapper = styled('div')` height: 100%; display: flex; justify-content: space-between; @media only screen and (max-width: 767px) { display: block; } ` export const Content = styled('main')` overflow: auto; display: flex; flex-direction: column; height: 100%; @media only screen and (max-width: 767px) { height: auto; } ` const DataStoryLayout = ({ children, location, pageContext }) => { const { frontmatter } = pageContext const { title, subtitle, by, date, heroImage } = frontmatter return ( <div className='data-story-layout-wrapper flex-column'> <Head data={{ title, description: subtitle, image: `${location.origin}/img/twitter_card_image.png`, imageAlt: 'The Qri Logo', url: location.href }}/> <DocsHeader location={location} showSidebar={false} /> <div className='data-story-header text-left' style={{ backgroundImage: `url(${heroImage})` }}> <div className='container'> <div className='title'>{title}</div> <div className='subtitle'>{subtitle}</div> <div className='byline'><span>by {by}</span> &nbsp; &nbsp;<span className='date'>{moment(date).format('MMMM Do YYYY')}</span></div> </div> </div> <div className='data-story'> {children} </div> <Footer /> </div> ) } export default DataStoryLayout
class Ray { constructor(pos, dir) { this.translate(pos) this.setAngle(dir) } render() { push() translate(this.pos.x, this.pos.y) line(0, 0, this.dir.x * 10, this.dir.y * 10) pop() } translate(pos) { this.pos = pos } setAngle(angle) { this.dir = p5.Vector.fromAngle(angle); } cast(collider) { // Implements line to line intersection algorithm // src: https://en.wikipedia.org/wiki/Line%E2%80%93line_intersection const x1 = collider.a.x const y1 = collider.a.y const x2 = collider.b.x const y2 = collider.b.y const x3 = this.pos.x const y3 = this.pos.y const x4 = this.pos.x + this.dir.x const y4 = this.pos.y + this.dir.y // calculate the denominator of the division const den = (x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4) // Return if lines are parallel, cannot divide by 0 if (den == 0) return const t = ((x1 - x3) * (y3 - y4) - (y1 - y3) * (x3 - x4)) / den const u = -((x1 - x2) * (y1 - y3) - (y1 - y2) * (x1 - x3)) / den // Return collision point if there is one if (t >= 0 && t <= 1 && u > 0) return createVector( t * (x2 - x1) + x1, t * (y2 - y1) + y1 ) } }
const btnLogin = document.querySelector('.btn-login') const form = document.querySelector('form') btnLogin.addEventListener('click', function (event) { event.preventDefault() const fields = [...document.querySelectorAll('.input-block input')] fields.forEach(field => { if (field.value === "") form.classList.add('validate-error') }) const formError = document.querySelector('.validate-error') if (!formError) { form.classList.add('form-hide') return } formError.addEventListener('animationend', (event) => { if (event.animationName === "wrong") { formError.classList.remove('validate-error') } }) }) form.addEventListener('animationstart', function (event) { if (event.animationName === "down") { document.querySelector('body').style.overflow = "hidden"; } }) form.addEventListener('animationend', function (event) { if (event.animationName === "down") { form.style.display = "none" document.querySelector('body').style.overflow = "none"; } }) /** background squares */ const squares = document.querySelector('ul.squares') for (let i = 1; i <= 10; i++) { const li = document.createElement('li') const size = Math.floor(Math.random() * (120 - 10)) + 10 const delay = Math.floor(Math.random() * (2 - 0.1)) + 0.1 const duration = Math.floor(Math.random() * (24 - 12)) + 12 const position = Math.floor(Math.random() * (1 - 99)) + 99 li.style.width = `${size}px` li.style.height = `${size}px` li.style.bottom = `-${size}px` li.style.left = `${position}%` li.style.animationDelay = `${delay}s` li.style.animationDuration = `${duration}s` li.style.animationTimingFunction = `cubic-bezier(${Math.random()},${Math.random()},${Math.random()},${Math.random()} )` console.log(li) squares.appendChild(li) } // Help Popup // Get the modal var modal = document.getElementById("myModal"); modal.style.display = "flex"; // Get the button that opens the modal var btn = document.getElementById("myBtn"); // Get the <span> element that closes the modal var btn2 = document.getElementsByClassName("close")[0]; // When the user clicks on the button, open the modal btn.onclick = function() { modal.style.display = "flex"; } // When the user clicks on <span> (x), close the modal btn2.onclick = function() { modal.style.display = "none"; } // When the user clicks anywhere outside of the modal, close it window.onclick = function(event) { if (event.target == modal) { modal.style.display = "none"; } }
import React, { Component } from 'react'; class Footer extends Component { render() { return ( <footer class="footer" style={{position: "absolute", bottom: "0", width: "100%", background: "#F14668", color: "white",}}> <div class="content has-text-centered"> <p> <strong style={{color: "black"}}>LastFM Converter</strong> by Andy Estevez. The source code is licensed <a href="http://opensource.org/licenses/mit-license.php" style={{color: "white", fontFamily: "italic" }}>MIT</a>. The website content is licensed <a href="http://creativecommons.org/licenses/by-nc-sa/4.0/" style={{color: "white"}}>CC BY NC SA 4.0</a>. </p> </div> <div class="columns is-mobile is-centered"> <div class="column is-narrow"> <p>About</p> <p>Contact</p> </div> <div class="column is-narrow"> <p><a href="https://www.termsfeed.com/live/284671ea-0fc1-4413-938e-f159c3278ef0" target="_blank" style={{color: "white"}}>Terms of Service</a></p> <p><a href="https://www.termsfeed.com/live/cab2b3a1-79b1-441c-80af-13dbbcf9efde" target="_blank" style={{color: "white"}}>Privacy Policy</a></p> </div> </div> </footer> ); } } export default Footer;
import React, {PropTypes} from 'react'; import WeekNames from './WeekNames'; import CalRow from './CalRow'; class CalendarTable extends React.Component { constructor(props) { super(props); this.NUMBER_OF_WEEKS = 6; this.init(props); } componentWillReceiveProps(nextProps) { this.init(nextProps); } init(props) { console.log(props); this.startDay = 1; this.firstDay = props.date || props.date; this.nextMonthClass = ''; this.lastDay = new Date(this.firstDay.getFullYear(), this.firstDay.getMonth() + 1, 0); this.eventsList = {}; props.events.map(event => this.aggregateEventDays(event)); console.log('event list ', this.eventsList); } aggregateEventDays(event) { let start = new Date(event.from); let end = new Date(event.to); let id = null; for (let d = start; d <= end; d.setDate(d.getDate() + 1)) { let key = d.getMonth() + '_' + d.getDate(); let desc = (id !== event.id) ? event.description : ' '; if (this.eventsList[key]) { this.eventsList[key].push(desc); } else { this.eventsList[key] = [desc]; } id = event.id; } } render() { return <div className="col-lg-12"> <table width="100%" className="table-bordered"> <WeekNames /> <tbody> {this.drawRows()} </tbody> </table> </div> } drawRows() { let rows = []; for (let i = 0; i < this.NUMBER_OF_WEEKS; i++) { let cells = this.getCells(i); rows.push(<CalRow key={i + '-calrow'} cells={cells}/>) } return rows; } getCells(rowNumber) { const FIRST_WEEK = 0; let output = []; if (rowNumber === FIRST_WEEK) { this.fillFirstWeekDays(output); } else { for (let i = 1; i <= 7; i++) { // end days of current month if (this.startDay > this.lastDay.getDate()) { this.startDay = 1; this.nextMonthClass = 'next-month'; this.fillDay(output, this.nextMonthClass); } else { this.fillDay(output, this.nextMonthClass); } } } return output; } fillDay(output, customClass) { if (this.isToday() && !customClass) { customClass = 'today'; } output.push({day: this.startDay, customClass: customClass, eventData: this.isEventDay()}); this.startDay++; } isToday() { return this.startDay === new Date().getDate() && this.firstDay.getMonth() === this.props.getCurrentDate().getMonth() && this.firstDay.getFullYear() === this.props.getCurrentDate().getFullYear(); } isEventDay() { let month = (this.nextMonthClass) ? this.firstDay.getMonth() + 1 : this.firstDay.getMonth(); let key = month + '_' + this.startDay; return this.eventsList[key] || null; } fillFirstWeekDays(output) { let startDayOfMonth = this.firstDay.getDay(); if (startDayOfMonth !== 0) { for (let i = 1; i <= 7; i++) { if (i <= startDayOfMonth) { output.push({day: ''}) } else { this.fillDay(output); } } } else { for (let i = 1; i <= 7; i++) { this.fillDay(output); } } } } CalendarTable.propTypes = { date: PropTypes.object.isRequired, events: PropTypes.array, getCurrentDate: PropTypes.func }; CalendarTable.defaultProps = {}; export default CalendarTable;
// 讲师列表的模块 // 发送ajax请求讲师列表的数据回来渲染 define(['jquery', 'template', 'bootstrap'], function ($, template, bt) { $.ajax({ url: '/api/teacher', type: 'get', success: function (info) { // console.log(info) if (info.code == 200) { // 渲染模板 var htmlStr = template('tc_list_tpl', info); $('#tc_list_tBody').html(htmlStr); } } }); // 查看讲师详情的模块 // 为查看按钮注册事件,但查看按钮是动态生成,所以得用事件委托进行注册事件才会有效果 $("#tc_list_tBody").on("click", "#check_info", function () { // alert('12345'); // 获取讲师的id var id = $(this).parent().attr('data-id'); // console.log(id); $.ajax({ url: "/api/teacher/view", type: 'get', data: { tc_id: id }, success: function (info) { // console.log(info); if (info.code == 200) { // 渲染模板 var htmlStr = template('tc_info_tpl', info.result); $("#teacherModal tbody").html(htmlStr); // 弹出查看框 $("#teacherModal").modal(); } } }) }); // 注销和启用功能 $("#tc_list_tBody").on("click", '.btnHandle', function () { var id = $(this).parent().attr("data-id"); var status = $(this).attr("data-status"); var _this = $(this); $.ajax({ url: '/api/teacher/handle', type: "post", data: { tc_id: id, tc_status: status }, success: function (info) { // 把页面上的状态和服务器更新一下 _this.attr("data-status",info.result.tc_status); if (info.code == 200) { alert('修改成功'); // 如果当前是1的时候,是注销功能,显示的是启用 if (info.result.tc_status == 1) { _this.text("启 用"); }else{ _this.text("注 销"); } } } }) }) })
// @flow import isEqual from "lodash/isEqual"; export function isObservablePropsChanged( observableProps: Array<string>, currentProps: {}, nextProps: {} ): boolean { for( let i = 0; i < observableProps.length; i++ ) if( !isEqual( currentProps[ observableProps[ i ] ], nextProps[ observableProps[ i ] ] ) ) return true; return false; }
/** * * @author Anass Ferrak aka " TheLordA " <ferrak.anass@gmail.com> * GitHub repo: https://github.com/TheLordA/Instagram-Clone * */ import React, { useState, useEffect, useContext } from "react"; import { Link } from "react-router-dom"; import axios from "axios"; import AuthenticationContext from "../contexts/auth/Auth.context"; import { BOOKMARK_POST } from "../contexts/types.js"; import Navbar from "../components/Navbar"; import { config as axiosConfig, ALL_POST_URL } from "../config/constants"; // Material-UI Components import { makeStyles } from "@material-ui/core/styles"; import Card from "@material-ui/core/Card"; import CardHeader from "@material-ui/core/CardHeader"; import CardMedia from "@material-ui/core/CardMedia"; import CardContent from "@material-ui/core/CardContent"; import CardActions from "@material-ui/core/CardActions"; import Avatar from "@material-ui/core/Avatar"; import TextField from "@material-ui/core/TextField"; import IconButton from "@material-ui/core/IconButton"; import Typography from "@material-ui/core/Typography"; import Divider from "@material-ui/core/Divider"; import List from "@material-ui/core/List"; import ListItem from "@material-ui/core/ListItem"; import ListItemText from "@material-ui/core/ListItemText"; // Material-UI Icons import FavoriteIcon from "@material-ui/icons/Favorite"; import FavoriteBorderIcon from "@material-ui/icons/FavoriteBorder"; import ChatBubbleOutlineIcon from "@material-ui/icons/ChatBubbleOutline"; import SendIcon from "@material-ui/icons/Send"; import DoubleArrowIcon from "@material-ui/icons/DoubleArrow"; import BookmarkIcon from "@material-ui/icons/Bookmark"; import BookmarkBorderIcon from "@material-ui/icons/BookmarkBorder"; // General style const useStyles = makeStyles((theme) => ({ root: { maxWidth: 500, margin: "20px auto", "& .MuiTextField-root": { width: "100%", }, "& .MuiOutlinedInput-multiline": { paddingTop: "8px", paddingBottom: "8px", marginTop: "5px", marginLeft: "5px", marginRight: "5px", }, "& .MuiCardContent-root:last-child": { paddingBottom: "10px", }, "& .MuiDivider-middle": { marginBottom: "4px", }, "& .MuiListItem-root": { padding: "0px 16px", }, "& .MuiCardContent-root": { paddingTop: "0px", paddingBottom: "5px", }, "& .MuiIconButton-root:focus": { backgroundColor: "rgba(0, 0, 0, 0)", }, }, header: { padding: "10px", }, media: { //height: 0, paddingTop: "56.25%", // 16:9 height: "max-content", }, likeBar: { height: "25px", paddingTop: "0px", marginTop: "8px", marginLeft: "2px", paddingLeft: "0px", paddingBottom: "4px", }, comments: { display: "flex", paddingTop: "0px", paddingLeft: "12px", paddingRight: "0px", }, comment_item_see_more: { width: "35%", cursor: "pointer", }, comments_icon_see_more: { height: "17px", width: "17px", paddingTop: "4px", paddingBottom: "3px", }, comments_icon: { height: "30px", paddingLeft: "0px", paddingTop: "13px", paddingRight: "8px", paddingBottom: "0px", }, inline: { display: "inline", fontWeight: "600", }, avatar: { height: "40px", }, links: { textDecoration: "none", }, })); const Home = () => { const classes = useStyles(); const { state, dispatch } = useContext(AuthenticationContext); const [data, setData] = useState([]); const [showSend, setShowSend] = useState(false); const [comment, setComment] = useState(""); const config = axiosConfig(localStorage.getItem("jwt")); useEffect(() => { axios.get(ALL_POST_URL, config).then((res) => { setData(res.data.posts); }); }, []); const likePost = (id) => { axios.put(`http://localhost:5000/like`, { postId: id }, config) .then((result) => { const newData = data.map((item) => { if (result.data._id === item._id) return result.data; else return item; }); setData(newData); }) .catch((err) => console.log(err)); }; const unlikePost = (id) => { axios.put(`http://localhost:5000/Unlike`, { postId: id }, config) .then((res) => { const newData = data.map((item) => { if (res.data._id === item._id) return res.data; else return item; }); setData(newData); }) .catch((err) => console.log(err)); }; const bookmark = (id) => { axios.put(`http://localhost:5000/bookmark-post`, { postId: id }, config) .then((result) => { dispatch({ type: BOOKMARK_POST, payload: { Bookmarks: result.data.Bookmarks }, }); localStorage.setItem("user", JSON.stringify(result.data)); }) .catch((err) => console.log(err)); }; const removeBookmark = (id) => { axios.put(`http://localhost:5000/remove-bookmark`, { postId: id }, config) .then((result) => { dispatch({ type: BOOKMARK_POST, payload: { Bookmarks: result.data.Bookmarks }, }); localStorage.setItem("user", JSON.stringify(result.data)); }) .catch((err) => console.log(err)); }; const makeComment = (text, postId) => { setComment(""); axios.put(`http://localhost:5000/comment`, { text, postId }, config) .then((result) => { const newData = data.map((item) => { if (result.data._id === item._id) return result.data; else return item; }); setData(newData); }) .catch((err) => console.log(err)); setComment(""); }; const deletePost = (postId) => { axios.delete(`http://localhost:5000/deletepost/${postId}`, config).then((res) => { const newData = data.filter((item) => { return item._id !== res.data; }); setData(newData); }); }; return ( <> <Navbar /> {data.map((item) => ( <div className="home" key={item._id}> <Card className={classes.root}> <CardHeader className={classes.header} avatar={ <Avatar> <img className={classes.avatar} alt="" src={`data:${item.PhotoType};base64,${item.Photo}`} /> </Avatar> } title={ <Link className={classes.links} to={ item.PostedBy._id !== state._id ? `/profile/${item.PostedBy._id}` : "/profile" } > {item.PostedBy.Name} </Link> } subheader="September 14, 2016" /> <CardMedia className={classes.media} image={`data:${item.PhotoType};base64,${item.Photo}`} title="Paella dish" /> <CardActions className={classes.likeBar} disableSpacing> {item.Likes.includes(state._id) ? ( <IconButton aria-label="Like" color="secondary" onClick={() => { unlikePost(item._id); }} > <FavoriteIcon /> </IconButton> ) : ( <IconButton aria-label="Like" onClick={() => { likePost(item._id); }} > <FavoriteBorderIcon /> </IconButton> )} <IconButton aria-label="comments"> <ChatBubbleOutlineIcon /> </IconButton> {state.Bookmarks.includes(item._id) ? ( <IconButton aria-label="Remove Bookmark" style={{ marginLeft: "auto", color: "#e0d011" }} onClick={() => { removeBookmark(item._id); }} > <BookmarkIcon /> </IconButton> ) : ( <IconButton aria-label="Bookmark" style={{ marginLeft: "auto" }} onClick={() => { bookmark(item._id); }} > <BookmarkBorderIcon /> </IconButton> )} </CardActions> <CardContent> <Typography variant="subtitle2" display="block" gutterBottom> {item.Likes.length} Likes </Typography> <Typography variant="body2" color="textSecondary" component="p"> {item.Body} </Typography> </CardContent> <Divider variant="middle" /> <List> {item.Comments.map((cmt) => { return ( <ListItem className={classes.comment_item} alignItems="flex-start" key={cmt._id} > <ListItemText secondary={ <React.Fragment> <Typography component="span" variant="body2" className={classes.inline} color="textPrimary" > <Link className={classes.links} to={ cmt.PostedBy._id !== state._id ? `/profile/${cmt.PostedBy._id}` : "/profile" } > {cmt.PostedBy.Name} </Link> </Typography> {" — "} {cmt.Text} </React.Fragment> } /> </ListItem> ); })} {item.Comments.length === 0 ? ( <ListItem alignItems="flex-start" style={{ left: "38%" }}> <Typography variant="caption" display="block" gutterBottom> No Comments yet </Typography> </ListItem> ) : null} {item.Comments.length > 3 && item.Comments.length !== 0 ? ( <ListItem alignItems="flex-start" className={classes.comment_item_see_more} > <Typography variant="caption" display="block" gutterBottom> See all {item.Comments.length} comments </Typography> <DoubleArrowIcon className={classes.comments_icon_see_more} /> </ListItem> ) : null} </List> <Divider variant="middle" /> <CardContent className={classes.comments}> <Avatar> <img className={classes.avatar} alt="" src="https://images.unsplash.com/photo-1537815749002-de6a533c64db?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=500&q=60" /> </Avatar> <TextField multiline rows={1} placeholder="Add your comment..." variant="outlined" value={comment} onChange={(event) => { event.preventDefault(); setComment(event.target.value); setShowSend(true); if (event.target.value === "") setShowSend(false); }} /> <IconButton aria-label="add to favorites" className={classes.comments_icon} disabled={!showSend} onClick={() => makeComment(comment, item._id)} > <SendIcon /> </IconButton> </CardContent> </Card> </div> ))} </> ); }; export default Home;
import React from 'react' import { SearchButtom } from "./Search.styled"; import { Icon,Tag } from 'antd-mobile'; function SearchBut(props) { const onChangeTag = (value) => { return () => { props.valueck(value) } // setvalue(value); }; return ( <SearchButtom > <div className="tabAll"> <p>历史搜索</p> <Icon onClick={props.tagClearAllChi} size='xs' color="#999999" type="cross-circle" /> </div> <div className="conTarAll"> { props.tagarr.map((item, index) => { return ( <Tag key={index} onChange={onChangeTag(item)} > {item} </Tag> ) }) } </div> </SearchButtom> ) } export default SearchBut
export function test { alert ('test'); } export var alicia = 'liar?';
import React, { useState } from 'react'; import { Dimensions, ScrollView, Image, } from 'react-native'; import Styled from 'styled-components/native'; import IconButton from '~/Components/IconButton'; const Container = Styled.View``; const ImageContainer = Styled.View` border-top-width: 1px; border-bottom-width: 1px; border-color: #D3D3D3; width: ${Dimensions.get('window').width}px; height: 400px; `; const FeedImageIndicatorContainer = Styled.View` flex: 1; flex-direction: row; justify-content: center; align-items: center; `; const FeedImageIndicator = Styled.View` width: 8px; height: 8px; border-radius: 8px; margin: 2px; `; const FeedMenuContainer = Styled.View` flex-direction: row; `; const MenuContainer = Styled.View` flex: 1; flex-direction: row; `; const FeedBody = ({ id, images }) => { const [ indicatorIndex, setIndicatorIndex ] = useState(0); const imageLength = images.length; return ( <Container> <ScrollView horizontal={true} pagingEnabled={true} showsHorizontalScrollIndicator={false} scrollEnabled={imageLength > 1} onScroll={event => { setIndicatorIndex( event.nativeEvent.contentOffset.x / Dimensions.get('window').width ); }}> {images.map((image, index) => ( <ImageContainer key={`FeedImage-${id}-${index}`}> <Image source={{ uri: image }} style={{ width: Dimensions.get('window').width, height: 400 }} /> </ImageContainer> ))} </ScrollView> <FeedMenuContainer> <MenuContainer> <IconButton iconName="favorite" /> <IconButton iconName="comment" /> <IconButton iconName="send" /> </MenuContainer> <MenuContainer> <FeedImageIndicatorContainer> {imageLength > 1 && images.map((image, index) => ( <FeedImageIndicator key={`FeedImageIndicator-${id}-${index}`} style={{ backgroundColor: indicatorIndex >= index && indicatorIndex < index + 1 ? '#3796EF' : '#D3D3D3' }} /> ))} </FeedImageIndicatorContainer> </MenuContainer> <MenuContainer style={{ justifyContent: 'flex-end' }}> <IconButton iconName="bookmark" /> </MenuContainer> </FeedMenuContainer> </Container> ); }; export default FeedBody;
import React from 'react' import { shallow } from 'enzyme' import { TradeAddPage } from '../../components/TradeAddPage' import { trades } from '../fixtures/trades' let addFirebaseTrade, history, wrapper beforeEach(() => { addFirebaseTrade = jest.fn() history = { push: jest.fn() } wrapper = shallow( <TradeAddPage addFirebaseTrade={addFirebaseTrade} history={history} trade={trades[1]} /> ) }) test('should render TradeAddPage correctly', () => { expect(wrapper).toMatchSnapshot() }) test('should add trade to trades array', () => { wrapper.find('FormParent').prop('handleSubmit')(trades[1]) expect(history.push).toHaveBeenLastCalledWith('/trades') expect(addFirebaseTrade).toHaveBeenLastCalledWith(trades[1]) })
import React, {Component } from 'react' import { Link } from 'react-router-dom' import FavoriteIcon from '@material-ui/icons/Favorite'; import IconButton from '@material-ui/core/IconButton'; class AllBeer extends Component { constructor(props) { super(props) this.state = { favorite: false, beer: props.beer } } addToFavorite = () => { if (this.state.favorite === false) { this.setState({ favorite: true }) } else { this.setState({ favorite: false }) } } render() { const { beer } = this.props const colors = { grey: 'rgba(0, 0, 0, 0.54)', red: '#dc3545' } let btn_class = !this.state.favorite ? colors.grey : colors.red return ( <div key={beer._id} style={{width: '100%', textAlign: 'center', marginTop: '3rem'}}> <IconButton style={{color: btn_class}} aria-label="Add to favorites" onClick={this.addToFavorite.bind(this)}> <FavoriteIcon /> </IconButton> <Link to={`/beer/${beer._id}`}><img style={{width: '15%', height: '15%', paddingLeft: '1rem', marginRight: '4rem'}} src={beer.image_url} alt={beer.name} /> </Link> <p style={{marginBottom: '0.5rem', marginTop: '1rem', fontSize: '1.5rem'}}>{beer.name}</p> <p style={{marginBottom: '1rem', fontWeight: 'bold', opacity: '0.5'}}>{beer.tagline}</p> <p style={{fontWeight: 'bold', fontSize: '0.8rem', lineHeight: '0.4rem', marginBottom: '2rem'}}>created by: {beer.contributed_by}</p> <hr style={{width: '95%', border: '0.8px solid grey', opacity: '0.5'}} /> </div> ) } } export default AllBeer;
import { combineReducers } from 'redux'; import arrWordsReducer from '../reducer/arrWordsReducer'; import isAddingReducer from '../reducer/isAddingReducer'; import * as api from '../reducer/api.reducer'; import * as player from '../reducer/player.reducer'; import * as routes from '../reducer/routes'; const combineReducer = combineReducers({ arrWords: arrWordsReducer, isAdding: isAddingReducer, ...api, ...player, ...routes }); export default combineReducer;
/* Write code to remove duplicates from an unsorted linked list FOLLOW UP How would you solve this problem if a temporary buffer is not allowed? */ module.exports = function(list) { var current = list.head , tmp = null , tmpV = null while (current) { tmp = current.next tmpV = null while (tmp) { if (current.data === tmp.data) { if (tmpV) { tmpV.next = tmp.next } else { current.next = tmp.next } } tmpV = tmp tmp = tmp.next } current = current.next } return list }
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { EditorState } from 'draft-js'; import classNames from 'classnames'; // import Option from '../../components/Option'; import styles from './styles.less'; // eslint-disable-line no-unused-vars // import Cropper from './Cropper'; import { createStyleSheet } from 'jss-theme-reactor'; import customPropTypes from 'material-ui/utils/customPropTypes'; import Dialog, {DialogActions, DialogContent} from 'material-ui/Dialog'; import Button from 'material-ui/Button'; import Crop from 'material-ui-icons/Crop'; let classes; const styleSheet = createStyleSheet('ImageBlock', (theme) => { var css = { root: { }, dialog: { '& .dialog-paper': { maxWidth: '90%', width: 'auto', }, }, dialogContent: { }, }; return css; }); export default class getImageComponent extends Component { static defaultProps = { open: false, }; static contextTypes = { styleManager: customPropTypes.muiRequired, }; constructor(props){ super(props); const { open, } = this.props; let { onStartEdit, onEndEdit, config, toggleCropper, } = props.blockProps; let {isReadOnly, isImageAlignmentEnabled} = config; this.state = { inEditMode: false, cropperOpened: false, isReadOnly, toggleCropper, open, }; } renderCropper = () => { return null; let {cropperOpened} = this.state; return <div> <Button onTouchTap={(event) => { this.setCropperOpened(true); event.stopPropagation(); event.preventDefault(); return false; }} > <Crop /> Обрезать </Button> </div> } setCropperOpened = (cropperOpened) => { const { block, contentState } = this.props; let {toggleCropper} = this.state; toggleCropper(block); }; componentWillMount(){ classes = this.context.styleManager.render(styleSheet); } handleOpen = (event) => { event.stopPropagation(); event.preventDefault(); this.setState({open: true}); }; handleClose = () => { this.setState({open: false}); }; render(): Object { const { block, contentState } = this.props; const { inEditMode, isReadOnly, open, } = this.state; const entity = contentState.getEntity(block.getEntityAt(0)); const { src } = entity.getData(); return ( <span className="rdw-image-imagewrapper"> <img src={src} alt="" className="block-image editor-image" onClick={::this.handleOpen} /> { !isReadOnly() ? this.renderCropper() : undefined } <Dialog className={[classes.dialog].join(" ")} onRequestClose={::this.handleClose} open={open} paperClassName="dialog-paper" > <DialogContent className={[classes.dialogContent].join(" ")} > <img className="editor-image opened" src={src} /> </DialogContent> <DialogActions> <Button key="close" onTouchTap={::this.handleClose} >Закрыть</Button> </DialogActions> </Dialog> </span> ); } }; getImageComponent.propTypes = { block: PropTypes.object.isRequired, blockProps: PropTypes.object.isRequired, contentState: PropTypes.object.isRequired, // getEditor: PropTypes.func.isRequired, }
// @flow const choo = require('choo'); const html = require('choo/html'); // Type of the app state type Model = { counter: number; } // All app specific events. Emitter also understands the built in choo events // "domcontentloaded", "render" and "*" type Event = 'increment' | 'decrement'; // Optional type alias used in events type Delta = number; // App must be given types for the valid events and the state model // Optionaly use ChooApp<any, any> if you don't care during dev or something. const app: ChooApp<Event, Model> = choo(); app.use(counterStore); app.route('/', mainView); app.mount('body'); function mainView (state, emit) { return html` <body> <main class="app"> <h1>Counter</h1> <p>Click count: ${ state.counter }!</p> <button onclick=${ () => emit('increment', 1) }>Increment</button> <button onclick=${ () => emit('decrement', 1) }>Decrement</button> </main> </body> `; } function counterStore(state, emitter) { state.counter = 0; emitter.on('increment', increment); emitter.on('decrement', decrement); emitter.on('*', (name, data) => { console.log('Event:', name, data); }); function increment(payload: Delta) { state.counter += payload; emitter.emit('render'); } function decrement(payload: Delta) { state.counter -= payload; emitter.emit('render'); } }
'use strict'; var express = require('express'); var app = express(); var tracks = [ { "id": 21, "title": "Halahula", "artist": "Untitled artist", "duration": 545, "path": "c:/music/halahula.mp3" }, { "id": 412, "title": "No sleep till Brooklyn", "artist": "Beastie Boys", "duration": 312.12, "path": "c:/music/beastie boys/No sleep till Brooklyn.mp3" } ]; var bodyParser = require('body-parser'); server.use(function use(req, res, next) { res.header('Access-Control-Allow-Origin', '*'); res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept'); res.header('Access-Control-Allow-Methods', 'POST, GET, OPTIONS, PUT, DELETE'); next(); }); server.use(bodyParser.urlencoded({ extended: false })); server.use(bodyParser.json()); // Setup server app.get('/playlists', function (req, res) { res.json(tracks); }); app.post('/playlists', function(req, res) { }); app.delete('/playlists/:id', function(req, res) { }); app.get('/playlis-tracks/', function(req, res) { }); app.get('/playlis-tracks/:playlist_id', function(req, res) { }); app.post('/playlist-tracks/:playlist_id', function(req, res) { }); app.delete('/playlist-tracks/:playlist_id/:track_id', function(req, res) { }); app.listen(3000); module.exports = app;