text
stringlengths
7
3.69M
function htmlspecialchars_decode(string, quote_style) { var optTemp = 0, i = 0, noquotes = false; if (typeof quote_style === 'undefined') quote_style = 2; string = string.toString().replace(/&lt;/g, '<').replace(/&gt;/g, '>'); var OPTS = { 'ENT_NOQUOTES': 0, 'ENT_HTML_QUOTE_SINGLE': 1, 'ENT_HTML_QUOTE_DOUBLE': 2, 'ENT_COMPAT': 2, 'ENT_QUOTES': 3, 'ENT_IGNORE': 4 }; if (quote_style === 0) noquotes = true; if (typeof quote_style !== 'number') { quote_style = [].concat(quote_style); for (i = 0; i < quote_style.length; i++) { if (OPTS[quote_style[i]] === 0) noquotes = true; else if (OPTS[quote_style[i]]) optTemp = optTemp | OPTS[quote_style[i]]; } quote_style = optTemp; } if (quote_style & OPTS.ENT_HTML_QUOTE_SINGLE) string = string.replace(/&#0*39;/g, "'"); if (!noquotes) string = string.replace(/&quot;/g, '"'); string = string.replace(/&amp;/g, '&'); return string; }
angular.module('angular-challonge', []) .constant('CHALLONGE_URL', 'https://api.challonge.com') // default constructor for options object .provider('challongeOptions', function () { // ref each link to see defaults and valid list of options // defaults shouldn't be needed as they are set in the .setKey method in the .config of the app var api_key = 'change me in the .config!', options = {api_key: api_key}; // to be set in the .config of the module to provide global api_key parameter for all option params this.setKey = function (key) { api_key = key; options = {api_key: key}; }; // params constructor class function Params() { this.params = options; // add set of properties in this.params // does not overwrite already set properties this.add = function (params) { if (params instanceof Object) { for (var prop in params) { if (this.params.hasOwnProperty(prop)) { console.log('skipping, has property: ' + prop); continue; } else { this.params[prop] = params[prop]; } } } else { throw new TypeError('must pass in an object of properties'); } }; // update set of properties in this.params // overwrites and adds new properties this.update = function (params) { if (params instanceof Object) { for (var prop in params) { this.params[prop] = params[prop]; } } else { throw new TypeError('must pass in an object of properties'); } }; } // should only return a params object // all logic changes should be done in the params class this.$get = function () { return new Params; }; }) // factory to interface with challonge API and return tournament data .factory('challonge', function ($http, CHALLONGE_URL, challongeOptions) { // function for format validation function formatCheck(format) { var _format; try { // default response format if (format === undefined) { _format = '.json'; return _format; // to handle invalid formats } else if (format !== 'json' || format !== 'xml') { throw new SyntaxError('invalid format type; must be json or xml') // use the user defined format } else { _format = '.' + format; return _format; } } catch (e) { return e; } } return { // TOURNAMENTS ENDPOINTS tournament: { // http://api.challonge.com/v1/documents/tournaments/index /** * * @param options * @param format * @returns {*} */ index: function (options, format) { var format = formatCheck(format), params = options ? options.params : challongeOptions.params; return $http({ method: 'GET', url: CHALLONGE_URL + '/v1/' + tournament + format, params: params, timeout: 10000 }); }, // http://api.challonge.com/v1/documents/tournaments/show /** * * @param tournament * @param options * @param format * @returns {*} */ show: function (tournament, options, format) { var format = formatCheck(format), params = options ? options.params : challongeOptions.params; return $http({ method: 'GET', url: CHALLONGE_URL + '/v1/tournaments/' + tournament + format, params: params, timeout: 10000 }); }, // http://api.challonge.com/v1/documents/tournaments/create /** * * @param options * @param format * @returns {*} */ create: function (options, format) { var format = formatCheck(format), params = options ? options.params : challongeOptions.params; return $http({ method: 'POST', url: CHALLONGE_URL + '/v1/tournaments' + format, params: params, timeout: 10000 }); }, // http://api.challonge.com/v1/documents/tournaments/destroy /** * * @param tournament * @param options * @param format * @returns {*} */ destroy: function (tournament, options, format) { var format = formatCheck(format), params = options ? options.params : challongeOptions.params; return $http({ method: 'DELETE', url: CHALLONGE_URL + '/v1/tournaments/' + tournament + format, params: params, timeout: 10000 }); }, // http://api.challonge.com/v1/documents/tournaments/process_check_in /** * * @param tournament * @param options * @param format * @returns {*} */ process_check_ins: function (tournament, options, format) { var format = formatCheck(format), params = options ? options.params : challongeOptions.params; return $http({ method: 'POST', url: CHALLONGE_URL + '/v1/touraments/' + tournament + '/process_check_ins' + format, params: params, timeout: 10000 }); }, // http://api.challonge.com/v1/documents/tournaments/abort_check_in /** * * @param tournament * @param options * @param format * @returns {*} */ abort_check_in: function (tournament, options, format) { var format = formatCheck(format), params = options ? options.params : challongeOptions.params; return $http({ method: 'POST', url: CHALLONGE_URL + '/v1/touraments/' + tournament + '/abort_check_in' + format, params: params, timeout: 10000 }); }, // http://api.challonge.com/v1/documents/tournaments/start /** * * @param tournament * @param options * @param format */ start: function (tournament, options, format) { var format = formatCheck(format), params = options ? options.params : challongeOptions.params; $http({ method: 'POST', url: CHALLONGE_URL + '/v1/tournaments/' + tournament + '/start' + format, params: params, timeout: 10000 }); }, // http://api.challonge.com/v1/documents/tournaments/finalize /** * * @param tournament * @param options * @param format * @returns {*} */ finalize: function (tournament, options, format) { var format = formatCheck(format), params = options ? options.params : challongeOptions.params; return $http({ method: 'POST', url: CHALLONGE_URL + '/v1/tournaments/' + tournament + '/finalize' + format, params: params, timeout: 10000 }); }, // http://api.challonge.com/v1/documents/tournaments/reset /** * * @param tournament * @param options * @param format * @returns {*} */ reset: function (tournament, options, format) { var format = formatCheck(format), params = options ? options.params : challongeOptions.params; return $http({ method: 'POST', url: CHALLONGE_URL + '/v1/tournaments/' + tournament + '/reset' + format, params: params, timeout: 10000 }); } }, // PARTICIPANT ENDPOINTS participant: { // http://api.challonge.com/v1/documents/participants/index /** * * @param tournament * @param participants * @param options * @param format * @returns {*} */ index: function (tournament, participants, options, format) { var format = formatCheck(format), params = options ? options.params : challongeOptions.params; return $http({ method: 'GET', url: CHALLONGE_URL + '/v1/tournaments/' + tournament + '/' + participants + format, params: params, timeout: 10000 }); }, // http://api.challonge.com/v1/documents/participants/show /** * * @param tournament * @param participants * @param options * @param format * @returns {*} */ show: function (tournament, participants, options, format) { var format = formatCheck(format), params = options ? options.params : challongeOptions.params; return $http({ method: 'GET', url: CHALLONGE_URL + '/v1/tournaments/' + tournament + '/participants/' + participants + format, params: params, timeout: 10000 }); }, // http://api.challonge.com/v1/documents/participants/create /** * * @param tournament * @param participants * @param options * @param format * @returns {*} */ create: function (tournament, participants, options, format) { var format = formatCheck(format), params = options ? options.params : challongeOptions.params; return $http({ method: 'POST', url: CHALLONGE_URL + '/v1/tournaments/' + tournament + '/' + participants + format, params: params, timeout: 10000 }); }, // TODO: check if the bulk_add works. // http://api.challonge.com/v1/documents/participants/bulk_add /** * * @param tournament * @param participants * @param options * @param format * @returns {*} */ bulk_add: function (tournament, participants, options, format) { var format = formatCheck(format), params = options ? options.params : challongeOptions.params; return $http({ method: 'POST', url: CHALLONGE_URL + '/v1/tournaments/' + tournament + '/' + participants + '/bulk_add' + format, params: params, timeout: 10000 }); }, // http://api.challonge.com/v1/documents/participants/destroy /** * * @param tournament * @param participants * @param options * @param format * @returns {*} */ destroy: function (tournament, participants, options, format) { var format = formatCheck(format), params = options ? options.params : challongeOptions.params; return $http({ method: 'DELETE', url: CHALLONGE_URL + '/v1/tournaments/' + tournament + '/participants/' + participants + format, params: params, timeout: 10000 }); }, // http://api.challonge.com/v1/documents/participants/check_in /** * * @param tournament * @param participants * @param options * @param format * @returns {*} */ check_in: function (tournament, participants, options, format) { var format = formatCheck(format), params = options ? options.params : challongeOptions.params; ///v1/tournaments/:tournaments/participants/:participant_id/check_in.format return $http({ method: 'POST', url: CHALLONGE_URL + '/v1/tournaments/' + tournament + '/participants/' + participants + '/check_in' + format, params: params, timeout: 10000 }); }, // http://api.challonge.com/v1/documents/participants/randomize /** * * @param tournament * @param options * @param format * @returns {*} */ randomize: function (tournament, options, format) { var format = formatCheck(format), params = options ? options.params : challongeOptions.params; return $http({ method: 'POST', url: CHALLONGE_URL + '/v1/tournaments/' + tournament + '/participants/randomize' + format, params: params, timeout: 10000 }); } }, // MATCH ENDPOINTS match: { // http://api.challonge.com/v1/documents/matches/index /** * * @param tournament * @param match * @param options * @param format * @returns {*} */ index: function (tournament, match, options, format) { var format = formatCheck(format), params = options ? options.params : challongeOptions.params; return $http({ method: 'GET', url: CHALLONGE_URL + '/v1/tournaments/' + tournament + '/matches' + format, params: params, timeout: 1000 }); }, // http://api.challonge.com/v1/documents/matches/show /** * * @param tournament * @param match * @param options * @param format * @returns {*} */ show: function (tournament, match, options, format) { var format = formatCheck(format), params = options ? options.params : challongeOptions.params; return $http({ method: 'GET', url: CHALLONGE_URL + '/v1/tournaments/' + tournament + '/matches/' + match + format, params: params, timeout: 1000 }); }, // http://api.challonge.com/v1/documents/matches/update /** * * @param tournament * @param match * @param options * @param format * @returns {*} */ update: function (tournament, match, options, format) { var format = formatCheck(format), params = options ? options.params : challongeOptions.params; return $http({ method: 'PUT', url: CHALLONGE_URL + '/v1/tournaments/' + tournament + '/matches/' + match + format, params: params, timeout: 1000 }); } }, // ATTACHMENT ENDPOINTS attachment: { // http://api.challonge.com/v1/documents/match_attachments/index /** * * @param tournament * @param match * @param options * @param format * @returns {*} */ index: function (tournament, match, options, format) { var format = formatCheck(format), params = options ? options.params : challongeOptions.params; return $http({ method: 'GET', url: CHALLONGE_URL + '/v1/tournaments/' + tournament + '/matches/' + match + '/attachments' + format, params: params, timeout: 1000 }); }, // http://api.challonge.com/v1/documents/match_attachments/show /** * * @param tournament * @param match * @param options * @param format * @returns {*} */ show: function (tournament, match, options, format) { var format = formatCheck(format), params = options ? options.params : challongeOptions.params; return $http({ method: 'GET', url: CHALLONGE_URL + '/v1/tournaments/' + tournament + '/matches/' + match + '/attachments' + format, params: params, timeout: 1000 }); }, // http://api.challonge.com/v1/documents/match_attachments/create // TODO: fix $http request to actual used the attachment in parameters /** * * @param tournament * @param match * @param attachment * @param options * @param format * @returns {*} */ create: function (tournament, match, attachment, options, format) { var format = formatCheck(format), params = options ? options.params : challongeOptions.params; return $http({ method: 'POST', url: CHALLONGE_URL + '/v1/tournaments/' + tournament + '/matches/' + match + '/attachments' + format, params: params, timeout: 1000 }); }, // http://api.challonge.com/v1/documents/match_attachments/update // TODO: fix $http request to actual used the attachment in parameters /** * * @param tournament * @param match * @param attachment * @param options * @param format * @returns {*} */ update: function (tournament, match, attachment, options, format) { var format = formatCheck(format), params = options ? options.params : challongeOptions.params; return $http({ method: 'PUT', url: CHALLONGE_URL + '/v1/tournaments/' + tournament + '/matches/' + match + '/attachments' + format, params: params, timeout: 1000 }); }, // http://api.challonge.com/v1/documents/match_attachments/destroy /** * * @param tournament * @param match * @param attachment * @param options * @param format * @returns {*} */ destroy: function (tournament, match, attachment, options, format) { var format = formatCheck(format), params = options ? options.params : challongeOptions.params; return $http({ method: 'DELETE', url: CHALLONGE_URL + '/v1/tournaments/' + tournament + '/matches/' + match + '/attachments/' + attachment + format, params: params, timeout: 1000 }); } } }; });
let hamburger = document.querySelector('.toggle-icon'); //hamburger menu hamburger.addEventListener('click', function(event) { document.querySelector('nav').classList.toggle('show-nav'); });
$(function() { province = $('#province_list'); city = $('#city_list'); area = $('#area_list'); $.post('/controller/address/addressHandler.php', { type : 'province_list' }, function(provinces, statu) // 回传函数 { var provinces = eval('(' + provinces + ')'); for (var i = 0; i < provinces.length; i++) { $( '<option value=' + provinces[i].province_code + '>' + provinces[i].name + '</option>').appendTo( province); } }); province.change(function() { $.post('/controller/address/addressHandler.php', { type : 'city_list', province_code : province.val() }, function(cities, statu) // 回传函数 { var cities = eval('(' + cities + ')'); city.children().remove(); $("<option value=''>请选择城市</option>").appendTo(city); for (var i = 0; i < cities.length; i++) { $( '<option value=' + cities[i].city_code + '>' + cities[i].name + '</option>').appendTo(city); } }); }); city.change(function() { $.post('/controller/address/addressHandler.php', { type : 'area_list', city_code : city.val() }, function(areas, statu) // 回传函数 { var areas = eval('(' + areas + ')'); area.children().remove(); $("<option value=''>请选择地区</option>").appendTo(area); for (var i = 0; i < areas.length; i++) { $( '<option value=' + areas[i].area_code + '>' + areas[i].name + '</option>').appendTo(area); } }); }); });
function probarValidarNombre(){ console.assert( validarNombre("") === "Este campo debe tener al menos 1 caracter", "No esta bien hecha la funcion validar nombre con un solo caracter"); console.assert( validarNombre('9384yhfdbkbiesdfhbedifudbsifjkbsdfikjcbfkxjcbsd;fkcdlfhlskndfm;ldskfnxc') === "Este campo debe tener menos de 50 caracteres", "No esta dando correctamente la funcion de mas de 50 caracteres") console.assert( validarNombre('12134564123') === 'El campo nombre solo acepta letras', 'No esta funcionando corre validar que tenga solo letras' ) } probarValidarNombre() function validarRegalo(){ console.assert( validarDescripcionRegalo('1234465144661+415165465416543165416549865415321564886541230546516532106531653156316534165313216534156315632156321653416531532165341653215321563416534156316531531654156') === "El texto que ingresaste es muy largo", "No esta funcionando la validacion del regalo" ) console.assert(validarDescripcionRegalo("") === "Por favor ingresa un texto valido", "No esta funcionando la funcion validarDescripcionRegalo con texto vacio" ) console.assert(validarDescripcionRegalo('{%$chichuni')=== "Por favor ingrese un caracter valido", "No esta funcionando la funcion validarDescripcionRegalo con caracteres prohibidos" ) } validarRegalo() function validarSeleccionDeCiudad(){ console.assert( validarCiudad('') === "Por Favor ingrese una provincia", "No esta funcionando la validacion de la ciudad" ) } validarSeleccionDeCiudad() //* AGREGO UN COMENTARIO PARA HACER UN PUSH
/* 🤖 this file was generated by svg-to-ts*/ export const EOSIconsReply = { name: 'reply', data: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M10 9V5l-7 7 7 7v-4.1c5 0 8.5 1.6 11 5.1-1-5-4-10-11-11z"/></svg>` };
// ファイルのインポート import React from 'react'; import ReactDom from 'react-dom'; /* ========================== */ // 親コンポーネント(Class Component) class Parent extends React.Component { // 初期stateの定義 constructor(props) { super(props); this.state = { value1: 'foo', value2: ['bar', 'baz'], }; // イベントハンドラー関数にthisをバインド this.handleClick = this.handleClick.bind(this); } // イベントハンドラー関数の定義 handleClick() { // stateを更新 this.setState(() => { return {value1: 'bar'}; }); } // レンダリング内容 render() { return ( // 子コンポーネントに値を渡す} <div> <Child data={this.state.value1} handleClick={this.handleClick} /> </div> ); } } /* ========================== */ // 子コンポーネント(Functional Component) const Child = (props) => ( // propsを通して値を取得} <div onClick={props.handleClick}> {props.data} </div> ); // propsのバリデーション Child.propTypes = { //handleClick: React.PropTypes.func, //data: React.PropTypes.string, }; /* ========================== */ // 生DOMにレンダリング ReactDom.render( <Parent />, document.querySelector('#content') );
app.views.CouponList = Backbone.View.extend({ initialize: function () { this.render(); this.collection.on("reset", this.render, this); }, render: function () { this.$el.html(this.template({coupons: this.collection.toJSON()})); return this; } });
const express=require('express'); const mongoose=require('mongoose') const User=require('./user') const Msg=require('./messages') module.exports={User,Msg};
+ function ($) { var defaultOption = { // 浏览器状态修改方式, push会加入window.history, replace 不会 push: true, replace: false, // 加载地址时,是否去除url参数,可以自定义参数返回处理后的地址 noQuery: false, container: "#oss-wraper", element: "a[oss-pjax-namespc='oss-pjax']", nameSpc: "oss-pjax", loadingTemplate: '<div style="width:100%;margin-top:16px;text-align:center;color: #666666">加载中...</div>', ajaxSetting: { timeout: 0, type: "GET", dataType: "html" }, methods: { /** * 点击事件, 可以通过 event.preventDefault()取消后续执行 * @param {any} event 触发事件对象 */ click: function (event) {}, /** * 准备修改页面内容 * @param {"replace"|"append"} loadType 加载页面内容形式(替换或者追加) */ beforChange: function (loadType) {}, /** * 页面处理完成方法 * @param {"replace"|"append"} loadType 加载页面内容形式(替换或者追加) */ complete: function (loadType) {} }, // 客户端默认版本号 clientVer: function () { return $("meta").filter(function () { var name = $(this).attr("http-equiv"); return name && name.toLowerCase() === "oss-pjax-ver"; }).attr("content"); }, }; const pjaxHtmlHelper = { /** * * 去掉页面中已经重复的js和css文件 * @param {any} con 内容对象 * @param {any} opt 实例选项 */ filterScripts: function (con, opt) { // 清除上个页面相关js,css 内容 $("script[oss-pjax-namespc='" + opt.nameSpc + "']").remove(); var pageScripts = $('script'); con.$scripts.each(function () { var nConItem = this; var nId = nConItem["src"] || nConItem.id || nConItem.innerText; for (var i = 0; i < pageScripts.length; i++) { var pageItem = pageScripts[i]; var pageId = pageItem["src"] || pageItem.id || pageItem.innerText; if (nId === pageId) { if (pageItem.hasAttribute("oss-pjax-global")) return; console.info("请求页面地址:" + con.url + " 包含了已经存在的" + pageId + " js文件/代码,将会重新加载!"); pageItem.parentNode.removeChild(pageItem); } } if (!nConItem.hasAttribute("oss-pjax-namespc")) { nConItem.setAttribute("oss-pjax-namespc", opt.nameSpc); } pjaxHtmlHelper.installScript(nConItem); }); }, /** * 原生追加js方法(不使用jquery append方式,否则每次发起xmlhttpreq) * @param sNode * @returns */ installScript: function (sNode) { if (!sNode) return; const script = document.createElement("script"); const attrs = sNode.attributes; for (let index = 0; index < attrs.length; index++) { const attr = attrs[index]; script.setAttribute(attr.name, attr.value); } script.innerHTML = sNode.innerHTML; document.body.appendChild(script); }, /** * 格式化内容 * @param {any} html 原始html * @param {any} opt pjax实例选项 * @param {any} xhr 请求xmlhttprequest * @returns {any} 格式化后的内容对象 */ formatContent: function (html, opt, url, xhr) { let con = { origin: html, isFull: /<html/i.test(html) }; let $html = null , $container = null; if (con.isFull) { $html = $("<div></div>"); const head = html.match(/<head[^>]*>([\s\S.]*)<\/head>/i); if (head) { $html.append($(this._parseHTML(head[0]))); } let $body = $(this._parseHTML(html.match(/<body[^>]*>([\s\S.]*)<\/body>/i)[0])); $html.append($body); $container = this.filterAndFind($body, opt.container); if (!$container.length) { $container = $("<div></div>").append($body); } } else { $html = $(this._parseHTML(html)); $container = this.filterAndFind($html, opt.container).first(); if (!$container.length) { $container = $("<div></div>").append($html); } } con.$scripts = this.filterAndFind($html, "script").remove(); con.title = this.filterAndFind($html, "title").last().remove().text(); if (!con.title) con.title = $container.attr("title"); con.content = $container.html(); con.version = xhr.getResponseHeader("oss-pjax-ver"); con.url = url; return con; }, _parseHTML: function (htmlString) { return $.parseHTML(htmlString, document, true); }, filterAndFind: function ($ele, selecter) { return $ele.filter(selecter).add($ele.find(selecter)); } }; // =========== 请求处理 Start ============ // 终止请求 function abortXHR(xhr) { if (xhr && xhr.readyState < 4) { xhr.onreadystatechange = $.noop; xhr.abort(); } } // 去除url 的 hash值 function stripHash(location) { return location.href.replace(/#.*/, ""); } /** * 验证链接 * @param {any} event 链接元素 * @return false-停止Pjax,执行原生。 {} Pjax执行需要的地址信息 */ function formatLinkEvent(event) { var link = event.currentTarget; if (!link) return false; if (link.tagName.toUpperCase() !== "A") throw "osspjax click event requires an anchor element"; // 如果已经被阻止,则取消 if (event.isDefaultPrevented()) return false; if (event.which > 1 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return false; // 忽略跨域请求 if (link.protocol && location.protocol !== link.protocol || link.hostname && location.hostname !== link.hostname) return false; if (stripHash(link) === stripHash(location)) { if (link.href.indexOf("#") === -1 || link.href === location.href) { // 当页地址,且非锚点请求,阻止后续 preventDefault(event); } return false; } return link.href; } // 如果启用了过滤参数,请求时去除query参数,适用于模板请求 function getRealReqUrl(opt, url, ver) { var q = opt.noQuery; let _remote_url; if (q) { if (typeof q === "function") { _remote_url = q(url); } else { var index = url.indexOf("?"); if (index > 0) _remote_url = url.substring(0, index); } } if (!_remote_url) _remote_url = url; return appVersionToUrl(_remote_url, ver); } function preventDefault(event) { if (event.preventDefault) { event.preventDefault(); } else { event.returnValue = false; }; } /** * 获取内容 * @param {any} url 请求地址 * @returns {any} promise对象 */ function getContent(ossPjax, url, loadType) { const opt = ossPjax._option; // 附加数据,版本号处理 const ver = exeClientVersion(opt.clientVer) || "1.0"; const realUrl = getRealReqUrl(ossPjax._option, url, ver); const ajaxOpt = $.extend({}, opt.ajaxSetting, { url: realUrl }); abortXHR(ossPjax._xhr); // 处理ajax的beforeSend var oldBeforEvent = ajaxOpt.beforeSend; ajaxOpt.beforeSend = function (x, p) { x.setRequestHeader("oss-pjax-ver", ver); x.setRequestHeader("oss-pjax", opt.nameSpc); if (oldBeforEvent && typeof oldBeforEvent == "function") { oldBeforEvent.call(this, x, p); } } startLoading(opt, loadType); var defer = $.Deferred(); ossPjax._xhr = $.ajax(ajaxOpt).done(function (resData, textStatus, hr) { var con = pjaxHtmlHelper.formatContent(resData, opt, url, hr); defer.resolve(con); }).fail(function (hr, textStatus, errMsg) { defer.reject(errMsg, textStatus, hr); }).always(function () { removeLoading(opt); }); return defer.promise(); } // 检测服务端返回版本信息 function checkResponseVsersion(option, con) { const cVer = option.clientVer; var clientVal = exeClientVersion(cVer); if (!clientVal) { option.clientVer = con.version; return; } // 版本不同,或者内容不存在 if ((con.version && con.version !== clientVal) || !con.content) { forceTo(con.url, con.version); } } function exeClientVersion(clientVer) { typeof clientVer == "function" ? clientVer() : clientVer; } function forceTo(url, version) { window.location.href = appVersionToUrl(url, version); } function appVersionToUrl(url, v) { if (v) { if (url.indexOf("_opv=") > 0) { url = url.replace(/([\?|&]_opv=)([^&]*)/i, "$1" + v); } else { if (url.indexOf("?") < 0) url += "?_opv=" + v; else url += "&_opv=" + v; } } return url; } function startLoading(option, loadType) { if (!option.loadingTemplate) { return; } const $loading = $(option.loadingTemplate); $loading.attr("oss-pjax-loading", "true"); const $container = $(option.container); if (loadType == "replace") $container.html($loading); else { $container.append($loading); } } function removeLoading(option) { if (!option.loadingTemplate) { return; } $(option.container).find("[oss-pjax-loading='true']").remove(); } /** * 替换内容 * @param {any} opt 参数配置 * @param {any} con 需要加载的相关内容 * @param {"replace"|"append"} loadType 加载页面内容形式(替换或者追加) */ function loadContent(opt, con, loadType) { const $container = $(opt.container); const isReplace = loadType == "replace"; // 准备加载事件 opt.methods.beforChange(loadType); // 清理目标( 追加类型不需要 if (isReplace) $container.html(""); // 替换标题 if (con.title && (opt.push || opt.replace)) document.title = con.title; // 追加新内容 $container.append(con.content); // 过滤安装脚本(追加模式下不会执行 if (isReplace) pjaxHtmlHelper.filterScripts(con, opt); // 展示 opt.methods.complete(loadType); } // =========== 请求处理 end ============ const OssPjax = function ($ele, opt) { const self = this; self._option = opt; // 设置初始页的页面状态值 var firstState = setPageState(self, null, null); if (opt.push || opt.replace) window.history.replaceState(firstState, firstState.title, firstState.url); $ele.on("click.pjax" + opt.nameSpc.replace(".", "_"), opt.element, function (event) { self.click(event); }); }; // 实例属性: state 是当前页面信息, xhr 远程请求实体信息 // 原型属性: haveSysVerCheck 是否已经开启服务器版本检查 OssPjax.prototype = { _pageState: null, _deepLevel: 0, _sysVerCheckCount: 0, _option: null, // 用来保存配置信息 _xhr: null, // 保存请求中信息 click: function (event) { var url = formatLinkEvent(event); if (!url) return; this._option.methods.click(event); if (event.isDefaultPrevented()) return; this.goTo(url); preventDefault(event); }, append: function (url) { const opt = this._option; const loadType = "append"; getContent(this, url, loadType).done(function (con) { checkResponseVsersion(opt, con); loadContent(opt, con, loadType); }).fail(function (errMsg, textStatus, hr) { forceTo(url); }); }, forceTo: function (url) { forceTo(url); }, goTo: function (url) { this._interGoTo(url); }, _interGoTo: function (url, popedState) { const ossPjax = this; const loadType = "replace"; getContent(ossPjax, url, loadType).done(function (con) { const opt = ossPjax._option; checkResponseVsersion(opt, con); if (!popedState) { // 正常浏览器请求 if (opt.push || opt.replace) { const newState = setPageState(ossPjax, con); if (opt.push) window.history.pushState(newState, newState.title, newState.url); else if (opt.replace) window.history.replaceState(newState, newState.title, newState.url); } } else { setPageState(ossPjax, null, popedState); } loadContent(opt, con, loadType); }).fail(function (errMsg, textStatus, hr) { forceTo(url); }); }, /** * 获取或者设置当前的页面State * @param {any} action 修改浏览器state的动作(pushState|replaceState) * @param {any} state osspjax 页面状态对象 * @returns {any} 如果未传值动作返回当前osspjax状态对象,否则返回执行动作成功与否 */ state: function (action, state) { if (action && state && state.url) { if (action === "pushState") { window.history.pushState(state, state.title, state.url); } else { window.history.replaceState(state, state.title, state.url); } setPageState(this, null, state); return true; } return this._pageState; } }; // ============= 页面State及事件处理 Start ============ function setPageState(instance, newContent, state) { if (!state) { if (!newContent) { //isFirstInitail = true; state = createState({}, instance._option.nameSpc); } else { state = createState(newContent, instance._option.nameSpc); } state._deepLevel = getDeepLevel(instance._option.nameSpc); } return window._oss_pjax_PageState = instance._pageState = state; } /** * 创建页面置换状态 * @param {any} title * @param {any} url */ function createState(newContent, nameSpc) { return { id: new Date().getTime(), nameSpc: nameSpc, title: newContent.title || document.title, url: newContent.url || document.URL }; } function addPopHandler(nameSpc, handler) { if (!this.popHandlers) this.popHandlers = []; this.popHandlers[nameSpc] = handler; if (!this.onPopstateTriger) window.onpopstate = this.onPopstateTriger = function (event) { let pageState = event.state; if (!pageState) return; let handlerSpc = pageState.nameSpc; let curState = window._oss_pjax_PageState; if (pageState.nameSpc !== curState.nameSpc && pageState._deepLevel > curState._deepLevel) handlerSpc = curState.nameSpc; const h = this.popHandlers[handlerSpc]; Popstate(h, pageState); } } /** * 浏览器回退前进 * @param {} state */ function Popstate(ossInstance, state) { if (state && state.url) { ossInstance._interGoTo(state.url, state); }; } // ============= 页面State处理 End ============ function fnPjax(option) { const $this = this; const dataName = "oss.pjax"; let cacheData = $this.data(dataName); if (typeof option == "object") { if (!cacheData) { const mOptions = $.extend(true, {}, defaultOption, option); setDeepLevel(mOptions.nameSpc); // 在初始化之前执行 $this.data(dataName, (cacheData = new OssPjax($this, mOptions))); addPopHandler(mOptions.nameSpc, cacheData); return cacheData; } else { throw "方法不存在,或者命名空间" + cacheData._option.nameSpc + "已经在当前元素挂载osspjax控件!"; } } else if (typeof option == "string") { const args = Array.apply(null, arguments); args.shift(); // 排除 option 本身 if (cacheData && typeof cacheData[option] == "function") { return cacheData[option].apply(cacheData, args); } else if (!cacheData && option == "state") { return false; } } return this; } function setDeepLevel(nameSpc) { var curLevel = window._oss_pjax_CurDeepLevel; if (!curLevel) { window._oss_pjax_CurDeepLevel = curLevel = 0; window._oss_pjax_NameSpcDeep = []; } // 不管存不存在直接重新设置值 var level = curLevel + 1; window._oss_pjax_CurDeepLevel = window._oss_pjax_NameSpcDeep[nameSpc] = level; return level; } function getDeepLevel(nameSpc) { return window._oss_pjax_NameSpcDeep[nameSpc]; } var isSupport = window.history && window.history.pushState && window.history.replaceState; if (isSupport) { var oldOssPjax = $.fn.osspjax; $.fn.osspjax = fnPjax; $.fn.osspjax.constructor = OssPjax; // 冲突控制权的回归处理 $.fn.osspjax.noConflict = function () { $.fn.osspjax = oldOssPjax; return this; }; } }(window.jQuery);
const net = require('net'); const express = require('express'); const path = require('path'); const bodyParser = require('body-parser'); const cookieParser = require('cookie-parser'); // 라우팅 var TCP = require('./tcpServer'); const sensors = require('./routes/sensors'); const test = require('./routes/test'); const dashboard = require('./routes/dashboard'); const app = express(); const http = require('http').Server(app); const io = require('socket.io')(http); const httpPort = 3000; // 미들웨어 app.set('views',path.join(__dirname,'views/pages')); app.set('view engine','ejs'); app.use(express.static(path.join(__dirname,'public'))); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({extended:true})); TCP.on('data',function (data) { /* 온도 dataArray[0] = temp_01 , dataArray[1] = temp_01-battery , dataArray[2] = temp_02 , dataArray[3] = temp_02-battery , dataArray[4] = temp_03 , dataArray[5] = temp_03-battery , 습도 dataArray[6] = humi_01 , dataArray[7] = humi_01-battery , dataArray[8] = humi_02 , dataArray[9] = humi_02-battery , 조도 dataArray[10] = lumi_01 , dataArray[11] = lumi_01-battery , dataArray[12] = lumi_02 , dataArray[13] = lumi_02-battery */ var dataArray = data.split(','); io.emit('temp',dataArray[0],dataArray[1],dataArray[2],dataArray[3],dataArray[4],dataArray[5]); io.emit('humi',dataArray[6],dataArray[7],dataArray[8],dataArray[9]); io.emit('lumi',dataArray[10],dataArray[11],dataArray[12],dataArray[13]); io.emit('dashValue',dataArray); io.emit('dashBattery',dataArray); }) app.use('/',dashboard); app.use('/sensors',sensors); app.use('/test',test); http.listen(httpPort,function () { console.log('Server listening on port '+httpPort); }) module.exports = app;
this["JST"] = this["JST"] || {}; this["JST"]["templates/basic.hbs"] = Handlebars.template(function (Handlebars,depth0,helpers,partials,data) { this.compilerInfo = [4,'>= 1.0.0']; helpers = this.merge(helpers, Handlebars.helpers); data = data || {}; var buffer = "", stack1, functionType="function", escapeExpression=this.escapeExpression, self=this; function program1(depth0,data) { var buffer = "", stack1; buffer += "\n <input type=\""; if (stack1 = helpers.type) { stack1 = stack1.call(depth0, {hash:{},data:data}); } else { stack1 = (depth0 && depth0.type); stack1 = typeof stack1 === functionType ? stack1.call(depth0, {hash:{},data:data}) : stack1; } buffer += escapeExpression(stack1) + "\" name=\""; if (stack1 = helpers.name) { stack1 = stack1.call(depth0, {hash:{},data:data}); } else { stack1 = (depth0 && depth0.name); stack1 = typeof stack1 === functionType ? stack1.call(depth0, {hash:{},data:data}) : stack1; } buffer += escapeExpression(stack1) + "\" value=\""; if (stack1 = helpers.value) { stack1 = stack1.call(depth0, {hash:{},data:data}); } else { stack1 = (depth0 && depth0.value); stack1 = typeof stack1 === functionType ? stack1.call(depth0, {hash:{},data:data}) : stack1; } buffer += escapeExpression(stack1) + "\">\n "; return buffer; } buffer += "<div class=\"body\">"; if (stack1 = helpers.body) { stack1 = stack1.call(depth0, {hash:{},data:data}); } else { stack1 = (depth0 && depth0.body); stack1 = typeof stack1 === functionType ? stack1.call(depth0, {hash:{},data:data}) : stack1; } if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "</div>\n<div class=\"inputs\">\n <form wl-form>\n "; stack1 = helpers.each.call(depth0, (depth0 && depth0.inputs), {hash:{},inverse:self.noop,fn:self.program(1, program1, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n </form>\n</div>\n"; return buffer; });
/** *Script removes defined effect from the selected compositions */ var mainWindow = new Window("palette", "Remove Effect", undefined); // main frame, column mainWindow.orientation = "column"; var inputTextGroup = mainWindow.add("group", undefined, "Input Text Group"); // first group, row inputTextGroup.orientation = "row"; var textInput = inputTextGroup.add("edittext", undefined, "Effect Name"); textInput.size = [100, 25]; var buttonGroup = mainWindow.add("group", undefined, "Button Group"); buttonGroup.orientation = "row"; var removeButton = buttonGroup.add("button", undefined, "Remove Effect"); removeButton.size = [100, 25]; mainWindow.center(); mainWindow.show(); removeButton.onClick = function (){ app.beginUndoGroup("Remove Effect"); var effectName = textInput.text; //Work with selected compositions only for (var k = 1; k <= app.project.numItems; k++){ if ((app.project.item(k) instanceof CompItem) && app.project.item(k).selected) { var myLayers = app.project.item(k).layers; for (var i = 1; i <= myLayers.length; i ++) { var CurrLayer = app.project.item(k).layer(i); // select curr layer // 1. Remove effect if (CurrLayer.Effects.property(effectName)){ CurrLayer.Effects.property(effectName).remove(); // removes selected effect } } } } // app.executeCommand(app.findMenuCommandId("Save a Copy As...")); // uncomment to save if needed app.endUndoGroup(); }
function fruitCalculate(fruit, grams, pricePerKilo) { let fruitPrice = grams / 1000 * pricePerKilo; console.log(`I need $${fruitPrice.toFixed(2)} to buy ${(grams / 1000).toFixed(2)} kilograms ${fruit}.`) } fruitCalculate('orange', 2500, 1.80);
var express = require('express'); var router = express.Router(); var logger = require('../controllers/log'); /* GET home page. */ router.post('/log', function(req, res, next) { logger.log(req,res); }); module.exports = router; /* get parameter ------------- type = info / error / warning etc... , error의 경우만 error폴더에 쌓임 service = moduApp / moduAdmin / bukchon etc... , service명에 따라 폴더 구분 post parameter ------------- ip = sender ip or dns url = request url method = get/post/put/delete param = parameter on method */
(function() { //这是本控制器的ID,非常重要,不要和已有的控制器重名 var controllerName = 'SampleModuleController'; //参考 main.js 中同名变量的说明 var imports = [ 'css!base/template/css/sample_module', { url: 'base/scripts/utils', alias: 'utils' }, 'rd.controls.Button', ]; var extraModules = [ ]; var controllerDefination = ['$scope', 'DataSourceService', 'EventService', main]; function main(scope, DataSourceService, EventService) { console.log('SampleModule controller is initializing..........'); //只有定义在this上的方法才能发布给外部。 this.hello = function(msg) { alert(scope.i18n.hello.st(msg)); } //只有定义在this上的属性才能发布给外部。 this.publicData = 'this is some public data defined in the SampleModule controller'; //定义在scope上的属性才可以被html模板访问 scope.someData = 'some data defined in the SampleModule controller...'; //定义在scope上的函数才可以被html模板访问 scope.openExample = function() { window.open('/doc/client/demo/controls/module/complex_load/index.html','_blank'); } } //========================================================================== // 从这里开始的代码、注释请不要随意修改 //========================================================================== 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); } })();
function toRegister(){ /*未注册,发送验证码*/ var InterValObj; //timer变量,控制时间 var count = 120; //间隔函数,1秒执行 var curCount;//当前剩余秒数 var bol = false; //默认认为没有正在发送短息 var btnSendCode = $(".send_code"); var mobile = $("#mobile"); $(".send_code").click(function () { //向后台发送处理数据 $.ajax({ type: "POST", //用POST方式传输 dataType: "text", //数据格式:JSON url: "/secure/send-register-mobile.html", //目标地址 data: {mobile: mobile.val(),needAfVerfy:true}, error: function (XMLHttpRequest, textStatus, errorThrown) { }, success: function (msg) { } }); window.clearInterval(InterValObj);//停止计时器 curCount = count; //设置button效果,开始计时 btnSendCode.attr("disabled", true); btnSendCode.attr("disabled", true); $("#verifyNo").focus(); bol = true; //正在发送状态更变 btnSendCode.text(+curCount + "s后可再获取"); InterValObj = window.setInterval(SetRemainTime, 1000); //启动计时器,1秒执行一次 return ""; }); //timer处理函数 function SetRemainTime() { if (curCount == 0) { window.clearInterval(InterValObj);//停止计时器 btnSendCode.attr("disabled", false); btnSendCode.attr("disabled", false);;//启用按钮 bol = false; //正在发送状态更变 btnSendCode.text("重新发送验证码"); return ""; } else { curCount--; btnSendCode.text(+curCount + "s后可再获取"); } } }
export const mapMulti = (array) => { return array.map(elem => elem * 2); } export const mapString = (array) => { let stringArray = []; array.map((element, index) => { let string = `element num is = ${element}, element index is ${index}`; stringArray.push(string); }) return stringArray; }
import styled from "styled-components"; const TextStyles = styled.section` margin-top:6rem; div{ width:80%; h4{ color:hsl(26, 100%, 55%); } h1{ text-transform:capitalize; font-weight:700; font-size:2.4rem; } .Short-text{hsl(26, 100%, 55%) color: hsl(219, 9%, 45%); letter-spacing:.5px; font-size:1.1rem; word-spacing:1px; } .price{ display:flex; p{ margin-right:.7rem; height:1.8rem; widtht:; font-weight:700; font-size:2rem; } .cut-off{ background-color:hsl(25, 100%, 94%); color:hsl(26, 100%, 55%); text-align:center; font-size:1rem; padding-top:6px; font-weight:650; margin-top:2.6rem; width:3rem; } } .original{ margin-top:-.6rem; text-decoration: line-through; color: hsl(220, 14%, 75%); font-weight:550; font-size:1.2rem; } } .cart-value{ margin-top:1rem; display:grid; grid-template-columns:50% 48%; grid-column-gap:1%; div{ display:grid; grid-template-columns:33% 33% 33%; button, p{ background-color: hsl(223, 64%, 98%); border:2px solid hsl(223, 64%, 98%); cursor:pointer; height:2rem; font-size:1.5rem; color:hsl(26, 100%, 55%); &:hover{ opacity:0.7; } } p{ margin-top:-.07rem; color:#000; text-align:center; font-size:1; font-weight:600; } } .submit{ text-transform:capitalize; font-size:1rem; width:100%; height:2rem; color:#fff; background-color:hsl(26, 100%, 55%); border:3px solid hsl(26, 100%, 55%); border-radius:5px; &:hover{ opacity:0.7; cursor:pointer; } } } `; export default TextStyles;
function add(num1,num2){ var res=num1+num2; console.log(res) } add(10,20) function sub(num1,num2){ var res=num1-num2 console.log(res) } sub(100,50)
import React, {Component} from 'react'; import BookItem from "./BookItem"; class BookShelf extends Component { render() { const {shelfName, books} = this.props; return ( <div className="bookshelf"> <h2 className="bookshelf-title">{shelfName}</h2> <div className="bookshelf-books"> <ol className="books-grid"> {books && books.constructor === Array && books.map((book) => <BookItem key={book.id} book={book} onChangeShelf={(book, value) => { this.props.onChangeShelf(book, value) }}/> )} </ol> </div> </div> ) } } export default BookShelf
var pJogada = ''; var bJogada = ''; var player = { vitorias: 0, derrotas: 0, empates: 0, pontos: 0 }; var bot = { vitorias: 0, derrotas: 0, empates: 0, pontos: 0 }; var players = [player, bot]; function jogar(valor) { let pRes = document.getElementById('res-player'); let bRes = document.getElementById('res-bot'); let div_pRes = document.getElementById('div-res-player'); let div_bRes = document.getElementById('div-res-bot'); let bValor = 0; if (valor == 'pedra') { pJogada = 'pedra'; pRes.className = 'fas fa-hand-rock fa-4x'; } else if (valor == 'papel') { pJogada = 'papel'; pRes.className = 'fas fa-hand-paper fa-4x'; } else if (valor == 'tesoura') { pJogada = 'tesoura'; pRes.className = 'fas fa-hand-scissors fa-4x'; } bValor = Math.floor(Math.random() * 3); if (bValor == 0) { bjogada = 'pedra'; bRes.className = 'fas fa-hand-rock fa-4x'; } else if (bValor == 1) { bjogada = 'papel'; bRes.className = 'fas fa-hand-paper fa-4x'; } else if (bValor == 2) { bjogada = 'tesoura'; bRes.className = 'fas fa-hand-scissors fa-4x'; } switch (pJogada) { case 'pedra': if (bjogada == 'pedra') { //empatar div_bRes.style.boxShadow = '1px 10px 0px rgb(229, 255, 0)'; //amarelo bot div_pRes.style.boxShadow = '1px 10px 0px rgb(229, 255, 0)'; //amarelo player bot.empates++; player.empates++; calcular(players); } else if (bjogada == 'papel') { //bot ganha div_bRes.style.boxShadow = '1px 10px 0px rgb(94, 255, 0)'; //verde bot div_pRes.style.boxShadow = '1px 10px 0px rgb(255, 0, 0)'; //vermelho player bot.vitorias++; player.derrotas++; calcular(players); } else if (bjogada == 'tesoura') { //player ganha div_bRes.style.boxShadow = '1px 10px 0px rgb(255, 0, 0)'; //vermelho bot div_pRes.style.boxShadow = '1px 10px 0px rgb(94, 255, 0)'; //verde player bot.derrotas++; player.vitorias++; calcular(players); } break; case 'papel': if (bjogada == 'pedra') { //player ganha div_bRes.style.boxShadow = '1px 10px 0px rgb(255, 0, 0)'; //vermelho bot div_pRes.style.boxShadow = '1px 10px 0px rgb(94, 255, 0)'; //verde player bot.derrotas++; player.vitorias++; calcular(players); } else if (bjogada == 'papel') { //empatar div_bRes.style.boxShadow = '1px 10px 0px rgb(229, 255, 0)'; //amarelo bot div_pRes.style.boxShadow = '1px 10px 0px rgb(229, 255, 0)'; //amarelo player bot.empates++; player.empates++; calcular(players); } else if (bjogada == 'tesoura') { //bot ganha div_bRes.style.boxShadow = '1px 10px 0px rgb(94, 255, 0)'; //verde bot div_pRes.style.boxShadow = '1px 10px 0px rgb(255, 0, 0)'; //vermelho player bot.vitorias++; player.derrotas++; calcular(players); } break; case 'tesoura': if (bjogada == 'pedra') { //bot ganha div_bRes.style.boxShadow = '1px 10px 0px rgb(94, 255, 0)'; //verde bot div_pRes.style.boxShadow = '1px 10px 0px rgb(255, 0, 0)'; //vermelho player bot.vitorias++; player.derrotas++; calcular(players); } else if (bjogada == 'papel') { //player ganha div_bRes.style.boxShadow = '1px 10px 0px rgb(255, 0, 0)'; //vermelho bot div_pRes.style.boxShadow = '1px 10px 0px rgb(94, 255, 0)'; //verde player bot.derrotas++; player.vitorias++; calcular(players); } else if (bjogada == 'tesoura') { //empatar div_bRes.style.boxShadow = '1px 10px 0px rgb(229, 255, 0)'; //amarelo bot div_pRes.style.boxShadow = '1px 10px 0px rgb(229, 255, 0)'; //amarelo player bot.empates++; player.empates++; calcular(players); } break; } } function calcular(p) { let pVitorias = document.getElementById('player-vitorias'); let pDerrotas = document.getElementById('player-derrotas'); let pEmpates = document.getElementById('player-empates'); let pPontos = document.getElementById('player-pontos'); let bVitorias = document.getElementById('bot-vitorias'); let bDerrotas = document.getElementById('bot-derrotas'); let bEmpates = document.getElementById('bot-empates'); let bPontos = document.getElementById('bot-pontos'); p[0].pontos = p[0].vitorias * 3 + p[0].empates; p[1].pontos = p[1].vitorias * 3 + p[1].empates; pVitorias.innerHTML = `Vitórias: ${p[0].vitorias}`; pDerrotas.innerHTML = `Derrotas: ${p[0].derrotas}`; pEmpates.innerHTML = `Empates: ${p[0].empates}`; pPontos.innerHTML = `Pontos: ${p[0].pontos}`; bVitorias.innerHTML = `Vitórias: ${p[1].vitorias}`; bDerrotas.innerHTML = `Derrotas: ${p[1].derrotas}`; bEmpates.innerHTML = `Empates: ${p[1].empates}`; bPontos.innerHTML = `Pontos: ${p[1].pontos}`; }
import paths from '@/router/paths'; import globals from '@/helpers/globals'; const view = name => (resolve) => { require([`@/views/${name}/index.vue`], resolve); // eslint-disable-line }; const path = (name) => { const appUrlPrefix = globals.get('CONFIG.appUrlPrefix'); const lang = globals.get('CONFIG.lang'); const currentPath = paths[name]; if (!lang || lang === 'en') { return `${appUrlPrefix}${currentPath}`; } return `${appUrlPrefix}/${lang}${currentPath}`; }; const create = name => ({ name, path: path(name), component: view(name), }); export default [ create('home'), create('login'), create('register'), create('account'), create('lang'), create('mock'), create('monitor'), create('setting'), ];
(function() { 'use strict'; angular.module('app.admin.router', [ 'app.admin.controller' ]) .config(configure); //Se inyecta los parametros configure.$inject = ['$stateProvider', '$urlRouterProvider']; //Se configura las rutas de la aplicación para modelo function configure($stateProvider, $urlRouterProvider) { $urlRouterProvider.otherwise('/'); $stateProvider .state('admin', { url: '/admin', template: '<administrador></administrador>' }); } })();
import './libstyle/Header.css'; import { useState } from 'react'; import { connect } from 'react-redux'; import { searchTermAction } from '../../../redux/actionCreators/normalAction'; import BlackButton from '../utils/BlackButton'; const SearchModal = ({ isShow, setShow, dispatch }) => { const [searchTerm, setSearchTerm] = useState(''); const handleClickOutside = () => { setShow(false); }; const handleStopPropagation = (e) => { e.stopPropagation(); }; const handleFormSubmit = (e) => { e.preventDefault(); if (searchTerm) { dispatch(searchTermAction(searchTerm)); searchTermAction(''); } }; const handleSearchTerm = (e) => { setSearchTerm(e.target.value); }; return isShow ? ( <div className='search-wrapper' onClick={handleClickOutside}> <div id='mobile-form-wrapper'> <form onClick={handleStopPropagation} onSubmit={handleFormSubmit}> <div className='label-search'> <label htmlFor='search-input'>SEARCH PRODUCT</label> </div> <input autoComplete='off' autoCapitalize='off' type='text' placeholder='SEARCH PRODUCTS' id='search-input' value={searchTerm} onChange={handleSearchTerm} /> <BlackButton type='submit'>SEARCH</BlackButton> </form> </div> </div> ) : null; }; const mapDispatchToProps = (dispatch) => ({ dispatch }); export default connect(null, mapDispatchToProps)(SearchModal);
'use strict'; const wrapper = require('./wrapper'); module.exports = { wrapper, };
requirejs.config({ baseUrl: "./js", paths: { 'jquery': "lib/jquery-3.2.0", } }) requirejs(['app/index'])
import React, { useReducer } from 'react'; import propTypes from 'prop-types'; import { reducer } from './reducers'; import { StoreContext } from './storeContext'; const initialState = { categories: [], budget: [], }; export default function StoreProvider({ children }) { const [state, dispatch] = useReducer(reducer, initialState); return ( <StoreContext.Provider value={{ state, dispatch }}> {children} </StoreContext.Provider> ); } StoreProvider.propTypes = { children: propTypes.node.isRequired, };
export { default as pattern } from './pattern' export { default as required } from './required' export { default as outlet } from './outlet'
/* * ProGade API * Copyright 2012, Hans-Peter Wandura (ProGade) * Last changes of this file: Aug 21 2012 */ /* @start class @param extends classPG_ClassBasics */ function classPG_Vars() { // Declarations... this.iMaxStructureDepth = 4; this.iMaxStructureCount = 250; this.iCurrentStructureCount = 0; // Construct... // Methods... /* @start method @return sStructure [type]string[/type] [en]...[/en] @param bUseHtml [type]bool[/type] [en]...[/en] @param xVar [needed][type]mixed[/type] [en]...[/en] @param iDepth [type]int[/type] [en]...[/en] @param bShowEmpty [type]bool[/type] [en]...[/en] @param bShowFunctions [type]bool[/type] [en]...[/en] @param iMaxCount [type]int[/type] [en]...[/en] @param iMaxDepth [type]int[/type] [en]...[/en] */ this.getStructureString = function(_bUseHtml, _xVar, _iDepth, _bShowEmpty, _bShowFunctions, _iMaxCount, _iMaxDepth) { if (typeof(_xVar) == 'undefined') {var _xVar = null;} if (typeof(_iDepth) == 'undefined') {var _iDepth = null;} if (typeof(_bShowEmpty) == 'undefined') {var _bShowEmpty = null;} if (typeof(_bShowFunctions) == 'undefined') {var _bShowFunctions = null;} if (typeof(_iMaxCount) == 'undefined') {var _iMaxCount = null;} if (typeof(_iMaxDepth) == 'undefined') {var _iMaxDepth = null;} _xVar = this.getRealParameter({'oParameters': _bUseHtml, 'sName': 'xVar', 'xParameter': _xVar}); _iDepth = this.getRealParameter({'oParameters': _bUseHtml, 'sName': 'iDepth', 'xParameter': _iDepth}); _bShowEmpty = this.getRealParameter({'oParameters': _bUseHtml, 'sName': 'bShowEmpty', 'xParameter': _bShowEmpty}); _bShowFunctions = this.getRealParameter({'oParameters': _bUseHtml, 'sName': 'bShowFunctions', 'xParameter': _bShowFunctions}); _iMaxCount = this.getRealParameter({'oParameters': _bUseHtml, 'sName': 'iMaxCount', 'xParameter': _iMaxCount}); _iMaxDepth = this.getRealParameter({'oParameters': _bUseHtml, 'sName': 'iMaxDepth', 'xParameter': _iMaxDepth}); _bUseHtml = this.getRealParameter({'oParameters': _bUseHtml, 'sName': 'bUseHtml', 'xParameter': _bUseHtml}); if (_bUseHtml == null) {_bUseHtml = false;} if (_iDepth == null) {_iDepth = 0; this.iCurrentStructureCount = 0;} if (_bShowEmpty == null) {_bShowEmpty = false;} if (_bShowFunctions == null) {_bShowFunctions = false;} if (_iMaxCount == null) {_iMaxCount = this.iMaxStructureCount;} if (_iMaxDepth == null) {_iMaxDepth = this.iMaxStructureDepth;} var _iStructureLength = 0; var _sStructure = ''; try { if (typeof(_xVar) != 'undefined') { if (_xVar === null) { if ((_bUseHtml == false) && (_sStructure != '')) {_sStructure += ", \n";} _sStructure += 'null'; } else if ((this.isArray({'xVar': _xVar})) || (this.isObject({'xVar': _xVar})) || (typeof(_xVar) == 'object')) { if ((_xVar != this.oWindow) && (_xVar != this.oDocument)) { if (_sStructure != '') {_sStructure += ", \n";} if (this.isArray({'xVar': _xVar})) { _sStructure += 'Array'; if (_bUseHtml == true) {_sStructure += '<br />';} _sStructure += '('; } else if ((this.isObject({'xVar': _xVar})) || (typeof(_xVar) == 'object')) { _sStructure += 'Object'; if (_bUseHtml == true) {_sStructure += '<br />';} _sStructure += '('; } if (_bUseHtml == true) {_sStructure += '<blockquote style="margin-top:0px; margin-bottom:0px;">';} var _bSeperator = false; for (var _iIndex in _xVar) { if (typeof(_xVar[_iIndex]) != 'undefined') { if ((typeof(_xVar[_iIndex]) != 'function') || (_bShowFunctions == true)) { if ((!this.isEmpty({'xVar': _xVar[_iIndex]})) || (_bShowEmpty == true)) { // if (_sStructure.length > 1000) {return _sStructure;} if ((_bUseHtml == false) && (_bSeperator == true)) {_sStructure += ", \n";} _sStructure += '['+_iIndex+'] = '; if ((_iDepth < _iMaxDepth) || ((typeof(_xVar[_iIndex]) != 'object') && (typeof(_xVar[_iIndex]) != 'array'))) { _sStructure += this.getStructureString( { 'xVar': _xVar[_iIndex], 'bUseHtml': _bUseHtml, 'iDepth': _iDepth+1, 'bShowEmpty': _bShowEmpty, 'bShowFunctions': _bShowFunctions, 'iMaxCount': _iMaxCount, 'iMaxDepth': _iMaxDepth } ); } else { if (typeof(_xVar[_iIndex]) == 'object') {_sStructure += '[object...]';} else if (typeof(_xVar[_iIndex]) == 'array') {_sStructure += '[array...]';} else {_sStructure += '[more...]';} } if (_bUseHtml == true) {_sStructure += '<br />';} _bSeperator = true; if (this.iCurrentStructureCount > _iMaxCount) { _sStructure += '\n[...more structure]'; if (_bUseHtml == true) {_sStructure += '</blockquote>';} _sStructure += ')'; return _sStructure; } this.iCurrentStructureCount++; } } } } if (_bUseHtml == true) {_sStructure += '</blockquote>';} _sStructure += ')'; } } else if (typeof(_xVar) == 'function') { if (_sStructure != '') {_sStructure += ", \n";} _sStructure += 'function:'+_xVar.getName(); } else { if ((_bUseHtml == false) && (_sStructure != '')) {_sStructure += ", \n";} if (typeof(_xVar) == 'string') { if (_bUseHtml == true) {_xVar = oPGStrings.htmlSpecialChars(_xVar);} _sStructure += '"'+_xVar+'"'; } else if (typeof(_xVar) == 'number') {_sStructure += _xVar;} else if (_xVar === false) {_sStructure += 'false';} else if (_xVar === true) {_sStructure += 'true';} } } } catch(e) {} return _sStructure; } /* @end method */ this.print_r = this.getStructureString; this.print = this.getStructureString; /* @start method @return sType [type]string[/type] [en]...[/en] @param xVar [needed][type]mixed[/type] [en]...[/en] */ this.getType = function(_xVar) { if (typeof(_xVar) == 'undefined') {return 'undefined';} else { _xVar = this.getRealParameter({'oParameters': _xVar, 'sName': 'xVar', 'xParameter': _xVar, 'bNotNull': true}); if (typeof(_xVar.constructor) != 'undefined') { switch(_xVar.constructor) { case Object: return 'object'; break; case Array: return 'array'; break; case String: return 'string'; break; case Number: return 'number'; break; } } } return null; } /* @end method */ /* @start method @return bIsObject [type]bool[/type] [en]...[/en] @param xVar [needed][type]mixed[/type] [en]...[/en] */ this.isObject = function(_xVar) { if (typeof(_xVar) == 'undefined') {var _xVar = null;} _xVar = this.getRealParameter({'oParameters': _xVar, 'sName': 'xVar', 'xParameter': _xVar, 'bNotNull': true}); if (_xVar != null) {return (_xVar.constructor === Object);} return false; } /* @end method */ /* @start method @return bIsArray [type]bool[/type] [en]...[/en] @param xVar [needed][type]mixed[/type] [en]...[/en] */ this.isArray = function(_xVar) { if (typeof(_xVar) == 'undefined') {var _xVar = null;} _xVar = this.getRealParameter({'oParameters': _xVar, 'sName': 'xVar', 'xParameter': _xVar, 'bNotNull': true}); if (_xVar != null) {return (_xVar.constructor === Array);} return false; } /* @end method */ /* @start method @return bIsString [type]bool[/type] [en]...[/en] @param xVar [needed][type]mixed[/type] [en]...[/en] */ this.isString = function(_xVar) { if (typeof(_xVar) == 'undefined') {var _xVar = null;} _xVar = this.getRealParameter({'oParameters': _xVar, 'sName': 'xVar', 'xParameter': _xVar, 'bNotNull': true}); if (_xVar != null) {return (_xVar.constructor === String);} return false; } /* @end method */ /* @start method @return bIsNumber [type]bool[/type] [en]...[/en] @param xVar [needed][type]mixed[/type] [en]...[/en] */ this.isNumber = function(_xVar) { if (typeof(_xVar) == 'undefined') {var _xVar = null;} _xVar = this.getRealParameter({'oParameters': _xVar, 'sName': 'xVar', 'xParameter': _xVar, 'bNotNull': true}); if (_xVar != null) {return (_xVar.constructor === Number);} return false; } /* @end method */ /* @start method @return bIsEmpty [type]bool[/type] [en]...[/en] @param xVar [needed][type]mixed[/type] [en]...[/en] */ this.isEmpty = function(_xVar) { if (typeof(_xVar) == 'undefined') {var _xVar = null;} _xVar = this.getRealParameter({'oParameters': _xVar, 'sName': 'xVar', 'xParameter': _xVar}); if ((typeof(_xVar) == 'undefined') || (_xVar == null)) {return true;} if (this.isNumber(_xVar)) { if ((!_xVar) || (_xVar == 0)) {return true;} } if (this.isString(_xVar)) { if ((!_xVar) || (_xVar == "")) {return true;} } if (this.isObject(_xVar)) {if (_xVar == null) {return true;}} if (this.isArray(_xVar)) {if (!_xVar.length) {return true;}} return false; } /* @end method */ /* @start method @return nNumber [type]number[/type] [en]...[/en] @param xVar [needed][type]mixed[/type] [en]...[/en] */ this.cssNumber = function(_xVar) { if (typeof(_xVar) == 'undefined') {var _xVar = null;} _xVar = this.getRealParameter({'oParameters': _xVar, 'sName': 'xVar', 'xParameter': _xVar, 'bNotNull': true}); if (_xVar != null) { if (this.isString(_xVar)) { _xVar.replace(/,/g, '.'); /* if ( (_xVar.search(/px/i) == -1) && (_xVar.search(/pt/i) == -1) && (_xVar.search(/\%/i) == -1) && (_xVar.search(/cm/i) == -1) && (_xVar.search(/em/i) == -1) && (_xVar.search(/ex/i) == -1) && (_xVar.search(/in/i) == -1) && (_xVar.search(/mm/i) == -1) && (_xVar.search(/pc/i) == -1) ) */ if (_xVar.search(/[0-9+.-]/i) == -1) { _xVar += 'px'; } } else {_xVar += 'px';} } return _xVar; } /* @end method */ /* @start method @return sColor [type]string[/type] [en]...[/en] @param xVar [needed][type]mixed[/type] [en]...[/en] */ this.cssColor = function(_xVar) { if (typeof(_xVar) == 'undefined') {var _xVar = null;} _xVar = this.getRealParameter({'oParameters': _xVar, 'sName': 'xVar', 'xParameter': _xVar, 'bNotNull': true}); if (_xVar != null) { if (this.isString(_xVar)) { //if ((_xVar.search(/\#/i) == -1) && (_xVar.search(/[0-9A-Fa-f]{3,6}/i) != -1) && (_xVar.search(/red/i) == -1)) {_xVar = '#'+_xVar;} _xVar.replace(/\#([0-9A-Fa-f]{3,6})/gi, '#$1'); } } return _xVar; } /* @end method */ } /* @end class */ classPG_Vars.prototype = new classPG_ClassBasics(); var oPGVars = new classPG_Vars();
import React, { useEffect, useState ,useContext} from 'react'; import SaberList from '../components/SaberList'; import ErrorModal from '../../shared/components/UIElements/ErrorModal'; import LoadingSpinner from '../../shared/components/UIElements/LoadingSpinner'; import { useHttpClient } from '../../shared/hooks/http-hook'; import { AuthContext } from '../../shared/context/auth-context'; const Sabers = () => { const auth = useContext(AuthContext); const [loadedSabers, setLoadedSabers] = useState(); const { isLoading, error, sendRequest, clearError } = useHttpClient(); const userId = auth.userId; useEffect(() => { const fetchPlaces = async () => { try { const responseData = await sendRequest( `${process.env.REACT_APP_BACKEND_URL}/saber/allSabers`, 'GET',null, { Authorization: 'Bearer ' + auth.token, } ); setLoadedSabers(responseData.sabers); } catch (err) {} }; userId && fetchPlaces(); }, [sendRequest, userId]); const saberDeletedHandler = deletedSaberId => { setLoadedSabers(prevSabers => prevSabers.filter(saber => saber._id !== deletedSaberId) ); }; return ( <React.Fragment> <ErrorModal error={error} onClear={clearError} /> {isLoading && ( <div className="center"> <LoadingSpinner /> </div> )} {!isLoading && loadedSabers && ( <SaberList items={loadedSabers} onDeleteSaber={saberDeletedHandler} /> )} </React.Fragment> ); }; export default Sabers;
describe('decorators', function () { var $ = require('jquery'); require('../grid-spec-helper')(); var decorators; var grid; var ctx = {}; beforeEach(function () { grid = this.buildSimpleGrid(); decorators = grid.decorators; //clear any other decorators decorators.remove(grid.decorators.getAlive()); decorators.popAllDead(); spyOn(grid, 'requestDraw'); //mock the method to prevent draw this.resetAllDirties(); //set everything clean to start }); describe('should satisfy', function () { beforeEach(function () { ctx.decorator = decorators.create(); }); it('single decorator default render an element that fills the bounding box', function () { var div = document.createElement('div'); div.style.position = 'absolute'; div.style.top = '5px'; div.style.left = '6px'; div.style.width = '25px'; div.style.height = '35px'; var decoratorElem = ctx.decorator.render(); div.appendChild(decoratorElem); document.body.appendChild(div); expect($(decoratorElem).offset()).toEqual({ top: 5, left: 6 }); expect($(decoratorElem).width()).toBe(25); expect($(decoratorElem).height()).toBe(35); }); it('should call a postrender if available on render', function () { var postRender = jasmine.createSpy('post render'); ctx.decorator.postRender = postRender; ctx.decorator.render(); expect(postRender).toHaveBeenCalled(); }); require('../decorators/decorator-test-body')(ctx); }); it('should let me create a decorator with values', function () { var d = decorators.create(2, 3, 4, 5, 'px', 'real'); expect(d).topToBe(2); expect(d).leftToBe(3); expect(d).heightToBe(4); expect(d).widthToBe(5); expect(d).unitsToBe('px'); expect(d).spaceToBe('real'); }); it('should let me add a decorator and request draw', function () { var dec = decorators.create(); this.resetAllDirties(); expect(decorators).not.toBeDirty(); decorators.add(dec); expect(decorators).toBeDirty(); expect(decorators.getAlive()[0]).toEqual(dec); }); it('should let me add multiple decorators', function () { var dec = decorators.create(); var dec2 = decorators.create(); decorators.add([dec, dec2]); expect(decorators.getAlive()[0]).toEqual(dec); expect(decorators.getAlive()[1]).toEqual(dec2); }); it('should let me remove a decorator', function () { var dec = decorators.create(); this.resetAllDirties(); expect(decorators).not.toBeDirty(); decorators.add(dec); this.resetAllDirties(); expect(decorators).not.toBeDirty(); decorators.remove(dec); expect(decorators).toBeDirty(); expect(decorators.getAlive()).toEqual([]); expect(decorators.popAllDead()).toEqual([dec]); }); it('should do nothing if removing an already removed decorator', function () { decorators.add(decorators.create()); var removed = decorators.create(); decorators.add(removed); decorators.remove(removed); decorators.remove(removed); expect(decorators.getAlive().length).toBe(1); expect(decorators.popAllDead().length).toBe(1); }); it('should let me remove multiple decorators', function () { var dec2 = decorators.create(); var dec1 = decorators.create(); decorators.add(dec1); decorators.add(dec2); decorators.remove([dec1, dec2]); expect(decorators.getAlive()).toEqual([]); expect(decorators.popAllDead()).toEqual([dec1, dec2]); }); it('should give me alive and pop all dead decorators', function () { var dec = decorators.create(); decorators.add(dec); var dec2 = decorators.create(); decorators.add(dec2); decorators.remove(dec); expect(decorators.getAlive()).toEqual([dec2]); expect(decorators.popAllDead()).toEqual([dec]); expect(decorators.popAllDead()).toEqual([]); }); });
import React, { useState, useEffect, useContext } from 'react'; import axios from 'axios'; import { withRouter } from 'react-router-dom'; import { ApiProfile } from '../../api/profile'; import { defaultPhoto400 } from '../../constants/defaultPhotos'; import { AppContext } from '../../context/appContext'; import { StyledTopSection, StyledTopSubSection, StyledButtonSection } from '../../containers/ProfilePrivate/styles'; const defualtProfile = { email: '', photo400: '', firstname: '' }; const ProfileDisplayTop = ({ publicProfile, publicUUID, history }) => { const [auth] = useContext(AppContext); const [profile, setProfile] = useState(defualtProfile); const { email, photo400, cover1000, firstname, lastname, phone, website } = profile; // will request data for the current user (private profile) useEffect(() => { if (!publicProfile && auth.uuid) { ApiProfile( axios, 'get', `/api/profile/${auth.uuid}`, null, profile, setProfile, null ); } }, [auth]); // will request data for the other user (public profile) useEffect(() => { if (publicProfile) { ApiProfile( axios, 'get', `/api/profile/${publicUUID}`, null, profile, setProfile, null ); } }, [publicUUID]); return ( <StyledTopSection bg={`url(${cover1000})`}> <StyledTopSubSection> <img src={photo400 || defaultPhoto400} alt="my-pic" width="400px" /> <section> <p>{firstname}</p> <p>{email}</p> </section> </StyledTopSubSection> {!publicProfile && ( <StyledButtonSection> <button type="button" onClick={() => history.push('/settings')} > Edit Profile </button> </StyledButtonSection> )} </StyledTopSection> ); }; export default withRouter(ProfileDisplayTop);
/** * Copyright(c) 2012-2016 weizoom */ "use strict"; var debug = require('debug')('m:outline.data:ProductModelList'); var React = require('react'); var ReactDOM = require('react-dom'); var ProductModel = require('./ProductModel.react'); var Action = require('./Action'); var ProductModelList = React.createClass({ getInitialState: function() { return { 'models': this.props.value } }, onClickAddModel: function(event) { this.state.models.push({ name: '', stocks: '' }); this.callChangeHandler(); }, onChangeModel: function(value, event) { var model = this.state.models[value.index]; model.name = value.name; model.stocks = value.stocks; this.callChangeHandler(); }, onDeleteModel: function(index) { this.state.models.splice(index, 1); this.callChangeHandler(); }, callChangeHandler: function() { var event = {target: ReactDOM.findDOMNode(this)} if (this.props.onChange) { this.props.onChange(this.state.models, event); } }, render:function(){ var models = this.props.value; debug(models); var cModels = ''; if (models) { var _this = this; cModels = models.map(function(model, index) { return ( <ProductModel value={model} index={index} key={index} onChange={_this.onChangeModel} onDelete={_this.onDeleteModel} /> ) }); } return ( <div name={this.props.name}> {cModels} <a className="ml15" onClick={this.onClickAddModel}>+ 添加规格</a> </div> ) } }) module.exports = ProductModelList;
import { CLEAR_PRODUCT_ERROR, CLEAR_PRODUCT_MESSAGE, LIST_PRODUCTS_FAIL, LIST_PRODUCTS_SUCCESS, PRODUCT_CREATED, PRODUCT_FAILED, LIST_ALL_PRODUCTS, FILTERED_PRODUCTS, PRODUCT_DELETED, PRODUCT_DELETE_FAIL, } from '../types' export default (state, action) => { switch (action.type) { case LIST_PRODUCTS_SUCCESS: return { ...state, bestSellers: action.payload, } case LIST_PRODUCTS_FAIL: return { ...state, error: action.payload, } case PRODUCT_CREATED: return { ...state, product: action.payload, message: 'Product created succefully' } case PRODUCT_FAILED: return { ...state, error: action.payload, } case CLEAR_PRODUCT_MESSAGE: return { ...state, message: null } case CLEAR_PRODUCT_ERROR: return { ...state, error: null } case LIST_ALL_PRODUCTS: return { ...state, allProducts: action.payload } case FILTERED_PRODUCTS: return { ...state, filtered: state.allProducts.filter(product => { //creating regular expression with global && not sensetive const regex = RegExp(`${action.payload}`, 'gi') //this will return anything the text we passed match in with the message return product.name.match(regex) || product.category.name.match(regex) }) } case PRODUCT_DELETED: return { ...state, message: 'Product Deleted', error: null } case PRODUCT_DELETE_FAIL: return { ...state, error: action.payload, message: null } default: return state } }
import React from 'react'; export default React.createClass({ render() { return ( <section id='contact' className='d-flex justify-content-center align-items-center'> <div className='container'> <h2 className='title'>Questions?</h2> <form className='container'> <div className='form-group row'> <input type='text' className='inputBox form-control col-xs-12 col-md col-lg-3 offset-lg-3' id='firstname' aria-describedby='first name' placeholder='First Name'/> <input type='text' className='inputBox form-control col-xs-12 col-md col-lg-3' id='lastname' aria-describedby='last name' placeholder='Last Name'/> </div> <div className='form-group row'> <input type='tel' className='inputBox form-control col-xs-12 col-md col-lg-3 offset-lg-3' id='phonenumber' aria-describedby='phone number' placeholder='Phone Number'/> <input type='email' className='inputBox form-control col-xs-12 col-md col-lg-3' id='email' aria-describedby='email' placeholder='Email'/> </div> <div className='form-group row'> <input type='text' className='inputBox form-control col-xs-12 col-lg-6 offset-lg-3' id='title' aria-describedby='title' placeholder='Title'/> </div> <div className='form-group row'> <textarea className="form-control col-xs-12 col-lg-6 offset-lg-3" id="textarea" placeholder='Write message...' rows="5"></textarea> </div> <div className='buttonContainer row'> <button type="submit" className="btn col col-lg-6 offset-lg-3">Submit</button> </div> </form> </div> </section> ) } })
import React from 'react'; import { makeStyles } from '@material-ui/core/styles'; import Card from '@material-ui/core/Card'; import CardActionArea from '@material-ui/core/CardActionArea'; import CardActions from '@material-ui/core/CardActions'; import CardContent from '@material-ui/core/CardContent'; import CardMedia from '@material-ui/core/CardMedia'; import Button from '@material-ui/core/Button'; import Typography from '@material-ui/core/Typography'; import './cardlayout.css' const useStyles = makeStyles({ root: { maxWidth: 345, }, media: { height: 140, }, }); export default function CardLayout({ getQuantity, img, name, available, price, category, vendor, buyProduct, quantity }) { const classes = useStyles(); return ( <Card className={classes.root}> <CardActionArea> <CardMedia className={classes.media} image={img} title={name} /> <CardContent> <div className="flex"> <Typography variant="body1" color="textPrimary" component="p"> Available quantity:<span className="card-span">{available}</span> </Typography> <Typography variant="body1" color="textPrimary" component="p"> Category:<span className="card-span">{category}</span> </Typography> </div> <div className="flex" style={{ marginTop: "20px" }}> <Typography variant="body1" color="textPrimary" component="p"> Price:<span className="card-span">{price}</span> </Typography> <Typography variant="body1" color="textPrimary" component="p"> Vendor:<span className="card-span">{vendor}</span> </Typography> </div> </CardContent> </CardActionArea> <CardActions> <input type="number" onChange={(e) => getQuantity(e, name)} min={1} id={name} value={quantity[name]} /> <Button className="buy-btn" onClick={(e) => buyProduct(e, name, price)}> Buy </Button> </CardActions> </Card> ); }
import React, { Component } from 'react'; import Input from './../common/Input' import { addExpense } from '../../api/remote'; export default class AddExpence extends Component { constructor(props) { super(props); this.state = { name: '', category: '', amount: 0, date: 1 }; this.onChangeHandler = this.onChangeHandler.bind(this); this.onSubmitHandler = this.onSubmitHandler.bind(this); } onChangeHandler(e) { this.setState({ [e.target.name]: e.target.value }); } onSubmitHandler(e) { e.preventDefault(); const year = Number(this.props.match.params.year) const month = Number(this.props.match.params.month) const date = Number(this.state.date) const amount = Number(this.state.amount) addExpense(year, month, date, this.state.name, this.state.category, amount) .then(res => { console.log(res) if (res.success) { this.props.history.push(`/plan/${year}/${month}`); // redirects } else { console.log('Enter data again'); } }) } render() { let monthMap = { 1: 'January', 2: 'February', 3: 'March', 4: 'April', 5: 'May', 6: 'June', 7: 'July', 8: 'August', 9: 'September', 10: 'October', 11: 'November', 12: 'December' } const year = Number(this.props.match.params.year) const month = Number(this.props.match.params.month) return ( <main> <div className="container"> <div className="row space-top"> <div className="col-md-12"> <h1>Add Expenses</h1> <h3>{monthMap[month]} {year}</h3> </div> </div> <div className="row space-top"> <div className="col-md-10"> <form onSubmit={this.onSubmitHandler}> <legend>Add a new expense</legend> <div className="form-group"> <Input name="name" value={this.state.name} onChange={this.onChangeHandler} label="Name:" /> </div> <div className="form-group"> <Input name="category" value={this.state.category} onChange={this.onChangeHandler} label="Category:" /> </div> <div className="form-group"> <Input name="amount" type="number" value={this.state.amount} onChange={this.onChangeHandler} label="Cost:" /> </div> <div className="form-group"> <Input name="date" type="number" value={this.state.date} onChange={this.onChangeHandler} label="Payment Date:" /> </div> <input type="submit" className="btn btn-secondary" value="Add" /> </form> </div> </div> </div> </main> ); } }
import React from "react"; import exceptional from "../../../images/exceptional.png"; const Exceptional = () => { return ( <section className="featuresServices mt-5 pt-5"> <div className="container d-flex justify-content-center mb-5"> <div className="row mb-5 pb-5 w-75"> <div className="col-md-5 mb-4"> <img src={exceptional} alt="" className="img-fluid w-100" /> </div> <div className="col-md-7 mt-3"> <h1> Exceptional Dental <br /> Care,On Your Terms </h1> <p className="text-secondary mt-5 mb-5"> Lorem ipsum dolor, sit amet consectetur adipisicing elit. Ea architecto maxime impedit perferendis quisquam sapiente. Magnam asperiores, beatae, id quis suscipit officia ullam facilis vitae possimus, doloribus saepe! Obcaecati, ad! Lorem ipsum dolor sit amet consectetur adipisicing elit. Eos, consectetur non sint obcaecati repudiandae ipsa itaque corporis sed voluptas quos debitis enim ut, nisi et possimus! Repellat sed quam quibusdam. </p> <button style={{ backgroundColor: "#16D2C3", width: "8em", height: "2.5em", border: "none", }} className="btn btn-primary mt-5 " > Learn More </button> </div> </div> </div> </section> ); }; export default Exceptional;
// feetToMile function feetToMile(inputFeet){ if(inputFeet <= -1){ return "Warnning! This is wrong input"; }else{ var mile = inputFeet / 5280; return mile; } } var mileResult = feetToMile(7500); console.log(mileResult); // woodCalculator function woodCalculator(chair,tabel,bed){ var chairCount = chair; var tabelCount = tabel * 3; var bedCount = bed * 5; var totalCoutn = chairCount + tabelCount + bedCount; return totalCoutn; } var woodCalculatorResult = woodCalculator(5,2,4); console.log(woodCalculatorResult); // brickCalculator function brickCalculator(inputBrick){ var perFloorIt = inputBrick; if(perFloorIt <=10){ return perFloorIt * 15 * 1000; }else if(perFloorIt >=11 && perFloorIt<=20){ return (perFloorIt - 10) * (12*1000) + (150000); } else if( perFloorIt > 20){ return (perFloorIt - 20) * (10*1000) + (270000); }else{ return "Warnning! you mistake something"; } } var resultBrick = brickCalculator(); console.log(resultBrick); // tinyFriend function tinyFriend(friendName){ var smallName = friendName[0]; for(var i = 0; i <friendName.length;i++){ var friendSerial = friendName[i]; if(friendSerial.length < smallName.length){ smallName = friendSerial; } } return smallName; } var friendResult = tinyFriend(['sohan','jitu','dev','nahid']); console.log(friendResult);
'use strict'; //const React = require('react'); import React from 'react'; //const ReactDOM = require('react-dom'); import ReactDOM from 'react-dom'; //const when = require('when'); import when from 'when'; //const client = require('./client'); import client from './client'; //import { NavBar } from './NavBar'; //const follow = require('./follow'); // function to hop multiple links by "rel" import follow from './follow'; //const stompClient = require('./websocket-listener'); import stompClient from './websocket-listener'; //const root = '/api'; const root = '/api/songs/search'; //const root = '/api/songs'; class SongInfo extends React.Component { constructor(props) { super(props); this.state = {songs: [], cellSelected: [], attributes: [], sortBy: "songindex,desc", searchBy:'findBySongindex', page: 1, songindex: this.props.songId, itemtext: this.props.songId, itemTextInput: this.props.songId, pageSize: 8, sort:"songindex,desc", links: {}}; this.updatePageSize = this.updatePageSize.bind(this); this.onNavigate = this.onNavigate.bind(this); this.refreshCurrentPage = this.refreshCurrentPage.bind(this); this.refreshAndGoToLastPage = this.refreshAndGoToLastPage.bind(this); console.log("SongA: constructor" ); } loadFromServer(itemTextUpdate, pageSize, pageSortUpdate) { follow(client, root, [ {rel: this.state.searchBy, params: {size: pageSize, sort:pageSortUpdate, item:this.props.itemParameter, songindex: itemTextUpdate}}] //itemText}}] // {rel: this.state.searchBy, params: {size: pageSize, sort:pageSort, songindex: songindex}}] ).then(songCollection => { return client({ method: 'GET', path: "api/profile/songs", headers: {'Accept': 'application/schema+json'} }).then(schema => { this.schema = schema.entity; this.links = songCollection.entity._links; return songCollection; }); }).then(songCollection => { this.page = songCollection.entity.page; return songCollection.entity._embedded.songs.map(song => client({ method: 'GET', path: song._links.self.href }) ); }).then(songPromises => { return when.all(songPromises); }).done(songs => { this.setState({ page: this.page, songs: songs, attributes: Object.keys(this.schema.properties), pageSize: pageSize, sort: pageSortUpdate, songindex: itemTextUpdate, links: this.links }); // console.log("props.songs[0].entity.itemtext = " + this.props.songs[0].entity.itemtext); }); } onNavigate(navUri) { client({ method: 'GET', path: navUri }).then(songCollection => { this.links = songCollection.entity._links; this.page = songCollection.entity.page; return songCollection.entity._embedded.songs.map(song => client({ method: 'GET', path: song._links.self.href }) ); }).then(songPromises => { return when.all(songPromises); }).done(songs => { this.setState({ page: this.page, songs: songs, attributes: Object.keys(this.schema.properties), pageSize: this.state.pageSize, itemTextInput: this.state.itemTextInput, links: this.links }); }); } updatePageSize(itemTextUpdate, pageSizeUpdate, pageSortUpdate, searchByUpdate) { this.loadFromServer(itemTextUpdate, pageSizeUpdate, pageSortUpdate); } // tag::websocket-handl</td>ers[] refreshAndGoToLastPage(message) { follow(client, root, [{ rel: 'songs', params: {size: this.state.pageSize, songindex: this.state.itemTextInput} }]).done(response => { if (response.entity._links.last !== undefined) { this.onNavigate(response.entity._links.last.href); } else { this.onNavigate(response.entity._links.self.href); } }) } refreshCurrentPage(message) { follow(client, root, [{ rel: 'songs', params: { size: this.state.pageSize, songindex: this.state.itemTextInput, page: this.state.page.number } }]).then(songCollection => { this.links = songCollection.entity._links; this.page = songCollection.entity.page; return songCollection.entity._embedded.songs.map(song => { return client({ method: 'GET', path: song._links.self.href }) }); }).then(songPromises => { return when.all(songPromises); }).then(songs => { this.setState({ page: this.page, songs: songs, attributes: Object.keys(this.schema.properties), pageSize: this.state.pageSize, songindex: this.state.itemTextInput, links: this.links }); }); } // end::websocket-handlers[] // tag::register-handlers[] componentDidMount() { this.loadFromServer(this.state.itemTextInput, this.state.pageSize, this.state.sortBy); stompClient.register([ {route: '/topic/newSong', callback: this.refreshAndGoToLastPage}, {route: '/topic/updateSong', callback: this.refreshCurrentPage}, {route: '/topic/deleteSong', callback: this.refreshCurrentPage} ]); } render() { return ( <SongList page={this.state.page} songId={this.props.songID} arrangement={this.props.arrangement} status={this.props.status} requestType={this.props.requestType} songs={this.state.songs} links={this.state.links} pageSize={this.state.pageSize} sortBy={this.state.sortBy} searchBy={this.state.searchBy} itemTextInput={this.state.itemTextInput} attributes={this.state.attributes} onNavigate={this.onNavigate} onUpdate={this.onUpdate} onDelete={this.onDelete} updatePageSize={this.updatePageSize} cellSelected={this.state.cellSelected}/> ) } } class SongList extends React.Component { constructor(props) { super(props); this.handleNavFirst = this.handleNavFirst.bind(this); this.handleNavPrev = this.handleNavPrev.bind(this); this.handleNavNext = this.handleNavNext.bind(this); this.handleNavLast = this.handleNavLast.bind(this); } handleNavFirst(e) { e.preventDefault(); this.props.onNavigate(this.props.links.first.href); } handleNavPrev(e) { e.preventDefault(); this.props.onNavigate(this.props.links.prev.href); } handleNavNext(e) { e.preventDefault(); this.props.onNavigate(this.props.links.next.href); } handleNavLast(e) { e.preventDefault(); this.props.onNavigate(this.props.links.last.href); } render() { var songs = this.props.songs.map(song => <Song key={song.entity._links.self.href} song={song} songId={this.props.songID} arrangement={this.props.arrangement} status={this.props.status} requestType={this.props.requestType} attributes={this.props.attributes} onUpdate={this.props.onUpdate} onDelete={this.props.onDelete}/> ); return ( <div> {songs} </div> ) } } class Song extends React.Component { constructor(props) { super(props); this.handleDelete = this.handleDelete.bind(this); this.handleUpdate = this.handleUpdate.bind(this); } handleDelete() { this.props.onDelete(this.props.song); } handleUpdate() { this.props.onUpdate(this.props.song); } render() { // songId: {this.props.songId} // arrangement: {this.props.arrangement} // status: {this.props.status} // requestType: {this.props.requestType} // name: {this.props.song.entity.name} // artist: {this.props.song.entity.artist} // album: {this.props.song.entity.album} // songyear: {this.props.song.entity.songyear} // dateadded: {this.props.song.entity.dateadded} // lastplayed: {this.props.song.entity.lastplayed} // playcount: {this.props.song.entity.playcount} //<div className="seq-model"> /*<div> <table> <tbody> <tr> <td> <figure> <img src={"cover?id=" + this.props.song.entity.albumid} alt={this.props.song.entity.albumid} height='150px' width='150px' /> </figure> </td> <td> <p>{this.props.status}</p> <p>{this.props.song.entity.tracknumber}: {this.props.song.entity.name}</p> <p>{this.props.song.entity.album}</p> <p>{this.props.song.entity.artist}</p> <p>{this.props.song.entity.songyear}</p> </td> </tr> </tbody> </table> </div> */ return ( <div > <ul> <li> <div className="col-md-4"> <figure> <img src={"cover?id=" + this.props.song.entity.albumid} alt={this.props.song.entity.albumid} height='200px' width='200px' /> </figure> </div> <div className="col-md-4"> <p>{this.props.status}</p> <p>{this.props.song.entity.tracknumber}: {this.props.song.entity.name}</p> <p>{this.props.song.entity.album}</p> <p>{this.props.song.entity.artist}</p> <p>{this.props.song.entity.songyear}</p> </div> </li> </ul> </div> ) } } export default SongInfo;
quitsmokingApp.BankbookMediator = function(_facade) { var bankbookFacade = _facade; var more_number = 1; var self = this; quitsmokingApp.BankbookMediator.prototype.initalizeBankbookListPage = function() { myCurrentPage = Constants.ViewingPage.BankbookList; more_number = 1; }; quitsmokingApp.BankbookMediator.prototype.appendHtmlBankbookListPage = function(aStatements) { var targetDiv = getJqtCurrentPageWrapper(myCurrentPage); emptyHTML(targetDiv); var html = self.getHtmlForBankbookList(aStatements); var insert = $(html); $(targetDiv).append(insert); }; quitsmokingApp.BankbookMediator.prototype.getHtmlForBankbookList = function(aStatements) { var html = ''; html += '<div class="info">'; html += '<p>개설일 '+mySetting.start_date+'</p>'; html += '<p>총 잔액 '+mySetting.total_amount+' 원<p>'; html += '<p>지난 기간 '+mySetting.d_day+'일</p>'; html += '</div>'; html += '<ul id="statements_list">'; for (var index=0; index < aStatements.rows.length; index++) { var statement = aStatements.rows.item(index); html += '<li class="statement_list">'; html += '<p><span class="date">'+statement['date']+'</span>'; html += '<span class="type'; html += self.getSapnClass(statement['type']); html += '">'+statement['type']+'</span></p>'; html += '<p><span class="detail">'+statement['detail']+'</span>'; html += '<span class="money'; html += self.getSapnClass(statement['type']); html += '">'+statement['money']+'원</span></p>'; html += '</li>'; } html += self.getHtmlForMore(aStatements); html += '</ul>'; return html; }; quitsmokingApp.BankbookMediator.prototype.getHtmlForMore = function(aStatements) { var html = ''; if (aStatements.rows.length==0) return html; if (!(aStatements.rows.length%Constants.Statement.PageView)){ //html += '<li id="more_li"><a href="javascript:" class="more_button" title="'+more_number+'">More'+more_number+'</a></li>'; html += '<li id="more_li"><div style="margin: 10px;"><a href="javascript:" class="whiteButton more_button" title="'+more_number+'">더 보기</a></div></li>'; } return html; }; quitsmokingApp.BankbookMediator.prototype.getSapnClass = function(aType) { var className=''; if (aType == Constants.StatementType.InCome){ className += ' blue'; } else{ className += ' red'; } return className; }; quitsmokingApp.BankbookMediator.prototype.attachEventBankbookListEvents = function() { $(".more_button").click(function(){ $("#more_li").remove(); bankbookFacade.getMoreStatementData(this.title); more_number = more_number + 1; }) }; quitsmokingApp.BankbookMediator.prototype.displayEventBankbookListPage = function() { goToPage(myCurrentPage,'slideleft'); }; quitsmokingApp.BankbookMediator.prototype.appendHtmlMoreBankbookListPage = function(aStatements) { var html =''; for (var index=0; index < aStatements.rows.length; index++) { var statement = aStatements.rows.item(index); html += '<li class="statement_list">'; html += '<p><span class="date">'+statement['date']+'</span>'; html += '<span class="type'; html += self.getSapnClass(statement['type']); html += '">'+statement['type']+'</span></p>'; html += '<p><span class="detail">'+statement['detail']+'</span>'; html += '<span class="money'; html += self.getSapnClass(statement['type']); html += '">'+statement['money']+'원</span></p>'; html += '</li>'; } html += self.getHtmlForMore(aStatements); $("#statements_list").append(html); }; };
import React, {PropTypes} from 'react'; import { View, ScrollView, Text, TextInput, TouchableOpacity, Image, } from 'react-native'; import { connect } from 'react-redux'; import Styles from './Styles/UploadStyle'; //import ImagePicker from 'react-native-image-crop-picker'; //import TagInput from 'react-native-tag-input'; import Actions from '../Actions/Creators'; import Toast from 'react-native-root-toast'; import NativeImagePicker from 'react-native-image-picker'; import { Actions as NavigationActions } from 'react-native-router-flux'; class UploadScreen extends React.Component { constructor (props) { super(props); this.state = { uri: '', path: '', caption: '', tags: [], }; this.handleCamera = this.handleCamera.bind(this); this.handleLibrary = this.handleLibrary.bind(this); this.handleChangeCaption = this.handleChangeCaption.bind(this); this.handleUpload = this.handleUpload.bind(this); this.handleChangeTags = this.handleChangeTags.bind(this); this.onLayoutImageWrapper = this.onLayoutImageWrapper.bind(this); } onLayoutImageWrapper(e) { console.log('onLayout', e.nativeEvent); return true; } shouldComponentUpdate (newProps) { console.log('shouldComponentUpdate', this.props.attempting, newProps.attempting, this.props.errorCode, newProps.errorCode); if (newProps.errorCode && this.props.errorCode != newProps.errorCode) { Toast.show('Oops! ' + newProps.errorCode, { duration: Toast.durations.SHORT, position: Toast.positions.BOTTOM, }); this.props.clearUpload(); return true; } if (this.props.attempting && !newProps.attempting) { const message = newProps.errorCode ? 'Error: ' + newProps.errorCode : 'YAY! Upload successful!'; Toast.show(message, { duration: Toast.durations.SHORT, position: Toast.positions.BOTTOM, }); if (!newProps.errorCode) { //success NavigationActions.photosList(); } return true; } //no message return true; } handleChangeCaption(value) { this.setState({ caption: value, }); } handleChangeTags(tags) { this.setState({ tags: tags, }); } handleCamera () { console.log('CAMERA'); // ImagePicker.openCamera({ // includeBase64: true, // }).then(image => { // this.setState({ // uri: 'data:image/jpeg;base64,' + image.data, // }); // }); NativeImagePicker.launchCamera({ }, (response) => { if (response.didCancel) { console.log('User cancelled image picker'); } else if (response.error) { console.log('ImagePicker Error: ', response.error); } else if (response.customButton) { console.log('User tapped custom button: ', response.customButton); } else { console.log('Picker response', response); this.setState({ uri: 'data:'+ response.type +';base64,' + response.data, path: 'file://' + response.path, }); } }); } handleLibrary () { console.log('LIBRARY'); // ImagePicker.openPicker({ // }).then(image => { // console.log(image); // this.setState({ // uri: image.path, // }); // }); NativeImagePicker.launchImageLibrary({ }, (response) => { if (response.didCancel) { console.log('User cancelled image picker'); } else if (response.error) { console.log('ImagePicker Error: ', response.error); } else if (response.customButton) { console.log('User tapped custom button: ', response.customButton); } else { console.log('Picker response', response); this.setState({ uri: 'data:'+ response.type +';base64,' + response.data, path: 'file://' + response.path, }); } }); } handleUpload() { console.log('handleUpload STATE: ', this.state); this.props.attemptUpload(this.state); } render () { const { uri, caption, path } = this.state; let img = null, form = null; if (uri.length) { img = <Image source={{ uri: path, isStatic: true }} style={Styles.image} ref="preview" />; //const regex = /\s/gi; form = (<View style={Styles.form}> <View style={Styles.textInputContainer}> <TextInput ref="caption" style={Styles.textInput} value={caption} onChangeText={this.handleChangeCaption} underlineColorAndroid="transparent" placeholder={'Name (required!)'} /> </View> {/*<TagInput value={this.state.tags} inputProps={{style: Styles.textInput, underlineColorAndroid: 'transparent'}} regex={regex} onChange={this.handleChangeTags} />*/} <TouchableOpacity style={[Styles.button, Styles.submit]} onPress={this.handleUpload}> <Text style={Styles.buttonText}>{'Upload'}</Text> </TouchableOpacity> </View>); } return ( <View style={Styles.container}> <View style={Styles.imageContainer} onLayout={this.onLayoutImageWrapper}> {img} </View> <View style={Styles.buttonsContainer}> <TouchableOpacity style={Styles.button} onPress={this.handleCamera}> <Text style={Styles.buttonText}>{'Camera'}</Text> </TouchableOpacity> <TouchableOpacity style={Styles.button} onPress={this.handleLibrary}> <Text style={Styles.buttonText}>{'Library'}</Text> </TouchableOpacity> </View> {form} </View> ); } } UploadScreen.propTypes = { // dispatch: PropTypes.func, attemptUpload: PropTypes.func, attempting: PropTypes.bool, clearUpload: PropTypes.func, errorCode: PropTypes.string, // close: PropTypes.func, }; const mapStateToProps = (state) => { return { attempting: state.upload.attempting, errorCode: state.upload.errorCode, }; }; const mapDispatchToProps = (dispatch) => { return { // close: NavigationActions.photosList, attemptUpload: (data) => dispatch(Actions.attemptUpload(data)), clearUpload: () => dispatch(Actions.clearUpload()), }; }; export default connect(mapStateToProps, mapDispatchToProps)(UploadScreen);
import React from "react"; import { App } from "../components"; const Container = (props) => { return <App {...props} />; }; export default Container;
const mongoose = require("mongoose"); mongoose.Promise = global.Promise; const productSchema = new mongoose.Schema({ productId : String, category: String, productName : String, productModel : String, price : Number, quantity : Number } ); const product = mongoose.model("product", productSchema); module.exports = product
'use strict'; var _hello = require('./components/hello.vue'); var _hello2 = _interopRequireDefault(_hello); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var a = 3; //import "babel-polyfill" var Foo = { template: '<div>foo</div>' }; var Bar = { template: '<div>bar</div>' }; // 2. 定义路由 var routes = [{ path: '/foo', component: _hello2.default }, { path: '/bar', component: Bar }]; // 3. 创建 router 实例,然后传 `routes` 配置 var router = new VueRouter({ routes: routes // (缩写)相当于 routes: routes }); // 4. 创建和挂载根实例。 var app = new Vue({ router: router }).$mount('#app');
/* * @lc app=leetcode.cn id=51 lang=javascript * * [51] N 皇后 */ // @lc code=start /** * @param {number} n * @return {string[][]} */ var solveNQueens = function(n) { const solution = [], // 记录最后结果数组 queens = new Array(n).fill(-1), // 记录每一组结果 columns = new Map(), diagonals1 = new Map(), diagonals2 = new Map(); // row 当前遍历到的行 let backtrack = (row) => { if (row == n) { let ans = generateBoard(queens, n) solution.push(ans); return; } else { // 对列进行遍历 for (let i = 0; i < n; i++) { if (columns.has(i)) { continue; } const val1 = row + i; if (diagonals1.has(val1)) continue; const val2 = row - i; if (diagonals2.has(val2)) continue; queens[row] = i; columns.set(i); diagonals1.set(val1); diagonals2.set(val2); backtrack(row + 1); queens[row] = -1; columns.delete(i); diagonals1.delete(val1); diagonals2.delete(val2) } } } backtrack(0); return solution; }; let generateBoard = (queens, n) => { let ans = []; for (let i = 0; i < n; i++) { let res = new Array(n).fill('.'); res[queens[i]] = 'Q'; ans.push(res.join('')); } return ans; } // @lc code=end
import React from "react"; import Square from "./Square"; function Squares({ squares, onClick, onContextMenu }) { return ( <div style={{ display: "flex" }}> {squares.map((square, i) => ( <Square onContextMenu={onContextMenu} squareProps={square} onClick={onClick} key={i} /> ))} </div> ); } export default Squares;
import { combineReducers } from 'redux'; const FETCH_POSTS = 'FETCH_POSTS'; const FETCH_POSTS_COMPLETE = 'FETCH_POSTS_COMPLETE'; const redditDefaultState = [ { data: { author: 'PaquitoSoft' } }, { data: { author: 'Tyler McGuinnis' } }, { data: { author: 'Addy Osmani' } } ]; const redditReducer = (state = redditDefaultState, action) => { switch (action.type) { case FETCH_POSTS: return state; case FETCH_POSTS_COMPLETE: return [...state, ...action.payload]; default: return state; } }; export const rootReducer = combineReducers({ reddit: redditReducer });
import styled from "styled-components"; export const StyledTrackInfo = styled.div` margin: 3vh 0; padding: 5vh; width: 100%; background-color: white; display: flex; flex-flow: column; align-items: center; border-top: black 3px; border-bottom: black 3px; & p span { color: #36324d; font-weight: bold; text-transform: uppercase; margin-right: 1vw; } & h2 { text-transform: uppercase; font-size: 2.5rem; font-weight: bold; } `; export const StyledAlbumInfo = styled(StyledTrackInfo)` background-color: white; `;
const users = { templateUrl: './app/components/user/users/users.html', controller: UsersController }; angular.module('user').component('users', users);
import ResultInfo from '../components/common/ResultInfo'; function NotFound() { return ( <div> <ResultInfo status={"404"} title={"Opps! Halaman yang anda cari tidak ditemukan"} extra={true} typeExtra={"backToHome"} /> </div> ) } export default NotFound
import { connect } from 'react-redux'; import EditDialog from './EditDialog'; import helper from '../../../common/common'; import {fetchAllDictionary, setDictionary2} from '../../../common/dictionary'; import {Action} from '../../../action-reducer/action'; import {getPathValue} from '../../../action-reducer/helper'; import showPopup from '../../../standard-business/showPopup'; const STATE_PATH = ['temp']; const action = new Action(STATE_PATH); const getSelfState = (rootState) => { return getPathValue(rootState, STATE_PATH); }; const changeActionCreator = (key, value) => (dispatch, getState) => { let obj = {[key]: value}; if (key === 'customerId') { const {formValue} = getSelfState(getState()); if (value && formValue.customerId && value.value === formValue.customerId.value) return; obj.consignorId = ''; obj.consigneeId = ''; } dispatch(action.assign(obj, 'formValue')); }; const searchActionCreator = (key, filter, config) => async (dispatch, getState) => { if (key === 'consignorId' || key === 'consigneeId') { const {formValue} = getSelfState(getState()); let options = []; if (formValue.customerId) { const url = `/api/order/input/customer_factory_drop_list`; const data = await helper.fetchJson(url, helper.postOption({customerId: formValue.customerId.value, name: filter, isAll: 1})); if (data.returnCode === 0) { options = data.result || []; } } dispatch(action.update({options}, ['controls'], {key: 'key', value: key})); }else { const {returnCode, result} = await helper.fuzzySearchEx(filter, config); dispatch(action.update({options: returnCode === 0 ? result : undefined}, 'controls', {key: 'key', value: key})); } }; const exitValidActionCreator = () => { return action.assign({valid: false}); }; const okActionCreator = () => async (dispatch, getState) => { const {formValue, value, sections, controls, type} = getSelfState(getState()); if (!helper.validValue(controls, formValue)) { dispatch(action.assign({valid: true})); return; } dispatch(action.assign({confirmLoading: true})); const URL_OK = '/api/config/customer_task'; const body = { ...helper.convert(formValue), taskList: sections.map(item => { const newItem = {...item.dataSource}; newItem.subList = item.options.map(item2 => { return {...item2.dataSource, isCheck: value.includes(item2.value) ? 1 : 0}; }); return newItem; }) }; const {returnCode, returnMsg} = await helper.fetchJson(URL_OK, helper.postOption(body, type === 1 ? 'put' : 'post')); if (returnCode !== 0) { helper.showError(returnMsg); dispatch(action.assign({confirmLoading: false})); return; } helper.showSuccessMsg('操作成功'); dispatch(action.assign({confirmLoading: false, visible: false, res: true})); }; const cancelActionCreator = () => (dispatch) => { dispatch(action.assign({visible: false})); }; const checkboxChangeActionCreator = (arr = []) => { return action.assign({value: arr}); }; const mapStateToProps = (state) => { return getSelfState(state); }; const actionCreators = { onCheckboxChange: checkboxChangeActionCreator, onChange: changeActionCreator, onSearch: searchActionCreator, onExitValid: exitValidActionCreator, onOk: okActionCreator, onCancel: cancelActionCreator }; const URL_BRANCH = '/api/config/customer_task/options/departments'; // 部门 const buildDialogState = async (data, type) => { try { let controls = [ {key: 'customerId', title: '客户', type: type === 0 ? 'search': 'readonly', searchType: 'customer', required: true}, {key: 'consignorId', title: '发货人', type: type === 0 ? 'search': 'readonly', props: {searchWhenClick: true}, required: true}, {key: 'consigneeId', title: '收货人', type: type === 0 ? 'search': 'readonly', props: {searchWhenClick: true}, required: true}, {key: 'businessType', title: '运输类型', type: type === 0 ? 'select': 'readonly', dictionary: 'business_type', required: true}, {key: 'deptmentId', title: '部门', type: type === 0 ? 'search': 'readonly',searchUrl: URL_BRANCH, required: true} ]; const dic = helper.getJsonResult(await fetchAllDictionary()); setDictionary2(dic, controls); const url = `/api/basic/sysDictionary/list`; let json = helper.getJsonResult(await helper.fetchJson(url, helper.postOption({dictionaryCode: 'task_type'}))); let taskTypes = json.data.filter(item => item.active === 'active_activated'); let sections = []; let defaultValue = []; for (let item of taskTypes) { const {dictionaryCode, dictionaryName} = item; let json2 = helper.getJsonResult(await helper.fetchJson(url, helper.postOption({dictionaryCode}))); const options = json2.data.filter(item => item.active === 'active_activated').map(item => { const disabled = Number(item.attributeNumber2 || 0) === 1; disabled && defaultValue.push(item.dictionaryCode); return {dataSource: item, label:item.dictionaryName, value:item.dictionaryCode, disabled: type === 2 ? true : disabled}; }); sections.push({dataSource: item, title: dictionaryName, options}); } let value = []; if (data.taskList) { data.taskList.map(item => { const currentValue = item.subList.filter(item => item.isCheck === 1).map(item => item.dictionaryCode); value = value.concat(currentValue); }) } const titles = ['新增', '编辑', '查看']; const props = { type, title: titles[type], controls, formValue: data, sections, value: type === 0 ? defaultValue : value, visible: true, confirmLoading: false }; global.store.dispatch(action.create(props)); return true; } catch (e) { helper.showError(e.message()); } }; /* * 功能:新增、编辑、查看对话框 * 参数:data - 记录信息 * type - 0:新增 1:编辑 2:查看 * 返回:成功返回true,取消或关闭返回空 * */ export default async (data, type) => { if (false === await buildDialogState(data, type)) return; const Container = connect(mapStateToProps, actionCreators)(EditDialog); return showPopup(Container, {}, true); };
export const getEmployees = () => { return fetch('/employees') .then(response => response.json()) .then(data => { return {employees: data}; }); }; export const getEmployee = (id) => { return fetch(`/employees/${id}`) .then(response => response.json()) .then(data => data) }; export const getTrainings = () => { return fetch('/trainings') .then(response => response.json()) .then(data => { return {trainings: data}; }); };
import React, { userEffect, useState} from 'react'; import { StyleSheet, Text, View, TouchableWithoutFeedback, Keyboard, StatusBar, } from 'react-native'; import { TextInputMask } from 'react-native-masked-Text'; export default function App() { const [state, setState] = React.useState(0); return ( <View style={styles.container}> <TouchableWithoutFeedback onPress={Keyboard.dismiss}> <view> <Text style={styles.title}>Academia em Casa</Text> <Text style={styles.label}>De segunda a quarta (braço e antebraço) </Text> <TextInputMask style={styles.textInput} type={'custom'} options={{ Mask: '(99)' , }} /> <view style={styles.box}> <Text style={style.textBox}> Para cuidar da saude algumas das maneiras sao: praticando exercicios fisicos, se alimentando bem, bebendo agua e dormindo !! </Text> </view> <Text style={styles.label}>De quinta a sábado (perna e panturrilha) </Text> <StatusBar style="auto" /> </view> </TouchableWithoutFeedback> </View> ); } const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: '#fff', marginHorizontal: '16', marginVertical: '40', }, title:{ fontSize:40, fontWeight: 'bold', color: '#3C5E45', }, label: { marginTop: 20, fontSize: 18, color: '#515753'}, textBox: { margin: 20, fontSize: 18, color:'#515753' }, box: { backgroundColor: '#EBFBEF', marginTop: 20}, textInput: 40, height: 40, width: '80%', margin: 10, color: '#737A75', borderColor: '#515753', borderBottonWidth: 1, }, );
var app = angular .module("myApp", []) .controller("myController", function($scope, $http) { $scope.data = [ { "ht": "Section1", "pt": "Hello I am first section" }, { "ht": "Section2", "pt": "Second One " }, { "ht": "Section3", "pt": "Third One" }, { "ht": "Section4", "pt": "The Last One" } ]; $scope.accord = { value: 'Section1' }; });
(function(G){G['i18n']={lc:{"en":function(n){return n===1?"one":"other"}}, c:function(d,k){if(!d)throw new Error("MessageFormat: Data required for '"+k+"'.")}, n:function(d,k,o){if(isNaN(d[k]))throw new Error("MessageFormat: '"+k+"' isn't a number.");return d[k]-(o||0)}, v:function(d,k){i18n.c(d,k);return d[k]}, p:function(d,k,o,l,p){i18n.c(d,k);return d[k] in p?p[d[k]]:(k=i18n.lc[l](d[k]-o),k in p?p[k]:p.other)}, s:function(d,k,p){i18n.c(d,k);return d[k] in p?p[d[k]]:p.other}} i18n["ch/maenulabs/validation/AtLeastCheck"]={ "message":function(d){return "Must be at least "+i18n.v(d,"amount")}} i18n["ch/maenulabs/validation/AtMostCheck"]={ "message":function(d){return "Must be at most "+i18n.v(d,"amount")}} i18n["ch/maenulabs/validation/ExistenceCheck"]={ "message":function(d){return "Is required"}} i18n["ch/maenulabs/validation/GreaterThanCheck"]={ "message":function(d){return "Must be greater than "+i18n.v(d,"amount")}} i18n["ch/maenulabs/validation/LessThanCheck"]={ "message":function(d){return "Must be less than "+i18n.v(d,"amount")}} i18n["ch/maenulabs/validation/StringLengthRangeCheck"]={ "minimum":function(d){return "Must be at least "+i18n.p(d,"amount",0,"en",{"one":"1 character","other":i18n.n(d,"amount")+" characters"})+" long"}, "maximum":function(d){return "Must be at most "+i18n.p(d,"amount",0,"en",{"one":"1 character","other":i18n.n(d,"amount")+" characters"})+" long"}} })(this);
import React, { Component } from "react"; import PropTypes from "prop-types"; import http from "../../server/httpService"; import { Highlight } from "react-instantsearch-dom"; import AlgoliaSearchBar from "../searchBar/AlgoliaSearchBar"; import ResultText from "../result/ResultSections"; import { RegexResults } from "../helper/regexService"; import Tappable from "react-tappable/lib/Tappable"; const urlLaw = "https://www.radiumlaw.com/api/"; class Result extends Component { state = { query: "", sectionNum: "", lawName: "", sectionText: "", sectionTitle: "", codeTitle: "", SectionId: "", laws: [], scrollIcon: false, }; async componentDidMount() {} getLaws = async () => { var urlId = urlLaw + this.state.SectionId; try { const { data: laws } = await http.get(urlId); console.log(laws); this.setState({ laws }); } catch (ex) { if (ex.response && ex.response === 404) alert("error receiving data"); } }; onSuggestionSelected = async (_, { suggestion }) => { const sectionNum = suggestion.section_num; const lawName = suggestion.law_code; const sectionTitle = suggestion.heading; const sectionText = suggestion.content_xml; const codeTitle = suggestion.code_title; const SectionId = suggestion._id.$oid; const scrollIcon = this.state.scrollIcon; this.setState({ sectionNum, lawName, sectionText, sectionTitle, codeTitle, SectionId, laws: [], scrollIcon: !scrollIcon, }); }; onSuggestionCleared = () => { this.setState({ query: "", }); }; showIcon = () => { let sectionText = this.state.sectionText; if (sectionText) { return ( <div> <Tappable onTap={this.handleClick}>Expand</Tappable> <i style={{ cursor: "pointer" }} onClick={() => this.handleClick()} className="fas fa-caret-down fa-3x " ></i> </div> ); } else return null; }; handleClick = (e) => { const scrollIcon = this.state.scrollIcon; this.getLaws(); this.setState({ scrollIcon: !scrollIcon }); }; render() { const { HideShowSearch } = this.props; const { sectionNum, sectionTitle, codeTitle, laws, } = this.state; const sectionTxt = RegexResults(this.state.sectionText); return ( <div className="container" style={{ textAlign: "justify", marginTop: "10px", zIndex: 1, position: "absolute", }} > <AlgoliaSearchBar query={this.state.query} HideShowSearch={HideShowSearch} codeTitle={this.state.codeTitle} sectionTitle={this.state.sectionTitle} sectionNum={sectionNum} onSuggestionCleared={this.onSuggestionCleared} onSuggestionSelected={this.onSuggestionSelected} /> <ResultText codeTitle={codeTitle} sectionTitle={sectionTitle} sectionTxt={sectionTxt} splitLaw={this.splitLaw} sectionNum={sectionNum} laws={laws} /> <div className="text-center">{this.showIcon()}</div> </div> ); } } function Hit(props) { return ( <div> <Highlight attribute="section_text" hit={props.hit} /> </div> ); } Hit.propTypes = { hit: PropTypes.object.isRequired, }; export default Result;
"use strict"; /*global alert: true, console: true, is, ODSA */ /* * For queries & switch cases, follow the numbering below: * Hash Functions (hashFunct): * 1. Simple Mod Hash * 2. Binning Hash * 3. Mid-Square Hash * 4. Simple Hash for Strings * 5. Improved Hash for Strings * * Collision Resolutions (collision): * 1. Linear Probing * 2. Linear Probing by Stepsize of 2 * 3. Linear Probing by Stepsize of 3 * 4. Pseudo-Random Probing * 5. Quadratic Probing * 6. Double Hashing (Prime) * 7. Double Hashing (Power-of-2) * * Table Size (tableSize): * Number between 1 and 16 * * Key Range (keyrange): * 1. 0-99 * 2. 0-999 * * M-value (m): * - A prime number (if collision=6) * - A power-of-2 (if collision=7) * * To handle queries: * Set the hashFunct, collision, tableSize, keyrange and m according to the reference above * For example, to choose Mid-Square Hash with pseudo-random probing, you would use: * hash.html?hashFunct=3&collision=4 */ /* The fun starts here */ (function ($) { /* * Queue Data Structure * Created by Stephen Morley - http://code.stephenmorley.org * Released under the terms of Creative Commons */ function Queue() { // initialise the queue and offset var queue = []; var offset = 0; /* Returns true if the queue is empty, and false otherwise. */ this.isEmpty = function () { return (queue.length === 0); }; /* Returns the length of the queue */ this.getLength = function () { return (queue.length - offset); }; /* Enqueues the specified item. */ this.enqueue = function (item) { queue.push(item); }; /* Dequeues an item and returns it. If the queue is empty then undefined is * returned. */ this.dequeue = function () { // if the queue is empty, return undefined if (queue.length === 0) { return undefined; } // store the item at the front of the queue var item = queue[offset]; // increment the offset and remove the free space if necessary if (++offset * 2 >= queue.length) { queue = queue.slice(offset); offset = 0; } // return the dequeued item return item; }; } /* End Queue */ /* * Primality testing code * * Copyright (c) 2011 Alexei Kourbatov, www.JavaScripter.net * All information on these Web sites, JavaScripter.net or JavaScripter.com, is provided "AS IS", without warranties of any * kind. I can change it at any time, without notice. * * Permission is hereby granted to use this information for educational purposes only. You are not allowed to get money for * re-distribution of this information or remove any copyright notices from these pages or code. If you want to make a mirror * of this Web site or otherwise re-distribute the information or code found on this site or make any commercial use of this * information or code, do ask me via e-mail: webmaster(at)javascripter.net. * * All trademarks are the property of their respective owners and are used here for information purposes only. JavaScript is * a trademark of Oracle Corporation. * * Courtesy of http://www.javascripter.net/faq/primefactors.txt */ /** * function leastFactor(n) returns: * the smallest prime that divides n * NaN if n is NaN or Infinity * 0 if n is 0 * 1 if n = 1, n = -1, or n is not an integer */ var leastFactor = function (n) { if (isNaN(n) || !isFinite(n)) { return NaN; } if (n === 0) { return 0; } if (n % 1 || n * n < 2) { return 1; } if (n % 2 === 0) { return 2; } if (n % 3 === 0) { return 3; } if (n % 5 === 0) { return 5; } var m = Math.sqrt(n); for (var i = 7; i <= m; i += 30) { if (n % i === 0) { return i; } if (n % (i + 4) === 0) { return i + 4; } if (n % (i + 6) === 0) { return i + 6; } if (n % (i + 10) === 0) { return i + 10; } if (n % (i + 12) === 0) { return i + 12; } if (n % (i + 16) === 0) { return i + 16; } if (n % (i + 22) === 0) { return i + 22; } if (n % (i + 24) === 0) { return i + 24; } } return n; }; /** * Optimized version of leastFactor for Opera, Chrome, Firefox * In these browsers, "i divides n" is much faster as * (q = n / i) === Math.floor(q) than n % i === 0 */ if (navigator.userAgent.indexOf('Opera') !== -1 || navigator.userAgent.indexOf('Chrome') !== -1 || navigator.userAgent.indexOf('Firefox') !== -1) { leastFactor = function (n) { if (isNaN(n) || !isFinite(n)) { return NaN; } if (n === 0) { return 0; } if (n % 1 || n * n < 2) { return 1; } if (n % 2 === 0) { return 2; } if (n % 3 === 0) { return 3; } if (n % 5 === 0) { return 5; } var q, m = Math.sqrt(n); for (var i = 7; i <= m; i += 30) { if ((q = n / i) === Math.floor(q)) { return i; } if ((q = n / (i + 4)) === Math.floor(q)) { return i + 4; } if ((q = n / (i + 6)) === Math.floor(q)) { return i + 6; } if ((q = n / (i + 10)) === Math.floor(q)) { return i + 10; } if ((q = n / (i + 12)) === Math.floor(q)) { return i + 12; } if ((q = n / (i + 16)) === Math.floor(q)) { return i + 16; } if ((q = n / (i + 22)) === Math.floor(q)) { return i + 22; } if ((q = n / (i + 24)) === Math.floor(q)) { return i + 24; } } return n; }; } /** * function isPrime(n) returns: * - false if n is NaN or not a finite integer * - true if n is prime * - false otherwise */ var isPrime = function (n) { if (isNaN(n) || !isFinite(n) || n % 1 || n < 2) { return false; } if (n === leastFactor(n)) { return true; } return false; }; /* End Primality test code */ function isPowerOf2(m) { /*jslint bitwise: true */ return !(isNaN(m) || !isFinite(m) || m < 1 || ((m - 1) & m) === 0); } /* Variables */ var jsav, // JSAV defCtrlState, // Stores the default state of the controls defTableSizeOptions, // Stores the HTML of the default table size options arr, // JSAV Array nextStep = new Queue(), // A queue containing 'steps' to be played when the user clicks 'Next' slotPerm = [0]; // A permutation of slots for pseudo random probing, must be a global so that // the same permutation is used each time // Process About button: Pop up a message with an Alert function about() { alert("Shellsort Algorithm Visualization\nWritten by Nayef Copty, Mauricio De la Barra, Daniel Breakiron, and Cliff Shaffer\nCreated as part of the OpenDSA hypertextbook project\nFor more information, see http://opendsa.org.\nSource and development history available at\nhttps://github.com/cashaffer/OpenDSA\nCompiled with JSAV library version " + JSAV.version()); } /** * Wrapper class for error messages */ function error(message) { jsav.umsg(message, {"color" : "red"}); jsav.umsg("<br />"); } /** * Sets the default state for the controls based on the query parameters */ function setDefaultControlState() { defCtrlState = {}; defCtrlState.hashFunct = 0; defCtrlState.collision = 0; defCtrlState.tableSize = 0; defCtrlState.keyrange = 0; defCtrlState.m = ''; // Update the default control state based on the query parameters var params = JSAV.utils.getQueryParameter(); // Set hash function if (params.hashFunct) { if (params.hashFunct > 0 && params.hashFunct <= 5) { defCtrlState.hashFunct = params.hashFunct; // Disable so user can't change the value set by parameter $('#function').attr('disabled', 'disabled'); } else { console.error("Invalid URL parameter method: " + params.hashFunct); } } // Set collision resolution policy if (params.collision) { if (params.collision > 0 && params.collision <= 7) { defCtrlState.collision = params.collision; // Disable so user can't change the value set by parameter $('#collision').attr('disabled', 'disabled'); } else { console.error("Invalid URL parameter collision: " + params.collision); } } // Set table size if (params.tableSize) { if (params.tableSize > 0 && params.tableSize <= 16) { defCtrlState.tableSize = params.tableSize; // Disable so user can't change the value set by parameter $('#tablesize').attr('disabled', 'disabled'); } else { console.error("Invalid URL parameter tableSize: " + params.tableSize); } } // Set keyrange if (params.keyrange) { if (params.keyrange > 0 && params.keyrange <= 2) { defCtrlState.keyrange = params.keyrange; // Disable so user can't change the value set by parameter $('#keyrange').attr('disabled', 'disabled'); } else { console.error("Invalid URL parameter keyrange: " + params.keyrange); } } // Set M-value if (params.m) { if (params.m > 0) { defCtrlState.m = params.m; // Disable so user can't change the value set by parameter $('#M').attr('disabled', 'disabled'); } else { console.error("Invalid URL parameter m: " + params.m); } } } /** * Instruct the user on what fields they are missing and clear and redraw the hash table */ function resetAV() { // Display a message telling them what fields they need to select jsav.clearumsg(); var missingFields = []; // Ensure user selected a hash function var funct = Number($('#function').val()); if (funct === 0) { missingFields.push('hash function'); } else { jsav.umsg('Algorithm Selected: ' + $("#function option:selected").text()); // If user selected binning, make sure they selected a key range too if (funct === 2) { if ($('#keyrange').val() === '0') { missingFields.push('key range'); } else { jsav.umsg('Key Range Selected: ' + $("#keyrange option:selected").text()); } } } // Ensure user selected a collision resolution policy var coll = Number($('#collision').val()); if (coll === 0) { missingFields.push('collision policy'); } else { jsav.umsg('Collsion Policy Selected: ' + $("#collision option:selected").text()); // Ensure a valid M-value is provided for double hashing policies var M = Number($('#M').val()); if (coll === 6) { // Double hashing (prime) $('#mValue').show(); $('#M').attr('placeholder', 'Prime Number'); if (isPrime(M)) { jsav.umsg('Prime Number Selected: ' + $("#M").val()); } else { missingFields.push('prime number M'); } } else if (coll === 7) { // Double hashing (power-of-2) $('#mValue').show(); $('#M').attr('placeholder', 'Power-of-2'); if (isPowerOf2(M)) { jsav.umsg('Power-of-2 Selected: ' + M); } else { missingFields.push('power-of-2 M'); } } else { $('#mValue').hide(); } } // Ensure user selected a table size if ($('#tablesize').val() === '0') { missingFields.push('table size'); } // Craft an appropriate message to the user, telling them what fields they are missing if (missingFields.length > 0) { // Disable the input box if fields are missing $("#input").attr("disabled", "disabled"); var msg = 'Please select a ' + missingFields.join(', '); var commaIndex = msg.lastIndexOf(","); if (commaIndex > -1) { msg = msg.substring(0, commaIndex) + ' and' + msg.substring(commaIndex + 1, msg.length); } jsav.umsg(msg); } else { // If all necessary fields are selected, enable the input box and tell the user to begin $("#input").removeAttr("disabled"); jsav.umsg("Enter a value and click Next"); jsav.umsg("<br />"); } // Draw new array var size = $('#tablesize').val(); var htmlData = ""; for (var i = 0; i < size; i++) { htmlData += "<li></li>"; } var hashTable = $('#hashTable'); hashTable.html(htmlData); // Create a new JSAV array arr = jsav.ds.array(hashTable, {indexed: true, layout: "vertical", center: false}); // Make sure the queue is clear and state variables are reset nextStep = new Queue(); slotPerm = [0]; // TODO - might be able to combine this with the loop above // Append a span containing the count to each index $('li.jsavindex').each(function (index, item) { $(item).append('<span id="' + index + '_count" class="jsavindexlabel countlabel" style="display: none;">1</span>'); }); } function setFunction() { // Reset the array size options list (if currently shows values for mid-square) if ($('#tablesize option').length === 3) { // Save the value the user has selected var size = $("#tablesize").val(); $("#tablesize").html(defTableSizeOptions); // Select the value the user previously had selected $("#tablesize").val(size); } // Disable and hide keyrange dropdown $('#keyrange').hide(); // Display Appropriate Message and Enable Appropriate Controls for each function switch ($('#function').val()) { // Prompt user to select a function case '0': $('#input').attr("disabled", "disabled"); break; // Binning case '2': // Enable key range $('#keyrange').show(); break; // Mid Square case '3': // Change array size options to only 8 and 16 $("#tablesize").html('<option value="0">Table Size</option><option value="8">8</option><option value="16">16</option>'); break; } // Refresh the AV display when the function is changed resetAV(); } /** * Reset all controls to their default state */ function resetControls() { $("#function").val(defCtrlState.hashFunct); $("#collision").val(defCtrlState.collision); $("#tablesize").val(defCtrlState.tableSize); $("#keyrange").val(defCtrlState.keyrange); $("#M").val(defCtrlState.m); if (defCtrlState.m === '') { $('#mValue').hide(); } setFunction(); // Clear input textbox and disable next button $("#input").val(""); $('#next').attr("disabled", "disabled"); } /** * Resets the visualization */ function reset() { // Clear any existing messages and hash table data jsav.clearumsg(); $('#hashTable').html(''); // Reset controls to their default state resetControls(); // Make sure the queue is empty nextStep = new Queue(); } function loadNextSlide() { var step = nextStep.dequeue(); if (step.canInsert) { if (step.insert) { // Insertion step jsav.umsg("Inserting " + step.value + " at position " + step.position + "."); jsav.umsg("<br>"); arr.unhighlight(step.position); arr.value(step.position, step.value); } else { // Highlighting step jsav.umsg("Attempting to insert " + step.value + " at position " + step.position + "."); arr.unhighlight(); arr.highlight(step.position); } } // Disable Next Button & re-enable input field if queue is empty if (nextStep.isEmpty()) { // Clear, enable and set the focus to the input textbox $("#input").val(""); $("#input").removeAttr("disabled"); $("#input").focus(); // Disable the next button $('#next').attr("disabled", "disabled"); // If array is full at the end of dequeue, display message if (!step.canInsert) { var errorMsg; if (step.arrayFull) { errorMsg = "Array is full. Insertion failed. Please Restart."; // User has been informed the array is full and they // must restart, so disable the input textbox //$('#input').attr("disabled", "disabled"); } else { errorMsg = "Array is not full, but number of insertion attempts is greater than array size. Insertion failed."; } error(errorMsg); arr.unhighlight(); } } else { // Set the focus to the 'Next' button so users can click 'Enter' to trigger the next step $("#next").focus(); } } /* Hashing Functions */ // Simple mod function function simpleMod(inputVal) { // Check that the input value is a number and within the correct range if (inputVal < 0 || inputVal > 99999 || isNaN(inputVal)) { error("Please enter a number in the range of 0-99999"); // Return error return 1; } // Simple Mod Function var pos = inputVal % arr.size(); jsav.umsg("Hash position = Input Value % Table Size"); jsav.umsg("Hash position = " + inputVal + " % " + arr.size() + ' = ' + pos); // Process function with selected collision resolution determineResolution(inputVal, pos, false, true); // Return success return 0; } // Binning Function function binning(inputVal) { var keyrange = $("#keyrange").val(); // Check that a key range has been selected if ((Number(keyrange)) === 0) { error("Please select a key range."); // Return error return 1; } else { // Key range selected switch (keyrange) { case '1': keyrange = 100; break; case '2': keyrange = 1000; break; } // Check that the input value is a number within the correct range if (inputVal < 0 || inputVal >= keyrange || isNaN(inputVal)) { error("Please enter an input value between 0 and " + keyrange - 1 + "."); // Return Error return 1; } else { // Valid input jsav.umsg("Attempting to insert: " + inputVal); // Binning function Position var binsize = keyrange / $("#tablesize").val(); var pos = Math.floor(inputVal / binsize); jsav.umsg("Bin Size = Key Range / Table Size"); jsav.umsg("Bin Size = " + keyrange + " / " + $("#tablesize").val() + " = " + binsize.toFixed(2)); jsav.umsg("Hash Position = Input Value / Bin Size"); jsav.umsg("Hash Position = " + inputVal + " / " + binsize.toFixed(2) + " = " + pos); // Process function with selected collision resolution determineResolution(inputVal, pos, false, true); // Return success return 0; } } } // Mid-Square Method function midSquare(inputVal) { // Check that input is a number within the correct range if (inputVal > 65536 || inputVal < 0 || isNaN(inputVal)) { error("Please enter a value in the range of 0-65536"); // Return error return 1; } jsav.umsg("Attempting to insert: " + inputVal); var size = Number($("#tablesize").val()); var strpadding = "00000000"; var modVal = 256; if (size === 16) { strpadding = "0000000000000000"; modVal = 65536; } // Square Input Value var squaredInput = (inputVal * inputVal) % modVal; // Convert squaredInput to base 2 and pad it to the correct length var binaryDigit = (strpadding + squaredInput.toString(2)).substr(size * -1); // Get the middle bits var len = size / 4; var start = (size - len) / 2; var middleBits = binaryDigit.substr(start, len); // Highlight the middle bits binaryDigit = binaryDigit.substring(0, start) + '<span style="color: red">' + middleBits + '</span>' + binaryDigit.substring(start + len, binaryDigit.length); // Convert Middle Bits to Decimal var pos = parseInt(middleBits, 2); jsav.umsg(inputVal + " * " + inputVal + " % " + modVal + " = " + squaredInput); jsav.umsg(size + "-bit binary digit = " + binaryDigit); jsav.umsg("Middle four bits = " + middleBits); jsav.umsg("Hash position = " + pos); // Process function with selected collision resolution determineResolution(inputVal, pos, false, true); // Return success return 0; } // Simple hashing for strings // - inputVal should be a string, however a number in a string is acceptable (e.g. "123") function simpleStrings(inputVal) { // Check input is a string if (inputVal === null) { error("Please enter a value to hash."); // Return error return 1; } jsav.umsg("Attempting to insert: " + inputVal); // Sum of string's ASCII number var sum = 0; for (var i = 0; i < inputVal.length; i++) { sum += inputVal.charCodeAt(i); } // Table Size var size = $("#tablesize").val(); // Position is the sum mod the table size var pos = sum % size; jsav.umsg("The sum is " + sum); jsav.umsg("Hash value: " + sum + " % " + size + " = " + pos); // Process function with selected collision resolution determineResolution(inputVal, pos, false, true); // Return success return 0; } // Hashing for Strings (Improved) // - inputVal should be a string, however a number in a string is acceptable (e.g. "123") function improvedStrings(inputVal) { // Check input is a string if (inputVal === null) { error("Please enter a value to hash."); // Return error return 1; } jsav.umsg("Attempting to insert " + inputVal); var inputLength = inputVal.length / 4; var sum = 0; var mult; for (var i = 0; i < inputLength; i++) { // Grab the substring of size 4 var inputsubstring = inputVal.substring(i * 4, (i * 4) + 4); mult = 1; for (var j = 0; j < inputsubstring.length; j++) { sum += inputsubstring.charCodeAt(j) * mult; mult *= 256; } } var size = $("#tablesize").val(); var pos = sum % size; jsav.umsg("The sum is " + sum); jsav.umsg("Hash value: " + sum + " % " + size + " = " + pos); // Process function with selected collision resolution determineResolution(inputVal, pos, false, true); // Return success return 0; } /* Collision Resolutions */ // Function that determines which collision resolution to pick function determineResolution(inputVal, pos, showCounts, printPerm) { var collisionResolution = $("#collision").val(); var ret = 0; var stepSize; switch (collisionResolution) { // No function chosen case '0': reset(); break; case '1': ret = linearProbing(inputVal, pos, showCounts, 1); break; case '2': ret = linearProbing(inputVal, pos, showCounts, 2); break; case '3': ret = linearProbing(inputVal, pos, showCounts, 3); break; case '4': ret = pseudoRandom(inputVal, pos, showCounts, printPerm); break; case '5': ret = quadraticProbing(inputVal, pos, showCounts); break; case '6': stepSize = doubleHashPrime(inputVal, showCounts); ret = linearProbing(inputVal, pos, showCounts, stepSize); break; case '7': stepSize = doubleHashPowerOf2(inputVal, showCounts); ret = linearProbing(inputVal, pos, showCounts, stepSize); break; } return ret; } // Linear Probing function linearProbing(inputVal, pos, showCounts, stepSize) { // Counter that counts how many times the loop ran var count = 0; var arrayFull = false; var canInsert = true; // Loop across the array. "infinite" loop. Breaks if array is full. for (;;) { // If space is available, break if (String(arr.value(pos)) === "") { break; } // If array is full, break out if (count === arr.size()) { // Tried to insert everywhere the algorithm would let us, failed canInsert = false; // Assume the array is full, since insertion failed arrayFull = true; if (stepSize > 1) { // Checking if there are any empty slots, even when count === arr.size() for (var b = 0; b < arr.size(); b++) { if (String(arr.value(b)) === "") { arrayFull = false; break; } } } break; } // Insert attempt as highlighting activity if (!showCounts) { enqueueStep(pos, inputVal, false, arrayFull, canInsert); } pos += stepSize; // Wrap around to the beginning of the array if (pos >= arr.size()) { pos %= arr.size(); } // Increment count count++; } // Empty spot found. Insert element inputVal at pos if (!showCounts) { enqueueStep(pos, inputVal, true, arrayFull, canInsert); } else { return pos; } } // Pseudo-Random Probing function pseudoRandom(inputVal, pos, showCounts, printPerm) { var arrayFull = false; var canInsert = true; // Cast into a number, otherwise '0' will be considered false. if ((Number(arr.value(pos))) !== false) { var i, j, rnum, temp; // If not already done, create a random permutation if (slotPerm.length < arr.size()) { for (i = 1; i < arr.size(); i++) { slotPerm[i] = i; } // Now, randomize for (i = 1; i < arr.size(); i++) { rnum = Math.ceil(Math.random() * (arr.size() - 1)); temp = slotPerm[i]; slotPerm[i] = slotPerm[rnum]; slotPerm[rnum] = temp; } } if (printPerm) { jsav.umsg("Permutation: " + slotPerm.join(' ')); } // Counter that counts how many times the loop ran var count = 0; // Current index of array of permutations var currIndex = 1; // Position to check, will point to the correct position at the end of the loop temp = pos; // Loop across the array. "infinite" loop. Breaks if array is full. for (;;) { // If space is available, break if (String(arr.value(temp)) === "") { break; } // If array is full, break out if (count === arr.size()) { // Tried to insert everywhere the algorithm would let us, failed canInsert = false; // Assume the array is full, since insertion failed, but check for any empty slots arrayFull = true; for (var b = 0; b < arr.size(); b++) { if (String(arr.value(b)) === "") { arrayFull = false; break; } } break; } // Insert attempt as highlighting activity if (!showCounts) { enqueueStep(temp, inputVal, false, arrayFull, canInsert); } // Calculate next position to check by adding the next random slot to the original position temp = pos + slotPerm[currIndex]; currIndex++; // Wrap around to the beginning of the array if (temp >= arr.size()) { temp %= arr.size(); } // Increment count count++; } // Empty spot found. Insert element inputVal at temp pos = temp; } if (!showCounts) { enqueueStep(pos, inputVal, true, arrayFull, canInsert); } else { return pos; } } // Quadratic Probing function quadraticProbing(inputVal, pos, showCounts) { var arrayFull = false; var canInsert = true; // Temp pointer that will point to the correct position at the end of the loop var temp = pos; // Counter that counts how many times the loop ran var count = 0; // i for the quadratic probing var i = 1; // Loop across the array. "infinite" loop. Breaks if array is full. for (;;) { // If space is available, break if (String(arr.value(temp)) === "") { break; } // If array is full, break out if (count === arr.size()) { // Tried to insert everywhere the algorithm would let us, failed canInsert = false; // Assume the array is full, since insertion failed, but check for any empty slots arrayFull = true; for (var b = 0; b < arr.size(); b++) { if (String(arr.value(b)) === "") { arrayFull = false; break; } } break; } // Insert attempt as highlighting activity if (!showCounts) { enqueueStep(temp, inputVal, false); } // Calculate the next position to check by adding the square of i to the original position, increment i temp = pos + i * i; i++; // Wrap around to the beginning of the array if (temp >= arr.size()) { temp %= arr.size(); } // Increment count count++; } // Empty spot found. Insert element inputVal at temp if (!showCounts) { enqueueStep(temp, inputVal, true); } else { return temp; } } /** * Calculates the step size for double hashing collision policy using a prime number M */ function doubleHashPrime(inputVal, showCounts) { var M = Number($('#M').val()); if (!isPrime(M)) { error("Please enter a valid prime number M"); // Return error return 1; } var stepSize = 1 + (inputVal % (M - 1)); if (!showCounts) { jsav.umsg("Step size = 1 + (Input Value % (M - 1))"); jsav.umsg("Step size = 1 + (" + inputVal + " % (" + M + " - 1)) = " + stepSize); } return stepSize; } /** * Calculates the step size for double hashing collision policy using a power of 2 */ function doubleHashPowerOf2(inputVal, showCounts) { var M = Number($('#M').val()); // Test if its a valid power of 2 if (!isPowerOf2(M)) { error("Please enter a valid power of 2 M"); // Return error return 1; } var stepSize = ((inputVal % (M / 2)) * 2) + 1; if (!showCounts) { jsav.umsg("Step size = ((Input Value % (M / 2)) * 2) + 1"); jsav.umsg("Step size = ((" + inputVal + " % (" + M + " / 2)) * 2) + 1 = " + stepSize); } return stepSize; } /** * Adds a step to the queue * pos - array position to perform an action * val - the value to insert * arrayFull - true if entire array is full * canInsert - true if pos is empty and insertion can take place * false if all positions the resolution algorithm attempts are full */ function enqueueStep(pos, val, insert, arrayFull, canInsert) { // Create an queue a highlight step var step = { 'position': pos, 'value': val, 'insert': false, 'arrayFull': arrayFull, 'canInsert': canInsert }; nextStep.enqueue(step); // Queue an insertion step too, if applicable if (insert && canInsert) { step = { 'position': pos, 'value': val, 'insert': true, 'arrayFull': arrayFull, 'canInsert': canInsert }; nextStep.enqueue(step); } } /** * Runs when page has finished loading * Anything that triggers an interaction with an HTML element should be done here */ $(document).ready(function () { jsav = new JSAV($('.avcontainer')); /* Key Presses */ $('#M').keyup(function (event) { resetAV(); }); $('#M').keypress(function (event) { // Capture 'Enter' press if (event.which === 13) { // Prevent 'Enter' from posting the form and refreshing the page event.preventDefault(); } }); $('#keyrange').change(function () { resetAV(); }); // If the user hits 'Enter' while the focus is on the textbox, // click 'Next' rather than refreshing the page $("#input").keypress(function (event) { // Capture 'Enter' press if (event.which === 13) { // Prevent 'Enter' from posting the form and refreshing the page event.preventDefault(); // If the user entered a value and inserting is allowed, trigger 'Next' if ($("#input").val() !== "" && !$('#next').attr('disabled')) { $('#next').click(); } } else { // Enable the 'Next' button when the user enters a value $('#next').removeAttr('disabled'); } }); /* Event Triggers */ // Event trigger change if hashing function option is changed $("#function").change(function () { setFunction(); }); // Event trigger change if collision function option is changed $("#collision").change(function () { resetAV(); }); // Event trigger change if size of hash changes $("#tablesize").change(function () { resetAV(); }); /* Next button pushed. * If no slide show exits, make one. * Else, load next slide */ $('#next').click(function () { var ret = 1; if (nextStep.isEmpty()) { // Perform first step // Input field value var inputVal = $("#input").val(); // Log the state of the exercise var state = {}; state.user_function = $("#function option:selected").text(); state.user_collision = $("#collision option:selected").text(); state.user_tablesize = $("#tablesize option:selected").text(); state.user_keyrange = $("#keyrange option:selected").text(); state.user_mValue = $("#mValue").val(); state.hash_table = arr.toString(); state.user_input = inputVal; ODSA.AV.logExerciseInit(state); // Disable input field to process it safely $("#input").attr("disabled", "disabled"); // Process input with selected function switch ($("#function").val()) { case '0': // No function chosen reset(); break; case '1': ret = simpleMod(inputVal); break; case '2': ret = binning(inputVal); break; case '3': ret = midSquare(inputVal); break; case '4': ret = simpleStrings(inputVal); break; case '5': ret = improvedStrings(inputVal); break; } // Show first slide if success if (ret === 0) { loadNextSlide(); } else { // Error occurred, re-enable input textfield console.error('Error occurred when hashing ' + inputVal); $("#input").removeAttr("disabled"); } } else { // Load next slide loadNextSlide(); var i; var tableSize = $("#tablesize").val(); var tableCount = []; // Reset counts to 0 for (i = 0; i < tableSize; i++) { tableCount[i] = 0; $('#' + i + '_count').html(0); } // Recalculate the counts for (i = 0; i < tableSize; i++) { ret = determineResolution(0, i, true, false); var count = tableCount[ret]; count++; tableCount[ret] = count; $('#' + ret + '_count').html(count); } } }); // Connect action callbacks to the HTML entities $('#about').click(about); $('#reset').click(reset); $('#help').click(function () { window.open("hashAVHelp.html", 'helpwindow'); }); $('#showcounts').click(function () { if ($('.countlabel').css('display') === 'none') { $('.countlabel').show(); $('#showcounts').val('Hide Counts'); } else { $('.countlabel').hide(); $('#showcounts').val('Show Counts'); } }); // create a new settings panel and specify the link to show it var settings = new JSAV.utils.Settings($(".jsavsettings")); // Set the default state for the controls setDefaultControlState(); // Get the default HTML for the tablesize dropdown list defTableSizeOptions = $('#tablesize').html(); // Adjust UI element positions var contWidth = $('#container').width() - 20; // 20 pixels for padding $('.jsavoutput').width(contWidth / 2); $('#hashTable').css('left', (3 * contWidth / 4)); // Call reset - the initial state of the vizualization reset(); }); }(jQuery));
const time = document.querySelector("h1"); function getNowTime() { const nowTime = new Date(); const nowHours = nowTime.getHours(); const nowMinutes = nowTime.getMinutes(); const nowSeconds = nowTime.getSeconds(); const nowTimeString = `${nowHours < 10 ? `0${nowHours}` : nowHours} : ${nowMinutes < 10 ? `0${nowMinutes}` : nowMinutes} : ${nowSeconds < 10 ? `0${nowSeconds}` : nowSeconds} `; return nowTimeString; } function writeTime(){ nowTimeString = getNowTime(); time.innerHTML = nowTimeString; } function init(){ setInterval(writeTime, 1); } init();
import React, { PureComponent } from "react"; // Material UI Components import { Paper, withStyles } from "@material-ui/core"; //Style import { dashboardStyle } from "./dashboardStyle"; // Recharts import { XAxis, YAxis, Tooltip, ResponsiveContainer, CartesianGrid, AreaChart, Area, Label } from "recharts"; import moment from "moment"; class Chart extends PureComponent { renderSecondArea = () => { return ( <Area isAnimationActive={false} type="monotone" dataKey={this.props.dataKey2} stackId="1" stroke={this.props.color} strokeWidth="3" fillOpacity="1" fill={`url(#${this.props.title}Color)`} /> ); }; render() { const { classes } = this.props; return ( <Paper className={classes.paper}> <ResponsiveContainer width="100%" height={310}> <AreaChart data={this.props.data} margin={{ top: 30, right: 30, left: 0, bottom: 15 }} > <CartesianGrid strokeDasharray="3 3" verticalFill={[ "263148", "#444444" ]} fillOpacity={0.1} /> <defs> <linearGradient id={`${this.props.title}Color`} x1="0" y1="0" x2="0" y2="1" > <stop offset="5%" stopColor={this.props.color} stopOpacity={0.8} /> <stop offset="95%" stopColor={this.props.color} stopOpacity={0} /> </linearGradient> </defs> <XAxis dataKey="time-stamp" name="Time" tick={{ fill: "white" }} stroke="#efefef" type="number" domain={[ "dataMin", "dataMax" ]} minTickGap={200} tickFormatter={unixTime => moment(unixTime * 1000).format("hh:mm:ss") } scale="time" > <Label value="Time" offset={0} fill="white" position="insideBottom" dy={15} /> <Label value={this.props.title} offset={0} fontSize={20} fill="white" position="top" dy={-250} /> </XAxis> <YAxis tick={{ fill: "white" }} stroke="#efefef" label={{ value: this.props.unit, fill: "white", angle: -90, position: "insideLeft" }} /> <Tooltip labelFormatter={unixTime => moment(unixTime * 1000).toString()} formatter={(value, name, props) => [ `${value} ${this.props.unit}`, this.props.title ]} /> <Area isAnimationActive={false} type="monotone" dataKey={this.props.dataKey1} stackId="1" stroke={this.props.color} strokeWidth="3" fillOpacity="1" fill={`url(#${this.props.title}Color)`} /> {this.props.dataKey2 !== undefined ? this.renderSecondArea() : undefined} </AreaChart> </ResponsiveContainer> </Paper> ); } } export default withStyles(dashboardStyle)(Chart);
import React, { Component } from "react"; import Button from "./Button"; import { FaPlus } from "react-icons/fa"; import AddTask from "./AddTask"; import { Col, Row } from "react-bootstrap"; class Header extends Component { constructor(props) { super(props); this.state = { display: false, }; } // onClick = () => { // console.log("cli"); // this.setState((prevState) => ({ // display: !prevState.display, // })); // this.props.onDis(this.state.display) // } render() { return ( <Row className="task-header m-1.5"> <Col sm={7} md={9} xs={9} xl={10} lg={10}> <h4 className="task-text">Task Manager</h4> </Col> <Col sm={5} md={3} xs={3} xl={2} lg={2}> <FaPlus onClick={() => this.props.onDis()} /> </Col> </Row> ); } } export default Header;
const { Router } = require("express"); const routes = Router(); const ProductsController = require("../controllers/products") routes.post('/', ProductsController.post); routes.get('/', ProductsController.get); routes.get('/:id', ProductsController.getById); routes.get('/categories/:category', ProductsController.get); routes.put('/:id', ProductsController.put); routes.delete('/:id', ProductsController.delete); module.exports = routes;
describe('P.views.exercises.priv.ImageRegion', function() { var View = P.views.exercises.priv.ImageRegion, Model = P.models.exercises.Description, Form = P.views.exercises.priv.ImageUpload, CollectionView = P.views.exercises.priv.ImageCollection; describe('form toggling', function() { beforeEach(function() { spyOn(Form.prototype, 'initialize'); spyOn(Form.prototype, 'render'); spyOn(CollectionView.prototype, 'initialize'); spyOn(CollectionView.prototype, 'render'); this.view = new View({ model: new Model() }); }); it('hides the form by default', function() { this.view.render(); expect(Form.prototype.initialize).not.toHaveBeenCalled(); expect(CollectionView.prototype.initialize).toHaveBeenCalled(); }); it('shows the form when .js-form-show is clicked', function() { CollectionView.prototype.initialize.and.callThrough(); CollectionView.prototype.render.and.callThrough(); this.view.render(); this.view.$('.js-form-show').click(); expect(Form.prototype.initialize).toHaveBeenCalled(); }); it('hides the form when .js-form-hide is clicked', function() { Form.prototype.initialize.and.callThrough(); Form.prototype.render.and.callThrough(); this.view.formShow(); expect(this.view.$('.v-imgUpload').length).toBe(1); this.view.$('.js-form-hide').click(); expect(this.view.$('.v-imgUpload').length).toBe(0); }); }); });
const { Types: { ObjectId: { isValid } } } = require("mongoose"); // mongoose.Types.ObjectId.isValid - query checkup for failed operations const User = require("../models/user"); const sharp = require("sharp"); const { sendWelcomeEmail, sendGoodbyeEmail } = require("../utils/emails"); // #################################################### // CREATE(POST) HANDLING // #################################################### exports.createUser = async (req, res, next) => { // console.log(req.body); // {email: "...", password: "...", name: "..."} const user = new User(req.body); try { // await user.save(); sendWelcomeEmail(user.email, user.name); const token = await user.generateAuthToken(); // res.status(201).send("New user created successfully"); res.status(201).send({ user, token }); } catch (err) { res.status(400).send(err.message); } }; exports.login = async (req, res, next) => { try { // manually written in the model findByCredentials const user = await User.findByCredentials( req.body.email, req.body.password ); const token = await user.generateAuthToken(); // send data res.send({ user, token }); } catch (err) { res.status(400).send(err.message); } }; // for current session exports.logout = async (req, res, next) => { try { // remove current token from the tokens array req.user.tokens = req.user.tokens.filter(item => item.token !== req.token); await req.user.save(); res.send("successfully logged out"); } catch (err) { res.status(500).send(err.message); } }; // for all sessions exports.logoutAll = async (req, res, next) => { try { req.user.tokens = []; await req.user.save(); res.send("successfully logged out"); } catch (err) { res.status(500).send(err.message); } }; exports.setProfileAvatar = async (req, res, next) => { // access file via req.file // req.user.avatar = req.file.buffer; // sharp // takes binary buffer convert to png with .png() // resize the image with .resize({width, height}) // return updated buffer with .toBuffer() try { const buffer = await sharp(req.file.buffer) .resize({ width: 250, height: 250 }) .png() .toBuffer(); req.user.avatar = buffer; await req.user.save(); res.send("Uploaded successfully"); } catch (err) { res.status(400).send(err.message); } }; // #################################################### // READ(GET) HANDLING // #################################################### exports.getProfile = (req, res, next) => { res.send(req.user); }; exports.getUserAvatar = async (req, res, next) => { if (!isValid(req.params.id)) { return res.status(400).send("Wrong request params"); } try { const user = await User.findById(req.params.id); if (!user || !user.avatar) { throw new Error("No avatar found"); } res.set("Content-Type", "image/png"); res.send(user.avatar); } catch (err) { res.status(400).send(err.message); } }; // #################################################### // UPDATE(PATCH) HANDLING // #################################################### exports.updateUser = async (req, res, next) => { const updates = Object.keys(req.body); const allowToUpdate = ["email", "password", "exp", "name"]; const isValidOption = updates.every(update => allowToUpdate.includes(update)); // console.log(req.body); if (!isValidOption) { return res.status(400).send("Invalid option for update"); } try { updates.forEach(update => (req.user[update] = req.body[update])); await req.user.save(); res.send(req.user); } catch (err) { if (err.name === "ValidationError") { return res.status(400).send(err.message); } res.status(500).send(err.message); } }; // #################################################### // REMOVE(DELETE) HANDLING // #################################################### exports.removeAvatar = async (req, res, next) => { // access file via req.file req.user.avatar = undefined; await req.user.save(); res.send("Removed successfully"); }; exports.removeUser = async (req, res, next) => { try { sendGoodbyeEmail(req.user.email, req.user.name); await req.user.remove(); res.send("Removed successfully"); } catch (err) { res.status(500).send(err.message); } };
import {ActivityIndicator, StyleSheet, TextInput, View} from "react-native"; import React, {Component} from "react"; import {Button, Input, Text} from "react-native-elements"; import {TextInputMask} from "react-native-masked-text"; import strings from "../strings"; import {boundMethod} from "autobind-decorator"; import {getAuthedAPI} from "../api"; import {ACTION_TYPES, createAction} from "../redux/actions"; import {Actions} from "react-native-router-flux"; import {connect} from "react-redux"; import {loadProfile} from "../common"; import ImagePicker from 'react-native-image-picker'; import ProfilePicture from "./ProfilePicture"; const dateRegex = /(0[1-9]|1[012])[- \/.](0[1-9]|[12][0-9]|3[01])[- \/.](19|20)\d\d/; function isFirstNameValid(text) { if (text === null) return false; return 0 < text.length && text.length <= 30; } function isLastNameValid(text) { if (text === null) return false; return 0 < text.length && text.length <= 30; } function isBirthDateValid(text) { if (text === null) return false; return dateRegex.test(text); } class EditProfile extends Component { constructor(props) { super(props); this.state = { firstName: "", lastName: "", birthDate: "", firstNameError: null, lastNameError: null, firstNameValid: false, lastNameValid: false, birthDateValid: false, bio: "", profileImageS3: null, profileImageError: null, profileImageUploading: false } } componentDidMount(): void { loadProfile(this.props.dispatch).then(() => { const {firstName, lastName, birthDate, bio, profileImageS3} = this.props.profile; const firstNameValid = isFirstNameValid(firstName); const lastNameValid = isLastNameValid(lastName); const birthDateValid = isBirthDateValid(birthDate); this.setState({ firstName, lastName, birthDate, firstNameValid, lastNameValid, birthDateValid, bio, profileImageS3 }); }); } @boundMethod updateFirstName(text) { const firstNameValid = 0 < text.length && text.length <= 30; this.setState({ firstName: text, firstNameValid, firstNameError: firstNameValid ? null : strings.pages.editProfile.firstNameError }); } @boundMethod updateLastName(text) { const lastNameValid = 0 < text.length && text.length <= 30; this.setState({ lastName: text, lastNameValid, lastNameError: lastNameValid ? null : strings.pages.editProfile.lastNameError }); } @boundMethod updateBirthDate(text) { const birthDateValid = dateRegex.test(text); this.setState({ birthDate: text, birthDateValid }); } @boundMethod handleBioInput(text) { this.setState({ bio: text }); } get submitButtonDisabled() { return !this.state.firstNameValid || !this.state.lastNameValid || !this.state.birthDateValid; } @boundMethod submit() { getAuthedAPI().editProfile( this.state.firstName, this.state.lastName, this.state.birthDate, this.state.bio ).then((response) => { const profile = { firstName: response.first_name, lastName: response.last_name, birthDate: response.birth_date, bio: response.bio } this.props.setProfile(profile); Actions.home({type: "replace"}); }); } @boundMethod onSelectProfilePicturePressed() { ImagePicker.showImagePicker( { cameraType: "front" }, (response) => { if (response.didCancel) { // console.log('User cancelled image picker'); } else if (response.error) { console.error('ImagePicker Error: ', response.error); } else if (response.customButton) { // console.log('User tapped custom button: ', response.customButton); } else { const source = {uri: response.uri}; this.setState({ profileImageUploading: true }); getAuthedAPI() .uploadProfilePicture(source) .then((response) => { this.setState({ profileImageS3: response.object, profileImageError: null }); }) .catch((error) => { console.log(error); if (error.response.status === 413) { this.setState({ profileImageError: strings.pages.editProfile.profilePictureTooLarge }); } else { return Promise.reject(error); } }) .finally(() => { this.setState({ profileImageUploading: false }); }) } } ) } render() { return ( <View> <View style={{marginLeft: 10, marginRight: 10, marginTop: 10 }}> {/* First name */} <Input placeholder="First Name (required)" value={this.state.firstName} onChangeText={this.updateFirstName} errorMessage={this.state.firstNameError} /> {/* Last name */} <Input placeholder="Last Name (required)" value={this.state.lastName} onChangeText={this.updateLastName} errorMessage={this.state.lastNameError} /> {/* Birth date */} <Text style={styles.textLabel}> {strings.pages.editProfile.birthDateLabel} </Text> <TextInputMask type={'datetime'} options={{ format: 'MM/DD/YYYY' }} value={this.state.birthDate} onChangeText={this.updateBirthDate} placeholder={"MM/DD/YYYY (required)"} style={styles.maskedDateInput} /> {/* Bio */} <Text style={styles.textLabel}> {strings.pages.editProfile.bioLabel} </Text> <TextInput multiline={true} style={styles.multiLineInput} placeholder="Lorem ipsum dolor..." onChangeText={this.handleBioInput} value={this.state.bio} /> {/* Profile image */} <Text style={styles.textLabel}> {strings.pages.editProfile.profilePicture} </Text> <View style={{display: "flex", flexDirection: "row"}}> {!this.state.profileImageUploading ? <ProfilePicture imageURL={this.state.profileImageS3} /> : <ActivityIndicator style={{width: 150, height: 150}} /> } <Button title="Choose Picture" containerStyle={styles.choosePictureButton} onPress={this.onSelectProfilePicturePressed} /> </View> {this.state.profileImageError && <Text style={{color: "red"}}>{this.state.profileImageError}</Text> } <Button title={strings.pages.editProfile.submit} containerStyle={styles.submitButton} disabled={this.submitButtonDisabled} onPress={this.submit} /> </View> </View> ); } } const styles = StyleSheet.create({ maskedDateInput: { width: "95%", alignSelf: 'center', color: 'black', fontSize: 18, minHeight: 40, borderBottomWidth: 1, alignItems: 'center', borderColor: "gray", paddingHorizontal: 10 }, textLabel: { alignSelf: "flex-start", marginTop: 10, marginLeft: 10 }, submitButton: { marginTop: 10 }, multiLineInput: { width: "95%", color: 'black', fontSize: 18, minHeight: 40, borderBottomWidth: 1, borderColor: "gray", paddingHorizontal: 10, alignSelf: "center" }, choosePictureButton: { marginLeft: 40, alignSelf: "center" } }); function mapStateToProps(state) { return { profile: state.profile }; } function mapDispatchToProps(dispatch) { return { setProfile: profile => dispatch(createAction(ACTION_TYPES.SET_PROFILE, profile)), dispatch } } export default connect(mapStateToProps, mapDispatchToProps)(EditProfile);
'use strict' const assert = require('assert') const SafeEventEmitter = require('safe-event-emitter') const pify = require('pify') const log = require('debug')('kitsunet:node') const proto = '/kitsunet/test/0.0.1' // TODO: change to `/kitsunet/1.0.0` const MAX_PEERS = 25 const MAX_PEERS_DISCOVERED = 250 const INTERVAL = 60 * 1000 // every minute class KitsunetPeer extends SafeEventEmitter { constructor ({ node, maxPeers, interval }) { super() assert(node, 'node is required') this.maxPeers = maxPeers || MAX_PEERS this.interval = interval || INTERVAL this.node = node this.connected = new Map() this.discovered = new Map() this.dialing = new Map() node.handle(proto, (_, conn) => { conn.getPeerInfo((err, peerInfo) => { if (err) return log(err) setImmediate(() => this.connected.set(peerInfo.id.toB58String(), peerInfo)) this.emit('kitsunet:connection', conn) }) }) node.on('peer:connect', (peerInfo) => { this.connected.set(peerInfo.id.toB58String(), peerInfo) setImmediate(() => this.emit('kitsunet:connect', peerInfo)) log(`peer connected ${peerInfo.id.toB58String()}`) }) node.on('peer:disconnect', (peerInfo) => { this.connected.delete(peerInfo.id.toB58String()) setImmediate(() => this.emit('kitsunet:disconnect', peerInfo)) log(`peer disconnected ${peerInfo.id.toB58String()}`) }) node.on('peer:discovery', (peerInfo) => { if (this.discovered.size > MAX_PEERS_DISCOVERED) return this.discovered.set(peerInfo.id.toB58String(), peerInfo) setImmediate(() => this.emit('kitsunet:discovery', peerInfo)) log(`peer discovered ${peerInfo.id.toB58String()}`) }) this.tryConnect() setInterval(this.tryConnect.bind(this), this.interval) } async tryConnect () { if (this.connected.size <= this.maxPeers) { if (this.discovered.size > 0) { const [id, peer] = this.discovered.entries().next().value this.discovered.delete(id) return this.dial(peer) } } } async dial (peer) { const b58Id = peer.id.toB58String() if (this.dialing.has(b58Id)) { log(`dial already in progress for ${b58Id}`) return } if (!this.connected.has(b58Id)) { try { this.dialing.set(b58Id, true) const conn = await pify(this.node.dialProtocol).call(this.node, peer, proto) this.emit('kitsunet:connection', conn) } catch (err) { log(err) } finally { this.dialing.delete(b58Id) } } } async hangup (peer) { return pify(this.node.hangUp).call(this.node, peer) } } module.exports = KitsunetPeer
function solution(records) { let answer = []; let map = new Map(); records.map(item =>{ let spliter = item.split(" "); let order = spliter[0]; let id = spliter[1]; if(order === "Enter" || order ==="Change"){ let name = spliter[2]; map.set(id,name); } }); for(let item of records){ let spliter = item.split(" "); let order = spliter[0]; let id = spliter[1]; if(order === "Change") continue; let name = map.get(id); let s = ""; if(order ==="Enter"){ s += name + "님이 들어왔습니다." } else{ s += name + "님이 나갔습니다." } answer.push(s); } return answer; } (function solve(){ let records = ["Enter uid1234 Muzi", "Enter uid4567 Prodo","Leave uid1234","Enter uid1234 Prodo","Change uid4567 Ryan"]; console.log(solution(records)); })();
const burgerMenuButton = document.querySelector('.burger-menu__button'); burgerMenuButton.addEventListener('click', e => { e.preventDefault(); burgerMenuButton.classList.toggle('burger-menu__button--close'); burgerMenuButton.parentElement.classList.toggle('burger-menu--active'); });
import * as React from "react"; import {Route, Switch} from "react-router-dom"; import Files from "../Main"; const Router = () => { return ( <div style={{marginTop: 80}}> <Switch> <Route path="/" exact component={Files}/> </Switch> </div> ) } export default Router;
export const CHANGE_DATA_USER = 'CHANGE_DATA_USER'; const initialDataUser = {}; function reducerUser(dataUser = initialDataUser, action) { const { type, payload } = action; switch (type) { case CHANGE_DATA_USER: return { ...payload, }; default: return dataUser; } } export default reducerUser;
import { GET_PROJECTS, PROJECTS_LOADING, DELETE_PROJECT, CREATE_PROJECT, UPDATE_PROJECT, TOGGLE_FRIEND_AS_A_PROJECT_MEMBER } from '../actions/types'; const initialState = { isLoading: false, data: [] }; export default (state = initialState, action) => { switch(action.type) { case GET_PROJECTS: return { ...state, isLoading: false, data: action.payload }; case PROJECTS_LOADING: return { ...state, isLoading: true }; case CREATE_PROJECT: return { ...state, data: [...state.data, action.payload] }; case DELETE_PROJECT: return { ...state, data: state.data.filter(project => project.id !== action.payload) }; case TOGGLE_FRIEND_AS_A_PROJECT_MEMBER: case UPDATE_PROJECT: const index = state.data.findIndex(project => project.id === action.payload.id); state.data[index] = action.payload; return { ...state, data: state.data }; default: return state; } }
import * as DeliveryAddressController from "./../controllers/delivery_address"; import { Router } from "express"; const router = new Router(); router.get("/", DeliveryAddressController.getAllDeliveryAddresses); router.post("/", DeliveryAddressController.createDeliveryAddress); router.patch("/:id", DeliveryAddressController.updateDeliveryAddress); router.delete("/:id", DeliveryAddressController.deleteDeliveryAddress); export default router;
/* eslint-disable */ // this is an auto generated file. This will be overwritten export const onCreateUser = /* GraphQL */ ` subscription OnCreateUser { onCreateUser { id name email password usertype createdAt updatedAt } } `; export const onUpdateUser = /* GraphQL */ ` subscription OnUpdateUser { onUpdateUser { id name email password usertype createdAt updatedAt } } `; export const onDeleteUser = /* GraphQL */ ` subscription OnDeleteUser { onDeleteUser { id name email password usertype createdAt updatedAt } } `; export const onCreateMusician = /* GraphQL */ ` subscription OnCreateMusician { onCreateMusician { id genre { id name subGenre createdAt updatedAt } instruments createdAt updatedAt } } `; export const onUpdateMusician = /* GraphQL */ ` subscription OnUpdateMusician { onUpdateMusician { id genre { id name subGenre createdAt updatedAt } instruments createdAt updatedAt } } `; export const onDeleteMusician = /* GraphQL */ ` subscription OnDeleteMusician { onDeleteMusician { id genre { id name subGenre createdAt updatedAt } instruments createdAt updatedAt } } `; export const onCreateInstrument = /* GraphQL */ ` subscription OnCreateInstrument { onCreateInstrument { id name genre { id name subGenre createdAt updatedAt } createdAt updatedAt } } `; export const onUpdateInstrument = /* GraphQL */ ` subscription OnUpdateInstrument { onUpdateInstrument { id name genre { id name subGenre createdAt updatedAt } createdAt updatedAt } } `; export const onDeleteInstrument = /* GraphQL */ ` subscription OnDeleteInstrument { onDeleteInstrument { id name genre { id name subGenre createdAt updatedAt } createdAt updatedAt } } `; export const onCreateGenre = /* GraphQL */ ` subscription OnCreateGenre { onCreateGenre { id name subGenre instruments { id name createdAt updatedAt } createdAt updatedAt } } `; export const onUpdateGenre = /* GraphQL */ ` subscription OnUpdateGenre { onUpdateGenre { id name subGenre instruments { id name createdAt updatedAt } createdAt updatedAt } } `; export const onDeleteGenre = /* GraphQL */ ` subscription OnDeleteGenre { onDeleteGenre { id name subGenre instruments { id name createdAt updatedAt } createdAt updatedAt } } `; export const onCreateVenue = /* GraphQL */ ` subscription OnCreateVenue { onCreateVenue { id genres { id name subGenre createdAt updatedAt } instruments { id name createdAt updatedAt } createdAt updatedAt } } `; export const onUpdateVenue = /* GraphQL */ ` subscription OnUpdateVenue { onUpdateVenue { id genres { id name subGenre createdAt updatedAt } instruments { id name createdAt updatedAt } createdAt updatedAt } } `; export const onDeleteVenue = /* GraphQL */ ` subscription OnDeleteVenue { onDeleteVenue { id genres { id name subGenre createdAt updatedAt } instruments { id name createdAt updatedAt } createdAt updatedAt } } `; export const onCreateBlog = /* GraphQL */ ` subscription OnCreateBlog { onCreateBlog { id name createdAt updatedAt } } `; export const onUpdateBlog = /* GraphQL */ ` subscription OnUpdateBlog { onUpdateBlog { id name createdAt updatedAt } } `; export const onDeleteBlog = /* GraphQL */ ` subscription OnDeleteBlog { onDeleteBlog { id name createdAt updatedAt } } `; export const onCreatePost = /* GraphQL */ ` subscription OnCreatePost { onCreatePost { id title blogID createdAt updatedAt } } `; export const onUpdatePost = /* GraphQL */ ` subscription OnUpdatePost { onUpdatePost { id title blogID createdAt updatedAt } } `; export const onDeletePost = /* GraphQL */ ` subscription OnDeletePost { onDeletePost { id title blogID createdAt updatedAt } } `; export const onCreateComment = /* GraphQL */ ` subscription OnCreateComment { onCreateComment { id postID content createdAt updatedAt } } `; export const onUpdateComment = /* GraphQL */ ` subscription OnUpdateComment { onUpdateComment { id postID content createdAt updatedAt } } `; export const onDeleteComment = /* GraphQL */ ` subscription OnDeleteComment { onDeleteComment { id postID content createdAt updatedAt } } `; export const onCreateTodo = /* GraphQL */ ` subscription OnCreateTodo { onCreateTodo { id name description createdAt updatedAt } } `; export const onUpdateTodo = /* GraphQL */ ` subscription OnUpdateTodo { onUpdateTodo { id name description createdAt updatedAt } } `; export const onDeleteTodo = /* GraphQL */ ` subscription OnDeleteTodo { onDeleteTodo { id name description createdAt updatedAt } } `;
var currentRegion; var sfName, lastSfName; var startTime = 0; var sfTitle; var fadeTime = 500; //time to fade when programmatically changing playhead position (in ms) var phpUrl = "https://damasi.be/masi"; //var phpUrl = "http://0.0.0.0:7000"; var mediaUrl = "/masi/media/"; var mainColor = getComputedStyle(document.documentElement).getPropertyValue('--main-color'); var backgroundColor = getComputedStyle(document.documentElement).getPropertyValue('--main-bg-color'); var waveBackgroundColor = 'inherit'; var accentColor = getComputedStyle(document.documentElement).getPropertyValue('--accent-color'); var regionColor = accentColor; var lastRegionColor = 'rgba(0,0,0,.5)'; var progressColor = accentColor; var lastProgressColor = mainColor; // init wavesurfer var wavesurfer = WaveSurfer.create({ container: document.querySelector('#waveform'), height: getComputedStyle(document.documentElement).getPropertyValue('--waveform-height'), backgroundColor: waveBackgroundColor, waveColor: mainColor, cursorColor: mainColor, progressColor: 'rgba(0,0,0,.1)', normalize: true, backend: 'MediaElementWebAudio', //splitChannels: true, plugins: [ WaveSurfer.regions.create({ dragSelection: { slop: 5 }}), WaveSurfer.cursor.create({ showTime: true, opacity: 1, customShowTimeStyle: { 'background-color': backgroundColor, color: mainColor, padding: '2px', 'font-family': getComputedStyle(document.documentElement).getPropertyValue('--secondary-font'), 'font-size': getComputedStyle(document.documentElement).getPropertyValue('--secondary-font-size') } }), ], }); wavesurfer.g = wavesurfer.backend.ac.createGain(); wavesurfer.backend.setFilter(wavesurfer.g); $(document).ready(function(){ $("#flip").click(function(){ $("#panel").slideToggle(40); return false; }); $("#toggleChrome").click(function(){ $(".chrome").toggle(40); return false; }); var sf = document.getElementsByClassName('sf'); for( let i=0; i < sf.length; i++ ) { sfName = sf[i].id; sf[i].innerHTML = '<div class="progress"></div><div class="sfName"></div><div class="timestamp"></div><div class="play"></div><div class="title" contenteditable="true"></div><div class="regions"></div>'; let title = sf[i].getElementsByClassName("title")[0]; sf[i].getElementsByClassName("sfName")[0].innerHTML = sfName; sf[i].getElementsByClassName("progress")[0].style.background = progressColor; sf[i].getElementsByClassName("play")[0].setAttribute("onclick", "playPause('" + sfName + "');" ); //add onclick function to each div loadRegionsFromServer(sfName); title.addEventListener("input", function() { sfTitle = title.innerHTML; updateTitle(title.parentNode.id, title.innerHTML); }, false); } sfName=null; }); function playPause(file) { if (sfName === file) { wavesurfer.playPause(); } else { loadSf(mediaUrl+file); } document.getElementById(file).style.color=accentColor; if (lastSfName && lastSfName!==sfName) { document.getElementById(lastSfName).style.color=mainColor; } } wavesurfer.on('ready', function () { let playPos = document.getElementById(sfName).getElementsByClassName("progress")[0].style.width.replace("%",""); wavesurfer.seekTo(playPos/100); wavesurfer.play(); }); wavesurfer.on('waveform-ready', showWaveform); function showWaveform() { if (document.getElementById("panel").style.display != 'block') { $("#panel").slideToggle(40, function() { wavesurfer.zoom(0); //hack to show redraw waveform once div is shown; }); } } function updateTitle(id, title) { let jsondata = JSON.stringify({ filename: id, title: title}); var s = document.createElement("script"); s.src = phpUrl + "/push/update-title.php?json=" + jsondata; document.body.appendChild(s); } function phpEcho(str) { console.log(str); } /* Progress bar */ (function() { var progressDiv = document.querySelector('#progress'); var showProgress = function(percent) { progressDiv.style.display = 'block'; progressDiv.innerHTML = 'Loading sound file... ' + percent + '%'; if (percent==100) { progressDiv.innerHTML += '<br>getting peaks...'; } }; var hideProgress = function() { progressDiv.style.display = 'none'; }; wavesurfer.on('loading', showProgress); wavesurfer.on('waveform-ready', hideProgress); wavesurfer.on('destroy', hideProgress); wavesurfer.on('error', hideProgress); })(); function loadVid() { var mediaElt = document.querySelector('video'); wavesurfer.load(mediaElt); } function loadSf(url) { wavesurfer.load(url); lastSfName = sfName; sfName = url.substring(url.lastIndexOf('/')+1); startTime = 0; loadRegionsFromServer(sfName); document.getElementById("sfname").innerText = sfName; //document.getElementById(sfName)..style.fontWeight = 'bold'; if (lastSfName) document.getElementById(lastSfName).getElementsByClassName("progress")[0].style.background = lastProgressColor; } function exportReaperProject() { var txt = '<REAPER_PROJECT\n\n TIMEMODE 3 5 -1 30 0 0 -1\n ZOOM 1 0 0\n\n <TRACK\n NAME '+sfName; var count = 0; var region, lastRegion; Object.keys(wavesurfer.regions.list).forEach(function (id) { lastRegion = region; region = wavesurfer.regions.list[id]; var color; //handle in between regions if (count==0) txt += reaperItem(0,region.start,'',''); else txt += reaperItem(lastRegion.end,region.start-lastRegion.end,'',''); if (region.attributes.label === 'rm') color = '33226774 B'; //red else color = '22258724 B'; //green txt += reaperItem(region.start,region.end-region.start,region.attributes.label,color); count++; }); txt += reaperItem(region.end,wavesurfer.getDuration()-region.end,'',''); txt += '\n >\n>' var blob = new Blob([txt], {type: "text/plain;charset=utf-8"}); saveAs(blob, sfName+".RPP"); } function reaperItem(start,length,name,color) { return '\n <ITEM\n POSITION '+start+'\n LENGTH '+length+'\n\n NAME '+name+'\n SOFFS '+start+'\n COLOR '+color+'\n\n <SOURCE WAVE\n FILE "'+sfName+'"\n >\n >' } //zoom document.querySelector('[data-action="zoom"]').oninput = function () { wavesurfer.zoom(Number(this.value)); }; document.getElementById("loginput").addEventListener('change', function(e){ var file = this.files[0]; if (file) { var reader = new FileReader(); reader.onload = function(e) { loadRegions(JSON.parse(reader.result)); } reader.onerror = function (evt) { console.error("An error ocurred reading the file: ", evt); }; reader.readAsText(file); } }, false); // Play button in GUI var button = document.querySelector('[data-action="play"]'); button.addEventListener('click', wavesurfer.playPause.bind(wavesurfer)); wavesurfer.on('audioprocess', function() { if(wavesurfer.isPlaying()) { document.getElementById('time-total').innerText = formatTime(wavesurfer.getDuration()); document.getElementById('time-current').innerText = formatTime(wavesurfer.getCurrentTime()); var width = (wavesurfer.getCurrentTime()/wavesurfer.getDuration()); if (document.getElementById(sfName)) //if a div exists for the sf document.getElementById(sfName).getElementsByClassName("progress")[0].style.width = width*100 + "%"; if (startTime>0) if (wavesurfer.getCurrentTime()<startTime-0.01) wavesurfer.seekTo(startTime/wavesurfer.getDuration()); } }); wavesurfer.on('region-dblclick', function(region, e) { region.remove(); saveRegionsToServer(); }); var lastSelectedRegion, selectedRegion; wavesurfer.on('region-click', regionFocus); wavesurfer.on('region-update-end', regionFocus); wavesurfer.on('interaction', handlePlayheadClick); var regionClicked = false; function regionFocus(region) { regionClicked = true; var input = document.getElementById("inputtext"); input.focus(); if (region.attributes.label!=null) input.value = region.attributes.label; else input.value = ''; lastSelectedRegion = selectedRegion; selectedRegion = region; selectedRegion.update({ color: regionColor }); if (lastSelectedRegion != null && lastSelectedRegion != selectedRegion) { lastSelectedRegion.update({ color: lastRegionColor }); } } function handlePlayheadClick() { if (regionClicked==false) { if (selectedRegion!=null) { selectedRegion.update({ color: 'rgba(11, 91, 162,.3)' }); selectedRegion=null; } var input = document.getElementById("inputtext"); input.focus(); input.value = ''; } regionClicked = false; } var timeIn, timeOut, note; function handle(e) { var input = document.getElementById("inputtext").value; var t = wavesurfer.getCurrentTime(); if (input.length==1) timeIn = t; note = input; timeOut = t; if (selectedRegion!=null) { selectedRegion.update({ attributes: { label: note }, }); } var key=e.keyCode || e.which; if (key==13){ if (selectedRegion!=null) { selectedRegion.update({ color: 'rgba(11, 91, 162,.3)' }); selectedRegion=null; } else { wavesurfer.addRegion({ start: timeIn, end: timeOut, attributes: { label: note } }); } document.getElementById("inputtext").value=''; } saveRegionsToServer(); } function formatTime(seconds) { minutes = Math.floor(seconds / 60); minutes = (minutes >= 10) ? minutes : "0" + minutes; seconds = Math.floor(seconds % 60); seconds = (seconds >= 10) ? seconds : "0" + seconds; return minutes + ":" + seconds; } /** * Save annotations */ function saveRegions() { var jsondata = JSON.stringify({ filename: sfName, regions: Object.keys(wavesurfer.regions.list).map(function(id) { var region = wavesurfer.regions.list[id]; return { start: region.start, end: region.end, attributes: region.attributes, //data: region.data }; }) }); var blob = new Blob([jsondata], {type: "text/plain;charset=utf-8"}); saveAs(blob, sfName+"_regions.json"); } wavesurfer.on('region-update-end', saveRegionsToServer); function saveRegionsToServer() { printRegionsToList(sfName); if (sfTitle === null) sfTitle = sfName; var jsondata = JSON.stringify({ filename: sfName, title: sfTitle, regions: Object.keys(wavesurfer.regions.list).map(function(id) { var region = wavesurfer.regions.list[id]; return { start: region.start, end: region.end, attributes: region.attributes, //data: region.data }; }) }); var s = document.createElement("script"); s.src = phpUrl + "/push/?json=" + jsondata; document.body.appendChild(s); } function savedJSON(txt) { //callback from save.php console.log(txt + " regions saved to server"); } function loadRegionsFromServer(filename) { wavesurfer.regions.clear(); console.log("regions cleared. loading regions for "+filename); var s = document.createElement("script"); s.src = phpUrl + "/pull.php?json=" + sfName; document.body.appendChild(s); } function servedJSON(json) { let data = JSON.parse(json); var sf = document.getElementById(data.filename); var div; if (sf) { if (data.title) sf.getElementsByClassName("title")[0].innerHTML = data.title; div = sf.getElementsByClassName("regions")[0]; div.innerHTML = ""; } if (data.regions) { data.regions.forEach(function(region) { wavesurfer.addRegion(region); handleStartEndTime(region); //not keeping in DRY here... if (sf) { if (region.attributes.label && region.attributes.label!="rm") { //only print regions with labels //div.innerHTML += formatTime(region.start) + "-" + formatTime(region.end) + " " + region.attributes.label; if (region.attributes.label === "start" || region.attributes.label === "end") { div.innerHTML += formatTime(region.start) + " " + region.attributes.label + "<br>"; } else { div.innerHTML += formatTime(region.start) + " " + region.attributes.label + " (" + formatTime(region.end-region.start) + ")<br>"; } } } }); } } wavesurfer.on('region-created', handleStartEndTime); wavesurfer.on('region-updated', handleStartEndTime); wavesurfer.on('region-update-end', handleStartEndTime); function handleStartEndTime(region) { if (region.attributes.label==="start") startTime = region.start; } function loadRegions(regions) { var sf = document.getElementById(sfName); var div; if (sf) { div = sf.getElementsByClassName("regions")[0]; div.innerHTML = ""; } regions.forEach(function(region) { wavesurfer.addRegion(region); if (sf) if (region.attributes.label && egion.attributes.label!="rm") div.innerHTML += formatTime(region.start) + " " + region.attributes.label + " (" + formatTime(region.end-region.start) + ")<br>"; }); } wavesurfer.on('region-update-end', saveRegionsToServer); wavesurfer.on('region-in', function(region, e) { if (region.attributes.label==="rm") { //fade out, move playhead, fade in var currTime = wavesurfer.backend.ac.currentTime; var fadeTimeS = fadeTime/1000; //in seconds var vol = wavesurfer.g.gain.value; wavesurfer.g.gain.linearRampToValueAtTime(vol,currTime); wavesurfer.g.gain.linearRampToValueAtTime(0,currTime+fadeTimeS); setTimeout(function(){ wavesurfer.play(region.end); }, fadeTime); wavesurfer.g.gain.linearRampToValueAtTime(vol,currTime+fadeTimeS+fadeTimeS); } else { // PRINT TO LOG var div = document.getElementById(sfName+"-log"); if (div) { div.innerHTML += formatTime(region.start) + " " + region.attributes.label + "<br>"; } var txt = document.getElementById("log"); if (txt) { txt.value += "\n"; txt.value += region.attributes.label; //txt.value += formatTime(region.start) + " " + region.attributes.label; txt.scrollTop = txt.scrollHeight; } } }); function offsetRegions(amount) { Object.keys(wavesurfer.regions.list).map(function(id) { var region = wavesurfer.regions.list[id]; region.update({start: region.start+amount, end: region.end+amount}) }) } function removeCloseRegions() { Object.keys(wavesurfer.regions.list).map(function(id) { if (region!=null) var lastRegion = region; var region = wavesurfer.regions.list[id]; if (lastRegion!=null) { if (region.start-lastRegion.start<0.1) { console.log("region removed") region.remove(); } } }) } function printRegionsToList(f) { var sf = document.getElementById(f); if (sf) { let div = sf.getElementsByClassName("regions")[0]; div.innerHTML = ""; Object.keys(wavesurfer.regions.list).map(function(id) { var region = wavesurfer.regions.list[id]; if (region.attributes.label && region.attributes.label!="rm") { //only print regions with labels //div.innerHTML += formatTime(region.start) + "-" + formatTime(region.end) + " " + region.attributes.label; if (region.attributes.label === "start" || region.attributes.label === "end") { div.innerHTML += formatTime(region.start) + " " + region.attributes.label + "<br>"; } else { div.innerHTML += formatTime(region.start) + " " + region.attributes.label + " (" + formatTime(region.end-region.start) + ")<br>"; } } }) } }
var uri = "../../public"; var gl_resultado = {}; var app; (function(){ app = angular.module("sgc", ['ngRoute','ui.keypress']); app.config(['$routeProvider', '$locationProvider', function AppConfig($routeProvider, $locationProvider){ $routeProvider .when("/documentos",{ templateUrl: 'documentos/index.html' }) .when("/consultarArchivos",{ templateUrl: 'documentos/consultarArchivos.html' }) .when("/solicitudes",{ templateUrl: 'documentos/solicitudes.html' }) .when("/consultarArchivosExternos",{ templateUrl: 'documentos/consultarArchivosExternos.html' }) .when("/manuales",{ templateUrl: 'documentos/manuales.html' }) .when("/archivos",{ templateUrl: 'documentos/archivos.html' }) .when("/procesos",{ templateUrl: 'documentos/procesos.html' }) .when("/tipodocumentos",{ templateUrl: 'documentos/documentos.html' }) .when("/subprocesos",{ templateUrl: 'documentos/subprocesos.html' }) .when("/obsoletos",{ templateUrl: 'documentos/obsoletos.html' }) .when("/indicadores",{ templateUrl: 'indicadores/index.html' }) .when("/indicadores/categorias",{ templateUrl: 'indicadores/categorias.html' }) .when("/indicadores/subcategorias",{ templateUrl: 'indicadores/subcategorias.html' }) .when("/indicadores/crear",{ templateUrl: 'indicadores/gestionIndicadores.html' }) .when("/indicadores/medidas",{ templateUrl: 'indicadores/medidas.html' }) .otherwise({ redirectTo:"/indicadores" }); }]); app.directive('ngEnter', function () { return function (scope, elements, attrs) { elements.bind('keydown keypress', function (event) { if (event.which === 13) { scope.$apply(function () { scope.$eval(attrs.ngEnter); }); event.preventDefault(); } }); }; }); app.filter('ifEmpty', function() { return function(input, defaultValue) { if (angular.isUndefined(input) || input === null || input === '') { return defaultValue; } return input; }; }); app.directive('uploaderModel',['$parse',function($parse){ return{ restrict: 'A', link: function(scope,iElement,iAttrs){ iElement.on('change',function(e) { $parse(iAttrs.uploaderModel).assign(scope,iElement[0].files[0]); }); } }; }]); })();
import React from 'react'; const BlackKey = ({note, pressed, idx}) => ( <div key={idx} className={pressed ? "black-key-pressed" : "black-key"}> <div key={idx} className="black-note-name">{note}</div> </div> ); export default BlackKey;
var width = window.innerWidth; var height = window.innerHeight; var paddle, ball; var bricks = []; var numBricks = 36; function setup(){ createCanvas(window.innerWidth, window.windowHeight); paddle = new Paddle(); ball = new Ball(100, 250); //4 Rows of 9 bricks for(var row = 0 ; row < 4; row++){ for(var b = 0; b < 9; b++){ var brick = new Brick(b*125 + 225 , 80 + row*40); bricks.push(brick); } } } function draw(){ background(0); paddle.move(); ball.move(); for(var b = 0; b < numBricks; b++){ bricks[b].display(); } } function Paddle(){ this.x = width/2 - 100; this.y = height - 100; this.display = function(){ fill(255); rect(this.x, this.y, 200, 50); } this.move = function(){ this.display(); if(keyIsDown(LEFT_ARROW) && this.x > 0){ this.x -= 10; } if (keyIsDown(RIGHT_ARROW) && this.x < width - 200){ this.x += 10; } } } function Brick(x, y){ this.x = x; this.y = y; this.display = function(){ fill(255); rect(this.x, this.y, 125, 40); } }
var searchData= [ ['cluster_5ftree',['cluster_tree',['../classtree.html#a79aae5881a0d62f4d53038fd204a2b03',1,'tree']]], ['convert_5fto_5fcoarser_5fgraph',['convert_to_coarser_graph',['../classgraph__cluster.html#a51dbc205a4b2212f1ce6b941427ce470',1,'graph_cluster']]], ['create_5fhmat',['create_hmat',['../classhmat.html#aa57c46567f41e879a388b1809de0e25c',1,'hmat']]], ['create_5fpriority_5fgroups',['create_priority_groups',['../classgraph__cluster.html#ac2cff48ba0e679bc3b6fac71fabd5fe1',1,'graph_cluster']]] ];
class Helpers { constructor() { this.helpers = {}; } /** * * @param value * @returns {Array} */ check(value) { return value ? value : []; } /** * * @param selector * @returns {NodeListOf<HTMLElementTagNameMap[keyof HTMLElementTagNameMap]>} */ queryAll(selector) { return document.querySelectorAll(selector); } /** * * @param selector * @returns {*} */ query(selector) { return this.check(document.querySelectorAll(selector)['0']); } /** * returns an object of all classes in DOM */ static getAllClasses() { document.addEventListener('DOMContentLoaded', () => { const obj = {}; const arr = []; document.querySelectorAll('*').forEach(item => { arr.push(item.classList); }); arr.forEach(it => { obj[it] = `.${it}`; }); document.write(JSON.stringify(obj)); return obj; }); } /** * returns an object of all id in DOM */ static getAllId() { document.addEventListener('DOMContentLoaded', () => { const obj = {}; const arr = []; document.querySelectorAll('*').forEach(item => { arr.push(item.id); }); arr.forEach(it => { obj[it] = `#${it}`; }); document.write(JSON.stringify(obj)); return obj; }); } /** * checks if the value is an element DOM * @param value * @param func * @return {*} */ static checkNodeType(value, func) { if (value.nodeType === 1) { return func(); } } /** * sets the active menu class depending on the scrollTop * @param selector (css selector class - makes scrollTop simple for every div that specifies this class) */ scrollspy(selector) { const section = this.queryAll(selector); const sections = {}; let i = 0; Array.prototype.forEach.call(section, e => { sections[e.id] = e.offsetTop; }); window.onscroll = function () { const scrollPosition = document.documentElement.scrollTop || document.body.scrollTop; for (i in sections) { if (sections[i] <= scrollPosition) { document.querySelector('.active').setAttribute('class', ' '); document.querySelector('a[href*=' + i + ']').setAttribute('class', 'active'); } } }; } /** * smooth scrolling * @param menu (selector css) contains all menu links(example: '.inner-wrap-menu h2 a') * @param sections (selector css) all div with id menu links (example: '.section') */ smoothScrolling(menu, sections) { const hrefArray = this.queryAll(menu); const elArray = this.queryAll(sections); /** * determines the location of the element on the page (Height) * @param el * @returns {number} */ const offset = (el) => { const rect = el.getBoundingClientRect(); const scrollTop = window.pageYOffset || document.documentElement.scrollTop; return rect.top + scrollTop; }; /** * on each link puts scrollTop (Height) * @returns {void} */ const getScroll = () => { for (let i = 0; i < elArray.length; i++) { if (elArray[i]) { hrefArray[i].addEventListener('click', e => { e.preventDefault(); window.scroll({ top: offset(elArray[i]), behavior: 'smooth' }); }); } } }; getScroll(); } /** * empty the contents * @param el (element Dom) * @return {void} */ deletingDomElement(el) { while (el.firstChild) { el.removeChild(el.firstChild); } } } export default Helpers;
import React, { Component } from 'react' import axios from 'axios' import { Form, Button, Badge } from 'react-bootstrap' import 'bootstrap/dist/css/bootstrap.min.css'; import { Link } from 'react-router-dom'; class Search extends Component { constructor(props) { super(props) this.state = { flights: [], from: "", to: "", date: "", airports: [] } } //Initial State Loading async componentDidMount() { axios.get("http://localhost:9000/search/airport", null, null) .then(response => response.data).then(data => this.setState({ airports: data })); console.log(this.state.airports); } //Searching Flights submitHandler = (event) => { axios.post("http://localhost:9000/search/flight", null, { params: { "date": this.state.date, "from": this.state.from, "to": this.state.to }, }) .then(response => response.data).then(data => this.setState({ flights: data })); event.preventDefault(); console.log(this.state.flights); } //Handler method for form change handleChange = (event) => { this.setState( { [event.target.name] : event.target.value } ) console.log(this.state); } //Book button to switch components bookFlight = (flight_id) => { this.props.history.push("/book") } render() { return ( <> <div className="center"> <table className="center-table"> <tbody> <tr> <td className="cellpad"> <Form.Select name="from" onChange={this.handleChange}> <option value="" >Source</option> {this.state.airports.map((airport) => <option key={airport.id} value={airport.city}>{airport.city}</option> )} </Form.Select> </td> <td className="cellpad"> <Form.Select name="to" onChange={this.handleChange}> <option value="" >Destination</option> {this.state.airports.map((airport) => <option key={airport.id} value={airport.city}>{airport.city}</option> )} </Form.Select> </td> <td className="cellpad"> <Form.Control type="date" name='date' onChange={this.handleChange} /> </td> <td className="cellpad"> <Button variant="outline-primary" onClick={this.submitHandler}>Submit</Button>{' '} </td> </tr> </tbody> </table> </div> <div className="center"> <table className="center-table"> <tbody> {this.state.flights.length === 0 ? <tr> <td colSpan="6">No Flights Available</td> </tr> : this.state.flights.map((flight) => <tr key={flight.flight_id}> <td><h4><Badge pill bg="light" text="dark"> {flight.airways} </Badge></h4></td> <td><h4><Badge pill bg="light" text="dark"> {flight.from} </Badge></h4></td> <td><h4><Badge pill bg="light" text="dark"> {flight.to} </Badge></h4></td> <td><h4><Badge pill bg="light" text="dark"> ₹{flight.cost} </Badge></h4></td> <td><h4> <Button variant="outline-dark"> <strong> <Link to={`/book/${flight.flight_id}`}> Book </Link> </strong> </Button> </h4></td> </tr>)} </tbody> </table> </div> </> ) } } export default Search
import './AgentSection.css' import AgentGrid from './AgentSection/AgentGrid' import AgentHeader from './AgentSection/AgentHeader' import AgentReasonGroups from '../../custom/AgentReasonGroups' const AgentSection = ({ agents, censor }) => { const free = AgentReasonGroups.free const call = AgentReasonGroups.call const reducer = (statusCount, agent) => { statusCount.total++ if (free.includes(agent.Reason)) { statusCount.free++ agent.status = 'free' return statusCount } if (call.includes(agent.Reason)) { statusCount.call++ agent.status = 'call' return statusCount } agent.status = 'busy' statusCount.busy++ return statusCount } const statusCount = agents.reduce(reducer, { free: 0, call: 0, busy: 0, total: 0 }) const agentsBack = agents.length !== 0 ? '' : 'NO AGENTS ONLINE' return ( <div id='agent-section'> <div id='agent-container'> <AgentHeader statusCount={statusCount} /> <div id='agent-list'> <AgentGrid agents={agents} censor={censor} /> <div id='agent-background'>{agentsBack}</div> </div> </div> </div> ) } export default AgentSection
"use strict"; const persone = { name: "alex", tel: "203232323", parents: { mom: 'olga', dad: 'mike' } }; console.log(JSON.stringify(persone)); // можно отправить на сервер(заворачивает в JSON) console.log(JSON.parse(JSON.stringify(persone)));// разворачивает const clone = JSON.parse(JSON.stringify(persone));//создание глубокого клона,который не связан с оригиналом clone.parents.mom = 'ana'; console.log(persone); console.log(clone);
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports["default"] = Require; function Require(sessionVariable) { return function (target, name, descriptor) { var original = descriptor.value; var method = original.bind(this); descriptor.value = function (response, data) { if (this !== target) { method = original.bind(this); target = this; } method(response, data); }; return descriptor; }; } module.exports = exports["default"];
/* Função para validar a inclusão dos serviços do aluno */ function insereServ(controller){ control = '../controller/'+controller+'Controller.php'; var dados = $('#formsfp').serialize(); $.post(control, dados, function(response){ var result = response if(result.match(/Redireciona.*/)){ //redireciona para proxima página link = result.replace('Redireciona:', ''); //carrega a url atual var url_atual = window.location.href; //retira a palavra view var urlink = url_atual.search('view'); //limpa a urla depois da palavra view var url = url_atual.substring(urlink,0); //redireciona para proxima página window.location.href = url+'view/'+link; }else{ //oculta a mensagem de ok $("#mensagemok").css("display","none"); //limpando a mensagem anterior $("#mensagemerror").empty(); //carrega informações na tela $("#mensagemerror").append(result); //exibe alert $("#mensagemerror").css("display","block"); //sobe a pagina até o topo $('html, body').animate({scrollTop:0}, 'slow'); } }); }; /* Função para validar a inclusão dos serviços do aluno */ function insereFpgto(controller){ control = '../controller/'+controller+'Controller.php'; var dados = $('#formfpgto').serialize(); $.post(control, dados, function(response){ var result = response console.log(response); if(result.match(/Redireciona.*/)){ //redireciona para proxima página link = result.replace('Redireciona:', ''); //carrega a url atual var url_atual = window.location.href; //retira a palavra view var urlink = url_atual.search('view'); //limpa a urla depois da palavra view var url = url_atual.substring(urlink,0); //redireciona para proxima página window.location.href = url+'view/'+link; }else{ //oculta a mensagem de ok $("#mensagemok").css("display","none"); //limpando a mensagem anterior $("#mensagemerror").empty(); //carrega informações na tela $("#mensagemerror").append(result); //exibe alert $("#mensagemerror").css("display","block"); //sobe a pagina até o topo $('html, body').animate({scrollTop:0}, 'slow'); } }); }; /* Função para validar a inclusão dos cheques da forma de pagamento */ function insereCheque(controller){ control = '../controller/'+controller+'Controller.php'; var dados = $('#formCheque').serialize(); $.post(control, dados, function(response){ var result = response console.log(response); if(result.match(/Redireciona.*/)){ //limpar os campos $('#formCheque input').each(function(){ $(this).val(''); }); //limpando a mensagem anterior $("#mensagemokc").empty(); //exibe alert $("#mensagemokc").css("display","block"); //exibe mensaagem $("#mensagemokc").append('Salvo com Sucesso!'); //oculta alert erro $("#mensagemerrorc").css("display","none"); //oculta loader //redireciona para proxima página link = result.replace('Redireciona:', ''); //carrega a url atual var url_atual = window.location.href; //retira a palavra view var urlink = url_atual.search('view'); //limpa a urla depois da palavra view var url = url_atual.substring(urlink,0); //redireciona para proxima página window.location.href = url+'view/'+link; }else{ //oculta a mensagem de ok $("#mensagemokc").css("display","none"); //limpando a mensagem anterior $("#mensagemerrorc").empty(); //carrega informações na tela $("#mensagemerrorc").append(result); //exibe alert $("#mensagemerrorc").css("display","block"); } }); }; /* função para salvar as informações do financeiro do aluno*/ function SalvarFin(controller){ control = '../controller/'+controller+'Controller.php'; var dados = $('#formsalvar').serialize(); $.post(control, dados, function(response){ var result = response if (result.match(/Salvo.*/)) { //limpando a mensagem anterior $("#mensagemok").empty(); //exibe alert $("#mensagemok").css("display","block"); //exibe mensaagem $("#mensagemok").append(result); //oculta alert erro $("#mensagemerror").css("display","none"); //sobe a pagina até o topo $('html, body').animate({scrollTop:0}, 'slow'); //apos 3 segundos oculta alerta setTimeout(function(){ $("#mensagemerror").css("display","none"); //redireciona para proxima página //carrega a url atual var url_atual = window.location.href; //retira a palavra view var urlink = url_atual.search('view'); //limpa a urla depois da palavra view var url = url_atual.substring(urlink,0); //redireciona para proxima página window.location.href = url+'view/alunofinanceiro.php'; }, 4000); }else{ //oculta a mensagem de ok $("#mensagemok").css("display","none"); //limpando a mensagem anterior $("#mensagemerror").empty(); //carrega informações na tela $("#mensagemerror").append(result); //exibe alert $("#mensagemerror").css("display","block"); //sobe a pagina até o topo $('html, body').animate({scrollTop:0}, 'slow'); } }); };
import Notification from './notification'; import 'this'; const notificationBar = new Notification(".notification-bar"); let countClick = 0; notificationBar.showMessage("Welkom op deze pagina"); document.addEventListener("click", () => { countClick++; notificationBar.showMessage(`je hebt ${countClick}x geklikt`); });
const test = require('ava') const especial = require('..') const tcpPortUsed = require('tcp-port-used') const createServer = async (start = true) => { const getPort = () => Math.floor(Math.random() * 10000 + 10000) let port = getPort() while (await tcpPortUsed.check(port)) { port = getPort() } const app = especial() let server if (start) { await new Promise((rs, rj) => { server = app.listen(port, (err) => { if (err) rj(err) else rs() }) }) } return { server, app, port, url: `ws://localhost:${port}`, } } module.exports = { createServer } test('helper stub', (t) => t.pass())
import React from 'react'; import { View, Text, TouchableOpacity, StyleSheet } from 'react-native'; const SamplerEdition = ({route,navigation}) => { const {props} = route.params const trimSample = () =>{ navigation.navigate("SamplerTrim",{props:props}); } return( <View> <Text style={styles.header}>Choix d'edition</Text> <View style={{alignItems:'center'}}> <Text style={styles.title}>Que voulez vous faire?</Text> <TouchableOpacity onPress={trimSample}> <Text style={styles.buttonLabel}> - Rogner le sample {props.id}</Text> </TouchableOpacity> <TouchableOpacity> <Text style={styles.buttonLabel}> - Changer le sample {props.id}</Text> </TouchableOpacity> </View> </View> ) } const styles = StyleSheet.create({ container: { flex: 1, alignItems: 'center', justifyContent: 'center', }, header: { fontSize: 30, backgroundColor: "tomato", color: "white", padding: 10, marginBottom:10 }, title:{ fontSize:30, fontWeight:'bold', padding:3 }, buttonLabel:{ fontSize:24, padding:3 } }); export default SamplerEdition;
// https://code.visualstudio.com/api/references/theme-color const colors = require('./colors.json') module.exports = { name: 'jellybeans', type: 'dark', colors: { "editor.background": colors['background'], "editor.foreground": colors['foreground'], "sideBar.background": colors['background'], "sideBarTitle.foreground": colors['foreground'], "sideBar.border": colors['black'], "statusBar.background": colors['black'], "activityBar.background": colors['background'], "activityBar.border": colors['black'], "terminal.background": colors['background'], "terminal.border": colors['black'], "terminal.foreground": colors['foreground'], "terminal.ansiBlack": colors['black'], "terminal.ansiBrightBlack": colors['bright-black'], "terminal.ansiBlue": colors['bright-blue'], "terminal.ansiBrightBlue": colors['blue'], "terminal.ansiCyan": colors['cyan'], "terminal.ansiBrightCyan": colors['bright-cyan'], "terminal.ansiGreen": colors['green'], "terminal.ansiBrightGreen": colors['bright-green'], "terminal.ansiMagenta": colors['magenta'], "terminal.ansiBrightMagenta": colors['bright-magenta'], "terminal.ansiRed": colors['red'], "terminal.ansiBrightRed": colors['bright-red'], "terminal.ansiWhite": colors['white'], "terminal.ansiBrightWhite": colors['bright-white'], "terminal.ansiYellow": colors['yellow'], "terminal.ansiBrightYellow": colors['bright-yellow'], "terminal.selectionBackground": colors['dark-blue'], "terminalCursor.background": colors['black'], "terminalCursor.foreground": colors['bright-white'] } }
function clickGithub1s() { // console.log('clickGithub1s...') // https://github.com/*/* let oldUrl = window.location.href let newUrl = oldUrl.slice(0,14) + '1s' + oldUrl.slice(14) // console.log(`newUrl: ${newUrl}`) window.location.href = newUrl } (function () { // console.log('绑定点击事件') let button = document.getElementById('github_1s_vscode_id') button.onclick = clickGithub1s })()
// Generated by CoffeeScript 1.6.2 (function() { var Admin, admin; process.stdout.write('\u001B[2J\u001B[0;0f'); Admin = require('icecast-admin').Admin; if (process.argv.length < 3) { console.log("usage: " + process.argv[1] + " 'http://username:password@hostname:port/'"); process.exit(1); } admin = new Admin({ url: process.argv[2] }); admin.stats(function(err, result) { var source, _i, _len, _ref, _results; if (err) { return console.log('Error:', err); } else { console.log("" + result.icestats.source.length + " sources"); _ref = result.icestats.source; _results = []; for (_i = 0, _len = _ref.length; _i < _len; _i++) { source = _ref[_i]; _results.push(console.log(source)); } return _results; } }); }).call(this);
import React, { useState } from 'react'; import Editor from "./components/Editor" import "./styles/codeMirror.css" import Themes from "./components/Themes" import SplitPane from "react-split-pane" const Codemirror = () => { const [html, sethtml] = useState("") const [css, setcss] = useState("") const [js, setjs] = useState("") const [theme, settheme] = useState("dracula") return ( <> <Themes settheme={settheme}></Themes> <div className="editorWraper"> <Editor language="xml" name="html" setcode={sethtml} theme={theme} /> <Editor language="css" name="css" setcode={setcss} theme={theme} /> <Editor language="javascript" name="js" setcode={setjs} theme={theme} /> </div> <div className="iframeContainer"> <iframe srcDoc={` <!DOCTYPE html> <html lang="en"> <head> </head> <style>${css}</style> <body> ${html} </body> <script>${js}</script> </html> `} frameborder="0" ></iframe> </div> </> ); } export default Codemirror;
import React from 'react'; export default class Spacer extends React.Component { constructor(props) { super(props); this.state = { height: '8vh' }; } render() { const type = this.props.spacerType; let height = this.state.height; let width = 'calc(' + 100 + 'vw -' + 260 + 'px)'; if (type == 'title') { height = 25 + 'px'; width = 260 + 'px'; } const style = { height: height, width: width } return ( <div style={style}></div> ); } }
$(function() { $(document).on('click', '#weather_link', function (event) { event.preventDefault(); $('#weather').html('<p class="loading">( loading weather... )</p>') $.ajax({ url: '/weather', method: 'get' }).done(function (response) { $('#weather').html(response) }) }); $(document).on('click', '#forecast_link', function (event) { event.preventDefault(); $('#forecast').html('<p class="loading">( loading forecast... )</p>') $.ajax({ url: '/forecast', method: 'get' }).done(function (response) { $('#forecast').html(response) }) }); $(document).on('click', '#CNN_link', function (event) { event.preventDefault(); $('#CNN').html('<p class="loading">( loading CNN... )</p>') $.ajax({ url: '/headlines/CNN', method: 'get' }).done(function (response) { $('#CNN').html(response) }) }); $(document).on('click', '#ENG_link', function (event) { event.preventDefault(); $('#ENG').html('<p class="loading">( loading engadget... )</p>') $.ajax({ url: '/headlines/engadget', method: 'get' }).done(function (response) { $('#ENG').html(response) }) }); $(document).on('click', '#NYT_link', function (event) { event.preventDefault(); $('#NYT').html('<p class="loading">( loading New York Times... )</p>') $.ajax({ url: '/headlines/the-new-york-times', method: 'get' }).done(function (response) { $('#NYT').html(response) }) }); $(document).on('click', '#WSJ_link', function (event) { event.preventDefault(); $('#WSJ').html('<p class="loading">(loading Wall Street Journal... )</p>') $.ajax({ url: '/headlines/the-wall-street-journal', method: 'get' }).done(function (response) { $('#WSJ').html(response) }) }); $(document).on('click', '#about_link', function (event) { event.preventDefault(); $.ajax({ url: '/about', method: 'get' }).done(function (response) { $('#about').html(response) }) }); if($('#weather').children()[0].textContent === '( loading weather... )') { $.ajax({ async: "true", url: '/weather', method: 'get' }).done(function (response) { $('#weather').html(response); }) } if($('#forecast').children()[0].textContent === '( loading forecast... )') { $.ajax({ url: '/forecast', method: 'get' }).done(function (response) { $('#forecast').html(response) }) } if($('#CNN').children()[0].textContent === '( loading CNN... )') { $.ajax({ url: '/headlines/CNN', method: 'get' }).done(function (response) { $('#CNN').html(response) }) } if($('#ENG').children()[0].textContent === '( loading engadget... )') { $.ajax({ url: '/headlines/engadget', method: 'get' }).done(function (response) { $('#ENG').html(response) }) } if($('#NYT').children()[0].textContent === '( loading New York Times... )') { $.ajax({ url: '/headlines/the-new-york-times', method: 'get' }).done(function (response) { $('#NYT').html(response) }) } if($('#WSJ').children()[0].textContent === '(loading Wall Street Journal... )') { $.ajax({ url: '/headlines/the-wall-street-journal', method: 'get' }).done(function (response) { $('#WSJ').html(response) }) } });
let deleteItems=document.querySelectorAll("#order-container .fas.fa-times"); for(let i=0;i<deleteItems.length;i++){ let deleteItem=deleteItems[i]; deleteItem.addEventListener("click", deleteOrderItem); } function deleteOrderItem(e){ let orderItem=e.currentTarget; orderItem.parentElement.remove(); } function reducePrice(e){ let name = e.currentTarget.parentElement.querySelector(".name").textContent; let totalPrice=document.querySelector(".total"); let panels=document.querySelectorAll(".panel"); for(i=0;i<panels.length;i++){ if(panels[i].textContent.indexOf(name) !== -1){ let value=panels[i].querySelector(".price").textContent; totalPrice.textContent=Number(totalPrice.textContent)-Number(value); break; } } }
myModule.controller('MainController', ["$scope",'clientId', function($scope, clientId){ console.log('Main controller created'); $scope.getClientId = function(){ $scope.clientId = clientId; //console.log(clientId); }; }]);
import * as Benchmark from 'benchmark'; import av from 'av'; import path from 'path'; import { runSequence, flatten } from './utils'; // banchmark files import { getFftSuites } from './benchFft'; import { getRmsSuites } from './benchRms'; import { getMfccSuites } from './benchMfcc'; global.Benchmark = Benchmark; const asset = av.Asset.fromFile(path.join(process.cwd(), 'assets/drum-loop-extract-1s.wav')); asset.on('error', (err) => console.log(err.stack)); asset.decodeToBuffer(init); function init(buffer) { const bufferLength = buffer.length; const sampleRate = asset.format.sampleRate; const logStack = []; const stack = []; const fftSuites = getFftSuites(buffer, bufferLength, sampleRate, logStack); stack.push(fftSuites); const rmsSuites = getRmsSuites(buffer, bufferLength, sampleRate, logStack); stack.push(rmsSuites); const mfccSuites = getMfccSuites(buffer, bufferLength, sampleRate, logStack); stack.push(mfccSuites); const suites = flatten(stack); suites.push(() => console.log(logStack.join('\n'))); runSequence(suites); }
import React from 'react'; import { withRouter } from 'react-router-dom'; import Scroll from '../../../baseUI/scroll/index'; import './Classify.css'; const Classify = (props) => { const handleclick = (id) => { // console.log("object",encodeURIComponent(id)) // this.props.history.push(`/detail/${id}`) props.history.push(`/detail?data=${encodeURIComponent(id)}`) // console.log(this.props) } // render() { const classifyData = props.classify || []; return ( <Scroll direction={"horizental"} refresh={true}> <div className="classify"> <div className="classify-box"> { classifyData.map((item, index) => { return ( <span className="classify-item" key={index} onClick={() => { handleclick(item) }}> {item} </span> ) }) } </div> </div> </Scroll > ); // } } export default withRouter(Classify)
/**here we are expeted that all the feeds are defined and came frm the app.js */ $(function () { describe('RSS Feeds', function () { it('are defined', function () { expect(allFeeds).toBeDefined(); expect(allFeeds.length).toBeGreaterThan(0); }); /**here we want to ensure that each url are defined and not empty * we expect that each url feed are defined */ it('each has url defined', function () { for (let feed of allFeeds) { expect(feed.url).toBeDefined(); expect(feed.url.constructor).toBe(String); expect(feed.url.length).not.toBe(0); } }); /* here we are ensure that each feed has a name is defined and the lengh is not zero */ it('each has name', function () { for (let feed of allFeeds) { expect(feed.name).toBeDefined(); expect(feed.name.constructor).toBe(String); expect(feed.name.length).not.toBe(0); } }); }); /* here we are going if the menu working when click * first we will checking if the menu is hidden by a default * the function will check if the body has thee hidden class * *we expect to be true it's hidden by default */ describe('The menu', function () { it('hidden by default', function () { let chechHidden = document.body.classList.contains('menu-hidden'); expect(chechHidden).toBe(true); }); /* ensureing that the menu button work */ it('change icons when clicked', function () { let iconClicked = document.querySelector('a.menu-icon-link'); iconClicked.click(); expect(document.body.classList.contains('menu-hidden')).toBe(false); iconClicked.click(); expect(document.body.classList.contains("menu-hidden")).toBe(true); }); }); /* it's requried asynchronous so we will use the call back function */ describe('initial entries', function () { beforeEach(function (done) { loadFeed(1, done); }); it('entries feed container', function () { let container_feed = document.querySelector('div.feed'); let entries = container_feed.querySelectorAll('article.entry') expect(entries.length).toBeGreaterThan(0); }); }); /** * decleared to varible f1,f2 without a value * use the asynchronous support * calling the jasimine before each function */ describe('New Feed Selection', function () { let f1, f2; beforeEach(function (done) { loadFeed(3, function () { f1 = document.querySelector('div.feed').innerHTML; loadFeed(2, function () { f2 = document.querySelector('div.feed').innerHTML; done(); }); }); }); it('loading new feeds', function () { expect(f1).not.toBe(f2); }); }); }());
import React from "react"; import "./style.css"; export function List({ children }) { return ( <div className="list-overflow-container"> <ul className="list-group list unstyled">{children}</ul> </div> ); } export function ListItem({ children }) { return <li className="list-group-item">{children}</li>; } export function CardItem(props) { return ( <li className="media"> <img src={props.image} className="mr-3" alt="..."/> <div className="media-body"> <h5 className="mt-0 mb-1">{(!props.title) ? "" : props.title }</h5> {(!props.ingredients) ? "Author unknown" : props.ingredients.map(ingredients => (ingredients + " "))} <p>{(!props.description) ? "" : props.description}</p> </div> <a href={props.link} target="blank"><button>View</button></a> {/* {(props.saved === "not saved") ? <button onClick={()=>props.saveBook(props)}>Save</button> : <span tabIndex="0"> Already Saved</span>} */} </li> ); }